diff --git a/.github/workflows/README.md b/.github/workflows/README.md index 1c013893f4..bd2ad4ef11 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -13,26 +13,27 @@ flowchart TB pr["pull_request: opened, synchronize, reopened, ready_for_review"] --> eprc["entry-pr-change-orchestrate.yml"] dispatch["workflow_dispatch"] --> eman["entry-manual-steer.yml"] - epl --> orch["ci-orchestrator.yml"] - epl -->|"version tag on main"| relv["release-version.yml"] + epl --> orch["call-orchestrator.yml"] + epl -->|"version tag on main"| relv["call-release-version.yml"] eprc --> orch - eprc -->|"fork PRs: privileged prebuild"| imgbuild["images-build-ci.yml"] - eprc -->|"fork PRs: privileged prebuild"| imgmirror["images-mirror-missing.yml"] + eprc -->|"fork PRs: privileged prebuild"| imgbuild["call-images-build-ci.yml"] + eprc -->|"fork PRs: privileged prebuild"| imgmirror["call-images-mirror-missing.yml"] eman --> orch - subgraph orchestrator["ci-orchestrator.yml jobs"] + subgraph orchestrator["call-orchestrator.yml jobs"] waitfork["wait-fork-prereq-run"] --> forkready["fork-prereqs-ready"] - lintwf["lint.yml: make lint + hadolint"] - testwf["test.yml: make test"] + lintwf["call-lint.yml: make lint + hadolint"] + testwf["call-test.yml: make test"] codeql["cron-security-codeql.yml"] - buildci["build-ci-images: images-build-ci.yml"] --> dns["test-dns.yml"] - mirror["images-mirror-missing.yml"] + buildci["build-ci-images: call-images-build-ci.yml"] --> dns["call-test-dns.yml"] + mirror["call-images-mirror-missing.yml"] subgraph chain["serial chunk chain"] chunk0["test-deploy-chunk-0"] chunk0 --> chunk1["test-deploy-chunk-1"] chunk1 --> chunk2["test-deploy-chunk-2"] + chunk2 --> chunk3["test-deploy-chunk-3"] end lintwf --> chain @@ -41,21 +42,18 @@ flowchart TB mirror --> chain buildci --> chain - chunk0 --> smoke["test-runner-smoke.yml"] + chunk0 --> smoke["call-test-runner-smoke.yml"] chain --> report["report-main-failures"] - instmake["test-install-make.yml"] - instpkgmgr["test-install-pkgmgr.yml"] - mirror --> devenv["test-workspace: test-workspace.yml"] - buildci --> testguide["test-instructions.yml"] - mirror --> testguide + instmake["call-test-install-make.yml"] + instpkgmgr["call-test-install-pkgmgr.yml"] + mirror --> devenv["test-workspace: call-test-workspace.yml"] chain --> donegate["done"] smoke --> donegate instmake --> donegate instpkgmgr --> donegate devenv --> donegate - testguide --> donegate end chunk0 --> deploy["call-test-deploy.yml"] @@ -102,8 +100,11 @@ the whole list instead of re-testing the same head forever. GitHub Actions cannot generate a variable number of jobs, so the chunk blocks are written out in the orchestrator. `INFINITO_CI_MAX_CHUNKS` must equal how many exist there โ€” `slots` plans a sweep against that key, and a sweep planned -larger than the chain silently drops its tail. Blocks whose slice comes back -empty skip themselves and cost nothing. +larger than the chain silently drops its tail. Declare one block more than +`available` fills (`ceil(available / chunk size) + 1`): the split receives +every declared block, so after a short priority chunk the regular rows still +fill the rest of the budget. Blocks whose slice comes back empty skip +themselves and cost nothing. Run `python -m cli.meta.ci.slots --matrix` to see the whole budget. @@ -258,7 +259,10 @@ failed chunk: `skipped` counts as passed, so an empty chunk never blocks the chain. After fixing what broke a sweep, `resume_from_chunk` re-enters at that index instead of re-running the green chunks. Both are inputs on `entry-manual-steer.yml`; -the other entry points take the defaults. +the other entry points take the defaults. A retrigger carries the source run's +`chunk_gate` over unless `infinito administration deploy ci trigger +--chunk-gate false` overrides it; the `i8ciallon` alias is `i8ciall` with that +override, for sweeps that should report every chunk before anyone looks. ## Cancellation @@ -277,6 +281,12 @@ run being created and needs no runner. `entry-cancel-superseded.yml` is the fallback for the case where it does not, and carries no group of its own, because the run holding a group cannot be the run that frees it. +A workflow the entries call declares no `concurrency` of its own: its jobs then +belong to the entry's group, and the entry's `cancel-in-progress` reaches them. +`call-images-build-ci.yml` and `call-images-mirror-missing.yml` still declare +one, so a run whose only live job is theirs stays outside the entry's group and +waits for the fallback. + ## Scheduled and standalone ```mermaid @@ -291,13 +301,12 @@ flowchart TB pushmain["push: main"] --> updatewf prtarget["pull_request_target: opened, reopened"] --> depclose["entry-pr-open-dependabot-close.yml"] - relhighest -.->|"gh workflow run"| relver["release-version.yml"] - relver --> imgbuildci["images-build-ci.yml"] - manual["workflow_dispatch"] --> mirrorcleanup["images-mirror-cleanup.yml"] - manual --> deploywf["test-instructions.yml: run a role README Production command"] + relhighest -.->|"gh workflow run"| relver["call-release-version.yml"] + relver --> imgbuildci["call-images-build-ci.yml"] + manual["workflow_dispatch"] --> mirrorcleanup["entry-manual-mirror-cleanup.yml"] ``` Also manually dispatchable: `cron-images-mirror-all.yml`, `cron-images-cleanup-ci.yml`, `cron-cleanup-stale.yml`, `cron-update.yml`, `cron-release-highest.yml`, `call-release-version.yml`, `call-lint.yml`, `call-test.yml`, `call-test-dns.yml`, -`test-workspace.yml`, `test-runner-smoke.yml`. +`call-test-workspace.yml`, `call-test-runner-smoke.yml`. diff --git a/.github/workflows/call-images-build-ci.yml b/.github/workflows/call-images-build-ci.yml index 1719d9a623..6167740b27 100644 --- a/.github/workflows/call-images-build-ci.yml +++ b/.github/workflows/call-images-build-ci.yml @@ -41,35 +41,13 @@ concurrency: cancel-in-progress: false jobs: - prepare: - name: ๐Ÿ“‹ Build Matrix - runs-on: ubuntu-latest - outputs: - matrix: ${{ steps.out.outputs.matrix }} - image_tag: ${{ steps.out.outputs.image_tag }} - steps: - - uses: actions/checkout@v7.0.0 - - - name: ๐Ÿ“ฆ Install jq - run: ./scripts/install/apt.sh jq - - - name: ๐Ÿงฎ Compute matrix JSON - id: out - run: scripts/github/runner/images_build_outputs.sh "${{ inputs.distros }}" "${{ inputs.image_tag }}" - build: - name: ๐Ÿ—๏ธ Build (${{ matrix.distro }}) - needs: prepare + name: ๐Ÿ’ฟ Image runs-on: ubuntu-latest permissions: contents: read packages: write - strategy: - fail-fast: false - matrix: - distro: ${{ fromJson(needs.prepare.outputs.matrix) }} - steps: - name: โฌ‡๏ธ Checkout trusted workflow repo (helpers) uses: actions/checkout@v7.0.0 @@ -86,6 +64,13 @@ jobs: persist-credentials: false allow-unsafe-pr-checkout: ${{ inputs.allow_unsafe_checkout }} + - name: ๐Ÿ“ฆ Install jq + run: ./scripts/install/apt.sh jq + + - name: ๐Ÿงฎ Compute the distro list and image tag + id: out + run: scripts/github/runner/images_build_outputs.sh "${{ inputs.distros }}" "${{ inputs.image_tag }}" + - name: ๐Ÿ’ฝ Disk pressure (start) shell: bash run: bash scripts/github/runner/disk_pressure_report.sh START @@ -127,20 +112,42 @@ jobs: run: | set -euo pipefail echo "owner=$(scripts/meta/resolve/repository/owner.sh)" >> "$GITHUB_OUTPUT" + echo "name=$(scripts/meta/resolve/repository/name.sh)" >> "$GITHUB_OUTPUT" - - name: ๐Ÿ”จ Build & push (retry 7x, 20s) + - name: ๐Ÿ”จ Build & push every distro (retry 7x, 20s) if: ${{ !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository) }} shell: bash env: GITHUB_REPOSITORY_OWNER: ${{ steps.owner.outputs.owner }} BUILD_CONTEXT_DIR: _src - MATRIX_DISTRO: ${{ matrix.distro }} - IMAGE_TAG: ${{ needs.prepare.outputs.image_tag }} + INFINITO_DISTROS: ${{ join(fromJson(steps.out.outputs.matrix), ' ') }} + IMAGE_TAG: ${{ steps.out.outputs.image_tag }} USE_NIX_TOKEN: ${{ !(github.event_name == 'pull_request_target' && github.event.pull_request.head.repo.full_name != github.repository) }} NIX_GITHUB_TOKEN: ${{ github.token }} MAX_ATTEMPTS: "7" RETRY_DELAY_SECONDS: "20" - run: ./scripts/image/push.sh + run: ./scripts/image/push_all.sh + + - name: โณ Assert every distro image is in the registry + shell: bash + env: + REGISTRY: ghcr.io + OWNER: ${{ steps.owner.outputs.owner }} + REPO_PREFIX: ${{ steps.owner.outputs.name }} + CI_TAG: ${{ steps.out.outputs.image_tag }} + INFINITO_DISTROS: ${{ join(fromJson(steps.out.outputs.matrix), ' ') }} + WAIT_ATTEMPTS: "90" + WAIT_SLEEP_SECONDS: "10" + run: ./scripts/meta/wait/ci_images.sh + + - name: ๐Ÿ“ค Upload per-distro build logs + if: always() + uses: actions/upload-artifact@v7 + with: + name: image-build-logs + path: build/image-logs/ + retention-days: 7 + if-no-files-found: ignore - name: ๐Ÿ’ฝ Disk pressure (post-build) if: always() diff --git a/.github/workflows/call-images-mirror-missing.yml b/.github/workflows/call-images-mirror-missing.yml index 40f77620d8..3127bc68ef 100644 --- a/.github/workflows/call-images-mirror-missing.yml +++ b/.github/workflows/call-images-mirror-missing.yml @@ -70,7 +70,6 @@ on: permissions: contents: read - packages: write concurrency: group: mirror-images-${{ github.repository }}-${{ inputs.concurrency_channel }}-${{ inputs.concurrency_key || github.ref_name }} @@ -80,6 +79,9 @@ jobs: sync: name: ๐Ÿชž Mirror runs-on: ubuntu-latest + permissions: + contents: read + packages: write env: DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} diff --git a/.github/workflows/call-orchestrator.yml b/.github/workflows/call-orchestrator.yml index be528068fd..f37831656c 100644 --- a/.github/workflows/call-orchestrator.yml +++ b/.github/workflows/call-orchestrator.yml @@ -37,6 +37,11 @@ on: required: false type: string default: "0" + chunk_size: + description: "๐Ÿ“ฆ Rows one chunk holds. Empty or 0 derives it from the runner slots a chunk may assume and the waves the queue window affords. Typed string for the same reason as resume_from_chunk." + required: false + type: string + default: "0" resume_from_chunk: description: "โญ๏ธ Skip every chunk below this index. Use to continue a sweep after fixing what broke it, instead of re-running the green chunks. Typed string, not number: a workflow_dispatch number input reaches the caller as a string, and handing that to a number-typed workflow_call input makes GitHub reject the job before it is created." required: false @@ -72,11 +77,6 @@ on: required: false type: string default: "rotate" - instructions: - description: "Run the instructions test (role README Production command). 'auto' runs it on a global scope only, 'true'/'false' force it." - required: false - type: string - default: "auto" tor: description: "Tor axis of the deploy matrix: 'auto' rotates the onion over the tor-capable rows, 'enforced' onions all of them, 'exclusive' also drops the rows that cannot, 'disabled' onions none." required: false @@ -88,10 +88,6 @@ on: type: boolean default: false -concurrency: - group: infinito-test-${{ github.ref }} - cancel-in-progress: ${{ github.event_name == 'workflow_dispatch' || github.ref != 'refs/heads/main' }} - permissions: actions: read contents: read @@ -170,14 +166,12 @@ jobs: && needs.lint.result == 'success' && needs.test.result == 'success' && needs.build-ci-images.result == 'success' - && needs.images-mirror-missing.result == 'success' - && needs.test-dns.result == 'success' }} + && needs.images-mirror-missing.result == 'success' }} needs: - lint - test - build-ci-images - images-mirror-missing - - test-dns - validate-selection uses: ./.github/workflows/call-test-deploy.yml with: @@ -185,6 +179,7 @@ jobs: index: "0" sweep: ${{ inputs.sweep != '' && inputs.sweep || github.run_number }} offset: ${{ inputs.offset }} + chunk_size: ${{ inputs.chunk_size }} whitelist: ${{ inputs.whitelist }} priority: ${{ inputs.priority }} lifecycles: ${{ inputs.lifecycles }} @@ -201,7 +196,6 @@ jobs: && needs.test.result == 'success' && needs.build-ci-images.result == 'success' && needs.images-mirror-missing.result == 'success' - && needs.test-dns.result == 'success' && (!inputs.chunk_gate || contains(fromJSON('["success","skipped"]'), needs.test-deploy-chunk-0.result)) }} needs: @@ -209,7 +203,7 @@ jobs: - test - build-ci-images - images-mirror-missing - - test-dns + - validate-selection - test-deploy-chunk-0 uses: ./.github/workflows/call-test-deploy.yml with: @@ -217,6 +211,7 @@ jobs: index: "1" sweep: ${{ inputs.sweep != '' && inputs.sweep || github.run_number }} offset: ${{ inputs.offset }} + chunk_size: ${{ inputs.chunk_size }} whitelist: ${{ inputs.whitelist }} priority: ${{ inputs.priority }} lifecycles: ${{ inputs.lifecycles }} @@ -233,15 +228,16 @@ jobs: && needs.test.result == 'success' && needs.build-ci-images.result == 'success' && needs.images-mirror-missing.result == 'success' - && needs.test-dns.result == 'success' && (!inputs.chunk_gate - || contains(fromJSON('["success","skipped"]'), needs.test-deploy-chunk-1.result)) }} + || (contains(fromJSON('["success","skipped"]'), needs.test-deploy-chunk-0.result) + && contains(fromJSON('["success","skipped"]'), needs.test-deploy-chunk-1.result))) }} needs: - lint - test - build-ci-images - images-mirror-missing - - test-dns + - validate-selection + - test-deploy-chunk-0 - test-deploy-chunk-1 uses: ./.github/workflows/call-test-deploy.yml with: @@ -249,6 +245,43 @@ jobs: index: "2" sweep: ${{ inputs.sweep != '' && inputs.sweep || github.run_number }} offset: ${{ inputs.offset }} + chunk_size: ${{ inputs.chunk_size }} + whitelist: ${{ inputs.whitelist }} + priority: ${{ inputs.priority }} + lifecycles: ${{ inputs.lifecycles }} + modes: ${{ inputs.mode }} + filesystem: ${{ inputs.filesystem }} + tor: ${{ inputs.tor }} + + test-deploy-chunk-3: + name: ๐Ÿงฑ Chunk 3 + if: >- + ${{ always() + && inputs.resume_from_chunk <= 3 + && needs.lint.result == 'success' + && needs.test.result == 'success' + && needs.build-ci-images.result == 'success' + && needs.images-mirror-missing.result == 'success' + && (!inputs.chunk_gate + || (contains(fromJSON('["success","skipped"]'), needs.test-deploy-chunk-0.result) + && contains(fromJSON('["success","skipped"]'), needs.test-deploy-chunk-1.result) + && contains(fromJSON('["success","skipped"]'), needs.test-deploy-chunk-2.result))) }} + needs: + - lint + - test + - build-ci-images + - images-mirror-missing + - validate-selection + - test-deploy-chunk-0 + - test-deploy-chunk-1 + - test-deploy-chunk-2 + uses: ./.github/workflows/call-test-deploy.yml + with: + distros: ${{ inputs.distros }} + index: "3" + sweep: ${{ inputs.sweep != '' && inputs.sweep || github.run_number }} + offset: ${{ inputs.offset }} + chunk_size: ${{ inputs.chunk_size }} whitelist: ${{ inputs.whitelist }} priority: ${{ inputs.priority }} lifecycles: ${{ inputs.lifecycles }} @@ -283,25 +316,13 @@ jobs: - test secrets: inherit - test-instructions: - if: ${{ inputs.instructions == 'true' || (inputs.instructions == 'auto' && (inputs.whitelist == '' || inputs.whitelist == '__ALL__')) }} - uses: ./.github/workflows/call-test-instructions.yml - needs: - - images-mirror-missing - - build-ci-images - - lint - - test - - validate-selection - with: - distros: "arch debian ubuntu fedora centos" - secrets: inherit - report-main-failures: name: ๐Ÿž Report main role failures needs: - test-deploy-chunk-0 - test-deploy-chunk-1 - test-deploy-chunk-2 + - test-deploy-chunk-3 if: ${{ always() && github.ref == 'refs/heads/main' && (contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')) }} runs-on: ubuntu-latest permissions: @@ -327,9 +348,9 @@ jobs: - test-deploy-chunk-0 - test-deploy-chunk-1 - test-deploy-chunk-2 + - test-deploy-chunk-3 - test-runner-smoke - test-workspace - - test-instructions - test - lint - security-codeql diff --git a/.github/workflows/call-test-deploy.yml b/.github/workflows/call-test-deploy.yml index 767d1b09d7..994768fc44 100644 --- a/.github/workflows/call-test-deploy.yml +++ b/.github/workflows/call-test-deploy.yml @@ -21,6 +21,11 @@ on: required: false type: string default: "0" + chunk_size: + description: "Rows one chunk holds; 0 derives it from the runner slots and the queue window." + required: false + type: string + default: "0" whitelist: description: "Optional space-separated whitelist of app ids" required: false @@ -126,7 +131,10 @@ env: INFINITO_GHCR_MIRROR_PREFIX: mirror INFINITO_MAIL_PRODUCTION_HOST: ${{ vars.INFINITO_MAIL_PRODUCTION_HOST }} INFINITO_MAIL_PRODUCTION_RESOLVER: ${{ vars.INFINITO_MAIL_PRODUCTION_RESOLVER }} - INFINITO_PLAYWRIGHT_KEEP: ${{ vars.INFINITO_PLAYWRIGHT_KEEP }} + INFINITO_PLAYWRIGHT_KEEP: ${{ vars.PLAYWRIGHT_KEEP_ALL }} + INFINITO_API_OPENAI_KEY: ${{ secrets.API_OPENAI_KEY || vars.API_OPENAI_KEY }} + INFINITO_API_ANTHROPIC_KEY: ${{ secrets.API_ANTHROPIC_KEY || vars.API_ANTHROPIC_KEY }} + INFINITO_API_OPENROUTER_KEY: ${{ secrets.API_OPENROUTER_KEY || vars.API_OPENROUTER_KEY }} INFINITO_APP_DISCOVERY_RUNNER: host INFINITO_DOCKER_FILESYSTEM_ALLOWED: ${{ inputs.filesystem }} INFINITO_LIFECYCLES: ${{ inputs.lifecycles }} @@ -151,9 +159,9 @@ jobs: set -euo pipefail echo "GITHUB_REPOSITORY_OWNER=$(scripts/meta/resolve/repository/owner.sh)" >> "$GITHUB_ENV" - - name: ๐Ÿ“ฆ Install deps (jq + envsubst) + - name: ๐Ÿ“ฆ Install jq shell: bash - run: ./scripts/install/apt.sh jq gettext-base + run: ./scripts/install/apt.sh jq - name: ๐Ÿ”ง Set up Python uses: actions/setup-python@v6 @@ -188,12 +196,14 @@ jobs: INFINITO_CI_SWEEP: ${{ inputs.sweep }} INFINITO_CI_CHUNK: ${{ inputs.index }} INFINITO_CI_OFFSET: ${{ inputs.offset }} + INFINITO_CI_CHUNK_SIZE: ${{ inputs.chunk_size }} run: ./scripts/github/resolve/output_apps.sh - name: ๐Ÿ—บ๏ธ Render the plan into the run summary shell: bash env: INFINITO_CI_SWEEP: ${{ inputs.sweep }} + INFINITO_CI_CHUNK_SIZE: ${{ inputs.chunk_size }} PLAN_DISTROS: ${{ inputs.distros }} PLAN_FILESYSTEM: ${{ inputs.filesystem }} PLAN_WHITELIST: ${{ steps.resolve_wl.outputs.whitelist }} @@ -419,3 +429,18 @@ jobs: if: ${{ always() && matrix.mode == 'swarm' }} timeout-minutes: 15 run: scripts/tests/deploy/swarm/utils/clean/teardown.sh + + - name: "๐Ÿ“– Replay the ${{ matrix.apps }} README instructions" + if: ${{ matrix.instructions != '' }} + env: + GUIDE_ROLE: ${{ matrix.apps }} + GUIDE_MODE: ${{ matrix.instructions }} + run: ./scripts/tests/deploy/distros.sh scripts/github/guide/one.sh + + - name: "โฌ†๏ธ Upload instructions rescue diagnostics" + if: ${{ always() && matrix.instructions != '' && !env.ACT }} + uses: actions/upload-artifact@v7 + with: + name: rescue-diagnostics-instructions-${{ matrix.artifact }} + path: ${{ env.INFINITO_RESCUE_DIAGNOSTICS_BASE }}/ + if-no-files-found: ignore diff --git a/.github/workflows/call-test-instructions.yml b/.github/workflows/call-test-instructions.yml deleted file mode 100644 index fe3bc1be60..0000000000 --- a/.github/workflows/call-test-instructions.yml +++ /dev/null @@ -1,105 +0,0 @@ -name: "๐Ÿ“– Test: Instructions" - -on: - workflow_call: - inputs: - distros: - description: "Space-separated distro list" - required: true - type: string - role: - description: "Role to test; empty picks one at random" - required: false - type: string - default: "" - priority: - description: "Space-separated app ids; a random one is preferred over whitelist" - required: false - type: string - default: "" - whitelist: - description: "Space-separated app ids; a random one is used when no role or priority is given" - required: false - type: string - default: "" - workflow_dispatch: - inputs: - distros: - description: "๐Ÿง Space-separated distro list" - required: true - type: string - role: - description: "๐Ÿ“– Role to test; empty picks one at random" - required: false - type: string - default: "" - priority: - description: "โญ App ids; a random one is preferred over the whitelist" - required: false - type: string - default: "" - whitelist: - description: "๐ŸŽฏ App ids; a random one runs when no role or priority is given" - required: false - type: string - default: "" - -permissions: - contents: read - packages: read - -jobs: - deploy: - name: ๐Ÿ“– Instructions - runs-on: ubuntu-latest - timeout-minutes: 345 - concurrency: - group: infinito-instructions - cancel-in-progress: false - queue: max - env: - INFINITO_IMAGE_TAG: ci-${{ github.sha }} - INFINITO_DISTROS: ${{ inputs.distros }} - steps: - - if: ${{ !env.ACT }} - uses: actions/checkout@v7.0.0 - - - name: "๐Ÿ“ฅ Load rescue-diagnostics SPOT into job env" - shell: bash - run: grep '^INFINITO_RESCUE_DIAGNOSTICS_BASE=' default.env >> "$GITHUB_ENV" - - - name: ๐Ÿ Install instructions + compose deps (Act runner only) - if: ${{ env.ACT }} - shell: bash - run: | - PYTHON=python3 PIP_BREAK_SYSTEM_PACKAGES=1 bash scripts/install/python.sh - apt-get update -qq && apt-get install -y -qq gettext-base jq - - - name: ๐ŸŽฒ Select the role and deploy mode - shell: bash - run: | - set -euo pipefail - python3 -m cli.meta.ci.guide_select \ - --role "${{ inputs.role }}" \ - --priority "${{ inputs.priority }}" \ - --whitelist "${{ inputs.whitelist }}" | tee -a "$GITHUB_ENV" - - - name: ๐Ÿ”‘ Login to GHCR - if: ${{ !env.ACT }} - uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4.4.0 - with: - registry: ghcr.io - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: ๐Ÿ“– Replay the instructions across ${{ inputs.distros }} - shell: bash - run: ./scripts/tests/deploy/distros.sh scripts/github/guide/one.sh - - - name: โฌ†๏ธ Upload rescue diagnostics - if: ${{ always() && !env.ACT }} - uses: actions/upload-artifact@v7 - with: - name: rescue-diagnostics-instructions-${{ env.GUIDE_ROLE }} - path: ${{ env.INFINITO_RESCUE_DIAGNOSTICS_BASE }}/ - if-no-files-found: ignore diff --git a/.github/workflows/call-test-runner-smoke.yml b/.github/workflows/call-test-runner-smoke.yml index 18f5065767..dee92320d0 100644 --- a/.github/workflows/call-test-runner-smoke.yml +++ b/.github/workflows/call-test-runner-smoke.yml @@ -17,10 +17,6 @@ on: default: "" type: string -concurrency: - group: runner-smoke-${{ github.ref }} - cancel-in-progress: true - permissions: contents: read packages: read diff --git a/.github/workflows/call-validation.yml b/.github/workflows/call-validation.yml index b992ba236f..6b4111c770 100644 --- a/.github/workflows/call-validation.yml +++ b/.github/workflows/call-validation.yml @@ -122,8 +122,8 @@ jobs: uses: actions/setup-python@v6 with: python-version: "3.12" - cache: pip - cache-dependency-path: pr-head/pyproject.toml + # Exception: no pip cache. The steps below run the PR head's own code, + # which would write a cache that a default-branch run later restores. - name: ๐Ÿ“ฆ Install project (host venv) if: ${{ inputs.whitelist != '' || inputs.priority != '' }} diff --git a/.github/workflows/cron-collection-source.yml b/.github/workflows/cron-collection-source.yml new file mode 100644 index 0000000000..50dc753b10 --- /dev/null +++ b/.github/workflows/cron-collection-source.yml @@ -0,0 +1,80 @@ +name: "โš–๏ธ Source benchmark" +run-name: "${{ github.event_name == 'schedule' && 'โฐ ' || '' }}โš–๏ธ Benchmark collection sources" + +on: + schedule: + - cron: "0 3 * * *" + workflow_dispatch: + +concurrency: + group: collection-source-${{ github.repository }} + cancel-in-progress: true + +permissions: + contents: read + actions: read + +jobs: + benchmark-collection-sources: + name: โš–๏ธ Time Galaxy against the git fallback + if: vars.CI_ENABLE_AUTO_UPDATES == 'true' + runs-on: ubuntu-latest + env: + HISTORY_PATH: build/collection-source-history.json + steps: + - name: โฌ‡๏ธ Checkout + uses: actions/checkout@v7.0.0 + with: + ref: main + + - name: ๐Ÿ”ง Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: pyproject.toml + + - name: ๐Ÿ“ฆ Install project with the deploy extra + env: + PYTHON: python3 + run: bash scripts/install/python.sh deploy + + - name: โ™ป๏ธ Restore the sample history from the last run + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + HISTORY_WORKFLOW: cron-collection-source.yml + run: bash scripts/github/update/restore_collection_history.sh + + - name: โฑ๏ธ Time both collection sources + run: bash scripts/github/update/collection_source.sh --history "${HISTORY_PATH}" + + - name: ๐Ÿ’พ Keep the sample history for the next run + uses: actions/upload-artifact@v7 + with: + name: collection-source-history + path: ${{ env.HISTORY_PATH }} + retention-days: 90 + + - name: ๐Ÿ”Ž Check for changes + id: diff + run: bash scripts/github/resolve/check_git_changes.sh default.env + + - name: โš™๏ธ Generate app token + if: steps.diff.outputs.changed == 'true' + id: app-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ secrets.BOT_APP_CLIENT_ID }} + private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }} + + - name: ๐Ÿ“‚ Open PR if the preferred source changed + if: steps.diff.outputs.changed == 'true' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + APP_SLUG: ${{ steps.app-token.outputs.app-slug }} + UPDATE_BRANCH_PREFIX: update/collection-source + UPDATE_COMMIT_MESSAGE: "update(galaxy): retune the preferred collection source" + UPDATE_PR_TITLE: "update(galaxy): retune the preferred collection source" + UPDATE_PR_BODY: "Automated retune of `INFINITO_ANSIBLE_COLLECTIONS_SOURCE` in `default.env`. The preferred source's median install time reached at least 3x the other's over the last 12 daily samples; a failed install counts as worse than any duration." + UPDATE_BASE_BRANCH: main + run: bash scripts/github/update/open/pr.sh default.env diff --git a/.github/workflows/cron-images-cleanup-ci.yml b/.github/workflows/cron-images-cleanup-ci.yml index 33b136a357..6f54549d13 100644 --- a/.github/workflows/cron-images-cleanup-ci.yml +++ b/.github/workflows/cron-images-cleanup-ci.yml @@ -13,10 +13,7 @@ on: type: string permissions: - actions: read contents: read - packages: write - pull-requests: read concurrency: group: images-cleanup-ci @@ -26,6 +23,11 @@ jobs: cleanup: name: ๐Ÿงน Delete old ci-* image versions runs-on: ubuntu-latest + permissions: + actions: read + contents: read + packages: write + pull-requests: read steps: - uses: actions/checkout@v7.0.0 diff --git a/.github/workflows/cron-images-mirror-all.yml b/.github/workflows/cron-images-mirror-all.yml index af8df88f85..6b84158dfc 100644 --- a/.github/workflows/cron-images-mirror-all.yml +++ b/.github/workflows/cron-images-mirror-all.yml @@ -54,7 +54,6 @@ on: permissions: contents: read - packages: write concurrency: group: mirror-images-${{ github.repository }}-${{ github.ref_name }} cancel-in-progress: false @@ -63,6 +62,9 @@ jobs: sync: name: ๐Ÿชž Mirror runs-on: ubuntu-latest + permissions: + contents: read + packages: write env: DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} diff --git a/.github/workflows/cron-release-highest.yml b/.github/workflows/cron-release-highest.yml index 563e6e5b50..8e17fadbae 100644 --- a/.github/workflows/cron-release-highest.yml +++ b/.github/workflows/cron-release-highest.yml @@ -12,8 +12,6 @@ concurrency: permissions: contents: read - packages: read - actions: write env: REGISTRY: ghcr.io @@ -22,6 +20,10 @@ jobs: check-and-trigger: name: ๐Ÿ”Ž Backfill highest missing release tag runs-on: ubuntu-latest + permissions: + contents: read + packages: read + actions: write steps: - name: โฌ‡๏ธ Checkout repository (with tags) @@ -77,4 +79,4 @@ jobs: env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} TAG: ${{ steps.pick.outputs.tag }} - run: gh workflow run release-version.yml -f tag="${TAG}" + run: gh workflow run call-release-version.yml -f tag="${TAG}" diff --git a/.github/workflows/cron-update.yml b/.github/workflows/cron-update.yml index 33ee4e3bcf..6e827796f2 100644 --- a/.github/workflows/cron-update.yml +++ b/.github/workflows/cron-update.yml @@ -65,6 +65,100 @@ jobs: UPDATE_BASE_BRANCH: main run: bash scripts/github/update/open/role_prs.sh roles + update-pip-pins: + name: ๐Ÿ Update pinned pip requirements + if: vars.CI_ENABLE_AUTO_UPDATES == 'true' + runs-on: ubuntu-latest + steps: + - name: โฌ‡๏ธ Checkout + uses: actions/checkout@v7.0.0 + with: + ref: main + + - name: ๐Ÿ”ง Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: pyproject.toml + + - name: ๐Ÿ“ฆ Install update dependencies + run: bash scripts/github/update/install_python.sh + + - name: ๐Ÿ”„ Update pinned pip requirements + run: bash scripts/github/update/pip_pins.sh + + - name: ๐Ÿ”Ž Check for changes + id: diff + run: bash scripts/github/resolve/check_git_changes.sh roles + + - name: โš™๏ธ Generate app token + if: steps.diff.outputs.changed == 'true' + id: app-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ secrets.BOT_APP_CLIENT_ID }} + private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }} + + - name: ๐Ÿ“‚ Open PR if pip pins changed + if: steps.diff.outputs.changed == 'true' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + APP_SLUG: ${{ steps.app-token.outputs.app-slug }} + UPDATE_BRANCH_PREFIX: update/pip-pins + UPDATE_COMMIT_MESSAGE: "update(pip): update pinned pip requirements" + UPDATE_PR_TITLE: "update(pip): update pinned pip requirements" + UPDATE_PR_BODY: "Automated update of exact pip pins in `roles/**/*.yml`." + UPDATE_BASE_BRANCH: main + run: bash scripts/github/update/open/role_prs.sh roles + + update-galaxy-pins: + name: ๐ŸŒŒ Update pinned Ansible collections + if: vars.CI_ENABLE_AUTO_UPDATES == 'true' + runs-on: ubuntu-latest + steps: + - name: โฌ‡๏ธ Checkout + uses: actions/checkout@v7.0.0 + with: + ref: main + + - name: ๐Ÿ”ง Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + cache: pip + cache-dependency-path: pyproject.toml + + - name: ๐Ÿ“ฆ Install update dependencies + run: bash scripts/github/update/install_python.sh + + - name: ๐Ÿ”„ Update pinned Ansible collections + run: bash scripts/github/update/galaxy_pins.sh + + - name: ๐Ÿ”Ž Check for changes + id: diff + run: bash scripts/github/resolve/check_git_changes.sh requirements + + - name: โš™๏ธ Generate app token + if: steps.diff.outputs.changed == 'true' + id: app-token + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ secrets.BOT_APP_CLIENT_ID }} + private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }} + + - name: ๐Ÿ“‚ Open PR if collection pins changed + if: steps.diff.outputs.changed == 'true' + env: + GH_TOKEN: ${{ steps.app-token.outputs.token }} + APP_SLUG: ${{ steps.app-token.outputs.app-slug }} + UPDATE_BRANCH_PREFIX: update/galaxy-pins + UPDATE_COMMIT_MESSAGE: "update(galaxy): bump pinned Ansible collections" + UPDATE_PR_TITLE: "update(galaxy): bump pinned Ansible collections" + UPDATE_PR_BODY: "Automated update of the collection `version:` pins in `requirements/`. Both the Galaxy file and the git fallback are bumped together; upstream releases resolved via `git ls-remote --tags`." + UPDATE_BASE_BRANCH: main + run: bash scripts/github/update/open/pr.sh requirements + update-repository-refs: name: ๐ŸŒฟ Update repository refs if: vars.CI_ENABLE_AUTO_UPDATES == 'true' diff --git a/.github/workflows/entry-delete-branch.yml b/.github/workflows/entry-delete-branch.yml index 66f1f9e538..8b9113032e 100644 --- a/.github/workflows/entry-delete-branch.yml +++ b/.github/workflows/entry-delete-branch.yml @@ -15,13 +15,15 @@ concurrency: cancel-in-progress: true permissions: - actions: write contents: read jobs: cancel-branch-runs: if: ${{ github.event.ref_type == 'branch' }} runs-on: ubuntu-latest + permissions: + actions: write + contents: read steps: - name: โฌ‡๏ธ Checkout uses: actions/checkout@v7.0.0 diff --git a/.github/workflows/entry-manual-mirror-cleanup.yml b/.github/workflows/entry-manual-mirror-cleanup.yml index b0b60f3fd6..efc372ad24 100644 --- a/.github/workflows/entry-manual-mirror-cleanup.yml +++ b/.github/workflows/entry-manual-mirror-cleanup.yml @@ -36,12 +36,14 @@ on: permissions: contents: read - packages: write jobs: cleanup: name: ๐Ÿ—‘๏ธ Delete private GHCR mirror packages runs-on: ubuntu-latest + permissions: + contents: read + packages: write steps: - name: โฌ‡๏ธ Checkout diff --git a/.github/workflows/entry-manual-steer.yml b/.github/workflows/entry-manual-steer.yml index 84464babf6..edcad68b70 100644 --- a/.github/workflows/entry-manual-steer.yml +++ b/.github/workflows/entry-manual-steer.yml @@ -1,5 +1,5 @@ name: "๐Ÿ•น๏ธ Manual" -run-name: "๐Ÿ•น๏ธ ${{ inputs.chunk_gate && '๐Ÿ›‘ ' || '' }}${{ inputs.offset != '0' && inputs.offset != '' && format('โฉ{0} ', inputs.offset) || '' }}${{ inputs.workspace != 'auto' && format('๐Ÿง‘โ€๐Ÿ’ป{0} ', inputs.workspace == 'true' && 'ๆ˜ฏ' || 'ๅฆ') || '' }}${{ inputs.instructions != 'auto' && format('๐Ÿ“–{0} ', inputs.instructions == 'true' && 'ๆ˜ฏ' || 'ๅฆ') || '' }}${{ inputs.tor != 'auto' && format('{0} ', inputs.tor == 'disabled' && '๐ŸŒ' || inputs.tor == 'enforced' && '๐Ÿง…ๅผบๅˆถ' || '๐Ÿง…็‹ฌๅ ') || '' }}${{ inputs.filesystem != '' && format('๐Ÿ—„๏ธ{0} ', inputs.filesystem) || '' }}${{ inputs.distros != '' && format('๐Ÿง{0} ', inputs.distros) || '' }}${{ inputs.lifecycles != '' && format('โ™ป๏ธ{0} ', inputs.lifecycles) || '' }}${{ inputs.mode != 'auto' && format('๐Ÿš€{0} ', inputs.mode) || '' }}${{ inputs.priority != '' && format('โญ{0} ', inputs.priority) || '' }}${{ inputs.whitelist != '' && format('๐ŸŽฏ{0}', inputs.whitelist) || '๐Ÿ”€ diff (origin/main)' }}" +run-name: "๐Ÿ•น๏ธ ${{ inputs.chunk_gate && '๐Ÿ›‘ ' || '' }}${{ inputs.offset != '0' && inputs.offset != '' && format('โฉ{0} ', inputs.offset) || '' }}${{ inputs.workspace != 'auto' && format('๐Ÿง‘โ€๐Ÿ’ป{0} ', inputs.workspace == 'true' && 'ๆ˜ฏ' || 'ๅฆ') || '' }}${{ inputs.tor != 'auto' && format('{0} ', inputs.tor == 'disabled' && '๐ŸŒ' || inputs.tor == 'enforced' && '๐Ÿง…ๅผบๅˆถ' || '๐Ÿง…็‹ฌๅ ') || '' }}${{ inputs.filesystem != '' && format('๐Ÿ—„๏ธ{0} ', inputs.filesystem) || '' }}${{ inputs.distros != '' && format('๐Ÿง{0} ', inputs.distros) || '' }}${{ inputs.lifecycles != '' && format('โ™ป๏ธ{0} ', inputs.lifecycles) || '' }}${{ inputs.mode != 'auto' && format('๐Ÿš€{0} ', inputs.mode) || '' }}${{ inputs.priority != '' && format('โญ{0} ', inputs.priority) || '' }}${{ inputs.whitelist != '' && format('๐ŸŽฏ{0}', inputs.whitelist) || '๐Ÿ”€ diff (origin/main)' }}" concurrency: group: global-ci-${{ github.repository }}-${{ github.ref_name }} @@ -58,6 +58,11 @@ on: required: false default: "0" type: string + chunk_size: + description: "๐Ÿ“ฆ Rows one chunk holds. Empty: derive it from slots and queue window" + required: false + default: "" + type: string chunk_gate: description: "๐Ÿ›‘ Stop the chunk chain at its first failed chunk" required: false @@ -86,15 +91,6 @@ on: - "rotate" - "compose" - "swarm" - instructions: - description: "๐Ÿ“– Run the instructions test. 'auto': on a global scope only" - required: false - default: "auto" - type: choice - options: - - "auto" - - "true" - - "false" permissions: contents: read @@ -116,10 +112,10 @@ jobs: priority: ${{ inputs.priority }} sweep: ${{ inputs.sweep }} offset: ${{ inputs.offset }} + chunk_size: ${{ inputs.chunk_size != '' && inputs.chunk_size || '0' }} chunk_gate: ${{ inputs.chunk_gate }} filesystem: ${{ inputs.filesystem }} workspace: ${{ inputs.workspace }} workspace_track: ${{ inputs.workspace_track }} - instructions: ${{ inputs.instructions }} tor: ${{ inputs.tor }} secrets: inherit diff --git a/.github/workflows/entry-pr-closed-cancel-workflows.yml b/.github/workflows/entry-pr-closed-cancel-workflows.yml index 2fa6071c79..c2f8e6ae12 100644 --- a/.github/workflows/entry-pr-closed-cancel-workflows.yml +++ b/.github/workflows/entry-pr-closed-cancel-workflows.yml @@ -11,13 +11,15 @@ concurrency: cancel-in-progress: true permissions: - actions: write contents: read - pull-requests: read jobs: cancel-pr-runs: runs-on: ubuntu-latest + permissions: + actions: write + contents: read + pull-requests: read steps: - name: โฌ‡๏ธ Checkout uses: actions/checkout@v7.0.0 diff --git a/AGENTS.md b/AGENTS.md index dd88b31d47..5cd5e69a96 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,6 +55,14 @@ Whenever an operator types out something an existing alias (listed by `make alia Agents MUST write all transient files (downloaded logs, intermediate output, scratch artefacts) to `/tmp`. The set of writable paths is defined by `sandbox.filesystem.allowWrite` in [`.claude/settings.json`](.claude/settings.json); of those entries, `/tmp` is the designated path for agent scratch data. Other entries are reserved for their respective tooling and MUST NOT be repurposed for agent temp data. The repository working tree MUST NOT hold transient files. +## Credentials in Agent Output ๐Ÿ” + +Agents MUST read deploy logs by extracting the field they need (`msg`, `stderr`, a probe result). Printing a raw task block, `argv` list, or environment dump is **FORBIDDEN โ›”**, including via a line-range `sed`/`head` over one. + +A secret denylist such as `grep -v 'password|token|key'` does **NOT** count as protection: it is case-sensitive, and secrets also travel inside URL paths. Local deploys run with `MASK_CREDENTIALS_IN_LOGS` disabled, so `no_log` does not mask these tasks. + +When a credential must be compared, compute and compare digests inside the container; never emit the value. If a credential does reach the transcript, agents MUST say so in the same message and list it for rotation. + ## Container-Owned Filesystem Entries ๐Ÿณ Files produced by the containerized runner (e.g. `__pycache__/*.pyc` under `tests/`, build artefacts) are often owned by `nobody` or another in-container UID and cannot be removed from the host. When a host-level `rm`/`chmod`/edit fails with `Permission denied` on such paths, agents MUST run the cleanup via `make compose-exec` (see [compose.yml](compose.yml); the repo is mounted at `/opt/src/infinito`) and MUST NOT ask the operator which path to take. diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ccaf1302e..2c523b9e14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,148 @@ # Changelog +## [14.0.0] - 2026-09-19 + +**For Users** + +* **AI assistance inside the applications you already run.** A gateway role, + *svc-ai-litellm*, fronts OpenAI, Anthropic and OpenRouter from declared keys, with + *svc-ai-ollama* and the new *svc-ai-lmstudio* serving local models from one shared + catalogue, so inference can stay inside the deployment. Sixteen applications use it for + their own built-in AI features instead of calling a vendor directly: WordPress AI Engine, + MediaWiki AIEditingAssistant, Moodle's AI subsystem, Zammad Smart Assist, the xWiki LLM + extension, Discourse AI, the Matrix ChatGPT bridge, Nextcloud, Mattermost Agents, n8n, + Open WebUI and Flowise. The gateway's admin UI signs in through Keycloak. See + [svc-ai-litellm](roles/svc-ai-litellm/README.md) and + [svc-ai-lmstudio](roles/svc-ai-lmstudio/README.md). + +* **Your tools reachable from your assistants.** About twenty applications now speak MCP. + Gitea, GitLab, Mattermost, Nextcloud, n8n, Baserow, Jenkins, Home Assistant, Moodle, + Snipe-IT and WordPress serve their own endpoints; ten more get one through a locked-down + sidecar. Open WebUI, Flowise and the agents discover what the deployment offers and + register it automatically. Access is bounded rather than assumed: blocked paths are + declared, every served path is gated, tools a provider calls mutating are withheld, + reader and writer roles are separate, and each provider authenticates callers as its own + service account. See [svc-ai-mcp-adapter](roles/svc-ai-mcp-adapter/README.md). + +* **Agents as employees, with a kernel between them and the host.** *web-app-hermes* and + *web-app-openclaw* deploy agents behind the single sign-on gate, wired to the gateway's + models and to the MCP servers discovery hands them, each proving on deploy that it can + actually reach them. *svc-virt-kata* runs that tier under a kernel-isolating container + runtime, and *svc-ai-robot* embodies an agent on a dedicated device. Every sandboxed + agent acts as its own platform account rather than borrowing yours. See + [web-app-hermes](roles/web-app-hermes/README.md), + [web-app-openclaw](roles/web-app-openclaw/README.md) and + [svc-virt-kata](roles/svc-virt-kata/README.md). + +* **Home automation joins the platform.** *web-app-homeassistant* deploys the automation + hub, exposes it as an MCP server so agents can drive it, persists the token it mints, and + is reachable over tor. See [web-app-homeassistant](roles/web-app-homeassistant/README.md). + +* **Changing a password changes it everywhere.** A user declares how its password must be + generated, the inventory pins one for every declared user, a new generator produces + API-key shapes, the deploy rotates credentials between its two passes, and a reset command + exists. Applications that persist an administrator password at install now realign it when + the declared one changes: Nextcloud, Moodle, EspoCRM, Jellyfin, Listmonk, Discourse, + Checkmk, xWiki, n8n, Matrix and the dedicated MariaDB and Postgres engines. Checkmk keeps + a 401 fatal so a wrong password cannot lock the account out. + +* **Onions, firewall and name resolution.** *svc-net-firewall* owns the packet filter as one + nftables table per role. Tor carries mail to a .onion in both deploy modes, rejects forged + sources on the guarded ports, and binds its dnsmasq listeners statically so a failed + re-enumeration can no longer drop every one of them. The deployment declares its own + address space once, the egress range moved out of the Docker pool, and the container + resolver follows the live bridge instead of a guessed address. Every host-bound port + requires an explicit onion decision. See + [svc-net-firewall](roles/svc-net-firewall/README.md). + +* **Application fixes you will notice.** Nextcloud installs an OnlyOffice release upstream + actually published, keeps social login working over tor, and makes its OIDC account an + administrator. Element shows invites again through the new room list. Moodle survives the + container roll during installation. Mattermost keeps its configuration in Postgres instead + of on a shared volume, and its plugin tree is per node. GitLab creates the default + organization a headless install never gets. Jellyfin waits for health before driving the + setup wizard. Keycloak registers redirect URIs only for the apps a play deploys, keeps the + allowed-origins claim out of the access token, and no longer caches LDAP federation past a + fresh grant. The platform's own health mail no longer eats the sender quota. + +* **Operating a deployment.** New make targets reach a single deployed application: + *compose-app-exec*, *compose-app-logs* and *compose-app-restart*. Diagnostics collect the + logs an application writes to a file, including from busybox containers. Health probes use + a fast start cadence with a window that outlasts a real boot, so a slow starter is no + longer reaped. The CSP health check accepts a status code a vhost declares instead of + dropping the vhost, and gives onion vhosts a navigation budget Tor can meet. + +**For Developers** + +* **MCP is declared, not wired.** A role states an *mcp* block in *meta/services.yml*, and + the vocabulary, discovery and rendering layer derives endpoints, clients, credentials and + network edges from it. A client-provider pairing is declared once, on the provider; + *sys-svc-mcp-reconcile* converges clients from the complete provider set; a refused pairing + is expressed as off rather than gated at the call site; and *svc-ai-mcp-adapter* is a + reusable per-provider sidecar rather than a standalone application. The contract is proven + on deploy, including refusal on *initialize* and the tool inventory itself. The design, + its delegation rules and a machine-checkable audit live under + [docs/contributing/design/role/services/mcp.md](docs/contributing/design/role/services/mcp.md). + +* **Registry and variant changes.** A variant can dictate the configuration of the providers + it pulls in, and an MCP round decides for itself what it carries, which is the breaking + change in this release. Fifteen moving pins gained names the registry can order, every MCP + provider is registered as a shared service, *meta/schema.yml* finished its rename to + *meta/secrets.yml*, role scripts are sorted into per-language folders, and *meta/addons* is + now an accepted declaration site for pins and plugins. + +* **Lints that fail closed.** Five properties that used to pass silently now fail. The PHP + and Ruby that roles ship are syntax-checked, and so are shell scripts that ship as Jinja + templates. *sys-service* owns every systemd unit a role installs. Healthcheck timings are + judged against what the base image was measured to hold, a variable-free healthcheck + belongs in *meta/services.yml*, an unenforceable NFS state layout fails at author time, a + sandboxed role cannot be pinned to the manager, credentials are kept out of volumes + declared non-secret, *no_log* is required on every task carrying one and forbidden in the + test roles, and a JavaScript default for an unset environment variable is rejected. + +* **Pins that cannot age unnoticed.** Image pins are classified and pull references built + from the class, a moving tag declares itself with the marker it already carries, and a + role's images move as one release or not at all. The updater reads addon declarations, + orders vendor patch counters and five-component versions, reads a release line written + before the number as a family, and now also watches pinned pip requirements and Ansible + collections. Seven roles moved off the Debian codename base onto slim, and one Ubuntu + mirror list with failover, a short timeout and a health test serves both the package cache + and the image builds. *js-yaml* was lifted to 4.3.2 for GHSA-2883-xcg3-v3hh. + +* **CI selects, resumes and proves.** A fourth deploy chunk stops a short priority chunk + stranding budget, a manual run can set the chunk size the formula would derive, and a + retrigger can override the chunk gate. Retriggering works by role and by what never got a + verdict, resumes behind the green window rather than the deployed one, retires suites the + source run already passed, and cancels the run before retriggering its failed roles. Each + role's README instructions are replayed on its smallest deploy row, in the mode its + *services.yml* declares. Distro images build concurrently on one runner, the matrix job + folds into the image job, and the deploy chunks no longer wait on the DNS test. + +* **Swarm, measured rather than assumed.** The deploy waits for its own update instead of + guessing after it, refuses to call a stack converged while it is still updating, survives a + task that failed and came back, reports what converged rather than only what did not, and + says why the convergence probe refused. Placement is constrained to a role's declared + platform arch, redis and memcached sidecars get a deploy block, and a run-once service no + longer strands the stack deploy waiting for a replica it never has. The rescue dump + captures the contents of the state volumes. In the test lab, workers are labelled + kata-capable only when the app is sandboxed, NFS detaches before the node containers die, + and the sandbox tier gets a second node. + +* **Faster gates.** Per-host setup runs once per host instead of once per application, a + role's volumes are answered from its own file instead of a whole-tree build, the Keycloak + RBAC root group resolves once rather than once per app, the Playwright fixture copy the + tree copy already made is dropped, logout helpers wait for a control instead of sleeping, + and the OIDC login helper stops waiting out probes that cannot match. Onion timeouts scale + by tor flavor instead of a flat multiplier, and every Playwright timeout has one source. + +* **Documentation and agent instructions.** Six new requirement documents cover the LLM + gateway and model backends, agent employees, Home Assistant, the robot role, the MCP proxy + expansion and native AI gateway integration. The MCP design docs are nested under their own + folder with an audit the lints can check. The role README template asks the reader for a + domain the deployment can resolve, enforces consistent Credits attribution, and drops the em + dash. Documentation generators are gathered under *cli/build/docs*, and a new CLI edits role + bonds in a matrix instead of hunting through files. + ## [13.0.0] - 2026-08-26 * **Tor as a first-class deployment axis.** The new *svc-net-tor* role routes onion diff --git a/CLAUDE.md b/CLAUDE.md index c468b65997..8487cc9e7c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -41,6 +41,12 @@ Anything else โ€” restating code, section banners, "Note that โ€ฆ", step narrati - For ANY non-trivial command (test runs, deploys, long pipelines), you MUST stream the FULL output to a file under `/tmp/` via `โ€ฆ 2>&1 | tee /tmp/.log` and grep / inspect that file repeatedly instead of re-running the command. Reason: re-running `make test` to "find the failure I just lost" costs 2 minutes per cycle; grepping the saved log costs milliseconds. - Default the filename to a meaningful slug + monotonically increasing index (`/tmp/make-test--.log`, `/tmp/act--.log`) so you can compare runs. - Tell the operator the exact `tail -f /tmp/.log` command for background runs, per the existing rule. +- That pipe **destroys the exit status**: `make test | tee` reports `tee`'s success even when make ends with `Error 2`. You MUST judge such a run by its `๐Ÿ“Š per-target wall-clock` table and its `FAILED TARGETS:` line, never by the exit code. + +## CI evidence ๐Ÿ“Š + +- A job's green conclusion is **NOT** evidence for a specific change. Before citing a run as proof, you MUST locate the line in that job's log where the change executed: a Playwright spec's `โœ“` (a leading `-` means the spec was skipped), the env var inside the container, or the command text of an `if:`-gated step. If the string is absent, report the run as silent on the change, not as supporting it. +- A green run on the fork does not speak for `infinito-nexus/core`. Tags do not follow a fork, and repository variables differ, so a step gated on either never runs there. Check the repository whose failure you are claiming to have fixed. ## Pushing ๐Ÿšข diff --git a/Dockerfile b/Dockerfile index f61529fc35..25e3f98710 100644 --- a/Dockerfile +++ b/Dockerfile @@ -26,11 +26,30 @@ RUN set -euo pipefail; \ echo 'accept-flake-config = true' >> /etc/nix/nix.conf; \ fi +COPY default.env ${INFINITO_SRC_DIR}/default.env +COPY scripts/install ${INFINITO_SRC_DIR}/scripts/install +COPY roles/dev-python/files/shell ${INFINITO_SRC_DIR}/roles/dev-python/files/shell +COPY requirements ${INFINITO_SRC_DIR}/requirements +COPY utils/__init__.py ${INFINITO_SRC_DIR}/utils/__init__.py +COPY utils/install/__init__.py ${INFINITO_SRC_DIR}/utils/install/__init__.py +COPY utils/install/collections.py ${INFINITO_SRC_DIR}/utils/install/collections.py + +# hadolint ignore=DL3008,DL3033,DL3041,SC1090,SC3040 +RUN set -euo pipefail; \ + source <(grep -hE '^INFINITO_PYTHON_INSTALL_SCRIPT=' "${INFINITO_SRC_DIR}/default.env"); \ + /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_PYTHON_INSTALL_SCRIPT:?}" ensure; \ + VENV="${INFINITO_VENV_DIR}" bash "${INFINITO_SRC_DIR}/scripts/install/venv.sh"; \ + ${PIP} install --upgrade pip setuptools wheel; \ + ${PIP} install ansible PyYAML; \ + ANSIBLE_COLLECTIONS_DIR="${HOME}/.ansible/collections" \ + bash "${INFINITO_SRC_DIR}/scripts/install/ansible.sh" + COPY . ${INFINITO_SRC_DIR} # hadolint ignore=DL3008,DL3033,DL3041,SC1090 RUN set -euo pipefail; \ - source <(grep -hE '^INFINITO_(PYTHON|DOCKER_CLI|PACKAGE|FILESYSTEM|INTERPRETERS)_INSTALL_SCRIPT=' "${INFINITO_SRC_DIR}/default.env"); \ + source <(grep -hE '^INFINITO_((PYTHON|DOCKER_CLI|PACKAGE|FILESYSTEM|INTERPRETERS)_INSTALL_SCRIPT|APT_UBUNTU_MIRRORS)=' "${INFINITO_SRC_DIR}/default.env"); \ + INFINITO_APT_UBUNTU_MIRRORS="${INFINITO_APT_UBUNTU_MIRRORS:?}" /bin/bash "${INFINITO_SRC_DIR}/scripts/install/apt-mirrors.sh"; \ /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_PYTHON_INSTALL_SCRIPT:?}"; \ /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_DOCKER_CLI_INSTALL_SCRIPT:?}"; \ /bin/bash "${INFINITO_SRC_DIR}/${INFINITO_PACKAGE_INSTALL_SCRIPT:?}"; \ diff --git a/Makefile b/Makefile index 4e1c82181f..f0055fd173 100644 --- a/Makefile +++ b/Makefile @@ -47,6 +47,11 @@ autoformat: install-lint autoformat-restage: @bash scripts/git/autoformat_restage.sh "$(MAKE)" autoformat +.PHONY: bond +# Serve the role bond matrix, where editing a cell rewrites the role's bond. +bond: + @"$${PYTHON}" -m cli.meta.roles.applications.bond $(args) + .PHONY: bootstrap # Install dependencies and prepare the project. bootstrap: install setup @@ -141,6 +146,35 @@ clean-sudo: @echo "Removing ignored git files with sudo" sudo git clean -fdX; +.PHONY: compose-app-exec +# Run a one-off command inside a deployed app container of the local compose stack. +# Usage: make compose-app-exec app= cmd="..." +# Example: make compose-app-exec app=flowise cmd="wget -qO- http://localhost:3000/api/v1/ping" +# Param app: container name of the deployed app. +# Param cmd: shell command to run inside it. +compose-app-exec: + @test -n '$(app)' || { echo 'usage: make compose-app-exec app= cmd="..."'; exit 2; } + @app='$(app)' cmd='$(cmd)' bash scripts/tests/deploy/local/exec/app.sh + +.PHONY: compose-app-logs +# Dump the logs of a deployed app container of the local compose stack. +# Usage: make compose-app-logs app= [tail=] +# Example: make compose-app-logs app=litellm tail=80 +# Param app: container name of the deployed app. +# Param tail: number of trailing lines (default: 200). +compose-app-logs: + @test -n '$(app)' || { echo 'usage: make compose-app-logs app= [tail=]'; exit 2; } + @app='$(app)' tail='$(tail)' bash scripts/tests/deploy/local/exec/logs.sh + +.PHONY: compose-app-restart +# Restart a single deployed app container of the local compose stack. +# Usage: make compose-app-restart app= +# Example: make compose-app-restart app=nextcloud +# Param app: container name of the deployed app. +compose-app-restart: + @test -n '$(app)' || { echo 'usage: make compose-app-restart app='; exit 2; } + @app='$(app)' bash scripts/tests/deploy/local/exec/restart.sh + .PHONY: compose-deploy # Run the local deploy router. # Usage: make compose-deploy [mode=...] [apps=...] [purge=...] [type=...] [bundles=...] [disable=...] [full_cycle=...] [variant=...] [debug=...] @@ -236,7 +270,7 @@ console: # Usage: make cosmos [role=] # Param role: single role id (default: all roles) cosmos: - @"$${PYTHON}" -m cli.build.readme $(role) --update-cosmos + @"$${PYTHON}" -m cli.build.docs.readme $(role) --update-cosmos .PHONY: diagnose-disk-usage # Show disk and Docker resource usage to identify what to clean up. @@ -250,11 +284,12 @@ diagnose-network: @$(MAKE) compose-exec cmd="python3 -m cli.contributing.network.diagnose" .PHONY: docs -# Regenerate generated documentation: role Cosmos diagrams, Quick Setup blocks, and the root-README roles index. +# Regenerate generated documentation: role Cosmos diagrams, Quick Setup blocks, the root-README roles index, and the MCP audit report. docs: @"$(MAKE)" cosmos @"$(MAKE)" readme-generate quick_setup=true @"$(MAKE)" readme-index + @"$(MAKE)" mcp-audit .PHONY: dotenv # Regenerate .env (SPOT) from default.env + runtime context. @@ -389,6 +424,11 @@ install-system-python: install-venv: install-system-python @bash scripts/install/venv.sh +.PHONY: integration-matrix +# Regenerate the role-by-role integration matrix from the roles and the curated edge map. +integration-matrix: + @"$${PYTHON}" -m cli.build.docs.integration_matrix + .PHONY: kernel-loop-load # Load the kernel loop driver the swarm backup DR drill needs. # Note: run this on the host; container environments have no modprobe. @@ -467,7 +507,6 @@ lint-packages: install-lint .PHONY: lint-php # Check that every PHP file parses, via `php -l`. -# Note: provisions the PHP CLI explicitly; an absent interpreter is skipped. lint-php: install-lint @bash scripts/install/wrapper.sh php @bash scripts/lint/wrapper.sh php @@ -485,7 +524,6 @@ lint-python: install-lint .PHONY: lint-ruby # Check that every Ruby file parses, via `ruby -c`. -# Note: provisions the Ruby CLI explicitly; an absent interpreter is skipped. lint-ruby: install-lint @bash scripts/install/wrapper.sh ruby @bash scripts/lint/wrapper.sh ruby @@ -502,6 +540,11 @@ lint-sql: install-lint @bash scripts/install/wrapper.sh sql @bash scripts/lint/wrapper.sh sql +.PHONY: mcp-audit +# Regenerate the MCP audit report; test_mcp_audit_report fails when it drifts. +mcp-audit: + @"$${PYTHON}" -m cli.build.docs.mcp_audit + .PHONY: meta-list # Print the repository role list. meta-list: @@ -572,7 +615,7 @@ quality-high: quality lint .PHONY: readme-check # Verify every role README matches the schema template (writes nothing; fails if any would change). readme-check: - @"$${PYTHON}" -m cli.build.readme --check + @"$${PYTHON}" -m cli.build.docs.readme --check .PHONY: readme-generate # Generate/complete role README.md files from templates/roles/README.md.j2.tmpl. @@ -582,13 +625,13 @@ readme-check: # Param cosmos: true regenerates only the Cosmos diagram # Param quick_setup: true regenerates only the Quick Setup section readme-generate: - @"$${PYTHON}" -m cli.build.readme $(role) $(if $(filter true,$(override)),--override) $(if $(filter true,$(cosmos)),--update-cosmos) $(if $(filter true,$(quick_setup)),--update-quick-setup) + @"$${PYTHON}" -m cli.build.docs.readme $(role) $(if $(filter true,$(override)),--override) $(if $(filter true,$(cosmos)),--update-cosmos) $(if $(filter true,$(quick_setup)),--update-quick-setup) .PHONY: readme-index # Regenerate the invokable-role overview table in the root README.md. # Param check: true verifies only and fails when the table is outdated readme-index: - @"$${PYTHON}" -m cli.build.readme.overview $(if $(filter true,$(check)),--check) + @"$${PYTHON}" -m cli.build.docs.readme.overview $(if $(filter true,$(check)),--check) .PHONY: requirements-archive # Archive fully-checked requirement files via pkgmgr (installs kpmx if missing). @@ -745,13 +788,14 @@ SWARM_DISTROS = $(or $(distros),$${INFINITO_DISTRO:?}) # Param distros: optional single distro the cluster runs on (default: INFINITO_DISTRO from .env). # Param variant: optional matrix variant index to deploy (default 0); a multi-variant app runs one cluster per swarm-zombie, so pick the round to validate. # Param disable: optional comma-separated provider keys removed from the test inventory (e.g. matomo,dashboard,prometheus,email,css). -# Param name: optional cluster-id prefix for the container + network names (parallel/named clusters); release with the same name=. +# Param name: optional cluster-id prefix for the container + network names; release with the same name=. # Param step_timeout: optional minute budget for the matrix-deploy step (default 690). # Note: Use `make swarm-exec` / `make swarm-shell` to inspect, `make swarm-down` to release. swarm-zombie: install-act @test -n '$(app)' || { echo 'usage: make swarm-zombie app= [distros=] [variant=] [name=] [disable=]'; exit 2; } @"$${PYTHON}" -m cli.meta.ci.validate --modes swarm --whitelist '$(app)#$(or $(variant),0)@swarm' @SWARM_NAME='$(or $(name),$(app))' INFINITO_KEEP_SWARM_NODES=false bash scripts/tests/deploy/swarm/utils/clean/teardown.sh + @bash scripts/tests/deploy/swarm/utils/clean/lab_subnet.sh @bash scripts/tests/deploy/act/down_act_outer.sh @ACT_RM=false \ ACT_BIND=true \ @@ -765,7 +809,7 @@ swarm-zombie: install-act ACT_WORKFLOW=.github/workflows/call-test-deploy.yml \ ACT_JOB=deploy \ ACT_MATRIX="apps:$(app);variant:$(or $(variant),0);mode:swarm" \ - ACT_INPUTS="whitelist=$(app) distros=$(SWARM_DISTROS) index=0 sweep=0 modes=swarm disable=$(disable)" \ + ACT_INPUTS="whitelist=$(app)#$(or $(variant),0)@swarm distros=$(SWARM_DISTROS) index=0 sweep=0 modes=swarm disable=$(disable)" \ bash scripts/tests/deploy/act/workflow.sh .PHONY: system-purge diff --git a/README.md b/README.md index 36f1685e3e..873f7bf390 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ Every invokable role in the tested lifecycle envelope, with its upstream homepag | Name | Status | Description | More | Integrated with | |---|---|---|---|---| -| [Akaunting](roles/web-app-akaunting/) | beta | Self-hosted platform for online accounting, bookkeeping, and business finance management | [๐ŸŒ](https://akaunting.com/) [๐ŸŽฌ](https://www.youtube.com/akaunting) [๐Ÿ› ๏ธ](roles/web-app-akaunting/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Akaunting](roles/web-app-akaunting/) | beta | Self-hosted platform for online accounting, bookkeeping, and business finance management | [๐ŸŒ](https://akaunting.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=UTVe_Zob_k0) [๐Ÿ› ๏ธ](roles/web-app-akaunting/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Asset Mirror (Privacy Proxy)](roles/web-svc-mirror/) | alpha | Nginx-based privacy proxy that mirrors whitelisted third-party assets under a first-party domain | [๐Ÿ› ๏ธ](roles/web-svc-mirror/README.md#quick-setup) | [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Assets Server](roles/web-svc-asset/) | beta | Nginx-based server for hosting static assets copied from a source directory to the web data path | [๐Ÿ› ๏ธ](roles/web-svc-asset/README.md#quick-setup) | [File Server](roles/web-svc-file/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/) | beta | Scheduled deduplicating backup system for Docker container volumes to a local directory, with consistent SQL dumps | [๐Ÿ› ๏ธ](roles/svc-bkp-volume-2-local/README.md#quick-setup) | [Backup Host Secrets](roles/svc-bkp-secrets-2-local/) | @@ -68,20 +68,20 @@ Every invokable role in the tested lifecycle envelope, with its upstream homepag | [Backup NFS](roles/svc-bkp-nfs-2-local/) | beta | Scheduled backup job for hard-linked differential rsync snapshots of an NFS export into the local backup tree | [๐Ÿ› ๏ธ](roles/svc-bkp-nfs-2-local/README.md#quick-setup) | [NFS Server](roles/svc-storage-nfs-server/) | | [Backup Remote Server](roles/svc-bkp-remote-2-local/) | beta | Scheduled pull-style backup replicating remote hosts onto this host over SSH and rsync as hard-linked snapshots | [๐Ÿ› ๏ธ](roles/svc-bkp-remote-2-local/README.md#quick-setup) | [Backup to External Device](roles/svc-bkp-local-2-device/) | | [Backup to External Device](roles/svc-bkp-local-2-device/) | beta | Plug-triggered systemd backup for hard-link deduplicated snapshots of the local backup tree onto a swappable USB device | [๐Ÿ› ๏ธ](roles/svc-bkp-local-2-device/README.md#quick-setup) | | -| [Baserow](roles/web-app-baserow/) | beta | Self-hosted no-code database platform with a spreadsheet-like interface for building and collaborating on data | [๐ŸŒ](https://baserow.io/) [๐ŸŽฌ](https://www.youtube.com/watch?v=5yFMfP96_4M) [๐Ÿ› ๏ธ](roles/web-app-baserow/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Baserow](roles/web-app-baserow/) | beta | Self-hosted no-code database platform with a spreadsheet-like interface for building and collaborating on data | [๐ŸŒ](https://baserow.io/) [๐ŸŽฌ](https://www.youtube.com/watch?v=5yFMfP96_4M) [๐Ÿ› ๏ธ](roles/web-app-baserow/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [BigBlueButton](roles/web-app-bigbluebutton/) | beta | Self-hosted web conferencing platform for virtual classrooms, online meetings, and real-time collaboration | [๐ŸŒ](https://bigbluebutton.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=YRkQB6MJllI) [๐Ÿ› ๏ธ](roles/web-app-bigbluebutton/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Collabora](roles/web-svc-collabora/), [Corporate Design](roles/web-svc-css/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | | [Bluesky](roles/web-app-bluesky/) | beta | Self-hosted decentralized social network on the open AT Protocol, with its own Personal Data Server | [๐ŸŒ](https://bsky.social/) [๐Ÿ› ๏ธ](roles/web-app-bluesky/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [BookWyrm](roles/web-app-bookwyrm/) | beta | Self-hosted federated reading platform for book reviews and reading tracking across the Fediverse | [๐ŸŒ](https://joinbookwyrm.com/) [๐Ÿ› ๏ธ](roles/web-app-bookwyrm/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Bridgy Fed](roles/web-app-bridgy-fed/) | beta | Federation bridge connecting ActivityPub (Fediverse), the AT Protocol (Bluesky), and the IndieWeb | [๐ŸŒ](https://fed.brid.gy/) [๐Ÿ› ๏ธ](roles/web-app-bridgy-fed/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | -| [Checkmk](roles/web-app-checkmk/) | beta | Open-source IT and application monitoring server behind SSO with native LDAP user management | [๐ŸŒ](https://checkmk.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=opO-SOgOJ1I) [๐Ÿ› ๏ธ](roles/web-app-checkmk/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Checkmk](roles/web-app-checkmk/) | beta | Open-source IT and application monitoring server behind SSO with native LDAP user management | [๐ŸŒ](https://checkmk.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=opO-SOgOJ1I) [๐Ÿ› ๏ธ](roles/web-app-checkmk/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Chess](roles/web-app-chess/) | beta | Federated chess server for playing and following rule-validated games over ActivityPub across the Fediverse | [๐ŸŒ](https://castling.club/) [๐Ÿ› ๏ธ](roles/web-app-chess/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | -| [Collabora](roles/web-svc-collabora/) | beta | Self-hosted online office backend for real-time in-browser editing of documents, spreadsheets, and presentations | [๐ŸŒ](https://www.collaboraonline.com/) [๐ŸŽฌ](https://www.youtube.com/@CollaboraOnline) [๐Ÿ› ๏ธ](roles/web-svc-collabora/README.md#quick-setup) | [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Collabora](roles/web-svc-collabora/) | beta | Self-hosted online office backend for real-time in-browser editing of documents, spreadsheets, and presentations | [๐ŸŒ](https://www.collaboraonline.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=8pqkclWG2BY) [๐Ÿ› ๏ธ](roles/web-svc-collabora/README.md#quick-setup) | [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Content Delivery Network](roles/web-svc-cdn/) | beta | Nginx-based content delivery network for serving shared static assets to internal web applications | [๐Ÿ› ๏ธ](roles/web-svc-cdn/README.md#quick-setup) | [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Corporate Design](roles/web-svc-css/) | beta | Service-registry role owning the canonical `css` flag and redirecting the CSS hostname to the CDN upstream | [๐Ÿ› ๏ธ](roles/web-svc-css/README.md#quick-setup) | [Content Delivery Network](roles/web-svc-cdn/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Coturn](roles/web-svc-coturn/) | beta | Free and open-source TURN/STUN relay server for NAT traversal in WebRTC and real-time communication | [๐ŸŒ](https://github.com/coturn/coturn) [๐Ÿ› ๏ธ](roles/web-svc-coturn/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Prometheus](roles/web-app-prometheus/) | | [Dashboard](roles/web-app-dashboard/) | beta | Self-hosted portal for unified access to all deployed applications via a customizable tile and menu interface | [๐Ÿ› ๏ธ](roles/web-app-dashboard/README.md#quick-setup) | [Assets Server](roles/web-svc-asset/), [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Simple Icons](roles/web-svc-simpleicons/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [Decidim](roles/web-app-decidim/) | beta | Open-source participatory democracy platform for public consultations, civic processes, and community voting | [๐ŸŒ](https://decidim.org/) [๐ŸŽฌ](https://www.youtube.com/channel/UCbxXpC5MmKImcGFzUJxdAUw) [๐Ÿ› ๏ธ](roles/web-app-decidim/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [Discourse](roles/web-app-discourse/) | beta | Open-source discussion and community forum platform with moderation, notifications, and plugin support | [๐ŸŒ](https://www.discourse.org/) [๐ŸŽฌ](https://www.youtube.com/@discourse_) [๐Ÿ› ๏ธ](roles/web-app-discourse/README.md#quick-setup) | [Assets Server](roles/web-svc-asset/), [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Decidim](roles/web-app-decidim/) | beta | Open-source participatory democracy platform for public consultations, civic processes, and community voting | [๐ŸŒ](https://decidim.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=luSdPZ-wUIY) [๐Ÿ› ๏ธ](roles/web-app-decidim/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Discourse](roles/web-app-discourse/) | beta | Open-source discussion and community forum platform with moderation, notifications, and plugin support | [๐ŸŒ](https://www.discourse.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=z3qp_uB46FA) [๐Ÿ› ๏ธ](roles/web-app-discourse/README.md#quick-setup) | [Assets Server](roles/web-svc-asset/), [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Docker Registry](roles/svc-registry-docker/) | beta | Cluster-local container image registry for serving custom-built images to Docker Swarm worker nodes | [๐ŸŒ](https://distribution.github.io/distribution/) [๐Ÿ› ๏ธ](roles/svc-registry-docker/README.md#quick-setup) | [Docker Swarm](roles/svc-swarm-node/) | | [Docker Registry Cache](roles/svc-registry-cache/) | beta | Cluster-local pull-through cache for shared Docker Hub base-image pulls, cutting duplicate transfers and rate limits | [๐Ÿ› ๏ธ](roles/svc-registry-cache/README.md#quick-setup) | [Docker Swarm](roles/svc-swarm-node/) | | [Docker Swarm](roles/svc-swarm-node/) | beta | Container orchestration cluster for scheduling services across pooled manager and worker nodes | [๐Ÿ› ๏ธ](roles/svc-swarm-node/README.md#quick-setup) | | @@ -90,67 +90,76 @@ Every invokable role in the tested lifecycle envelope, with its upstream homepag | [ERPNext](roles/web-app-erpnext/) | beta | Self-hosted open-source ERP suite for finance, CRM, inventory, manufacturing, HR, sales, and projects | [๐ŸŒ](https://erpnext.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=JlqE-BfDEUY) [๐Ÿ› ๏ธ](roles/web-app-erpnext/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [EspoCRM](roles/web-app-espocrm/) | beta | Open-source CRM platform for managing sales, customer interactions, and business processes across teams | [๐ŸŒ](https://www.espocrm.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=TH6yJPTPLO0) [๐Ÿ› ๏ธ](roles/web-app-espocrm/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Fediwall](roles/web-app-fediwall/) | beta | Self-hosted Fediverse wall for showing recent public posts by hashtag or account in a live masonry grid | [๐ŸŒ](https://github.com/defnull/fediwall) [๐Ÿ› ๏ธ](roles/web-app-fediwall/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Friendica](roles/web-app-friendica/), [Mastodon](roles/web-app-mastodon/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | -| [Fider](roles/web-app-fider/) | beta | Open-source community feedback platform for collecting, voting on, and prioritizing feature requests and ideas | [๐ŸŒ](https://www.fider.io/) [๐Ÿ› ๏ธ](roles/web-app-fider/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Fider](roles/web-app-fider/) | beta | Open-source community feedback platform for collecting, voting on, and prioritizing feature requests and ideas | [๐ŸŒ](https://www.fider.io/) [๐Ÿ› ๏ธ](roles/web-app-fider/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [File Server](roles/web-svc-file/) | beta | Static file server over HTTPS with directory listing, .well-known handling, and automatic TLS certificates | [๐Ÿ› ๏ธ](roles/web-svc-file/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | -| [Flowise](roles/web-app-flowise/) | beta | Low-code visual builder for creating, testing, and publishing LLM and RAG workflows as HTTP endpoints | [๐ŸŒ](https://flowiseai.com/) [๐ŸŽฌ](https://www.youtube.com/@FlowiseAI) [๐Ÿ› ๏ธ](roles/web-app-flowise/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Ollama](roles/svc-ai-ollama/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Qdrant](roles/svc-db-qdrant/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Firewall ruleset](roles/svc-net-firewall/) | beta | nftables packet filter whose rules each role owns as its own table, replaced atomically and reloaded at boot | [๐ŸŒ](https://www.netfilter.org/projects/nftables/) [๐ŸŽฌ](https://www.youtube.com/watch?v=EGKhIljDPCw) [๐Ÿ› ๏ธ](roles/svc-net-firewall/README.md#quick-setup) | | +| [Flowise](roles/web-app-flowise/) | beta | Low-code visual builder for creating, testing, and publishing LLM and RAG workflows as HTTP endpoints | [๐ŸŒ](https://flowiseai.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=h_0TJTY6Ulg) [๐Ÿ› ๏ธ](roles/web-app-flowise/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Ollama](roles/svc-ai-ollama/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Qdrant](roles/svc-db-qdrant/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Friendica](roles/web-app-friendica/) | beta | Decentralized, federated social-networking platform for peer-to-peer communication and community building | [๐ŸŒ](https://friendi.ca/) [๐Ÿ› ๏ธ](roles/web-app-friendica/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Funkwhale](roles/web-app-funkwhale/) | beta | Self-hosted, federated platform for sharing, hosting, and streaming your own music and audio library | [๐ŸŒ](https://www.funkwhale.audio/) [๐Ÿ› ๏ธ](roles/web-app-funkwhale/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Typesense](roles/svc-db-typesense/), [Universal Logout](roles/web-svc-logout/) | | [FusionDirectory](roles/web-app-fusiondirectory/) | beta | Web-based LDAP administration interface for managing users, groups, and directory objects | [๐ŸŒ](https://www.fusiondirectory.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=dThpssnXGyk) [๐Ÿ› ๏ธ](roles/web-app-fusiondirectory/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [Gitea](roles/web-app-gitea/) | beta | Lightweight self-hosted Git service for code collaboration, version control, and repository management | [๐ŸŒ](https://about.gitea.com/) [๐Ÿ› ๏ธ](roles/web-app-gitea/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [GitLab](roles/web-app-gitlab/) | beta | Self-hosted DevOps platform for Git source-code management, CI/CD pipelines, and issue tracking | [๐ŸŒ](https://about.gitlab.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=7q9Y1Cv-ib0) [๐Ÿ› ๏ธ](roles/web-app-gitlab/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Gitea](roles/web-app-gitea/) | beta | Lightweight self-hosted Git service for code collaboration, version control, and repository management | [๐ŸŒ](https://about.gitea.com/) [๐Ÿ› ๏ธ](roles/web-app-gitea/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [GitLab](roles/web-app-gitlab/) | beta | Self-hosted DevOps platform for Git source-code management, CI/CD pipelines, and issue tracking | [๐ŸŒ](https://about.gitlab.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=7q9Y1Cv-ib0) [๐Ÿ› ๏ธ](roles/web-app-gitlab/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Hermes Agent](roles/web-app-hermes/) | beta | Kernel-isolated agent runtime serving an OpenAI-compatible API, routed to models through the shared LLM gateway | [๐ŸŒ](https://hermes-agent.nousresearch.com/) [๐Ÿ› ๏ธ](roles/web-app-hermes/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Kata & gVisor](roles/svc-virt-kata/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [Home Assistant](roles/web-app-homeassistant/) | beta | Smart-home automation hub with device integrations, dashboards and a built-in MCP server for AI agent access | [๐ŸŒ](https://www.home-assistant.io/) [๐Ÿ› ๏ธ](roles/web-app-homeassistant/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Dashboard](roles/web-app-dashboard/), [Flowise](roles/web-app-flowise/), [Hermes Agent](roles/web-app-hermes/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [HTML Server](roles/web-svc-html/) | beta | NGINX vhost for serving static HTML websites over HTTPS with automatic Let's Encrypt certificates | [๐Ÿ› ๏ธ](roles/web-svc-html/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Hugo](roles/web-app-hugo/) | beta | Static site generator building HTML from an upstream Git repository at build time and serving it via nginx | [๐ŸŒ](https://gohugo.io/) [๐Ÿ› ๏ธ](roles/web-app-hugo/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Imprint](roles/web-svc-legal/) | beta | NGINX-served static page rendering a legal imprint (Impressum) from a Jinja2 template | [๐Ÿ› ๏ธ](roles/web-svc-legal/README.md#quick-setup) | [HTML Server](roles/web-svc-html/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Intel Driver](roles/drv-intel/) | alpha | Intel VA-API media driver for hardware-accelerated video decode and encode across Linux distributions | [๐ŸŒ](https://github.com/intel/media-driver) [๐Ÿ› ๏ธ](roles/drv-intel/README.md#quick-setup) | | -| [Jellyfin](roles/web-app-jellyfin/) | beta | Self-hosted media server for streaming and organizing movies, TV, music, and photos, with OIDC and LDAP login | [๐ŸŒ](https://jellyfin.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=0t3lSJL3B_Q) [๐Ÿ› ๏ธ](roles/web-app-jellyfin/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [Jenkins](roles/web-app-jenkins/) | beta | Open-source automation server for CI/CD pipelines, builds, and plugin-driven deployment workflows | [๐ŸŒ](https://www.jenkins.io/) [๐ŸŽฌ](https://www.youtube.com/channel/UC5JBtmoz7ePk-33ZHimGiDQ) [๐Ÿ› ๏ธ](roles/web-app-jenkins/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [Jitsi Meet](roles/web-app-jitsi/) | beta | Self-hosted WebRTC platform for end-to-end-encryptable video conferencing with federated authentication | [๐ŸŒ](https://jitsi.org/) [๐ŸŽฌ](https://www.youtube.com/channel/UCyXuxN-aNUpRv0juUXLyjbw) [๐Ÿ› ๏ธ](roles/web-app-jitsi/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | -| [Joomla](roles/web-app-joomla/) | beta | Open-source content management system for building websites, intranets, and online applications without writing code | [๐ŸŒ](https://www.joomla.org/) [๐ŸŽฌ](https://www.youtube.com/user/joomla) [๐Ÿ› ๏ธ](roles/web-app-joomla/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Jellyfin](roles/web-app-jellyfin/) | beta | Self-hosted media server for streaming and organizing movies, TV, music, and photos, with OIDC and LDAP login | [๐ŸŒ](https://jellyfin.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=0t3lSJL3B_Q) [๐Ÿ› ๏ธ](roles/web-app-jellyfin/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Jenkins](roles/web-app-jenkins/) | beta | Open-source automation server for CI/CD pipelines, builds, and plugin-driven deployment workflows | [๐ŸŒ](https://www.jenkins.io/) [๐ŸŽฌ](https://www.youtube.com/watch?v=rNy00_gOo8o) [๐Ÿ› ๏ธ](roles/web-app-jenkins/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Jitsi Meet](roles/web-app-jitsi/) | beta | Self-hosted WebRTC platform for end-to-end-encryptable video conferencing with federated authentication | [๐ŸŒ](https://jitsi.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=TB7LlM4erx8) [๐Ÿ› ๏ธ](roles/web-app-jitsi/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Universal Logout](roles/web-svc-logout/) | +| [Joomla](roles/web-app-joomla/) | beta | Open-source content management system for building websites, intranets, and online applications without writing code | [๐ŸŒ](https://www.joomla.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=mXFSIC_zM2o) [๐Ÿ› ๏ธ](roles/web-app-joomla/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Kata & gVisor](roles/svc-virt-kata/) | beta | Kernel-isolating container runtimes that sandbox untrusted workloads in a microVM or a userspace kernel | [๐ŸŒ](https://katacontainers.io/) [๐Ÿ› ๏ธ](roles/svc-virt-kata/README.md#quick-setup) | | | [Keycloak](roles/web-app-keycloak/) | beta | Self-hosted identity and access management platform for single sign-on, multi-factor authentication, and user federation | [๐ŸŒ](https://www.keycloak.org/) [๐Ÿ› ๏ธ](roles/web-app-keycloak/README.md#quick-setup) | [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [KIX](roles/web-app-kix/) | beta | Open-source ITSM and helpdesk platform (OTRS fork) for ticketing, CMDB, knowledge base, and reporting | [๐ŸŒ](https://www.kixdesk.com/en/) [๐ŸŽฌ](https://www.youtube.com/watch?v=D62emos1FQ8) [๐Ÿ› ๏ธ](roles/web-app-kix/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [LAM](roles/web-app-lam/) | beta | Web interface for administering LDAP directories: managing users, groups, and other directory objects | [๐ŸŒ](https://www.ldap-account-manager.org/) [๐Ÿ› ๏ธ](roles/web-app-lam/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [LibreTranslate](roles/web-svc-libretranslate/) | beta | Self-hosted open-source machine translation API for translating and detecting text across languages | [๐ŸŒ](https://libretranslate.com/) [๐Ÿ› ๏ธ](roles/web-svc-libretranslate/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [LibreTranslate](roles/web-svc-libretranslate/) | beta | Self-hosted open-source machine translation API for translating and detecting text across languages | [๐ŸŒ](https://libretranslate.com/) [๐Ÿ› ๏ธ](roles/web-svc-libretranslate/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [LID Switch Driver](roles/drv-lid-switch/) | alpha | Power-aware systemd logind configuration for predictable laptop lid-close behavior across battery, AC, and docked states | [๐Ÿ› ๏ธ](roles/drv-lid-switch/README.md#quick-setup) | | -| [Listmonk](roles/web-app-listmonk/) | beta | Self-hosted platform for newsletters and mailing lists with subscriber segmentation and campaign analytics | [๐ŸŒ](https://listmonk.app/) [๐Ÿ› ๏ธ](roles/web-app-listmonk/README.md#quick-setup) | [Assets Server](roles/web-svc-asset/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Listmonk](roles/web-app-listmonk/) | beta | Self-hosted platform for newsletters and mailing lists with subscriber segmentation and campaign analytics | [๐ŸŒ](https://listmonk.app/) [๐Ÿ› ๏ธ](roles/web-app-listmonk/README.md#quick-setup) | [Assets Server](roles/web-svc-asset/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [LiteLLM Admin UI](roles/web-app-litellm/) | beta | Browser-facing admin interface for the shared LLM gateway, published on its own domain behind the front proxy | [๐ŸŒ](https://docs.litellm.ai/) [๐Ÿ› ๏ธ](roles/web-app-litellm/README.md#quick-setup) | [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | +| [LiteLLM Gateway](roles/svc-ai-litellm/) | beta | OpenAI-compatible LLM gateway routing a single /v1 endpoint to local and hosted model backends with per-consumer keys | [๐ŸŒ](https://docs.litellm.ai/) [๐Ÿ› ๏ธ](roles/svc-ai-litellm/README.md#quick-setup) | [LM Studio](roles/svc-ai-lmstudio/), [Ollama](roles/svc-ai-ollama/), [PostgreSQL](roles/svc-db-postgres/) | | [LittleJS](roles/web-app-littlejs/) | alpha | Self-hosted HTML5 game sandbox for browsing and running lightweight engine demos and games in the browser | [๐ŸŒ](https://killedbyapixel.github.io/LittleJS/) [๐ŸŽฌ](https://youtu.be/chuBzGjv7Ms) [๐Ÿ› ๏ธ](roles/web-app-littlejs/README.md#quick-setup) | [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | -| [Magento](roles/web-app-magento/) | alpha | Self-hosted e-commerce platform for catalog management, checkout, promotions, and multi-store online retail | [๐ŸŒ](https://business.adobe.com/products/commerce/magento/open-source.html) [๐ŸŽฌ](https://www.youtube.com/user/magentocommerce) [๐Ÿ› ๏ธ](roles/web-app-magento/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [LM Studio](roles/svc-ai-lmstudio/) | beta | Headless local model server for open LLMs with an OpenAI-compatible API on the container network | [๐ŸŒ](https://lmstudio.ai/) [๐Ÿ› ๏ธ](roles/svc-ai-lmstudio/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/) | +| [Magento](roles/web-app-magento/) | alpha | Self-hosted e-commerce platform for catalog management, checkout, promotions, and multi-store online retail | [๐ŸŒ](https://business.adobe.com/products/commerce/magento/open-source.html) [๐ŸŽฌ](https://www.youtube.com/watch?v=nFdz9DZrdFc) [๐Ÿ› ๏ธ](roles/web-app-magento/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Mailu](roles/web-app-mailu/) | beta | Self-hosted mail server suite with SMTP/IMAP/POP3, webmail, spam filtering, antivirus, DKIM signing, and TLS | [๐ŸŒ](https://mailu.io/) [๐Ÿ› ๏ธ](roles/web-app-mailu/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [MariaDB](roles/svc-db-mariadb/) | beta | Shared relational database server for applications needing central SQL storage, run in Docker | [๐ŸŒ](https://mariadb.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=YsIJB15fq_c) [๐Ÿ› ๏ธ](roles/svc-db-mariadb/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Tor Onion Service](roles/svc-net-tor/) | | [Mastodon](roles/web-app-mastodon/) | beta | Self-hosted federated social network for microblogging, real-time timelines, and community moderation | [๐ŸŒ](https://joinmastodon.org/) [๐Ÿ› ๏ธ](roles/web-app-mastodon/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Matomo](roles/web-app-matomo/) | beta | Self-hosted, privacy-first web analytics platform for real-time visitor tracking and site metrics | [๐ŸŒ](https://matomo.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=Qc2kooLNDiU) [๐Ÿ› ๏ธ](roles/web-app-matomo/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [MariaDB](roles/svc-db-mariadb/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [Matrix](roles/web-app-matrix/) | beta | Federated, end-to-end-encrypted messaging platform with a web client and protocol bridges to external chat networks | [๐ŸŒ](https://matrix.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=3AVsNqH_-9M) [๐Ÿ› ๏ธ](roles/web-app-matrix/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [Mattermost](roles/web-app-mattermost/) | beta | Open-source, self-hosted team messaging platform for real-time collaboration via channels, threads, and integrations | [๐ŸŒ](https://mattermost.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=szfZfQFUSnU) [๐Ÿ› ๏ธ](roles/web-app-mattermost/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [MediaWiki](roles/web-app-mediawiki/) | beta | Collaborative wiki platform for user-driven documentation with an extensible extension ecosystem and content management | [๐ŸŒ](https://www.mediawiki.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=-JnIjpRvgNY) [๐Ÿ› ๏ธ](roles/web-app-mediawiki/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Matrix](roles/web-app-matrix/) | beta | Federated, end-to-end-encrypted messaging platform with a web client and protocol bridges to external chat networks | [๐ŸŒ](https://matrix.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=3AVsNqH_-9M) [๐Ÿ› ๏ธ](roles/web-app-matrix/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Mattermost](roles/web-app-mattermost/) | beta | Open-source, self-hosted team messaging platform for real-time collaboration via channels, threads, and integrations | [๐ŸŒ](https://mattermost.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=szfZfQFUSnU) [๐Ÿ› ๏ธ](roles/web-app-mattermost/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [MCP Adapter](roles/svc-ai-mcp-adapter/) | alpha | Reusable per-provider MCP adapter exposing a narrow allowlisted read surface | [๐ŸŒ](https://modelcontextprotocol.io/) [๐Ÿ› ๏ธ](roles/svc-ai-mcp-adapter/README.md#quick-setup) | | +| [MediaWiki](roles/web-app-mediawiki/) | beta | Collaborative wiki platform for user-driven documentation with an extensible extension ecosystem and content management | [๐ŸŒ](https://www.mediawiki.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=-JnIjpRvgNY) [๐Ÿ› ๏ธ](roles/web-app-mediawiki/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Memcached](roles/svc-db-memcached/) | beta | Central in-memory caching engine with per-consumer key-prefix isolation, usable centrally or as an embedded sidecar | [๐ŸŒ](https://memcached.org/) [๐Ÿ› ๏ธ](roles/svc-db-memcached/README.md#quick-setup) | [Tor Onion Service](roles/svc-net-tor/) | | [MIG](roles/web-app-mig/) | alpha | Interactive graph visualization of all Infinito.Nexus roles and their dependencies for architecture transparency | [๐Ÿ› ๏ธ](roles/web-app-mig/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Mini-QR](roles/web-app-mini-qr/) | beta | Self-hosted browser tool for generating QR codes from text or URLs with privacy-friendly local rendering | [๐ŸŒ](https://github.com/lyqht/mini-qr) [๐Ÿ› ๏ธ](roles/web-app-mini-qr/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | -| [Mobilizon](roles/web-app-mobilizon/) | beta | Federated, self-hosted platform for organizing events and building communities and groups | [๐ŸŒ](https://joinmobilizon.org/) [๐ŸŽฌ](https://framatube.org/c/mobilizon/videos) [๐Ÿ› ๏ธ](roles/web-app-mobilizon/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [Moodle](roles/web-app-moodle/) | beta | Open-source learning management system for creating, managing, and delivering online courses and e-learning | [๐ŸŒ](https://moodle.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=3ORsUGVNxGs) [๐Ÿ› ๏ธ](roles/web-app-moodle/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [n8n](roles/web-app-n8n/) | beta | Self-hosted low-code automation platform for connecting services and building workflow integrations visually | [๐ŸŒ](https://n8n.io/) [๐ŸŽฌ](https://youtu.be/4cQWJViybAQ) [๐Ÿ› ๏ธ](roles/web-app-n8n/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [Nextcloud](roles/web-app-nextcloud/) | beta | Self-hosted cloud platform for file sync, sharing, real-time collaboration, and team workspaces under your own domain | [๐ŸŒ](https://nextcloud.com/) [๐ŸŽฌ](https://youtu.be/3jcYJGQgenI?si=FDmoMSrAb9_WvviC) [๐Ÿ› ๏ธ](roles/web-app-nextcloud/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [BigBlueButton](roles/web-app-bigbluebutton/), [Collabora](roles/web-svc-collabora/), [Corporate Design](roles/web-svc-css/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Discourse](roles/web-app-discourse/), [Flowise](roles/web-app-flowise/), [GitLab](roles/web-app-gitlab/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Mastodon](roles/web-app-mastodon/), [Matomo](roles/web-app-matomo/), [Matrix](roles/web-app-matrix/), [Mattermost](roles/web-app-mattermost/), [OnlyOffice](roles/web-svc-onlyoffice/), [Open WebUI](roles/web-app-openwebui/), [OpenLDAP](roles/svc-db-openldap/), [OpenProject](roles/web-app-openproject/), [PeerTube](roles/web-app-peertube/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/), [XWiki](roles/web-app-xwiki/), [Zammad](roles/web-app-zammad/) | +| [Mobilizon](roles/web-app-mobilizon/) | beta | Federated, self-hosted platform for organizing events and building communities and groups | [๐ŸŒ](https://joinmobilizon.org/) [๐ŸŽฌ](https://framatube.org/w/2mtugeJXaihsQnTHVWHf2E) [๐Ÿ› ๏ธ](roles/web-app-mobilizon/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Moodle](roles/web-app-moodle/) | beta | Open-source learning management system for creating, managing, and delivering online courses and e-learning | [๐ŸŒ](https://moodle.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=3ORsUGVNxGs) [๐Ÿ› ๏ธ](roles/web-app-moodle/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [n8n](roles/web-app-n8n/) | beta | Self-hosted low-code automation platform for connecting services and building workflow integrations visually | [๐ŸŒ](https://n8n.io/) [๐ŸŽฌ](https://youtu.be/4cQWJViybAQ) [๐Ÿ› ๏ธ](roles/web-app-n8n/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Nextcloud](roles/web-app-nextcloud/) | beta | Self-hosted cloud platform for file sync, sharing, real-time collaboration, and team workspaces under your own domain | [๐ŸŒ](https://nextcloud.com/) [๐ŸŽฌ](https://youtu.be/3jcYJGQgenI?si=FDmoMSrAb9_WvviC) [๐Ÿ› ๏ธ](roles/web-app-nextcloud/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [BigBlueButton](roles/web-app-bigbluebutton/), [Collabora](roles/web-svc-collabora/), [Corporate Design](roles/web-svc-css/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Discourse](roles/web-app-discourse/), [GitLab](roles/web-app-gitlab/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Mastodon](roles/web-app-mastodon/), [Matomo](roles/web-app-matomo/), [Matrix](roles/web-app-matrix/), [Mattermost](roles/web-app-mattermost/), [OnlyOffice](roles/web-svc-onlyoffice/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [OpenLDAP](roles/svc-db-openldap/), [OpenProject](roles/web-app-openproject/), [PeerTube](roles/web-app-peertube/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/), [XWiki](roles/web-app-xwiki/), [Zammad](roles/web-app-zammad/) | | [NFS Client](roles/svc-storage-nfs-client/) | beta | Client-side NFS setup for mounting a remote server export on every swarm node, with a deploy-time reachability probe | [๐Ÿ› ๏ธ](roles/svc-storage-nfs-client/README.md#quick-setup) | [NFS Server](roles/svc-storage-nfs-server/) | | [NFS Server](roles/svc-storage-nfs-server/) | beta | Kernel-level NFS server for exporting a shared directory tree with IP-restricted access for swarm-node hosts | [๐Ÿ› ๏ธ](roles/svc-storage-nfs-server/README.md#quick-setup) | [Backup NFS](roles/svc-bkp-nfs-2-local/) | -| [Odoo ERP](roles/web-app-odoo/) | beta | Open-source ERP suite for CRM, sales, accounting, inventory, HR, and website management | [๐ŸŒ](https://www.odoo.com/) [๐ŸŽฌ](https://www.odoo.com/slides/getting-started-15) [๐Ÿ› ๏ธ](roles/web-app-odoo/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Odoo ERP](roles/web-app-odoo/) | beta | Open-source ERP suite for CRM, sales, accounting, inventory, HR, and website management | [๐ŸŒ](https://www.odoo.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=FCmFgHVzd3E) [๐Ÿ› ๏ธ](roles/web-app-odoo/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Ollama](roles/svc-ai-ollama/) | beta | Self-hosted model server for running open LLMs locally behind a simple HTTP API | [๐ŸŒ](https://ollama.com/) [๐Ÿ› ๏ธ](roles/svc-ai-ollama/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/) | -| [OnlyOffice](roles/web-svc-onlyoffice/) | beta | Document server backend for real-time in-browser editing of documents, spreadsheets, and presentations | [๐ŸŒ](https://www.onlyoffice.com/) [๐ŸŽฌ](https://www.youtube.com/channel/UCNxeQm7vVujR8eFPtpVAVNg) [๐Ÿ› ๏ธ](roles/web-svc-onlyoffice/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/) | -| [Open WebUI](roles/web-app-openwebui/) | beta | Self-hosted chat interface for interacting with local and private AI models via backends such as Ollama | [๐ŸŒ](https://openwebui.com/) [๐Ÿ› ๏ธ](roles/web-app-openwebui/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Ollama](roles/svc-ai-ollama/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [OnlyOffice](roles/web-svc-onlyoffice/) | beta | Document server backend for real-time in-browser editing of documents, spreadsheets, and presentations | [๐ŸŒ](https://www.onlyoffice.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=uiFxnRK_aWM) [๐Ÿ› ๏ธ](roles/web-svc-onlyoffice/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/) | +| [Open WebUI](roles/web-app-openwebui/) | beta | Self-hosted chat interface for interacting with local and private AI models via backends such as Ollama | [๐ŸŒ](https://openwebui.com/) [๐Ÿ› ๏ธ](roles/web-app-openwebui/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [OpenClaw](roles/web-app-openclaw/) | beta | Self-hosted personal AI agent gateway with a browser control UI, sandboxed in a Kata microVM or gVisor runtime | [๐ŸŒ](https://openclaw.ai/) [๐Ÿ› ๏ธ](roles/web-app-openclaw/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Kata & gVisor](roles/svc-virt-kata/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [OpenCloud](roles/web-app-opencloud/) | beta | Self-hosted platform for file sync, sharing, and collaboration with Keycloak SSO and central LDAP directory | [๐ŸŒ](https://opencloud.eu/) [๐ŸŽฌ](https://www.youtube.com/watch?v=Cg48rFNY0R4) [๐Ÿ› ๏ธ](roles/web-app-opencloud/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [OpenLDAP](roles/svc-db-openldap/) | beta | Self-hosted LDAP directory service for centralized user, group, and schema management with TLS-secured access | [๐ŸŒ](https://www.openldap.org/) [๐Ÿ› ๏ธ](roles/svc-db-openldap/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Tor Onion Service](roles/svc-net-tor/) | | [OpenProject](roles/web-app-openproject/) | beta | Self-hosted platform for project management, work-package tracking, Gantt planning, and team collaboration | [๐ŸŒ](https://www.openproject.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=rvCd0xH7rCs) [๐Ÿ› ๏ธ](roles/web-app-openproject/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [OpenResty](roles/svc-prx-openresty/) | beta | NGINX-based web platform and reverse proxy with validated config reloads and Let's Encrypt integration | [๐ŸŒ](https://openresty.org/) [๐ŸŽฌ](https://openresty.org/en/videos.html) [๐Ÿ› ๏ธ](roles/svc-prx-openresty/README.md#quick-setup) | [Tor Onion Service](roles/svc-net-tor/) | +| [OpenResty](roles/svc-prx-openresty/) | beta | NGINX-based web platform and reverse proxy with validated config reloads and Let's Encrypt integration | [๐ŸŒ](https://openresty.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=NR8U1qYHGqk) [๐Ÿ› ๏ธ](roles/svc-prx-openresty/README.md#quick-setup) | [Tor Onion Service](roles/svc-net-tor/) | | [OpenTalk](roles/web-app-opentalk/) | beta | Sovereign open-source video conferencing platform for audio/video calls, screen sharing, breakout rooms, and SSO | [๐ŸŒ](https://opentalk.eu/) [๐Ÿ› ๏ธ](roles/web-app-opentalk/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | | [Package update](roles/update/) | beta | System-maintenance role for refreshing the package index and upgrading installed packages via the OS package manager | [๐Ÿ› ๏ธ](roles/update/README.md#quick-setup) | | | [PeerTube](roles/web-app-peertube/) | beta | Decentralized, federated platform for peer-to-peer video hosting, streaming, and live broadcasting | [๐ŸŒ](https://joinpeertube.org/) [๐ŸŽฌ](https://framatube.org/w/cX4KAPLTwha6hzLZ5xePGZ) [๐Ÿ› ๏ธ](roles/web-app-peertube/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Universal Logout](roles/web-svc-logout/) | | [Penpot](roles/web-app-penpot/) | beta | Self-hosted design and prototyping platform for UI/UX work, real-time collaboration, and developer handoff | [๐ŸŒ](https://penpot.app/) [๐ŸŽฌ](https://www.youtube.com/watch?v=vAkb4QQmbfk) [๐Ÿ› ๏ธ](roles/web-app-penpot/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [pgAdmin](roles/web-app-pgadmin/) | beta | Web-based administration and development platform for managing multiple PostgreSQL servers, with optional OAuth2 login | [๐ŸŒ](https://www.pgadmin.org/) [๐ŸŽฌ](https://www.pgadmin.org/videos/) [๐Ÿ› ๏ธ](roles/web-app-pgadmin/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [pgAdmin](roles/web-app-pgadmin/) | beta | Web-based administration and development platform for managing multiple PostgreSQL servers, with optional OAuth2 login | [๐ŸŒ](https://www.pgadmin.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=WFT5MaZN6g4) [๐Ÿ› ๏ธ](roles/web-app-pgadmin/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [PhpMyAdmin](roles/web-app-phpmyadmin/) | beta | Web-based administration tool for MySQL and MariaDB with schema management, querying, and import/export | [๐ŸŒ](https://www.phpmyadmin.net/) [๐Ÿ› ๏ธ](roles/web-app-phpmyadmin/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Pixelfed](roles/web-app-pixelfed/) | beta | Decentralized, federated platform for photo sharing and image feeds across the fediverse | [๐ŸŒ](https://pixelfed.org/) [๐Ÿ› ๏ธ](roles/web-app-pixelfed/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [PostgreSQL](roles/svc-db-postgres/) | beta | Containerized relational database with automated database, user, and privilege provisioning | [๐ŸŒ](https://www.postgresql.org/) [๐Ÿ› ๏ธ](roles/svc-db-postgres/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Tor Onion Service](roles/svc-net-tor/) | | [Postmarks](roles/web-app-postmarks/) | beta | Single-user ActivityPub bookmarking site federating public bookmarks to Mastodon and the Fediverse | [๐ŸŒ](https://github.com/ckolderup/postmarks) [๐Ÿ› ๏ธ](roles/web-app-postmarks/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [Pretix](roles/web-app-pretix/) | beta | Self-hosted ticketing platform for events with online sales, registration management, and secure payments | [๐ŸŒ](https://pretix.eu/) [๐ŸŽฌ](https://www.youtube.com/channel/UCG1Og1YUpgIJD4geAZLAp5g) [๐Ÿ› ๏ธ](roles/web-app-pretix/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [Prometheus](roles/web-app-prometheus/) | beta | Open-source monitoring and alerting toolkit for storing metrics as time-series data and querying them with PromQL | [๐ŸŒ](https://prometheus.io/) [๐ŸŽฌ](https://www.youtube.com/c/PrometheusIo) [๐Ÿ› ๏ธ](roles/web-app-prometheus/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Pretix](roles/web-app-pretix/) | beta | Self-hosted ticketing platform for events with online sales, registration management, and secure payments | [๐ŸŒ](https://pretix.eu/) [๐ŸŽฌ](https://www.youtube.com/watch?v=5F6QkZP1Zf0) [๐Ÿ› ๏ธ](roles/web-app-pretix/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Prometheus](roles/web-app-prometheus/) | beta | Open-source monitoring and alerting toolkit for storing metrics as time-series data and querying them with PromQL | [๐ŸŒ](https://prometheus.io/) [๐ŸŽฌ](https://www.youtube.com/watch?v=PzFUwBflXYc) [๐Ÿ› ๏ธ](roles/web-app-prometheus/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Flowise](roles/web-app-flowise/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Proprietary Drivers](roles/drv-non-free/) | alpha | Proprietary GPU driver installer for Arch-based systems via mhwd nonfree hardware detection | [๐Ÿ› ๏ธ](roles/drv-non-free/README.md#quick-setup) | | -| [Qdrant](roles/svc-db-qdrant/) | beta | Central vector database engine for storing and searching per-consumer embeddings shared across the stack | [๐ŸŒ](https://qdrant.tech/) [๐ŸŽฌ](https://www.youtube.com/watch?v=_opNdOa48Lc) [๐Ÿ› ๏ธ](roles/svc-db-qdrant/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Tor Onion Service](roles/svc-net-tor/) | +| [Qdrant](roles/svc-db-qdrant/) | beta | Central vector database engine for storing and searching per-consumer embeddings shared across the stack | [๐ŸŒ](https://qdrant.tech/) [๐ŸŽฌ](https://www.youtube.com/watch?v=_opNdOa48Lc) [๐Ÿ› ๏ธ](roles/svc-db-qdrant/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Flowise](roles/web-app-flowise/), [Hermes Agent](roles/web-app-hermes/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [Tor Onion Service](roles/svc-net-tor/) | | [RabbitMQ](roles/svc-db-rabbitmq/) | beta | Shared message broker for async messaging with per-consumer virtual host and user isolation | [๐ŸŒ](https://www.rabbitmq.com/) [๐Ÿ› ๏ธ](roles/svc-db-rabbitmq/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Tor Onion Service](roles/svc-net-tor/) | | [Redirector](roles/web-opt-rdr-domains/) | beta | NGINX glue role for 301 redirects from source to target domains with automatic SSL for the source hosts | [๐Ÿ› ๏ธ](roles/web-opt-rdr-domains/README.md#quick-setup) | | | [Redis](roles/svc-db-redis/) | beta | In-memory key-value cache and store, shared centrally with per-consumer ACL isolation or embedded as a sidecar | [๐ŸŒ](https://redis.io/) [๐Ÿ› ๏ธ](roles/svc-db-redis/README.md#quick-setup) | [Tor Onion Service](roles/svc-net-tor/) | @@ -160,14 +169,14 @@ Every invokable role in the tested lifecycle envelope, with its upstream homepag | [Semaphore UI](roles/web-app-semaphore/) | beta | Web UI and API for running Ansible, Terraform/OpenTofu, and shell automation on a schedule or on demand | [๐ŸŒ](https://semaphoreui.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=nzR4yDuZQMU) [๐Ÿ› ๏ธ](roles/web-app-semaphore/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Shopware](roles/web-app-shopware/) | beta | Open-source ecommerce platform built on Symfony and Vue.js for building and scaling online storefronts | [๐ŸŒ](https://www.shopware.com/en/) [๐ŸŽฌ](https://www.youtube.com/watch?v=bG57TZPYsyw) [๐Ÿ› ๏ธ](roles/web-app-shopware/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Simple Icons](roles/web-svc-simpleicons/) | beta | Containerized icon server for hosting the Simple Icons brand SVG and PNG collection for web and documentation use | [๐ŸŒ](https://simpleicons.org/) [๐Ÿ› ๏ธ](roles/web-svc-simpleicons/README.md#quick-setup) | [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | -| [Snipeโ€‘IT](roles/web-app-snipe-it/) | beta | Open-source IT asset management system for tracking hardware and software inventory | [๐ŸŒ](https://snipeitapp.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=q0V6FAPc1ls) [๐Ÿ› ๏ธ](roles/web-app-snipe-it/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Snipeโ€‘IT](roles/web-app-snipe-it/) | beta | Open-source IT asset management system for tracking hardware and software inventory | [๐ŸŒ](https://snipeitapp.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=q0V6FAPc1ls) [๐Ÿ› ๏ธ](roles/web-app-snipe-it/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Social Home](roles/web-app-socialhome/) | alpha | Privacy-first social platform for households, federating peer-to-peer over WebRTC on an embedded SQLite store | [๐ŸŒ](https://github.com/social-home-io/socialhome) [๐Ÿ› ๏ธ](roles/web-app-socialhome/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Coturn](roles/web-svc-coturn/), [Dashboard](roles/web-app-dashboard/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Sphinx](roles/web-app-sphinx/) | beta | Documentation generator that builds HTML from a source repository and serves it through a lightweight HTTP server | [๐ŸŒ](https://www.sphinx-doc.org/) [๐Ÿ› ๏ธ](roles/web-app-sphinx/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Storage Optimizer](roles/svc-opt-ssd-hdd/) | beta | Tiering role placing Docker volumes on SSD or HDD by workload type, with symlinks keeping paths consistent | [๐Ÿ› ๏ธ](roles/svc-opt-ssd-hdd/README.md#quick-setup) | | -| [SuiteCRM](roles/web-app-suitecrm/) | beta | Open-source CRM platform for sales, service, cases, and campaign management with workflow automation | [๐ŸŒ](https://suitecrm.com/) [๐ŸŽฌ](https://suitecrm.com/suitecrm-demo-video/) [๐Ÿ› ๏ธ](roles/web-app-suitecrm/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [SuiteCRM](roles/web-app-suitecrm/) | beta | Open-source CRM platform for sales, service, cases, and campaign management with workflow automation | [๐ŸŒ](https://suitecrm.com/) [๐ŸŽฌ](https://www.youtube.com/watch?v=pOAs_C3Fp_E) [๐Ÿ› ๏ธ](roles/web-app-suitecrm/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Swapfile](roles/svc-opt-swapfile/) | beta | On-target automation for creating and activating swap space via a cloned swapfile script | [๐Ÿ› ๏ธ](roles/svc-opt-swapfile/README.md#quick-setup) | | | [Taiga](roles/web-app-taiga/) | beta | Open-source agile project management platform for Scrum, Kanban, and hybrid team workflows | [๐ŸŒ](https://taiga.io/) [๐ŸŽฌ](https://www.youtube.com/watch?v=TYPX8nQEU5I) [๐Ÿ› ๏ธ](roles/web-app-taiga/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [SeaweedFS](roles/web-app-seaweedfs/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [Tor Onion Service](roles/svc-net-tor/) | alpha | Tor daemon publishing the node as a v3 onion service | [๐Ÿ› ๏ธ](roles/svc-net-tor/README.md#quick-setup) | [Asset Mirror (Privacy Proxy)](roles/web-svc-mirror/) | +| [Tor Onion Service](roles/svc-net-tor/) | beta | Tor daemon publishing the node as a v3 onion service | [๐Ÿ› ๏ธ](roles/svc-net-tor/README.md#quick-setup) | [Asset Mirror (Privacy Proxy)](roles/web-svc-mirror/) | | [Typesense](roles/svc-db-typesense/) | beta | Central Dockerized search engine shared by multiple apps with per-consumer scoped API keys | [๐ŸŒ](https://typesense.org/) [๐Ÿ› ๏ธ](roles/svc-db-typesense/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Tor Onion Service](roles/svc-net-tor/) | | [Unbound](roles/svc-dns-unbound/) | beta | Central recursive/forwarding DNSSEC resolver on a static IP for consumer stacks to target as their DNS | [๐ŸŒ](https://nlnetlabs.nl/projects/unbound/about/) [๐Ÿ› ๏ธ](roles/svc-dns-unbound/README.md#quick-setup) | | | [Universal Logout](roles/web-svc-logout/) | beta | Central logout proxy for single-action sign-out across all OIDC-connected apps, with Nginx snippets and a live status UI | [๐Ÿ› ๏ธ](roles/web-svc-logout/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | @@ -175,12 +184,12 @@ Every invokable role in the tested lifecycle envelope, with its upstream homepag | [Wireguard](roles/svc-net-wireguard-core/) | alpha | Host-level WireGuard VPN service with wg-quick config, package install, and IP-forwarding sysctl for secure tunnels | [๐ŸŒ](https://www.wireguard.com/) [๐Ÿ› ๏ธ](roles/svc-net-wireguard-core/README.md#quick-setup) | | | [Wireguard Client](roles/svc-net-wireguard-plain/) | alpha | Client-side WireGuard VPN role for stable connectivity with a systemd service and script that tune interface MTU | [๐ŸŒ](https://www.wireguard.com/) [๐Ÿ› ๏ธ](roles/svc-net-wireguard-plain/README.md#quick-setup) | | | [WireGuard Client behind NAT](roles/svc-net-wireguard-firewalled/) | alpha | Networking helper for iptables forwarding and NAT masquerading of a WireGuard client running behind NAT or a firewall | [๐Ÿ› ๏ธ](roles/svc-net-wireguard-firewalled/README.md#quick-setup) | | -| [WordPress](roles/web-app-wordpress/) | beta | Content management system for building and managing websites, blogs, and multisite networks with themes and plugins | [๐ŸŒ](https://wordpress.org/) [๐ŸŽฌ](https://www.youtube.com/wordpress) [๐Ÿ› ๏ธ](roles/web-app-wordpress/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Discourse](roles/web-app-discourse/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [WordPress](roles/web-app-wordpress/) | beta | Content management system for building and managing websites, blogs, and multisite networks with themes and plugins | [๐ŸŒ](https://wordpress.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=QU8GFqvXRxE) [๐Ÿ› ๏ธ](roles/web-app-wordpress/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Discourse](roles/web-app-discourse/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Mailu](roles/web-app-mailu/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [OpenClaw](roles/web-app-openclaw/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [World Wide Web](roles/web-opt-rdr-www/) | beta | NGINX server blocks that permanently redirect www subdomains to their non-www apex domains | [๐Ÿ› ๏ธ](roles/web-opt-rdr-www/README.md#quick-setup) | [Tor Onion Service](roles/svc-net-tor/) | | [XMPP](roles/web-svc-xmpp/) | beta | Placeholder stub role for a future XMPP server/container deployment, implementation pending | [๐ŸŒ](https://ejabberd.im/) [๐Ÿ› ๏ธ](roles/web-svc-xmpp/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Keycloak](roles/web-app-keycloak/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | -| [XWiki](roles/web-app-xwiki/) | beta | Self-hosted enterprise wiki and knowledge-management platform with collaboration and app-based extensibility | [๐ŸŒ](https://www.xwiki.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=8DePx30dh2g) [๐Ÿ› ๏ธ](roles/web-app-xwiki/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [XWiki](roles/web-app-xwiki/) | beta | Self-hosted enterprise wiki and knowledge-management platform with collaboration and app-based extensibility | [๐ŸŒ](https://www.xwiki.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=8DePx30dh2g) [๐Ÿ› ๏ธ](roles/web-app-xwiki/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [YOURLS](roles/web-app-yourls/) | beta | Self-hosted URL shortener for creating, tracking, and managing short links with built-in click analytics | [๐ŸŒ](https://yourls.org/) [๐Ÿ› ๏ธ](roles/web-app-yourls/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [MariaDB](roles/svc-db-mariadb/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [Zammad](roles/web-app-zammad/) | beta | Open-source helpdesk and ticketing system for handling customer requests via email, chat, phone, and web | [๐ŸŒ](https://zammad.org/) [๐ŸŽฌ](https://www.youtube.com/@zammadhq) [๐Ÿ› ๏ธ](roles/web-app-zammad/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Memcached](roles/svc-db-memcached/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [Zammad](roles/web-app-zammad/) | beta | Open-source helpdesk and ticketing system for handling customer requests via email, chat, phone, and web | [๐ŸŒ](https://zammad.org/) [๐ŸŽฌ](https://www.youtube.com/watch?v=K30V0Uimr-s) [๐Ÿ› ๏ธ](roles/web-app-zammad/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Hermes Agent](roles/web-app-hermes/), [Keycloak](roles/web-app-keycloak/), [LiteLLM Gateway](roles/svc-ai-litellm/), [Mailu](roles/web-app-mailu/), [Matomo](roles/web-app-matomo/), [Memcached](roles/svc-db-memcached/), [Open WebUI](roles/web-app-openwebui/), [OpenClaw](roles/web-app-openclaw/), [OpenLDAP](roles/svc-db-openldap/), [PostgreSQL](roles/svc-db-postgres/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | ## Guides ๐Ÿ“š diff --git a/TODO.md b/TODO.md index 9f401239e6..48cc42d59f 100644 --- a/TODO.md +++ b/TODO.md @@ -83,7 +83,8 @@ against those runs say so inline. `container_extra_hosts` lookup yet (fix is the same one-line lookup, apply on CI evidence): wordpress (daggerhart plugin) and mediawiki (PluggableAuth) are structurally identical PHP in-app plugins (high - likelihood); discourse, jenkins, jira, confluence, odoo, openwebui, + likelihood); discourse is now confirmed and pinned (run 33445831564, job + Nextcloud#7); jenkins, jira, confluence, odoo, openwebui, pretix, zammad, semaphore, jellyfin, listmonk, xwiki, mastodon consume the issuer server-side too (unverified network path). oauth2-proxy-based apps are NOT affected (proven green: prometheus admin SSO). Two names have left diff --git a/aliases b/aliases index 09dff24008..53bf1b44ac 100644 --- a/aliases +++ b/aliases @@ -1,5 +1,6 @@ alias i8='infinito' # the infinito CLI alias i8bo='m bootstrap' +alias i8bond='m bond' alias i8bu='m build' alias i8buce='m build-cleanup' alias i8bude='m build-dependency' @@ -16,16 +17,21 @@ alias i8ceco='m clean-container-owned' alias i8cepa='m clean-pycache-dirs' alias i8cesa='m clean-stale-nfs' alias i8cesu='m clean-sudo' +alias i8ciall='__i8ciall(){ [ -z "${1:-}" ] && { echo "usage: i8ciall " >&2; return 2; }; ghaf "$1" || echo "i8ciall: force-cancel of run $1 reported nothing to cancel; continuing" >&2; infinito administration deploy ci trigger --failed --strict --roles-only --run "$1"; }; __i8ciall' # retrigger run $1 (id or url): only the roles that truly failed take the priority line, by name, letting the rotation pick the axes, plus the priority entries that run never deployed, axes and all; the aborted, the still-running and the never-reached stay on the regular line, which resumes behind the green stretch the run added to the offset it was given; the workspace suite comes back unless every one of its jobs went green; force-cancels the run first so it stops holding runner slots +alias i8ciallon='__i8ciallon(){ [ -z "${1:-}" ] && { echo "usage: i8ciallon " >&2; return 2; }; ghaf "$1" || echo "i8ciallon: force-cancel of run $1 reported nothing to cancel; continuing" >&2; infinito administration deploy ci trigger --failed --strict --roles-only --chunk-gate false --run "$1"; }; __i8ciallon' # like i8ciall, but the retrigger keeps deploying the remaining chunks after a failed one (chunk_gate=false) instead of stopping the chain; the run still ends red alias i8cifail='__i8cifail(){ [ -z "${1:-}" ] && { echo "usage: i8cifail " >&2; return 2; }; ghaf "$1" || echo "i8cifail: force-cancel of run $1 reported nothing to cancel; continuing" >&2; infinito administration deploy ci trigger --failed --run "$1"; }; __i8cifail' # retrigger the exact failed selections (role#variant@mode+tor) of run $1 (id or url) across every mode, plus its never-deployed priority entries, reproducing every other input of that run; force-cancels the run first so it stops holding runner slots alias i8cifo='__i8cifo(){ [ -z "${1:-}" ] && { echo "usage: i8cifo " >&2; return 2; }; ghaf "$1" || echo "i8cifo: force-cancel of run $1 reported nothing to cancel; continuing" >&2; infinito administration deploy ci trigger --failed --strict --run "$1"; }; __i8cifo' # like i8cifail but only hard-failed selections, excluding cancelled/aborted; force-cancels the run first alias i8cire='__i8cire(){ make quality && gips && i8cifail "$1"; }; __i8cire' alias i8co='m compose-deploy' alias i8co2='m console' +alias i8coape='m compose-app-exec' alias i8codo='m compose-down' alias i8cone='m compose-entity-purge' alias i8coni='m compose-inner-run' alias i8conire='m compose-inventory-refresh' alias i8copa='m compose-playwright' +alias i8copal='m compose-app-logs' +alias i8copare='m compose-app-restart' alias i8copu='m compose-up' alias i8core='m compose-restart' alias i8cos='m cosmos' @@ -40,6 +46,7 @@ alias i8dofo='m dotenv-force' alias i8fi='m fix-chmod' alias i8fido='m fix-dockerignore' alias i8he='m help' +alias i8inma='m integration-matrix' alias i8kelo='m kernel-loop-load' alias i8la='m alias' alias i8li='m lint' @@ -69,6 +76,7 @@ alias i8mativas='i8mativ -s' # variant with symbols alias i8mativaso='clear && i8maal' # clear + deploy matrix of every deployable variant, in CI query order alias i8matiw='i8matis --sort "desc weight"' # complexity matrix, symbols, heaviest roles first alias i8matix='infinito meta roles applications complexity' # deploy matrix / complexity overview +alias i8mcau='m mcp-audit' alias i8me='m meta-list' alias i8memi='m meta-mig' alias i8mete='m meta-tree' diff --git a/ansible.cfg b/ansible.cfg index b2c5c1ba3c..62be0232c0 100644 --- a/ansible.cfg +++ b/ansible.cfg @@ -25,6 +25,9 @@ lookup_plugins = ./plugins/lookup library = ./library module_utils = ./utils +[callback_profile_tasks] +task_output_limit = 300 + [ssh_connection] ssh_args = -o ControlMaster=auto -o ControlPersist=20s -o ControlPath=~/.ssh/ansible-%h-%p-%r -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o StrictHostKeyChecking=accept-new -o PreferredAuthentications=publickey,password,keyboard-interactive pipelining = True diff --git a/cli/administration/deploy/ci/runs.py b/cli/administration/deploy/ci/runs.py index ca038f8656..553ff712e6 100644 --- a/cli/administration/deploy/ci/runs.py +++ b/cli/administration/deploy/ci/runs.py @@ -46,12 +46,15 @@ ENTRY_WORKFLOW = ".github/workflows/entry-manual-steer.yml" SELECTION_INPUTS = ("priority", "offset") """The two inputs a retrigger decides itself rather than carrying over. -``priority`` IS the retrigger: it names what failed. ``offset`` follows from -it -- the source run already has a verdict for everything up to where its -budget ran out, so the regular line resumes behind that window -(:func:`resume_offset`) instead of repeating it. Everything else is carried -verbatim, including ``whitelist``, so a retrigger of a scoped run stays inside -that scope instead of quietly widening to the whole repository.""" +``priority`` IS the retrigger: it names what failed. ``offset`` is recomputed +rather than carried, but from the carried value up: the source run got a +stretch behind its own offset green before its budget ran out, so the regular +line resumes behind that stretch +(:func:`cli.administration.deploy.ci.selections.resume_offset`) instead of +repeating it, and never falls back behind where that run started. Everything +else is carried verbatim, including ``whitelist``, so a retrigger of a scoped +run stays inside that scope instead of quietly widening to the whole +repository.""" def dispatch_inputs() -> tuple[str, ...]: @@ -84,7 +87,6 @@ CONFIG_INPUTS = ( "filesystem", "chunk_gate", "workspace", - "instructions", ) LOG_INPUTS = ("tor",) @@ -370,7 +372,31 @@ def config_from_title(title: str) -> dict[str, str]: return {name: recorded[name] for name in CONFIG_INPUTS if name in recorded} -def config_from_run(title: str, logged: dict[str, str] | None = None) -> dict[str, str]: +SUITE_JOB_IDS = {"workspace": "test-workspace"} + + +def suite_passed(jobs: list[dict], suite: str) -> bool: + """Whether every job of ``suite`` ('workspace') completed successfully. + + Only a clean sweep of successes retires the suite. A shard that failed, + was cancelled, timed out or skipped did not run through, and a run that + holds no job for the suite at all never started it -- none of those is + evidence the suite is good, so the retrigger keeps asking for it. + """ + job_id = SUITE_JOB_IDS[suite] + outcomes = [ + _effective(job) + for job in jobs + if job_id in str(job.get("name", "")).split(" / ")[1:] + ] + return bool(outcomes) and all(outcome == "success" for outcome in outcomes) + + +def config_from_run( + title: str, + logged: dict[str, str] | None = None, + jobs: list[dict] | None = None, +) -> dict[str, str]: """Every input the source run was dispatched with, except the selection. The job log is the source: it records all inputs verbatim, including the @@ -381,16 +407,32 @@ def config_from_run(title: str, logged: dict[str, str] | None = None) -> dict[st so the retrigger leaves it on that same default rather than pinning today's default into a run that never asked for it. + A suite is turned off only when every job of it came back green; one that + failed, was cancelled or never ran at all keeps it on the retrigger, so a + retrigger spends its runners on what is not yet proven. + + What the source asked for does not enter that decision: the run's own jobs + are the evidence. A suite reached on the ``auto`` default is the common + case -- ``call-orchestrator.yml`` reads ``auto`` as global scope off the + ``whitelist`` alone, so a ``--failed`` retrigger, which puts its selection + on ``priority`` and leaves the whitelist empty, would run every green + suite again for as long as the retrigger chain lasts. + Args: title: the source run's display title. logged: inputs read verbatim from a called job's log (:func:`inputs_from_jobs`). + jobs: the source run's jobs, which record the suites it already + passed (:func:`suite_passed`). """ recorded = run_name.values_from_title(title) config = { name: (logged or {}).get(name) or recorded.get(name, "") for name in carried_inputs() } + for suite in SUITE_JOB_IDS: + if suite_passed(jobs or [], suite): + config = {**config, suite: "false"} return {name: value for name, value in config.items() if value} diff --git a/cli/administration/deploy/ci/selections.py b/cli/administration/deploy/ci/selections.py index d41adc6515..d841e31d71 100644 --- a/cli/administration/deploy/ci/selections.py +++ b/cli/administration/deploy/ci/selections.py @@ -17,8 +17,14 @@ stopped, instead of aggregating to role ids and guessing the rest. from __future__ import annotations +from typing import TYPE_CHECKING + from utils.github.variant import axes, selection +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping + from typing import Any + from .runs import _effective, _iter_deploy_jobs @@ -63,74 +69,187 @@ def failed_selections(jobs: list[dict], *, strict: bool = False) -> list[str]: return sorted(tokens) -def deployed_selections(jobs: list[dict]) -> set[str]: - """Every selection the source run actually deployed, green or red. +def collapse_to_roles(tokens: Iterable[str]) -> list[str]: + """The same selections with every axis dropped, one entry per role. - The verdict is irrelevant here: what matters is that the run reached the - row at all, because that is what a retrigger no longer has to repeat. + :func:`failed_selections` reproduces the combination that broke, which is + what a handful of red rows deserves. Once most of the ranking is red the + question is no longer which combination broke but whether the role comes up + at all, and a token per combination spends the priority budget proving the + same role red twice. The role name lets the rotation pick the axes. + + What this gives up is the guarantee the pinned form exists for: the + combination that failed may not be among the ones the retrigger draws. + + Args: + tokens: selection tokens, as :func:`failed_selections` returns them. + + Returns: + sorted, deduplicated role ids. """ - return { - selection.describe( + return sorted({selection.parse(token).app for token in tokens}) + + +def _variants(entry: Mapping[str, Any]) -> tuple[int, ...]: + """The variant shards one matrix row covers.""" + return tuple(int(part) for part in str(entry.get("variant", "")).split(",") if part) + + +def row_identity(entry: Mapping[str, Any]) -> str: + """One matrix row as the ``role#variant`` the sweep rotation cannot move. + + Args: + entry: a row of :func:`cli.meta.ci.matrix.entries_of`. + """ + return selection.describe(selection.Pin(entry["apps"], _variants(entry))) + + +def proven_rows(jobs: list[dict]) -> set[str]: + """The rows the source run proved, as ``role#variant``, axes dropped. + + Mode, onion state, distro and filesystem are assigned by the rotation over + the sweep number, and a retrigger is a new run with a new number + (``call-orchestrator.yml`` falls back to ``github.run_number``). Comparing + the full deploy tokens therefore compares two different sweeps: measured + against the current ranking, 2 of 277 rows matched, so every walk stopped + on its first row and the regular line never left the head. The row is the + coarsest identity the rotation cannot move. + + Dropping the axes does not mean forgiving them. A row is proven only when + *every* job it had was green: one red or aborted combination un-proves it, + however many green siblings it has. Only a priority row can have several, + since it deploys its whole cross-product at once while a regular row gets + one combination per sweep -- and letting a green compose job carry a red + swarm one would walk the regular line past a combination nobody fixed. + + Args: + jobs: the source run's jobs. + """ + green: set[str] = set() + broken: set[str] = set() + for app, _mode, job in _iter_deploy_jobs(jobs): + label = axes.parse_label(str(job.get("name", ""))) + if label is None: + continue + row = selection.describe( selection.Pin( - app, - tuple(int(part) for part in label.variant.split(",") if part), - label.mode, - label.tor, - label.distro or None, + app, tuple(int(part) for part in label.variant.split(",") if part) ) ) - for app, _mode, job in _iter_deploy_jobs(jobs) - if (label := axes.parse_label(str(job.get("name", "")))) is not None - } + (green if _effective(job) == "success" else broken).add(row) + return green - broken -def resume_offset(regular: list[dict[str, str]], deployed: set[str]) -> str: - """Where a retrigger should pick the regular line up again. +def carried_index(regular: list[dict[str, str]], carried: str, proven: set[str]) -> int: + """Where in *regular* the source run began reading. - The source run deployed a window of the ranking and stopped at its budget. - Everything inside that window has a verdict -- the red rows come back on - the priority line anyway -- so the regular line has no reason to walk it a - second time. The answer is the last row of the leading run of deployed - rows, as a selection token: a token still names the same row after the - ranking shifts, a row count does not. + A retrigger inherits the window its source was given: the rows in front of + that window were proven by the runs before it, and re-walking them from the + head would redeploy a green stretch that nobody doubts. The source run's + own ``offset`` input is that window's start. - Stops at the first gap. A hole inside the window means that row was - filtered out, not that the run got further, and resuming past it would skip - whatever follows. + The token can name a row this ranking no longer has -- the role was + removed, a variant was dropped, the filters moved. The start is then the + first row the source run got green, which lies inside the same window and + so never falls behind it. A run with nothing green and an unresolvable + token leaves no anchor at all and starts at the head. Args: regular: the regular line of the retrigger's own discovery, in ranking order. - deployed: tokens the source run deployed (:func:`deployed_selections`). + carried: the source run's ``offset`` input, a token or a row count. + proven: the rows the source run got green (:func:`proven_rows`). + + Returns: + the index to start reading at; ``0`` when the source run was given no + offset. + """ + if not carried: + return 0 + if carried.lstrip("+-").isdigit(): + return max(int(carried), 0) + pin = selection.parse(carried) + for index, entry in enumerate(regular): + if selection.covers(pin, entry): + return index + for index, entry in enumerate(regular): + if row_identity(entry) in proven: + return index + return 0 + + +def resume_offset( + regular: list[dict[str, str]], + proven: set[str], + leading: Iterable[selection.Pin] = (), + carried: str = "", +) -> str: + """Where a retrigger should pick the regular line up again. + + The source run read a window of the ranking, starting where *carried* put + it (:func:`carried_index`) and stopping at its budget. Only the green part + of that window is newly settled, so the answer is the last row of the + leading run of *successful* rows behind the window's start, as a selection + token -- a token still names the same row after the ranking shifts, a row + count does not. + + The window's start is the floor: with nothing green behind it the answer is + the start itself, never the head. Walking back to the head is what made + every retrigger redeploy the whole stretch its predecessors had already + proven. + + Stops at the first row that is not proven, whether or not the priority line + claims it, and one red combination is enough to un-prove a row + (:func:`proven_rows`). Resuming past it would drop every other combination + of that row and everything the run never reached behind it. + + A row the priority line claims is never the answer. ``regular`` is + discovered without the priority line (see the retrigger's ``_ranking``), so + it still holds rows the run will hand to that line instead + (:func:`cli.meta.ci.matrix.candidates`): a variant-less pin takes its whole + role, a pinned one takes those variants. Naming such a row would emit an + offset that resolves against nothing once the run applies the priority + line, and abort the discovery of every chunk. + + Args: + regular: the regular line of the retrigger's own discovery, in ranking + order. + proven: the rows the source run got green in every combination it ran + them in (:func:`proven_rows`). + leading: the retrigger's priority pins, whose rows leave the regular + line. + carried: the source run's own ``offset`` input. Returns: the ``role#variant`` token to resume at, or ``''`` when the source run - deployed nothing of this line -- then the retrigger starts at the head, - as it would without an offset. + started at the head and got nothing skippable of this line green -- + then the retrigger starts at the head too, as it would without an + offset. - The returned token names a place in the ranking, so it carries no axes. - Membership is still tested on the full deploy token, because that is - what the source run recorded; but every axis rotates with the sweep - number, and the retrigger gets a fresh one. An axis-pinned offset would - therefore resolve only in the rare sweep whose rotation happens to - reproduce the source run's combination, and abort the discovery of - every chunk in all the others. + The returned token names a place in the ranking, so it carries no axes, + and neither does the membership test behind it (:func:`proven_rows`): + the source run recorded its combinations under its own sweep number and + the retrigger gets a fresh one, so comparing them row by row is the only + comparison that survives the rotation. """ - resume = "" - for entry in regular: - variants = tuple( - int(part) for part in str(entry.get("variant", "")).split(",") if part - ) - deployment = selection.describe( - selection.Pin( - entry["apps"], - variants, - entry["mode"], - entry["tor"] == "true", - entry["distro"], - ) - ) - if deployment not in deployed: + pins = tuple(leading) + claimed_apps = {pin.app for pin in pins if not pin.variants} + claimed_rows = {(pin.app, variant) for pin in pins for variant in pin.variants} + + def free(entry: Mapping[str, Any]) -> str: + app = entry["apps"] + variants = _variants(entry) + if app in claimed_apps or any((app, v) in claimed_rows for v in variants): + return "" + return row_identity(entry) + + start = carried_index(regular, carried, proven) + window = regular[start:] + resume = next((token for entry in window if (token := free(entry))), "") + if not start: + resume = "" + for entry in window: + if row_identity(entry) not in proven: break - resume = selection.describe(selection.Pin(entry["apps"], variants)) + resume = free(entry) or resume return resume diff --git a/cli/administration/deploy/ci/trigger/__main__.py b/cli/administration/deploy/ci/trigger/__main__.py index 88295a383d..d419af43ec 100644 --- a/cli/administration/deploy/ci/trigger/__main__.py +++ b/cli/administration/deploy/ci/trigger/__main__.py @@ -8,7 +8,9 @@ every other dispatch input is carried over (:func:`runs.carried_inputs`, read off the workflow itself), and the priority line names the exact selections that failed -- role, variant, deploy mode, onion state and distro -- rather than the roles they belong to. The filesystem is left to the rotation -(:mod:`cli.administration.deploy.ci.selections` says why). +(:mod:`cli.administration.deploy.ci.selections` says why). ``--chunk-gate`` is +the one deliberate exception: it overrides the carried value so a retrigger can +keep deploying past a failed chunk. """ from __future__ import annotations @@ -18,7 +20,8 @@ import sys from cli.administration.deploy.ci import gh, runs, selections from cli.meta.ci import matrix, query -from utils.github.variant import pools, tor +from utils.github import run_name +from utils.github.variant import pools, selection, tor _WORKFLOW = "entry-manual-steer.yml" _ALL = "__ALL__" @@ -32,20 +35,14 @@ def _fetch(run: str, repo: str) -> dict: return gh.fetch_run(gh.run_id_from_url(run), repo=gh.slug_from_url(run)) -def _resume_offset(source: dict, whitelist: str, config: dict[str, str]) -> str: - """Where the retrigger's regular line should start. - - The source run walked the ranking until its budget ran out. Those rows - have a verdict already -- and the red ones return on the priority line -- - so the regular line resumes behind them instead of redeploying the same - window. The ranking is recomputed under the retrigger's own configuration, - because that is the list the offset will be resolved against. +def _ranking(whitelist: str, config: dict[str, str]) -> list[dict[str, str]]: + """The regular line the retrigger's own discovery would walk. The priority line is deliberately left out of that computation: it only blacklists rows from the regular query, and a token in it that no longer resolves would abort here, in a helper whose job is to save runner time. """ - entries = matrix.entries_of( + return matrix.entries_of( modes=query.resolve_modes(config.get("mode") or query.ALL_MODES), whitelist="" if whitelist == _ALL else whitelist, priority="", @@ -55,9 +52,6 @@ def _resume_offset(source: dict, whitelist: str, config: dict[str, str]) -> str: distros=pools.resolve_distros(config.get("distros")), filesystems=pools.resolve_filesystems(config.get("filesystem")), ) - return selections.resume_offset( - entries, selections.deployed_selections(source["jobs"]) - ) def main(argv: list[str] | None = None) -> int: @@ -82,10 +76,12 @@ def main(argv: list[str] | None = None) -> int: help=( "Re-trigger what was not green in the source run as the priority " "line, together with the priority entries that run never deployed " - "at all; the remaining roles follow once they succeed. Every mode " - "is read, and each failed job comes back as the exact selection " - "that failed -- variant, deploy mode and onion state included. A " - "leftover scope argument is accepted and ignored." + "at all; the remaining roles follow once they succeed, starting " + "behind the green stretch the run added to the offset it was " + "given. Every mode is read, and each failed job comes back as the " + "exact selection that failed -- variant, deploy mode and onion " + "state included. A leftover scope argument is accepted and " + "ignored." ), ) group.add_argument( @@ -112,12 +108,40 @@ def main(argv: list[str] | None = None) -> int: action="store_true", help=( "With --failed: re-trigger only roles with a hard failure (โŒ), " - "not cancelled/aborted (๐Ÿšซ) or still-running (โณ)." + "not cancelled/aborted (๐Ÿšซ) or still-running (โณ). Those two never " + "reached a verdict, so the regular line owes them their turn " + "rather than the priority line owing them a place." + ), + ) + p.add_argument( + "--roles-only", + action="store_true", + help=( + "With --failed: put the failed roles on the priority line by name, " + "letting the rotation assign the axes, instead of replaying the " + "exact combination each job failed in. Useful when so much is red " + "that covering the role matters more than reproducing the row. " + "Priority entries the source run never deployed keep their pins " + "either way -- that run holds no evidence against the axes they " + "named." + ), + ) + p.add_argument( + "--chunk-gate", + choices=("true", "false"), + default=None, + help=( + "Override the carried chunk_gate input. 'false' keeps deploying " + "the remaining chunks after a failed one instead of stopping the " + "chain; 'true' stops at the first failed chunk. Omitted: the " + "source run's value, else the workflow default." ), ) args = p.parse_args(argv) if args.strict and args.failed is None: p.error("--strict only applies with --failed") + if args.roles_only and args.failed is None: + p.error("--roles-only only applies with --failed") branch = gh.current_branch() repo = gh.resolve_repo() @@ -137,6 +161,7 @@ def main(argv: list[str] | None = None) -> int: whitelist = "" priority = "" + priority_entries: set[str] = set() if args.apps is not None: apps = " ".join(args.apps.split()) if not apps: @@ -145,6 +170,8 @@ def main(argv: list[str] | None = None) -> int: elif args.failed is not None: statuses = runs.parse_role_statuses(source["jobs"]) failed = selections.failed_selections(source["jobs"], strict=args.strict) + if args.roles_only: + failed = selections.collapse_to_roles(failed) untriggered = runs.untriggered_priority( runs.dispatched_priority(source, repo), statuses ) @@ -153,22 +180,35 @@ def main(argv: list[str] | None = None) -> int: return 0 if untriggered: print(f"Priority roles that never deployed: {' '.join(untriggered)}") - priority = " ".join(sorted(set(failed) | set(untriggered))) + priority_entries = set(failed) | set(untriggered) else: whitelist = _ALL config: dict[str, str] = {} + carried_offset = "" if source is not None: + logged = runs.inputs_from_jobs(source["jobs"], repo) config = runs.config_from_run( - source["displayTitle"], - runs.inputs_from_jobs(source["jobs"], repo), + source["displayTitle"], logged, jobs=source["jobs"] + ) + carried_offset = logged.get("offset") or run_name.value_from_title( + source["displayTitle"], "offset" ) carried_whitelist = config.pop("whitelist", "") if not whitelist and carried_whitelist: whitelist = carried_whitelist + if args.chunk_gate is not None: + config["chunk_gate"] = args.chunk_gate if args.failed is not None: - config["offset"] = _resume_offset(source, whitelist, config) + ranking = _ranking(whitelist, config) + priority = " ".join(sorted(priority_entries)) + config["offset"] = selections.resume_offset( + ranking, + selections.proven_rows(source["jobs"]), + selection.parse_list(priority), + carried=carried_offset, + ) if config["offset"]: print(f"Regular line resumes at: {config['offset']}") else: diff --git a/cli/administration/deploy/development/coredns.py b/cli/administration/deploy/development/coredns.py index 473d197478..d587daa3d6 100644 --- a/cli/administration/deploy/development/coredns.py +++ b/cli/administration/deploy/development/coredns.py @@ -2,31 +2,35 @@ from __future__ import annotations import itertools import os -import shutil -import subprocess +import re import tempfile from dataclasses import dataclass from pathlib import Path +from string import Template +from utils.cache.files import read_text from utils.env.parser import parse_static_env @dataclass(frozen=True) class CoreDNSCorefileRenderer: """ - Render compose/coredns/Corefile from compose/coredns/Corefile.tmpl using envsubst. + Render compose/coredns/Corefile from compose/coredns/Corefile.tmpl. What this does: - Reads variables from env file (default: .env, generated from default.env) - - Runs `envsubst` to substitute variables into the Corefile template + - Substitutes ``${VAR}`` placeholders into the Corefile template - Writes the output atomically (tmp -> rename) - Optionally prints a preview of the first N lines + Substitution runs in-process rather than through envsubst: the act runner and + the nested deploy containers do not all ship gettext, and a missing binary + turned a two-variable substitution into a failed deploy. + Hard guarantees: - Fails if template/env files are missing - Fails if output path exists and is a directory - Fails if output directory cannot be created or is not writable - - Fails if envsubst is missing - Fails if rendered file is empty """ @@ -50,15 +54,6 @@ class CoreDNSCorefileRenderer: if not path.is_file(): raise RuntimeError(f"{label} is not a file: {path}") - def _require_envsubst(self) -> str: - p = shutil.which("envsubst") - if not p: - raise RuntimeError( - "envsubst not found. Install gettext-base (Ubuntu/Debian) or gettext (Arch)." - ) - self._log(f"Using envsubst: {p}") - return p - def _ensure_output_parent(self, out_file: Path) -> None: parent = out_file.parent @@ -110,7 +105,6 @@ class CoreDNSCorefileRenderer: self._require_file(tmpl_file, label="template file") self._require_output_target(out_file) self._ensure_output_parent(out_file) - envsubst = self._require_envsubst() env = self._load_env_file(env_file) @@ -119,19 +113,13 @@ class CoreDNSCorefileRenderer: ) tmp_file = Path(tmp_name) - self._log("Rendering Corefile via envsubst (atomic write)") + self._log("Rendering Corefile (atomic write)") try: - with ( - tmpl_file.open("r", encoding="utf-8") as fin, - os.fdopen(fd, "w", encoding="utf-8") as fout, - ): - subprocess.check_call( - [envsubst], - stdin=fin, - stdout=fout, - env=env, - cwd=self.repo_root, - ) + rendered = Template(read_text(tmpl_file)).safe_substitute( + env, DOMAIN_RE=re.escape(env["INFINITO_DOMAIN"]) + ) + with os.fdopen(fd, "w", encoding="utf-8") as fout: + fout.write(rendered) size = tmp_file.stat().st_size if size == 0: diff --git a/cli/administration/deploy/development/deploy/__init__.py b/cli/administration/deploy/development/deploy/__init__.py index 4ee1facf40..d9b9fd495e 100644 --- a/cli/administration/deploy/development/deploy/__init__.py +++ b/cli/administration/deploy/development/deploy/__init__.py @@ -5,6 +5,7 @@ Internal layout (one module per responsibility): * :mod:`.run` โ€” :func:`_run_deploy`, one deploy pass inside the container * :mod:`.drill` โ€” :func:`_maybe_recover_drill`, backup/recover verification * :mod:`.purge` โ€” :func:`_purge_app_entities`, inter-round entity cleanup +* :mod:`.rotate` โ€” :func:`_rotate_credentials`, inter-pass credential rotation * :mod:`.cli` โ€” :func:`add_parser` + :func:`handler`, arg parsing and the round/pass orchestration loop diff --git a/cli/administration/deploy/development/deploy/cli.py b/cli/administration/deploy/development/deploy/cli.py index e040f19be1..40544f24a5 100644 --- a/cli/administration/deploy/development/deploy/cli.py +++ b/cli/administration/deploy/development/deploy/cli.py @@ -27,6 +27,7 @@ from cli.administration.inventory.provision.services_disabler import ( from .drill import _maybe_recover_drill from .purge import _purge_app_entities +from .rotate import _rotate_credentials from .run import _run_deploy @@ -194,6 +195,9 @@ def handler(args: argparse.Namespace) -> int: if bool(args.full_cycle): _maybe_recover_drill(compose, plan_index) + _rotate_credentials( + compose, inventory_dir=inv_dir, round_variants=round_variants + ) print(f"=== {pass_label} PASS 2 (async) ===") rc = run_pass( { diff --git a/cli/administration/deploy/development/deploy/rotate.py b/cli/administration/deploy/development/deploy/rotate.py new file mode 100644 index 0000000000..3d5e33911c --- /dev/null +++ b/cli/administration/deploy/development/deploy/rotate.py @@ -0,0 +1,50 @@ +"""Credential rotation between PASS 1 and PASS 2 of a matrix-deploy round.""" + +from __future__ import annotations + +import json +import os +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from cli.administration.deploy.development.compose import Compose + +ROTATION_EXEMPT = ("administrator",) + + +def _rotate_credentials( + compose: Compose, *, inventory_dir: str, round_variants: dict[str, int] +) -> None: + """Regenerate the round's inventory credentials before the async pass. + + Args: + compose: the development stack the inventory lives in. + inventory_dir: the round's inventory directory. + round_variants: variant index per app, as baked by `init`. + + PASS 2 otherwise reads the exact values PASS 1 wrote, so nothing in the + deploy ever has to propagate a changed secret. `administrator` stays + exempt: its password is `ansible_become_password`, and rotating it would + lock the deploy out of its own host. + """ + print("=== matrix-deploy: rotating credentials between passes ===") + compose.exec( + [ + "infinito", + "administration", + "inventory", + "credentials", + "reset", + "--inventory-dir", + inventory_dir, + "--schema", + "--users", + "--app-variants", + json.dumps(round_variants, sort_keys=True), + "--backup", + "--except", + *ROTATION_EXEMPT, + ], + check=True, + workdir=os.environ["INFINITO_SRC_DIR"], + ) diff --git a/cli/administration/deploy/development/init.py b/cli/administration/deploy/development/init.py index 6b69dd919b..de711ef911 100644 --- a/cli/administration/deploy/development/init.py +++ b/cli/administration/deploy/development/init.py @@ -175,9 +175,9 @@ def handler(args: argparse.Namespace) -> int: if len(plan) == 1: _, inv_dir, round_variants, include_R, _purge_set = plan[0] - non_zero = {a: i for a, i in round_variants.items() if i} - suffix = f" variants={non_zero}" if non_zero else "" shown = built_includes.get(inv_dir, include_R) + non_zero = {a: i for a, i in round_variants.items() if i and a in shown} + suffix = f" variants={non_zero}" if non_zero else "" print( f">>> Inventory initialized at {inv_dir} " f"(include={','.join(shown)} " @@ -189,8 +189,8 @@ def handler(args: argparse.Namespace) -> int: f"(primary_apps={','.join(primary_apps)}):" ) for round_index, inv_dir, round_variants, include_R, _purge_set in plan: - non_zero = {a: i for a, i in round_variants.items() if i} shown = built_includes.get(inv_dir, include_R) + non_zero = {a: i for a, i in round_variants.items() if i and a in shown} print( f" [round {round_index}] {inv_dir} " f"include={','.join(shown)} " diff --git a/cli/administration/deploy/development/inventory/legacy_resolver.py b/cli/administration/deploy/development/inventory/legacy_resolver.py index 1dff1fa170..5b70ba0698 100644 --- a/cli/administration/deploy/development/inventory/legacy_resolver.py +++ b/cli/administration/deploy/development/inventory/legacy_resolver.py @@ -20,6 +20,8 @@ from utils.cache.base import _deep_merge from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ROLE_FILE_META_SERVICES +from .nested_overrides import apply_topic, collect_provider_overrides + def _build_services_overrides_for_round( *, @@ -72,9 +74,30 @@ def _build_services_overrides_for_round( merged = _deep_merge(dict(base_services), dict(variant_services)) if isinstance(merged, dict): overrides[role_name] = merged + _apply_nested_service_maps(overrides, roles_dir=roles_dir) return overrides +def _apply_nested_service_maps(overrides: dict[str, dict], *, roles_dir: str) -> None: + """Replace a pulled-in provider's services map with what the round demands. + + Only the ``services`` topic reaches this path: the closure walks service + edges, so the other config topics a variant may override are the inventory + bake's business. + + Args: + overrides: ``{role: services map}``, mutated in place. + roles_dir: roles directory the service registry is built from. + """ + payloads = {role: {"services": services} for role, services in overrides.items()} + for provider, topics in collect_provider_overrides( + payloads, roles_dir=roles_dir + ).items(): + if "services" not in topics: + continue + overrides[provider] = apply_topic(overrides.get(provider), topics["services"]) + + def _resolve_round_include( *, primary_apps: Sequence[str], diff --git a/cli/administration/deploy/development/inventory/nested_overrides.py b/cli/administration/deploy/development/inventory/nested_overrides.py new file mode 100644 index 0000000000..b17a362b13 --- /dev/null +++ b/cli/administration/deploy/development/inventory/nested_overrides.py @@ -0,0 +1,90 @@ +"""Collect the provider config a round's variants dictate. + +The topic vocabulary and merge semantics live in +``utils.roles.applications.topics``; this module resolves which role demands +what, and refuses two roles demanding different things for one provider. + +Only a config topic counts, and only on an entry naming another role's +service. A role's own entity entry is skipped, which is what keeps the two +existing `services..users` / `services..domains` declarations from +being read as overrides. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +from utils.roles.applications.services.registry import ( + build_service_registry_from_roles_dir, +) +from utils.roles.applications.topics import CONFIG_TOPICS, apply_topic, provider_of + +__all__ = ["CONFIG_TOPICS", "NestedOverrideConflictError", "apply_topic"] + + +class NestedOverrideConflictError(RuntimeError): + """Two roles in one round demand different config for one provider.""" + + +def _claims(payloads: Mapping[str, Any]) -> list[tuple[str, str, str, Any]]: + """Return the ``(role, service_key, topic, value)`` a round's payloads carry. + + Args: + payloads: ``{role: variant payload}`` for one round. + + Reading this before the service registry keeps a round whose variants + override nothing from paying for the registry at all. + """ + claims: list[tuple[str, str, str, Any]] = [] + for role_name, payload in payloads.items(): + if not isinstance(payload, Mapping): + continue + services = payload.get("services") + if not isinstance(services, Mapping): + continue + for service_key, entry in services.items(): + if not isinstance(entry, Mapping): + continue + claims.extend( + (role_name, service_key, topic, entry[topic]) + for topic in sorted(CONFIG_TOPICS & set(entry)) + ) + return claims + + +def collect_provider_overrides( + payloads: Mapping[str, Any], *, roles_dir: str +) -> dict[str, dict[str, Any]]: + """Return ``{provider: {topic: value}}`` demanded by the round's payloads. + + Args: + payloads: ``{role: variant payload}`` for one round. + roles_dir: roles directory the service registry is built from. + + Raises: + NestedOverrideConflictError: two roles demand different values for the + same topic of the same provider. + """ + claims = _claims(payloads) + if not claims: + return {} + + registry = build_service_registry_from_roles_dir(Path(roles_dir)) + demanded: dict[str, dict[str, Any]] = {} + claimed_by: dict[tuple[str, str], str] = {} + for role_name, service_key, topic, value in claims: + provider = provider_of(service_key, registry) + if not provider or provider == role_name: + continue + previous = claimed_by.get((provider, topic)) + if previous and demanded[provider][topic] != value: + raise NestedOverrideConflictError( + f"{role_name} and {previous} demand different " + f"{topic!r} for {provider!r} in the same round; a " + f"round deploys it once, so the two cannot both hold" + ) + demanded.setdefault(provider, {})[topic] = value + claimed_by[(provider, topic)] = role_name + return demanded diff --git a/cli/administration/deploy/development/inventory/payload.py b/cli/administration/deploy/development/inventory/payload.py index 588decaec3..6421739441 100644 --- a/cli/administration/deploy/development/inventory/payload.py +++ b/cli/administration/deploy/development/inventory/payload.py @@ -15,6 +15,8 @@ from typing import Any from utils.cache.applications import get_variant_overrides_only +from .nested_overrides import apply_topic, collect_provider_overrides + def _resolve_variant_payloads( *, @@ -32,6 +34,10 @@ def _resolve_variant_payloads( Apps without `meta/variants.yml` collapse to a single empty override `{}`. Out-of-range indices clamp to 0. + + A config topic a variant declares under a service it depends on is + finally moved onto that service's provider, so the role pulling a + dependency in is what decides how lean the dependency runs. """ overrides_per_app = get_variant_overrides_only(roles_dir=roles_dir) resolved: dict[str, Any] = {} @@ -43,6 +49,16 @@ def _resolve_variant_payloads( if not 0 <= index < len(variant_list): index = 0 resolved[app_id] = variant_list[index] + for provider, topics in collect_provider_overrides( + resolved, roles_dir=roles_dir + ).items(): + if provider not in resolved: + continue + payload = resolved[provider] + payload = dict(payload) if isinstance(payload, Mapping) else {} + for topic, value in topics.items(): + payload[topic] = apply_topic(payload.get(topic), value) + resolved[provider] = payload return resolved diff --git a/cli/administration/deploy/development/inventory/planner.py b/cli/administration/deploy/development/inventory/planner.py index 8dcfdff18d..99e64a74c4 100644 --- a/cli/administration/deploy/development/inventory/planner.py +++ b/cli/administration/deploy/development/inventory/planner.py @@ -103,11 +103,10 @@ def plan_dev_inventory_matrix( round_include = per_variant_includes[round_index] round_variants = dict(primary_round_variants) - for dep in round_include: + for dep, dep_variants in variants_per_app.items(): if dep in round_variants: continue - dep_variants = variants_per_app.get(dep) or [{}] - dep_count = max(1, len(dep_variants)) + dep_count = max(1, len(dep_variants or [{}])) round_variants[dep] = round_index if round_index < dep_count else 0 inv_dir = f"{base}-{round_index}" if total_rounds > 1 else base diff --git a/cli/administration/inventory/credentials/reset/__init__.py b/cli/administration/inventory/credentials/reset/__init__.py new file mode 100644 index 0000000000..a9b50fb880 --- /dev/null +++ b/cli/administration/inventory/credentials/reset/__init__.py @@ -0,0 +1,5 @@ +from __future__ import annotations + +from .cli import main + +__all__ = ["main"] diff --git a/cli/administration/inventory/credentials/reset/__main__.py b/cli/administration/inventory/credentials/reset/__main__.py new file mode 100755 index 0000000000..3f63d30f07 --- /dev/null +++ b/cli/administration/inventory/credentials/reset/__main__.py @@ -0,0 +1,8 @@ +#!/usr/bin/env python3 + +from __future__ import annotations + +from .cli import main + +if __name__ == "__main__": # pragma: no cover + raise SystemExit(main()) diff --git a/cli/administration/inventory/credentials/reset/cli.py b/cli/administration/inventory/credentials/reset/cli.py new file mode 100644 index 0000000000..9287c30b65 --- /dev/null +++ b/cli/administration/inventory/credentials/reset/cli.py @@ -0,0 +1,212 @@ +"""Rotate the generated credentials of an inventory. + +Usage example:: + + infinito administration inventory credentials reset \\ + --inventory-dir /etc/inventories/local-full-server \\ + --schema --users --except administrator +""" + +from __future__ import annotations + +import argparse +import json +import shutil +from datetime import UTC, datetime +from pathlib import Path + +from cli.administration.inventory.provision.project import ( + build_env_with_project_root, + detect_project_root, +) +from cli.administration.inventory.provision.reset import reset_credentials +from cli.administration.inventory.provision.ruamel_io import load_document + + +def _parse_app_variants(raw: str | None) -> dict[str, int]: + if not raw: + return {} + try: + parsed = json.loads(raw) + except json.JSONDecodeError as exc: + raise SystemExit(f"--app-variants must be valid JSON: {exc}") from exc + if not isinstance(parsed, dict): + raise SystemExit("--app-variants must be a JSON object") + variants: dict[str, int] = {} + for application_id, index in parsed.items(): + try: + variants[str(application_id)] = int(index) + except (TypeError, ValueError) as exc: + raise SystemExit( + f"--app-variants[{application_id!r}] must be an integer, got {index!r}" + ) from exc + return variants + + +def _backup(host_vars_file: Path) -> Path: + """Copy ``host_vars_file`` next to itself, stamped with the current UTC time. + + Args: + host_vars_file: the file about to be rewritten. + + Returns: + The path of the copy. + + A rotation destroys the only record of what the previous pass deployed + with, which is exactly what a post-mortem needs. The `.backup` suffix + keeps the copy out of both the mirror glob and Ansible's host_vars + loading, which only reads YAML extensions. + """ + stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") + copy = host_vars_file.with_name(f"{host_vars_file.name}.{stamp}.backup") + shutil.copyfile(host_vars_file, copy) + return copy + + +def _mirror_host_vars(host_vars_dir: Path, source: Path) -> list[str]: + """Copy ``source`` over every other host_vars file in its directory. + + Args: + host_vars_dir: the inventory's ``host_vars`` directory. + source: the file the other hosts are aligned to. + + Returns: + The host names that were overwritten. + + A multi-host test inventory holds one file per node, all copies of the + manager's. Rotating only the manager's would hand every other node the + previous secrets. + """ + mirrored: list[str] = [] + for candidate in sorted(host_vars_dir.glob("*.yml")): + if candidate == source: + continue + shutil.copyfile(source, candidate) + mirrored.append(candidate.stem) + return mirrored + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description=( + "Drop the generated credentials of an inventory and regenerate them, " + "so the next deploy has to propagate a changed secret." + ) + ) + parser.add_argument( + "--inventory-dir", required=True, help="Inventory directory to rotate." + ) + parser.add_argument( + "--host", default="localhost", help="Host whose host_vars file is rotated." + ) + parser.add_argument( + "--vault-password-file", + default=None, + help="Vault password file. Default: /.password", + ) + parser.add_argument( + "--schema", + action="store_true", + help="Rotate applications..credentials.* (everything meta/secrets.yml generates).", + ) + parser.add_argument( + "--users", action="store_true", help="Rotate users..password." + ) + parser.add_argument( + "--except", + dest="exclude", + nargs="*", + default=[], + help="Application ids and user keys to leave untouched (e.g. administrator).", + ) + parser.add_argument( + "--include", + nargs="*", + default=None, + help=( + "Application ids whose credentials rotate. Absent rotates every " + "application block in the file, which on a matrix inventory is " + "every mirror artefact too, not just the ids the round " + "provisioned. User passwords ignore this and always rotate in " + "full." + ), + ) + parser.add_argument( + "--app-variants", + default=None, + help="JSON object {app_id: variant_index}, as passed to provision.", + ) + parser.add_argument( + "--mirror", + action="store_true", + help="Copy the rotated host_vars file over every other host in the inventory.", + ) + parser.add_argument( + "--backup", + action="store_true", + help="Keep the pre-rotation host_vars as .YYYYMMDDTHHMMSSZ.backup.", + ) + args = parser.parse_args(argv) + + if not args.schema and not args.users: + raise SystemExit("Nothing to rotate: pass --schema, --users, or both.") + + inventory_dir = Path(args.inventory_dir).resolve() + host_vars_file = inventory_dir / "host_vars" / f"{args.host}.yml" + if not host_vars_file.exists(): + raise SystemExit(f"No host_vars file to rotate: {host_vars_file}") + + vault_password_file = ( + Path(args.vault_password_file).resolve() + if args.vault_password_file + else inventory_dir / ".password" + ) + if not vault_password_file.exists(): + raise SystemExit(f"Vault password file not found: {vault_password_file}") + + project_root = detect_project_root(Path(__file__).resolve()) + env = build_env_with_project_root(project_root) + + document = load_document(host_vars_file) + applications = document.get("applications") or {} + application_ids = sorted(str(application_id) for application_id in applications) + if not application_ids: + raise SystemExit(f"No applications block to rotate in {host_vars_file}") + + credential_ids = None + if args.include is not None: + wanted = set(args.include) + credential_ids = [app_id for app_id in application_ids if app_id in wanted] + if not credential_ids: + raise SystemExit(f"--include matches no block in {host_vars_file}") + + if args.backup: + print(f"[INFO] Pre-rotation copy: {_backup(host_vars_file)}") + + exclude = set(args.exclude) + print( + f"[INFO] Rotating credentials in {host_vars_file} " + f"({len(credential_ids or application_ids)} applications, " + f"{len(application_ids)} for users, " + f"excluding {sorted(exclude) or 'nothing'})" + ) + rotated = reset_credentials( + application_ids=application_ids, + credential_ids=credential_ids, + roles_dir=(project_root / "roles").resolve(), + host_vars_file=host_vars_file, + vault_password_file=vault_password_file, + project_root=project_root, + env=env, + schema=args.schema, + users=args.users, + exclude=exclude, + app_variants=_parse_app_variants(args.app_variants), + ) + print(f"[INFO] Rotated {rotated} value(s)") + + if args.mirror: + mirrored = _mirror_host_vars(host_vars_file.parent, host_vars_file) + print(f"[INFO] Mirrored to {', '.join(mirrored) or 'no other host'}") + + return 0 diff --git a/cli/administration/inventory/provision/cli.py b/cli/administration/inventory/provision/cli.py index e92832d76a..05a8bfa4c6 100644 --- a/cli/administration/inventory/provision/cli.py +++ b/cli/administration/inventory/provision/cli.py @@ -21,6 +21,7 @@ from .passwords import generate_random_password from .project import build_env_with_project_root, detect_project_root from .services_disabler import apply_services_disabled_from_env from .tor_node import apply_tor_node_onion +from .users_generator import generate_user_passwords from .yaml_io import dump_yaml, load_yaml @@ -237,6 +238,18 @@ def main(argv: list[str] | None = None) -> int: become_password=args.become_password, ) + print( + f"[INFO] Pinning a password for every user the {len(application_ids)} " + "resolved applications declare..." + ) + pinned = generate_user_passwords( + roles_dir=roles_dir, + application_ids=application_ids, + host_vars_file=host_vars_file, + vault_password_file=vault_password_file, + ) + print(f"[INFO] Pinned {pinned} user password(s)") + app_variants: dict[str, int] = {} if args.app_variants: try: diff --git a/cli/administration/inventory/provision/credentials_generator.py b/cli/administration/inventory/provision/credentials_generator.py index c71484ad1c..b0a3a4f826 100644 --- a/cli/administration/inventory/provision/credentials_generator.py +++ b/cli/administration/inventory/provision/credentials_generator.py @@ -11,10 +11,10 @@ from ruamel.yaml.comments import CommentedMap from cli.administration.inventory.credentials.emit import ( credentials_map, declared_credentials, - ensure_map, ) from .role_resolver import resolve_role_path +from .ruamel_io import dump_document, ensure_map, load_document if TYPE_CHECKING: from pathlib import Path @@ -127,22 +127,7 @@ def generate_credentials_for_roles( if not snippets: return - yaml_rt = YAML(typ="rt") - yaml_rt.preserve_quotes = True - - if host_vars_file.exists(): - with host_vars_file.open("r", encoding="utf-8") as f: - doc = yaml_rt.load(f) - if doc is None: - doc = CommentedMap() - else: - doc = CommentedMap() - - if not isinstance(doc, CommentedMap): - tmp = CommentedMap() - for k, v in dict(doc).items(): - tmp[k] = v - doc = tmp + doc = load_document(host_vars_file) for snippet in snippets: apps_snip = snippet.get("applications", {}) or {} @@ -170,6 +155,4 @@ def generate_credentials_for_roles( ): doc["ansible_become_password"] = snippet["ansible_become_password"] - host_vars_file.parent.mkdir(parents=True, exist_ok=True) - with host_vars_file.open("w", encoding="utf-8") as f: - yaml_rt.dump(doc, f) + dump_document(host_vars_file, doc) diff --git a/cli/administration/inventory/provision/host_vars.py b/cli/administration/inventory/provision/host_vars.py index 20d1532d8c..550f51aa6e 100644 --- a/cli/administration/inventory/provision/host_vars.py +++ b/cli/administration/inventory/provision/host_vars.py @@ -4,13 +4,12 @@ import json import sys from typing import TYPE_CHECKING, Any -from ruamel.yaml import YAML from ruamel.yaml.comments import CommentedMap from utils.cache.yaml import load_yaml_any -from utils.handler.vault import VaultHandler from .passwords import generate_random_password +from .ruamel_io import dump_document, load_document, vault_value if TYPE_CHECKING: from pathlib import Path @@ -32,6 +31,12 @@ def _deep_update_commented_map(target: CommentedMap, updates: dict[str, Any]) -> target[key] = value +def _merge_into_host_vars(host_vars_file: Path, overrides: dict[str, Any]) -> None: + document = load_document(host_vars_file) + _deep_update_commented_map(document, overrides) + dump_document(host_vars_file, document) + + def apply_vars_overrides_from_file(host_vars_file: Path, vars_file: Path) -> None: if not vars_file.exists(): raise SystemExit(f"Vars file not found: {vars_file}") @@ -44,28 +49,7 @@ def apply_vars_overrides_from_file(host_vars_file: Path, vars_file: Path) -> Non if not isinstance(overrides, dict): raise SystemExit(f"Vars file must contain a mapping at top-level: {vars_file}") - yaml_rt = YAML(typ="rt") - yaml_rt.preserve_quotes = True - - if host_vars_file.exists(): - with host_vars_file.open("r", encoding="utf-8") as f: - doc = yaml_rt.load(f) - if doc is None: - doc = CommentedMap() - else: - doc = CommentedMap() - - if not isinstance(doc, CommentedMap): - tmp = CommentedMap() - for k, v in dict(doc).items(): - tmp[k] = v - doc = tmp - - _deep_update_commented_map(doc, overrides) - - host_vars_file.parent.mkdir(parents=True, exist_ok=True) - with host_vars_file.open("w", encoding="utf-8") as f: - yaml_rt.dump(doc, f) + _merge_into_host_vars(host_vars_file, overrides) def apply_vars_overrides(host_vars_file: Path, json_str: str) -> None: @@ -77,58 +61,20 @@ def apply_vars_overrides(host_vars_file: Path, json_str: str) -> None: if not isinstance(overrides, dict): raise SystemExit("JSON for --vars must be an object at the top level.") - yaml_rt = YAML(typ="rt") - yaml_rt.preserve_quotes = True - - if host_vars_file.exists(): - with host_vars_file.open("r", encoding="utf-8") as f: - doc = yaml_rt.load(f) - if doc is None: - doc = CommentedMap() - else: - doc = CommentedMap() - - if not isinstance(doc, CommentedMap): - tmp = CommentedMap() - for k, v in dict(doc).items(): - tmp[k] = v - doc = tmp - - _deep_update_commented_map(doc, overrides) - - host_vars_file.parent.mkdir(parents=True, exist_ok=True) - with host_vars_file.open("w", encoding="utf-8") as f: - yaml_rt.dump(doc, f) + _merge_into_host_vars(host_vars_file, overrides) def ensure_host_vars_file( host_vars_file: Path, host: str, ) -> None: - yaml_rt = YAML(typ="rt") - yaml_rt.preserve_quotes = True - - if host_vars_file.exists(): - with host_vars_file.open("r", encoding="utf-8") as f: - data = yaml_rt.load(f) - if data is None: - data = CommentedMap() - else: - data = CommentedMap() - - if not isinstance(data, CommentedMap): - tmp = CommentedMap() - for k, v in dict(data).items(): - tmp[k] = v - data = tmp + data = load_document(host_vars_file) local_hosts = {"localhost", "127.0.0.1", "::1"} if host in local_hosts and "ansible_connection" not in data: data["ansible_connection"] = "local" - host_vars_file.parent.mkdir(parents=True, exist_ok=True) - with host_vars_file.open("w", encoding="utf-8") as f: - yaml_rt.dump(data, f) + dump_document(host_vars_file, data) def ensure_become_password( @@ -136,47 +82,18 @@ def ensure_become_password( vault_password_file: Path, become_password: str | None, ) -> None: - yaml_rt = YAML(typ="rt") - yaml_rt.preserve_quotes = True + document = load_document(host_vars_file) - if host_vars_file.exists(): - with host_vars_file.open("r", encoding="utf-8") as f: - doc = yaml_rt.load(f) - if doc is None: - doc = CommentedMap() - else: - doc = CommentedMap() - - if not isinstance(doc, CommentedMap): - tmp = CommentedMap() - for k, v in dict(doc).items(): - tmp[k] = v - doc = tmp - - current_value = doc.get("ansible_become_password") - - if become_password is None and current_value is not None: + if become_password is None and document.get("ansible_become_password") is not None: return plain_password = ( become_password if become_password is not None else generate_random_password() ) - - handler = VaultHandler(str(vault_password_file)) - snippet_text = handler.encrypt_string(plain_password, "ansible_become_password") - - snippet_yaml = YAML(typ="rt") - encrypted_doc = snippet_yaml.load(snippet_text) or CommentedMap() - encrypted_value = encrypted_doc.get("ansible_become_password") - if encrypted_value is None: - raise SystemExit( - "Failed to parse 'ansible_become_password' from ansible-vault output." - ) - - doc["ansible_become_password"] = encrypted_value - host_vars_file.parent.mkdir(parents=True, exist_ok=True) - with host_vars_file.open("w", encoding="utf-8") as f: - yaml_rt.dump(doc, f) + document["ansible_become_password"] = vault_value( + vault_password_file, plain_password, "ansible_become_password" + ) + dump_document(host_vars_file, document) def _get_path_administrator_home_from_group_vars(project_root: Path) -> str: diff --git a/cli/administration/inventory/provision/mirror_overrides.py b/cli/administration/inventory/provision/mirror_overrides.py index 166e68feb6..fb59acacde 100644 --- a/cli/administration/inventory/provision/mirror_overrides.py +++ b/cli/administration/inventory/provision/mirror_overrides.py @@ -2,19 +2,14 @@ from __future__ import annotations from typing import TYPE_CHECKING -from ruamel.yaml import YAML -from ruamel.yaml.comments import CommentedMap - from utils.cache.yaml import load_yaml_any +from .ruamel_io import dump_document, ensure_map, load_document + if TYPE_CHECKING: from pathlib import Path - -def _ensure_ruamel_map(node: CommentedMap, key: str) -> CommentedMap: - if key not in node or not isinstance(node.get(key), CommentedMap): - node[key] = CommentedMap() - return node[key] + from ruamel.yaml.comments import CommentedMap def _is_blank(val: object) -> bool: @@ -67,27 +62,11 @@ def apply_mirror_overrides(host_vars_file: Path, mirrors_file: Path) -> None: if not has_applications: return - yaml_rt = YAML(typ="rt") - yaml_rt.preserve_quotes = True - - if host_vars_file.exists(): - with host_vars_file.open("r", encoding="utf-8") as f: - doc = yaml_rt.load(f) - if doc is None: - doc = CommentedMap() - else: - doc = CommentedMap() - - if not isinstance(doc, CommentedMap): - tmp = CommentedMap() - for k, v in dict(doc).items(): - tmp[k] = v - doc = tmp - + doc = load_document(host_vars_file) changed = False if has_applications: - apps_doc = _ensure_ruamel_map(doc, "applications") + apps_doc = ensure_map(doc, "applications") for app_id, app_block in mirrors_apps.items(): if not isinstance(app_block, dict): continue @@ -96,8 +75,8 @@ def apply_mirror_overrides(host_vars_file: Path, mirrors_file: Path) -> None: if not isinstance(services, dict): continue - app_doc = _ensure_ruamel_map(apps_doc, str(app_id)) - services_doc = _ensure_ruamel_map(app_doc, "services") + app_doc = ensure_map(apps_doc, str(app_id)) + services_doc = ensure_map(app_doc, "services") for svc_name, svc_block in services.items(): if not isinstance(svc_block, dict): @@ -114,7 +93,7 @@ def apply_mirror_overrides(host_vars_file: Path, mirrors_file: Path) -> None: image = image.strip() version = version.strip() - svc_doc = _ensure_ruamel_map(services_doc, str(svc_name)) + svc_doc = ensure_map(services_doc, str(svc_name)) policy = _get_policy(svc_doc) if policy == "skip": @@ -139,6 +118,4 @@ def apply_mirror_overrides(host_vars_file: Path, mirrors_file: Path) -> None: if not changed: return - host_vars_file.parent.mkdir(parents=True, exist_ok=True) - with host_vars_file.open("w", encoding="utf-8") as f: - yaml_rt.dump(doc, f) + dump_document(host_vars_file, doc) diff --git a/cli/administration/inventory/provision/passwords.py b/cli/administration/inventory/provision/passwords.py index e2c9a83f29..251c466b03 100644 --- a/cli/administration/inventory/provision/passwords.py +++ b/cli/administration/inventory/provision/passwords.py @@ -1,7 +1,69 @@ from __future__ import annotations +import re +import secrets +import string + from utils.manager.value_generator import ValueGenerator +USER_PASSWORD_LENGTH = 64 +DECLARED_PASSWORD_ATTEMPTS = 64 +SHELL_SAFE_MARKS = "-_." +_USER_PASSWORD_ALPHABET = string.ascii_letters + string.digits + SHELL_SAFE_MARKS +_USER_PASSWORD_RE = re.compile( + r"^[A-Za-z0-9](?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[-_.])[A-Za-z0-9._-]{15,}$" +) + def generate_random_password(length: int = 64) -> str: return ValueGenerator().generate_strong_password(length) + + +def generate_user_password(length: int = USER_PASSWORD_LENGTH) -> str: + """Return a shell-safe password for a declared user. + + Args: + length: characters to generate, at least 16. + + Returns: + letters, digits and the marks ``-_.``, never a leading ``-``, with one + of each class the Keycloak realm policy ``specialChars(1)`` counts. + """ + if length < 16: + raise ValueError("A user password must be at least 16 characters") + for _ in range(DECLARED_PASSWORD_ATTEMPTS): + body = [secrets.choice(_USER_PASSWORD_ALPHABET) for _ in range(length)] + body[0] = secrets.choice(string.ascii_letters + string.digits) + body[secrets.randbelow(length - 1) + 1] = secrets.choice(SHELL_SAFE_MARKS) + password = "".join(body) + if _USER_PASSWORD_RE.match(password): + return password + raise RuntimeError("Failed to generate a user password after many attempts") + + +def generate_declared_user_password(username, algorithm, validation): + """Return a password satisfying what the user's own declaration demands. + + Args: + username: the user the password belongs to, for the failure message. + algorithm: a ValueGenerator algorithm name, or None for the shell-safe + default every user gets when its declaration asks for nothing. + validation: a regular expression the value must match, or None. + + An application whose registration rejects the shell-safe alphabet states + that in its own meta/users.yml rather than carrying a second credential + beside the account it already owns. + """ + for _ in range(DECLARED_PASSWORD_ATTEMPTS): + value = ( + ValueGenerator().generate_value(algorithm) + if algorithm + else generate_user_password() + ) + if not validation or re.search(validation, value): + return value + raise SystemExit( + f"user {username!r}: {DECLARED_PASSWORD_ATTEMPTS} passwords from " + f"algorithm {algorithm or 'the shell-safe default'!r} all failed " + f"password_validation {validation!r}; the two cannot both hold" + ) diff --git a/cli/administration/inventory/provision/reset.py b/cli/administration/inventory/provision/reset.py new file mode 100644 index 0000000000..54e5bfba82 --- /dev/null +++ b/cli/administration/inventory/provision/reset.py @@ -0,0 +1,259 @@ +"""Rotate the credentials an inventory generated, so a redeploy has to carry them. + +Provisioning fills a missing credential and leaves an existing one alone. That +keeps a redeploy stable, and it also means no deploy ever runs against a secret +that moved: every pass reads the value the first pass wrote. Dropping the +generated values and regenerating them between two deploy passes turns the +second pass into a test of the update path, where each role has to push its new +secret into the application and the database it already created. +""" + +from __future__ import annotations + +import sys +from typing import TYPE_CHECKING + +from ruamel.yaml.comments import CommentedMap + +from cli.administration.inventory.credentials.vault import is_ruamel_vault +from utils.manager.credential_key import CREDENTIALS_KEY, SECRETS_KEY +from utils.roles.mapping import ROLE_FILE_META_SECRETS, ROLE_FILE_VARS_MAIN + +from .credentials_generator import generate_credentials_for_roles +from .ruamel_io import dump_document, load_document +from .users_generator import generate_user_passwords, required_user_policies + +if TYPE_CHECKING: + from pathlib import Path + + +ROTATABLE_KEY = "rotatable" + + +def _pinned_paths( + schema: CommentedMap, prefix: tuple[str, ...] +) -> set[tuple[str, ...]]: + """Return the credential paths ``schema`` marks ``rotatable: false``. + + Args: + schema: a ``credentials`` branch of a role's ``meta/secrets.yml``. + prefix: the path walked so far. + + Returns: + The pinned paths, each as a tuple of keys. + """ + pinned: set[tuple[str, ...]] = set() + for key, meta in schema.items(): + if not isinstance(meta, CommentedMap): + continue + if meta.get(ROTATABLE_KEY) is False: + pinned.add((*prefix, key)) + else: + pinned |= _pinned_paths(meta, (*prefix, key)) + return pinned + + +def _pinned_credentials(roles_dir: Path) -> dict[str, set[tuple[str, ...]]]: + """Map application id to the credentials its role refuses to have rotated. + + Args: + roles_dir: directory the roles live in. + + Returns: + Application id to the set of pinned credential paths. + """ + pinned: dict[str, set[tuple[str, ...]]] = {} + for role_dir in sorted(roles_dir.iterdir()): + schema = load_document(role_dir / ROLE_FILE_META_SECRETS).get(CREDENTIALS_KEY) + if not isinstance(schema, CommentedMap): + continue + paths = _pinned_paths(schema, ()) + if not paths: + continue + application_id = load_document(role_dir / ROLE_FILE_VARS_MAIN).get( + "application_id" + ) + if application_id: + pinned[str(application_id)] = paths + return pinned + + +def _drop_generated( + node: CommentedMap, pinned: set[tuple[str, ...]], prefix: tuple[str, ...] +) -> int: + """Remove every vault-encrypted leaf below ``node``. + + Args: + node: a ``credentials`` branch of the inventory. + pinned: paths the role marked ``rotatable: false``. + prefix: the path walked so far. + + Returns: + How many values were removed. + + A `plain` credential the operator supplies stays unencrypted in host_vars + (an empty string while it was never set), so restricting the drop to + vaulted leaves keeps operator input out of the rotation. + """ + dropped = 0 + for key in list(node.keys()): + path = (*prefix, key) + if path in pinned: + print( + f"[WARN] not rotated, pinned as rotatable: false: {'.'.join(path)}", + file=sys.stderr, + ) + continue + value = node.get(key) + if isinstance(value, CommentedMap): + dropped += _drop_generated(value, pinned, path) + elif is_ruamel_vault(value): + del node[key] + dropped += 1 + return dropped + + +def _drop_app_credentials( + document: CommentedMap, + exclude: set[str], + pinned: dict[str, set[tuple[str, ...]]], + application_ids: list[str], +) -> int: + """Remove the generated credentials of the applications being rotated. + + Args: + document: the host_vars document. + exclude: application ids to leave untouched. + pinned: per-application credential paths that must survive a rotation. + application_ids: the ids the caller regenerates afterwards. Passing a + narrower set here than the caller regenerates would drop + credentials nothing writes back. + + Returns: + How many values were removed. + """ + applications = document.get("applications") + if not isinstance(applications, CommentedMap): + return 0 + + rotated = set(application_ids) + dropped = 0 + for application_id, application in applications.items(): + if application_id in exclude or not isinstance(application, CommentedMap): + continue + if str(application_id) not in rotated: + continue + secrets = application.get(SECRETS_KEY) + if not isinstance(secrets, CommentedMap): + continue + credentials = secrets.get(CREDENTIALS_KEY) + if isinstance(credentials, CommentedMap): + dropped += _drop_generated( + credentials, pinned.get(str(application_id), set()), () + ) + return dropped + + +def _drop_user_passwords( + document: CommentedMap, + roles_dir: Path, + application_ids: list[str], + exclude: set[str], +) -> int: + """Remove the pinned password of every user the resolved roles declare. + + Args: + document: the host_vars document. + roles_dir: directory the roles live in. + application_ids: the roles resolved into this inventory. + exclude: user keys to leave untouched. + + Returns: + How many passwords were removed. + + Only declared users are dropped, because only those get a new password + pinned afterwards; a user that exists solely in the inventory would lose + its password with nothing to put it back. + """ + users = document.get("users") + if not isinstance(users, CommentedMap): + return 0 + + dropped = 0 + for username in required_user_policies(roles_dir, application_ids): + if username in exclude: + continue + user = users.get(username) + if isinstance(user, CommentedMap) and user.pop("password", None) is not None: + dropped += 1 + return dropped + + +def reset_credentials( + application_ids: list[str], + roles_dir: Path, + host_vars_file: Path, + vault_password_file: Path, + project_root: Path, + env: dict[str, str] | None, + schema: bool, + users: bool, + exclude: set[str], + workers: int = 4, + app_variants: dict[str, int] | None = None, + credential_ids: list[str] | None = None, +) -> int: + """Replace every generated credential in ``host_vars_file`` with a fresh one. + + Args: + application_ids: the roles resolved into this inventory. + roles_dir: directory the roles live in. + host_vars_file: inventory file the credentials are rewritten in. + vault_password_file: vault password used to encrypt each value. + project_root: repository root the role resolver works from. + env: environment the credential subprocesses inherit. + schema: rotate ``applications..credentials.*``. + users: rotate ``users..password``. + exclude: application ids and user keys to leave untouched. + workers: worker threads for credentials generation. + app_variants: variant index per app, as at provision time. + credential_ids: application ids whose credentials rotate; ``None`` + rotates all of ``application_ids``. User passwords ignore it and + always resolve through the full ``application_ids``. + + Returns: + How many values were rotated. + """ + if not schema and not users: + raise SystemExit("reset_credentials: pick at least one of schema, users") + + rotated_ids = application_ids if credential_ids is None else credential_ids + document = load_document(host_vars_file) + dropped = 0 + if schema: + dropped += _drop_app_credentials( + document, exclude, _pinned_credentials(roles_dir), rotated_ids + ) + if users: + dropped += _drop_user_passwords(document, roles_dir, application_ids, exclude) + dump_document(host_vars_file, document) + + if schema: + generate_credentials_for_roles( + application_ids=rotated_ids, + roles_dir=roles_dir, + host_vars_file=host_vars_file, + vault_password_file=vault_password_file, + project_root=project_root, + env=env, + workers=workers, + app_variants=app_variants, + ) + if users: + generate_user_passwords( + roles_dir=roles_dir, + application_ids=application_ids, + host_vars_file=host_vars_file, + vault_password_file=vault_password_file, + ) + return dropped diff --git a/cli/administration/inventory/provision/role_resolver.py b/cli/administration/inventory/provision/role_resolver.py index 0afe5d21e1..85f7cad928 100644 --- a/cli/administration/inventory/provision/role_resolver.py +++ b/cli/administration/inventory/provision/role_resolver.py @@ -3,6 +3,8 @@ from __future__ import annotations import sys from pathlib import Path +from cli.meta.roles.applications.role_name import EXIT_NO_SUCH_APPLICATION_ROLE + from .subprocess_runner import run_subprocess @@ -20,6 +22,8 @@ def resolve_role_path( - bare folder name (e.g. web-app-nextcloud) - relative path (e.g. roles/web-app-nextcloud) - absolute path + + Returns None when the id belongs to no application role. """ cmd = [ sys.executable, @@ -29,7 +33,14 @@ def resolve_role_path( "-r", str(roles_dir), ] - result = run_subprocess(cmd, capture_output=True, env=env) + result = run_subprocess( + cmd, + capture_output=True, + env=env, + ok_returncodes=(0, EXIT_NO_SUCH_APPLICATION_ROLE), + ) + if result.returncode == EXIT_NO_SUCH_APPLICATION_ROLE: + return None raw = (result.stdout or "").strip() if not raw: diff --git a/cli/administration/inventory/provision/ruamel_io.py b/cli/administration/inventory/provision/ruamel_io.py new file mode 100644 index 0000000000..5e3b82c0c3 --- /dev/null +++ b/cli/administration/inventory/provision/ruamel_io.py @@ -0,0 +1,95 @@ +"""Round-trip YAML access for the inventory files this package rewrites. + +The counterpart to :mod:`yaml_io`, which reads values. Everything here keeps +comments, quoting and vault tags intact, because host_vars is hand-edited as +often as it is generated. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from ruamel.yaml import YAML +from ruamel.yaml.comments import CommentedMap + +from utils.handler.vault import VaultHandler + +if TYPE_CHECKING: + from pathlib import Path + + +def round_trip_yaml() -> YAML: + """Return a YAML handler configured the way every writer here needs it.""" + handler = YAML(typ="rt") + handler.preserve_quotes = True + return handler + + +def as_commented_map(data: Any) -> CommentedMap: + """Return ``data`` as a CommentedMap, empty when it holds no mapping. + + Args: + data: whatever a round-trip load returned. + """ + if isinstance(data, CommentedMap): + return data + if data is None: + return CommentedMap() + migrated = CommentedMap() + for key, value in dict(data).items(): + migrated[key] = value + return migrated + + +def load_document(path: Path) -> CommentedMap: + """Return the round-trip document at ``path``, empty when it does not exist. + + Args: + path: the YAML file to read. + """ + if not path.exists(): + return CommentedMap() + with path.open("r", encoding="utf-8") as handle: + return as_commented_map(round_trip_yaml().load(handle)) + + +def dump_document(path: Path, document: CommentedMap) -> None: + """Write ``document`` to ``path``, creating the parent directory. + + Args: + path: the YAML file to write. + document: the round-trip document to serialise. + """ + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8") as handle: + round_trip_yaml().dump(document, handle) + + +def ensure_map(node: CommentedMap, key: str) -> CommentedMap: + """Return ``node[key]`` as a CommentedMap, creating it when absent. + + Args: + node: the parent mapping. + key: the child key to resolve. + """ + if key not in node or not isinstance(node.get(key), CommentedMap): + node[key] = CommentedMap() + return node[key] + + +def vault_value(vault_password_file: Path | str, plain: str, name: str) -> Any: + """Return ``plain`` as a parsed ``!vault`` node ready to assign. + + Args: + vault_password_file: vault password used to encrypt. + plain: the secret to encrypt. + name: the key ansible-vault names the snippet after. + + ansible-vault emits a YAML snippet rather than a value, so the encrypted + node has to be read back out of it before it can be assigned anywhere. + """ + snippet = VaultHandler(str(vault_password_file)).encrypt_string(plain, name) + encrypted = as_commented_map(round_trip_yaml().load(snippet)).get(name) + if encrypted is None: + raise SystemExit(f"Failed to parse {name!r} from ansible-vault output.") + return encrypted diff --git a/cli/administration/inventory/provision/services_disabler.py b/cli/administration/inventory/provision/services_disabler.py index 7f01e59260..33b4ac0cb1 100644 --- a/cli/administration/inventory/provision/services_disabler.py +++ b/cli/administration/inventory/provision/services_disabler.py @@ -86,6 +86,21 @@ def find_roles_with_service(service_name: str, roles_dir: Path) -> set[str]: return role_ids +def _declared_toggles(app_id: str, svc_name: str, roles_dir: Path) -> list[str]: + """The toggles this role's contract carries for this service, in file order. + + `compare_application_keys` rejects any host_vars key the role contract does + not declare, so writing a toggle the role never had turns a `disable=` run + into an inventory the validator refuses. 34 service blocks declare + `enabled` without `shared`. + """ + services = _load_yaml_mapping_tolerant(roles_dir / app_id / ROLE_FILE_META_SERVICES) + entry = services.get(svc_name) if services else None + if not isinstance(entry, dict): + return [] + return [flag for flag in ("enabled", "shared") if flag in entry] + + def find_provider_roles(services: list[str], roles_dir: Path) -> dict[str, str]: """ Return mapping of service_name -> application_id for the provider role of each @@ -204,17 +219,19 @@ def apply_services_disabled( svc_map = CommentedMap() app_data["services"] = svc_map + flags = _declared_toggles(app_id, svc_name, roles_dir) + if not flags: + continue + svc = svc_map.get(svc_name) if not isinstance(svc, CommentedMap): svc = CommentedMap() svc_map[svc_name] = svc - svc["enabled"] = False - svc["shared"] = False + for flag in flags: + svc[flag] = False changed = True - print( - f"[INFO] disable: {app_id}.services.{svc_name} " - "โ†’ enabled=false, shared=false" - ) + written = ", ".join(f"{flag}=false" for flag in flags) + print(f"[INFO] disable: {app_id}.services.{svc_name} โ†’ {written}") if changed: with host_vars_file.open("w", encoding="utf-8") as f: diff --git a/cli/administration/inventory/provision/subprocess_runner.py b/cli/administration/inventory/provision/subprocess_runner.py index 5df3e53408..02416141b0 100644 --- a/cli/administration/inventory/provision/subprocess_runner.py +++ b/cli/administration/inventory/provision/subprocess_runner.py @@ -7,10 +7,11 @@ def run_subprocess( cmd: list[str], capture_output: bool = False, env: dict[str, str] | None = None, + ok_returncodes: tuple[int, ...] = (0,), ) -> subprocess.CompletedProcess: """ Run a subprocess command and either stream output or capture it. - Raise SystemExit on non-zero return code. + Raise SystemExit on a return code outside `ok_returncodes`. """ if capture_output: result = subprocess.run( @@ -19,7 +20,7 @@ def run_subprocess( else: result = subprocess.run(cmd, text=True, env=env, check=False) - if result.returncode != 0: + if result.returncode not in ok_returncodes: msg = f"Command failed: {' '.join(str(c) for c in cmd)}\n" if capture_output: msg += f"STDOUT:\n{result.stdout}\nSTDERR:\n{result.stderr}\n" diff --git a/cli/administration/inventory/provision/users_generator.py b/cli/administration/inventory/provision/users_generator.py new file mode 100644 index 0000000000..07f557ecb6 --- /dev/null +++ b/cli/administration/inventory/provision/users_generator.py @@ -0,0 +1,118 @@ +"""Pin a password on every user the resolved role set needs. + +A user definition that declares no password falls back to +``{{ 42 | strong_password }}``. That is a template, not a value: it is +re-rendered at every use site, so the task that creates an account and the +task that later authenticates as it read two different secrets. Inventory +creation is where the value gets decided once, next to the role credentials +that are already generated there. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_USERS + +from .passwords import generate_declared_user_password +from .ruamel_io import dump_document, ensure_map, load_document, vault_value + +if TYPE_CHECKING: + from pathlib import Path + + +def required_user_policies( + roles_dir: Path, application_ids: list[str] +) -> dict[str, dict[str, str | None]]: + """Return every declared username with the password policy it asks for. + + Args: + roles_dir: directory the roles live in. + application_ids: the roles resolved into this inventory. + + A role that declares no users contributes none, so the result follows the + deployment rather than everything the repository could ever deploy. Two + roles sharing a user must agree on its policy: the account is one thing, so + silently picking one declaration would hand the other role a password its + application rejects. + """ + policies: dict[str, dict[str, str | None]] = {} + sources: dict[str, Path] = {} + for application_id in application_ids: + users_file = roles_dir / application_id / ROLE_FILE_META_USERS + if not users_file.exists(): + continue + declared = load_yaml_any(users_file) + if not isinstance(declared, dict): + continue + for username, overrides in declared.items(): + if not isinstance(overrides, dict): + raise SystemExit( + f"Invalid definition for user {username!r} in {users_file}" + ) + name = str(username) + declared = overrides.get("password") + policy = ( + { + "algorithm": declared.get("algorithm"), + "validation": declared.get("validation"), + } + if isinstance(declared, dict) + else {"algorithm": None, "validation": None} + ) + known = policies.get(name) + if known is not None and known != policy and any(policy.values()): + raise SystemExit( + f"user {name!r} carries conflicting password policies: " + f"{sources[name]} asks for {known}, {users_file} for {policy}" + ) + if known is None or any(policy.values()): + policies[name] = policy + sources[name] = users_file + return dict(sorted(policies.items())) + + +def generate_user_passwords( + roles_dir: Path, + application_ids: list[str], + host_vars_file: Path, + vault_password_file: Path, +) -> int: + """Write a vaulted password for every required user that has none yet. + + Args: + roles_dir: directory the roles live in. + application_ids: the roles resolved into this inventory. + host_vars_file: inventory file the passwords are written into. + vault_password_file: vault password used to encrypt each value. + + Returns: + How many users received a freshly generated password. + """ + policies = required_user_policies(roles_dir, application_ids) + if not policies: + return 0 + + document = load_document(host_vars_file) + users_doc = ensure_map(document, "users") + + generated = 0 + for username, policy in policies.items(): + user_doc = ensure_map(users_doc, username) + if user_doc.get("password"): + continue + user_doc["password"] = vault_value( + vault_password_file, + generate_declared_user_password( + username, policy["algorithm"], policy["validation"] + ), + f"{username}_password", + ) + generated += 1 + + if generated == 0: + return 0 + + dump_document(host_vars_file, document) + return generated diff --git a/cli/administration/recover/__main__.py b/cli/administration/recover/__main__.py index e19785e4dc..ae6c5720c7 100644 --- a/cli/administration/recover/__main__.py +++ b/cli/administration/recover/__main__.py @@ -147,6 +147,7 @@ def main(argv: list[str] | None = None) -> int: ) except ValueError as exc: parser.error(str(exc)) + return 2 return _local(cmd, args.target, args.preview) diff --git a/cli/build/README.md b/cli/build/README.md index b28e1281a2..ad238b6c56 100644 --- a/cli/build/README.md +++ b/cli/build/README.md @@ -1,14 +1,3 @@ # Build ๐Ÿ—๏ธ -Build-time generators that materialise role include lists, dependency graphs, and tree visualisations from the role metadata in `roles/`. - -## `readme` - -`python -m cli.build.readme [roles...] [--override] [--update-cosmos] [--check]` generates or completes role `README.md` files from `templates/roles/README.md.j2` (the section schema single source of truth). It derives the `## Cosmos` mermaid diagram from `meta/services.yml`, the `## Quick Setup` commands from the role id, and the `## Credits` block from `meta/main.yml`. Prose sections are never rewritten. - -- default: add only the managed sections that are missing. -- `--override`: regenerate every managed section in place. -- `--update-cosmos`: regenerate only the Cosmos diagram. -- `--check`: write nothing; exit non-zero if any README would change. - -Make wrappers: `make readme-generate [role=] [override=true] [cosmos=true]` and `make readme-check`. +Build-time generators that materialise role include lists, dependency graphs, tree visualisations, and documentation pages from the role metadata in `roles/`. Nothing here talks to a running deployment; every command reads the repository and writes an artefact back into it. diff --git a/cli/build/docs/README.md b/cli/build/docs/README.md new file mode 100644 index 0000000000..68d621de48 --- /dev/null +++ b/cli/build/docs/README.md @@ -0,0 +1,3 @@ +# Documentation Generators ๐Ÿ“ + +Generators that render pages committed under `docs/`. Each one reads role metadata, renders a single page, and writes it back into the documentation tree, so `docs/` holds only the rendered result and never the code that produces it. A lint fails when a generated page drifts from a fresh run, so every page here is regenerated through its own make target rather than edited by hand. diff --git a/cli/build/docs/__init__.py b/cli/build/docs/__init__.py new file mode 100644 index 0000000000..bfdb1cdab1 --- /dev/null +++ b/cli/build/docs/__init__.py @@ -0,0 +1,5 @@ +"""Generators that render documentation into ``docs/``. + +Each subpackage owns one generated page and runs through its own make target; +``docs/`` itself holds only the rendered result. +""" diff --git a/cli/build/docs/integration_matrix/__init__.py b/cli/build/docs/integration_matrix/__init__.py new file mode 100644 index 0000000000..1d48518cec --- /dev/null +++ b/cli/build/docs/integration_matrix/__init__.py @@ -0,0 +1,12 @@ +"""Compatibility wrapper. + +The implementation lives in ``cli/build/docs/integration_matrix/__main__.py``; +this package re-exports its public API so ``from +cli.build.docs.integration_matrix import ...`` works. +""" + +from __future__ import annotations + +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] diff --git a/docs/requirements/027-integration-matrix.gen.py b/cli/build/docs/integration_matrix/__main__.py similarity index 93% rename from docs/requirements/027-integration-matrix.gen.py rename to cli/build/docs/integration_matrix/__main__.py index 4aa9bf986e..316c2c001b 100755 --- a/docs/requirements/027-integration-matrix.gen.py +++ b/cli/build/docs/integration_matrix/__main__.py @@ -13,13 +13,17 @@ in the COLUMN role: - dash -> diagonal (same role) """ -# nocheck: file-size โ€” curated EDGES data table plus matrix renderers; the data +# nocheck: file-size curated EDGES data table plus matrix renderers; the data and the renderer read together, splitting them only adds indirection. import re -from pathlib import Path -# nocheck: project-root-import โ€” standalone docs generator, no package container to import PROJECT_ROOT from. -ROLES_DIR = Path(__file__).resolve().parent.parent.parent / "roles" +from utils.cache.files import read_text +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +ROLES_DIR = PROJECT_ROOT / "roles" +REPORT = PROJECT_ROOT / "docs" / "requirements" / "027-integration-matrix.md" FRAMEWORK = { "sso": "keycloak", @@ -34,6 +38,7 @@ FRAMEWORK = { "collabora": "collabora", "onlyoffice": "onlyoffice", "libretranslate": "libretranslate", + "litellm": "litellm", } WEB_APP = [ @@ -67,6 +72,7 @@ WEB_APP = [ "kix", "lam", "listmonk", + "litellm", "littlejs", "magento", "mailu", @@ -80,6 +86,7 @@ WEB_APP = [ "mini-qr", "mobilizon", "moodle", + "n8n", "navigator", "nextcloud", "odoo", @@ -228,7 +235,7 @@ EDGES = [ ( "mattermost", "keycloak", - "https://docs.mattermost.com/onboard/sso-saml.html", + "https://docs.mattermost.com/administration-guide/onboard/sso-saml.html", "coin", ), ( @@ -539,12 +546,11 @@ def scan_framework_edges(): """Derive infinito-native integration edges from each role's meta/services.yml.""" edges = [] for prefix in ("web-app-", "web-svc-"): - for path in sorted(ROLES_DIR.glob(prefix + "*/meta/services.yml")): + for path in sorted(ROLES_DIR.glob(f"{prefix}*/{ROLE_FILE_META_SERVICES}")): role = path.parent.parent.name entity = role[len(prefix) :] - try: - lines = path.read_text(encoding="utf-8").splitlines() - except OSError: + lines = read_text(str(path)).splitlines() + if not lines: continue seen = set() for line in lines: @@ -555,7 +561,7 @@ def scan_framework_edges(): target = FRAMEWORK.get(key) if target and target != entity and target not in seen: seen.add(target) - rel = f"../../roles/{role}/meta/services.yml" + rel = f"../../roles/{role}/{ROLE_FILE_META_SERVICES}" edges.append((entity, target, rel, "wired")) return edges @@ -596,7 +602,7 @@ def build(): HEADER = """# 027 - Integration Matrix -> Generated by [027-integration-matrix.gen.py](027-integration-matrix.gen.py). Do not edit by hand โ€” edit the generator's `EDGES` map and re-run. +> Generated by `make integration-matrix`. Do not edit by hand, edit the generator's `EDGES` map and re-run. Companion artifact for [026-unified-addon-syntax.md](026-unified-addon-syntax.md). Axes are the **entity names** of every `web-app-*` and `web-svc-*` role. @@ -615,7 +621,7 @@ A cell marks whether the **row** role ships an addon/plugin that wires in the ** Notes: - The matrix is **directional**: the row hosts the plugin/flag. Bidirectional pairs (e.g. `nextcloud`โ†”`openproject`) carry a symbol in both cells, each linking to that side. -- {wired} edges are derived automatically by scanning every role's `meta/services.yml` for integration service keys (`sso`โ†’keycloak, `matomo`โ†’matomo, `prometheus`โ†’prometheus, `email`โ†’mailu, `dashboard`, `css`, `logout`, `cdn`, `coturn`, `collabora`, `onlyoffice`, `libretranslate`). `ldap`/`redis`/`mariadb` map to `svc-db-*` roles that are off these axes and are not shown. +- {wired} edges are derived automatically by scanning every role's `meta/services.yml` for integration service keys (`sso`โ†’keycloak, `matomo`โ†’matomo, `prometheus`โ†’prometheus, `email`โ†’mailu, `dashboard`, `css`, `logout`, `cdn`, `coturn`, `collabora`, `onlyoffice`, `libretranslate`, `litellm`). `ldap`/`redis`/`mariadb` map to `svc-db-*` roles that are off these axes and are not shown. The `litellm` column is the AI gateway surface of [036](036-native-ai-gateway-integration.md): the service key resolves to `svc-ai-litellm`, which is off-axis, so the edge is drawn to the `litellm` entity that fronts it. - `โ†’ keycloak` {wired} cells are the central `sso` service; a {check}/{coin} on `โ†’ keycloak` instead means a role-local OIDC/SAML addon path beyond the central service. - Native ActivityPub federation between fediverse roles (`mastodon`, `peertube`, `pixelfed`, `funkwhale`, `mobilizon`, `bookwyrm`, `socialhome`) needs **no plugin** and is therefore not a {check} edge unless an installable connector exists. @@ -634,7 +640,7 @@ def main(): out = HEADER.format( check=CHECK, wired=WIRED, coin=COIN, cross=CROSS, dash=DASH, matrix=build() ) - path = Path(__file__).resolve().parent / "027-integration-matrix.md" + path = REPORT path.write_text(out, encoding="utf-8") print( f"wrote {path} ({len(ENTITIES)}x{len(ENTITIES)} matrix, " diff --git a/docs/requirements/integration_matrix_data.py b/cli/build/docs/integration_matrix/data.py similarity index 99% rename from docs/requirements/integration_matrix_data.py rename to cli/build/docs/integration_matrix/data.py index ef6a92c8df..497df6d86a 100644 --- a/docs/requirements/integration_matrix_data.py +++ b/cli/build/docs/integration_matrix/data.py @@ -224,7 +224,7 @@ EDGES: list[tuple[str, str, str, str]] = [ ( "mattermost", "keycloak", - "https://docs.mattermost.com/onboard/sso-saml.html", + "https://docs.mattermost.com/administration-guide/onboard/sso-saml.html", "coin", ), ( diff --git a/cli/build/docs/mcp_audit/__init__.py b/cli/build/docs/mcp_audit/__init__.py new file mode 100644 index 0000000000..759a8bda3b --- /dev/null +++ b/cli/build/docs/mcp_audit/__init__.py @@ -0,0 +1,12 @@ +"""Compatibility wrapper. + +The implementation lives in ``cli/build/docs/mcp_audit/__main__.py``; this +package re-exports its public API so ``from cli.build.docs.mcp_audit import +...`` works. +""" + +from __future__ import annotations + +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] diff --git a/cli/build/docs/mcp_audit/__main__.py b/cli/build/docs/mcp_audit/__main__.py new file mode 100755 index 0000000000..cbb3af4a70 --- /dev/null +++ b/cli/build/docs/mcp_audit/__main__.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Generate the operational MCP audit report. + +The metadata stays where it belongs: each role owns its ``meta/mcp.yml``, and +nothing here writes back into a role. This script only reads that metadata and +renders the one table a reviewer needs to answer "what does this surface +actually expose, as whom, to whom" without opening twenty-four files. + +Run ``make mcp-audit`` and commit the result; a lint fails when the committed +report differs from a fresh generation, so the table cannot drift away from the +roles the way the hand-maintained disposition lists once did. +""" + +from utils.cache.yaml import load_yaml_any +from utils.roles.applications.mcp import derive_allowed_consumers +from utils.roles.mapping import ROLE_FILE_META_MCP, ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +REPO_ROOT = PROJECT_ROOT +ROLES_DIR = REPO_ROOT / "roles" +REPORT = ( + REPO_ROOT / "docs/contributing/design/role/services/mcp/audit.md" +) + +COLUMNS = ( + "role", + "version", + "source", + "transport", + "auth", + "subject", + "scope", + "tools", + "implementation", + "consumers", + "blocker", +) + +EMPTY = "โ€”" + + +def _load(path): + data = load_yaml_any(str(path), default_if_missing={}) + return data if isinstance(data, dict) else {} + + +def _deployed_version(role_dir): + """Return the version of the role's own container, or EMPTY.""" + services = _load(role_dir / ROLE_FILE_META_SERVICES) + entity = role_dir.name.rsplit("-", 1)[-1] + for name, service in services.items(): + if not isinstance(service, dict): + continue + if name == entity and service.get("version"): + return str(service["version"]) + return EMPTY + + +def _version(role_dir): + """Return the version the role deploys the surface at.""" + return _cell(_deployed_version(role_dir)) + + +def _scope(tools): + """Return the read/write posture as one token.""" + if not isinstance(tools, dict): + return EMPTY + if tools.get("mutating_tools_enabled"): + return "read-write" + return "read-only" if tools.get("read_only_default") else EMPTY + + +def _subject(mcp): + """Return the declared subject together with the principal it resolves to.""" + subject = str(mcp.get("auth_subject") or "").strip() + owner = str((mcp.get("credential") or {}).get("owner") or "").strip() + if subject and owner: + return f"{subject} (`{owner}`)" + return subject or owner or EMPTY + + +def _join(values): + if not isinstance(values, list) or not values: + return EMPTY + return ", ".join(f"`{v}`" for v in values) + + +def _cell(value): + text = str(value or "").strip() + return text.replace("|", r"\|") if text else EMPTY + + +def _services_by_role(): + return { + role_dir.name: _load(role_dir / ROLE_FILE_META_SERVICES) + for role_dir in sorted(ROLES_DIR.iterdir()) + if role_dir.is_dir() + } + + +def rows(): + """Yield one report row per role that owns MCP metadata.""" + services_by_role = _services_by_role() + for mcp_path in sorted(ROLES_DIR.glob(f"*/{ROLE_FILE_META_MCP}")): + role_dir = mcp_path.parent.parent + mcp = _load(mcp_path) + tools = mcp.get("tools") + consumers = ( + derive_allowed_consumers(role_dir.name, services_by_role) + if mcp.get("direction") in ("server", "both") + else [] + ) + yield { + "role": f"`{role_dir.name}`", + "version": _version(role_dir), + "source": f"[link]({mcp['source_url']})" + if mcp.get("source_url") + else EMPTY, + "transport": _cell(mcp.get("transport")), + "auth": _cell(mcp.get("auth")), + "subject": _subject(mcp), + "scope": _scope(tools), + "tools": ( + str(len(tools["allowlist"])) + if isinstance(tools, dict) and isinstance(tools.get("allowlist"), list) + else EMPTY + ), + "implementation": _cell(mcp.get("implementation")), + "consumers": _join(consumers), + "blocker": _cell(mcp.get("reason")), + } + + +def render(): + """Return the full report as markdown.""" + lines = [ + "# 035 - MCP Audit Report", + "", + "Generated by `make mcp-audit`; do not edit by hand.", + "Run that script from the repository root and commit the result.", + "", + "One row per role that owns `meta/mcp.yml`. The disposition of every other", + "role lives in the audit lists of the MCP proxy-expansion requirement.", + "", + "`version` is the version the role deploys, read from its own `meta/services.yml`,", + "not the version the MCP surface was verified against.", + "`tools` counts the allowlist entries; the names themselves stay in the role.", + "", + "| " + " | ".join(COLUMNS) + " |", + "|" + "|".join(" --- " for _ in COLUMNS) + "|", + ] + lines.extend("| " + " | ".join(row[c] for c in COLUMNS) + " |" for row in rows()) + lines.append("") + return "\n".join(lines) + + +if __name__ == "__main__": + REPORT.write_text(render(), encoding="utf-8") + print(f"wrote {REPORT.relative_to(REPO_ROOT)}") diff --git a/cli/build/readme/__init__.py b/cli/build/docs/readme/__init__.py similarity index 66% rename from cli/build/readme/__init__.py rename to cli/build/docs/readme/__init__.py index e136cfc0db..96930f560c 100644 --- a/cli/build/readme/__init__.py +++ b/cli/build/docs/readme/__init__.py @@ -1,9 +1,9 @@ """Role README schema, section parsing, Cosmos derivation, and generation. ``templates/roles/README.md.j2.tmpl`` is the single source of truth for the -role-README structure. :mod:`cli.build.readme.schema` derives the +role-README structure. :mod:`cli.build.docs.readme.schema` derives the required/optional section set from it; the lint (``tests/lint/ansible/roles/test_readme.py``) and the generator -(``python -m cli.build.readme``) both consume that same schema so the +(``python -m cli.build.docs.readme``) both consume that same schema so the three never drift. """ diff --git a/cli/build/readme/__main__.py b/cli/build/docs/readme/__main__.py similarity index 94% rename from cli/build/readme/__main__.py rename to cli/build/docs/readme/__main__.py index 0bdaddd619..167169e86b 100755 --- a/cli/build/readme/__main__.py +++ b/cli/build/docs/readme/__main__.py @@ -2,7 +2,7 @@ """Generate or complete role README.md files from the schema template. Usage: - python -m cli.build.readme [roles...] [--override] [--check] [--roles-dir DIR] + python -m cli.build.docs.readme [roles...] [--override] [--check] [--roles-dir DIR] With no role names every role directory is processed. ``--override`` regenerates the managed sections (Cosmos, Quick Setup, Credits) even when @@ -17,7 +17,7 @@ from __future__ import annotations import argparse from pathlib import Path -from cli.build.readme.generate import MANAGED_SECTIONS, generate_readme, role_dirs +from cli.build.docs.readme.generate import MANAGED_SECTIONS, generate_readme, role_dirs from utils.cache.files import PROJECT_ROOT from utils.roles.mapping import ROLE_FILE_README diff --git a/cli/build/readme/cosmos.py b/cli/build/docs/readme/cosmos.py similarity index 100% rename from cli/build/readme/cosmos.py rename to cli/build/docs/readme/cosmos.py diff --git a/cli/build/readme/generate.py b/cli/build/docs/readme/generate.py similarity index 88% rename from cli/build/readme/generate.py rename to cli/build/docs/readme/generate.py index cc26fa6ca2..201362567f 100644 --- a/cli/build/readme/generate.py +++ b/cli/build/docs/readme/generate.py @@ -23,11 +23,12 @@ from __future__ import annotations import jinja2 -from cli.build.readme import schema -from cli.build.readme.cosmos import derive_cosmos_mermaid -from cli.build.readme.sections import Readme, parse_readme +from cli.build.docs.readme import schema +from cli.build.docs.readme.cosmos import derive_cosmos_mermaid +from cli.build.docs.readme.sections import Readme, parse_readme from utils.cache.files import PROJECT_ROOT, read_text from utils.cache.yaml import load_yaml +from utils.roles.credits import author_urls from utils.roles.deploy import role_has_stack from utils.roles.entity.name import get_entity_name from utils.roles.mapping import ROLE_FILE_META_MAIN, ROLE_FILE_README @@ -69,6 +70,19 @@ def _app_name(preamble: str, role_name: str) -> str: return entity.replace("-", " ").title() +def _needs_clearnet_resolver(role_dir) -> bool: + """Whether the role refuses to deploy without ``networks.internet.dns``. + + Only the inventories under ``inventories/development/`` set that value, so a + role asserting it has to name it in the block an operator copies, or the + documented deploy aborts on the assert. + """ + return any( + "networks.internet.dns" in read_text(str(path)) + for path in sorted((role_dir / "tasks").rglob("*.yml")) + ) + + def _base_context(role_dir, role_name: str, app_name: str, *, invokable: bool) -> dict: return { "application_id": role_name, @@ -81,7 +95,9 @@ def _base_context(role_dir, role_name: str, app_name: str, *, invokable: bool) - {"name": "Feature", "description": "Describe a capability."} ], "application_author": _role_author(role_dir), + "application_author_url": author_urls().get(_role_author(role_dir)), "application_is_host": not role_has_stack(role_dir), + "application_needs_clearnet_resolver": _needs_clearnet_resolver(role_dir), "cosmos_mermaid": derive_cosmos_mermaid(role_dir, role_name), "cosmos_legend": _cosmos_legend(), } diff --git a/cli/build/readme/overview.py b/cli/build/docs/readme/overview.py similarity index 98% rename from cli/build/readme/overview.py rename to cli/build/docs/readme/overview.py index bdce04308e..1c37145e11 100644 --- a/cli/build/readme/overview.py +++ b/cli/build/docs/readme/overview.py @@ -1,7 +1,7 @@ """Generate the invokable-role overview table in the repository README. Usage: - python -m cli.build.readme.overview [--check] [--readme PATH] [--roles-dir DIR] + python -m cli.build.docs.readme.overview [--check] [--readme PATH] [--roles-dir DIR] The table lives in its own ``## Roles Overview ๐Ÿงฉ`` section directly above ``## Use it online ๐Ÿš€`` in the root README.md and is fully regenerated on every diff --git a/cli/build/readme/schema.py b/cli/build/docs/readme/schema.py similarity index 98% rename from cli/build/readme/schema.py rename to cli/build/docs/readme/schema.py index 5cd0eda767..dc66b8ea89 100644 --- a/cli/build/readme/schema.py +++ b/cli/build/docs/readme/schema.py @@ -14,7 +14,7 @@ import functools import jinja2 -from cli.build.readme.sections import h2_titles +from cli.build.docs.readme.sections import h2_titles from utils.cache.files import PROJECT_ROOT TEMPLATE_DIR = PROJECT_ROOT / "templates" / "roles" diff --git a/cli/build/readme/sections.py b/cli/build/docs/readme/sections.py similarity index 100% rename from cli/build/readme/sections.py rename to cli/build/docs/readme/sections.py diff --git a/cli/contributing/update/collection_source/__init__.py b/cli/contributing/update/collection_source/__init__.py new file mode 100644 index 0000000000..ab2c0b6137 --- /dev/null +++ b/cli/contributing/update/collection_source/__init__.py @@ -0,0 +1,5 @@ +"""CLI entry point package for retuning the preferred collection source.""" + +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] diff --git a/cli/contributing/update/collection_source/__main__.py b/cli/contributing/update/collection_source/__main__.py new file mode 100755 index 0000000000..f0ffb7694e --- /dev/null +++ b/cli/contributing/update/collection_source/__main__.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import re +import subprocess +import sys +import time +from pathlib import Path +from tempfile import TemporaryDirectory + +from utils.update.collection_source import ( + RATIO, + SOURCES, + WINDOW, + append_sample, + decide, + load_history, +) + +from . import PROJECT_ROOT + +SETTING = "INFINITO_ANSIBLE_COLLECTIONS_SOURCE" +REQUIREMENTS = { + "galaxy": Path("requirements/requirements.galaxy.yml"), + "git": Path("requirements/requirements.git.yml"), +} + + +def read_preferred(env_file: Path) -> str: + """The source currently tried first, as declared in default.env. + + Args: + env_file: the default.env holding the setting. + """ + match = re.search( + rf"^{SETTING}=(\S+)\s*$", + env_file.read_text( + encoding="utf-8" + ), # nocheck: cache-read -- write_preferred rewrites this file in the same run + re.MULTILINE, + ) + if match is None: + raise SystemExit(f"{SETTING} is not declared in {env_file}") + return match.group(1) + + +def write_preferred(env_file: Path, source: str) -> None: + """Point the setting at SOURCE. + + Args: + env_file: the default.env holding the setting. + source: the source to try first from now on. + """ + text = env_file.read_text( + encoding="utf-8" + ) # nocheck: cache-read -- rewritten on the next line + env_file.write_text( + re.sub(rf"^{SETTING}=\S+$", f"{SETTING}={source}", text, flags=re.MULTILINE), + encoding="utf-8", + ) + + +def measure(repo_root: Path, requirements: Path, timeout: int) -> float | None: + """Seconds a cold install from REQUIREMENTS takes, or None when it fails. + + Args: + repo_root: repository root the requirements path is relative to. + requirements: the requirements file to install from. + timeout: seconds after which the install counts as failed. + """ + with TemporaryDirectory() as target: + started = time.monotonic() + try: + completed = subprocess.run( + [ + sys.executable, + "-m", + "ansible.cli.galaxy", + "collection", + "install", + "-r", + str(repo_root / requirements), + "-p", + target, + "--force-with-deps", + ], + capture_output=True, + text=True, + timeout=timeout, + check=False, + ) + except subprocess.TimeoutExpired: + return None + elapsed = time.monotonic() - started + return elapsed if completed.returncode == 0 else None + + +def main() -> int: + parser = argparse.ArgumentParser( + description=( + "Time both collection sources, record the sample, and retune the " + "preferred default when one source is durably slower." + ) + ) + parser.add_argument("--repo-root", type=Path, default=PROJECT_ROOT) + parser.add_argument( + "--history", + type=Path, + default=None, + help="JSON file holding the rolling window of samples", + ) + parser.add_argument( + "--timeout", + type=int, + default=900, + help="Seconds after which one install counts as failed", + ) + args = parser.parse_args() + + repo_root = args.repo_root.resolve() + env_file = repo_root / "default.env" + history_file = ( + args.history or repo_root / "build" / "collection-source-history.json" + ) + + sample: dict[str, float | None] = {} + for source in SOURCES: + seconds = measure(repo_root, REQUIREMENTS[source], args.timeout) + sample[source] = seconds + print(f"{source}: {'failed' if seconds is None else f'{seconds:.1f}s'}") + + history = append_sample(load_history(history_file), sample) + history_file.parent.mkdir(parents=True, exist_ok=True) + history_file.write_text(json.dumps(history, indent=2), encoding="utf-8") + + preferred = read_preferred(env_file) + verdict = decide(history, preferred) + print( + f"samples: {verdict.samples}/{WINDOW}, " + f"medians: {verdict.medians}, preferred: {verdict.preferred}" + ) + + if not verdict.changed: + print("Preferred collection source stays unchanged.") + return 0 + + write_preferred(env_file, verdict.proposed) + print( + f"Preferred collection source {verdict.preferred} -> {verdict.proposed}: " + f"its median is at least {RATIO}x the other's over {WINDOW} samples." + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cli/contributing/update/galaxy/__init__.py b/cli/contributing/update/galaxy/__init__.py new file mode 100644 index 0000000000..f79db0b735 --- /dev/null +++ b/cli/contributing/update/galaxy/__init__.py @@ -0,0 +1,5 @@ +"""CLI entry point package for pinned Ansible collection updates.""" + +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] diff --git a/cli/contributing/update/galaxy/__main__.py b/cli/contributing/update/galaxy/__main__.py new file mode 100755 index 0000000000..c83fb083be --- /dev/null +++ b/cli/contributing/update/galaxy/__main__.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +from pathlib import Path + +from utils.update.galaxy import apply_updates, find_outdated_updates + +from . import PROJECT_ROOT + + +def main() -> int: + parser = argparse.ArgumentParser( + description=( + "Update pinned Ansible collection versions in requirements/ to their " + "latest upstream release tag." + ) + ) + parser.add_argument( + "--repo-root", + type=Path, + default=PROJECT_ROOT, + help="Repository root to scan and update", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Print planned updates without modifying files", + ) + args = parser.parse_args() + + repo_root = args.repo_root.resolve() + updates = find_outdated_updates(repo_root) + + if not updates: + print("Pinned Ansible collections are already up to date.") + return 0 + + print("Planned collection pin updates:") + for update in updates: + print(f"- {update.pin.fqcn} {update.pin.version} -> {update.latest}") + + if args.dry_run: + return 0 + + changed_paths = apply_updates(repo_root, updates) + if changed_paths: + print("\nUpdated files:") + for path in changed_paths: + print(f"- {path.relative_to(repo_root)}") + else: + print("\nNo files changed.") + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cli/contributing/update/pip/__init__.py b/cli/contributing/update/pip/__init__.py new file mode 100644 index 0000000000..427a508803 --- /dev/null +++ b/cli/contributing/update/pip/__init__.py @@ -0,0 +1,5 @@ +"""CLI entry point package for pinned pip requirement updates.""" + +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] diff --git a/cli/contributing/update/pip/__main__.py b/cli/contributing/update/pip/__main__.py new file mode 100755 index 0000000000..903ee10cd1 --- /dev/null +++ b/cli/contributing/update/pip/__main__.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +from pathlib import Path + +from utils.update.pip import apply_updates, find_outdated_updates + +from . import PROJECT_ROOT + + +def main() -> int: + parser = argparse.ArgumentParser( + description="Update exact pip pins in roles/**/*.yml to their latest release." + ) + parser.add_argument( + "--repo-root", + type=Path, + default=PROJECT_ROOT, + help="Repository root to scan and update", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Print planned updates without modifying files", + ) + args = parser.parse_args() + + repo_root = args.repo_root.resolve() + updates = find_outdated_updates(repo_root) + + if not updates: + print("Pinned pip requirements are already up to date.") + return 0 + + print("Planned pip pin updates:") + for update in updates: + rel_path = update.entry.config_path.relative_to(repo_root) + print( + f"- {rel_path}:{update.entry.line_number} " + f"{update.entry.package} {update.entry.version} -> {update.latest}" + ) + + if args.dry_run: + return 0 + + changed_paths = apply_updates(updates) + if changed_paths: + print("\nUpdated files:") + for path in changed_paths: + print(f"- {path.relative_to(repo_root)}") + else: + print("\nNo files changed.") + + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cli/meta/ci/chunks.py b/cli/meta/ci/chunks.py index 498a5004b1..81a34e63ea 100644 --- a/cli/meta/ci/chunks.py +++ b/cli/meta/ci/chunks.py @@ -58,7 +58,7 @@ def plan( priority: rows of the priority line, in query order. regular: rows of the regular line, in query order. size: rows one chunk may hold (``slots.chunk_size``). - blocks: chunk blocks the workflow declares (``slots.chunk_count``). + blocks: chunk blocks the workflow declares (``slots.chunk_blocks``). budget: rows the run job cap allows in total (``slots.available``). offset: how many regular rows to skip before filling the chunks. ``0`` (the default) starts at the head of the ranking. A value past the diff --git a/cli/meta/ci/dev_runtime.py b/cli/meta/ci/dev_runtime.py index ff4f248163..ebb196d178 100644 --- a/cli/meta/ci/dev_runtime.py +++ b/cli/meta/ci/dev_runtime.py @@ -28,7 +28,7 @@ def image_label(image: str) -> str: """Shorten a dev-runtime image to its last two registry segments. ``quay.io/centos/centos:latest`` becomes ``centos:latest``; a two-segment - image such as ``debian:bookworm`` is returned unchanged. + image such as ``debian:13`` is returned unchanged. Args: image: full image reference. diff --git a/cli/meta/ci/guide_select.py b/cli/meta/ci/guide_select.py deleted file mode 100644 index 1e3063f7e5..0000000000 --- a/cli/meta/ci/guide_select.py +++ /dev/null @@ -1,80 +0,0 @@ -"""Pick the role and deploy mode for the Guide test. - -Role selection: an explicit ``--role`` wins; otherwise a random pick from -``--priority``, then ``--whitelist``, then every invokable role inside the -tested lifecycle envelope (``INFINITO_LIFECYCLES`` in ``default.env``) whose -guide deploy mode is not skipped via ``meta/tests.yml``. The mode is ``host`` -for a role that ships no container stack (installed straight onto the machine), -else ``compose``. The distro is not picked here: the role is replayed on every -distro by ``scripts/tests/deploy/distros.sh``. Output is ``key=value`` lines -for ``$GITHUB_ENV``. -""" - -from __future__ import annotations - -import argparse -import random -import sys -from typing import TYPE_CHECKING - -from utils.cache.files import PROJECT_ROOT -from utils.roles.deploy import role_has_stack -from utils.roles.lifecycle import tested_lifecycles -from utils.roles.meta_lookup import get_role_test_skips -from utils.roles.validation.invokable import ( - _get_invokable_paths, - _is_role_invokable, - _role_lifecycle, -) - -if TYPE_CHECKING: - from pathlib import Path - - -def _tokens(raw: str) -> list[str]: - return [t for t in raw.split() if t] - - -def _guide_mode(role_dir: Path) -> str: - return "compose" if role_has_stack(role_dir) else "host" - - -def _testable_roles() -> list[str]: - paths = _get_invokable_paths() - roles_dir = PROJECT_ROOT / "roles" - tested = set(tested_lifecycles()) - return sorted( - d.name - for d in roles_dir.iterdir() - if d.is_dir() - and _is_role_invokable(d.name, paths) - and _role_lifecycle(d) in tested - and _guide_mode(d) not in get_role_test_skips(d, role_name=d.name) - ) - - -def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--role", default="") - parser.add_argument("--priority", default="") - parser.add_argument("--whitelist", default="") - args = parser.parse_args(argv) - - if args.role.strip(): - role = args.role.strip() - else: - pool = _tokens(args.priority) or _tokens(args.whitelist) or _testable_roles() - if not pool: - print("guide_select: no candidate roles", file=sys.stderr) - return 1 - role = random.choice(pool) # noqa: S311 - test-role pick, not cryptographic - - mode = _guide_mode(PROJECT_ROOT / "roles" / role) - - print(f"GUIDE_ROLE={role}") - print(f"GUIDE_MODE={mode}") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/cli/meta/ci/matrix.py b/cli/meta/ci/matrix.py index ba20407b99..3beb7ad6a7 100644 --- a/cli/meta/ci/matrix.py +++ b/cli/meta/ci/matrix.py @@ -35,10 +35,10 @@ import sys from cli.meta.ci import chunks, query, slots from utils.cache.applications import get_variants -from utils.github.variant import axes, pools, selection, tor +from utils.github.variant import axes, instructions, pools, selection, tor from utils.roles.display import display_names -DROPPED = ("priority", "weight", "id", "covered", "clone") +DROPPED = ("priority", "id", "covered", "clone") """Entry keys the plan table reads but the matrix JSON withholds, so a deploy job cannot reference one: they describe the row's rank, not its deployment.""" @@ -149,13 +149,6 @@ def offset_index(raw: int | str | None, regular: list[dict[str, str]]) -> int: ) -def redundant(entry: dict[str, str]) -> bool: - """Whether the sweep drops this row as coverage an earlier row already has.""" - if entry["priority"] == "true": - return False - return entry["clone"] == "true" or entry["covered"] != "0" - - def chunks_of( entries: list[dict[str, str]], offset: int | str | None = 0 ) -> list[list[dict[str, str]]]: @@ -168,7 +161,7 @@ def chunks_of( regular = [ entry for entry in entries - if entry["priority"] != "true" and not redundant(entry) + if entry["priority"] != "true" and not instructions.redundant(entry) ] return [ sorted(chunk, key=axes.sort_key) @@ -176,7 +169,7 @@ def chunks_of( [entry for entry in entries if entry["priority"] == "true"], regular, size=slots.chunk_size(), - blocks=slots.chunk_count(), + blocks=slots.chunk_blocks(), budget=slots.available(), offset=offset_index(offset, regular), ) diff --git a/cli/meta/ci/plan.py b/cli/meta/ci/plan.py index f7c3294a82..8fc8a80988 100644 --- a/cli/meta/ci/plan.py +++ b/cli/meta/ci/plan.py @@ -15,6 +15,10 @@ sweep's budget (raise ``--offset`` to reach it), โœ‚๏ธ cut as redundant coverag a clone or a row an earlier one already embeds, which no sweep deploys. ``--cli`` renders fixed-width terminal tables instead of Markdown. +๐Ÿ“– marks the row that replays the role's README instructions after its deploy, +and names the mode the replay runs in -- which is the guide's own, not the +row's (:mod:`utils.roles.guide`). + ๐Ÿ†” numbers the rows of this table, 1..n, and ๐Ÿ”ฐ names the ๐Ÿ†” of the earlier row that already embeds this one -- empty when nothing does. A row with a ๐Ÿ”ฐ is redundant coverage: whatever it would prove, the row it points at proves first. ๐Ÿ‘ marks the other reason a row is cut: it @@ -29,7 +33,7 @@ import sys from cli.meta.ci import matrix, query, slots from cli.meta.roles.applications.complexity.render import _dwidth -from utils.github.variant import axes, pools, tor +from utils.github.variant import axes, instructions, pools, tor from utils.roles.display import display_names from utils.symbol_glossary import to_emoji @@ -49,7 +53,7 @@ _COLUMNS = ( "tor", "triggered", "covered_by", - "weight", + "instructions", "clone", ) _GLYPH = {"triggered": "enabled", "distro": "distros"} @@ -98,7 +102,7 @@ def cells( positions.setdefault(entry.get("id", ""), str(counter)) for counter, entry in enumerate(entries, start=1): chunk = _chunk_of(entry, plan) - if matrix.redundant(entry): + if instructions.redundant(entry): status, where = _CUT, "" elif chunk is None: status, where = _OFF, "" @@ -118,7 +122,7 @@ def cells( to_emoji("tor" if entry["tor"] == "true" else "clearnet"), status, positions.get(covered, covered) if covered not in ("", "0") else "", - entry["weight"], + to_emoji(entry["instructions"]) if entry["instructions"] else "", to_emoji("clone") if entry.get("clone") == "true" else "", ) ) diff --git a/cli/meta/ci/slots.py b/cli/meta/ci/slots.py index ed4e3cb795..bffd2df69e 100644 --- a/cli/meta/ci/slots.py +++ b/cli/meta/ci/slots.py @@ -34,8 +34,9 @@ What is left is :func:`available`, the rows one sweep can deploy. It is spent by :func:`chunk_count` blocks of :func:`chunk_size` rows. Because the orchestrator cannot generate a variable number of jobs, the block count is also capped by ``INFINITO_CI_MAX_CHUNKS``, the number of chunk blocks the -workflow YAML actually declares; a sweep that would need more rows than those -blocks hold leaves the rest to the next sweep's offset. +workflow YAML actually declares (:func:`chunk_blocks`); a sweep that would +need more rows than those blocks hold leaves the rest to the next sweep's +offset. """ from __future__ import annotations @@ -141,7 +142,15 @@ def waves(repo_root: Path | None = None) -> int: def chunk_size(repo_root: Path | None = None) -> int: - """Rows one chunk may hold before its tail risks the queue cancel.""" + """Rows one chunk may hold before its tail risks the queue cancel. + + ``INFINITO_CI_CHUNK_SIZE`` takes precedence when set; 0 derives the value + from the runner slots a chunk may assume and the waves the queue window + affords. + """ + override = setting("INFINITO_CI_CHUNK_SIZE") + if override > 0: + return override return setting("INFINITO_CI_CONCURRENCY") * waves(repo_root) @@ -190,10 +199,15 @@ def available(repo_root: Path | None = None) -> int: return max(limit - reserved_slots(repo_root) - entry_overhead(repo_root), 1) +def chunk_blocks() -> int: + """Chunk blocks call-orchestrator.yml declares, the most a sweep may plan.""" + return setting("INFINITO_CI_MAX_CHUNKS") + + def chunk_count(repo_root: Path | None = None) -> int: """Chunk blocks a sweep fills, capped by the blocks the YAML declares.""" needed = math.ceil(available(repo_root) / chunk_size(repo_root)) - return max(min(needed, setting("INFINITO_CI_MAX_CHUNKS")), 1) + return max(min(needed, chunk_blocks()), 1) def rows_per_sweep(repo_root: Path | None = None) -> int: @@ -230,7 +244,7 @@ def render_matrix() -> str: ("job timeout (minutes)", job_timeout_minutes()), ("waves", waves()), ("chunk size", chunk_size()), - ("chunk blocks (INFINITO_CI_MAX_CHUNKS)", setting("INFINITO_CI_MAX_CHUNKS")), + ("chunk blocks (INFINITO_CI_MAX_CHUNKS)", chunk_blocks()), ("chunks filled", chunk_count()), ("rows per sweep", rows_per_sweep()), ] diff --git a/cli/meta/ci/validate.py b/cli/meta/ci/validate.py index d54d5f9b29..97708c884d 100644 --- a/cli/meta/ci/validate.py +++ b/cli/meta/ci/validate.py @@ -50,6 +50,13 @@ def problems( ) -> tuple[list[str], list[str]]: """Every reason the tokens of one input cannot deploy on this branch. + A token that narrows nothing beyond the role name is answered by existence: + it asks for the role in whatever axes the rotation picks, so any discovered + row satisfies it. Rows are keyed by ``(name, variant)`` and a variant is an + int, so looking such a token up variant-first can only miss, which reported + every collapsed priority entry as matching nothing and left a role that + really had no row indistinguishable from one with a full set. + Args: tokens: the raw ``whitelist``/``priority`` value. modes: the run's selected deploy modes. @@ -72,11 +79,19 @@ def problems( modes, whitelist=selection.names(pins), lifecycles=lifecycles ) } + discovered_apps = {app for app, _variant in rows} declared = get_variants() errors: list[str] = [] warnings: list[str] = [] for pin in pins: token = selection.describe(pin) + if not pin.pinned: + if pin.app not in discovered_apps: + warnings.append( + f"{label}: {token!r} matches no discovered row " + f"(no row in this run's mode and lifecycle envelope)" + ) + continue variants = pin.variants or (None,) for variant in variants: offered = rows.get((pin.app, variant)) diff --git a/cli/meta/roles/applications/bond/__init__.py b/cli/meta/roles/applications/bond/__init__.py new file mode 100644 index 0000000000..85993a0f11 --- /dev/null +++ b/cli/meta/roles/applications/bond/__init__.py @@ -0,0 +1 @@ +"""Render the bond matrix: which roles couple to which, and how tightly.""" diff --git a/cli/meta/roles/applications/bond/__main__.py b/cli/meta/roles/applications/bond/__main__.py new file mode 100755 index 0000000000..a253a81cfb --- /dev/null +++ b/cli/meta/roles/applications/bond/__main__.py @@ -0,0 +1,7 @@ +#!/usr/bin/env python3 +"""Serve the bond matrix of every role that declares one.""" + +from .cli import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cli/meta/roles/applications/bond/cli.py b/cli/meta/roles/applications/bond/cli.py new file mode 100644 index 0000000000..b349b3d110 --- /dev/null +++ b/cli/meta/roles/applications/bond/cli.py @@ -0,0 +1,97 @@ +"""Serve the editable bond matrix, or export it as a static file.""" + +from __future__ import annotations + +import argparse +import contextlib +import shutil +import subprocess +import sys +from pathlib import Path + +from utils import PROJECT_ROOT + +from .matrix import collect_edges, participants +from .render import render, render_json +from .serve import serve + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="bond", + description=( + "Show which roles bond to which, and how tightly. Serves an editable " + "matrix on localhost; a cell edit rewrites the bond in the role." + ), + ) + parser.add_argument( + "--roles-dir", + default=str(PROJECT_ROOT / "roles"), + help="roles directory to read and write (default: the project's own)", + ) + parser.add_argument( + "-o", + "--out", + default="", + help="export a read-only file here instead of serving", + ) + parser.add_argument( + "--format", + choices=("html", "json"), + default="html", + help="export format, json implies --out (default: html)", + ) + parser.add_argument( + "--port", + type=int, + default=0, + help="port to serve on (default: any free port)", + ) + parser.add_argument( + "--no-open", + action="store_true", + help="do not open a browser", + ) + return parser + + +def _open(target: str) -> None: + """Open the matrix with the desktop's handler, if there is one.""" + opener = shutil.which("xdg-open") or shutil.which("open") + if not opener: + print(f"no xdg-open/open on PATH; the matrix is at {target}", file=sys.stderr) + return + subprocess.run([opener, target], check=False) + + +def main(argv: list[str] | None = None) -> int: + args = build_parser().parse_args(argv) + roles_dir = Path(args.roles_dir) + if not roles_dir.is_dir(): + print(f"no such roles directory: {roles_dir}", file=sys.stderr) + return 2 + + edges = collect_edges(roles_dir) + if not edges: + print(f"no services..bond found under {roles_dir}", file=sys.stderr) + return 1 + + if args.format == "json": + payload = render_json(edges) + if not args.out: + print(payload) + return 0 + elif args.out: + payload = render(edges, participants(edges)) + else: + httpd, url = serve(roles_dir, edges, args.port) + print(f"{url} ({len(edges)} bonds, editing writes to {roles_dir})") + if not args.no_open: + _open(url) + with contextlib.suppress(KeyboardInterrupt), httpd: + httpd.serve_forever() + return 0 + + Path(args.out).write_text(payload, encoding="utf-8") + print(args.out) + return 0 diff --git a/cli/meta/roles/applications/bond/edit.py b/cli/meta/roles/applications/bond/edit.py new file mode 100644 index 0000000000..281128c99b --- /dev/null +++ b/cli/meta/roles/applications/bond/edit.py @@ -0,0 +1,105 @@ +"""Write a single ``bond`` scalar back into a role's ``meta/services.yml``. + +The file is edited line by line rather than parsed and re-dumped: these files +carry ``# nocheck:`` directives and hand-tuned ordering that a YAML round-trip +would drop. +""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING + +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +if TYPE_CHECKING: + from pathlib import Path + +_TOP_KEY = re.compile(r"^(?P[^\s#][^:]*):\s*(?:#.*)?$") +_BOND = re.compile(r"^(?P\s*bond:\s*)(?P[^#]*?)(?P\s*#.*)?$") + + +class EditError(Exception): + """Raised when the requested bond cannot be written.""" + + +def parse_bond(raw: str) -> float | None: + """Return the bond a user typed, or None when they cleared the field.""" + text = str(raw).strip() + if text in ("", "-", "ยท"): + return None + try: + value = float(text) + except ValueError as exc: + raise EditError(f"not a number: {raw!r}") from exc + if not 0.0 <= value <= 1.0: + raise EditError(f"bond must be between 0 and 1, got {value:g}") + return value + + +def _block(lines: list[str], key: str) -> tuple[int, int]: + """Return the half-open line range of the top-level ``key`` mapping.""" + start = -1 + for index, line in enumerate(lines): + match = _TOP_KEY.match(line) + if match is None: + continue + if start < 0: + if match.group("key").strip() == key: + start = index + continue + return start, index + if start < 0: + raise EditError(f"no top-level entry {key!r}") + return start, len(lines) + + +def set_bond(roles_dir: Path, role: str, service_key: str, bond: float | None) -> str: + """Set, or with ``bond=None`` remove, ``.bond`` in ``role``. + + Args: + roles_dir: directory holding the role directories. + role: the consumer role whose file declares the bond. + service_key: the top-level key inside that role's services file. + bond: the new value, or None to drop the declaration entirely. + + Returns: + The value as it now stands in the file, or "" when it was removed. + """ + path = roles_dir / role / ROLE_FILE_META_SERVICES + if not path.is_file(): + raise EditError(f"no such file: {path}") + + raw = path.read_text( + encoding="utf-8" + ) # nocheck: cache-read โ€” a cached read would serve the text from before the previous edit and silently revert it + lines = raw.splitlines(keepends=True) + start, end = _block(lines, service_key) + + target = next( + (i for i in range(start + 1, end) if _BOND.match(lines[i].rstrip("\n"))), -1 + ) + if bond is None: + if target < 0: + return "" + del lines[target] + else: + text = f"{bond:g}" + if target < 0: + indent = next( + ( + line[: len(line) - len(line.lstrip())] + for line in lines[start + 1 : end] + if line.strip() and not line.lstrip().startswith("#") + ), + " ", + ) + lines.insert(start + 1, f"{indent}bond: {text}\n") + else: + match = _BOND.match(lines[target].rstrip("\n")) + if match is None: + raise EditError(f"cannot rewrite {lines[target]!r}") + lines[target] = f"{match['lead']}{text}{match['tail'] or ''}\n" + + path.write_text("".join(lines), encoding="utf-8") + return "" if bond is None else f"{bond:g}" diff --git a/cli/meta/roles/applications/bond/matrix.py b/cli/meta/roles/applications/bond/matrix.py new file mode 100644 index 0000000000..a6954e279f --- /dev/null +++ b/cli/meta/roles/applications/bond/matrix.py @@ -0,0 +1,77 @@ +"""Read every ``services..bond`` and resolve it to a role-to-role edge. + +``bond`` states how tightly a role couples to the service it declares: ``>= 1`` +keeps the partner on the same host, ``< 1`` lets it live on its own. The value +sits on the consumer's side of the relation, so the pair is directed and the +two directions of one pair need not agree. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from utils.cache.yaml import load_yaml_any +from utils.roles.applications.services.registry import ( + build_service_registry_from_roles_dir, +) +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +if TYPE_CHECKING: + from pathlib import Path + +DEFAULT_BOND = 1.0 + + +def _as_bond(value: Any) -> float | None: + """Return the bond as a float, or None when the entry declares none.""" + if isinstance(value, bool) or value is None: + return None + try: + return float(str(value).strip()) + except (TypeError, ValueError): + return None + + +def collect_edges(roles_dir: Path) -> dict[tuple[str, str], dict[str, Any]]: + """Return ``{(consumer, provider): {bond, service_key, enabled}}``. + + A role's entry for its own entity is skipped: a role does not bond to + itself, and those entries carry unrelated topics such as users or domains. + """ + registry = build_service_registry_from_roles_dir(roles_dir) + provider_of = { + key: str((entry or {}).get("role") or "") + for key, entry in registry.items() + if isinstance(entry, dict) + } + + edges: dict[tuple[str, str], dict[str, Any]] = {} + for path in sorted(roles_dir.glob(f"*/{ROLE_FILE_META_SERVICES}")): + consumer = path.parent.parent.name + services = load_yaml_any(str(path), default_if_missing={}) or {} + if not isinstance(services, dict): + continue + for key, entry in services.items(): + if not isinstance(entry, dict): + continue + bond = _as_bond(entry.get("bond")) + if bond is None: + continue + provider = provider_of.get(str(key), "") + if not provider or provider == consumer: + continue + edges[(consumer, provider)] = { + "bond": bond, + "service_key": str(key), + "enabled": entry.get("enabled"), + } + return edges + + +def participants(edges: dict[tuple[str, str], dict[str, Any]]) -> list[str]: + """Return every role on either end of a bond, in stable order.""" + seen: set[str] = set() + for consumer, provider in edges: + seen.add(consumer) + seen.add(provider) + return sorted(seen) diff --git a/cli/meta/roles/applications/bond/render.py b/cli/meta/roles/applications/bond/render.py new file mode 100644 index 0000000000..52b4474b5a --- /dev/null +++ b/cli/meta/roles/applications/bond/render.py @@ -0,0 +1,218 @@ +"""Render the bond matrix as an HTML page, optionally editable. + +Every cell carries both directions of one pair, row-to-column above +column-to-row, because a bond is declared on the consumer's side and the two +need not agree. Brightness is the bond: black for none, white for 1. +""" + +from __future__ import annotations + +import html +import json +from typing import Any + +_STYLE = """ +:root { color-scheme: dark; --bg:#0b0c0e; --fg:#d8d8d8; --grid:#ffffff1c; } +* { box-sizing: border-box; } +body { margin:0; background:var(--bg); color:var(--fg); + font:12px/1.35 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif; } +header { position:sticky; top:0; z-index:5; background:var(--bg); + border-bottom:1px solid var(--grid); padding:10px 14px; } +h1 { margin:0 0 4px; font-size:15px; font-weight:600; } +.meta { opacity:.65; } +.legend { margin-top:7px; display:flex; gap:14px; flex-wrap:wrap; align-items:center; } +.ramp { display:inline-block; width:120px; height:11px; border:1px solid var(--grid); + background:linear-gradient(to right,#000,#fff); vertical-align:-2px; margin:0 5px; } +#q { margin-top:8px; padding:4px 7px; width:260px; border:1px solid var(--grid); + border-radius:4px; background:transparent; color:inherit; font:inherit; } +#msg { margin-left:10px; font-size:11px; opacity:0; transition:opacity .15s; } +#msg.on { opacity:1; } #msg.bad { color:#f77; } +.wrap { overflow:auto; max-height:calc(100vh - 130px); } +table { border-collapse:separate; border-spacing:0; } +th, td { border-right:1px solid var(--grid); border-bottom:1px solid var(--grid); } +thead th { position:sticky; top:0; z-index:3; background:var(--bg); height:132px; + vertical-align:bottom; padding:0; } +thead th div { writing-mode:vertical-rl; transform:rotate(180deg); + padding:6px 3px; white-space:nowrap; font-weight:500; } +tbody th { position:sticky; left:0; z-index:2; background:var(--bg); text-align:left; + padding:0 8px 0 6px; white-space:nowrap; font-weight:500; } +thead th:first-child { position:sticky; left:0; z-index:4; background:var(--bg); } +td { width:30px; min-width:30px; padding:0; } +.b, .nb { display:block; height:13px; text-align:center; font-size:9px; line-height:13px; + font-variant-numeric:tabular-nums; } +.nb { background:#000; } +.b[data-c] { cursor:pointer; } +.b[data-c]:hover { outline:1px solid #4af; outline-offset:-1px; } +.diag { background:repeating-linear-gradient(45deg,#000,#000 3px,#1b1d22 3px,#1b1d22 6px); } +#ed { position:fixed; z-index:9; width:44px; height:22px; padding:0 3px; text-align:center; + border:1px solid #4af; border-radius:3px; background:#000; color:#fff; + font:11px ui-monospace,monospace; display:none; } +.hidden { display:none; } +""" + +_SCRIPT = """ +const box = document.getElementById('q'); +const rows = [...document.querySelectorAll('tbody tr')]; +const heads = [...document.querySelectorAll('thead th[data-role]')]; +box.addEventListener('input', () => { + const q = box.value.trim().toLowerCase(); + rows.forEach(tr => tr.classList.toggle('hidden', !!q && !tr.dataset.role.includes(q))); + heads.forEach((th, i) => { + const hit = !q || th.dataset.role.includes(q) || + rows.some(tr => !tr.classList.contains('hidden') && + tr.children[i + 1].dataset.filled === '1'); + th.classList.toggle('hidden', !hit); + rows.forEach(tr => tr.children[i + 1].classList.toggle('hidden', !hit)); + }); +}); + +const ed = document.getElementById('ed'); +const msg = document.getElementById('msg'); +let cur = null; + +function say(text, bad) { + msg.textContent = text; + msg.className = 'on' + (bad ? ' bad' : ''); + setTimeout(() => { msg.className = ''; }, 2600); +} + +function close() { ed.style.display = 'none'; cur = null; } + +document.querySelector('tbody').addEventListener('click', e => { + const bar = e.target.closest('.b[data-c]'); + if (!bar) { close(); return; } + cur = bar; + const r = bar.getBoundingClientRect(); + ed.style.left = Math.round(r.left + r.width / 2 - 22) + 'px'; + ed.style.top = Math.round(r.top + r.height / 2 - 11) + 'px'; + ed.style.display = 'block'; + ed.value = bar.dataset.b || ''; + ed.select(); +}); + +ed.addEventListener('keydown', e => { + if (e.key === 'Escape') { close(); return; } + if (e.key !== 'Enter') return; + const bar = cur, value = ed.value; + close(); + fetch('bond', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ consumer: bar.dataset.c, provider: bar.dataset.p, value }) + }).then(r => r.json()).then(d => { + if (!d.ok) { say(d.error, true); return; } + bar.textContent = d.text; + bar.dataset.b = d.text; + bar.style.background = d.bg; + bar.style.color = d.fg; + say(d.written); + }).catch(err => say(String(err), true)); +}); +ed.addEventListener('blur', close); +""" + + +def shade(bond: float) -> tuple[str, str]: + """Return the (background, foreground) pair for a bond between 0 and 1.""" + level = round(max(0.0, min(1.0, bond)) * 255) + return f"rgb({level},{level},{level})", "#000" if level > 140 else "#fff" + + +def _bar( + edge: dict[str, Any] | None, consumer: str, provider: str, editable: bool +) -> str: + """Return one of a cell's two direction bars.""" + if edge is None: + return '' + bond = edge["bond"] + background, foreground = shade(bond) + text = f"{bond:g}" + handle = "" + if editable: + handle = ( + f' data-c="{html.escape(consumer)}" data-p="{html.escape(provider)}"' + f' data-b="{text}"' + ) + return ( + f'' + f"{text}" + ) + + +def render( + edges: dict[tuple[str, str], dict[str, Any]], + roles: list[str], + *, + editable: bool = False, +) -> str: + """Return the full HTML page for the given edges. + + Args: + edges: the collected ``{(consumer, provider): edge}`` mapping. + roles: every participating role, in the order rows and columns take. + editable: wire the cells to the server's write endpoint. + """ + head = "".join( + f'
{html.escape(r)}
' + for r in roles + ) + body = [] + for row in roles: + cells = [] + for col in roles: + if row == col: + cells.append('') + continue + out, back = edges.get((row, col)), edges.get((col, row)) + filled = "1" if out is not None or back is not None else "0" + cells.append( + f'' + + _bar(out, row, col, editable) + + _bar(back, col, row, editable) + + "" + ) + body.append( + f'' + f"{html.escape(row)}" + "".join(cells) + "" + ) + + hint = ( + "click a bar to edit, Enter writes it to the role" + if editable + else "read only, run without --out to edit" + ) + return f""" + + +Bond matrix + +
+

Bond matrix

+
{len(edges)} bonds across {len(roles)} roles · + row → column above column → row · {hint}
+
+ 01 + no bond +
+ +
+
+{head} +{"".join(body)} +
+ + + +""" + + +def render_json(edges: dict[tuple[str, str], dict[str, Any]]) -> str: + """Return the same data as JSON, for a caller that wants to post-process.""" + return json.dumps( + [ + {"consumer": consumer, "provider": provider, **edge} + for (consumer, provider), edge in sorted(edges.items()) + ], + indent=2, + ) diff --git a/cli/meta/roles/applications/bond/serve.py b/cli/meta/roles/applications/bond/serve.py new file mode 100644 index 0000000000..dd08ae9db0 --- /dev/null +++ b/cli/meta/roles/applications/bond/serve.py @@ -0,0 +1,111 @@ +"""Serve the bond matrix on localhost and write every cell edit back to disk. + +The edge map is built once at startup and kept in step with the writes this +server performs, so a role file edited by hand elsewhere needs a restart. +""" + +from __future__ import annotations + +import json +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import TYPE_CHECKING, Any + +from .edit import EditError, parse_bond, set_bond +from .matrix import participants +from .render import render, shade + +if TYPE_CHECKING: + from pathlib import Path + +MAX_BODY = 4096 + + +class _Handler(BaseHTTPRequestHandler): + server_version = "bond-matrix" + roles_dir: Path + edges: dict[tuple[str, str], dict[str, Any]] + + def log_message(self, fmt: str, *args: Any) -> None: + return + + def _send(self, code: int, body: bytes, content_type: str) -> None: + self.send_response(code) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _json(self, code: int, payload: dict[str, Any]) -> None: + self._send(code, json.dumps(payload).encode(), "application/json") + + def do_GET(self) -> None: + if self.path.split("?")[0] not in ("/", "/index.html"): + self._json(404, {"ok": False, "error": "not found"}) + return + page = render(self.edges, participants(self.edges), editable=True) + self._send(200, page.encode(), "text/html; charset=utf-8") + + def do_POST(self) -> None: + if self.path.split("?")[0] != "/bond": + self._json(404, {"ok": False, "error": "not found"}) + return + length = int(self.headers.get("Content-Length") or 0) + if length > MAX_BODY: + self._json(413, {"ok": False, "error": "body too large"}) + return + try: + payload = json.loads(self.rfile.read(length) or b"{}") + key = (str(payload["consumer"]), str(payload["provider"])) + raw = payload["value"] + except (ValueError, KeyError, TypeError): + self._json(400, {"ok": False, "error": "malformed request"}) + return + + edge = self.edges.get(key) + if edge is None: + self._json(404, {"ok": False, "error": f"no bond {key[0]} -> {key[1]}"}) + return + + try: + bond = parse_bond(raw) + text = set_bond(self.roles_dir, key[0], edge["service_key"], bond) + except EditError as exc: + self._json(400, {"ok": False, "error": str(exc)}) + return + + if bond is None: + del self.edges[key] + background, foreground = "#000", "#fff" + else: + edge["bond"] = bond + background, foreground = shade(bond) + written = f"{key[0]}/{edge['service_key']}.bond = {text or 'removed'}" + self._json( + 200, + { + "ok": True, + "text": text, + "bg": background, + "fg": foreground, + "written": written, + }, + ) + + +def serve( + roles_dir: Path, + edges: dict[tuple[str, str], dict[str, Any]], + port: int, +) -> tuple[ThreadingHTTPServer, str]: + """Return a server bound to loopback and the URL it listens on. + + Args: + roles_dir: directory the writes land in. + edges: the collected edge map, mutated in place as edits arrive. + port: the port to bind, or 0 to let the OS pick one. + """ + handler = type( + "_BoundHandler", (_Handler,), {"roles_dir": roles_dir, "edges": edges} + ) + httpd = ThreadingHTTPServer(("127.0.0.1", port), handler) + return httpd, f"http://127.0.0.1:{httpd.server_address[1]}/" diff --git a/cli/meta/roles/applications/complexity/cli.py b/cli/meta/roles/applications/complexity/cli.py index 8d1ea4b3e9..ee60cde3c3 100644 --- a/cli/meta/roles/applications/complexity/cli.py +++ b/cli/meta/roles/applications/complexity/cli.py @@ -5,9 +5,14 @@ from __future__ import annotations import argparse import re import sys -from typing import Any +from typing import TYPE_CHECKING, Any from utils import PROJECT_ROOT +from utils.cache.applications import get_variants +from utils.roles.applications.topics import overridden_providers + +if TYPE_CHECKING: + from collections.abc import Mapping from .filter import FilterError, compile_predicate from .model import ( @@ -272,7 +277,11 @@ def _apply_sort(rows: list[ComplexityRow], sort_spec: list[tuple[str, bool]]) -> rows.sort(key=_SORT_KEYS[column], reverse=reverse) -def _mark_covered(rows: list[ComplexityRow]) -> list[ComplexityRow]: +def _mark_covered( + rows: list[ComplexityRow], + overridden: Mapping[tuple[str, int], set[str]] | None = None, + variant_counts: Mapping[str, int] | None = None, +) -> list[ComplexityRow]: """Assign each sorted row its numeric ``id`` (its position in sort order) and its ``covered_by`` via a greedy set-cover: the first row is green, and every later row's ``covered_by`` is the (1-based) ``id`` of the first @@ -284,11 +293,36 @@ def _mark_covered(rows: list[ComplexityRow]) -> list[ComplexityRow]: coverer's deploy genuinely brings this row up. Two variants of the same role never cover each other (a role never embeds itself). - Coverage is variant-aware: when a service.yml declares another service - enabled+shared it always pulls that provider's variant 0, so only a row's - variant-0 (or whole-role) form can be covered. A variant > 0 row is never - covered and is always green; it may still cover other roles' rows.""" - green: list[tuple[int, str, set[str]]] = [] + Coverage is variant-aware: only a row's variant-0 (or whole-role) form can + be covered, because a coverer only ever brings a provider up at variant 0. + Which coverers do that is not a property of the coverer alone. A job's + round index is the primary role's own variant index, and + ``inventory.planner.plan_dev_inventory_matrix`` hands each pulled-in + dependency ``round_index if round_index < its variant count else 0``. So a + variant N row covers a provider exactly when N lands past that provider's + last variant and falls back to 0 - which is why ``variant_counts`` is + needed here: N alone does not say it. + + A variant that dictates a provider's own config is not evidence about that + provider in any variant: the deploy ran a configuration the provider does + not declare. ``overridden`` maps ``(role, variant)`` to the providers it + overrides, and such a pair never covers those providers. + + Args: + rows: the complexity rows, in ranking order. + overridden: ``{(role, variant): {provider role, ...}}``, or None when + no variant dictates anything. + variant_counts: ``{role: how many variants it declares}``. A role + missing from it counts as one, which is the whole-role case. + """ + demands = overridden or {} + counts = variant_counts or {} + + def pulls_at_zero(coverer_variant: int | None, provider: str) -> bool: + index = coverer_variant or 0 + return index == 0 or index >= counts.get(provider, 1) + + green: list[tuple[int, str, int | None, set[str]]] = [] out: list[ComplexityRow] = [] for index, row in enumerate(rows, start=1): coverable = row.variant in (None, 0) @@ -296,8 +330,11 @@ def _mark_covered(rows: list[ComplexityRow]) -> list[ComplexityRow]: next( ( gid - for gid, gname, gset in green - if gname != row.name and row.name in gset + for gid, gname, gvariant, gset in green + if gname != row.name + and row.name in gset + and row.name not in demands.get((gname, gvariant or 0), ()) + and pulls_at_zero(gvariant, row.name) ), None, ) @@ -305,7 +342,7 @@ def _mark_covered(rows: list[ComplexityRow]) -> list[ComplexityRow]: else None ) if coverer is None: - green.append((index, row.name, set(row.services))) + green.append((index, row.name, row.variant, set(row.services))) out.append(row._replace(id=index, covered_by=coverer or 0)) return out @@ -321,6 +358,7 @@ def main(argv: list[str] | None = None) -> int: sort_spec = parse_sort_spec(args.sort) except ValueError as exc: p.error(str(exc)) + return 2 roles_dir = PROJECT_ROOT / "roles" if not roles_dir.is_dir(): @@ -353,7 +391,14 @@ def main(argv: list[str] | None = None) -> int: rows = attach_siblings(rows) _apply_sort(rows, sort_spec) - rows = _mark_covered(rows) + rows = _mark_covered( + rows, + overridden_providers(roles_dir), + { + role: max(1, len(entries or [{}])) + for role, entries in get_variants(roles_dir=roles_dir).items() + }, + ) _apply_sort(rows, sort_spec) rows = [r._replace(row=line) for line, r in enumerate(rows, start=1)] diff --git a/cli/meta/roles/applications/complexity/filter.py b/cli/meta/roles/applications/complexity/filter.py index ba0fbb242e..88a34c97f1 100644 --- a/cli/meta/roles/applications/complexity/filter.py +++ b/cli/meta/roles/applications/complexity/filter.py @@ -27,7 +27,6 @@ from typing import Any Predicate = Callable[[dict[str, Any]], bool] -_OPERATORS = ("%%", "==", "!=", "<=", ">=", "<", ">") _KEYWORDS = frozenset({"and", "or", "xor", "not"}) _NUMBER_RE = re.compile(r"^-?\d+(?:\.\d+)?$") _TOKEN_RE = re.compile( diff --git a/cli/meta/roles/applications/role_name/__main__.py b/cli/meta/roles/applications/role_name/__main__.py index c3a8842510..04b3b10f69 100755 --- a/cli/meta/roles/applications/role_name/__main__.py +++ b/cli/meta/roles/applications/role_name/__main__.py @@ -18,6 +18,12 @@ from utils.roles.mapping import ROLE_FILE_VARS_MAIN from . import PROJECT_ROOT +EXIT_NO_SUCH_APPLICATION_ROLE = 3 + + +class RoleNotFoundError(RuntimeError): + """No role under `roles_path` declares this application_id.""" + def get_role(application_id, roles_path): """ @@ -43,7 +49,7 @@ def get_role(application_id, roles_path): if data.get("application_id") == application_id: return role - raise RuntimeError( + raise RoleNotFoundError( f"No role found with application_id '{application_id}' in {roles_path}" ) @@ -69,6 +75,9 @@ def main(): folder = get_role(args.application_id, args.roles_path) print(folder) sys.exit(0) + except RoleNotFoundError as err: + print(f"Error: {err}", file=sys.stderr) + sys.exit(EXIT_NO_SUCH_APPLICATION_ROLE) except RuntimeError as err: print(f"Error: {err}", file=sys.stderr) sys.exit(1) diff --git a/compose.yml b/compose.yml index 778ee135b5..5cc60f4415 100644 --- a/compose.yml +++ b/compose.yml @@ -71,6 +71,9 @@ services: - letsencrypt:/etc/letsencrypt/ environment: + INFINITO_API_ANTHROPIC_KEY: ${INFINITO_API_ANTHROPIC_KEY} + INFINITO_API_OPENAI_KEY: ${INFINITO_API_OPENAI_KEY} + INFINITO_API_OPENROUTER_KEY: ${INFINITO_API_OPENROUTER_KEY} INFINITO_BUILDKIT_ENABLED: ${INFINITO_BUILDKIT_ENABLED} INFINITO_CONTAINER_CA_ENABLED: ${INFINITO_CONTAINER_CA_ENABLED} INFINITO_DIR_VAR_LIB: ${INFINITO_DIR_VAR_LIB} @@ -84,7 +87,6 @@ services: INFINITO_MAIL_PRODUCTION_RESOLVER: ${INFINITO_MAIL_PRODUCTION_RESOLVER} INFINITO_PLAYWRIGHT_KEEP: ${INFINITO_PLAYWRIGHT_KEEP} INFINITO_PLAYWRIGHT_REPORTS_BASE_DIR: ${INFINITO_PLAYWRIGHT_REPORTS_BASE_DIR} - INFINITO_PLAYWRIGHT_STAGE_BASE_DIR: ${INFINITO_PLAYWRIGHT_STAGE_BASE_DIR} INFINITO_SRC_DIR: ${INFINITO_SRC_DIR} INFINITO_SWARM_MGR_IP: ${INFINITO_SWARM_MGR_IP} INFINITO_TOR_SOCKS_PORT: ${INFINITO_TOR_SOCKS_PORT} diff --git a/compose/cache.override.yml b/compose/cache.override.yml index 4df4214cb4..6b19f94232 100644 --- a/compose/cache.override.yml +++ b/compose/cache.override.yml @@ -63,6 +63,9 @@ services: timeout: 3s retries: 60 start_period: 120s + networks: + default: + ipv4_address: ${INFINITO_CACHE_PACKAGE_IP:?Run 'make dotenv' to generate the .env single source of truth} restart: unless-stopped package-cache-frontend: diff --git a/compose/coredns/Corefile.tmpl b/compose/coredns/Corefile.tmpl index 6bffd62f6d..adc5186d65 100644 --- a/compose/coredns/Corefile.tmpl +++ b/compose/coredns/Corefile.tmpl @@ -1,26 +1,30 @@ .:53 { template IN A { - match ^${INFINITO_DOMAIN_RE}\.$ + match ^${DOMAIN_RE}\.$ answer "{{ .Name }} 60 IN A ${INFINITO_IP4}" fallthrough } template IN A { - match ^(.*)\.${INFINITO_DOMAIN_RE}\.$ + match ^(.*)\.${DOMAIN_RE}\.$ answer "{{ .Name }} 60 IN A ${INFINITO_IP4}" fallthrough } template IN AAAA { - match ^${INFINITO_DOMAIN_RE}\.$ + match ^${DOMAIN_RE}\.$ fallthrough } template IN AAAA { - match ^(.*)\.${INFINITO_DOMAIN_RE}\.$ + match ^(.*)\.${DOMAIN_RE}\.$ fallthrough } + template IN ANY ${INFINITO_DOMAIN} { + authority "${INFINITO_DOMAIN}. 60 IN SOA ns.${INFINITO_DOMAIN}. hostmaster.${INFINITO_DOMAIN}. 1 60 60 60 60" + } + forward . 1.1.1.1 8.8.8.8 # noqa: hardcoded-dns-resolver log errors diff --git a/compose/coredns/README.md b/compose/coredns/README.md index e153d7e6ea..2484ead448 100644 --- a/compose/coredns/README.md +++ b/compose/coredns/README.md @@ -7,10 +7,10 @@ The sidecar resolves the dev/CI stack's internal hostnames so the `infinito` run - This directory MUST contain only files consumed by the `coredns` compose service. - The `Corefile.tmpl` MUST be the source of truth. - It is rendered to `Corefile` by [coredns.py](../../cli/administration/deploy/development/coredns.py) via `envsubst`, using values from `.env` (generated from [default.env](../../default.env), overridable through the CLI's environment). + It is rendered to `Corefile` by [coredns.py](../../cli/administration/deploy/development/coredns.py), which substitutes its `${VAR}` placeholders in-process, using values from `.env` (generated from [default.env](../../default.env), overridable through the CLI's environment). - The rendered `Corefile` is build artefact and MUST stay in `.gitignore`. ## Files ๐Ÿ“„ -- `Corefile.tmpl`: `envsubst` template processed at stack start. +- `Corefile.tmpl`: `${VAR}` template processed at stack start. - `Corefile`: rendered output, bind-mounted read-only into the `coredns` container at `/Corefile`. diff --git a/compose/package-cache-frontend/upstreams.conf b/compose/package-cache-frontend/upstreams.conf index 6539c2e5b2..b5c5ef08e7 100644 --- a/compose/package-cache-frontend/upstreams.conf +++ b/compose/package-cache-frontend/upstreams.conf @@ -18,6 +18,10 @@ resolver 127.0.0.11 ipv6=off valid=30s; # and apt probes for missing files often enough that retrying those would double # the request rate. # +# Nexus answers that 502 only after trying every address of the remote in turn, +# one connect timeout each; for a remote with several addresses that outlasts a +# client's own timeout before the mirror is ever asked. +# # These stay prefix locations. A regex location forfeits nginx's implicit # `/debian` -> `/debian/` redirect, and the URL-reachability test probes exactly # that slash-less form through the runner's DNS hijack, so it turns into a 404. @@ -27,6 +31,7 @@ server { location /debian/ { rewrite ^/debian/(.*)$ /repository/apt-debian/$1 break; proxy_intercept_errors on; + proxy_read_timeout 8s; error_page 502 503 504 = @debian_mirror; proxy_pass http://package-cache:8081; } @@ -37,6 +42,7 @@ server { location /debian-security/ { rewrite ^/debian-security/(.*)$ /repository/apt-debian-security/$1 break; proxy_intercept_errors on; + proxy_read_timeout 8s; error_page 502 503 504 = @debian_security_mirror; proxy_pass http://package-cache:8081; } @@ -52,6 +58,7 @@ server { location /ubuntu/ { rewrite ^/ubuntu/(.*)$ /repository/apt-ubuntu/$1 break; proxy_intercept_errors on; + proxy_read_timeout 8s; error_page 502 503 504 = @ubuntu_mirror; proxy_pass http://package-cache:8081; } @@ -66,6 +73,7 @@ server { location /ubuntu/ { rewrite ^/ubuntu/(.*)$ /repository/apt-ubuntu-security/$1 break; proxy_intercept_errors on; + proxy_read_timeout 8s; error_page 502 503 504 = @ubuntu_security_mirror; proxy_pass http://package-cache:8081; } diff --git a/compose/swarm/playbook.yml b/compose/swarm/playbook.yml index 98738d2f04..007e222128 100644 --- a/compose/swarm/playbook.yml +++ b/compose/swarm/playbook.yml @@ -134,7 +134,7 @@ timeout: 30 when: lab_is_mgr or inventory_hostname in [lab_nfs, lab_backup] - - name: own the whole dnsmasq config (fedora and centos ship local-service, which implies bind-interfaces and dnsmasq refuses next to our bind-dynamic) + - name: own the whole dnsmasq config (the packaging appends --local-service unconditionally and only an interface, except-interface, listen-address or auth-server directive resets it; without that reset a failed interface re-enumeration empties dnsmasq's local-subnet list and it rejects every query, loopback included, until an address event rebuilds it) template: # nocheck: stack-host-template - lab node system config, every DNS node writes its own /etc/dnsmasq.conf and IS_STACK_HOST does not exist in this play src: dnsmasq.conf.j2 dest: /etc/dnsmasq.conf diff --git a/compose/swarm/templates/dnsmasq.conf.j2 b/compose/swarm/templates/dnsmasq.conf.j2 index ef198a34b5..48dfe761fb 100644 --- a/compose/swarm/templates/dnsmasq.conf.j2 +++ b/compose/swarm/templates/dnsmasq.conf.j2 @@ -5,3 +5,4 @@ server={{ resolver }} {% endfor %} address=/{{ lab_domain }}/{{ lab_domain_target }} local=/{{ lab_domain }}/ +interface=* diff --git a/composer.json b/composer.json index f18dac2f6e..86e6d05780 100644 --- a/composer.json +++ b/composer.json @@ -3,10 +3,16 @@ "description": "PHPUnit dependencies for the PHP shipped in roles/*/files/php/.", "type": "project", "license": "MIT", + "require": { + "php": ">=8.3" + }, "require-dev": { - "phpunit/phpunit": "^11.0" + "phpunit/phpunit": "^12.0" }, "config": { + "platform": { + "php": "8.3" + }, "sort-packages": true }, "scripts": { diff --git a/default.env b/default.env index e8aa256d8d..98641b4d54 100644 --- a/default.env +++ b/default.env @@ -16,12 +16,27 @@ # Git repository holding the operator's terminal aliases (an `aliases` file at repo root); developers override this with their own repo. INFINITO_ALIAS_REPOSITORY=https://github.com/kevinveenbirkenbach/alias +# Requirements file scripts/install/ansible.sh tries first, `galaxy` or `git`; the other one stays the fallback. +INFINITO_ANSIBLE_COLLECTIONS_SOURCE=galaxy + +# Anthropic API key the development inventory feeds into API.anthropic.api_key; empty leaves the anthropic routes unpublished. +INFINITO_API_ANTHROPIC_KEY="" + +# OpenAI API key the development inventory feeds into API.openai.api_key; empty leaves the openai routes unpublished. +INFINITO_API_OPENAI_KEY="" + +# OpenRouter API key the development inventory feeds into API.openrouter.api_key; empty leaves openrouter/auto unpublished. +INFINITO_API_OPENROUTER_KEY="" + # Where scripts/meta/resolve/apps.sh runs the meta-CLI: host | docker. INFINITO_APP_DISCOVERY_RUNNER=docker # Per-app variant index map for credential generation, set per round by the swarm matrix orchestrator; empty elsewhere. INFINITO_APP_VARIANTS= +# Ubuntu mirrors in failover order for image apt; the package-cache takes the first as primary, the second as fallback. +INFINITO_APT_UBUNTU_MIRRORS="http://de.archive.ubuntu.com/ubuntu/ http://ftp.fau.de/ubuntu/ http://ftp.halifax.rwth-aachen.de/ubuntu/ http://archive.ubuntu.com/ubuntu/" + # Host interface(s) the compose stack binds published ports to. INFINITO_BIND_IP=127.0.0.1 @@ -55,6 +70,9 @@ INFINITO_CACHE_PACKAGE_FRONTEND_IP=172.30.0.4 # Host directory backing the Nexus 3 package-cache blobstore. INFINITO_CACHE_PACKAGE_HOST_PATH=/var/cache/infinito/core/cache/package/data +# Static IPv4 address the Nexus package-cache takes on the docker bridge. +INFINITO_CACHE_PACKAGE_IP=172.30.0.5 + # Content freshness window (minutes) for immutable cached artifacts (wheels, debs, rpms). 8640 = 6 days. INFINITO_CACHE_PACKAGE_MAX_AGE_MIN=8640 @@ -88,6 +106,9 @@ INFINITO_CACHE_STACK=true # Index of the deploy chunk the discovery emits; each chunk block of call-orchestrator.yml passes its own. INFINITO_CI_CHUNK=0 +# Rows one deploy chunk holds, overriding the concurrency-times-waves derivation; 0 derives it. +INFINITO_CI_CHUNK_SIZE=0 + # Runner slots a deploy chunk may assume are free; with the job timeout it sizes a chunk in cli.meta.ci.slots. INFINITO_CI_CONCURRENCY=20 @@ -97,8 +118,8 @@ INFINITO_CI_DISTRO_BUDGET_SECONDS=20400 # Job budget per workflow run cli.meta.ci.slots spends on the deploy chunks (GitHub matrix cap: 256). INFINITO_CI_JOB_LIMIT=256 -# Chunk job blocks call-orchestrator.yml declares; cli.meta.ci.slots must never plan more than these exist in the YAML. -INFINITO_CI_MAX_CHUNKS=3 +# Chunk job blocks call-orchestrator.yml declares; one above what the budget fills, so a short priority chunk strands no row. +INFINITO_CI_MAX_CHUNKS=4 # Regular rows a run skips before filling its chunks; a count or a selection token, 0 starts at the head of the ranking. INFINITO_CI_OFFSET=0 @@ -166,12 +187,9 @@ INFINITO_DOCKER_MOUNT=/var/lib/docker # Docker volume backing /var/lib/docker; generator overrides to /mnt/docker on GHA. INFINITO_DOCKER_VOLUME=docker -# Top-level project domain for CI/dev (overridden in real deploys); .test because the default mail provider (Stalwart) rejects .example. +# Top-level project domain rendered into vhost/cert/test fixtures; CI/dev default, overridden in real deploys. INFINITO_DOMAIN=infinito.test -# INFINITO_DOMAIN escaped for inclusion in regex patterns (literal `.`); keep in sync with INFINITO_DOMAIN. -INFINITO_DOMAIN_RE=infinito\.test - # Repo-relative path of the filesystem userland install script (ext4, btrfs, zfs). INFINITO_FILESYSTEM_INSTALL_SCRIPT=scripts/install/filesystem.sh @@ -347,6 +365,9 @@ INFINITO_SWARM_NODE_PIDS_LIMIT=8192 # Ceiling in minutes for one distro's swarm matrix deploy in scripts/tests/deploy/swarm/routine/00_one.sh; swarm's step level. INFINITO_SWARM_STEP_TIMEOUT_MINUTES=350 +# Wall clock 00_one.sh leaves collect_and_teardown under the sweep budget; measured worst case 12m44s on the swarm moodle#1 rescue path. +INFINITO_SWARM_TEARDOWN_RESERVE_SECONDS=900 + # Docker label stamped on every act-swarm-test container (DinD + NFS sidecar) so cleanup selects by label, not a guessed name. INFINITO_SWARM_TEST_LABEL=infinito.swarm-test diff --git a/docs/agents/action/iteration/roundtrip.md b/docs/agents/action/iteration/roundtrip.md index 55b3785894..896d211950 100644 --- a/docs/agents/action/iteration/roundtrip.md +++ b/docs/agents/action/iteration/roundtrip.md @@ -36,4 +36,4 @@ The roundtrip is a gate, not a debugger: when a step goes red it stops and leave - On a recent Docker engine the swarm step can abort at job setup; run `make act-runner-image` once and prefix the run with `ACT_PLATFORM_IMAGE=local/act-runner-fixed:latest` (see [Workflow Loop](workflow.md)). - The swarm-test nfs-server serves shared storage from userspace `nfs-ganesha` (the `ganesha` flavor of `svc-storage-nfs-server`, the default in every runtime), which runs inside the privileged DinD node and never touches the host kernel `nfsd`, so an interrupted export cannot wedge the host. The `kernel` flavor is a per-inventory override for real hosts, where `nfsd` is not shared across clusters. If a swarm step ever hangs at `Reload NFS exports` from a stuck kernel-NFS mount, you MUST recover with `make swarm-clean` on the host (needs sudo): it removes what the docker CLI can, then runs `umount -f -l /var/lib/infinito` + `exportfs -ua` + `systemctl restart docker`. The no-sudo sandbox only prints those commands, so the host recovery is mandatory and the sweep MUST stop until it is done; never fall back to compose-only. -- Distinct `SWARM_NAME` per app means several apps can keep their clusters in parallel under `keep=true`; release each one with `make swarm-down name=`. +- Only one swarm cluster fits per worktree: the lab subnet is pinned to the worktree slot (`INFINITO_SWARM_LAB_SUBNET` in `scripts/system/worktree/up.sh`), so a second cluster in the same worktree fails at network creation with `invalid pool request: Pool overlaps`. `swarm-zombie` therefore reclaims whatever holds that subnet before it starts (`utils/clean/lab_subnet.sh`), so a cluster kept with `keep=true` survives only until the next swarm run in the same worktree. Inspect a kept cluster before starting the next run. Parallel clusters need separate worktrees (`make worktree-up`), which carry distinct lab octets and are left untouched by the reclaim; `make swarm-clean` is the deliberate exception that clears every worktree's clusters. diff --git a/docs/contributing/actions/testing/suppression.md b/docs/contributing/actions/testing/suppression.md index f55f3fd857..b0f3939497 100644 --- a/docs/contributing/actions/testing/suppression.md +++ b/docs/contributing/actions/testing/suppression.md @@ -44,9 +44,11 @@ The placement rule is per check. The catalog "Position" column uses these labels | Rule | Position | Affected test | Effect | | --------------------------- | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `url` | same or above | [test_urls_reachable.py](../../../../tests/external/repository/test_urls_reachable.py) | Skips probing the literal HTTP(S) URL. Use for CDN roots and API base URLs that 4xx without a path. | +| `onion-flag` | same or above | [test_onion_port_flag.py](../../../../tests/lint/ansible/services/test_onion_port_flag.py) | Accepts a `false` under `ports.onion`. The marker MUST carry a reason naming why that port stays off the node onion; a bare marker is rejected. | | `docker-version` | same or above | [test_image_versions.py](../../../../tests/external/update/docker/test_image_versions.py), [test_semver_pinning.py](../../../../tests/lint/ansible/services/test_semver_pinning.py) | Skips both the live version-update warning and the non-semver-pin lint for that image's `version:` key. | | `repository-version` | same or above | [test_repository_versions.py](../../../../tests/external/update/repository/test_repository_versions.py), [test_semver_pinning.py](../../../../tests/lint/ansible/services/test_semver_pinning.py) | Skips both the live ref-update warning and the non-semver-pin lint for that entity's `ref:` key. | | `dockerfile-arg-default` | same or above | [test_arg_without_default.py](../../../../tests/lint/docker/dockerfile/test_arg_without_default.py) | Allows the marked `ARG` to carry a default. The caller normally supplies every build argument so a missing one fails the build instead of selecting a base image nobody chose. | +| `debian-codename` | same or above | [test_no_debian_codename_tags.py](../../../../tests/lint/repository/test_no_debian_codename_tags.py) | Allows an image reference whose tag names a Debian release by codename. Reserved for an upstream that publishes no numeric tag; the marker MUST name which upstream, because a codename pin can never be raised by the updater. | | `direct-yaml` | same line / span | [test_no_direct_calls.py](../../../../tests/lint/repository/yaml/test_no_direct_calls.py) | Allows the marked `yaml.safe_load` / `safe_dump` call to bypass `utils.cache.yaml`. MUST use `nocheck:`, not `noqa:`. | | `curl-timeout` | same or above | [test_curl_via_filter.py](../../../../tests/lint/repository/test_curl_via_filter.py) | Allows a bare curl invocation without the `curl` filter or inline `--max-time`. | | `redundant-bool-ternary` | same line | [test_no_redundant_bool_patterns.py](../../../../tests/lint/filesystem/python/test_no_redundant_bool_patterns.py) | Allows the redundant `\| bool \| ternary('true','false')` pattern when a consumer requires the lowercase tokens. | @@ -59,6 +61,10 @@ The placement rule is per check. The catalog "Position" column uses these labels | `file-size` | head (first 30 lines) | [test_python_file_size.py](../../../../tests/lint/repository/structure/test_python_file_size.py) | Opts the entire `.py` file out of the 500-line cap. | | `comments-valid` | head (first 30 lines) | [test_comments_valid.py](../../../../tests/lint/repository/test_comments_valid.py) | Opts the entire file out of the useful-comment check. Reserved for vendored / upstream config templates (e.g. Discourse `app.yml`) whose inline documentation is all intentional. | | `info-media` | head of `meta/main.yml` (first 30 lines) | [test_info_homepage_video.py](../../../../tests/lint/ansible/roles/meta/test_info_homepage_video.py) | Opts an invokable role out of the required `meta/info.yml` `homepage` + `video` entries. Marker lives in `meta/main.yml` (a comment-only `info.yml` would fail the info schema lint). Reserved for fully self-written roles (backups, host plumbing) that have no upstream product page or demo video. | +| `credential-masking` | same or above | [test_credential_tasks_are_masked.py](../../../../tests/lint/ansible/modules/test_credential_tasks_are_masked.py) | Allows the marked task to carry a credential without `no_log` on itself or a parent. Marker goes on or directly above the task's `- name:`. | +| `env-default` | same or above | [test_no_env_defaults_in_javascript.py](../../../../tests/lint/filesystem/env/test_no_env_defaults_in_javascript.py) | Allows JavaScript to substitute a value for an unset environment variable. Reserved for a value the code itself owns and no role renders. Normalising to `""`, `"[]"`, `false`, `0` or another `process.env` entry needs no marker. | +| `jinja-mapping-key` | same or above | [test_no_jinja_in_mapping_keys.py](../../../../tests/lint/ansible/roles/meta/test_no_jinja_in_mapping_keys.py) | Allows a Jinja expression to stand as a mapping key under `roles/*/meta/`. Ansible renders the values of an `include_vars` payload and leaves the keys as written, so the consumer receives the source text. Marker goes on or directly above the line. | +| `host-node-resolver` | same or above | [test_host_node_resolver_is_unconditional.py](../../../../tests/lint/ansible/tasks/test_host_node_resolver_is_unconditional.py) | Allows a conditional `resolve_host_cid` include whose `_HOST_NODE` a `delegate_to` in the same role reads. Marker goes on or directly above the include's `- name:`. | | `project-walk` | same line / span | [test_no_raw_project_walk.py](../../../../tests/lint/filesystem/python/test_no_raw_project_walk.py) | Allows a raw `Path.rglob`, `os.walk`, or `glob.glob` call outside the `utils.cache.files.iter_project_files` contract. | | `cache-read` | same line / span | [test_no_uncached_file_reads.py](../../../../tests/lint/filesystem/python/test_no_uncached_file_reads.py) | Allows a raw `Path.read_text` / `Path.read_bytes` call in `tests/lint/` outside the LRU-cached `utils.cache.files.read_text` contract. | | `lookup-cache-import` | same or above | [test_no_cache_imports_in_lookups.py](../../../../tests/lint/filesystem/python/test_no_cache_imports_in_lookups.py) | Allows a lookup plugin (`plugins/lookup/` or `roles/*/lookup_plugins/`) to import a config-merge function from `utils.cache.applications` / `.domains` / `.users` instead of reaching the SPOT via `lookup_loader.get('applications'/'config'/'domains'/'users')`. Reserved for the SPOT providers (`applications` / `config` / `applications_current_play` / `users` / `domains`) and the raw-volume accessors (`volume` / `nginx`). | @@ -83,6 +89,8 @@ The placement rule is per check. The catalog "Position" column uses these labels | `role-file-spot` | same or above | [test_file_spot.py](../../../../tests/lint/ansible/roles/test_file_spot.py) | Allows a `.py` file to carry a literal role-file path instead of the matching `ROLE_FILE_*` constant from `utils.roles.mapping`. Reserved for tests asserting the constant's value, migration scripts, or doc strings. | | `playwright-service-flag` | comment block above | [test_env_services_match.py](../../../../tests/integration/roles/playwright/test_env_services_match.py) | Exempts a top-level service in `roles//meta/services.yml` from the "must be registered as `_SERVICE_ENABLED=` in `templates/playwright.env.j2`" check. | | `playwright-service-gate` | same or above | [test_spec_env_gates.py](../../../../tests/integration/roles/playwright/test_spec_env_gates.py) | Exempts a `_SERVICE_ENABLED=` line in `roles//templates/playwright.env.j2` from the "must be gated in `files/playwright/playwright.spec.js`" check. | +| `mcp-consumer-services-entry` | head of file | [test_mcp_consumer_services_entry.py](../../../../tests/lint/ansible/services/test_mcp_consumer_services_entry.py) | Exempts a server-capable `roles//meta/mcp.yml` from the "must carry a `"{{ '' in group_names }}"`-gated `services.` entry for every role declaring `mcp_consumer: true`" check. Reserved for a provider that legitimately owns no co-deploy edge to its clients. | +| `mcp-consumer-variant` | head of file | [test_mcp_consumer_variant.py](../../../../tests/lint/ansible/services/test_mcp_consumer_variant.py) | Exempts a server-capable `roles//meta/mcp.yml` from the "must ship one `meta/variants.yml` entry enabling every admitted consumer, with `sso` pinned on, and pulling in a consumer variant that does not pin `sso: false`" check. Reserved for a provider whose pairing is genuinely proven elsewhere. | | `pkgmgr-deprecated` | same or above | [test_pkgmgr_deprecated.py](../../../../tests/lint/repository/dependencies/test_pkgmgr_deprecated.py) | Suppresses the warn-only deprecation notice for `include_role` / `import_role` of `pkgmgr` / `pkgmgr-install`. The check emits a `DeprecationWarning` locally and a GitHub Actions `::warning` annotation in CI. Prefer `pip install ` or `pip install git+`. | | `deprecated-http-header` | same or above | [test_no_deprecated_http_security_headers.py](../../../../tests/lint/repository/network/test_no_deprecated_http_security_headers.py) | Exempts a deprecated `add_header` / `Header set/add` line for `X-Frame-Options` / `X-XSS-Protection` / `X-Download-Options` / `X-Permitted-Cross-Domain-Policies`. Prefer Content-Security-Policy via the role's `meta/server.yml` (`csp.flags` / `csp.whitelist`). | | `container-name` | same or above | [test_mode_incompatible_keys.py](../../../../tests/lint/ansible/jinja/test_mode_incompatible_keys.py) | Allows a raw `container_name:` key in a `roles/*/templates/**/*.j2` template. Default path: route through the generic `compose_only` lookup (`{{ lookup('compose_only', 'container_name', NAME) }}`) so swarm-mode replicas do not collide on the static name. | @@ -94,12 +102,19 @@ The placement rule is per check. The catalog "Position" column uses these labels | `templated-conditional` | same or above | [test_no_templated_conditionals.py](../../../../tests/lint/ansible/test_no_templated_conditionals.py) | Exempts a `when` / `failed_when` / `changed_when` / `until` value that legitimately carries `{{ }}` / `{% %}`. Reserved for genuine edge cases; the default path is a bare expression. Per-item render/apply data guards belong on a `condition:` data field (honored by the sys-svc-compose render helper and `LISTMONK_SETTINGS`), not `when:`. | | `container-address-quote` | same or above | [test_address_never_quoted.py](../../../../tests/lint/ansible/shell/container/test_address_never_quoted.py) | Allows `*_CONTAINER_ADDRESS \| quote` in a role task file. Reserved for sites that never see the swarm `$(...)` fragment (`DEPLOYMENT_MODE == 'compose'`-gated tasks, `compose_mode_force` roles) or consumers that re-evaluate the argument themselves. | | `container-exec-resolver` | same or above; `argv:` target item | [test_exec_uses_resolver.py](../../../../tests/lint/ansible/shell/container/test_exec_uses_resolver.py) | Allows a `container exec` / `container inspect` target that does not route through the `container_address` lookup. Reserved for a container ID already resolved at `delegate_to` runtime (`*_LOCAL_CID`), where the lookup would return a manager-only subshell, and for deliberate bare-name partner probes gated on compose co-location. | +| `container-address-needs-shell` | same or above; `argv:` target item | [test_argv_exec_needs_shell.py](../../../../tests/lint/ansible/shell/container/test_argv_exec_needs_shell.py) | Allows a `container_address`-derived target to be reached from a `command: argv:` list, which runs no shell to evaluate the swarm `$(...)` fragment. Reserved for roles pinned to compose via `compose_mode_force`, where the lookup can only ever yield a bare name. | | `container-inspect-type` | same or above; `argv:` inspect item | [test_inspect_pins_type.py](../../../../tests/lint/ansible/shell/container/test_inspect_pins_type.py) | Allows an untyped `container inspect` under `roles/`. Default path: pin `--type container`, because a role's overlay network carries the same entity name as its main container, so an untyped inspect can resolve the network and report `map has no entry for key "State"`. Use the typed subcommand (`container volume inspect` etc.) when the target genuinely is not a container. | | `container-healthcheck-unused` | same or above the service key or its `healthcheck:` line | [test_container_healthcheck_declared_is_used.py](../../../../tests/lint/ansible/jinja/test_container_healthcheck_declared_is_used.py) | Allows a `services..healthcheck` that no `lookup('container_healthcheck', โ€ฆ)` call renders. Default path: add the lookup to the service block, because an unrendered declaration reads like the service is watched while the compose file carries no probe. Reserved for a call the static resolver cannot attribute โ€” mastodon renders every service through a macro whose `service_name` is a macro parameter. | | `image-healthcheck` | same or above the service key | [test_image_healthcheck_declared.py](../../../../tests/integration/roles/test_image_healthcheck_declared.py) | Allows a `roles/*/meta/services.yml` entry whose image ships no `HEALTHCHECK` to declare none either. Default path: add `healthcheck:` to the entry, because a container without a probe counts as healthy the moment its process starts โ€” which is how a service that came back empty passes a restore drill. Reserved for containers nothing can probe: a one-shot process that exits, or an image with neither a port nor a shell. | | `csp-unsafe` | same line | [test_csp_unsafe_requires_justification.py](../../../../tests/lint/ansible/roles/meta/test_csp_unsafe_requires_justification.py) | Documents an `unsafe-*: true` flag in `roles/*/meta/csp.yml`. MUST be paired with a `Reason:` on the same line naming what breaks without the relaxation. `unsafe-inline` re-admits the inline execution an XSS needs and `unsafe-eval` re-admits string-to-code, so the flag has to be verified against the running app, not copied from another role. | | `min-storage-headroom` | same line OR comment block above key | [test_min_storage_headroom.py](../../../../tests/external/update/docker/test_min_storage_headroom.py) | Allows a `roles/*/meta/services.yml` `min_storage` to exceed the measured compressed size of its own `image:`/`version:` by more than 1 GB. MUST be paired with a `Reason:` on the same comment line naming what occupies the space. Reserved for services whose data volume genuinely dominates the footprint; the default path is to lower the value, because an over-declared budget makes a host look too small and prunes a cache the deploy did not need to lose. | +| `healthcheck-binary` | same or above | [test_healthcheck_binary_on_slim_base.py](../../../../tests/lint/ansible/roles/meta/test_healthcheck_binary_on_slim_base.py) | Exempts a `roles/*/meta/services.yml` healthcheck flavor from the requirement that the role's `files/Dockerfile` install the binary the probe runs, when the service sits on a `-slim` image. MUST name where the binary comes from instead. A `-slim` tag carries the runtime and nothing around it, so `curl` is absent and the probe fails from the first beat; under swarm the task is then reaped with exit 137 and every deployment holding the service in its closure fails on the convergence wait, naming the service rather than the missing binary. | | `galaxy-git-parity` | same or above | [test_galaxy_entries_have_git_source.py](../../../../tests/lint/repository/dependencies/test_galaxy_entries_have_git_source.py) | Exempts a `requirements/requirements.galaxy.yml` collection from the requirement to also carry a `type: git` entry in `requirements/requirements.git.yml`. Reserved for collections that publish no usable git remote; without the git entry a `galaxy.ansible.com` outage fails `make install`, because the fallback in `scripts/install/ansible.sh` cannot resolve the collection either. | +| `loop-var-shadow` | same or above | [test_loop_var_shadowing.py](../../../../tests/lint/ansible/tasks/test_loop_var_shadowing.py) | Allows a `loop_var` to take the name of a variable declared in `group_vars/**` or in a role's `vars`/`defaults`. Inside the loop that name carries the item, so every lookup, template and nested include reading it sees the item instead, and ansible only warns. Reserved for a loop whose body reads the name as the item on purpose, typically because the item IS that value: state which meaning the body relies on. | +| `firewall-fragment-accept` | same or above | [test_firewall_fragment_verdicts.py](../../../../tests/lint/ansible/jinja/test_firewall_fragment_verdicts.py) | Allows a rule in a `roles/*/templates/nftables.conf.j2` fragment to end in an `accept` verdict. Default path: express the intent as a `drop` of what must not pass, or put the rule in the chain carrying the policy it has to overrule, because an `accept` terminates only its own base chain and every other chain at that hook still runs, docker's `drop` policy on forwarded packets included. Reserved for an accept whose only job is to skip the fragment's own later rules. | +| `shell-template` | head (first 30 lines) | [test_no_shell_templates.py](../../../../tests/lint/filesystem/shell/test_no_shell_templates.py) | Allows a `*.sh.j2` to exist. Default path: ship the script as a plain `.sh` under `files/shell/` and pass its values as `ExecStart` arguments or `Environment=` entries, because shellcheck, the repository's `.sh` guards and every test skip a Jinja template, so nothing reads what actually runs on the host. Reserved for a script whose shape is generated, not just its values. Place the marker BELOW the shebang, never above it, and prefer the Jinja comment form so it does not reach the rendered script. | +| `systemd-via-sys-service` | same or above | [test_systemd_units_via_sys_service.py](../../../../tests/lint/ansible/modules/test_systemd_units_via_sys_service.py) | Allows a role task to render a `*.service.j2` itself instead of handing the unit to `sys-service`. Default path: name the template `templates/systemctl.service.j2` and include `sys-service` with `system_service_id`, so the unit also gets the daemon reload, the enable, and the timer, async and flush behaviour. Reserved for units `sys-service` cannot carry, such as a user-scope unit under `$HOME`. | +| `software-identity` | same or above | [test_software_identity_variables.py](../../../../tests/lint/ansible/jinja/test_software_identity_variables.py) | Allows a `.j2` template to write the software's name, domain or URL as a literal. Default path: render `SOFTWARE_NAME`, `SOFTWARE_DOMAIN`, `SOFTWARE_URL` or `ORGANIZATION`, which `group_vars/all/00_general.yml` declares once and derives from each other, so a rename reaches the template too. Reserved for a literal that must survive a rename, such as an identifier a third party issued under the old name. | ## Tool-Native `noqa` Codes ๐Ÿงน diff --git a/docs/contributing/artefact/files/plugins/lookup/applications.md b/docs/contributing/artefact/files/plugins/lookup/applications.md index 58186bf903..c051176c84 100644 --- a/docs/contributing/artefact/files/plugins/lookup/applications.md +++ b/docs/contributing/artefact/files/plugins/lookup/applications.md @@ -18,6 +18,7 @@ The `applications` lookup is the ONLY supported runtime entry point for merged a | `lookup('applications')` | Full merged mapping keyed by `application_id`. | | `lookup('applications', '')` | Merged entry for that application. Raises when missing. | | `lookup('applications', '', default_value)` | Merged entry, or `default_value` when the entry is missing. | +| `lookup('applications', carrier=True)` | `{"key": [...], "applications": {...}}`: the full mapping plus the cache key it is valid under. Reserved for the constructor's carrier task (see below). | ## Data Sources ๐Ÿ“š @@ -26,7 +27,19 @@ The lookup merges exactly two sources: 1. **Defaults** discovered from each role's per-topic meta files: `roles/*/meta/server.yml`, `roles/*/meta/rbac.yml`, `roles/*/meta/services.yml`, `roles/*/meta/volumes.yml`, plus `roles/*/meta/secrets.yml` (post-`apply_schema()`). Variants from `roles/*/meta/variants.yml` deep-merge over the assembled per-role payload. See [layout.md](../../../../design/role/services/layout.md). 2. **Overrides** supplied through the normal Ansible variable `applications` in inventory, group vars, host vars, or role vars. -No intermediate merged `applications` fact exists. No other source is consulted. +No other source is consulted. + +## Play-Scoped Carrier ๐ŸงŠ + +Ansible forks a fresh worker process for every task. The in-process cache inside `get_merged_applications` therefore never survives from one task to the next, and every task that touches the lookup would render the full tree again (about 16 to 23 seconds per task on a CI runner, measured on the workspace jobs). + +The constructor stage renders once through the [applications_carrier](../../../../../../plugins/action/applications_carrier.py) action and parks the result together with its cache key in the host fact `_INFINITO_APPLICATIONS_RENDERED` (the action calls `lookup('applications', carrier=True)`). Every later worker inherits that fact at fork time; `get_merged_applications` serves it whenever the key still matches and renders only when it does not (a changed `applications`, `users`, `DOMAIN_PRIMARY` or `SYSTEM_EMAIL_DOMAIN`). + +- The task sits in `tasks/stages/01_constructor.yml` after the `networks`, `design` and `service_provider` merges, after the `add_host` placements and after the token store, so the payload renders with the same `group_names`, `groups` and user records a role would see. Moving it earlier bakes stale values into the play. +- The action masks its own result: the fact is the whole rendered tree with every application's credentials, so it never reaches a log regardless of `MASK_CREDENTIALS_IN_LOGS`. +- User records inside the payload are the token store's state at render time. Readers of tokens captured later in the play MUST go through `lookup('users', ...)` or `lookup('config', , 'users....')`, both of which read the users cache fresh. +- The carrier is private to the lookup. Consumers MUST NOT read `_INFINITO_APPLICATIONS_RENDERED`; they keep going through `lookup('applications')`, which is what makes the carrier transparent. +- The carrier is the only materialised merged view a play MAY hold. The rule against a top-level `applications` fact above is unchanged. ## Adding an Application Entry โž• @@ -69,6 +82,7 @@ applications: |---|---| | [applications.py](../../../../../../plugins/lookup/applications.py) | Runtime entry point for the `applications` lookup. | | [applications.py (cache)](../../../../../../utils/cache/applications.py) | Shared aggregation helper that builds and caches defaults (`get_application_defaults`, `get_variants`, `get_merged_applications`). | +| [carrier.py](../../../../../../utils/cache/carrier.py) | The play-scoped carrier: fact name, `merged_applications_cache_key`, and the reader that serves the carried payload. | | [test_applications.py](../../../../../../tests/unit/python/plugins/lookup/test_applications.py) | Unit tests covering the full-dict, single-entry, override, strict missing, and non-strict missing cases. | For the related users pattern see [users.md](users.md). diff --git a/docs/contributing/design/deployment-modes.md b/docs/contributing/design/deployment-modes.md index 49978b232b..3b0aa59547 100644 --- a/docs/contributing/design/deployment-modes.md +++ b/docs/contributing/design/deployment-modes.md @@ -81,24 +81,27 @@ future sticky sessions) is uniform across both modes. ## Volume model -Storage backing is **per-volume opt-in**, declared on the volume itself. -Default: `nfs: false` (local Docker volume). +Storage backing is derived from the role's placement, not declared per +volume. An unpinned role's volumes are rendered onto the shared export; a +`placement: manager` role keeps them node-local. -| Mode | `storage.backend` | Per-volume `nfs` | Rendered as | -| ------- | ----------------- | ---------------- | -------------------------------------- | -| compose | any | any | local docker volume (today's shape) | -| swarm | `nfs` | `true` | NFS driver block (multi-node accessible) | -| swarm | `nfs` | `false` | local + service pinned to single node | -| swarm | `local` | any | local + service pinned to single node | +| Mode | `storage.backend` | Role placement | Rendered as | +| ------- | ----------------- | -------------- | ---------------------------------------- | +| compose | any | any | local docker volume (today's shape) | +| swarm | `nfs` | unpinned | NFS driver block (multi-node accessible) | +| swarm | `nfs` | `manager` | local docker volume, node-local | +| swarm | `local` | any | local docker volume, node-local | -A service with any non-NFS volume under swarm mode MUST receive a -`deploy.placement.constraints` rule pinning it to a single node. The -deploy MUST NOT silently lose data on reschedule. +A volume whose payload cannot tolerate NFS semantics opts out with +`nfs: false` plus a justification, which keeps engine state local without +pinning the whole role. The deploy MUST NOT silently lose data on +reschedule. -DB volumes (MariaDB, Postgres) are intentionally left at the -`nfs: false` default. NFS for databases is documented in 023's -Future Extensions as out of scope for v1 because of well-known -locking / `fsync` semantics issues. +State that several replicas would write to the same file needs more than +node-local storage: pair `nfs: false` with a single replica or a manager +pin, or externalise the state into a database. The +`embedded-state-on-nfs` lint enforces this for roles that run no RDBMS of +their own. ## Network model diff --git a/docs/contributing/design/inventory.md b/docs/contributing/design/inventory.md index df209921ff..e37266dbbf 100644 --- a/docs/contributing/design/inventory.md +++ b/docs/contributing/design/inventory.md @@ -47,6 +47,8 @@ Rendering happens at **play runtime**, never during the build pipeline above. Th `get_merged_applications` is invoked transitively by `lookup('applications', ...)` and by `lookup('config', application_id, 'services..')`. Tasks that read service flags through these lookups always see real Python values, never raw Jinja strings. +The render runs once per play. The constructor stage parks the payload and its cache key in the host fact `_INFINITO_APPLICATIONS_RENDERED`, and every task's worker process (Ansible forks one per task) serves that payload instead of rendering again. See [applications.md](../artefact/files/plugins/lookup/applications.md) for the carrier contract. + A role's task that reads its own service flag therefore picks up the runtime-resolved value, even when the inventory carried a Jinja string for that flag: the conditional evaluates against the play's actual `group_names`, which reflects which other application groups the host joined. ## Interaction between the three inclusion mechanisms ๐Ÿงฌ diff --git a/docs/contributing/design/role/services/README.md b/docs/contributing/design/role/services/README.md index b0d786b24c..8c37f04f1e 100644 --- a/docs/contributing/design/role/services/README.md +++ b/docs/contributing/design/role/services/README.md @@ -12,3 +12,5 @@ and consumers MUST follow. | [layout.md](layout.md) | Per-role `meta/.yml` shape, file-root convention, services-inlining rule, `meta/secrets.yml` (incl. the `default:` field), per-role `networks:` and per-entity `ports` shape, `run_after`/`lifecycle` placement. | | [base.md](base.md) | Service registration, discovery, load order, injection model, lookup plugins. | | [email.md](email.md) | `email` lookup plugin contract. | +| [mcp.md](mcp.md) | `mcp` service block: fields, allowed values, endpoint metadata, client discovery. | +| [lifecycle.md](lifecycle.md) | Role lifecycle stages and what each one promises. | diff --git a/docs/contributing/design/role/services/layout.md b/docs/contributing/design/role/services/layout.md index 3ac1b7c16e..809303a385 100644 --- a/docs/contributing/design/role/services/layout.md +++ b/docs/contributing/design/role/services/layout.md @@ -87,6 +87,8 @@ The unified schema supports: - **Nested keys.** Both flat and nested credential keys are accepted, so e.g. `recaptcha.key` and `recaptcha.secret` remain nested. - **`algorithm:` defaults to `plain`** when the field is omitted. +- **`type:` (optional)** is one of `string`, `integer`, `boolean`. A supplied value of another type aborts inventory creation. +- **`regex:` (optional)** is a pattern the supplied value MUST match in full (`re.fullmatch`). Anchors are implicit; `sk-[A-Za-z0-9]{16,}` needs no `^` or `$`. - **`default:` (optional)** is a Jinja string used as the credential's value when the inventory does not provide one. - `default:` is **NOT rendered at inventory creation time.** The literal Jinja string is written verbatim into the inventory so that referenced variables (`CAPTCHA.RECAPTCHA.KEY`, `lookup(...)`, โ€ฆ) resolve only at deploy/runtime when those variables are actually defined. - `default:` values are **NOT validated.** `validation:` only applies to user-provided values, so the schema default is exempt. @@ -108,6 +110,58 @@ credentials: default: "{{ CAPTCHA.RECAPTCHA.SECRET | default('') }}" ``` +### What is checked, and when ๐Ÿ”Ž + +`type:` and `regex:` are enforced by `validate_supplied_value()` in +[inventory.py](../../../../../utils/manager/inventory.py) at inventory-creation +time, on every path where a value arrives from outside: + +| Source | Checked | +|---|---| +| `--set applications..secrets.credentials.=` | yes | +| A value already present in the inventory | yes | +| The literal written from `default:` | no | +| A value produced from `algorithm:` | no | + +A generated value is exempt because the algorithm that produced it is named by +the same schema, and `generate_value()` takes no schema argument. + +An empty string means "not configured" and passes every check, which is what +makes an optional provider key expressible: declare the shape, leave the value +empty, and the consumer gates on emptiness. + +`validation.min_length` is declared in many role schemas but enforced nowhere. +Do not read it as a guarantee. + +### Worked Example: an optional external key + +```yaml +# roles/svc-ai-litellm/meta/secrets.yml +credentials: + openai_api_key: + description: "OpenAI API key; empty leaves the openai/* models unpublished" + type: "string" + regex: "\\S{20,}" + default: "{{ API.openai.api_key }}" +``` + +The `default:` points at the central `API` block in +[group_vars/all/18_api.yml](../../../../../group_vars/all/18_api.yml), so an +operator fills the provider in one place while the role keeps the shape the +value must have. + +### Write a pattern for the paste, not for the vendor ๐Ÿšซ + +`regex:` MUST NOT pin a vendor's key prefix. OpenAI moved issuance from `sk-` to +`sk-proj-` without notice, and Anthropic issues `sk-ant-api03-`; a schema that +encoded either would reject a valid key and abort inventory creation, which is a +hard failure for a value that was correct. + +Write the pattern against the mistakes a paste makes โ€” a trailing newline, an +embedded space, a truncated copy, a `` โ€” and leave the provider's +format alone. A key pasted into the wrong provider's slot is not caught here; +it is caught at deploy time, where the route it publishes answers nothing. + Flat schema entries keep the same shape: ```yaml @@ -159,6 +213,8 @@ All port data lives under `.ports` in `meta/services.yml` (no `ports:` s relay: # for port-ranges (coturn, BBB, nextcloud TURN) start: end: + onion: + : # forward this category over the node onion ``` ### `internal` / `local` / `public` Split ๐Ÿงญ @@ -168,6 +224,7 @@ All port data lives under `.ports` in `meta/services.yml` (no `ports:` s | `internal` | **Internal container port.** Lives inside the container's network namespace, addressed by other containers on the same role-local network. NOT a host-bound port. Multiple roles MAY legitimately declare the same value (e.g. several nginx-based apps with `internal: { http: 80 }`). | | `local` | **Localhost-bound host port.** Bound on `127.0.0.1` and only reachable through the front-proxy / SSH tunnels. The OS-level binding namespace is shared across all roles, so `local` values MUST be unique across the whole repo. | | `public` | **Public-facing host port.** Bound on `0.0.0.0` and exposed to the public internet (or to whatever the operator's firewall allows). Same uniqueness rule as `local`. | +| `onion` | **Onion opt-in, not a port.** A category-keyed map of booleans naming which of the entity's own categories get a `HiddenServicePort` on the node onion. It declares no numbers: the port is read from `local` when the category is declared there and from `public` otherwise, matching what `container_ports` publishes. Collision detection ignores it. | ### Always Category-Keyed Maps ๐Ÿ—‚๏ธ @@ -202,6 +259,34 @@ coturn: end: 39999 ``` +### `onion` Forwarding Opt-In ๐Ÿง… + +`ports.onion` names the categories that answer on the node onion. Only the named +categories are forwarded. + +The flag is mandatory, enforced by [test_onion_port_flag.py](../../../../../tests/lint/ansible/services/test_onion_port_flag.py): +every category declared under `local` or `public` needs a `true` or a `false`, +and every `false` needs `# nocheck: onion-flag` plus the reason it is false. +Four groups are settled centrally instead and take no flag: the categories a +hidden service cannot carry (`relay`, `media`, `stun_turn`, `stun_turn_tls`), +the proxy-fronted `http`, `sso` and `websocket`, the implicit-TLS variants +(`smtps`, `imaps`, `pop3s`, `ldaps`), and any entity that already answers the +question through `exposed:`. + +```yaml +mailu: + ports: + public: + smtp: 25 + smtps: 465 + imap: 143 + onion: + smtp: true # 25 gets a HiddenServicePort; 465 and 143 do not +``` + +The forward is per-variant: `meta/variants.yml` may drop the flag, and the role +then loses the `HiddenServicePort` in that variant. + ### Multi-Entity Roles ๐ŸŽ›๏ธ Each entity carries its own `ports` block: diff --git a/docs/contributing/design/role/services/mcp.md b/docs/contributing/design/role/services/mcp.md new file mode 100644 index 0000000000..a9bd7b7376 --- /dev/null +++ b/docs/contributing/design/role/services/mcp.md @@ -0,0 +1,131 @@ +# MCP Service Block ๐Ÿ”Œ + +A role declares `meta/mcp.yml` when it actually serves or consumes MCP. The file is a capability descriptor, not a service entry: no single role provides MCP, so the service registry cannot pair provider and consumer, and the `mcp_consumer` flag in `meta/services.yml` does it instead. Vocabulary lives in [`utils/roles/applications/mcp.py`](../../../../../utils/roles/applications/mcp.py); the hard lint is [`test_mcp_schema.py`](../../../../../tests/lint/ansible/services/test_mcp_schema.py). + +`classification` is required and is one of `native_server`, `native_client`, `native_both`, `plugin_server`, `sidecar_server`, `adapter_server`. A role that cannot serve declares no `mcp` block at all. + +## Server shape + +```yaml +mcp: + bond: 1 + classification: native_server + direction: server # server | client | both + transport: sse # streamable_http | sse + exposure: internal # internal | public + auth: app_password # oidc | app_password | basic_auth | bearer_token | upstream_session | none + auth_subject: service_account # user | service_account | administrator | none + implementation: native # native | plugin | sidecar | adapter | external + credential: + owner: mcp-web-app-example # a dedicated non-login identity, never `administrator` + source: token_store # token_store | credentials + key: web-app-example + endpoint: + service_key: example # names a service entry in the same file + path: /mcp + port_key: http # resolves under that service's ports.local or ports.internal + host_header: true # optional; set it when the endpoint sits behind the role's own vhost + tools: + read_only_default: true + mutating_tools_enabled: false +``` + +`exposure: public` additionally requires a complete `limits` block. + +## Client shape + +A client declares what it can present instead of what it serves: + +```yaml +mcp: + classification: native_client + direction: client + implementation: native + supported_transports: [streamable_http, sse] + supported_auths: [bearer_token, app_password, upstream_session] +``` + +A client-only block MUST NOT declare an `endpoint`. + +## Adapter shape + +`implementation: adapter` requires `classification: adapter_server` and a pinned, hash-checked contract: + +```yaml + adapter: + type: openapi_allowlist # see below + image: registry.example.invalid/infinito-mcp-adapter + version: 1.2.3 + digest: sha256:0123456789abcdef + upstream_api_version: v1 + specification_path: roles/web-app-example/files/mcp/openapi-v1.json + specification_sha256: sha256:fedcba9876543210 + limits: + request_bytes: 65536 + response_bytes: 1048576 + timeout_seconds: 15 + concurrent_requests: 4 + page_size: 100 + result_items: 500 + stream_seconds: 300 + tools: + allowlist: [example_search, example_get] + schema_sha256: sha256:abcdef0123456789 + read_only_default: true + mutating_tools_enabled: false +``` + +`type` is one of `openapi_allowlist`, `graphql_allowlist`, `named_query`, `s3_prefix`, `prometheus_readonly`, `n8n_workflow`, `resource_readonly`. `graphql_allowlist`, `named_query`, `s3_prefix` and `resource_readonly` additionally require a non-empty `adapter.scope` naming the exact buckets, prefixes, collections or queries reachable. `openapi_allowlist` and `graphql_allowlist` require a checked-in `specification_path` under the role's own `files/`. + +## Rules + +- `classification` is required and MUST be deployable; all MCP-specific fields MUST be literals (only `enabled`/`shared` may carry Jinja). +- `enabled`/`shared` are omitted. [`utils/cache/applications.py`](../../../../../utils/cache/applications.py) derives both from the admitted clients as `"{{ '' in group_names or โ€ฆ }}"`, and `false` when no client is admitted, so a surface is reachable exactly while a peer that uses it is deployed. Write either key to override that: a value in `meta/variants.yml` wins over one in `meta/mcp.yml`, and both win over the derivation. Do not hand-write a `group_names` gate: it is a second source for the derived fact and drifts when an edge changes. +- `direction: server | both` requires `auth`, `credential`, a complete `endpoint`, and at least one admitted client. +- Admission lives in `meta/services.yml`, not here. A client sets `services..mcp_consumer: true` in its own role; a provider refuses one by setting `mcp_consumer: false` on that client's entry. [`test_mcp_consumer_services_entry.py`](../../../../../tests/lint/ansible/services/test_mcp_consumer_services_entry.py) requires every provider to carry a `"{{ '' in group_names }}"`-gated entry for every declared client, so a round plans provider and client together. +- `credential.owner` MUST NOT be `administrator`. Two providers resolving to the same owner and secret abort discovery. +- `auth: none` requires `exposure: internal`. +- `auth_subject: service_account | administrator` requires an explicit `tools.mutating_tools_enabled: false`. +- `auth_subject: user` or `auth: oidc` requires a `delegation` block; see [delegation.md](mcp/delegation.md). +- `endpoint.service_key` MUST name a service in the same file; `endpoint.port_key` MUST resolve under its `ports.local` or `ports.internal`. +- Suppress a finding with `# nocheck: mcp-schema` (file head = whole file, on/above a line = that finding). + +## Public exposure + +`exposure: public` puts the endpoint on the role's own vhost, so it inherits what that vhost already provides: routing through the shared proxy, TLS from the platform certificate, `client_max_body_size` from `server.client_max_body_size`, and the proxy read timeout of the location it is mounted in. + +Rate limiting is not among them. The proxy ships no `limit_req` or `limit_conn` anywhere, so a public MCP endpoint is only as protected as its own authentication and its declared `limits`. An operator exposing one to the open internet has to put a rate limiter in front of the vhost; the platform will not supply one. + +Prefer `exposure: internal`. A client inside the container network reaches the endpoint without any of this. + +## Why stdio is not deployed + +`transport` accepts `streamable_http` and `sse` only. A stdio MCP server is a local process the client spawns, so it inherits the client container's filesystem and network with no endpoint to authenticate, no proxy to route through, and nothing for a probe to reach. Every property the other rules rely on (`auth`, `exposure`, `endpoint`) is undefined for it. Clients that support stdio are pinned away from it in their own role: Flowise sets `CUSTOM_MCP_PROTOCOL=sse` so no flow can spawn a command. + +## Client discovery + +Clients do not read the server list directly. [`lookup('mcp_servers')`](../../../../../plugins/lookup/mcp_servers.py) computes the intersection of the provider's admitted clients, resolved by `derive_allowed_consumers` in [`utils/roles/applications/mcp.py`](../../../../../utils/roles/applications/mcp.py), with the calling client's `supported_transports` and `supported_auths`, resolves each provider's declared credential, and returns: + +```yaml +MCP_DISCOVERY: "{{ lookup('mcp_servers') }}" +MCP_DISCOVERED_SERVERS: "{{ MCP_DISCOVERY.selected }}" +MCP_REJECTED_SERVERS: "{{ MCP_DISCOVERY.rejected }}" +``` + +Every rejected entry carries a stable `reason`: `consumer_not_allowed`, `transport_unsupported`, `auth_unsupported`, `credential_missing` or `endpoint_unreachable`. + +## RBAC + +Reaching a tool server is a distinct grant from using the application, carried by the provider's `mcp` RBAC role. `mcp` is application-scoped: it is granted through `application_roles`, never through the unscoped `roles` list, so granting it on one application grants it nowhere else. + +```yaml +users: + alice: + application_roles: + web-app-baserow: [mcp] +``` + +## See Also + +- Service metadata basics: [base.md](base.md) +- User delegation audit: [delegation.md](mcp/delegation.md) diff --git a/docs/contributing/design/role/services/mcp/audit.md b/docs/contributing/design/role/services/mcp/audit.md new file mode 100644 index 0000000000..f9b15c0fa0 --- /dev/null +++ b/docs/contributing/design/role/services/mcp/audit.md @@ -0,0 +1,38 @@ +# 035 - MCP Audit Report + +Generated by `make mcp-audit`; do not edit by hand. +Run that script from the repository root and commit the result. + +One row per role that owns `meta/mcp.yml`. The disposition of every other +role lives in the audit lists of the MCP proxy-expansion requirement. + +`version` is the version the role deploys, read from its own `meta/services.yml`, +not the version the MCP surface was verified against. +`tools` counts the allowlist entries; the names themselves stay in the role. + +| role | version | source | transport | auth | subject | scope | tools | implementation | consumers | blocker | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | +| `svc-db-qdrant` | v1.19.1 | [link](https://s.infinito.nexus/code) | streamable_http | bearer_token | service_account (`mcp-svc-db-qdrant`) | read-only | 2 | adapter | `web-app-flowise`, `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-baserow` | 2.3.3 | [link](https://baserow.io/user-docs/mcp-server) | streamable_http | bearer_token | service_account (`mcp-web-app-baserow`) | read-only | 4 | adapter | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-checkmk` | 2.4.0p32 | [link](https://s.infinito.nexus/code) | streamable_http | bearer_token | service_account (`mcp-web-app-checkmk`) | read-only | 3 | adapter | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-fider` | stable | [link](https://s.infinito.nexus/code) | streamable_http | bearer_token | service_account (`mcp-web-app-fider`) | read-only | 3 | adapter | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-flowise` | 24-slim | [link](https://github.com/FlowiseAI/Flowise/tree/flowise%403.1.4/packages/server/src/routes/custom-mcp-servers) | โ€” | โ€” | โ€” | read-only | โ€” | native | โ€” | โ€” | +| `web-app-gitea` | 1.27.3 | [link](https://pkg.go.dev/gitea.com/gitea/gitea-mcp) | streamable_http | bearer_token | service_account (`mcp-web-app-gitea`) | read-only | 24 | adapter | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-gitlab` | โ€” | [link](https://docs.gitlab.com/user/gitlab_duo/model_context_protocol/mcp_server/) | streamable_http | bearer_token | service_account (`mcp-web-app-gitlab`) | read-only | 14 | adapter | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-hermes` | v2026.9.7 | [link](https://hermes-agent.nousresearch.com/) | โ€” | โ€” | โ€” | read-only | โ€” | native | โ€” | โ€” | +| `web-app-homeassistant` | 2026.7 | [link](https://www.home-assistant.io/integrations/mcp_server/) | streamable_http | bearer_token | service_account (`mcp-web-app-homeassistant`) | read-only | 10 | native | `web-app-flowise`, `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-jellyfin` | 10.11.11 | [link](https://s.infinito.nexus/code) | streamable_http | bearer_token | service_account (`mcp-web-app-jellyfin`) | read-only | 3 | adapter | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-jenkins` | 2.568.3-lts | [link](https://plugins.jenkins.io/mcp-server/) | streamable_http | bearer_token | service_account (`mcp-web-app-jenkins`) | read-only | 15 | adapter | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-listmonk` | v6.2.0 | [link](https://s.infinito.nexus/code) | streamable_http | bearer_token | service_account (`mcp-web-app-listmonk`) | read-only | 3 | adapter | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-mattermost` | 11.11.0 | [link](https://github.com/mattermost/mattermost-plugin-agents/blob/master/mcpserver/README.md) | streamable_http | bearer_token | service_account (`mcp-web-app-mattermost`) | read-only | 11 | adapter | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-moodle` | 8.3-fpm | [link](https://moodle.org/plugins/webservice_mcp) | streamable_http | bearer_token | service_account (`mcp-web-app-moodle`) | read-only | 5 | plugin | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-n8n` | 1.100.1 | [link](https://github.com/n8n-io/n8n/tree/n8n%401.100.1/packages/%40n8n/nodes-langchain/nodes/mcp) | streamable_http | bearer_token | service_account (`mcp-web-app-n8n`) | read-only | 1 | native | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-nextcloud` | 34-fpm-alpine | [link](https://docs.nextcloud.com/server/latest/admin_manual/ai/app_context_agent.html) | streamable_http | bearer_token | service_account (`mcp-web-app-nextcloud`) | read-only | 9 | adapter | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-openclaw` | 2026.7.1 | [link](https://openclaw.ai/) | โ€” | โ€” | โ€” | read-only | โ€” | native | โ€” | โ€” | +| `web-app-openwebui` | 0.11.0 | [link](https://docs.openwebui.com/features/extensibility/mcp/) | โ€” | โ€” | โ€” | read-only | โ€” | native | โ€” | โ€” | +| `web-app-pretix` | 2026.7.0 | [link](https://s.infinito.nexus/code) | streamable_http | bearer_token | service_account (`mcp-web-app-pretix`) | read-only | 3 | adapter | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-prometheus` | v3.14.0 | [link](https://s.infinito.nexus/code) | streamable_http | bearer_token | service_account (`mcp-web-app-prometheus`) | read-only | 3 | adapter | `web-app-flowise`, `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-snipe-it` | โ€” | [link](https://s.infinito.nexus/code) | streamable_http | bearer_token | service_account (`mcp-web-app-snipe-it`) | read-only | 3 | adapter | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-app-wordpress` | 7.1.0 | [link](https://github.com/WordPress/mcp-adapter/tree/v0.5.0) | streamable_http | basic_auth | service_account (`mcp-web-app-wordpress`) | read-only | 3 | plugin | `web-app-hermes`, `web-app-openclaw` | โ€” | +| `web-app-zammad` | 7.1.2 | [link](https://s.infinito.nexus/code) | streamable_http | bearer_token | service_account (`mcp-web-app-zammad`) | read-only | 3 | adapter | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | +| `web-svc-libretranslate` | v1.9.6 | [link](https://s.infinito.nexus/code) | streamable_http | bearer_token | service_account (`mcp-web-svc-libretranslate`) | read-only | 2 | adapter | `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui` | โ€” | diff --git a/docs/contributing/design/role/services/mcp/delegation.md b/docs/contributing/design/role/services/mcp/delegation.md new file mode 100644 index 0000000000..7fe91b0607 --- /dev/null +++ b/docs/contributing/design/role/services/mcp/delegation.md @@ -0,0 +1,68 @@ +# MCP User Delegation ๐Ÿชช + +`auth_subject: user` and `auth: oidc` claim that an MCP call executes with the +requesting end user's permissions. A `delegation:` block records the audit that +backs the claim; without it, +[`test_mcp_schema.py`](../../../../../../tests/lint/ansible/services/test_mcp_schema.py) +rejects the role. + +## Declaring it + +```yaml +mcp: + auth: oidc + auth_subject: user + delegation: + verified_version: 1.2.3 + source_url: https://example.invalid/project/tree/v1.2.3/path/to/auth + refresh: true + revocation: true + audience_binding: true +``` + +All three booleans MUST be `true`, and `verified_version` MUST name the exact +tag or digest the source was read at. A newer upstream release is not evidence +for the deployed pin. + +## Client audit + +| Client | Pin | Delegation | Evidence | +|---|---|---|---| +| `web-app-openwebui` | 0.11.0 | capable | `ToolServerConnection.auth_type: system_oauth` resolves the caller's token through `oauth_manager.get_oauth_token(user.id, oauth_session_id)` and presents it as the Bearer | +| `web-app-hermes` | v2026.7.20 | incapable | [`config.yaml.j2`](../../../../../../roles/web-app-hermes/templates/config.yaml.j2) renders one static `Authorization` header per server; no user session exists at render time | +| `web-app-openclaw` | 2026.7.1 | incapable | [`openclaw.json.j2`](../../../../../../roles/web-app-openclaw/templates/openclaw.json.j2) renders one static `Authorization` header per server | +| `web-app-flowise` | 3.1.3 | incapable | Registry entries bind to a workspace and store one encrypted custom header, not a per-user token | + +## Provider audit + +| Provider | Pin | Delegation | Evidence | +|---|---|---|---| +| `web-app-baserow` | 2.3.1 | incapable | The endpoint authenticates a Baserow app password bound to the endpoint owner | +| `web-app-gitea` | sidecar | incapable | The sidecar authenticates a Gitea token | +| `web-app-gitlab` | 18.x | incapable | The endpoint authenticates a GitLab PAT or GitLab-issued OAuth token, not a platform OIDC access token | +| `web-app-homeassistant` | 2026.7 | incapable | The endpoint authenticates a Home Assistant long-lived access token | +| `web-app-jenkins` | plugin | incapable | The endpoint authenticates Jenkins basic auth | +| `web-app-mattermost` | plugin | incapable | The endpoint authenticates a Mattermost bot token | +| `web-app-moodle` | plugin | incapable | The endpoint authenticates a Moodle web-service token | +| `web-app-nextcloud` | ExApp | incapable | The endpoint authenticates a Nextcloud app password bound to one user | + +No pair of a capable client and a capable provider exists at the current pins, +so every provider declares `auth_subject: service_account`. + +## The renderable path + +`svc-ai-mcp-adapter` validates the platform's OIDC access token, so an +adapter-backed provider is the one surface that can declare +`auth: oidc` with `auth_subject: user`. Only Open WebUI can consume it: + +- [`mcp_authorization`](../../../../../../plugins/filter/mcp/authorization.py) + raises for `auth: oidc`, because a rendered config cannot carry a caller's + token, and `mcp_authorization_is_renderable` returns `false` so the + static-config clients drop the server instead of presenting a wrong secret. +- [`mcp_tool_server_connections`](../../../../../../plugins/filter/mcp/tool_server_connections.py) + emits `auth_type: system_oauth` with an empty `key` for those servers, so + Open WebUI resolves the caller's own token per request. + +## See Also + +- Service block vocabulary: [mcp.md](../mcp.md) diff --git a/docs/contributing/environment/cache.md b/docs/contributing/environment/cache.md index d7fabe358a..dda4466e8d 100644 --- a/docs/contributing/environment/cache.md +++ b/docs/contributing/environment/cache.md @@ -16,8 +16,8 @@ Pulls only. Pushes are not intercepted. | Format | Repo names | Upstream | |---|---|---| -| `apt` | `apt-debian`, `apt-debian-security`, `apt-ubuntu`, `apt-ubuntu-security` | `deb.debian.org`, `archive.ubuntu.com`, `security.ubuntu.com` | -| `apt` (mirrors) | `apt-debian-mirror`, `apt-debian-security-mirror`, `apt-ubuntu-mirror`, `apt-ubuntu-security-mirror` | `ftp.debian.org`, `security.debian.org`, `de.archive.ubuntu.com` | +| `apt` | `apt-debian`, `apt-debian-security`, `apt-ubuntu`, `apt-ubuntu-security` | `deb.debian.org`; both Ubuntu repos take the first entry of `INFINITO_APT_UBUNTU_MIRRORS` | +| `apt` (mirrors) | `apt-debian-mirror`, `apt-debian-security-mirror`, `apt-ubuntu-mirror`, `apt-ubuntu-security-mirror` | `ftp.debian.org`, `security.debian.org`; both Ubuntu repos take the second entry of `INFINITO_APT_UBUNTU_MIRRORS` | | `pypi` | `pypi-proxy` | `pypi.org` (incl. `files.pythonhosted.org`) | | `npm` | `npm-proxy` | `registry.npmjs.org` | | `rubygems` | `gem-proxy` | `rubygems.org` | @@ -28,7 +28,7 @@ Pulls only. Pushes are not intercepted. A proxy repo that holds a cached copy serves it when its remote is unreachable, regardless of `metadataMaxAge` (measured). `autoBlock` is therefore off: while a remote is auto-blocked Nexus answers `404 Remote Auto Blocked` instead of falling back to that cached copy. The mirror repos below only come into play when nothing is cached either. -Every apt suite exists twice, once per upstream mirror. Nexus has no group repository type for `apt` (only maven, raw, docker, yum, npm, pypi, rubygems, go and friends), so the failover lives in the frontend: a request that the primary repo answers with `502`/`503`/`504` is re-run against the `-mirror` repo, which proxies a different host. `404` deliberately does not retry, because a missing file is missing on both mirrors and apt probes for missing files often. +Every apt suite exists twice, once per upstream mirror. Nexus has no group repository type for `apt` (only maven, raw, docker, yum, npm, pypi, rubygems, go and friends), so the failover lives in the frontend: a request that the primary repo answers with `502`/`503`/`504` is re-run against the `-mirror` repo, which proxies a different host. `404` deliberately does not retry, because a missing file is missing on both mirrors and apt probes for missing files often. The frontend waits at most 8 s for a primary before it re-runs the request against the mirror; the `-mirror` locations keep the global 300 s. Bootstrap is idempotent and runs from [package.sh](../../../scripts/docker/cache/package.sh) once the stack is healthy. diff --git a/docs/contributing/tools/agents/cheatsheet.md b/docs/contributing/tools/agents/cheatsheet.md index 2456f72e73..9ebae273cd 100644 --- a/docs/contributing/tools/agents/cheatsheet.md +++ b/docs/contributing/tools/agents/cheatsheet.md @@ -27,6 +27,8 @@ from its procedure file. Run `make install-skills` to (re)install them. | Running the quality gate (`make quality`) to green | `i8-quality` | | Running the full gate (`make quality-high`: quality plus every lint) to green | `i8-quality-high` | | Cleaning up code, docs, or roles after a change | `i8-refactor` | +| Checking a branch out into a parallel worktree | `i8-worktree-create` | +| Releasing a parallel worktree and its slot | `i8-worktree-down` | | A GitHub Actions / CI run failed and needs triage | `triage` | | A local deploy is failing on the host | `i8-debug-local` | | Inspecting a `*.log` or `*job-logs.txt` file dropped in the workdir | `i8-debug-log` | diff --git a/docs/contributing/tools/agents/claude/sandbox.md b/docs/contributing/tools/agents/claude/sandbox.md index 5605454f5d..9923b286e7 100644 --- a/docs/contributing/tools/agents/claude/sandbox.md +++ b/docs/contributing/tools/agents/claude/sandbox.md @@ -55,6 +55,7 @@ The agent MAY write to the paths listed in `sandbox.filesystem.allowWrite`. All | `~/.cache/pip` | pip's package cache. Granted because the project's `make install-python` step (transitively invoked by `make test`, which runs as a pre-commit hook) populates this cache; denying it would force every install to redownload from PyPI even when the requirements have not changed. | | `~/.cache/gh` | `gh` CLI's cache directory (HTTP response cache + extension metadata). Granted because every `gh` invocation writes cache entries at startup; denying it would require every `gh` call to be wrapped with an `XDG_CACHE_HOME=/tmp/...` env prefix, which adds a shell shape that falls out of sandbox auto-allow and forces per-subcommand allow entries. Auth tokens are **not** stored here (they live in `~/.config/gh/`, which stays read-only). Persistence trade-off is identical to `~/.cache/pip` / `~/.cache/pre-commit`: cache poisoning, if it occurred, would survive reboots, but API auth is server-side so the blast radius is bounded to wrong-output-to-operator. | | `~/.venvs` | Project-managed Python virtualenvs (notably `~/.venvs/pkgmgr`, the editable-install target for `infinito-nexus` itself). Required so the pre-commit `make test` hook can refresh the editable install of this repository's Python package without hitting `[Errno 30] Read-only file system`. The directory holds only Python interpreters and packages, no host credentials. | +| `~/.local/share/worktrees` | Default parent directory of the branch worktrees created by `make worktree-up`. Granted at the `worktrees` level rather than per repository so the target can create the `//` path it derives from `git remote get-url origin`; without it `mkdir -p` fails with `Read-only file system` before any checkout happens. The directory holds only git checkouts of this repository, no host credentials. | | `~/.ansible` | Ansible's runtime state directory (notably `~/.ansible/tmp/`, where `ansible-galaxy` and other ansible CLIs create per-invocation temp dirs). Required because the pre-commit `make test` flow runs `make install-ansible`, which fails to even initialize the `ansible` Python package without write access here (`DEFAULT_LOCAL_TMP` setup uses `tempfile.mkdtemp` against this path). | Adding entries here widens the agent's effective write scope. New paths SHOULD be justified against the same standard as the existing three (required for normal workflow, no sensitive content, narrow as possible). diff --git a/docs/contributing/tools/github/actions/README.md b/docs/contributing/tools/github/actions/README.md index e06e358fcb..10ddffc8fc 100644 --- a/docs/contributing/tools/github/actions/README.md +++ b/docs/contributing/tools/github/actions/README.md @@ -3,5 +3,6 @@ This directory documents GitHub Actions in this repository. - [workflows.md](workflows.md): catalog of every workflow file under `.github/workflows/`. +- [instructions.md](instructions.md): how the role README's Production block is replayed inside a deploy row. - [configuration.md](configuration.md): repository variables that control CI behaviour. - [secrets.md](secrets.md): repository secrets that workflows consume, and the failure mode when they are missing. diff --git a/docs/contributing/tools/github/actions/configuration.md b/docs/contributing/tools/github/actions/configuration.md index e6d8cd29e8..e3507c7719 100644 --- a/docs/contributing/tools/github/actions/configuration.md +++ b/docs/contributing/tools/github/actions/configuration.md @@ -11,7 +11,34 @@ Repository variables are set under **Settings โ†’ Secrets and variables โ†’ Acti | `CI_SYNC_MAIN_SOURCE_REPOSITORY` | [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml) | Syncs `main` from `infinito-nexus/core` before CI scope discovery | `/` to use another source, or `false`, empty, or the current repository to skip | | `CI_RUN_ON_MAIN` | [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml) | Pushes to `main` skip CI | `true` to run CI on `main` pushes too | | `CI_ENABLE_AUTO_UPDATES` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml) | Update jobs skipped; Dependabot PRs auto-closed | `true` to allow update PRs (workflow-driven and Dependabot) | -| `INFINITO_PLAYWRIGHT_KEEP` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Playwright keeps trace, screenshot and video only when a test fails | `true` to keep them for every test (passing runs included) | +| `PLAYWRIGHT_KEEP_ALL` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Playwright keeps trace, screenshot and video only when a test fails | `true` to keep them for every test (passing runs included); the workflow forwards it as `INFINITO_PLAYWRIGHT_KEEP` | +| `API_OPENAI_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | The gateway publishes no `openai/*` model, and the CLI test asserts their absence | An OpenAI key, to deploy and test the route | +| `API_ANTHROPIC_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | The gateway publishes no `anthropic/*` model | An Anthropic key | +| `API_OPENROUTER_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | The gateway publishes no `openrouter/auto` model | An OpenRouter key | +| `INFINITO_MAIL_PRODUCTION_HOST` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | The read-only production mail assertions are skipped, because the task that runs them is gated on this host being set | The public hostname of a deployed mail server, to assert its MX, SPF, DKIM, DMARC and PTR records and its SMTP greeting after a deploy; nothing is sent and nothing is mutated | +| `INFINITO_MAIL_PRODUCTION_RESOLVER` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Those assertions resolve through the runner's own resolver | A DNS server address, to resolve the records against it instead; ignored while `INFINITO_MAIL_PRODUCTION_HOST` is unset | + +## Provider keys: variable or secret? ๐Ÿ”‘ + +The three `API_*_KEY` entries are read as `${{ secrets.X || vars.X }}`, so a +secret of the same name wins and the variable is the fallback. Prefer the +secret: a repository **variable is not masked**, and the development inventory +sets `MASK_CREDENTIALS_IN_LOGS: false`, so a key supplied as a variable can be +printed by a task that echoes its own arguments. + +An unset key is not an error. The provider's route stays unpublished, the +gateway serves whatever local backend the round deploys, and +[the litellm CLI test](../../../../../roles/svc-ai-litellm/files/test/probe.py) +asserts the absence rather than skipping. + +They travel as `INFINITO_API_OPENAI_KEY`, `INFINITO_API_ANTHROPIC_KEY` and +`INFINITO_API_OPENROUTER_KEY` through the workflow `env:` block, the passthrough +allowlist in [passthrough.py](../../../../../utils/env/handlers/passthrough.py), +the `infinito` service environment in +[compose.yml](../../../../../compose.yml), and land in `API..api_key` +in the development inventory, whose path is the SPOT behind +`INFINITO_INVENTORY_VARS_FILE`. Skipping the compose forwarding makes them +resolve to empty inside the container without any error. ## Cancelling in-progress runs ๐Ÿ›‘ diff --git a/docs/contributing/tools/github/actions/instructions.md b/docs/contributing/tools/github/actions/instructions.md new file mode 100644 index 0000000000..ff2ed50334 --- /dev/null +++ b/docs/contributing/tools/github/actions/instructions.md @@ -0,0 +1,27 @@ +# Instructions replay ๐Ÿ“– + +How CI proves that a role README's `### Production` block still deploys the role. + +For the workflow catalog see [workflows.md](workflows.md). + +## Where it runs ๐Ÿ—๏ธ + +The replay rides along on a deploy row of the sweep instead of holding a job of its own. `utils/roles/guide.py` marks one row per role: + +- the role's **smallest variant**, the one whose `meta/variants.yml` overlay enables the fewest services, because that is the shape the README describes; +- only when the README carries a `### Production` heading; +- only when the guide's own mode (`compose` for a role shipping a container stack, `host` otherwise) is enabled in `meta/services.yml` and not listed under `skip` in `meta/tests.yml`. + +The marked row carries `instructions: ` in the matrix JSON and a ๐Ÿ“– in its job title, between the variant number and the โญ of a priority row. + +## What the row does ๐Ÿš€ + +`.github/workflows/call-test-deploy.yml` runs the replay as the job's last step, after the row's own deploy and after the swarm teardown: the replay deploys the role a second time and needs the runner's ports. It calls `scripts/tests/deploy/distros.sh scripts/github/guide/one.sh` with `GUIDE_ROLE` set to the row's app and `GUIDE_MODE` to the mode the marker carries, which is independent of the deploy mode the rotation gave the row. A swarm row therefore still replays a `compose` guide. + +A red deploy skips the replay: the step carries no `always()`, so the runner state a failed deploy leaves behind never reaches the guide. + +## Reading a failure ๐Ÿ” + +The replay writes its rescue snapshots under `INFINITO_RESCUE_DIAGNOSTICS_BASE//`, uploaded as `rescue-diagnostics-instructions-`. The deploy's own snapshots live in `rescue-diagnostics-`. + +To reproduce one locally, export `GUIDE_ROLE`, `GUIDE_MODE`, `INFINITO_DISTRO` and run `scripts/github/guide/one.sh`. diff --git a/docs/contributing/tools/github/actions/secrets.md b/docs/contributing/tools/github/actions/secrets.md index 6679053894..54cefb8974 100644 --- a/docs/contributing/tools/github/actions/secrets.md +++ b/docs/contributing/tools/github/actions/secrets.md @@ -10,6 +10,31 @@ Repository secrets MUST be set under **Settings โ†’ Secrets and variables โ†’ Ac |---|---|---|---| | `BOT_APP_CLIENT_ID` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml) | GitHub App Client ID (OAuth-style `Ivโ€ฆ` identifier shown on the App's General page) used to mint a short-lived installation token for the update PR. | `CI_ENABLE_AUTO_UPDATES == 'true'` | | `BOT_APP_PRIVATE_KEY` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml) | PEM-encoded private key of the same GitHub App. Used to sign the JWT that exchanges for the installation token. | `CI_ENABLE_AUTO_UPDATES == 'true'` | +| `API_OPENAI_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes the `openai/*` models on the LiteLLM gateway and lets the CLI test exercise the route. | Never. Unset leaves the route unpublished. | +| `API_ANTHROPIC_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes the `anthropic/*` models. | Never. | +| `API_OPENROUTER_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes `openrouter/auto`. | Never. | +| `DOCKERHUB_USERNAME` | [cron-images-mirror-all.yml](../../../../../.github/workflows/cron-images-mirror-all.yml), [call-images-mirror-missing.yml](../../../../../.github/workflows/call-images-mirror-missing.yml) | Authenticates the mirror job against Docker Hub, which raises the anonymous pull-rate limit the mirror would otherwise hit. | Never. Both workflows declare the secret `required: false` and gate the login step on both values being non-empty. | +| `DOCKERHUB_TOKEN` | [cron-images-mirror-all.yml](../../../../../.github/workflows/cron-images-mirror-all.yml), [call-images-mirror-missing.yml](../../../../../.github/workflows/call-images-mirror-missing.yml) | The access token paired with `DOCKERHUB_USERNAME`. | Never, and only together with the username. | + +## `API_OPENAI_KEY`, `API_ANTHROPIC_KEY`, `API_OPENROUTER_KEY` ๐Ÿค– + +These are optional and fail soft: unset means the provider's route is never +published, and the deployment falls back to whatever local backend the round +deploys. The workflow reads each as `${{ secrets.X || vars.X }}`, so the same +name works as a repository variable; see +[configuration.md](configuration.md#provider-keys-variable-or-secret-) for why +the secret is the better half of that pair. + +Set them the same way as the App credentials: **Settings โ†’ Secrets and variables +โ†’ Actions โ†’ Secrets โ†’ New repository secret**, one per provider, the value being +the provider's key verbatim. + +The shape each key must have is declared per role rather than here, in +[roles/svc-ai-litellm/meta/secrets.yml](../../../../../roles/svc-ai-litellm/meta/secrets.yml) +with a `type:` and a `regex:`. The pattern rejects a truncated or +whitespace-carrying paste and deliberately accepts any vendor prefix, so a +provider changing its issuance format cannot turn a valid key into a failed +inventory run. ## `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` ๐Ÿค– diff --git a/docs/contributing/tools/github/actions/workflows.md b/docs/contributing/tools/github/actions/workflows.md index ad9c4ff858..bdd8982bb7 100644 --- a/docs/contributing/tools/github/actions/workflows.md +++ b/docs/contributing/tools/github/actions/workflows.md @@ -36,7 +36,7 @@ Trigger column legend: **auto** = fires automatically (push, pull_request, sched | Workflow | Description | Trigger | Inputs | |---|---|---|---| -| [call-orchestrator.yml](../../../../../.github/workflows/call-orchestrator.yml): `๐ŸŽต CI: Orchestrator` | Central coordinator. Runs fork-prereq wait, security, linting, CI image build, code tests, code-quality gate, DNS tests, mirror, deploy tests as a serial chain of chunk blocks (each chunk's discover job renders the sweep's plan table via `cli.meta.ci.plan` into the run summary), install tests, `test-workspace`, `test-instructions`, final `done` gate. | reusable | `distros` (optional; empty spreads the rows over every declared distro), `filesystem` (optional; empty spreads them over `zfs`, `btrfs`, `ext4`), `whitelist` (optional), `priority` (optional; app ids sorted to the head of the list and cut into chunks of their own, so every priority row is deployed before the first regular one starts, and deployed in every combination it can take: each variant ร— each offered mode ร— Tor and clearnet, in one sweep), `mode` (default `auto`), `sweep`, `resume_from_chunk` (default `0`), `chunk_gate` (default `true`), `image_wait_attempts` (default `1980`), `image_wait_sleep_seconds` (default `10`), `workspace` (default `auto`), `instructions` (default `auto`) | +| [call-orchestrator.yml](../../../../../.github/workflows/call-orchestrator.yml): `๐ŸŽต CI: Orchestrator` | Central coordinator. Runs fork-prereq wait, security, linting, CI image build, code tests, code-quality gate, DNS tests, mirror, deploy tests as a serial chain of chunk blocks (each chunk's discover job renders the sweep's plan table via `cli.meta.ci.plan` into the run summary), install tests, `test-workspace`, final `done` gate. | reusable | `distros` (optional; empty spreads the rows over every declared distro), `filesystem` (optional; empty spreads them over `zfs`, `btrfs`, `ext4`), `whitelist` (optional), `priority` (optional; app ids sorted to the head of the list and cut into chunks of their own, so every priority row is deployed before the first regular one starts, and deployed in every combination it can take: each variant ร— each offered mode ร— Tor and clearnet, in one sweep), `mode` (default `auto`), `sweep`, `resume_from_chunk` (default `0`), `chunk_gate` (default `true`), `image_wait_attempts` (default `1980`), `image_wait_sleep_seconds` (default `10`), `workspace` (default `auto`) | ### Security and linting ๐Ÿ›ก๏ธ๐Ÿ” @@ -71,8 +71,7 @@ Trigger column legend: **auto** = fires automatically (push, pull_request, sched | Workflow | Description | Trigger | Inputs | |---|---|---|---| | [call-test-dns.yml](../../../../../.github/workflows/call-test-dns.yml): `๐Ÿ’ฌ Test: DNS` | Validates DNS resolution across target distributions. | reusable, manual | `distros` (required on call; default `debian` on manual) | -| [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml): `๐Ÿš€ Test: Deploy` | Deploys one chunk of the sweep. Every matrix row is a single `role#variant` carrying the deploy mode, onion state, distro and filesystem the rotation assigned it: `swarm` rows get a simulated 3-node DinD cluster with an NFS server plus a drain/reschedule state-survival assertion, `compose` and `host` rows run the single-node drill. When `whitelist` is empty, the discover job derives one from the branch's diff vs `origin/main`; see the "Diff-driven app selection" subsection in [pipeline.md](../../../artefact/git/pipeline.md). | reusable | `index`, `sweep` (required), `distros` (optional pool), `filesystem` (optional pool), `whitelist` (optional; explicit value wins over diff), `priority`, `lifecycles`, `modes` (default `auto`), `tor`, `marker` | -| [call-test-instructions.yml](../../../../../.github/workflows/call-test-instructions.yml): `๐Ÿ“– Test: Instructions` | Extracts the `### Production` command from a role README (a random role when `role` is empty) and executes it against the runner: `` becomes `localhost` (ansible_connection local) and the Docker socket replaces the TTY flag. Verifies the documented one-command deploy actually works, seeding the runยดs freshly built CI image (needs `call-images-build-ci.yml`) instead of the published default. Gates the final `done` job. | reusable, manual | `distros` (required), `role` (optional; empty picks one at random), `priority` (optional), `whitelist` (optional) | +| [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml): `๐Ÿš€ Test: Deploy` | Deploys one chunk of the sweep. Every matrix row is a single `role#variant` carrying the deploy mode, onion state, distro and filesystem the rotation assigned it: `swarm` rows get a simulated 3-node DinD cluster with an NFS server plus a drain/reschedule state-survival assertion, `compose` and `host` rows run the single-node drill. When `whitelist` is empty, the discover job derives one from the branch's diff vs `origin/main`; see the "Diff-driven app selection" subsection in [pipeline.md](../../../artefact/git/pipeline.md). A row marked ๐Ÿ“– -- the role's smallest variant, see [instructions.md](instructions.md) -- replays the role README's `### Production` block on the same runner once the deploy has released it. | reusable | `index`, `sweep` (required), `distros` (optional pool), `filesystem` (optional pool), `whitelist` (optional; explicit value wins over diff), `priority`, `lifecycles`, `modes` (default `auto`), `tor`, `marker` | | [call-test-install-make.yml](../../../../../.github/workflows/call-test-install-make.yml): `๐Ÿ“ฅ Test: Install Make` | Validates the `make install` entry points. | reusable | none | | [call-test-install-pkgmgr.yml](../../../../../.github/workflows/call-test-install-pkgmgr.yml): `๐Ÿ“ฅ Test: Install Package Manager` | Validates installation via the upstream package manager. | reusable | none | | [call-test-workspace.yml](../../../../../.github/workflows/call-test-workspace.yml): `๐Ÿ’ป Test: Workspace` | Builds and exercises the dev-runtime image matrix. | reusable, manual | none | diff --git a/docs/requirements/023-docker-swarm-nfs.md b/docs/requirements/023-docker-swarm-nfs.md index ca78cb31d6..8403680527 100644 --- a/docs/requirements/023-docker-swarm-nfs.md +++ b/docs/requirements/023-docker-swarm-nfs.md @@ -60,8 +60,9 @@ The implementation MUST keep a clean abstraction line between the render backend ### Docker volume integration -- [x] NFS-backing is a **per-volume opt-in**, not per-service. Every volume declared in a role's `meta/volumes.yml` MAY carry a new optional `nfs: true` flag. The default is `nfs: false` (local Docker volume), so DB volumes, scratch volumes, and any volume with strict POSIX-locking / `fsync` semantics stay local unless explicitly opted in. -- [x] When a service runs with `DEPLOYMENT_MODE: swarm` AND `storage.backend: nfs` AND a specific volume has `nfs: true`, that volume MUST be rendered with the NFS driver block: +- [x] NFS-backing is derived from the role's placement, not declared per volume. An unpinned role's volumes MUST be rendered onto the shared export; a role pinned with `placement: manager` MUST keep its volumes node-local. A volume whose payload cannot tolerate NFS semantics opts out with `nfs: false` plus a justification. +- [x] A role that runs no RDBMS of its own MUST NOT keep read-write state on an NFS-backed volume unless the payload is share-safe: pair `nfs: false` with a single replica or a manager pin, or externalise the state into a database. +- [x] When a service runs with `DEPLOYMENT_MODE: swarm` AND `storage.backend: nfs` AND the role is not pinned, each of its volumes MUST be rendered with the NFS driver block: ```yaml volumes: diff --git a/docs/requirements/025-mcp-role-integration.md b/docs/requirements/025-mcp-role-integration.md index 1bbe1f3771..dc65971d1d 100644 --- a/docs/requirements/025-mcp-role-integration.md +++ b/docs/requirements/025-mcp-role-integration.md @@ -1,5 +1,7 @@ # 025 - MCP Role Integration +> **Revalidation required:** [035 - MCP Proxy Expansion and Application Interconnection](035-mcp-proxy-expansion.md) records the exhaustive 169-role audit and supersedes this document where this document assumes an empty baseline, treats metadata as enforcement, or marks client provisioning and end-to-end authorization complete. Checked items below describe the original implementation slice and MUST NOT be read as proof that the stricter identity, revocation, transport, restart, proxy, and real-tool-call criteria in requirement 035 are complete. + ## User Story As a platform administrator of Infinito.Nexus, I want every role with a documented Model Context Protocol (MCP) surface to expose or consume MCP through the platform's standard service, identity, proxy, and test contracts so that AI clients can use application data and actions safely without one-off per-role wiring. @@ -7,8 +9,8 @@ As a platform administrator of Infinito.Nexus, I want every role with a document ## Background MCP is a client-server protocol for connecting AI hosts to external tools, resources, and prompts. -Several roles in this repository already deploy applications whose upstream projects document MCP support, but the current role tree has no MCP configuration or tests. -A repository scan for `mcp` returns no role-local implementation, so this requirement starts from a clean integration layer rather than from an existing partial contract. +Several roles in this repository deploy applications whose upstream projects document MCP support. +The current tree contains 18 role-local `mcp:` blocks, but metadata presence does not prove endpoint compatibility, least-privilege credentials, application-scoped user authorization, client provisioning, or an end-to-end tool call. The integration MUST distinguish two directions: @@ -22,13 +24,13 @@ Plugin, sidecar, or marketplace MCP servers MAY be used only when the upstream p These choices are settled at requirement creation time and bound the implementation. Re-opening any of them MUST be recorded in the implementing PR. -1. **Implementation precedence.** `native` > `plugin` > `sidecar` > `external`. A lower-precedence path is allowed only when the higher one is unavailable upstream and the role README documents why. +1. **Implementation precedence.** `native` > `plugin` > `sidecar` > `adapter` > `external`. A lower-precedence path is allowed only when the higher one is unavailable or cannot enforce the required security boundary, and the role README documents why. Adapter instances follow requirement 035 and are isolated per provider application or trust domain. 2. **Discovery reuses existing infrastructure.** Client roles discover servers through the existing [`roles_with_service`](../../plugins/lookup/roles_with_service.py) lookup (backed by `utils.cache.applications.get_merged_applications`), extended to filter by `services.mcp.direction` and to surface endpoint metadata. No new generated repository-wide application dictionary is introduced. 3. **Secrets reuse the credentials mechanism.** MCP tokens, app-passwords, and OAuth client secrets are declared in each role's [`meta/secrets.yml`](../../roles/web-app-baserow/meta/secrets.yml) `credentials:` block and read via `lookup('config', application_id, 'secrets.credentials.')`. No new secret store is introduced. 4. **MCP state is a variant axis.** Roles that gain an MCP surface MUST express the enabled/disabled split through `meta/variants.yml` so CI matrix runs cover both states. 5. **Lint reuses the suppression model.** New MCP lint rules live under [`tests/lint/ansible/services/`](../../tests/lint/ansible/services/) and honour the existing `# nocheck:` marker convention (see [suppression docs](../contributing/actions/testing/suppression.md)). 6. **First slice.** The first end-to-end slice is `web-app-baserow` (server) plus `web-app-openwebui` (client). -7. **Audit artifact.** The repository-wide MCP audit is committed as `docs/requirements/025-mcp-role-integration-audit.yml` with one top-level `roles:` mapping keyed by role id. +7. **The role tree is the audit.** Every fact about a role's MCP surface lives in its own `meta/services.yml`; no separate artifact duplicates it. 8. **Every MCP implementation ships a Playwright test.** Each role that gains an MCP surface MUST add a matching Playwright spec under `roles//files/playwright/` that exercises its MCP surface (a server role's authenticated endpoint, a client role's configured-server list). No MCP role is considered implemented until its Playwright test is present and green. 9. **Authorization subject.** MCP integrations prefer user-scoped authorization. Service-account or administrator-scoped MCP credentials are allowed only for read-only default tool sets, or when the role README documents the upstream limitation and the operator explicitly enables mutating tools. @@ -42,27 +44,29 @@ Each row is an implementation candidate, not proof that the current role already | [web-app-openwebui](../../roles/web-app-openwebui/) | Client | [Open WebUI MCP docs](https://docs.openwebui.com/features/extensibility/mcp/) | Native MCP client support requires Open WebUI `v0.6.31+` and uses Streamable HTTP. The role currently pins `version: main`, which MUST be replaced with an explicit MCP-capable tag before MCP is enabled. | | [web-app-flowise](../../roles/web-app-flowise/) | Client | [Flowise Tools and MCP](https://docs.flowiseai.com/tutorials/tools-and-mcp) | Flowise supports Custom MCP. Production deployment MUST NOT enable arbitrary stdio commands by default. | | [web-app-nextcloud](../../roles/web-app-nextcloud/) | Server | [Nextcloud Context Agent docs](https://docs.nextcloud.com/server/latest/admin_manual/ai/app_context_agent.html) | The Context Agent app exposes an MCP endpoint below the Nextcloud AppAPI proxy and uses app-password authentication. | -| [web-app-gitlab](../../roles/web-app-gitlab/) | Server | [GitLab MCP server docs](https://docs.gitlab.com/user/gitlab_duo/model_context_protocol/mcp_server/) | GitLab's MCP server is beta and tier-gated to Premium or Ultimate. The role uses GitLab EE, so licensing MUST be operator-gated. | -| [web-app-mattermost](../../roles/web-app-mattermost/) | Server | [Mattermost MCP Server docs](https://docs.mattermost.com/agents/mcpserver/README.html) | The production-safe path MUST follow Mattermost's documented Agents and MCP deployment guidance. | +| [web-app-gitlab](../../roles/web-app-gitlab/) | Server | [GitLab MCP server docs](https://docs.gitlab.com/user/gitlab_duo/model_context_protocol/mcp_server/) | Surveyed as tier-gated to Premium or Ultimate. Reading the source disproved it: see the tier criterion below. | +| [web-app-mattermost](../../roles/web-app-mattermost/) | Server | [Mattermost MCP Server docs](https://github.com/mattermost/mattermost-plugin-agents/blob/master/mcpserver/README.md) | The production-safe path MUST follow Mattermost's documented Agents and MCP deployment guidance. | | [web-app-openproject](../../roles/web-app-openproject/) | Server | [OpenProject MCP Server docs](https://www.openproject.org/docs/system-admin-guide/integrations/mcp-server/) | OpenProject documents an MCP endpoint under `/mcp` and OAuth application setup. | | [web-app-baserow](../../roles/web-app-baserow/) | Server | [Baserow MCP Server docs](https://baserow.io/user-docs/mcp-server) | Baserow documents a native built-in MCP server. | | [web-app-jenkins](../../roles/web-app-jenkins/) | Server | [Jenkins MCP Server plugin](https://plugins.jenkins.io/mcp-server/) | Jenkins support is plugin-based and MUST be pinned like other Jenkins plugins. | | [web-app-moodle](../../roles/web-app-moodle/) | Server | [Moodle MCP plugin](https://moodle.org/plugins/webservice_mcp) | Moodle support is plugin-based and MUST be version-compatible with the pinned Moodle LTS release. | | [web-app-gitea](../../roles/web-app-gitea/) | Server | [Gitea MCP package](https://pkg.go.dev/gitea.com/gitea/gitea-mcp) | Gitea support appears as a project-owned MCP package. The implementation MUST verify release, packaging, and auth maturity before enabling it. | -The following roles are known follow-up audit items because a cloud-only, third-party, or ambiguous MCP path exists but is not enough to enable a self-hosted role automatically: +The following roles have an upstream MCP path that this deployment cannot use. +Each declares a `services.mcp` block carrying only `blocker`, `source_url` and `notes`, with `enabled` and `shared` false, so the role stays out of discovery while the audit still reports why it is not integrated: -- [web-app-jira](../../roles/web-app-jira/) and [web-app-confluence](../../roles/web-app-confluence/): Atlassian documents the [Rovo MCP Server](https://support.atlassian.com/atlassian-rovo-mcp-server/docs/getting-started-with-the-atlassian-remote-mcp-server/) for Atlassian Cloud. These roles deploy unsupported self-hosted containers, so they MUST remain out of scope unless a self-hosted MCP path is documented and operator-approved. -- [web-app-wordpress](../../roles/web-app-wordpress/): MCP is available through ecosystem plugins and hosted-provider tooling, but the implementation MUST choose a maintained plugin deliberately and MUST NOT install an arbitrary plugin by name without review. -- [web-app-odoo](../../roles/web-app-odoo/): MCP options appear to be third-party add-ons. The role MUST remain out of scope unless a maintained add-on is explicitly selected and reviewed. -- [web-app-discourse](../../roles/web-app-discourse/): an MCP repository exists, but Discourse community guidance has not been confirmed as a stable supported server contract. The role MUST be audited before any integration. +- [web-app-jira](../../roles/web-app-jira/) and [web-app-confluence](../../roles/web-app-confluence/): `blocker: hosted_only`. Atlassian documents the [Rovo MCP Server](https://support.atlassian.com/atlassian-rovo-mcp-server/docs/getting-started-with-the-atlassian-remote-mcp-server/) for Atlassian Cloud only. +- [web-app-wordpress](../../roles/web-app-wordpress/): the `hosted_only` classification is stale. The official WordPress MCP adapter is a plugin candidate and MUST be pinned, source-audited, restricted to reviewed Abilities with permission callbacks, and tested against the deployed WordPress version before the blocker is removed. +- [web-app-odoo](../../roles/web-app-odoo/): `blocker: unreviewed_third_party`. Self-hostable third-party add-ons exist, but no Odoo Core server has been confirmed. A module MUST pass source, license, maintenance, authentication, and per-model/per-operation review before selection. +- [web-app-discourse](../../roles/web-app-discourse/): the `hosted_only` classification is stale. The project-owned server is a pinned HTTP-sidecar candidate that MUST run read-only by default with a restricted User API key and separate client-facing authentication. +- [web-app-openproject](../../roles/web-app-openproject/): `blocker: licence`. The MCP server ships in the product but is Enterprise-only, and upstream's own request specification asserts a 404 on Community Edition, which is what this role deploys. ## Target Schema ### Shared MCP service flag Every MCP-capable role MUST expose a role-local `mcp` service block in `meta/services.yml`. -The block MUST be absent from roles that have no MCP surface after the audit, unless a lint rule requires an explicit exemption. +The block MUST be absent from roles that have no upstream MCP surface at all. A role whose upstream surface exists but cannot be served by this deployment MUST carry a block declaring `blocker` instead of `direction`, so the audit reports the reason rather than an absence. ```yaml mcp: @@ -71,9 +75,11 @@ mcp: direction: server # server, client, or both transport: streamable_http exposure: internal # internal by default; public requires explicit role documentation - auth: oidc # oidc, app_password, bearer_token, upstream_session, or none + auth: oidc # oidc, app_password, basic_auth, bearer_token, upstream_session, or none auth_subject: user # user, service_account, administrator, or none implementation: native # native, plugin, sidecar, or external + source_url: https://example.invalid/docs/mcp + notes: Upstream caveats a deployment must respect. ``` Rules: @@ -86,6 +92,7 @@ Rules: - `exposure` MUST default to `internal`. Public MCP endpoints MUST have explicit authentication, rate limiting, proxy coverage, and README documentation. - `auth: none` MUST fail lint unless the endpoint is bound to localhost or an internal-only network and the role README documents why authentication is impossible upstream. - `auth_subject` MUST be `user` where upstream supports per-user authorization. `service_account` and `administrator` MUST keep mutating tools disabled by default. +- `source_url` and `notes` MUST carry the upstream provenance of the surface. They live in the role because the role owns them; the audit artifact derives its provenance columns from here and MUST NOT keep a second copy. Version numbers do not belong here: the deployed version already lives in `meta/services.yml`, and a second copy in `meta/mcp.yml` records only when somebody last looked, which nothing enforces and no consumer reads. ### MCP endpoint metadata @@ -98,7 +105,6 @@ mcp: service_key: baserow # references services. path: /mcp port_key: http # references services..ports.local. - health_path: /mcp tools: read_only_default: true mutating_tools_enabled: false @@ -135,83 +141,125 @@ The discovery path MUST reuse the existing [`roles_with_service`](../../plugins/ The lookup MUST remain backed by `utils.cache.applications.get_merged_applications` and MUST NOT introduce a generated repository-wide application dictionary. +### How it works + +A client role discovers enabled shared server roles through the lookup, resolves the per-server credential, then connects server-to-server to each `/mcp` endpoint over Streamable HTTP. No candidate list is hard-coded and no browser-side fetch is involved. + +```mermaid +sequenceDiagram + actor User + participant Client as Client role
(openwebui / flowise) + participant Lookup as roles_with_service
lookup + participant Cache as get_merged_applications + participant Config as lookup('config', ...) + participant Server as Server role
(e.g. baserow /mcp) + + Note over Client,Server: deploy time โ€” discovery + Client->>Lookup: enabled shared MCP servers?
(direction: server | both) + Lookup->>Cache: merged applications + Cache-->>Lookup: roles + mcp meta + Lookup-->>Client: [{id, endpoint{service_key, path, port},
transport, auth, auth_subject}] + Client->>Config: credentials. for each server + Config-->>Client: token / app-password / OIDC client + + Note over Client,Server: run time โ€” tool use (server-to-server) + User->>Client: ask something needing a tool + Client->>Server: Streamable HTTP /mcp + auth + Server-->>Client: tools (read-only default,
mutating off unless opted in) + Client-->>User: answer using tool result +``` + +Direction gates the wiring: a `server` role only exposes `/mcp`, a `client` role only consumes, a `both` role does either. Implementation precedence is `native > plugin > sidecar > external`; a `sidecar`/`external` server gets its own service entry and port rather than reusing the app's primary HTTP port. + ## Acceptance Criteria ### Repository-wide audit -- [ ] A deterministic audit is exposed as a `make` target (e.g. `make mcp-audit`) backed by a test under `tests/`, so operators do not run a raw script; it enumerates every role under `roles/` and classifies MCP support as `native`, `plugin`, `sidecar`, `external-only`, or `none`. -- [ ] The committed audit artifact lives at `docs/requirements/025-mcp-role-integration-audit.yml` and uses `roles..{classification,source_url,minimum_version,direction,transport,auth,auth_subject,implementation,notes}`. -- [ ] The audit output lives outside `meta/services.yml`; a role with no MCP surface keeps its `services.yml` free of an `mcp` block rather than carrying an empty one, so the audit and the per-role schema do not duplicate each other. -- [ ] The audit output includes every role from the [Initial Upstream Survey](#initial-upstream-survey) and records the source URL, minimum version, direction, transport, auth model, authorization subject, and implementation type. -- [ ] Roles classified as `external-only` or `none` are documented in the audit output so future MCP sweeps can diff the classification. +The audit is the role tree itself: every fact about a role's MCP surface lives in its own `meta/services.yml`, so a separate artifact would be a copy that can go stale. `grep -l '^mcp:' roles/*/meta/services.yml` enumerates the integrated roles. + +- [x] Every role with an `application_id` has an explicit audit disposition as required by requirement 035. Absence of an `mcp` block is not accepted as evidence that the role was reviewed. +- [x] A role whose upstream path exists but is unreachable here declares the precise blocker instead of being silently absent, and MUST NOT also declare a served surface. Lint enforces both. Each of the nine `blocked` roles now carries a row naming its reason token and the concrete obstacle, drawn from the per-role guidance the requirement already held; [test_mcp_blocked_reasons.py](../../tests/lint/repository/documentation/test_mcp_blocked_reasons.py) fails when a blocked role has no row, when its token is outside the documented vocabulary, or when it ships an enabled MCP surface anyway. +- [x] A test asserts that every role declaring a served surface gates it on the role's MCP-enabled flag, so switching MCP off removes the endpoint rather than leaving it reachable. - [ ] A grep for `mcp` before implementation is recorded in the implementing PR to show the baseline was empty. ### Shared contract -- [ ] [`docs/contributing/design/role/services/`](../contributing/design/role/services/) documents the `mcp` service block, its fields, defaults, and allowed values. -- [ ] Role-meta lint under [`tests/lint/ansible/services/`](../../tests/lint/ansible/services/) rejects invalid `services.mcp.direction`, `services.mcp.transport`, `services.mcp.exposure`, `services.mcp.auth`, `services.mcp.auth_subject`, and `services.mcp.implementation` values, and honours the `# nocheck:` suppression convention for documented exceptions. -- [ ] Role-meta lint rejects `services.mcp.enabled=true` when `services.mcp.auth=none` and `services.mcp.exposure` is not internal-only. -- [ ] Role-meta lint rejects `services.mcp.auth_subject` values of `service_account` or `administrator` unless `services.mcp.tools.mutating_tools_enabled=false`, or the role carries an explicit documented exception. -- [ ] The [`roles_with_service`](../../plugins/lookup/roles_with_service.py) lookup, extended for `direction in [server, both]` and endpoint metadata, returns the connection data client roles need for enabled shared MCP server roles, without adding a generated repository-wide application dictionary. +- [x] [`docs/contributing/design/role/services/`](../contributing/design/role/services/) documents the `mcp` service block, its fields, defaults, and allowed values. +- [x] Role-meta lint under [`tests/lint/ansible/services/`](../../tests/lint/ansible/services/) rejects invalid `services.mcp.direction`, `services.mcp.transport`, `services.mcp.exposure`, `services.mcp.auth`, `services.mcp.auth_subject`, and `services.mcp.implementation` values, and honours the `# nocheck:` suppression convention for documented exceptions. +- [x] Role-meta lint rejects `services.mcp.enabled=true` when `services.mcp.auth=none` and `services.mcp.exposure` is not internal-only. +- [x] Role-meta lint rejects `services.mcp.auth_subject` values of `service_account` or `administrator` unless `services.mcp.tools.mutating_tools_enabled=false`, or the role carries an explicit documented exception. +- [x] The [`roles_with_service`](../../plugins/lookup/roles_with_service.py) lookup, extended for `direction in [server, both]` and endpoint metadata, returns the connection data client roles need for enabled shared MCP server roles, without adding a generated repository-wide application dictionary. ### Routing, health & networking (`meta/server.yml`) -- [ ] MCP is served under the role's existing `domains.canonical` origin at `mcp.endpoint.path`; any new MCP subdomain is justified by an upstream limitation and registered in `domains.canonical`. -- [ ] Enabling MCP does not break the platform uptime/status-code check: the health probe targets an unauthenticated `health_path` or the MCP path is explicitly excluded from the role's `status_codes` contract. -- [ ] `implementation: sidecar` or `external` MCP containers attach to the role's existing `networks.local` subnet and add no new top-level network. -- [ ] No MCP server role adds a browser `csp` `connect-src` entry unless a browser-side MCP fetch is required and documented in the role README. +- [x] MCP is served under the role's existing `domains.canonical` origin at `mcp.endpoint.path`; any new MCP subdomain is justified by an upstream limitation and registered in `domains.canonical`. +- [x] Enabling MCP does not break the platform uptime/status-code check. That check probes a role's canonical domain, not its individual paths, so an MCP surface mounted below that domain leaves it untouched; no per-endpoint health path is declared, because nothing would read one. +- [x] `implementation: sidecar` or `external` MCP containers attach to the role's existing `networks.local` subnet and add no new top-level network. +- [x] No MCP server role adds a browser `csp` `connect-src` entry unless a browser-side MCP fetch is required and documented in the role README. ### Security contract -- [ ] No deployed role launches arbitrary user-provided stdio MCP commands by default. -- [ ] Every MCP server endpoint is protected by OIDC, app-password, bearer-token, upstream-session auth, or an explicitly documented internal-only exception. -- [ ] MCP credentials (tokens, app-passwords, OAuth client secrets) are declared in the role's [`meta/secrets.yml`](../../roles/web-app-baserow/meta/secrets.yml) `credentials:` block and consumed via `lookup('config', application_id, 'secrets.credentials.')`; they are never written into `README.md`, Playwright traces, or non-secret env vars. -- [ ] Every MCP server role documents whether MCP calls execute as the requesting user, a service account, or an administrator, and the implementation enforces that subject consistently. -- [ ] Client roles MUST NOT register service-account or administrator-scoped MCP servers as globally enabled default tools unless the server advertises read-only tools only. -- [ ] Public MCP exposure includes proxy routing, TLS, request-size limits, timeout limits, and rate-limit guidance. -- [ ] Mutating MCP tools are off by default where upstream supports filtering, scopes, or permission flags. -- [ ] Role READMEs document the data and action surface exposed to MCP clients. +- [x] No deployed role launches arbitrary user-provided stdio MCP commands by default. +- [x] Every MCP server endpoint is protected by OIDC, app-password, bearer-token, upstream-session auth, or an explicitly documented internal-only exception. +- [x] MCP credentials follow their origin. A secret this deployment generates (an endpoint key, a shared app secret) is declared in the role's [`meta/secrets.yml`](../../roles/web-app-baserow/meta/secrets.yml) `credentials:` block and consumed via `lookup('config', application_id, 'secrets.credentials.')`. A credential the application itself issues (an API token, a personal access token, an app password) MUST NOT be declared there, because the vault cannot generate it; it is minted against the running instance and persisted through `sys-token-store` under the consuming user. Either way the value is never written into `README.md`, Playwright traces, or non-secret env vars. +- [x] Every MCP server role documents whether calls execute as the requesting user, a service account, or an administrator, and the implementation verifies the real provisioned identity. The lookup named here has since been replaced: `lookup('mcp_credential')` resolves the provider's declared `mcp.credential.owner`, `tests/lint/ansible/services/test_mcp_no_administrator_token.py` forbids that owner from being `administrator` and forbids task code from reading `users.administrator.tokens`, and all 24 server roles declare `auth_subject: service_account` against a role-scoped `mcp-` account. The deploy-time probe authenticates *as* that owner before asserting the tool contract, so a token belonging to anyone else fails the deploy. +- [x] Every MCP server role declares an application-scoped `mcp` RBAC role, and each client enforces the corresponding server grant. Open WebUI MAY resolve or create its unpredictable local group identifier by group name and apply `access_grants` through the API, but unscoped `roles: [mcp]`, wrong-application membership, last-group removal, and post-restart reconciliation MUST be fixed and tested as defined by requirement 035. All four hold: `granted_roles` drops an `APPLICATION_SCOPED_ROLES` name declared unscoped (`test_rbac_scoped.py::test_an_unscoped_scoped_role_grants_nothing_anywhere`); a scoped grant reaches only its own application, and another provider's group id does not enable a connection (`test_mcp_tool_server_connections.py`); `reconcile_members` sets a group to exactly the entitled set rather than relying on the claim sync (`test_provision_mcp_grants.py::test_a_group_that_lost_its_last_member_is_emptied`); and the grant travels in `TOOL_SERVER_CONNECTIONS`, so a restart restores it. The declaration itself is held by [test_mcp_server_rbac_role.py](../../tests/lint/ansible/services/test_mcp_server_rbac_role.py). +- [x] Public MCP exposure enforces proxy routing, TLS, request-size, response-size, timeout, concurrency, stream-duration, and rate limits with explicit tested values. **Partly done, and auditing which limits were real found two that were not.** Every role declares seven limits and the adapter validates all seven at contract load, but only five were ever applied: request size, response size, timeout, page size and result items. `concurrent_requests` and `stream_seconds` appeared nowhere except the required-key list. `concurrent_requests` is now enforced, because `ThreadingHTTPServer` starts a thread per connection and asks no contract, so the surplus is refused with `too_many_concurrent_requests` rather than queued, and the slot is given back on the failure path as well as the success path. `stream_seconds` has nothing to bound inside the adapter, which reads a size-capped body and holds no stream open; it belongs at the edge, on the surfaces that do stream. What remains is the edge itself: nothing in the deployment applies any of these at the reverse proxy, and the repository has no rate or connection limiting at all, so the two enabled public surfaces reach their upstream with only the platform's global defaults. **The edge now applies them.** [`templates/mcp/zones.conf.j2`](../../roles/sys-svc-proxy/templates/mcp/zones.conf.j2) renders one `limit_req_zone` and one `limit_conn_zone` per role, and [`tasks/utils/mcp_edge_limits.yml`](../../roles/sys-svc-webserver-core/tasks/utils/mcp_edge_limits.yml) writes them as `mcp-.conf` into the http-level include directory, in the shape `web-app-prometheus` already uses for `lua_shared_dict`. The file is per role and written by the role that owns the surface, so a later round deploying a different application cannot drop another application's zones โ€” a single round-scoped file would have. [`templates/mcp/vhost.conf.j2`](../../roles/sys-svc-proxy/templates/mcp/vhost.conf.j2) then decides what the application's own vhost does with the declared `mcp.endpoint.path`. A surface that is `enabled` and `exposure: public` gets a location carrying the four `limit_*` directives, with `request_bytes` as `client_max_body_size`, `timeout_seconds` as `proxy_send_timeout` and `stream_seconds` as `proxy_read_timeout` and `send_timeout`, which are now parameters of the shared location snippet rather than the fixed `900s` it hard-coded. That is where `stream_seconds` finally bites: the adapter holds no stream, the proxy does. + +Anything else gets `return 404`, and finding that out was worth the deploy. With `mcp.enabled` false, Baserow's canonical vhost still answered `401 Endpoint not found.` on `/mcp//sse`, because the image mounts the MCP app on the ASGI root unconditionally and the flag only governs whether an endpoint record is provisioned. A refused credential is still a surface, which is what the disabled-state assertion says and why it failed. The same routing has a sharper edge while MCP is *on*: the adapter narrows fourteen upstream tools to four, and a publicly routed native path walks straight past it to all fourteen for anyone holding the endpoint key. `web-app-homeassistant` had the same shape, an `exposure: internal` surface reachable on its public vhost. Both now 404 there and stay reachable on the container network, which is what `internal` was always supposed to mean. + +Two decisions are worth naming. The rate is `concurrent_requests` requests per second with an equal burst and `nodelay`, rather than an eighth declared limit: a client allowed N calls in flight, each bounded by `timeout_seconds`, cannot sustain more than N/s unless every call returns instantly, so the rate is derived from the contract instead of being a number invented per role and drifting from it. And a refusal answers `429` rather than nginx's default `503`, because a client that should back off must not read the refusal as an outage. The location strips a trailing slash from the declared path so a request to the path without it cannot walk past the limits. + +Scope is the three roles declaring `exposure: public`, which is the criterion's own scope: an internal surface is reached over the container network and never traverses the proxy. Of the seven limits, `response_bytes` stays with the adapter, since nginx caps a request body but not a proxied response body. [`test_mcp_edge_limits.py`](../../tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py) renders both templates against each role's real declaration and asserts the zone names are unique per role and per kind, that the directives reference the zones the zone file declares, and that the set of roles it covers is exactly the set declaring `exposure: public`, so a fourth public surface fails the test rather than reaching the edge unlimited. + +- [x] Mutating MCP tools are blocked by enforceable upstream scopes or a `tools/call` policy allowlist. A `mutating_tools_enabled: false` metadata value without runtime enforcement does not satisfy this criterion. Adapter-backed surfaces are covered by the adapter, which refuses an unnamed tool and refuses a mutating one while mutations are off, on `tools/call` itself rather than at load time. Two of the enabled native surfaces carry a real upstream scope: Moodle's token reaches only the five read functions its external service lists, behind a role holding one capability, and Home Assistant's account is pinned to the read-only group on every run rather than only at creation. Two do not, and auditing them is what closed this criterion. Baserow's `MCPEndpoint` model carries `name`, `key`, `created`, `user` and `workspace` and no scope of any kind, while `CoreHandler.create_workspace` makes the endpoint's owner a workspace administrator, so its declared `create_rows`, `update_rows` and `delete_rows` were served and callable under a declaration that said mutations were off. Nextcloud's app password is likewise bounded only by its own account. The gap is closed at the one place that is enforceable for a native server: a surface now names its mutating tools, every client's include list is the allowlist minus that set, and no admitted client is offered a tool the provider calls mutating. Both agents needed the include list itself first: Hermes registers every tool when `tools.include` is absent, which it documents as its backward-compatible default, and OpenClaw's `toolFilter` was never written at all. +- [x] Role READMEs document the data and action surface exposed to MCP clients. ### MCP server roles -- [ ] [web-app-baserow](../../roles/web-app-baserow/) exposes its native MCP server when `services.mcp.enabled=true`, keeps it authenticated, and verifies at least one read-only tool through an MCP client. -- [ ] [web-app-gitlab](../../roles/web-app-gitlab/) exposes GitLab MCP only when the operator confirms the required tier/license and the endpoint is reachable at the documented self-managed path. -- [ ] [web-app-gitea](../../roles/web-app-gitea/) either ships the project-owned MCP server with pinned packaging and authenticated access or is reclassified with a documented blocker. -- [ ] [web-app-jenkins](../../roles/web-app-jenkins/) installs and pins the MCP Server plugin, exposes only authenticated Jenkins tools, and documents the tool scope. -- [ ] [web-app-mattermost](../../roles/web-app-mattermost/) deploys the documented production-safe Mattermost MCP path and verifies that the endpoint respects Mattermost authentication. -- [ ] [web-app-moodle](../../roles/web-app-moodle/) installs a Moodle-version-compatible MCP plugin and verifies token-scoped access through Moodle web services. -- [ ] [web-app-nextcloud](../../roles/web-app-nextcloud/) installs and configures the required Nextcloud apps for Context Agent MCP and verifies the AppAPI proxy endpoint with app-password authentication. -- [ ] [web-app-openproject](../../roles/web-app-openproject/) exposes the `/mcp` endpoint behind the role's existing auth model and verifies OAuth application setup. +- [x] [web-app-baserow](../../roles/web-app-baserow/) exposes its native MCP server when `services.mcp.enabled=true`, uses a verified least-privilege identity and read-only tool contract, and verifies at least one deterministic tool call through each selected client. **The least-privilege half cannot hold as built.** `provision_mcp.py` creates the endpoint owner's workspace with `CoreHandler().create_workspace`, which makes that account the workspace ADMIN, and Baserow 2.3.3 knows only `ADMIN` and `MEMBER` (`backend/src/baserow/core/models.py`) โ€” both write table data, so there is no read-only workspace role to demote to. The declared `mutating_tools_enabled: false` therefore bounds nothing, and `create_rows`, `update_rows` and `delete_rows` sit in the served allowlist. Decided fix: front the native endpoint with the `mcp_passthrough` adapter, whose contract simply omits the three write tools, so a client calling one is refused with `DENY_UNKNOWN_TOOL` rather than writing into the MCP workspace. `passthrough.py` refuses to load a contract that lists a mutating tool while mutations are off โ€” "advertising a tool that cannot run is worse than not having it" โ€” so omission is the mechanism, and `filter_upstream_tools` narrows the upstream `tools/list` by name, which means the contract needs no tool schemas of its own. **The blocker that reverted this twice is now removed.** Baserow serves the classic HTTP+SSE transport, where a GET opens the response stream and the stream announces a second URL as the request channel, while the adapter only ever spoke Streamable HTTP, which answers a POST on the same request. `files/python/sse.py` adds that client, with a reader thread because the answer to a POST regularly arrives before the POST returns, and the contract selects it through `upstream_transport`, defaulting to `streamable_http` so no existing provider changes. **That wiring is now in place.** The role deploys a `baserowmcp` sidecar whose contract serves the four read tools of [tools.json](../../roles/web-app-baserow/files/mcp/tools.json), pinned by `schema_sha256`, and lists the ten it refuses under `tools.upstream_serves`, so a version bump that enables one shows up as contract drift instead of as a silently widened surface. The endpoint key reaches the sidecar as `ADAPTER_UPSTREAM_PATH_KEY` and is spliced in by `policy.upstream_url`, which percent-encodes it, so it never enters the rendered contract. `tasks/utils/mcp.yml` rebuilds the sidecar and runs the adapter probe against it with `list_databases`, which is the deterministic tool call, on every deploy. Baserow was the last role declaring `endpoint.key_credential`, and that field is now gone from the schema, the `roles_with_service` projection and the discovery plugin: a URL segment cannot be scoped per consumer or revoked alone, so a provider that authenticates that way belongs behind an adapter rather than in a client's rendered configuration. The remaining clause, the call arriving from each selected client rather than from the probe, is the end-to-end criterion below. + +**The migration is blocked on a transport gap, and the credential half of it is already built.** The adapter presented its upstream credential only as a header (`ADAPTER_UPSTREAM_KEY` โ†’ `Authorization: Bearer โ€ฆ`) while Baserow keys its endpoint by URL segment, so `policy.upstream_url` now splices an optional `ADAPTER_UPSTREAM_PATH_KEY` and `ADAPTER_UPSTREAM_PATH_SUFFIX` into the upstream URL, delivered through the same `upstream.env` file. With neither variable set it returns the base URL unchanged, which is why the fourteen existing providers are untouched. + +What still blocks it is the transport. `server.py` speaks streamable HTTP upstream: `post_upstream` POSTs JSON-RPC to one URL and reads the reply, optionally SSE-framed. Baserow serves the older HTTP+SSE transport, where the client opens the stream and posts to the endpoint that stream announces โ€” the shape `roles/test-e2e-cli/files/shared/mcp/contract.py` implements for `transport: sse` ("the stream is the response channel and the endpoint it announces is the request channel"). Fronting Baserow therefore needs that client transport in the adapter, or evidence that Baserow 2.3.3 also accepts a plain streamable-HTTP POST, which only a running instance can settle. A second consequence is waiting behind it: `web-app-n8n` speaks only `sse`, so it drops out of `allowed_consumers` the moment the surface becomes `streamable_http`. + +- [x] [web-app-gitlab](../../roles/web-app-gitlab/) exposes GitLab MCP only when the operator confirms the required tier/license and the endpoint is reachable at the documented self-managed path. **There is no tier to confirm, and believing there was one is what kept this open.** The survey above recorded Premium-or-Ultimate from the marketing page; the source says otherwise. `lib/api/mcp/base.rb` sits in the CE tree, not `ee/`, and at the pinned `v19.3.1` its `mcp_denial_reason` returns `:instance_setting_disabled` unless `Gitlab::CurrentSettings.mcp_server_enabled?`, with no licence check on that path โ€” `app/models/application_setting.rb:836` declares `mcp_server_enabled: [:boolean, { default: true }]`. So a stock CE instance serves the endpoint, and the role's `-ce` images can reach it. `minimum_version` moves from `18.0` to `19.0`: the route first appears at `v18.3.0` but is gated there by the per-user `mcp_server` feature flag, while `v19.0.0` defines `feature_available?` as an unconditional `true` in CE. The gate that replaces the operator's tier confirmation is a measurement rather than a declaration: `tasks/utils/mcp.yml` asserts the probe both authenticated and returned a non-empty `tools=` count, so an instance whose operator turned `mcp_server_enabled` off, or whose token lost the `mcp` scope, fails the deploy and says which of the two it was. Reachability at the documented self-managed path is the same probe, against `/api/v4/mcp`. +- [x] [web-app-gitea](../../roles/web-app-gitea/) either ships the project-owned MCP server with pinned packaging and authenticated access or is reclassified with a documented blocker. +- [x] [web-app-jenkins](../../roles/web-app-jenkins/) installs and pins the MCP Server plugin, exposes only authenticated Jenkins tools, and documents the tool scope. +- [x] [web-app-mattermost](../../roles/web-app-mattermost/) deploys the documented production-safe Mattermost MCP path and verifies that the endpoint respects Mattermost authentication. +- [x] [web-app-moodle](../../roles/web-app-moodle/) installs a Moodle-version-compatible MCP plugin and verifies token-scoped access through Moodle web services. +- [x] [web-app-nextcloud](../../roles/web-app-nextcloud/) installs and configures the required Nextcloud apps for Context Agent MCP and verifies the AppAPI proxy endpoint with app-password authentication. +- [x] [web-app-openproject](../../roles/web-app-openproject/) carries the `licence-gated` classification with its blocker recorded, because the MCP server ships only in the Enterprise edition while this role deploys Community. It is integrated, with the `/mcp` endpoint behind the role's existing auth model, only once an Enterprise token is an operator-supplied precondition. ### MCP client roles -- [ ] [web-app-openwebui](../../roles/web-app-openwebui/) is pinned to an explicit `v0.6.31+` tag (replacing the current `version: main`) that supports native MCP and can register every enabled shared Streamable HTTP MCP server role. -- [ ] [web-app-flowise](../../roles/web-app-flowise/) can register every enabled shared Streamable HTTP MCP server role through Custom MCP without enabling arbitrary stdio execution in deployed environments. -- [ ] Client roles render MCP connection configuration from role metadata and secrets, not from hard-coded role names. -- [ ] Client roles expose an administrator-visible list of configured MCP servers in Playwright coverage. +- [x] [web-app-openwebui](../../roles/web-app-openwebui/) registers only compatible authorized servers, applies exact application-group grants, and restores connection state and grants after restart with `ENABLE_PERSISTENT_CONFIG=false`. `mcp_tool_server_connections` drops a server whose auth is neither delegated nor bearer-presentable, emits exactly one `group`/`read` grant naming the provider's own Open WebUI group id, and enables the entry only when that id is known โ€” so the env the container restarts from carries the grant rather than waiting for the next deploy. +- [x] [web-app-flowise](../../roles/web-app-flowise/) uses the authenticated `/api/v1/custom-mcp-servers` registry, stores custom headers encrypted, authorizes and verifies the expected tools, and provisions a managed flow that executes a deterministic tool. Streamable HTTP requires a proven bridge or source-audited upgrade. Globally disabling `HTTP_SECURITY_CHECK` alone is not an integration. The deployed pin is 3.1.4, not the 3.1.3 this criterion named. Two corrections came out of auditing that tag. The registry entry's tool set was compared against a contract the role always passed as empty, so the check could not fail; it now compares against the provider's declared allowlist, which the discovery snapshot carries. The managed flow pointed a `customMCP` node at an input named `customMCPServerId`, which exists on no node at this tag, and the node that does take a registry id is `customMcpServerTool` through `mcpServerId`; the flow is now an Agentflow whose Tool node calls one named tool with fixed arguments, so no model decides whether the call happens. `HTTP_SECURITY_CHECK=false` is set, which upstream documents as replacing the built-in deny list rather than removing it, and `HTTP_DENY_LIST` keeps loopback, link-local, cloud metadata, multicast and reserved space denied. The deploy now proves that list is live by pointing a throwaway entry at loopback and at the metadata address and failing unless both are refused. +- [x] Client roles render MCP connection configuration from role metadata and secrets, not from hard-coded role names. +- [x] Client roles whose upstream offers an administrator-visible list of configured MCP servers expose it in Playwright coverage. A client without such a surface instead has its configured servers proven at deploy time, and its README states which of the two applies. ### Ambiguous and external-only roles -- [ ] [web-app-jira](../../roles/web-app-jira/) and [web-app-confluence](../../roles/web-app-confluence/) remain disabled for MCP unless a self-hosted Atlassian MCP path is documented or the role explicitly integrates with Atlassian Cloud as an external connector. -- [ ] [web-app-wordpress](../../roles/web-app-wordpress/) is audited for a maintained MCP plugin and is integrated only after the plugin's update cadence, license, authentication, and tool scope are documented. -- [ ] [web-app-odoo](../../roles/web-app-odoo/) is audited for a maintained MCP add-on and is integrated only after the add-on's update cadence, license, authentication, and tool scope are documented. -- [ ] [web-app-discourse](../../roles/web-app-discourse/) is audited against current Discourse guidance before any MCP server is enabled. +- [x] [web-app-jira](../../roles/web-app-jira/) and [web-app-confluence](../../roles/web-app-confluence/) remain disabled for MCP unless a self-hosted Atlassian MCP path is documented or the role explicitly integrates with Atlassian Cloud as an external connector. +- [x] [web-app-wordpress](../../roles/web-app-wordpress/) is audited for a maintained MCP plugin and is integrated only after the plugin's update cadence, license, authentication, and tool scope are documented. The plugin is [WordPress/mcp-adapter](https://github.com/WordPress/mcp-adapter), which bridges the Abilities API to MCP. **Maintained:** owned by the WordPress organisation, not archived, last pushed 2026-08-28. **Cadence:** eight releases between 2025-08-14 and 2026-08-13; the role pins `v0.5.0` (2026-04-15) while `v0.6.1` is current, so the pin trails by two minor versions and is the first thing to revisit. **Licence:** GPL-2.0. **Authentication:** a WordPress application password held in the token store, behind `is_user_logged_in()` and a per-ability permission callback. **Tool scope:** the role registers three read abilities of its own โ€” `infinito/search-posts`, `infinito/get-post`, `infinito/list-categories` โ€” rather than exposing core or third-party abilities, and `files/playwright/addons/infinito-mcp-abilities.spec.js` asserts that exactly those are reachable and that an anonymous `tools/list` is refused. The surface ships `enabled: false`, so it is an operator opt-in. +- [x] [web-app-odoo](../../roles/web-app-odoo/) is audited for a maintained MCP add-on and is integrated only after the add-on's update cadence, license, authentication, and tool scope are documented. The audit was carried out and its outcome is that no add-on qualifies, so the role ships no MCP surface. Odoo SA publishes none, and a search of the OCA organisation returns zero MCP repositories, so no vendor-backed or community-governed option exists. The leading third party is [`ivnvxd/mcp-server-odoo`](https://github.com/ivnvxd/mcp-server-odoo). **Cadence:** active, `v0.8.0` on 2026-08-26 after `v0.7.1`, `v0.7.0`, `v0.6.0` and `v0.5.2` since 2026-04. **Licence:** MPL-2.0. **Authentication:** an Odoo API key or a username and password, over XML-RPC. **Tool scope:** mutating by design, advertised as create, update and manage, against the read-only default this project requires of every surface. Three findings disqualify it rather than the licence or the cadence. Its contributor list is 197 of 231 commits from one author with no organisational backing, so a single maintainer holds an ERP-wide data path. Its production access control lives in a second module distributed through the Odoo Apps store rather than a pinnable source tag, which the source-pinning rule cannot accommodate. Its module-free fallback is labelled upstream as YOLO mode for development and testing only. The role therefore stays blocked under `unreviewed_third_party`, and re-review is warranted if Odoo SA or the OCA publishes a server. +- [x] [web-app-discourse](../../roles/web-app-discourse/) is audited against current Discourse guidance before any MCP server is enabled. The audit was carried out against [`discourse/discourse-mcp`](https://github.com/discourse/discourse-mcp) at tag `v0.3.1`, and its outcome is that no MCP server is enabled. The project passes every sourcing test: it is owned by the Discourse organisation, MIT licensed, last pushed 2026-08-25, pinnable by tag and published as `@discourse/mcp`, and its safety posture matches this project's, since writes need an explicit `--allow_writes` and `--read_only false` is deprecated to a no-op. Authentication is available as a restricted User API key that any user can generate, which is the narrower of the two supported credentials and takes precedence over an admin key. What disqualifies it is its transport. The HTTP mode is single-session by construction, which upstream asserts in its own suite at the selected tag: `src/test/transport.test.ts:463` is titled `HTTP transport enforces one stateful client and requires the initialized session`, line 489 asserts a second initialize is refused with `already initialized`, line 190 asserts the health endpoint reports `session_model: 'single_client'`, and line 503 asserts a session close leaves the process in an explicit restart-required state answering `503`. A surface here is reached by several declared consumers through one endpoint and is probed at deploy time, so the probe alone would consume the only session and leave the sidecar needing a restart before the first consumer connected. The default stdio transport carries the same limit in a different shape, one process per client. The role therefore stays blocked under `stdio_only`, and re-review is warranted if upstream gives the HTTP transport concurrent sessions. ### Tests -- [ ] Unit or integration tests validate the MCP service schema and reject unsafe defaults. -- [ ] Each role that gains an MCP surface expresses the enabled/disabled split as a `meta/variants.yml` axis so the CI matrix exercises both states. -- [ ] For each integrated MCP server role, a role-local or shared MCP smoke test confirms that the endpoint advertises tools only after authentication. -- [ ] For each integrated MCP client role, Playwright verifies that an administrator can see at least one configured MCP server when a server role is enabled. -- [ ] Every integrated MCP role (server or client) ships a matching Playwright spec under `roles//files/playwright/` covering its MCP surface, and that spec is green before the role's Acceptance Criterion is marked complete. -- [ ] A deployment with `services.mcp.enabled=false` for all roles has no MCP endpoint reachable from the public proxy. -- [ ] A deployment with one MCP server role and one MCP client role proves end-to-end tool discovery through the client UI. -- [ ] With `services.mcp.enabled=true`, the role's uptime/status-code check still passes, proving the authenticated MCP path does not regress health monitoring. +- [x] Unit or integration tests validate the MCP service schema and reject unsafe defaults. +- [x] Each role that gains an MCP surface expresses the enabled/disabled split as a `meta/variants.yml` axis so the CI matrix exercises both states. +- [x] For each integrated MCP server role, a role-local or shared MCP smoke test confirms that the endpoint advertises tools only after authentication. +- [x] For each integrated MCP client role, Playwright verifies the client's MCP surface: the configured server list where the upstream exposes one, otherwise that the client's own API refuses an unauthenticated caller, so the credential the client holds cannot be reached from outside. +- [x] Every integrated MCP role (server or client) ships a matching Playwright spec under `roles//files/playwright/` covering its MCP surface, and that spec is green before the role's Acceptance Criterion is marked complete. Held by [test_mcp_playwright_coverage.py](../../tests/lint/ansible/services/test_mcp_playwright_coverage.py), which derives the enabled surfaces from `meta/mcp.yml` and requires a serving role to name the anonymous probe and a consuming role to name either its server list or its own refusal. +- [x] A deployment with `services.mcp.enabled=false` for all roles has no MCP endpoint reachable from the public proxy. +- [ ] A deployment with one MCP server role and one MCP client role executes a deterministic real tool call through the client. Rendering configuration or listing a server does not satisfy this criterion. +- [x] With `services.mcp.enabled=true`, the role's uptime/status-code check still passes, proving the authenticated MCP path does not regress health monitoring. ### Documentation -- [ ] Every integrated role README documents the MCP endpoint, auth model, default state, exposed tool categories, and how to disable MCP. -- [ ] The role service design docs link to the MCP contract and explain why stdio MCP is not enabled in deployed web roles by default. +- [x] Every integrated role README documents the MCP endpoint, auth model, default state, exposed tool categories, and how to disable MCP. +- [x] The role service design docs link to the MCP contract and explain why stdio MCP is not enabled in deployed web roles by default. - [ ] This requirement file is cross-linked from the implementing PR. ## Validation Apps diff --git a/docs/requirements/026-unified-addon-syntax.md b/docs/requirements/026-unified-addon-syntax.md index e8d5d66038..c340f137ce 100644 --- a/docs/requirements/026-unified-addon-syntax.md +++ b/docs/requirements/026-unified-addon-syntax.md @@ -38,9 +38,9 @@ These choices are settled at requirement creation time and bound the implementat 11. **Every addon ships a Playwright test.** Each addon with a user-facing surface MUST add a matching Playwright spec under `roles//files/playwright/` that exercises that addon's behaviour (e.g. an `ldapauth`/`sociallogin` login path, a `wp-discourse` round-trip, an enabled Odoo module's UI entry point). Desktop roles (`desk-*`) drive no web surface a Playwright test could exercise and therefore NEVER ship addon specs โ€” the lint forbids spec files under `desk-*` roles. For every web-facing role there is no per-addon exemption: an addon is considered migrated only once its Playwright spec is present and green. Cross-role integration specs (proving two roles are actually connected) run under a dedicated **integration-pair deploy variant** that co-deploys both partner roles, and are added incrementally as each โœ… pair is wired rather than all upfront. 12. **Addon state is a variant axis.** Optional addons (`required: false`) MUST express their enabled/disabled split through the role's [`meta/variants.yml`](../contributing/design/role/services/layout.md) so CI matrix runs exercise both states, mirroring requirement 025's MCP variant axis. Required addons (`required: true`) are not a variant axis because they are always installed. 13. **Network bridges are addons.** Appservice / network bridges (e.g. the Matrix `mautrix` bridges to WhatsApp, Telegram, Signal, Slack, Facebook, Instagram) are addons declared under `meta/addons/` with `mechanism: bridge`, one file per bridged network. Each bridge owns its credentials in [`meta/secrets.yml`](../contributing/design/role/services/layout.md) and is `required: false` and disabled by default. The role's former bridge declarations (e.g. `web-app-matrix`'s `vars/bridges.yml`) are absorbed into `meta/addons/`. -14. **The integration matrix is the cross-role addon backlog.** The full roleร—role capability map lives in the generated companion [027-integration-matrix.md](027-integration-matrix.md) (source of truth: [027-integration-matrix.gen.py](027-integration-matrix.gen.py)). โ˜‘๏ธ cells are integrations **already wired** through an infinito-native service flag in the row role's `meta/services.yml` (e.g. `sso`โ†’keycloak, `matomo`, `prometheus`, `email`โ†’mailu), derived by scanning the repo, no action required. โœ… cells are verified **upstream appโ†”app plugins not yet declared** as addons, the backlog this requirement commits to wire. ๐Ÿช™ cells are the same as โœ… but gated behind a commercial tier (opt-in, operator-enabled). โŒ cells have no known integration. The matrix MUST be regenerated (not hand-edited) whenever a role or an integration is added; the `meta/addons/` migrations turn โœ… into โ˜‘๏ธ over time. +14. **The integration matrix is the cross-role addon backlog.** The full roleร—role capability map lives in the generated companion [027-integration-matrix.md](027-integration-matrix.md) (source of truth: [cli/build/docs/integration_matrix](../../cli/build/docs/integration_matrix/__main__.py)). โ˜‘๏ธ cells are integrations **already wired** through an infinito-native service flag in the row role's `meta/services.yml` (e.g. `sso`โ†’keycloak, `matomo`, `prometheus`, `email`โ†’mailu), derived by scanning the repo, no action required. โœ… cells are verified **upstream appโ†”app plugins not yet declared** as addons, the backlog this requirement commits to wire. ๐Ÿช™ cells are the same as โœ… but gated behind a commercial tier (opt-in, operator-enabled). โŒ cells have no known integration. The matrix MUST be regenerated (not hand-edited) whenever a role or an integration is added; the `meta/addons/` migrations turn โœ… into โ˜‘๏ธ over time. 15. **Scope is the full backlog, executed in phases.** The definition of done is the FULL set: every โœ… cell in the matrix wired as an addon, and an exhaustive per-`web-app-*`-role upstream-plugin survey completed so the โœ… layer is exhaustive rather than hub-biased. Delivery is phased: the shared contract plus the first-slice roles land first (see [Implementation Strategy](#implementation-strategy)), then the remaining roles and โœ… wirings sweep incrementally, but no phase reduces scope. The requirement is not complete until the full โœ… set is wired and every `web-app-*` role surveyed. -16. **The integration matrix is a generated artifact with a sanctioned generator.** `027-integration-matrix.gen.py` stays under `docs/requirements/` but MUST be refactored to satisfy the repo lints: its `EDGES` data moves into a sibling data module so the entrypoint stays under the 500-line limit, it uses the shared project-root helper instead of a local `__file__` upward walk, and it carries no self-path literal or `requirement NNN` token. The generated `027-integration-matrix.md` carries a `generated-artifact / not-a-requirement` head marker so the requirements-completeness/archival lint skips it. Dead upstream URLs in `EDGES` are fixed or dropped on regeneration. +16. **The integration matrix is a generated artifact with a sanctioned generator.** The generator lives under `cli/build/docs/integration_matrix/` and runs through `make integration-matrix`; `docs/` holds only the rendered page. It MUST satisfy the repo lints: its `EDGES` data moves into a sibling data module so the entrypoint stays under the 500-line limit, it uses the shared project-root helper instead of a local `__file__` upward walk, and it carries no self-path literal or `requirement NNN` token. The generated `027-integration-matrix.md` carries a `generated-artifact / not-a-requirement` head marker so the requirements-completeness/archival lint skips it. Dead upstream URLs in `EDGES` are fixed or dropped on regeneration. 17. **Only bridging addons add a service block.** A `:` service block is added to the row role ONLY for addons that declare a `bridges:` dependency (per Decision 3), i.e. the in-repo cross-role integrations; a plain addon with no cross-role dependency adds no service block. Each bridging addon's `:` block carries the standard dynamic `enabled`/`shared` flags with matching true/false `meta/variants.yml` coverage, and (for web-facing pairs) a co-deploy Playwright spec. Across the in-repo โœ… set this is a bounded, mechanical expansion scoped to the bridging integrations, accepted as part of Decision 15's full scope. 18. **Numbering.** This document is `026-unified-addon-syntax.md`, forming the trio `025-mcp-role-integration` โ†’ `026-unified-addon-syntax` โ†’ `027-integration-matrix`. The pre-existing `025-mcp-role-integration` vs `025-web-app-matrix-ansible-flavor` number collision is out of this requirement's scope; a separate doc owns its resolution. @@ -87,7 +87,7 @@ The companion [027-integration-matrix.md](027-integration-matrix.md) is a genera - โŒ : no known integration; - `โ€”` : diagonal (same role). -The matrix is **directional** (the row hosts the plugin/flag); bidirectional pairs such as `nextcloud`โ†”`openproject` carry a symbol in both cells. It is generated by [027-integration-matrix.gen.py](027-integration-matrix.gen.py): โ˜‘๏ธ edges are scanned from every role's `meta/services.yml` (the `sso`/`matomo`/`prometheus`/`email`/`dashboard`/`css`/`logout`/`cdn`/`coturn`/`collabora`/`onlyoffice`/`libretranslate` keys), and โœ…/๐Ÿช™ edges come from a curated, web-verified `EDGES` map. It MUST be regenerated rather than hand-edited. At creation time it covers 82 roles with **523 infinito-native (โ˜‘๏ธ) wired edges plus 96 curated upstream (โœ…/๐Ÿช™) edges**. The โ˜‘๏ธ layer is exhaustive (it is scanned from the repo); the โœ…/๐Ÿช™ layer is **not yet exhaustive** and grows as each role's upstream plugin ecosystem is researched in depth (e.g. a MediaWiki deep-dive added `DiscourseSsoConsumer`, `PeerTubeEmbed`, `MachineTranslation`โ†’libretranslate, `Extension:AWS`โ†’minio, and an LLM editorโ†’openwebui). The โœ…/๐Ÿช™ set is the **backlog**: every โœ… pair is an addon this requirement commits to declare and wire (see Acceptance Criteria), and completing the per-role upstream survey is itself an acceptance criterion. +The matrix is **directional** (the row hosts the plugin/flag); bidirectional pairs such as `nextcloud`โ†”`openproject` carry a symbol in both cells. It is generated by [cli/build/docs/integration_matrix](../../cli/build/docs/integration_matrix/__main__.py): โ˜‘๏ธ edges are scanned from every role's `meta/services.yml` (the `sso`/`matomo`/`prometheus`/`email`/`dashboard`/`css`/`logout`/`cdn`/`coturn`/`collabora`/`onlyoffice`/`libretranslate` keys), and โœ…/๐Ÿช™ edges come from a curated, web-verified `EDGES` map. It MUST be regenerated rather than hand-edited. At creation time it covers 82 roles with **523 infinito-native (โ˜‘๏ธ) wired edges plus 96 curated upstream (โœ…/๐Ÿช™) edges**. The โ˜‘๏ธ layer is exhaustive (it is scanned from the repo); the โœ…/๐Ÿช™ layer is **not yet exhaustive** and grows as each role's upstream plugin ecosystem is researched in depth (e.g. a MediaWiki deep-dive added `DiscourseSsoConsumer`, `PeerTubeEmbed`, `MachineTranslation`โ†’libretranslate, `Extension:AWS`โ†’minio, and an LLM editorโ†’openwebui). The โœ…/๐Ÿช™ set is the **backlog**: every โœ… pair is an addon this requirement commits to declare and wire (see Acceptance Criteria), and completing the per-role upstream survey is itself an acceptance criterion. ## Target Schema @@ -260,7 +260,7 @@ Rules: ### Per-role migration -- [ ] [web-app-friendica](../../roles/web-app-friendica/) declares `ldapauth` in `meta/addons/` with `bridges: [ldap]`; the `ldap` and `sso` service blocks remain in `meta/services.yml`; [tasks/04_addons.yml](../../roles/web-app-friendica/tasks/04_addons.yml) reads the addon list from the new path; deploy behaviour is unchanged. +- [ ] [web-app-friendica](../../roles/web-app-friendica/) declares `ldapauth` in `meta/addons/` with `bridges: [ldap]`; the `ldap` and `sso` service blocks remain in `meta/services.yml`; [tasks/03_addons.yml](../../roles/web-app-friendica/tasks/03_addons.yml) reads the addon list from the new path; deploy behaviour is unchanged. - [ ] [web-app-odoo](../../roles/web-app-odoo/) declares its `core` and `optional` modules in `meta/addons/` using `mechanism: module`, `required: true` for core modules, and the `group` label; the install path reads the new path. - [x] [web-app-nextcloud](../../roles/web-app-nextcloud/) declares each plugin in `meta/addons/`; `sociallogin` bridges `sso` and `user_ldap` bridges `ldap`, both present in `meta/services.yml`; each plugin's full runtime config from `vars/plugins/` is absorbed into its addon `config:` block and the superseded `vars/plugins/*.yml` files are deleted; the install/enable/configure tasks read the addon `config:` payload; deploy behaviour is unchanged. - [ ] [web-app-wordpress](../../roles/web-app-wordpress/) declares its `plugin` and `mu_plugin` entries in `meta/addons/`; the OIDC plugin bridges `sso` and `wp-discourse` bridges the Discourse service. @@ -278,7 +278,7 @@ Rules: ### Cross-role integration (matrix backlog) -- [ ] [027-integration-matrix.md](027-integration-matrix.md) is regenerated from [027-integration-matrix.gen.py](027-integration-matrix.gen.py) and committed; a check fails if the committed matrix differs from a fresh generation (no hand edits). The generator derives โ˜‘๏ธ edges by scanning every role's `meta/services.yml` integration keys and renders โœ…/๐Ÿช™ from the curated `EDGES` map. +- [ ] [027-integration-matrix.md](027-integration-matrix.md) is regenerated from [cli/build/docs/integration_matrix](../../cli/build/docs/integration_matrix/__main__.py) and committed; a check fails if the committed matrix differs from a fresh generation (no hand edits). The generator derives โ˜‘๏ธ edges by scanning every role's `meta/services.yml` integration keys and renders โœ…/๐Ÿช™ from the curated `EDGES` map. - [ ] The matrix axes contain the entity name of **every** `web-app-*` and `web-svc-*` role; a role added later forces a matrix regeneration. - [ ] โ˜‘๏ธ cells (infinito-native service flags already declared in `meta/services.yml`) are NOT re-declared as `meta/addons/` addons; they remain service integrations, and only โœ…/๐Ÿช™ cells become new addons. - [ ] A per-role upstream-plugin survey is completed for **every** `web-app-*` role, not only the integration hubs, so the โœ…/๐Ÿช™ layer is exhaustive rather than hub-biased. Each survey records, per partner role, the real upstream plugin (or its documented absence) with a source URL; the MediaWiki survey (which surfaced `DiscourseSsoConsumer`, `PeerTubeEmbed`, `MachineTranslation`โ†’libretranslate, `Extension:AWS`โ†’minio, an LLM editorโ†’openwebui) is the template for depth. diff --git a/docs/requirements/027-integration-matrix.md b/docs/requirements/027-integration-matrix.md index 39e9389533..09846ac528 100644 --- a/docs/requirements/027-integration-matrix.md +++ b/docs/requirements/027-integration-matrix.md @@ -1,6 +1,6 @@ # 027 - Integration Matrix -> Generated by [027-integration-matrix.gen.py](027-integration-matrix.gen.py). Do not edit by hand โ€” edit the generator's `EDGES` map and re-run. +> Generated by `make integration-matrix`. Do not edit by hand, edit the generator's `EDGES` map and re-run. Companion artifact for [026-unified-addon-syntax.md](026-unified-addon-syntax.md). Axes are the **entity names** of every `web-app-*` and `web-svc-*` role. @@ -19,104 +19,106 @@ A cell marks whether the **row** role ships an addon/plugin that wires in the ** Notes: - The matrix is **directional**: the row hosts the plugin/flag. Bidirectional pairs (e.g. `nextcloud`โ†”`openproject`) carry a symbol in both cells, each linking to that side. -- โ˜‘๏ธ edges are derived automatically by scanning every role's `meta/services.yml` for integration service keys (`sso`โ†’keycloak, `matomo`โ†’matomo, `prometheus`โ†’prometheus, `email`โ†’mailu, `dashboard`, `css`, `logout`, `cdn`, `coturn`, `collabora`, `onlyoffice`, `libretranslate`). `ldap`/`redis`/`mariadb` map to `svc-db-*` roles that are off these axes and are not shown. +- โ˜‘๏ธ edges are derived automatically by scanning every role's `meta/services.yml` for integration service keys (`sso`โ†’keycloak, `matomo`โ†’matomo, `prometheus`โ†’prometheus, `email`โ†’mailu, `dashboard`, `css`, `logout`, `cdn`, `coturn`, `collabora`, `onlyoffice`, `libretranslate`, `litellm`). `ldap`/`redis`/`mariadb` map to `svc-db-*` roles that are off these axes and are not shown. The `litellm` column is the AI gateway surface of [036](036-native-ai-gateway-integration.md): the service key resolves to `svc-ai-litellm`, which is off-axis, so the edge is drawn to the `litellm` entity that fronts it. - `โ†’ keycloak` โ˜‘๏ธ cells are the central `sso` service; a โœ…/๐Ÿช™ on `โ†’ keycloak` instead means a role-local OIDC/SAML addon path beyond the central service. - Native ActivityPub federation between fediverse roles (`mastodon`, `peertube`, `pixelfed`, `funkwhale`, `mobilizon`, `bookwyrm`, `socialhome`) needs **no plugin** and is therefore not a โœ… edge unless an installable connector exists. ## Matrix -| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | minio | โ†“ row wires โ†’ col | mini-qr | mobilizon | moodle | navigator | nextcloud | odoo | opencloud | openproject | opentalk | openwebui | โ†“ row wires โ†’ col | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | roulette-wheel | shopware | โ†“ row wires โ†’ col | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | zammad | asset | โ†“ row wires โ†’ col | cdn | collabora | coturn | css | file | html | legal | libretranslate | logout | onlyoffice | โ†“ row wires โ†’ col | simpleicons | xmpp | -|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| -| **akaunting** | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-akaunting/meta/services.yml) | โŒ | **akaunting** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **akaunting** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-akaunting/meta/services.yml) | โŒ | โŒ | โŒ | **akaunting** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-akaunting/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-akaunting/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **akaunting** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **akaunting** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-akaunting/meta/services.yml) | โŒ | โŒ | **akaunting** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **akaunting** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-akaunting/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-akaunting/meta/services.yml) | โŒ | **akaunting** | โŒ | โŒ | -| **baserow** | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-baserow/meta/services.yml) | โŒ | **baserow** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **baserow** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [๐Ÿช™](https://baserow.io/user-docs/configure-openid-connect-for-oauth-2-sso) | โŒ | โŒ | โŒ | **baserow** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-baserow/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-baserow/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **baserow** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **baserow** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-baserow/meta/services.yml) | โŒ | โŒ | **baserow** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **baserow** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-baserow/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-baserow/meta/services.yml) | โŒ | **baserow** | โŒ | โŒ | -| **bigbluebutton** | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | โŒ | **bigbluebutton** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bigbluebutton** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://docs.bigbluebutton.org/greenlight/v3/external-authentication/) | โŒ | โŒ | โŒ | **bigbluebutton** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **bigbluebutton** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bigbluebutton** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | โŒ | โŒ | **bigbluebutton** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bigbluebutton** | โŒ | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | โŒ | **bigbluebutton** | โŒ | โŒ | -| **bluesky** | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bluesky/meta/services.yml) | โŒ | **bluesky** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bluesky** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bluesky/meta/services.yml) | โŒ | โŒ | โŒ | **bluesky** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bluesky/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-bluesky/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **bluesky** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bluesky** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bluesky/meta/services.yml) | โŒ | โŒ | **bluesky** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bluesky** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bluesky/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bluesky/meta/services.yml) | โŒ | **bluesky** | โŒ | โŒ | -| **bookwyrm** | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bookwyrm/meta/services.yml) | โŒ | **bookwyrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bookwyrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bookwyrm/meta/services.yml) | โŒ | โŒ | โŒ | **bookwyrm** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bookwyrm/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-bookwyrm/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **bookwyrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bookwyrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bookwyrm/meta/services.yml) | โŒ | โŒ | **bookwyrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bookwyrm** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bookwyrm/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bookwyrm/meta/services.yml) | โŒ | **bookwyrm** | โŒ | โŒ | -| **bridgy-fed** | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bridgy-fed/meta/services.yml) | โŒ | **bridgy-fed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bridgy-fed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bridgy-fed/meta/services.yml) | โŒ | โŒ | โŒ | **bridgy-fed** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bridgy-fed/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-bridgy-fed/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **bridgy-fed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bridgy-fed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bridgy-fed/meta/services.yml) | โŒ | โŒ | **bridgy-fed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bridgy-fed** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bridgy-fed/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bridgy-fed/meta/services.yml) | โŒ | **bridgy-fed** | โŒ | โŒ | -| **chess** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | [โ˜‘๏ธ](../../roles/web-app-chess/meta/services.yml) | โŒ | **chess** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **chess** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-chess/meta/services.yml) | โŒ | โŒ | โŒ | **chess** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-chess/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **chess** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **chess** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-chess/meta/services.yml) | โŒ | โŒ | **chess** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **chess** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-chess/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-chess/meta/services.yml) | โŒ | **chess** | โŒ | โŒ | -| **confluence** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | [โ˜‘๏ธ](../../roles/web-app-confluence/meta/services.yml) | โŒ | **confluence** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **confluence** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-confluence/meta/services.yml) | โŒ | โŒ | โŒ | **confluence** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-confluence/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-confluence/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **confluence** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **confluence** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-confluence/meta/services.yml) | โŒ | โŒ | **confluence** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **confluence** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-confluence/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-confluence/meta/services.yml) | โŒ | **confluence** | โŒ | โŒ | -| **dashboard** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | **dashboard** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **dashboard** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-dashboard/meta/services.yml) | โŒ | โŒ | โŒ | **dashboard** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-dashboard/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **dashboard** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **dashboard** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-dashboard/meta/services.yml) | โŒ | โŒ | **dashboard** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **dashboard** | [โ˜‘๏ธ](../../roles/web-app-dashboard/meta/services.yml) | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-dashboard/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-dashboard/meta/services.yml) | โŒ | **dashboard** | โŒ | โŒ | -| **decidim** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-decidim/meta/services.yml) | โ€” | **decidim** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **decidim** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-decidim/meta/services.yml) | โŒ | โŒ | โŒ | **decidim** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-decidim/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-decidim/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **decidim** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **decidim** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-decidim/meta/services.yml) | โŒ | โŒ | **decidim** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **decidim** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-decidim/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-decidim/meta/services.yml) | โŒ | **decidim** | โŒ | โŒ | -| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | minio | โ†“ row wires โ†’ col | mini-qr | mobilizon | moodle | navigator | nextcloud | odoo | opencloud | openproject | opentalk | openwebui | โ†“ row wires โ†’ col | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | roulette-wheel | shopware | โ†“ row wires โ†’ col | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | zammad | asset | โ†“ row wires โ†’ col | cdn | collabora | coturn | css | file | html | legal | libretranslate | logout | onlyoffice | โ†“ row wires โ†’ col | simpleicons | xmpp | -| **discourse** | โŒ | โŒ | [โœ…](https://github.com/discourse/discourse-bbb) | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-discourse/meta/services.yml) | โŒ | **discourse** | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **discourse** | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/discourse/discourse-jitsi) | โŒ | [โœ…](https://github.com/discourse/discourse-openid-connect) | โŒ | โŒ | โŒ | **discourse** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-discourse/meta/services.yml) | [โœ…](https://github.com/discourse/discourse-activity-pub) | [โœ…](https://github.com/discourse/discourse-matomo-analytics) | [โœ…](https://github.com/discourse/discourse-chat-integration) | [โœ…](https://github.com/discourse/discourse-chat-integration) | โŒ | โŒ | โŒ | **discourse** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/discourse/discourse-ai) | **discourse** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/discourse/discourse-prometheus) | โŒ | โŒ | **discourse** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **discourse** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-discourse/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-discourse/meta/services.yml) | โŒ | **discourse** | โŒ | โŒ | -| **erpnext** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-erpnext/meta/services.yml) | โŒ | **erpnext** | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **erpnext** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://docs.frappe.io/framework/user/en/guides/integration/openid_connect_and_frappe_social_login) | โŒ | โŒ | โŒ | **erpnext** | โŒ | โŒ | [โœ…](https://docs.frappe.io/erpnext/user/manual/en/setting-up-email-account) | โŒ | [โ˜‘๏ธ](../../roles/web-app-erpnext/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **erpnext** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **erpnext** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-erpnext/meta/services.yml) | โŒ | โŒ | **erpnext** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **erpnext** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-erpnext/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-erpnext/meta/services.yml) | โŒ | **erpnext** | โŒ | โŒ | -| **espocrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-espocrm/meta/services.yml) | โŒ | **espocrm** | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **espocrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://docs.espocrm.com/administration/oidc/) | โŒ | โŒ | โŒ | **espocrm** | โŒ | โŒ | [โœ…](https://docs.espocrm.com/user-guide/imap-smtp-configuration/) | โŒ | [โ˜‘๏ธ](../../roles/web-app-espocrm/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **espocrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **espocrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-espocrm/meta/services.yml) | โŒ | โŒ | **espocrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **espocrm** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-espocrm/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-espocrm/meta/services.yml) | โŒ | **espocrm** | โŒ | โŒ | -| **fediwall** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fediwall/meta/services.yml) | โŒ | **fediwall** | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **fediwall** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fediwall/meta/services.yml) | โŒ | โŒ | โŒ | **fediwall** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fediwall/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-fediwall/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **fediwall** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **fediwall** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fediwall/meta/services.yml) | โŒ | โŒ | **fediwall** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **fediwall** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fediwall/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fediwall/meta/services.yml) | โŒ | **fediwall** | โŒ | โŒ | -| **fider** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fider/meta/services.yml) | โŒ | **fider** | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | **fider** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fider/meta/services.yml) | โŒ | โŒ | โŒ | **fider** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fider/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-fider/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **fider** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **fider** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fider/meta/services.yml) | โŒ | โŒ | **fider** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **fider** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fider/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fider/meta/services.yml) | โŒ | **fider** | โŒ | โŒ | -| **flowise** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | โŒ | **flowise** | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | **flowise** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | โŒ | โŒ | โŒ | **flowise** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **flowise** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **flowise** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | โŒ | โŒ | **flowise** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **flowise** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | โŒ | **flowise** | โŒ | โŒ | -| **friendica** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-friendica/meta/services.yml) | โŒ | **friendica** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | **friendica** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-friendica/meta/services.yml) | โŒ | โŒ | โŒ | **friendica** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-friendica/meta/services.yml) | โŒ | [โœ…](https://github.com/friendica/friendica-addons) | โŒ | โŒ | โŒ | โŒ | โŒ | **friendica** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **friendica** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-friendica/meta/services.yml) | โŒ | โŒ | **friendica** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **friendica** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-friendica/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-friendica/meta/services.yml) | โŒ | **friendica** | โŒ | โŒ | -| **funkwhale** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-funkwhale/meta/services.yml) | โŒ | **funkwhale** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | **funkwhale** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-funkwhale/meta/services.yml) | โŒ | โŒ | โŒ | **funkwhale** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-funkwhale/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-funkwhale/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **funkwhale** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **funkwhale** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-funkwhale/meta/services.yml) | โŒ | โŒ | **funkwhale** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **funkwhale** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-funkwhale/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-funkwhale/meta/services.yml) | โŒ | **funkwhale** | โŒ | โŒ | -| **fusiondirectory** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fusiondirectory/meta/services.yml) | โŒ | **fusiondirectory** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | **fusiondirectory** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fusiondirectory/meta/services.yml) | โŒ | โŒ | โŒ | **fusiondirectory** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fusiondirectory/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-fusiondirectory/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **fusiondirectory** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **fusiondirectory** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fusiondirectory/meta/services.yml) | โŒ | โŒ | **fusiondirectory** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **fusiondirectory** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fusiondirectory/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fusiondirectory/meta/services.yml) | โŒ | **fusiondirectory** | โŒ | โŒ | -| **gitea** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitea/meta/services.yml) | โŒ | **gitea** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | **gitea** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitea/meta/services.yml) | โŒ | โŒ | โŒ | **gitea** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitea/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitea/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **gitea** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **gitea** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitea/meta/services.yml) | โŒ | โŒ | **gitea** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **gitea** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitea/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitea/meta/services.yml) | โŒ | **gitea** | โŒ | โŒ | -| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | minio | โ†“ row wires โ†’ col | mini-qr | mobilizon | moodle | navigator | nextcloud | odoo | opencloud | openproject | opentalk | openwebui | โ†“ row wires โ†’ col | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | roulette-wheel | shopware | โ†“ row wires โ†’ col | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | zammad | asset | โ†“ row wires โ†’ col | cdn | collabora | coturn | css | file | html | legal | libretranslate | logout | onlyoffice | โ†“ row wires โ†’ col | simpleicons | xmpp | -| **gitlab** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://docs.gitlab.com/user/project/integrations/confluence/) | [โ˜‘๏ธ](../../roles/web-app-gitlab/meta/services.yml) | โŒ | **gitlab** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **gitlab** | โ€” | โŒ | [โœ…](https://docs.gitlab.com/integration/jenkins/) | [โœ…](https://docs.gitlab.com/integration/jira/) | โŒ | โŒ | [โœ…](https://docs.gitlab.com/integration/saml/) | โŒ | โŒ | โŒ | **gitlab** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitlab/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitlab/meta/services.yml) | [โœ…](https://docs.gitlab.com/user/project/integrations/matrix/) | [โœ…](https://docs.gitlab.com/user/project/integrations/mattermost_notifications/) | โŒ | โŒ | โŒ | **gitlab** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **gitlab** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitlab/meta/services.yml) | โŒ | โŒ | **gitlab** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **gitlab** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitlab/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitlab/meta/services.yml) | โŒ | **gitlab** | โŒ | โŒ | -| **hugo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-hugo/meta/services.yml) | โŒ | **hugo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **hugo** | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-hugo/meta/services.yml) | โŒ | โŒ | โŒ | **hugo** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-hugo/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-hugo/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **hugo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **hugo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-hugo/meta/services.yml) | โŒ | โŒ | **hugo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **hugo** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-hugo/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-hugo/meta/services.yml) | โŒ | **hugo** | โŒ | โŒ | -| **jenkins** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jenkins/meta/services.yml) | โŒ | **jenkins** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://plugins.jenkins.io/gitea/) | **jenkins** | [โœ…](https://plugins.jenkins.io/gitlab-plugin) | โŒ | โ€” | โŒ | โŒ | โŒ | [โœ…](https://plugins.jenkins.io/oic-auth/) | โŒ | โŒ | โŒ | **jenkins** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jenkins/meta/services.yml) | โŒ | [โœ…](https://plugins.jenkins.io/mattermost/) | โŒ | โŒ | โŒ | **jenkins** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jenkins** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://plugins.jenkins.io/prometheus) | โŒ | โŒ | **jenkins** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jenkins** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jenkins/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jenkins/meta/services.yml) | โŒ | **jenkins** | โŒ | โŒ | -| **jira** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jira/meta/services.yml) | โŒ | **jira** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jira** | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jira/meta/services.yml) | โŒ | โŒ | โŒ | **jira** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jira/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-jira/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **jira** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jira** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jira/meta/services.yml) | โŒ | โŒ | **jira** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jira** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jira/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jira/meta/services.yml) | โŒ | **jira** | โŒ | โŒ | -| **jitsi** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jitsi/meta/services.yml) | โŒ | **jitsi** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jitsi** | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | [โ˜‘๏ธ](../../roles/web-app-jitsi/meta/services.yml) | โŒ | โŒ | โŒ | **jitsi** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jitsi/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-jitsi/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **jitsi** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jitsi** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jitsi/meta/services.yml) | โŒ | โŒ | **jitsi** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jitsi** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jitsi/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jitsi/meta/services.yml) | โŒ | **jitsi** | โŒ | โŒ | -| **joomla** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-joomla/meta/services.yml) | โŒ | **joomla** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **joomla** | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | [โœ…](../../roles/web-app-joomla/files/joomla-oidc-plugin/) | โŒ | โŒ | โŒ | **joomla** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-joomla/meta/services.yml) | โŒ | [โœ…](https://extensions.joomla.org/extension/itcs-matomo/) | โŒ | โŒ | โŒ | โŒ | โŒ | **joomla** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **joomla** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-joomla/meta/services.yml) | โŒ | โŒ | **joomla** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **joomla** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-joomla/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-joomla/meta/services.yml) | โŒ | **joomla** | โŒ | โŒ | -| **keycloak** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-keycloak/meta/services.yml) | โŒ | **keycloak** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **keycloak** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | **keycloak** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-keycloak/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-keycloak/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **keycloak** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **keycloak** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-keycloak/meta/services.yml) | โŒ | โŒ | **keycloak** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **keycloak** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-keycloak/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-keycloak/meta/services.yml) | โŒ | **keycloak** | โŒ | โŒ | -| **kix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-kix/meta/services.yml) | โŒ | **kix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **kix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-kix/meta/services.yml) | โ€” | โŒ | โŒ | **kix** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-kix/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-kix/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **kix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **kix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-kix/meta/services.yml) | โŒ | โŒ | **kix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **kix** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-kix/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-kix/meta/services.yml) | โŒ | **kix** | โŒ | โŒ | -| **lam** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-lam/meta/services.yml) | โŒ | **lam** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **lam** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-lam/meta/services.yml) | โŒ | โ€” | โŒ | **lam** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-lam/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **lam** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **lam** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-lam/meta/services.yml) | โŒ | โŒ | **lam** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **lam** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-lam/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-lam/meta/services.yml) | โŒ | **lam** | โŒ | โŒ | -| **listmonk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-listmonk/meta/services.yml) | โŒ | **listmonk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **listmonk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-listmonk/meta/services.yml) | โŒ | โŒ | โ€” | **listmonk** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-listmonk/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-listmonk/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **listmonk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **listmonk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-listmonk/meta/services.yml) | โŒ | โŒ | **listmonk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **listmonk** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-listmonk/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-listmonk/meta/services.yml) | โŒ | **listmonk** | โŒ | โŒ | -| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | minio | โ†“ row wires โ†’ col | mini-qr | mobilizon | moodle | navigator | nextcloud | odoo | opencloud | openproject | opentalk | openwebui | โ†“ row wires โ†’ col | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | roulette-wheel | shopware | โ†“ row wires โ†’ col | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | zammad | asset | โ†“ row wires โ†’ col | cdn | collabora | coturn | css | file | html | legal | libretranslate | logout | onlyoffice | โ†“ row wires โ†’ col | simpleicons | xmpp | -| **littlejs** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-littlejs/meta/services.yml) | โŒ | **littlejs** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **littlejs** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-littlejs/meta/services.yml) | โŒ | โŒ | โŒ | **littlejs** | โ€” | โŒ | [โ˜‘๏ธ](../../roles/web-app-littlejs/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-littlejs/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **littlejs** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **littlejs** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-littlejs/meta/services.yml) | โŒ | โŒ | **littlejs** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **littlejs** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-littlejs/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-littlejs/meta/services.yml) | โŒ | **littlejs** | โŒ | โŒ | -| **magento** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-magento/meta/services.yml) | โŒ | **magento** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **magento** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-magento/meta/services.yml) | โŒ | โŒ | โŒ | **magento** | โŒ | โ€” | [โ˜‘๏ธ](../../roles/web-app-magento/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-magento/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **magento** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **magento** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-magento/meta/services.yml) | โŒ | โŒ | **magento** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **magento** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-magento/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-magento/meta/services.yml) | โŒ | **magento** | โŒ | โŒ | -| **mailu** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mailu/meta/services.yml) | โŒ | **mailu** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mailu** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mailu/meta/services.yml) | โŒ | โŒ | โŒ | **mailu** | โŒ | โŒ | โ€” | โŒ | [โ˜‘๏ธ](../../roles/web-app-mailu/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **mailu** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mailu** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mailu/meta/services.yml) | โŒ | โŒ | **mailu** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mailu** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mailu/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mailu/meta/services.yml) | โŒ | **mailu** | โŒ | โŒ | -| **mastodon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mastodon/meta/services.yml) | โŒ | **mastodon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mastodon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mastodon/meta/services.yml) | โŒ | โŒ | โŒ | **mastodon** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mastodon/meta/services.yml) | โ€” | [โ˜‘๏ธ](../../roles/web-app-mastodon/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **mastodon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mastodon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mastodon/meta/services.yml) | โŒ | โŒ | **mastodon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mastodon** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mastodon/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mastodon/meta/services.yml) | โŒ | **mastodon** | โŒ | โŒ | -| **matomo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matomo/meta/services.yml) | โŒ | **matomo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **matomo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matomo/meta/services.yml) | โŒ | โŒ | โŒ | **matomo** | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | **matomo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **matomo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matomo/meta/services.yml) | โŒ | โŒ | **matomo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **matomo** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matomo/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matomo/meta/services.yml) | โŒ | **matomo** | โŒ | โŒ | -| **matrix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matrix/meta/services.yml) | โŒ | **matrix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **matrix** | [โœ…](https://github.com/matrix-org/matrix-hookshot) | โŒ | โŒ | [โœ…](https://github.com/matrix-org/matrix-hookshot) | [โœ…](https://github.com/element-hq/element-web/blob/develop/docs/jitsi.md) | โŒ | [โœ…](https://matrix-org.github.io/synapse/latest/openid.html) | โŒ | โŒ | โŒ | **matrix** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matrix/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-matrix/meta/services.yml) | โ€” | โŒ | โŒ | โŒ | โŒ | **matrix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **matrix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://matrix-org.github.io/synapse/latest/metrics-howto.html) | โŒ | โŒ | **matrix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **matrix** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matrix/meta/services.yml) | [โ˜‘๏ธ](../../roles/web-app-matrix/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matrix/meta/services.yml) | โŒ | **matrix** | โŒ | โŒ | -| **mattermost** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mattermost/meta/services.yml) | โŒ | **mattermost** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mattermost** | [โœ…](https://github.com/mattermost/mattermost-plugin-gitlab) | โŒ | [โœ…](https://github.com/mattermost/mattermost-plugin-jenkins) | [โœ…](https://github.com/mattermost/mattermost-plugin-jira) | [โœ…](https://github.com/mattermost-community/mattermost-plugin-jitsi) | โŒ | [๐Ÿช™](https://docs.mattermost.com/onboard/sso-saml.html) | โŒ | โŒ | โŒ | **mattermost** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mattermost/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-mattermost/meta/services.yml) | โŒ | โ€” | โŒ | โŒ | โŒ | **mattermost** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/mattermost/mattermost-plugin-agents) | **mattermost** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/cpanato/mattermost-plugin-alertmanager) | โŒ | โŒ | **mattermost** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mattermost** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mattermost/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mattermost/meta/services.yml) | โŒ | **mattermost** | โŒ | โŒ | -| **mediawiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mediawiki/meta/services.yml) | โŒ | **mediawiki** | [โœ…](https://www.mediawiki.org/wiki/Extension:DiscourseSsoConsumer) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mediawiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://www.mediawiki.org/wiki/Extension:OpenID_Connect) | โŒ | โŒ | โŒ | **mediawiki** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mediawiki/meta/services.yml) | โŒ | [โœ…](https://www.mediawiki.org/wiki/Extension:Matomo) | โŒ | โŒ | โ€” | โŒ | [โœ…](https://www.mediawiki.org/wiki/Extension:AWS) | **mediawiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://www.mediawiki.org/wiki/Extension:AIEditingAssistant) | **mediawiki** | [โœ…](https://www.mediawiki.org/wiki/Extension:PeerTubeEmbed) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mediawiki/meta/services.yml) | โŒ | โŒ | **mediawiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mediawiki** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mediawiki/meta/services.yml) | โŒ | โŒ | โŒ | [โœ…](https://www.mediawiki.org/wiki/Extension:MachineTranslation) | [โ˜‘๏ธ](../../roles/web-app-mediawiki/meta/services.yml) | โŒ | **mediawiki** | โŒ | โŒ | -| **mig** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mig/meta/services.yml) | โŒ | **mig** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mig** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mig/meta/services.yml) | โŒ | โŒ | โŒ | **mig** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mig/meta/services.yml) | โŒ | โŒ | โŒ | โ€” | โŒ | **mig** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mig** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mig/meta/services.yml) | โŒ | โŒ | **mig** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mig** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mig/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mig/meta/services.yml) | โŒ | **mig** | โŒ | โŒ | -| **minio** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-minio/meta/services.yml) | โŒ | **minio** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **minio** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-minio/meta/services.yml) | โŒ | โŒ | โŒ | **minio** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-minio/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โ€” | **minio** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **minio** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-minio/meta/services.yml) | โŒ | โŒ | **minio** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **minio** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-minio/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-minio/meta/services.yml) | โŒ | **minio** | โŒ | โŒ | -| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | minio | โ†“ row wires โ†’ col | mini-qr | mobilizon | moodle | navigator | nextcloud | odoo | opencloud | openproject | opentalk | openwebui | โ†“ row wires โ†’ col | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | roulette-wheel | shopware | โ†“ row wires โ†’ col | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | zammad | asset | โ†“ row wires โ†’ col | cdn | collabora | coturn | css | file | html | legal | libretranslate | logout | onlyoffice | โ†“ row wires โ†’ col | simpleicons | xmpp | -| **mini-qr** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mini-qr/meta/services.yml) | โŒ | **mini-qr** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mini-qr** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mini-qr/meta/services.yml) | โŒ | โŒ | โŒ | **mini-qr** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mini-qr/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **mini-qr** | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mini-qr** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mini-qr/meta/services.yml) | โŒ | โŒ | **mini-qr** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mini-qr** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mini-qr/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mini-qr/meta/services.yml) | โŒ | **mini-qr** | โŒ | โŒ | -| **mobilizon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mobilizon/meta/services.yml) | โŒ | **mobilizon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mobilizon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mobilizon/meta/services.yml) | โŒ | โŒ | โŒ | **mobilizon** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mobilizon/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-mobilizon/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **mobilizon** | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mobilizon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mobilizon/meta/services.yml) | โŒ | โŒ | **mobilizon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mobilizon** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mobilizon/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mobilizon/meta/services.yml) | โŒ | **mobilizon** | โŒ | โŒ | -| **moodle** | โŒ | โŒ | [โœ…](https://moodle.org/plugins/mod_bigbluebuttonbn) | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-moodle/meta/services.yml) | โŒ | **moodle** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **moodle** | โŒ | โŒ | โŒ | โŒ | [โœ…](https://moodle.org/plugins/mod_jitsi) | โŒ | [โœ…](https://moodle.org/plugins/auth_oidc) | โŒ | โŒ | โŒ | **moodle** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-moodle/meta/services.yml) | โŒ | [โœ…](https://moodle.org/plugins/tool_webanalytics) | [โœ…](https://docs.moodle.org/en/Matrix) | โŒ | โŒ | โŒ | โŒ | **moodle** | โŒ | โŒ | โ€” | โŒ | [โœ…](https://moodle.org/plugins/repository_owncloud) | โŒ | โŒ | โŒ | โŒ | [โœ…](https://moodle.org/plugins/aiprovider_openwebui) | **moodle** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-moodle/meta/services.yml) | โŒ | โŒ | **moodle** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **moodle** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-moodle/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-moodle/meta/services.yml) | โŒ | **moodle** | โŒ | โŒ | -| **navigator** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-navigator/meta/services.yml) | โŒ | **navigator** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **navigator** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-navigator/meta/services.yml) | โŒ | โŒ | โŒ | **navigator** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-navigator/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **navigator** | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **navigator** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-navigator/meta/services.yml) | โŒ | โŒ | **navigator** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **navigator** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-navigator/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-navigator/meta/services.yml) | โŒ | **navigator** | โŒ | โŒ | -| **nextcloud** | โŒ | โŒ | [โœ…](https://apps.nextcloud.com/apps/bbb) | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-nextcloud/meta/services.yml) | โŒ | **nextcloud** | [โœ…](https://github.com/nextcloud/integration_discourse) | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/nextcloud/integration_openai) | โŒ | โŒ | โŒ | โŒ | **nextcloud** | [โœ…](https://github.com/nextcloud/integration_gitlab) | โŒ | โŒ | [โœ…](https://github.com/nextcloud/integration_jira) | โŒ | โŒ | [โœ…](https://github.com/nextcloud/user_oidc) | โŒ | โŒ | โŒ | **nextcloud** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-nextcloud/meta/services.yml) | [โœ…](https://github.com/nextcloud/integration_mastodon) | [โœ…](https://apps.nextcloud.com/apps/matomo) | [โœ…](https://github.com/nextcloud/integration_matrix) | [โœ…](https://github.com/nextcloud/integration_mattermost) | โŒ | โŒ | โŒ | **nextcloud** | โŒ | โŒ | [โœ…](https://github.com/nextcloud/integration_moodle) | โŒ | โ€” | โŒ | โŒ | [โœ…](https://github.com/nextcloud/integration_openproject) | โŒ | [โœ…](https://github.com/nextcloud/integration_openai) | **nextcloud** | [โœ…](https://github.com/nextcloud/integration_peertube) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-nextcloud/meta/services.yml) | โŒ | โŒ | **nextcloud** | โŒ | โŒ | โŒ | [โœ…](https://github.com/eneiluj/integration_suitecrm) | โŒ | โŒ | [โœ…](https://apps.nextcloud.com/apps/xwiki) | โŒ | [โœ…](https://github.com/nextcloud/integration_zammad) | โŒ | **nextcloud** | โŒ | [โœ…](https://github.com/nextcloud/richdocuments) | [โ˜‘๏ธ](../../roles/web-app-nextcloud/meta/services.yml) | [โ˜‘๏ธ](../../roles/web-app-nextcloud/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-nextcloud/meta/services.yml) | [โœ…](https://github.com/ONLYOFFICE/onlyoffice-nextcloud) | **nextcloud** | โŒ | โŒ | -| **odoo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-odoo/meta/services.yml) | โŒ | **odoo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **odoo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/OCA/server-auth/tree/16.0/auth_oidc) | โŒ | โŒ | โŒ | **odoo** | โŒ | โŒ | [โœ…](https://www.odoo.com/documentation/latest/applications/general/email_communication.html) | โŒ | [โ˜‘๏ธ](../../roles/web-app-odoo/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **odoo** | โŒ | โŒ | โŒ | โŒ | [๐Ÿช™](https://apps.odoo.com/apps/modules/19.0/nextcloud_odoo_integration) | โ€” | โŒ | โŒ | โŒ | โŒ | **odoo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-odoo/meta/services.yml) | โŒ | โŒ | **odoo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **odoo** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-odoo/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-odoo/meta/services.yml) | โŒ | **odoo** | โŒ | โŒ | -| **opencloud** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opencloud/meta/services.yml) | โŒ | **opencloud** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **opencloud** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opencloud/meta/services.yml) | โŒ | โŒ | โŒ | **opencloud** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opencloud/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-opencloud/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **opencloud** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | **opencloud** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opencloud/meta/services.yml) | โŒ | โŒ | **opencloud** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **opencloud** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opencloud/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opencloud/meta/services.yml) | โŒ | **opencloud** | โŒ | โŒ | -| **openproject** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openproject/meta/services.yml) | โŒ | **openproject** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **openproject** | [โœ…](https://www.openproject.org/docs/system-admin-guide/integrations/gitlab-integration/) | โŒ | โŒ | โŒ | โŒ | โŒ | [๐Ÿช™](https://www.openproject.org/docs/system-admin-guide/authentication/openid-providers/) | โŒ | โŒ | โŒ | **openproject** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openproject/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-openproject/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **openproject** | โŒ | โŒ | โŒ | โŒ | [โœ…](https://www.openproject.org/docs/system-admin-guide/integrations/nextcloud/) | โŒ | โŒ | โ€” | โŒ | โŒ | **openproject** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openproject/meta/services.yml) | โŒ | โŒ | **openproject** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **openproject** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openproject/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openproject/meta/services.yml) | โŒ | **openproject** | โŒ | โŒ | -| **opentalk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | โŒ | **opentalk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **opentalk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | โŒ | โŒ | โŒ | **opentalk** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **opentalk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | **opentalk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | โŒ | โŒ | **opentalk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **opentalk** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | โŒ | **opentalk** | โŒ | โŒ | -| **openwebui** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | โŒ | **openwebui** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **openwebui** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | โŒ | โŒ | โŒ | **openwebui** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **openwebui** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | **openwebui** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | โŒ | โŒ | **openwebui** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **openwebui** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | โŒ | **openwebui** | โŒ | โŒ | -| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | minio | โ†“ row wires โ†’ col | mini-qr | mobilizon | moodle | navigator | nextcloud | odoo | opencloud | openproject | opentalk | openwebui | โ†“ row wires โ†’ col | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | roulette-wheel | shopware | โ†“ row wires โ†’ col | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | zammad | asset | โ†“ row wires โ†’ col | cdn | collabora | coturn | css | file | html | legal | libretranslate | logout | onlyoffice | โ†“ row wires โ†’ col | simpleicons | xmpp | -| **peertube** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-peertube/meta/services.yml) | โŒ | **peertube** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **peertube** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://www.npmjs.com/package/peertube-plugin-auth-openid-connect) | โŒ | โŒ | โŒ | **peertube** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-peertube/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-peertube/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **peertube** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **peertube** | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-peertube/meta/services.yml) | โŒ | โŒ | **peertube** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **peertube** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-peertube/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-peertube/meta/services.yml) | โŒ | **peertube** | โŒ | โŒ | -| **pgadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pgadmin/meta/services.yml) | โŒ | **pgadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pgadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pgadmin/meta/services.yml) | โŒ | โŒ | โŒ | **pgadmin** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pgadmin/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-pgadmin/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **pgadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pgadmin** | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pgadmin/meta/services.yml) | โŒ | โŒ | **pgadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pgadmin** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pgadmin/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pgadmin/meta/services.yml) | โŒ | **pgadmin** | โŒ | โŒ | -| **phpldapadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpldapadmin/meta/services.yml) | โŒ | **phpldapadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **phpldapadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpldapadmin/meta/services.yml) | โŒ | โŒ | โŒ | **phpldapadmin** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpldapadmin/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **phpldapadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **phpldapadmin** | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpldapadmin/meta/services.yml) | โŒ | โŒ | **phpldapadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **phpldapadmin** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpldapadmin/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpldapadmin/meta/services.yml) | โŒ | **phpldapadmin** | โŒ | โŒ | -| **phpmyadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpmyadmin/meta/services.yml) | โŒ | **phpmyadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **phpmyadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpmyadmin/meta/services.yml) | โŒ | โŒ | โŒ | **phpmyadmin** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpmyadmin/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpmyadmin/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **phpmyadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **phpmyadmin** | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpmyadmin/meta/services.yml) | โŒ | โŒ | **phpmyadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **phpmyadmin** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpmyadmin/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpmyadmin/meta/services.yml) | โŒ | **phpmyadmin** | โŒ | โŒ | -| **pixelfed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pixelfed/meta/services.yml) | โŒ | **pixelfed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pixelfed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pixelfed/meta/services.yml) | โŒ | โŒ | โŒ | **pixelfed** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pixelfed/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-pixelfed/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **pixelfed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pixelfed** | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pixelfed/meta/services.yml) | โŒ | โŒ | **pixelfed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pixelfed** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pixelfed/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pixelfed/meta/services.yml) | โŒ | **pixelfed** | โŒ | โŒ | -| **postmarks** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-postmarks/meta/services.yml) | โŒ | **postmarks** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **postmarks** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-postmarks/meta/services.yml) | โŒ | โŒ | โŒ | **postmarks** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-postmarks/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-postmarks/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **postmarks** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **postmarks** | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | [โ˜‘๏ธ](../../roles/web-app-postmarks/meta/services.yml) | โŒ | โŒ | **postmarks** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **postmarks** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-postmarks/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-postmarks/meta/services.yml) | โŒ | **postmarks** | โŒ | โŒ | -| **pretix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pretix/meta/services.yml) | โŒ | **pretix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pretix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://docs.pretix.eu/en/latest/admin/installation/index.html) | โŒ | โŒ | โŒ | **pretix** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pretix/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-pretix/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **pretix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pretix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | [โ˜‘๏ธ](../../roles/web-app-pretix/meta/services.yml) | โŒ | โŒ | **pretix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pretix** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pretix/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pretix/meta/services.yml) | โŒ | **pretix** | โŒ | โŒ | -| **prometheus** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-prometheus/meta/services.yml) | โŒ | **prometheus** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **prometheus** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-prometheus/meta/services.yml) | โŒ | โŒ | โŒ | **prometheus** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-prometheus/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-prometheus/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **prometheus** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **prometheus** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | **prometheus** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **prometheus** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-prometheus/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-prometheus/meta/services.yml) | โŒ | **prometheus** | โŒ | โŒ | -| **roulette-wheel** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-roulette-wheel/meta/services.yml) | โŒ | **roulette-wheel** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **roulette-wheel** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-roulette-wheel/meta/services.yml) | โŒ | โŒ | โŒ | **roulette-wheel** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-roulette-wheel/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-roulette-wheel/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **roulette-wheel** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **roulette-wheel** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-roulette-wheel/meta/services.yml) | โ€” | โŒ | **roulette-wheel** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **roulette-wheel** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-roulette-wheel/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-roulette-wheel/meta/services.yml) | โŒ | **roulette-wheel** | โŒ | โŒ | -| **shopware** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-shopware/meta/services.yml) | โŒ | **shopware** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **shopware** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-shopware/meta/services.yml) | โŒ | โŒ | โŒ | **shopware** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-shopware/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-shopware/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **shopware** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **shopware** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-shopware/meta/services.yml) | โŒ | โ€” | **shopware** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **shopware** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-shopware/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-shopware/meta/services.yml) | โŒ | **shopware** | โŒ | โŒ | -| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | minio | โ†“ row wires โ†’ col | mini-qr | mobilizon | moodle | navigator | nextcloud | odoo | opencloud | openproject | opentalk | openwebui | โ†“ row wires โ†’ col | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | roulette-wheel | shopware | โ†“ row wires โ†’ col | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | zammad | asset | โ†“ row wires โ†’ col | cdn | collabora | coturn | css | file | html | legal | libretranslate | logout | onlyoffice | โ†“ row wires โ†’ col | simpleicons | xmpp | -| **snipe-it** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-snipe-it/meta/services.yml) | โŒ | **snipe-it** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **snipe-it** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-snipe-it/meta/services.yml) | โŒ | โŒ | โŒ | **snipe-it** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-snipe-it/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-snipe-it/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **snipe-it** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **snipe-it** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-snipe-it/meta/services.yml) | โŒ | โŒ | **snipe-it** | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **snipe-it** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-snipe-it/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-snipe-it/meta/services.yml) | โŒ | **snipe-it** | โŒ | โŒ | -| **socialhome** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-socialhome/meta/services.yml) | โŒ | **socialhome** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **socialhome** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-socialhome/meta/services.yml) | โŒ | โŒ | โŒ | **socialhome** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **socialhome** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **socialhome** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-socialhome/meta/services.yml) | โŒ | โŒ | **socialhome** | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **socialhome** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-socialhome/meta/services.yml) | โŒ | **socialhome** | โŒ | โŒ | -| **sphinx** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-sphinx/meta/services.yml) | โŒ | **sphinx** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **sphinx** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-sphinx/meta/services.yml) | โŒ | โŒ | โŒ | **sphinx** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-sphinx/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-sphinx/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **sphinx** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **sphinx** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-sphinx/meta/services.yml) | โŒ | โŒ | **sphinx** | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **sphinx** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-sphinx/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-sphinx/meta/services.yml) | โŒ | **sphinx** | โŒ | โŒ | -| **suitecrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-suitecrm/meta/services.yml) | โŒ | **suitecrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **suitecrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://docs.suitecrm.com/8.x/admin/configuration/saml/8.7.0-saml-configuration/) | โŒ | โŒ | โŒ | **suitecrm** | โŒ | โŒ | [โœ…](https://github.com/SuiteCRM/SuiteCRM) | โŒ | [โ˜‘๏ธ](../../roles/web-app-suitecrm/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **suitecrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **suitecrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-suitecrm/meta/services.yml) | โŒ | โŒ | **suitecrm** | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **suitecrm** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-suitecrm/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-suitecrm/meta/services.yml) | โŒ | **suitecrm** | โŒ | โŒ | -| **taiga** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-taiga/meta/services.yml) | โŒ | **taiga** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **taiga** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/taigaio/taiga-contrib-oidc-auth) | โŒ | โŒ | โŒ | **taiga** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-taiga/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-taiga/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **taiga** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **taiga** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-taiga/meta/services.yml) | โŒ | โŒ | **taiga** | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | **taiga** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-taiga/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-taiga/meta/services.yml) | โŒ | **taiga** | โŒ | โŒ | -| **wordpress** | โŒ | โŒ | [โœ…](https://wordpress.org/plugins/video-conferencing-with-bbb/) | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-wordpress/meta/services.yml) | โŒ | **wordpress** | [โœ…](https://wordpress.org/plugins/wp-discourse/) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **wordpress** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://wordpress.org/plugins/daggerhart-openid-connect-generic/) | โŒ | โŒ | [โœ…](https://wordpress.org/plugins/integration-for-listmonk-mailing-list-and-newsletter-manager/) | **wordpress** | โŒ | โŒ | โŒ | [โœ…](https://wordpress.org/plugins/activitypub/) | [โœ…](https://wordpress.org/plugins/matomo/) | โŒ | โŒ | โŒ | โŒ | โŒ | **wordpress** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **wordpress** | [โœ…](https://wordpress.org/plugins/video-manager-for-peertube/) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-wordpress/meta/services.yml) | โŒ | โŒ | **wordpress** | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | **wordpress** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-wordpress/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-wordpress/meta/services.yml) | โŒ | **wordpress** | โŒ | โŒ | -| **xwiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-xwiki/meta/services.yml) | โŒ | **xwiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xwiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://extensions.xwiki.org/xwiki/bin/view/Extension/OpenID%20Connect/) | โŒ | โŒ | โŒ | **xwiki** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-xwiki/meta/services.yml) | โŒ | [โœ…](https://extensions.xwiki.org/xwiki/bin/view/Extension/Piwiki%20Integration) | โŒ | โŒ | โŒ | โŒ | โŒ | **xwiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xwiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-xwiki/meta/services.yml) | โŒ | โŒ | **xwiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | **xwiki** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-xwiki/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-xwiki/meta/services.yml) | โŒ | **xwiki** | โŒ | โŒ | -| **yourls** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-yourls/meta/services.yml) | โŒ | **yourls** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **yourls** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-yourls/meta/services.yml) | โŒ | โŒ | โŒ | **yourls** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-yourls/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-yourls/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **yourls** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **yourls** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-yourls/meta/services.yml) | โŒ | โŒ | **yourls** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | **yourls** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-yourls/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-yourls/meta/services.yml) | โŒ | **yourls** | โŒ | โŒ | -| **zammad** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-zammad/meta/services.yml) | โŒ | **zammad** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **zammad** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://admin-docs.zammad.org/en/latest/settings/security/third-party/saml.html) | โŒ | โŒ | โŒ | **zammad** | โŒ | โŒ | [โœ…](https://admin-docs.zammad.org/en/latest/channels/email/index.html) | โŒ | [โ˜‘๏ธ](../../roles/web-app-zammad/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **zammad** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **zammad** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-zammad/meta/services.yml) | โŒ | โŒ | **zammad** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | **zammad** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-zammad/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-zammad/meta/services.yml) | โŒ | **zammad** | โŒ | โŒ | -| **asset** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **asset** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **asset** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **asset** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-asset/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **asset** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **asset** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-asset/meta/services.yml) | โŒ | โŒ | **asset** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | **asset** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-asset/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **asset** | โŒ | โŒ | -| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | minio | โ†“ row wires โ†’ col | mini-qr | mobilizon | moodle | navigator | nextcloud | odoo | opencloud | openproject | opentalk | openwebui | โ†“ row wires โ†’ col | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | roulette-wheel | shopware | โ†“ row wires โ†’ col | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | zammad | asset | โ†“ row wires โ†’ col | cdn | collabora | coturn | css | file | html | legal | libretranslate | logout | onlyoffice | โ†“ row wires โ†’ col | simpleicons | xmpp | -| **cdn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-cdn/meta/services.yml) | โŒ | **cdn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **cdn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **cdn** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-cdn/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **cdn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **cdn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-cdn/meta/services.yml) | โŒ | โŒ | **cdn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **cdn** | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **cdn** | โŒ | โŒ | -| **collabora** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **collabora** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **collabora** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **collabora** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-collabora/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **collabora** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **collabora** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-collabora/meta/services.yml) | โŒ | โŒ | **collabora** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **collabora** | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **collabora** | โŒ | โŒ | -| **coturn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **coturn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **coturn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **coturn** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-coturn/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **coturn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **coturn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-coturn/meta/services.yml) | โŒ | โŒ | **coturn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **coturn** | โŒ | โŒ | โ€” | [โ˜‘๏ธ](../../roles/web-svc-coturn/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **coturn** | โŒ | โŒ | -| **css** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **css** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **css** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **css** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-css/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **css** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **css** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-css/meta/services.yml) | โŒ | โŒ | **css** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **css** | [โ˜‘๏ธ](../../roles/web-svc-css/meta/services.yml) | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **css** | โŒ | โŒ | -| **file** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **file** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **file** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **file** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-file/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **file** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **file** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-file/meta/services.yml) | โŒ | โŒ | **file** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **file** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-file/meta/services.yml) | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | **file** | โŒ | โŒ | -| **html** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **html** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **html** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **html** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-html/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **html** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **html** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-html/meta/services.yml) | โŒ | โŒ | **html** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **html** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-html/meta/services.yml) | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | **html** | โŒ | โŒ | -| **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-legal/meta/services.yml) | โŒ | โŒ | **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | **legal** | โŒ | โŒ | -| **libretranslate** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **libretranslate** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **libretranslate** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-libretranslate/meta/services.yml) | โŒ | โŒ | โŒ | **libretranslate** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-libretranslate/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **libretranslate** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **libretranslate** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-libretranslate/meta/services.yml) | โŒ | โŒ | **libretranslate** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **libretranslate** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-libretranslate/meta/services.yml) | โŒ | โŒ | โŒ | โ€” | [โ˜‘๏ธ](../../roles/web-svc-libretranslate/meta/services.yml) | โŒ | **libretranslate** | โŒ | โŒ | -| **logout** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **logout** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **logout** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **logout** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-logout/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **logout** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **logout** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-logout/meta/services.yml) | โŒ | โŒ | **logout** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **logout** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-logout/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | **logout** | โŒ | โŒ | -| **onlyoffice** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **onlyoffice** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **onlyoffice** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **onlyoffice** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-onlyoffice/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **onlyoffice** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **onlyoffice** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-onlyoffice/meta/services.yml) | โŒ | โŒ | **onlyoffice** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **onlyoffice** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-onlyoffice/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | **onlyoffice** | โŒ | โŒ | -| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | minio | โ†“ row wires โ†’ col | mini-qr | mobilizon | moodle | navigator | nextcloud | odoo | opencloud | openproject | opentalk | openwebui | โ†“ row wires โ†’ col | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | roulette-wheel | shopware | โ†“ row wires โ†’ col | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | zammad | asset | โ†“ row wires โ†’ col | cdn | collabora | coturn | css | file | html | legal | libretranslate | logout | onlyoffice | โ†“ row wires โ†’ col | simpleicons | xmpp | -| **simpleicons** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-simpleicons/meta/services.yml) | โŒ | **simpleicons** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **simpleicons** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-simpleicons/meta/services.yml) | โŒ | โŒ | โŒ | **simpleicons** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-simpleicons/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **simpleicons** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **simpleicons** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-simpleicons/meta/services.yml) | โŒ | โŒ | **simpleicons** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **simpleicons** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-simpleicons/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **simpleicons** | โ€” | โŒ | -| **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-xmpp/meta/services.yml) | โŒ | โŒ | โŒ | **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-xmpp/meta/services.yml) | โŒ | โŒ | **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-xmpp/meta/services.yml) | โŒ | **xmpp** | โŒ | โ€” | +| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | litellm | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | โ†“ row wires โ†’ col | minio | mini-qr | mobilizon | moodle | n8n | navigator | nextcloud | odoo | opencloud | openproject | โ†“ row wires โ†’ col | opentalk | openwebui | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | โ†“ row wires โ†’ col | roulette-wheel | shopware | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | โ†“ row wires โ†’ col | zammad | asset | cdn | collabora | coturn | css | file | html | legal | libretranslate | โ†“ row wires โ†’ col | logout | onlyoffice | simpleicons | xmpp | +|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| +| **akaunting** | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-akaunting/meta/services.yml) | โŒ | **akaunting** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **akaunting** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-akaunting/meta/services.yml) | โŒ | โŒ | โŒ | **akaunting** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-akaunting/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-akaunting/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **akaunting** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **akaunting** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-akaunting/meta/services.yml) | **akaunting** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **akaunting** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-akaunting/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **akaunting** | [โ˜‘๏ธ](../../roles/web-app-akaunting/meta/services.yml) | โŒ | โŒ | โŒ | +| **baserow** | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-baserow/meta/services.yml) | โŒ | **baserow** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **baserow** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [๐Ÿช™](https://baserow.io/user-docs/configure-openid-connect-for-oauth-2-sso) | โŒ | โŒ | โŒ | **baserow** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-baserow/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-baserow/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **baserow** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **baserow** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-baserow/meta/services.yml) | **baserow** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **baserow** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-baserow/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **baserow** | [โ˜‘๏ธ](../../roles/web-app-baserow/meta/services.yml) | โŒ | โŒ | โŒ | +| **bigbluebutton** | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | โŒ | **bigbluebutton** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bigbluebutton** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://docs.bigbluebutton.org/greenlight/v3/external-authentication/) | โŒ | โŒ | โŒ | **bigbluebutton** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **bigbluebutton** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bigbluebutton** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | **bigbluebutton** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bigbluebutton** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **bigbluebutton** | [โ˜‘๏ธ](../../roles/web-app-bigbluebutton/meta/services.yml) | โŒ | โŒ | โŒ | +| **bluesky** | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bluesky/meta/services.yml) | โŒ | **bluesky** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bluesky** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bluesky/meta/services.yml) | โŒ | โŒ | โŒ | **bluesky** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bluesky/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-bluesky/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **bluesky** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bluesky** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bluesky/meta/services.yml) | **bluesky** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bluesky** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bluesky/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **bluesky** | [โ˜‘๏ธ](../../roles/web-app-bluesky/meta/services.yml) | โŒ | โŒ | โŒ | +| **bookwyrm** | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bookwyrm/meta/services.yml) | โŒ | **bookwyrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bookwyrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bookwyrm/meta/services.yml) | โŒ | โŒ | โŒ | **bookwyrm** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bookwyrm/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-bookwyrm/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **bookwyrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bookwyrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bookwyrm/meta/services.yml) | **bookwyrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bookwyrm** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bookwyrm/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **bookwyrm** | [โ˜‘๏ธ](../../roles/web-app-bookwyrm/meta/services.yml) | โŒ | โŒ | โŒ | +| **bridgy-fed** | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bridgy-fed/meta/services.yml) | โŒ | **bridgy-fed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bridgy-fed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bridgy-fed/meta/services.yml) | โŒ | โŒ | โŒ | **bridgy-fed** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bridgy-fed/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-bridgy-fed/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **bridgy-fed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bridgy-fed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bridgy-fed/meta/services.yml) | **bridgy-fed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **bridgy-fed** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-bridgy-fed/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **bridgy-fed** | [โ˜‘๏ธ](../../roles/web-app-bridgy-fed/meta/services.yml) | โŒ | โŒ | โŒ | +| **chess** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | [โ˜‘๏ธ](../../roles/web-app-chess/meta/services.yml) | โŒ | **chess** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **chess** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-chess/meta/services.yml) | โŒ | โŒ | โŒ | **chess** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-chess/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **chess** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **chess** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-chess/meta/services.yml) | **chess** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **chess** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-chess/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **chess** | [โ˜‘๏ธ](../../roles/web-app-chess/meta/services.yml) | โŒ | โŒ | โŒ | +| **confluence** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | [โ˜‘๏ธ](../../roles/web-app-confluence/meta/services.yml) | โŒ | **confluence** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **confluence** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-confluence/meta/services.yml) | โŒ | โŒ | โŒ | **confluence** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-confluence/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-confluence/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **confluence** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **confluence** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-confluence/meta/services.yml) | **confluence** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **confluence** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-confluence/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **confluence** | [โ˜‘๏ธ](../../roles/web-app-confluence/meta/services.yml) | โŒ | โŒ | โŒ | +| **dashboard** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | **dashboard** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **dashboard** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-dashboard/meta/services.yml) | โŒ | โŒ | โŒ | **dashboard** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-dashboard/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **dashboard** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **dashboard** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-dashboard/meta/services.yml) | **dashboard** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **dashboard** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-dashboard/meta/services.yml) | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-dashboard/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **dashboard** | [โ˜‘๏ธ](../../roles/web-app-dashboard/meta/services.yml) | โŒ | โŒ | โŒ | +| **decidim** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-decidim/meta/services.yml) | โ€” | **decidim** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **decidim** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-decidim/meta/services.yml) | โŒ | โŒ | โŒ | **decidim** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-decidim/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-decidim/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **decidim** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **decidim** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-decidim/meta/services.yml) | **decidim** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **decidim** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-decidim/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **decidim** | [โ˜‘๏ธ](../../roles/web-app-decidim/meta/services.yml) | โŒ | โŒ | โŒ | +| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | litellm | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | โ†“ row wires โ†’ col | minio | mini-qr | mobilizon | moodle | n8n | navigator | nextcloud | odoo | opencloud | openproject | โ†“ row wires โ†’ col | opentalk | openwebui | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | โ†“ row wires โ†’ col | roulette-wheel | shopware | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | โ†“ row wires โ†’ col | zammad | asset | cdn | collabora | coturn | css | file | html | legal | libretranslate | โ†“ row wires โ†’ col | logout | onlyoffice | simpleicons | xmpp | +| **discourse** | โŒ | โŒ | [โœ…](https://github.com/discourse/discourse-bbb) | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-discourse/meta/services.yml) | โŒ | **discourse** | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **discourse** | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/discourse/discourse-jitsi) | โŒ | [โœ…](https://github.com/discourse/discourse-openid-connect) | โŒ | โŒ | โŒ | **discourse** | [โ˜‘๏ธ](../../roles/web-app-discourse/meta/services.yml) | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-discourse/meta/services.yml) | [โœ…](https://github.com/discourse/discourse-activity-pub) | [โœ…](https://github.com/discourse/discourse-matomo-analytics) | [โœ…](https://github.com/discourse/discourse-chat-integration) | [โœ…](https://github.com/discourse/discourse-chat-integration) | โŒ | โŒ | **discourse** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **discourse** | โŒ | [โœ…](https://github.com/discourse/discourse-ai) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/discourse/discourse-prometheus) | **discourse** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **discourse** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-discourse/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **discourse** | [โ˜‘๏ธ](../../roles/web-app-discourse/meta/services.yml) | โŒ | โŒ | โŒ | +| **erpnext** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-erpnext/meta/services.yml) | โŒ | **erpnext** | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **erpnext** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://docs.frappe.io/framework/user/en/guides/integration/openid_connect_and_frappe_social_login) | โŒ | โŒ | โŒ | **erpnext** | โŒ | โŒ | โŒ | [โœ…](https://docs.frappe.io/erpnext/user/manual/en/setting-up-email-account) | โŒ | [โ˜‘๏ธ](../../roles/web-app-erpnext/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **erpnext** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **erpnext** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-erpnext/meta/services.yml) | **erpnext** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **erpnext** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-erpnext/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **erpnext** | [โ˜‘๏ธ](../../roles/web-app-erpnext/meta/services.yml) | โŒ | โŒ | โŒ | +| **espocrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-espocrm/meta/services.yml) | โŒ | **espocrm** | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **espocrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://docs.espocrm.com/administration/oidc/) | โŒ | โŒ | โŒ | **espocrm** | โŒ | โŒ | โŒ | [โœ…](https://docs.espocrm.com/user-guide/imap-smtp-configuration/) | โŒ | [โ˜‘๏ธ](../../roles/web-app-espocrm/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **espocrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **espocrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-espocrm/meta/services.yml) | **espocrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **espocrm** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-espocrm/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **espocrm** | [โ˜‘๏ธ](../../roles/web-app-espocrm/meta/services.yml) | โŒ | โŒ | โŒ | +| **fediwall** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fediwall/meta/services.yml) | โŒ | **fediwall** | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **fediwall** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fediwall/meta/services.yml) | โŒ | โŒ | โŒ | **fediwall** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fediwall/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-fediwall/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **fediwall** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **fediwall** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fediwall/meta/services.yml) | **fediwall** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **fediwall** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fediwall/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **fediwall** | [โ˜‘๏ธ](../../roles/web-app-fediwall/meta/services.yml) | โŒ | โŒ | โŒ | +| **fider** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fider/meta/services.yml) | โŒ | **fider** | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | **fider** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fider/meta/services.yml) | โŒ | โŒ | โŒ | **fider** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fider/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-fider/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **fider** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **fider** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fider/meta/services.yml) | **fider** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **fider** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fider/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **fider** | [โ˜‘๏ธ](../../roles/web-app-fider/meta/services.yml) | โŒ | โŒ | โŒ | +| **flowise** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | โŒ | **flowise** | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | **flowise** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | โŒ | โŒ | โŒ | **flowise** | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **flowise** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **flowise** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | **flowise** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **flowise** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **flowise** | [โ˜‘๏ธ](../../roles/web-app-flowise/meta/services.yml) | โŒ | โŒ | โŒ | +| **friendica** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-friendica/meta/services.yml) | โŒ | **friendica** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | **friendica** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-friendica/meta/services.yml) | โŒ | โŒ | โŒ | **friendica** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-friendica/meta/services.yml) | โŒ | [โœ…](https://github.com/friendica/friendica-addons) | โŒ | โŒ | โŒ | โŒ | **friendica** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **friendica** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-friendica/meta/services.yml) | **friendica** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **friendica** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-friendica/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **friendica** | [โ˜‘๏ธ](../../roles/web-app-friendica/meta/services.yml) | โŒ | โŒ | โŒ | +| **funkwhale** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-funkwhale/meta/services.yml) | โŒ | **funkwhale** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | **funkwhale** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-funkwhale/meta/services.yml) | โŒ | โŒ | โŒ | **funkwhale** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-funkwhale/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-funkwhale/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **funkwhale** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **funkwhale** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-funkwhale/meta/services.yml) | **funkwhale** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **funkwhale** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-funkwhale/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **funkwhale** | [โ˜‘๏ธ](../../roles/web-app-funkwhale/meta/services.yml) | โŒ | โŒ | โŒ | +| **fusiondirectory** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fusiondirectory/meta/services.yml) | โŒ | **fusiondirectory** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | **fusiondirectory** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fusiondirectory/meta/services.yml) | โŒ | โŒ | โŒ | **fusiondirectory** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fusiondirectory/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-fusiondirectory/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **fusiondirectory** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **fusiondirectory** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fusiondirectory/meta/services.yml) | **fusiondirectory** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **fusiondirectory** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-fusiondirectory/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **fusiondirectory** | [โ˜‘๏ธ](../../roles/web-app-fusiondirectory/meta/services.yml) | โŒ | โŒ | โŒ | +| **gitea** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitea/meta/services.yml) | โŒ | **gitea** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | **gitea** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitea/meta/services.yml) | โŒ | โŒ | โŒ | **gitea** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitea/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitea/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **gitea** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **gitea** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitea/meta/services.yml) | **gitea** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **gitea** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitea/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **gitea** | [โ˜‘๏ธ](../../roles/web-app-gitea/meta/services.yml) | โŒ | โŒ | โŒ | +| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | litellm | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | โ†“ row wires โ†’ col | minio | mini-qr | mobilizon | moodle | n8n | navigator | nextcloud | odoo | opencloud | openproject | โ†“ row wires โ†’ col | opentalk | openwebui | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | โ†“ row wires โ†’ col | roulette-wheel | shopware | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | โ†“ row wires โ†’ col | zammad | asset | cdn | collabora | coturn | css | file | html | legal | libretranslate | โ†“ row wires โ†’ col | logout | onlyoffice | simpleicons | xmpp | +| **gitlab** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://docs.gitlab.com/user/project/integrations/confluence/) | [โ˜‘๏ธ](../../roles/web-app-gitlab/meta/services.yml) | โŒ | **gitlab** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **gitlab** | โ€” | โŒ | [โœ…](https://docs.gitlab.com/integration/jenkins/) | [โœ…](https://docs.gitlab.com/integration/jira/) | โŒ | โŒ | [โœ…](https://docs.gitlab.com/integration/saml/) | โŒ | โŒ | โŒ | **gitlab** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitlab/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitlab/meta/services.yml) | [โœ…](https://docs.gitlab.com/user/project/integrations/matrix/) | [โœ…](https://docs.gitlab.com/user/project/integrations/mattermost_notifications/) | โŒ | โŒ | **gitlab** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **gitlab** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitlab/meta/services.yml) | **gitlab** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **gitlab** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-gitlab/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **gitlab** | [โ˜‘๏ธ](../../roles/web-app-gitlab/meta/services.yml) | โŒ | โŒ | โŒ | +| **hugo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-hugo/meta/services.yml) | โŒ | **hugo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **hugo** | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-hugo/meta/services.yml) | โŒ | โŒ | โŒ | **hugo** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-hugo/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-hugo/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **hugo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **hugo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-hugo/meta/services.yml) | **hugo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **hugo** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-hugo/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **hugo** | [โ˜‘๏ธ](../../roles/web-app-hugo/meta/services.yml) | โŒ | โŒ | โŒ | +| **jenkins** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jenkins/meta/services.yml) | โŒ | **jenkins** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://plugins.jenkins.io/gitea/) | **jenkins** | [โœ…](https://plugins.jenkins.io/gitlab-plugin) | โŒ | โ€” | โŒ | โŒ | โŒ | [โœ…](https://plugins.jenkins.io/oic-auth/) | โŒ | โŒ | โŒ | **jenkins** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jenkins/meta/services.yml) | โŒ | [โœ…](https://plugins.jenkins.io/mattermost/) | โŒ | โŒ | **jenkins** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jenkins** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://plugins.jenkins.io/prometheus) | **jenkins** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jenkins** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jenkins/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **jenkins** | [โ˜‘๏ธ](../../roles/web-app-jenkins/meta/services.yml) | โŒ | โŒ | โŒ | +| **jira** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jira/meta/services.yml) | โŒ | **jira** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jira** | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jira/meta/services.yml) | โŒ | โŒ | โŒ | **jira** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jira/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-jira/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **jira** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jira** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jira/meta/services.yml) | **jira** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jira** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jira/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **jira** | [โ˜‘๏ธ](../../roles/web-app-jira/meta/services.yml) | โŒ | โŒ | โŒ | +| **jitsi** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jitsi/meta/services.yml) | โŒ | **jitsi** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jitsi** | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | [โ˜‘๏ธ](../../roles/web-app-jitsi/meta/services.yml) | โŒ | โŒ | โŒ | **jitsi** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jitsi/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-jitsi/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **jitsi** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jitsi** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jitsi/meta/services.yml) | **jitsi** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **jitsi** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-jitsi/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **jitsi** | [โ˜‘๏ธ](../../roles/web-app-jitsi/meta/services.yml) | โŒ | โŒ | โŒ | +| **joomla** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-joomla/meta/services.yml) | โŒ | **joomla** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **joomla** | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | [โœ…](../../roles/web-app-joomla/files/joomla-oidc-plugin/) | โŒ | โŒ | โŒ | **joomla** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-joomla/meta/services.yml) | โŒ | [โœ…](https://extensions.joomla.org/extension/itcs-matomo/) | โŒ | โŒ | โŒ | โŒ | **joomla** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **joomla** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-joomla/meta/services.yml) | **joomla** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **joomla** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-joomla/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **joomla** | [โ˜‘๏ธ](../../roles/web-app-joomla/meta/services.yml) | โŒ | โŒ | โŒ | +| **keycloak** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-keycloak/meta/services.yml) | โŒ | **keycloak** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **keycloak** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | **keycloak** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-keycloak/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-keycloak/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **keycloak** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **keycloak** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-keycloak/meta/services.yml) | **keycloak** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **keycloak** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-keycloak/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **keycloak** | [โ˜‘๏ธ](../../roles/web-app-keycloak/meta/services.yml) | โŒ | โŒ | โŒ | +| **kix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-kix/meta/services.yml) | โŒ | **kix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **kix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-kix/meta/services.yml) | โ€” | โŒ | โŒ | **kix** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-kix/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-kix/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **kix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **kix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-kix/meta/services.yml) | **kix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **kix** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-kix/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **kix** | [โ˜‘๏ธ](../../roles/web-app-kix/meta/services.yml) | โŒ | โŒ | โŒ | +| **lam** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-lam/meta/services.yml) | โŒ | **lam** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **lam** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-lam/meta/services.yml) | โŒ | โ€” | โŒ | **lam** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-lam/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **lam** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **lam** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-lam/meta/services.yml) | **lam** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **lam** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-lam/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **lam** | [โ˜‘๏ธ](../../roles/web-app-lam/meta/services.yml) | โŒ | โŒ | โŒ | +| **listmonk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-listmonk/meta/services.yml) | โŒ | **listmonk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **listmonk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-listmonk/meta/services.yml) | โŒ | โŒ | โ€” | **listmonk** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-listmonk/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-listmonk/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **listmonk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **listmonk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-listmonk/meta/services.yml) | **listmonk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **listmonk** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-listmonk/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **listmonk** | [โ˜‘๏ธ](../../roles/web-app-listmonk/meta/services.yml) | โŒ | โŒ | โŒ | +| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | litellm | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | โ†“ row wires โ†’ col | minio | mini-qr | mobilizon | moodle | n8n | navigator | nextcloud | odoo | opencloud | openproject | โ†“ row wires โ†’ col | opentalk | openwebui | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | โ†“ row wires โ†’ col | roulette-wheel | shopware | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | โ†“ row wires โ†’ col | zammad | asset | cdn | collabora | coturn | css | file | html | legal | libretranslate | โ†“ row wires โ†’ col | logout | onlyoffice | simpleicons | xmpp | +| **litellm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-litellm/meta/services.yml) | โŒ | **litellm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **litellm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-litellm/meta/services.yml) | โŒ | โŒ | โŒ | **litellm** | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **litellm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **litellm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-litellm/meta/services.yml) | **litellm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **litellm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **litellm** | [โ˜‘๏ธ](../../roles/web-app-litellm/meta/services.yml) | โŒ | โŒ | โŒ | +| **littlejs** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-littlejs/meta/services.yml) | โŒ | **littlejs** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **littlejs** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-littlejs/meta/services.yml) | โŒ | โŒ | โŒ | **littlejs** | โŒ | โ€” | โŒ | [โ˜‘๏ธ](../../roles/web-app-littlejs/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-littlejs/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **littlejs** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **littlejs** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-littlejs/meta/services.yml) | **littlejs** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **littlejs** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-littlejs/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **littlejs** | [โ˜‘๏ธ](../../roles/web-app-littlejs/meta/services.yml) | โŒ | โŒ | โŒ | +| **magento** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-magento/meta/services.yml) | โŒ | **magento** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **magento** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-magento/meta/services.yml) | โŒ | โŒ | โŒ | **magento** | โŒ | โŒ | โ€” | [โ˜‘๏ธ](../../roles/web-app-magento/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-magento/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **magento** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **magento** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-magento/meta/services.yml) | **magento** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **magento** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-magento/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **magento** | [โ˜‘๏ธ](../../roles/web-app-magento/meta/services.yml) | โŒ | โŒ | โŒ | +| **mailu** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mailu/meta/services.yml) | โŒ | **mailu** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mailu** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mailu/meta/services.yml) | โŒ | โŒ | โŒ | **mailu** | โŒ | โŒ | โŒ | โ€” | โŒ | [โ˜‘๏ธ](../../roles/web-app-mailu/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **mailu** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mailu** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mailu/meta/services.yml) | **mailu** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mailu** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mailu/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **mailu** | [โ˜‘๏ธ](../../roles/web-app-mailu/meta/services.yml) | โŒ | โŒ | โŒ | +| **mastodon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mastodon/meta/services.yml) | โŒ | **mastodon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mastodon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mastodon/meta/services.yml) | โŒ | โŒ | โŒ | **mastodon** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mastodon/meta/services.yml) | โ€” | [โ˜‘๏ธ](../../roles/web-app-mastodon/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **mastodon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mastodon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mastodon/meta/services.yml) | **mastodon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mastodon** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mastodon/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **mastodon** | [โ˜‘๏ธ](../../roles/web-app-mastodon/meta/services.yml) | โŒ | โŒ | โŒ | +| **matomo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matomo/meta/services.yml) | โŒ | **matomo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **matomo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matomo/meta/services.yml) | โŒ | โŒ | โŒ | **matomo** | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | **matomo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **matomo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matomo/meta/services.yml) | **matomo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **matomo** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matomo/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **matomo** | [โ˜‘๏ธ](../../roles/web-app-matomo/meta/services.yml) | โŒ | โŒ | โŒ | +| **matrix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matrix/meta/services.yml) | โŒ | **matrix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **matrix** | [โœ…](https://github.com/matrix-org/matrix-hookshot) | โŒ | โŒ | [โœ…](https://github.com/matrix-org/matrix-hookshot) | [โœ…](https://github.com/element-hq/element-web/blob/develop/docs/jitsi.md) | โŒ | [โœ…](https://matrix-org.github.io/synapse/latest/openid.html) | โŒ | โŒ | โŒ | **matrix** | [โ˜‘๏ธ](../../roles/web-app-matrix/meta/services.yml) | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matrix/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-matrix/meta/services.yml) | โ€” | โŒ | โŒ | โŒ | **matrix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **matrix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://matrix-org.github.io/synapse/latest/metrics-howto.html) | **matrix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **matrix** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-matrix/meta/services.yml) | [โ˜‘๏ธ](../../roles/web-app-matrix/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **matrix** | [โ˜‘๏ธ](../../roles/web-app-matrix/meta/services.yml) | โŒ | โŒ | โŒ | +| **mattermost** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mattermost/meta/services.yml) | โŒ | **mattermost** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mattermost** | [โœ…](https://github.com/mattermost/mattermost-plugin-gitlab) | โŒ | [โœ…](https://github.com/mattermost/mattermost-plugin-jenkins) | [โœ…](https://github.com/mattermost/mattermost-plugin-jira) | [โœ…](https://github.com/mattermost-community/mattermost-plugin-jitsi) | โŒ | [๐Ÿช™](https://docs.mattermost.com/administration-guide/onboard/sso-saml.html) | โŒ | โŒ | โŒ | **mattermost** | [โ˜‘๏ธ](../../roles/web-app-mattermost/meta/services.yml) | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mattermost/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-mattermost/meta/services.yml) | โŒ | โ€” | โŒ | โŒ | **mattermost** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mattermost** | โŒ | [โœ…](https://github.com/mattermost/mattermost-plugin-agents) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/cpanato/mattermost-plugin-alertmanager) | **mattermost** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mattermost** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mattermost/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **mattermost** | [โ˜‘๏ธ](../../roles/web-app-mattermost/meta/services.yml) | โŒ | โŒ | โŒ | +| **mediawiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mediawiki/meta/services.yml) | โŒ | **mediawiki** | [โœ…](https://www.mediawiki.org/wiki/Extension:DiscourseSsoConsumer) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mediawiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://www.mediawiki.org/wiki/Extension:OpenID_Connect) | โŒ | โŒ | โŒ | **mediawiki** | [โ˜‘๏ธ](../../roles/web-app-mediawiki/meta/services.yml) | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mediawiki/meta/services.yml) | โŒ | [โœ…](https://www.mediawiki.org/wiki/Extension:Matomo) | โŒ | โŒ | โ€” | โŒ | **mediawiki** | [โœ…](https://www.mediawiki.org/wiki/Extension:AWS) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mediawiki** | โŒ | [โœ…](https://www.mediawiki.org/wiki/Extension:AIEditingAssistant) | [โœ…](https://www.mediawiki.org/wiki/Extension:PeerTubeEmbed) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mediawiki/meta/services.yml) | **mediawiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mediawiki** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mediawiki/meta/services.yml) | โŒ | โŒ | โŒ | [โœ…](https://www.mediawiki.org/wiki/Extension:MachineTranslation) | **mediawiki** | [โ˜‘๏ธ](../../roles/web-app-mediawiki/meta/services.yml) | โŒ | โŒ | โŒ | +| **mig** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mig/meta/services.yml) | โŒ | **mig** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mig** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mig/meta/services.yml) | โŒ | โŒ | โŒ | **mig** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mig/meta/services.yml) | โŒ | โŒ | โŒ | โ€” | **mig** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mig** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mig/meta/services.yml) | **mig** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mig** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mig/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **mig** | [โ˜‘๏ธ](../../roles/web-app-mig/meta/services.yml) | โŒ | โŒ | โŒ | +| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | litellm | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | โ†“ row wires โ†’ col | minio | mini-qr | mobilizon | moodle | n8n | navigator | nextcloud | odoo | opencloud | openproject | โ†“ row wires โ†’ col | opentalk | openwebui | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | โ†“ row wires โ†’ col | roulette-wheel | shopware | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | โ†“ row wires โ†’ col | zammad | asset | cdn | collabora | coturn | css | file | html | legal | libretranslate | โ†“ row wires โ†’ col | logout | onlyoffice | simpleicons | xmpp | +| **minio** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-minio/meta/services.yml) | โŒ | **minio** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **minio** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-minio/meta/services.yml) | โŒ | โŒ | โŒ | **minio** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-minio/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **minio** | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **minio** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-minio/meta/services.yml) | **minio** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **minio** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-minio/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **minio** | [โ˜‘๏ธ](../../roles/web-app-minio/meta/services.yml) | โŒ | โŒ | โŒ | +| **mini-qr** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mini-qr/meta/services.yml) | โŒ | **mini-qr** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mini-qr** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mini-qr/meta/services.yml) | โŒ | โŒ | โŒ | **mini-qr** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mini-qr/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **mini-qr** | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mini-qr** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mini-qr/meta/services.yml) | **mini-qr** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mini-qr** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mini-qr/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **mini-qr** | [โ˜‘๏ธ](../../roles/web-app-mini-qr/meta/services.yml) | โŒ | โŒ | โŒ | +| **mobilizon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mobilizon/meta/services.yml) | โŒ | **mobilizon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mobilizon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mobilizon/meta/services.yml) | โŒ | โŒ | โŒ | **mobilizon** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mobilizon/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-mobilizon/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **mobilizon** | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mobilizon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mobilizon/meta/services.yml) | **mobilizon** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **mobilizon** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-mobilizon/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **mobilizon** | [โ˜‘๏ธ](../../roles/web-app-mobilizon/meta/services.yml) | โŒ | โŒ | โŒ | +| **moodle** | โŒ | โŒ | [โœ…](https://moodle.org/plugins/mod_bigbluebuttonbn) | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-moodle/meta/services.yml) | โŒ | **moodle** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **moodle** | โŒ | โŒ | โŒ | โŒ | [โœ…](https://moodle.org/plugins/mod_jitsi) | โŒ | [โœ…](https://moodle.org/plugins/auth_oidc) | โŒ | โŒ | โŒ | **moodle** | [โ˜‘๏ธ](../../roles/web-app-moodle/meta/services.yml) | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-moodle/meta/services.yml) | โŒ | [โœ…](https://moodle.org/plugins/tool_webanalytics) | [โœ…](https://docs.moodle.org/en/Matrix) | โŒ | โŒ | โŒ | **moodle** | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | [โœ…](https://moodle.org/plugins/repository_owncloud) | โŒ | โŒ | โŒ | **moodle** | โŒ | [โœ…](https://moodle.org/plugins/aiprovider_openwebui) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-moodle/meta/services.yml) | **moodle** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **moodle** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-moodle/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **moodle** | [โ˜‘๏ธ](../../roles/web-app-moodle/meta/services.yml) | โŒ | โŒ | โŒ | +| **n8n** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-n8n/meta/services.yml) | โŒ | **n8n** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **n8n** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-n8n/meta/services.yml) | โŒ | โŒ | โŒ | **n8n** | [โ˜‘๏ธ](../../roles/web-app-n8n/meta/services.yml) | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-n8n/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-n8n/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **n8n** | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | **n8n** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-n8n/meta/services.yml) | **n8n** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **n8n** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-n8n/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **n8n** | [โ˜‘๏ธ](../../roles/web-app-n8n/meta/services.yml) | โŒ | โŒ | โŒ | +| **navigator** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-navigator/meta/services.yml) | โŒ | **navigator** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **navigator** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-navigator/meta/services.yml) | โŒ | โŒ | โŒ | **navigator** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-navigator/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **navigator** | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | **navigator** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-navigator/meta/services.yml) | **navigator** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **navigator** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-navigator/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **navigator** | [โ˜‘๏ธ](../../roles/web-app-navigator/meta/services.yml) | โŒ | โŒ | โŒ | +| **nextcloud** | โŒ | โŒ | [โœ…](https://apps.nextcloud.com/apps/bbb) | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-nextcloud/meta/services.yml) | โŒ | **nextcloud** | [โœ…](https://github.com/nextcloud/integration_discourse) | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/nextcloud/integration_openai) | โŒ | โŒ | โŒ | โŒ | **nextcloud** | [โœ…](https://github.com/nextcloud/integration_gitlab) | โŒ | โŒ | [โœ…](https://github.com/nextcloud/integration_jira) | โŒ | โŒ | [โœ…](https://github.com/nextcloud/user_oidc) | โŒ | โŒ | โŒ | **nextcloud** | [โ˜‘๏ธ](../../roles/web-app-nextcloud/meta/services.yml) | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-nextcloud/meta/services.yml) | [โœ…](https://github.com/nextcloud/integration_mastodon) | [โœ…](https://apps.nextcloud.com/apps/matomo) | [โœ…](https://github.com/nextcloud/integration_matrix) | [โœ…](https://github.com/nextcloud/integration_mattermost) | โŒ | โŒ | **nextcloud** | โŒ | โŒ | โŒ | [โœ…](https://github.com/nextcloud/integration_moodle) | โŒ | โŒ | โ€” | โŒ | โŒ | [โœ…](https://github.com/nextcloud/integration_openproject) | **nextcloud** | โŒ | [โœ…](https://github.com/nextcloud/integration_openai) | [โœ…](https://github.com/nextcloud/integration_peertube) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-nextcloud/meta/services.yml) | **nextcloud** | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/eneiluj/integration_suitecrm) | โŒ | โŒ | [โœ…](https://apps.nextcloud.com/apps/xwiki) | โŒ | **nextcloud** | [โœ…](https://github.com/nextcloud/integration_zammad) | โŒ | โŒ | [โœ…](https://github.com/nextcloud/richdocuments) | [โ˜‘๏ธ](../../roles/web-app-nextcloud/meta/services.yml) | [โ˜‘๏ธ](../../roles/web-app-nextcloud/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **nextcloud** | [โ˜‘๏ธ](../../roles/web-app-nextcloud/meta/services.yml) | [โœ…](https://github.com/ONLYOFFICE/onlyoffice-nextcloud) | โŒ | โŒ | +| **odoo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-odoo/meta/services.yml) | โŒ | **odoo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **odoo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/OCA/server-auth/tree/16.0/auth_oidc) | โŒ | โŒ | โŒ | **odoo** | โŒ | โŒ | โŒ | [โœ…](https://www.odoo.com/documentation/latest/applications/general/email_communication.html) | โŒ | [โ˜‘๏ธ](../../roles/web-app-odoo/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **odoo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [๐Ÿช™](https://apps.odoo.com/apps/modules/19.0/nextcloud_odoo_integration) | โ€” | โŒ | โŒ | **odoo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-odoo/meta/services.yml) | **odoo** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **odoo** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-odoo/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **odoo** | [โ˜‘๏ธ](../../roles/web-app-odoo/meta/services.yml) | โŒ | โŒ | โŒ | +| **opencloud** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opencloud/meta/services.yml) | โŒ | **opencloud** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **opencloud** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opencloud/meta/services.yml) | โŒ | โŒ | โŒ | **opencloud** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opencloud/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-opencloud/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **opencloud** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | **opencloud** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opencloud/meta/services.yml) | **opencloud** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **opencloud** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opencloud/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **opencloud** | [โ˜‘๏ธ](../../roles/web-app-opencloud/meta/services.yml) | โŒ | โŒ | โŒ | +| **openproject** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openproject/meta/services.yml) | โŒ | **openproject** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **openproject** | [โœ…](https://www.openproject.org/docs/system-admin-guide/integrations/gitlab-integration/) | โŒ | โŒ | โŒ | โŒ | โŒ | [๐Ÿช™](https://www.openproject.org/docs/system-admin-guide/authentication/openid-providers/) | โŒ | โŒ | โŒ | **openproject** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openproject/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-openproject/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **openproject** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://www.openproject.org/docs/system-admin-guide/integrations/nextcloud/) | โŒ | โŒ | โ€” | **openproject** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openproject/meta/services.yml) | **openproject** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **openproject** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openproject/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **openproject** | [โ˜‘๏ธ](../../roles/web-app-openproject/meta/services.yml) | โŒ | โŒ | โŒ | +| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | litellm | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | โ†“ row wires โ†’ col | minio | mini-qr | mobilizon | moodle | n8n | navigator | nextcloud | odoo | opencloud | openproject | โ†“ row wires โ†’ col | opentalk | openwebui | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | โ†“ row wires โ†’ col | roulette-wheel | shopware | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | โ†“ row wires โ†’ col | zammad | asset | cdn | collabora | coturn | css | file | html | legal | libretranslate | โ†“ row wires โ†’ col | logout | onlyoffice | simpleicons | xmpp | +| **opentalk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | โŒ | **opentalk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **opentalk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | โŒ | โŒ | โŒ | **opentalk** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **opentalk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **opentalk** | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | **opentalk** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **opentalk** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **opentalk** | [โ˜‘๏ธ](../../roles/web-app-opentalk/meta/services.yml) | โŒ | โŒ | โŒ | +| **openwebui** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | โŒ | **openwebui** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **openwebui** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | โŒ | โŒ | โŒ | **openwebui** | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **openwebui** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **openwebui** | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | **openwebui** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **openwebui** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **openwebui** | [โ˜‘๏ธ](../../roles/web-app-openwebui/meta/services.yml) | โŒ | โŒ | โŒ | +| **peertube** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-peertube/meta/services.yml) | โŒ | **peertube** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **peertube** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://www.npmjs.com/package/peertube-plugin-auth-openid-connect) | โŒ | โŒ | โŒ | **peertube** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-peertube/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-peertube/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **peertube** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **peertube** | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-peertube/meta/services.yml) | **peertube** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **peertube** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-peertube/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **peertube** | [โ˜‘๏ธ](../../roles/web-app-peertube/meta/services.yml) | โŒ | โŒ | โŒ | +| **pgadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pgadmin/meta/services.yml) | โŒ | **pgadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pgadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pgadmin/meta/services.yml) | โŒ | โŒ | โŒ | **pgadmin** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pgadmin/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-pgadmin/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **pgadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pgadmin** | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pgadmin/meta/services.yml) | **pgadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pgadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pgadmin/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **pgadmin** | [โ˜‘๏ธ](../../roles/web-app-pgadmin/meta/services.yml) | โŒ | โŒ | โŒ | +| **phpldapadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpldapadmin/meta/services.yml) | โŒ | **phpldapadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **phpldapadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpldapadmin/meta/services.yml) | โŒ | โŒ | โŒ | **phpldapadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpldapadmin/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **phpldapadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **phpldapadmin** | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpldapadmin/meta/services.yml) | **phpldapadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **phpldapadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpldapadmin/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **phpldapadmin** | [โ˜‘๏ธ](../../roles/web-app-phpldapadmin/meta/services.yml) | โŒ | โŒ | โŒ | +| **phpmyadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpmyadmin/meta/services.yml) | โŒ | **phpmyadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **phpmyadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpmyadmin/meta/services.yml) | โŒ | โŒ | โŒ | **phpmyadmin** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpmyadmin/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpmyadmin/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **phpmyadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **phpmyadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpmyadmin/meta/services.yml) | **phpmyadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **phpmyadmin** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-phpmyadmin/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **phpmyadmin** | [โ˜‘๏ธ](../../roles/web-app-phpmyadmin/meta/services.yml) | โŒ | โŒ | โŒ | +| **pixelfed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pixelfed/meta/services.yml) | โŒ | **pixelfed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pixelfed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pixelfed/meta/services.yml) | โŒ | โŒ | โŒ | **pixelfed** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pixelfed/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-pixelfed/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **pixelfed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pixelfed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pixelfed/meta/services.yml) | **pixelfed** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pixelfed** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pixelfed/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **pixelfed** | [โ˜‘๏ธ](../../roles/web-app-pixelfed/meta/services.yml) | โŒ | โŒ | โŒ | +| **postmarks** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-postmarks/meta/services.yml) | โŒ | **postmarks** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **postmarks** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-postmarks/meta/services.yml) | โŒ | โŒ | โŒ | **postmarks** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-postmarks/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-postmarks/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **postmarks** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **postmarks** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | [โ˜‘๏ธ](../../roles/web-app-postmarks/meta/services.yml) | **postmarks** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **postmarks** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-postmarks/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **postmarks** | [โ˜‘๏ธ](../../roles/web-app-postmarks/meta/services.yml) | โŒ | โŒ | โŒ | +| **pretix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pretix/meta/services.yml) | โŒ | **pretix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pretix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://docs.pretix.eu/en/latest/admin/installation/index.html) | โŒ | โŒ | โŒ | **pretix** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pretix/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-pretix/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **pretix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pretix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | [โ˜‘๏ธ](../../roles/web-app-pretix/meta/services.yml) | **pretix** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **pretix** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-pretix/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **pretix** | [โ˜‘๏ธ](../../roles/web-app-pretix/meta/services.yml) | โŒ | โŒ | โŒ | +| **prometheus** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-prometheus/meta/services.yml) | โŒ | **prometheus** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **prometheus** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-prometheus/meta/services.yml) | โŒ | โŒ | โŒ | **prometheus** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-prometheus/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-prometheus/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **prometheus** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **prometheus** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | **prometheus** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **prometheus** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-prometheus/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **prometheus** | [โ˜‘๏ธ](../../roles/web-app-prometheus/meta/services.yml) | โŒ | โŒ | โŒ | +| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | litellm | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | โ†“ row wires โ†’ col | minio | mini-qr | mobilizon | moodle | n8n | navigator | nextcloud | odoo | opencloud | openproject | โ†“ row wires โ†’ col | opentalk | openwebui | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | โ†“ row wires โ†’ col | roulette-wheel | shopware | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | โ†“ row wires โ†’ col | zammad | asset | cdn | collabora | coturn | css | file | html | legal | libretranslate | โ†“ row wires โ†’ col | logout | onlyoffice | simpleicons | xmpp | +| **roulette-wheel** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-roulette-wheel/meta/services.yml) | โŒ | **roulette-wheel** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **roulette-wheel** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-roulette-wheel/meta/services.yml) | โŒ | โŒ | โŒ | **roulette-wheel** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-roulette-wheel/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-roulette-wheel/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **roulette-wheel** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **roulette-wheel** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-roulette-wheel/meta/services.yml) | **roulette-wheel** | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **roulette-wheel** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-roulette-wheel/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **roulette-wheel** | [โ˜‘๏ธ](../../roles/web-app-roulette-wheel/meta/services.yml) | โŒ | โŒ | โŒ | +| **shopware** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-shopware/meta/services.yml) | โŒ | **shopware** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **shopware** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-shopware/meta/services.yml) | โŒ | โŒ | โŒ | **shopware** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-shopware/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-shopware/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **shopware** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **shopware** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-shopware/meta/services.yml) | **shopware** | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **shopware** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-shopware/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **shopware** | [โ˜‘๏ธ](../../roles/web-app-shopware/meta/services.yml) | โŒ | โŒ | โŒ | +| **snipe-it** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-snipe-it/meta/services.yml) | โŒ | **snipe-it** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **snipe-it** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-snipe-it/meta/services.yml) | โŒ | โŒ | โŒ | **snipe-it** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-snipe-it/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-snipe-it/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **snipe-it** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **snipe-it** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-snipe-it/meta/services.yml) | **snipe-it** | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **snipe-it** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-snipe-it/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **snipe-it** | [โ˜‘๏ธ](../../roles/web-app-snipe-it/meta/services.yml) | โŒ | โŒ | โŒ | +| **socialhome** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-socialhome/meta/services.yml) | โŒ | **socialhome** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **socialhome** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-socialhome/meta/services.yml) | โŒ | โŒ | โŒ | **socialhome** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **socialhome** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **socialhome** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-socialhome/meta/services.yml) | **socialhome** | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **socialhome** | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-socialhome/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | โŒ | **socialhome** | [โ˜‘๏ธ](../../roles/web-app-socialhome/meta/services.yml) | โŒ | โŒ | โŒ | +| **sphinx** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-sphinx/meta/services.yml) | โŒ | **sphinx** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **sphinx** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-sphinx/meta/services.yml) | โŒ | โŒ | โŒ | **sphinx** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-sphinx/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-sphinx/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **sphinx** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **sphinx** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-sphinx/meta/services.yml) | **sphinx** | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | **sphinx** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-sphinx/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **sphinx** | [โ˜‘๏ธ](../../roles/web-app-sphinx/meta/services.yml) | โŒ | โŒ | โŒ | +| **suitecrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-suitecrm/meta/services.yml) | โŒ | **suitecrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **suitecrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://docs.suitecrm.com/8.x/admin/configuration/saml/8.7.0-saml-configuration/) | โŒ | โŒ | โŒ | **suitecrm** | โŒ | โŒ | โŒ | [โœ…](https://github.com/SuiteCRM/SuiteCRM) | โŒ | [โ˜‘๏ธ](../../roles/web-app-suitecrm/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **suitecrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **suitecrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-suitecrm/meta/services.yml) | **suitecrm** | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | **suitecrm** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-suitecrm/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **suitecrm** | [โ˜‘๏ธ](../../roles/web-app-suitecrm/meta/services.yml) | โŒ | โŒ | โŒ | +| **taiga** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-taiga/meta/services.yml) | โŒ | **taiga** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **taiga** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://github.com/taigaio/taiga-contrib-oidc-auth) | โŒ | โŒ | โŒ | **taiga** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-taiga/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-taiga/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **taiga** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **taiga** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-taiga/meta/services.yml) | **taiga** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | **taiga** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-taiga/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **taiga** | [โ˜‘๏ธ](../../roles/web-app-taiga/meta/services.yml) | โŒ | โŒ | โŒ | +| **wordpress** | โŒ | โŒ | [โœ…](https://wordpress.org/plugins/video-conferencing-with-bbb/) | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-wordpress/meta/services.yml) | โŒ | **wordpress** | [โœ…](https://wordpress.org/plugins/wp-discourse/) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **wordpress** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://wordpress.org/plugins/daggerhart-openid-connect-generic/) | โŒ | โŒ | [โœ…](https://wordpress.org/plugins/integration-for-listmonk-mailing-list-and-newsletter-manager/) | **wordpress** | [โ˜‘๏ธ](../../roles/web-app-wordpress/meta/services.yml) | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-wordpress/meta/services.yml) | [โœ…](https://wordpress.org/plugins/activitypub/) | [โœ…](https://wordpress.org/plugins/matomo/) | โŒ | โŒ | โŒ | โŒ | **wordpress** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **wordpress** | โŒ | โŒ | [โœ…](https://wordpress.org/plugins/video-manager-for-peertube/) | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-wordpress/meta/services.yml) | **wordpress** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | **wordpress** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-wordpress/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **wordpress** | [โ˜‘๏ธ](../../roles/web-app-wordpress/meta/services.yml) | โŒ | โŒ | โŒ | +| **xwiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-xwiki/meta/services.yml) | โŒ | **xwiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xwiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://extensions.xwiki.org/xwiki/bin/view/Extension/OpenID%20Connect/) | โŒ | โŒ | โŒ | **xwiki** | [โ˜‘๏ธ](../../roles/web-app-xwiki/meta/services.yml) | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-xwiki/meta/services.yml) | โŒ | [โœ…](https://extensions.xwiki.org/xwiki/bin/view/Extension/Piwiki%20Integration) | โŒ | โŒ | โŒ | โŒ | **xwiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xwiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-xwiki/meta/services.yml) | **xwiki** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | **xwiki** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-xwiki/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **xwiki** | [โ˜‘๏ธ](../../roles/web-app-xwiki/meta/services.yml) | โŒ | โŒ | โŒ | +| **yourls** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-yourls/meta/services.yml) | โŒ | **yourls** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **yourls** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-yourls/meta/services.yml) | โŒ | โŒ | โŒ | **yourls** | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-yourls/meta/services.yml) | โŒ | [โ˜‘๏ธ](../../roles/web-app-yourls/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **yourls** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **yourls** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-yourls/meta/services.yml) | **yourls** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | **yourls** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-yourls/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **yourls** | [โ˜‘๏ธ](../../roles/web-app-yourls/meta/services.yml) | โŒ | โŒ | โŒ | +| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | litellm | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | โ†“ row wires โ†’ col | minio | mini-qr | mobilizon | moodle | n8n | navigator | nextcloud | odoo | opencloud | openproject | โ†“ row wires โ†’ col | opentalk | openwebui | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | โ†“ row wires โ†’ col | roulette-wheel | shopware | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | โ†“ row wires โ†’ col | zammad | asset | cdn | collabora | coturn | css | file | html | legal | libretranslate | โ†“ row wires โ†’ col | logout | onlyoffice | simpleicons | xmpp | +| **zammad** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-zammad/meta/services.yml) | โŒ | **zammad** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **zammad** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โœ…](https://admin-docs.zammad.org/en/latest/settings/security/third-party/saml.html) | โŒ | โŒ | โŒ | **zammad** | [โ˜‘๏ธ](../../roles/web-app-zammad/meta/services.yml) | โŒ | โŒ | [โœ…](https://admin-docs.zammad.org/en/latest/channels/email/index.html) | โŒ | [โ˜‘๏ธ](../../roles/web-app-zammad/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **zammad** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **zammad** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-zammad/meta/services.yml) | **zammad** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **zammad** | โ€” | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-app-zammad/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **zammad** | [โ˜‘๏ธ](../../roles/web-app-zammad/meta/services.yml) | โŒ | โŒ | โŒ | +| **asset** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **asset** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **asset** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **asset** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-asset/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **asset** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **asset** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-asset/meta/services.yml) | **asset** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **asset** | โŒ | โ€” | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-asset/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **asset** | โŒ | โŒ | โŒ | โŒ | +| **cdn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-cdn/meta/services.yml) | โŒ | **cdn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **cdn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **cdn** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-cdn/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **cdn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **cdn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-cdn/meta/services.yml) | **cdn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **cdn** | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **cdn** | โŒ | โŒ | โŒ | โŒ | +| **collabora** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **collabora** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **collabora** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **collabora** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-collabora/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **collabora** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **collabora** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-collabora/meta/services.yml) | **collabora** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **collabora** | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **collabora** | โŒ | โŒ | โŒ | โŒ | +| **coturn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **coturn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **coturn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **coturn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **coturn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **coturn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-coturn/meta/services.yml) | **coturn** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **coturn** | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | โŒ | **coturn** | โŒ | โŒ | โŒ | โŒ | +| **css** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **css** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **css** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **css** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-css/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **css** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **css** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-css/meta/services.yml) | **css** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **css** | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-css/meta/services.yml) | โŒ | โŒ | โ€” | โŒ | โŒ | โŒ | โŒ | **css** | โŒ | โŒ | โŒ | โŒ | +| **file** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **file** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **file** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **file** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-file/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **file** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **file** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-file/meta/services.yml) | **file** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **file** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-file/meta/services.yml) | โ€” | โŒ | โŒ | โŒ | **file** | โŒ | โŒ | โŒ | โŒ | +| **html** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **html** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **html** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **html** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-html/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **html** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **html** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-html/meta/services.yml) | **html** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **html** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-html/meta/services.yml) | โŒ | โ€” | โŒ | โŒ | **html** | โŒ | โŒ | โŒ | โŒ | +| **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-legal/meta/services.yml) | **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **legal** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โ€” | โŒ | **legal** | โŒ | โŒ | โŒ | โŒ | +| **libretranslate** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **libretranslate** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **libretranslate** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-libretranslate/meta/services.yml) | โŒ | โŒ | โŒ | **libretranslate** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-libretranslate/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **libretranslate** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **libretranslate** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-libretranslate/meta/services.yml) | **libretranslate** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **libretranslate** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-libretranslate/meta/services.yml) | โŒ | โŒ | โŒ | โ€” | **libretranslate** | [โ˜‘๏ธ](../../roles/web-svc-libretranslate/meta/services.yml) | โŒ | โŒ | โŒ | +| โ†“ row wires โ†’ col | akaunting | baserow | bigbluebutton | bluesky | bookwyrm | bridgy-fed | chess | confluence | dashboard | decidim | โ†“ row wires โ†’ col | discourse | erpnext | espocrm | fediwall | fider | flowise | friendica | funkwhale | fusiondirectory | gitea | โ†“ row wires โ†’ col | gitlab | hugo | jenkins | jira | jitsi | joomla | keycloak | kix | lam | listmonk | โ†“ row wires โ†’ col | litellm | littlejs | magento | mailu | mastodon | matomo | matrix | mattermost | mediawiki | mig | โ†“ row wires โ†’ col | minio | mini-qr | mobilizon | moodle | n8n | navigator | nextcloud | odoo | opencloud | openproject | โ†“ row wires โ†’ col | opentalk | openwebui | peertube | pgadmin | phpldapadmin | phpmyadmin | pixelfed | postmarks | pretix | prometheus | โ†“ row wires โ†’ col | roulette-wheel | shopware | snipe-it | socialhome | sphinx | suitecrm | taiga | wordpress | xwiki | yourls | โ†“ row wires โ†’ col | zammad | asset | cdn | collabora | coturn | css | file | html | legal | libretranslate | โ†“ row wires โ†’ col | logout | onlyoffice | simpleicons | xmpp | +| **logout** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **logout** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **logout** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **logout** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-logout/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **logout** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **logout** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-logout/meta/services.yml) | **logout** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **logout** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-logout/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **logout** | โ€” | โŒ | โŒ | โŒ | +| **onlyoffice** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **onlyoffice** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **onlyoffice** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **onlyoffice** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-onlyoffice/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **onlyoffice** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **onlyoffice** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-onlyoffice/meta/services.yml) | **onlyoffice** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **onlyoffice** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-onlyoffice/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **onlyoffice** | โŒ | โ€” | โŒ | โŒ | +| **simpleicons** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-simpleicons/meta/services.yml) | โŒ | **simpleicons** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **simpleicons** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-simpleicons/meta/services.yml) | โŒ | โŒ | โŒ | **simpleicons** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-simpleicons/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **simpleicons** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **simpleicons** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-simpleicons/meta/services.yml) | **simpleicons** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **simpleicons** | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-simpleicons/meta/services.yml) | โŒ | โŒ | โŒ | โŒ | **simpleicons** | โŒ | โŒ | โ€” | โŒ | +| **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-xmpp/meta/services.yml) | โŒ | โŒ | โŒ | **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | [โ˜‘๏ธ](../../roles/web-svc-xmpp/meta/services.yml) | **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xmpp** | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | โŒ | **xmpp** | [โ˜‘๏ธ](../../roles/web-svc-xmpp/meta/services.yml) | โŒ | โŒ | โ€” | ## Maintenance diff --git a/docs/requirements/031-llm-gateway-model-backends.md b/docs/requirements/031-llm-gateway-model-backends.md new file mode 100644 index 0000000000..d6db5c5039 --- /dev/null +++ b/docs/requirements/031-llm-gateway-model-backends.md @@ -0,0 +1,109 @@ +# 031 - LLM Gateway and Model Backends (LiteLLM) + +## User Story + +As a platform administrator of Infinito.Nexus, I want a single OpenAI-compatible LLM gateway that routes to any model backend (local Ollama, LM Studio, OpenRouter, ...), so that every AI consumer (OpenWebUI, Flowise, and the agent employees in [032](032-agent-employees-firecracker.md)) targets one `/v1` endpoint and I swap or add model backends centrally without touching any consumer. + +## Background + +AI consumers in this repository each wire their own model provider today: [`web-app-flowise`](../../roles/web-app-flowise/) ships a role-local LiteLLM config, others point directly at [`svc-ai-ollama`](../../roles/svc-ai-ollama/). This duplicates provider wiring and hard-codes backends into consumers. + +A single OpenAI-compatible **LLM gateway** ([LiteLLM Proxy](https://docs.litellm.ai/docs/simple_proxy)) fronts every backend: local `svc-ai-ollama`, a new `svc-ai-lmstudio`, OpenRouter, and any other provider LiteLLM supports. Consumers speak only the gateway `/v1` with a model alias; provider selection and routing are gateway config. This requirement promotes the existing Flowise-local LiteLLM pattern to a shared `svc-ai-litellm` role and makes it the one place backends are declared. + +This is the **model plane**. The tool plane (MCP) is separate ([025](025-mcp-role-integration.md)); the agent fleet that consumes this gateway is [032](032-agent-employees-firecracker.md). + +## Confirmed Decisions + +These choices are settled at requirement creation time and bound the implementation. Re-opening any of them MUST be recorded in the implementing PR. + +1. **A `svc-ai-litellm` gateway is the single model entrypoint.** It exposes one OpenAI-compatible `/v1` endpoint and routes to backends via its `model_list`. No consumer addresses a provider directly. +2. **`svc-ai-ollama` stays the default local backend behind the gateway.** No new model-serving stack replaces it; it is registered as a `model_list` entry. +3. **A `svc-ai-lmstudio` role is added as a routable backend, x86/GPU node only.** It deploys LM Studio in headless server mode (`lms server`, OpenAI-compatible API) and registers behind the gateway. LM Studio has no arm64 Linux server build, so it MUST be pinned to an x86 (typically GPU) node via placement constraint and MUST NOT be scheduled onto the Raspberry Pi / arm64 agent nodes of [032](032-agent-employees-firecracker.md). LM Studio ships primarily as a desktop GUI; the role MUST use its headless/server mode, and the README MUST document the container caveat (GPU passthrough, licensing/model-download constraints). +4. **Flowise's role-local LiteLLM is refactored into the shared role.** The role-local LiteLLM config and container in `web-app-flowise` (`templates/litellm.config.yaml.j2`, its compose service, related env) are removed; Flowise consumes `svc-ai-litellm` instead. No duplicated LiteLLM deployment remains. Flowise stays green after the refactor. +5. **Consumers carry only gateway URL + model alias.** Switching or adding a backend is a `svc-ai-litellm` config change and MUST NOT require a consumer redeploy. +6. **The gateway is authenticated with per-consumer virtual keys.** LiteLLM virtual keys are issued per consumer (OpenWebUI, Flowise, and each 032 agent); a master key is admin-only. This gives per-consumer rate limiting and revocation. The gateway MUST NOT be reachable unauthenticated even on the internal overlay. Keys live in each consumer role's `meta/secrets.yml` `credentials:` block. +7. **`svc-ai-litellm` is headless and internal-only; the admin UI is a separate optional `web-app-litellm` role.** The gateway itself exposes no public domain and no LiteLLM admin UI. A distinct `web-app-litellm` role serves the admin interface behind the proxy with SSO, following the standard `web-app-*` contract. Coupling is asymmetric: `web-app-litellm` REQUIRES the gateway (deploying it forces `svc-ai-litellm` to `enabled: true` + `shared: true`), while `svc-ai-litellm` only OPTIONALLY references the UI (via `group_names`) and runs fine without it. + +## Component Roles + +Every consumer speaks only the gateway `/v1`; the gateway is the single place backends are wired. + +| Component | Role | Interactive? | +|---|---|---| +| [`web-app-openwebui`](../../roles/web-app-openwebui/) | Human chat UI to models (and MCP client per [025](025-mcp-role-integration.md)) | Human, on demand | +| [`web-app-flowise`](../../roles/web-app-flowise/) | No-code builder for LLM apps / agent flows | Human, on demand | +| `web-app-hermes`, `web-app-openclaw` ([032](032-agent-employees-firecracker.md)) | Autonomous agent employees | Autonomous | +| `svc-ai-litellm` | One OpenAI-compatible `/v1`, routes to any backend (headless, internal-only) | โ€” | +| `web-app-litellm` | Optional admin UI for the gateway (proxy + SSO); requires `svc-ai-litellm` | Human, on demand | +| `svc-ai-ollama` | Local small models | โ€” | +| `svc-ai-lmstudio` | Local headless models | โ€” | + +```mermaid +flowchart TB + human([Human]) + + subgraph consumers["Model consumers"] + owui["web-app-openwebui
chat UI"] + flowise["web-app-flowise
flow builder"] + agents["web-app-hermes / web-app-openclaw
(032, autonomous)"] + end + + gw["svc-ai-litellm
LLM gateway (one /v1)"] + + subgraph back["Model backends (wired only here)"] + ollama["svc-ai-ollama
local small"] + lms["svc-ai-lmstudio
local headless"] + openrouter["OpenRouter
external / hosted"] + end + + human -->|chat| owui + human -->|build flows| flowise + owui & flowise & agents -->|/v1 + model alias| gw + gw -->|route by model| ollama + gw -->|route by model| lms + gw -->|route by model| openrouter +``` + +## Backend blockers + +`lmstudio/llmster-preview:cpu` publishes one `linux/amd64` manifest, runs `/app/daemon-run.sh` as its entrypoint and exposes `1234/tcp` (measured against the registry config blob on 2026-08-28). The role wires that server and the gateway routes `lmstudio/default` to it, but a completion additionally needs a model in the container's store on an x86 node with the memory to load it. Until such a node joins the deployment, verify the gateway against `svc-ai-ollama` and leave the LM Studio completion criterion unchecked. + +Closing probe once the node exists: `POST {gateway}/v1/chat/completions` with `"model": "lmstudio/default"` and a consumer virtual key, expecting a non-empty `choices[0].message.content`. + +## Where each guarantee is enforced + +| Guarantee | Enforced by | +| --- | --- | +| No consumer addresses a backend directly | [test_model_backend_via_gateway.py](../../tests/lint/ansible/jinja/test_model_backend_via_gateway.py), over role `templates/` and `vars/` | +| Every declared backend has a `model_list` branch | [test_gateway_backend_registered.py](../../tests/lint/ansible/services/test_gateway_backend_registered.py) | +| Every consumer mints its own key and runs the gateway contract | [test_litellm_consumer_contract.py](../../tests/lint/ansible/services/test_litellm_consumer_contract.py) | +| Gateway is closed, keys are per consumer, revocation is isolated | [probe_auth.py](../../roles/svc-ai-litellm/files/python/probe_auth.py), run on every gateway deploy; unit-tested in [test_probe_auth.py](../../tests/unit/python/roles/svc-ai-litellm/files/test_probe_auth.py) | +| Empty key or out-of-deployment base URL fails the deploy | [consumer_contract.yml](../../roles/svc-ai-litellm/tasks/utils/consumer_contract.yml) | +| The admin UI sits behind Keycloak | [test-oidc-login.js](../../roles/web-app-litellm/files/playwright/test-oidc-login.js), gated on `services.sso` | + +Decision 7's "proxy + SSO" is served by `services.sso.flavor: oidc` on `web-app-litellm` plus LiteLLM's own `GENERIC_*` OIDC settings, rendered into the gateway's env behind `LITELLM_UI_SSO`. An oauth2-proxy sidecar is not an option here: `get_entity_name` maps both `web-app-litellm` and `svc-ai-litellm` to `litellm`, so the two roles share one compose directory, one swarm stack name and one docker network name, and a second stack would overwrite the gateway's `compose.yml` and delete its service under `docker stack deploy --prune`. `web-app-bigbluebutton` is the precedent for a stackless role carrying `flavor: oidc`. The trade-off: an anonymous request reaches LiteLLM's own login page rather than being refused at the edge, and LiteLLM caps SSO at five accounts without a licence. + +Re-routing an alias is a one-line edit to `roles/svc-ai-litellm/templates/config.yaml.j2` followed by `make compose-deploy apps=svc-ai-litellm`; confirm no consumer redeploy is needed by prompting a consumer afterwards without redeploying it. + +## Acceptance Criteria + +- [x] A `svc-ai-litellm` role exposes one OpenAI-compatible `/v1` endpoint; its `model_list` routes to at least `svc-ai-ollama`, `svc-ai-lmstudio`, and one external provider (OpenRouter). +- [x] A `svc-ai-lmstudio` role deploys LM Studio in headless server mode with an OpenAI-compatible API reachable in-cluster, registered behind the gateway. +- [ ] A request to a model alias backed by `svc-ai-lmstudio` returns a completion through the gateway. **Blocked:** see [Backend blockers](#backend-blockers). +- [x] `web-app-flowise` is refactored to consume `svc-ai-litellm`; its role-local LiteLLM config, compose service, and env are removed, no duplicated LiteLLM deployment remains, and Flowise stays green. +- [x] Switching a consumer's backend requires only a `svc-ai-litellm` config change, verified by re-routing a model alias with no consumer redeploy. +- [x] The gateway rejects unauthenticated requests; each consumer authenticates with its own LiteLLM virtual key, and revoking one key blocks only that consumer. +- [x] `svc-ai-litellm` is headless (no admin UI, no public domain); a separate `web-app-litellm` role serves the admin UI behind proxy + SSO, and deploying it forces `svc-ai-litellm` to `enabled: true` + `shared: true`, while the gateway deploys and runs without the UI role. +- [x] `svc-ai-lmstudio` is constrained to an x86 node and is never scheduled onto an arm64/Pi node. +- [ ] The gateway comes up green in both compose and swarm modes. +- [x] A Playwright spec (or equivalent test) verifies a completion round-trips through the gateway. + +## Cross-linking + +- Implementing PR: _to be linked_. + +## See Also + +- Agent fleet that consumes this gateway: [032-agent-employees-firecracker.md](032-agent-employees-firecracker.md) +- MCP tool plane: [025-mcp-role-integration.md](025-mcp-role-integration.md) +- Local model backend: [svc-ai-ollama](../../roles/svc-ai-ollama/) diff --git a/docs/requirements/032-agent-employees-firecracker.md b/docs/requirements/032-agent-employees-firecracker.md new file mode 100644 index 0000000000..4d56711987 --- /dev/null +++ b/docs/requirements/032-agent-employees-firecracker.md @@ -0,0 +1,325 @@ +# 032 - Kernel-Isolated AI Agent Employees with Flowise Supervisor + +## User Story + +As a platform administrator of Infinito.Nexus, I want to deploy self-hostable AI agent platforms (Hermes Agent, OpenClaw) as kernel-isolated, scalable "employees" across my nodes, coordinated by a Flowise supervisor over MCP and routed to models through the [031](031-llm-gateway-model-backends.md) gateway, so that I run a fleet of isolated agents with cross-agent pipelines and kernel-level isolation, without bespoke per-agent wiring. + +## Background + +The agents are real, self-hostable, open-source platforms, each deployed as its own role: + +- **[Hermes Agent](https://hermes-agent.nousresearch.com/)** (Nous Research, MIT). Self-hostable with `local`, `Docker`, `SSH`, `Singularity`, `Modal` backends plus container hardening. Ships an official web dashboard with **self-hosted OIDC** auth (fits the platform SSO), delegates work through **isolated subagents**, has persistent memory, scheduling, vision web browsing, and MCP support (**client since v0.2.0, server since v0.6.0**). Deployed as `web-app-hermes`. +- **[OpenClaw](https://openclaw.ai/)** (open-source, npm/pnpm). Built-in Gateway web dashboard (default port `18789`) plus CLI/TUI, browser control, filesystem sandbox, persistent memory, skills/plugins, and native MCP (`@modelcontextprotocol/sdk`, both client and server). Deployed as `web-app-openclaw`. + +Both bring their own agent logic and internal sandboxing. This requirement adds the **isolation and scaling substrate** around them plus a **Flowise supervisor** for cross-agent coordination. Model routing is the [031](031-llm-gateway-model-backends.md) gateway; the MCP tool contract is [025](025-mcp-role-integration.md). + +Both platforms run model-generated code, which is untrusted, so a kernel-level boundary is required on top of their in-app sandboxing. [gVisor](https://gvisor.dev/) provides that boundary behind an OCI runtime, so each agent app stays a normal container spec and only pins `runtime: runsc`, reusing the existing image pipeline, replicas, healthchecks, and dual-mode machinery. [Kata Containers](https://katacontainers.io/) wrapping Firecracker was the original choice; Decision #2 records why it is unreachable on this container engine. ([E2B](https://github.com/e2b-dev/infra) is the higher-level alternative but brings its own Nomad/Consul orchestration and x86-cloud self-host, which would replace the swarm model.) + +Two host- and swarm-level facts constrain the design and are settled below: swarm's stack deploy drops the compose `runtime:` key, so the runtime has to become a node-wide default, and every deploy path in this repository runs inside a privileged container, so a hypervisor-backed runtime cannot be exercised here at all. + +## Confirmed Decisions + +These choices are settled at requirement creation time and bound the implementation. Re-opening any of them MUST be recorded in the implementing PR. + +1. **Each agent platform is its own role; no generic wrapper.** `web-app-hermes` and `web-app-openclaw` are separate roles reflecting their different stacks (Hermes Docker backend vs OpenClaw npm/pnpm). No speculative "generic agent runner" abstraction. Additional agent platforms become additional roles. +2. **Isolation is gVisor on top of in-app sandboxing; Firecracker is out of reach on this engine.** Each agent app runs under `runtime: runsc`, a userspace guest kernel that intercepts syscalls before they reach the host, so untrusted model-generated code stays kernel-isolated even if the app's own sandbox is bypassed. No custom VMM, jailer wiring, or bespoke rootfs pipeline. E2B/Beam noted as alternatives in the role README but not adopted. + + Kata with the Firecracker hypervisor was the original choice and cannot be delivered on Docker Engine: Firecracker requires the container rootfs as a block device (the containerd `devmapper` snapshotter), while dockerd always hands the runtime a directory. Kata's Firecracker driver advertises no filesystem sharing, and Kata's own documentation tests Docker with QEMU as the VMM. Reaching a microVM here means moving the agent tier off dockerd onto containerd with `devmapper`, which is a separate decision. Until then the microVM clauses below describe an intent, not a shipped mechanism. + + No agent needs host access to do agent work: OpenClaw's browser control and filesystem access run inside the guest, and Hermes' subagent execution runs inside the guest, so the agent runtime is fully isolatable. The only host-level demand is Hermes' web dashboard, which wants `network_mode: host` and a shared host PID namespace solely to display **host** metrics that an isolated guest cannot expose. That host-monitoring view is severable and MUST NOT pull the agent tier out of its isolated runtime: the agent runtime stays isolated, and the host-metrics dashboard is either run in Hermes' embedded/in-process mode (with reduced host stats) or split out to a separate non-isolated `runc` sidecar. +3. **Swarm parity via node-default runtime.** `docker stack deploy` ignores the compose `runtime:` key. The isolating runtime is therefore installed and set as the daemon-wide default on placement-labelled agent nodes; the agent services are pinned there via placement constraint, and every other service is kept off those nodes by the inverse constraint, because a node-wide default runtime applies to whatever is scheduled on it. Compose mode uses the compose `runtime:` key directly on the same image. Both modes MUST reach a running isolated agent, and the deploy MUST refuse to label a node whose daemon still defaults to the shared kernel. A dedicated provisioning role (`svc-virt-kata`) installs the runtime, re-renders the daemon configuration, and labels the node. +4. **Never a plain container, and the deploy proves it.** A preflight probes the host for `/dev/kvm` and for each runtime's binary, and selects the strongest runtime that is actually installed; the choice is logged at deploy time. It MUST NOT fall back to a plain `runc` container: unisolated execution of model-generated code is never allowed. + + This is the one clause that carries a hard guarantee, so it is enforced rather than asserted. In compose the agent role reads the runtime the container actually received and refuses the deploy when it is `runc`. In swarm the node reads its own default runtime and refuses the sandbox label while that is still `runc`, because the label is what routes sandboxed services to it. A lint additionally refuses a privileged container, a host network, pid, ipc or user namespace, and a host docker socket in any role that declares the sandbox, since any one of those hands the workload back to the host and cancels the runtime. + + The embodied deployment of [034](034-svc-ai-robot.md) is the deliberate exception: it drops the runtime because a guest kernel between the agent and the hardware it drives defeats the purpose, and it narrows the grant to an explicit device allowlist instead. +5. **Raspberry Pi is a real deploy target.** Agent images MUST publish an `arm64` manifest so a Pi-class node can pull them, and the agents MUST schedule across at least two labelled worker nodes. This is arch coverage, not arch exclusivity: the same images keep running on the amd64 nodes that CI and the lab use, so the requirement is that every architecture a node may have is published, never that a deploy is pinned to one. +6. **Models go through the [031](031-llm-gateway-model-backends.md) gateway.** Each agent's BYO-model config points only at the `svc-ai-litellm` `/v1` + a model alias; it never addresses a provider directly. The Pis run no large models locally; heavy inference is routed to a GPU/external backend by the gateway. +7. **Agents consume tools as MCP clients via the [025](025-mcp-role-integration.md) mechanism.** Hermes and OpenClaw are configured as MCP clients of the repository's MCP server roles over HTTP/SSE (not stdio: under microVM isolation and multi-node placement a stdio subprocess cannot reach an MCP server in another container). Discovery and credentials reuse 025's [`roles_with_service`](../../plugins/lookup/roles_with_service.py) lookup and `credentials:` blocks. Both roles are added to 025's MCP audit as client roles. Only 025's shared contract (the `services.mcp` schema) and the lookup extension are prerequisites for this requirement; 025's audit tooling, full lint set, and baserow+openwebui slice are independent later work. +8. **Flowise cross-agent supervisor is Phase 2, deferred.** The supervisor (Flowise as MCP client delegating to Hermes' MCP-server mode v0.6.0+ and OpenClaw's MCP-server, chaining cross-agent pipelines) is a separate later slice, not the first implementation. Rationale: it depends on the young hermes MCP-server mode and adds a second orchestration tier. The first slice ships each agent standalone; the supervisor design below is retained as the Phase 2 target. Single-agent use MUST always work without Flowise. +9. **Agent dashboards are public behind proxy + Keycloak OIDC.** `web-app-hermes` and `web-app-openclaw` follow the standard `web-app-*` contract: own canonical domain, reverse-proxy routing, SSO enforced via [`web-app-keycloak`](../../roles/web-app-keycloak/). Hermes uses its native self-hosted OIDC support. OpenClaw's native OIDC is unverified upstream: if absent, the dashboard sits behind the platform's standard auth-proxy pattern (SSO enforced at the proxy, OpenClaw's own token auth staying internal-only). No unauthenticated public surface either way. + + Amended after implementation: the deployed Hermes version serves a bearer API rather than a browser dashboard, so its native-OIDC support cannot be used. It is gated at the auth proxy instead, like OpenClaw and Flowise, admitting the role's `administrator` and `mcp` groups. Holding `API_SERVER_KEY` alone was the whole boundary before, which put every MCP provider Hermes is admitted to behind one shared deployment secret. The cost of the proxy is deliberate: an OpenAI-compatible client presenting only a bearer no longer reaches Hermes through its public vhost, and has to come from inside the container network. +10. **First slice is dashboard-only.** The first implementation wires each agent through its web dashboard only. Chat-platform connectors (Telegram/Discord/Signal/...), which need operator-supplied bot tokens, are deferred to a follow-up and MUST NOT block the first green deploy. +11. **Agents that spin up containers use nested Docker inside the isolated runtime; host socket passthrough is forbidden.** When an agent needs to run compose workloads (see the scenario below), it runs a nested Docker daemon inside its own isolated runtime. Mounting the host `/var/run/docker.sock` into an agent that executes model-generated code is **forbidden**: it grants root-equivalent host control and defeats the isolation entirely. Nested Docker costs performance and, on gVisor, may need `runsc` with the appropriate platform; the role README MUST document the overhead. An agent role that requires containers MUST declare this capability explicitly. +12. **Embodied / dedicated-device mode moves the trust boundary to the whole device.** For an agent that owns and explores a single-purpose machine (a robot platform, a home-assistant appliance), the isolation boundary is the entire dedicated node, not a guest kernel inside it. Privileged/full host access (`/dev`, GPIO, sensors, cameras, host network) is allowed **only** on a node that is dedicated, single-tenant, network-segmented, and explicitly opted in, with the blast radius documented in the role README. It is **forbidden on any shared cluster node**: agents on shared infrastructure always stay under Decision #4. This is the deliberate exception that keeps the general rule intact rather than a hole in it. +13. **An agent can be provisioned with its own platform user account.** Creating an agent employee optionally provisions a dedicated identity through the platform's existing user mechanism (the `users` lookup, LDAP via [`svc-db-openldap`](../../roles/svc-db-openldap/), SSO via [`web-app-keycloak`](../../roles/web-app-keycloak/)); no new account system is built. The account is a **non-privileged standard user** by default (never administrator/service-account-with-mutating-tools). When enabled, the agent authenticates as its own user: OIDC login to its dashboard, a distinct mailbox/identity, and MCP calls made with `auth_subject: user` ([025](025-mcp-role-integration.md)) scoped to that account rather than a shared service account. The account is opt-in per agent; its password/token lives in the role's `meta/secrets.yml` `credentials:` block, never in README or env. An agent MUST also be deployable against an existing account (no forced account creation). + +## Architecture + +```mermaid +flowchart TB + operator([Operator]) -->|"supervise / build pipeline"| flowise + operator -.->|"direct chat (Telegram/Discord/CLI)"| pool + + subgraph host["Swarm cluster"] + subgraph mgr["Manager / normal-runtime nodes (runc)"] + flowise["web-app-flowise
supervisor (MCP client)"] + gw["svc-ai-litellm
LLM gateway /v1 (031)"] + end + + subgraph anode["Agent nodes (label: kata-capable, arm64)"] + k["container engine + gVisor runtime"] + subgraph pool["Agent employees (swarm replicas)"] + hermes["web-app-hermes
gVisor isolated
MCP client+server"] + openclaw["web-app-openclaw
gVisor isolated
MCP client+server"] + end + k --- pool + end + end + + mcpservers["025 MCP server roles
(nextcloud, gitlab, baserow...)"] + + flowise -->|"delegate via MCP"| hermes + flowise -->|"delegate via MCP"| openclaw + hermes & openclaw -->|"tools via MCP (025)"| mcpservers + flowise & hermes & openclaw -->|"models /v1"| gw + + kvm["/dev/kvm + nested virt"]:::pre --> anode + classDef pre fill:#fdd,stroke:#c00,stroke-dasharray: 4 3; +``` + +## Flowise Supervisor (cross-agent pipelines) โ€” Phase 2 + +Deferred to a follow-up slice (Decision #8). Flowise treats each agent as an MCP-exposed sub-agent and chains them. Single-agent use always works directly, without Flowise. Retained here as the Phase 2 target. + +```mermaid +sequenceDiagram + actor User + participant F as Flowise supervisor + participant O as web-app-openclaw + participant H as web-app-hermes + participant G as svc-ai-litellm /v1 + + User->>F: "research topic X, then schedule a summary call" + F->>O: MCP: browse + gather (openclaw tools) + O->>G: inference /v1 + O-->>F: research result + F->>H: MCP: schedule + notify (hermes tools) + H->>G: inference /v1 + H-->>F: scheduled + sent + F-->>User: combined result +``` + +## Example Scenario (orientation): corporate-design CSS sweep agent + +A concrete end-to-end illustration of how the pieces compose. Nothing here is a new mechanism; it maps onto the decisions above. + +**Admin sets it up once:** + +1. Deploy an agent employee (`web-app-hermes` or `web-app-openclaw`) with its **own non-privileged account** (Decision #13) provisioned via `users`/LDAP/Keycloak, plus a matching account on the git forge ([`web-app-gitea`](../../roles/web-app-gitea/) / [`web-app-gitlab`](../../roles/web-app-gitlab/)). +2. Grant it three tool surfaces: the git-forge **MCP server** (025) for branches/PRs/review comments, a **local-deploy/exec** capability inside its isolated sandbox (to `make compose-deploy` a role and drive a browser), and its **model alias** via the 031 gateway. +3. Give it the task prompt: "iterate every role, align its CSS to the corporate design, screenshot, open a PR, wait for review". + +**The agent then runs autonomously, step by step:** + +```mermaid +sequenceDiagram + actor Admin + participant A as Agent employee
(own account, isolated runtime) + participant S as Local sandbox
(compose + browser) + participant G as svc-ai-litellm /v1 (031) + participant F as git forge MCP (025) + + Admin->>A: create agent + assign task + loop for each role under roles/ + A->>S: make compose-deploy (spin up local containers) + A->>S: open app, capture 12 screenshots + A->>G: assess screenshots vs corporate design + G-->>A: inconsistencies + CSS fixes + A->>S: edit role CSS/theme, redeploy, re-screenshot + A->>A: commit on a per-sweep branch + end + A->>F: open PR (as its own account) with screenshots + A->>F: poll PR for review feedback + F-->>A: reviewer comments + A->>F: push fixes, update PR + Note over A,F: waits / iterates until approved +``` + +Key points this scenario pins down: + +- **"Spins up local containers"** happens inside the agent's isolated sandbox, which MUST therefore be able to run compose workloads (nested Docker inside the isolated runtime). This is a real capability constraint the agent role MUST declare; it is exactly the kind of host-near need Decision #4's runtime selection has to accommodate. +- **"Created its own account"** = the git-forge identity from Decision #13; the PR is authored by the agent, not a shared bot. +- **"Waits for feedback"** = the agent polls the PR through the git-forge MCP server (025); the human review gate stays human. +- Models, tools, and identity are the three separate planes (031 gateway, 025 MCP, IAM account) meeting in one workflow. + +## Example Scenario (orientation): Hermes as an isolated home assistant on a Raspberry Pi + +Formalised as its own role in [033-web-app-homeassistant.md](033-web-app-homeassistant.md). Hermes runs on a single Raspberry Pi as a household assistant, kernel-isolated, reachable over voice/chat, controlling home devices through MCP without ever getting host access. + +**Setup:** + +1. One Pi joins as a `kata-capable` arm64 node; `web-app-hermes` deploys there under the isolating runtime selected by the preflight (Decision #4). +2. Models route through the 031 gateway: light intents to a small local `svc-ai-ollama`, heavy reasoning to an external backend. +3. Home devices are reached as **MCP tool servers** (025) over HTTP/SSE, e.g. a smart-home hub MCP server. Hermes is an MCP client only; it never touches the Pi host. +4. The dashboard sits behind proxy + Keycloak OIDC (Decision #9); voice/chat connectors are the follow-up (Decision #10). + +```mermaid +flowchart LR + user([Household]) -->|voice / chat| hermes + subgraph pi["Raspberry Pi (kata-capable, arm64)"] + hermes["web-app-hermes
gVisor isolated"] + end + gw["svc-ai-litellm /v1 (031)"] + hub["smart-home hub
MCP server (025)"] + hermes -->|models /v1| gw + hermes -->|"devices via MCP (tools)"| hub +``` + +The point: an assistant with real reach into the home, but the agent runtime stays isolated and the Pi host stays untouched. Capabilities come through MCP tools, not host access. + +## Example Scenario (orientation): Hermes as an embodied robot platform (full-access, dedicated device) + +The inverse of every other scenario, and deliberately so. Formalised as its own role in [034-svc-ai-robot.md](034-svc-ai-robot.md). Here Hermes is given full rights to explore and drive **one dedicated machine** so it can map its own hardware and act in the physical world: the robot platform idea. This is only coherent under Decision #12. + +**Setup:** + +1. A **dedicated, single-tenant, network-segmented** device (robot controller / SBC), NOT a shared cluster node. This device is Hermes' body. +2. `web-app-hermes` is deployed there with privileged host access (`/dev`, GPIO, sensors, cameras, host network). The trust boundary is the whole device (Decision #12), so there is no microVM around the agent here. +3. Hermes self-explores: enumerates devices, probes sensors/actuators, maps what the machine can do, then controls it. Models via the 031 gateway; higher-level tools still via MCP (025) where useful. +4. Explicit operator opt-in; the README documents the blast radius (this agent can do anything the device can). + +```mermaid +flowchart TB + subgraph device["Dedicated device = the trust boundary (Decision #12)"] + hermes["web-app-hermes
PRIVILEGED, full host access"] + hw["/dev, GPIO, sensors,
cameras, actuators"] + hermes -->|explore + control| hw + end + gw["svc-ai-litellm /v1 (031)"] + hermes -->|models /v1| gw + + shared["Shared cluster nodes"]:::no + device -. "network-segmented, NEVER on shared infra" .-> shared + classDef no fill:#fdd,stroke:#c00,stroke-dasharray:4 3; +``` + +Guardrails that keep this from becoming a hole in the isolation model: + +- **Dedicated device only.** Full access is permitted solely on a node whose only tenant is this agent. Forbidden on any shared cluster node (Decision #12). +- **Segmentation.** The device is network-isolated from shared infrastructure; a compromise stays on the device. +- **Explicit, documented opt-in.** Privileged mode is off by default and the README states exactly what the agent can reach. +- **Different class, not a downgrade.** This is embodied-agent deployment, not the shared-infra agent tier relaxing its rules; shared-infra agents stay isolated per Decision #4. + +## Use Cases + +```mermaid +flowchart LR + operator([Operator]) + admin([Platform admin]) + + subgraph sys["Agent fleet"] + u1(["Deploy agent employee (hermes / openclaw)"]) + u1b(["Provision agent's own user account (opt-in)"]) + u2(["Chat / assign task directly"]) + u3(["Build cross-agent pipeline in Flowise"]) + u4(["Deploy stack + preflight KVM"]) + u5(["Scale agent replicas"]) + u6(["Connect MCP tool servers (025)"]) + end + + operator --- u2 + operator --- u3 + admin --- u1 + u1 -.->|opt-in| u1b + admin --- u4 + admin --- u5 + admin --- u6 +``` + +## Multi-Node Deployment (Raspberry Pi cluster) + +Each Raspberry Pi joins the swarm as an agent node labelled `kata-capable` with the isolating runtime as its daemon-wide default (Decision #3, applied per node). Flowise and the gateway run on a manager node. Swarm distributes agent replicas across the Pis; adding a Pi adds agent capacity with no code change. The Pis do **not** run large models locally: agents speak only the gateway `/v1`, which routes light work to a small local `svc-ai-ollama` and heavy work to a GPU or external backend. All node-run images MUST be `arm64`. + +```mermaid +flowchart TB + operator([Operator]) -->|supervise| flowise + admin([Admin]) -->|"docker node update --label-add"| swarm + + subgraph swarm["Docker Swarm cluster"] + subgraph mgr["Manager node (runc)"] + flowise["web-app-flowise"] + gw["svc-ai-litellm gateway /v1"] + end + subgraph pi1["Raspberry Pi #1 (kata-default, arm64)"] + h1["web-app-hermes
gVisor isolated"] + end + subgraph pi2["Raspberry Pi #2 (kata-default, arm64)"] + o1["web-app-openclaw
gVisor isolated"] + end + subgraph piN["Raspberry Pi #N ..."] + aN["agent replica ..."] + end + end + + flowise -->|delegate MCP| h1 + flowise -->|delegate MCP| o1 + h1 & o1 & aN -->|only /v1| gw +``` + +## Where each guarantee is enforced + +| Guarantee | Enforced by | +| --- | --- | +| Isolation is real in compose | `svc-virt-kata/tasks/utils/assert_isolated.yml` reads `HostConfig.Runtime` off the running container and refuses `runc` | +| Isolation is real in swarm | `svc-virt-kata/tasks/00_core.yml` reads `container info --format DefaultRuntime` and refuses `runc` **before** labelling the node, so the label never promises what the node cannot deliver | +| The sandbox cannot be escaped through the host daemon | [test_sandboxed_no_host_socket.py](../../tests/lint/ansible/services/test_sandboxed_no_host_socket.py), scoped to the roles whose templates pin `SANDBOX_RUNTIME` | +| Inference reaches only the gateway | [test_litellm_consumer_contract.py](../../tests/lint/ansible/services/test_litellm_consumer_contract.py) and [test_model_backend_via_gateway.py](../../tests/lint/ansible/jinja/test_model_backend_via_gateway.py) | +| The dashboards are gated | `test-oidc-login.js` and `test-guest.js` in each agent's `files/playwright/` | +| The agent images run on arm64 | [test_arm64_images.py](../../tests/external/update/docker/test_arm64_images.py) | + +## Agent identity + +The platform already reserves a user key per role, so `hermes` and `openclaw` existed as accounts, non-privileged and each with its own mailbox, before either role claimed one. Claiming the key is what turns a reservation into an identity the agent may authenticate as, and gives the account its description. + +Each agent now claims its own key in `meta/users.yml` and declares nothing about the password there, because provisioning stores one for every declared account. An earlier attempt pinned the password to a separate `identity_password` credential in `meta/secrets.yml`; that was the wrong home for it. An account password belongs to the account, and the provisioning code says so directly: a role whose registration rejects the shell-safe alphabet states that in its own `meta/users.yml` rather than carrying a second credential beside the account it already owns. The `{{ 42 | strong_password }}` that re-renders per read is the fallback for an inventory nobody provisioned, not the value a deployed account holds. + +Pointing an agent at an account that already exists needs no code: the inventory `users` variable overrides the same key, which is the documented override path. + +[test_agent_identity.py](../../tests/lint/ansible/services/test_agent_identity.py) holds the claim, the absence of any role on the account, and the absence of a second credential for it, over the roles derived from the sandbox-runtime scan rather than a list. + +Still open: MCP calls carrying that identity, and the obstacle is upstream rather than a piece of this platform nobody wrote yet. [035](035-mcp-proxy-expansion.md) already fixes the bar: `auth_subject: user` may be set only after the exact client and server prove authorization-code or token-exchange behaviour, token refresh, audience binding, revocation and expiry. No MCP provider deployed here clears it โ€” every server role authenticates as one `service_account`, because that is what its upstream offers โ€” so `auth_subject: user` has nothing to resolve against. Meeting the bar means a provider gaining per-user OAuth upstream, not a credential model this repository can add on its own. + +## Blocked on hardware and on Phase 2 + +A single-node lab cannot answer the multi-node criteria: replica scaling, placement across two `kata-capable` Raspberry-Pi-class nodes, and the compose-plus-swarm end-to-end pass all need the cluster the requirement describes. The arm64 half of the placement criterion is proven by the image check above; the two-node half is not. + +The Flowise supervisor criteria are Phase 2, and reading both upstreams turned "not built yet" into a concrete blocker: `stdio_only`, the same reason `web-app-discourse` carries in [035](035-mcp-proxy-expansion.md). Neither agent's server mode speaks a transport a second container can reach. + +OpenClaw's own CLI reference says so directly: `openclaw mcp serve` "starts a stdio MCP server" whose process "the MCP client owns". Every HTTP transport in that document belongs to the opposite direction, `openclaw mcp add --url --transport streamable-http`, which is OpenClaw acting as a client. Hermes is the same shape: both entry points, `mcp_serve.py` and `agent/transports/hermes_tools_mcp_server.py`, run the MCP SDK's stdio transport, the repository defines neither `run_streamable_http_async` nor `sse_app`, and the user-facing MCP guide describes only Hermes consuming external servers. + +That is what stops the supervisor flow rather than effort. Flowise reaches an MCP server over the container network, and a stdio server has no address there: the client spawns and owns the process, so a shared endpoint two consumers could hold at once does not exist, and the deploy-time contract probe would consume the only session. Wrapping each agent in a stdio-to-HTTP bridge would put an unreviewed process on the platform's most privileged path โ€” an agent with tool access โ€” to work around a transport upstream has not shipped, which is the workaround this project refuses. Re-review when either upstream serves MCP over HTTP. + +## Acceptance Criteria + +- [x] A `web-app-hermes` role deploys Hermes Agent and it comes up healthy with at least one connected interface. +- [ ] A `web-app-openclaw` role deploys OpenClaw and it comes up healthy with at least one connected interface. +- [x] Both agent dashboards are exposed behind the reverse proxy with Keycloak OIDC SSO; no unauthenticated public surface. +- [x] Both agent roles run under the isolating runtime, and the deploy fails when they do not: compose reads the container's actual runtime, swarm reads the node's default runtime before labelling it. +- [x] Where KVM is unavailable (e.g. local `act` through DinD), the agent runs under the gVisor (`runsc`) fallback, never plain `runc`; the chosen runtime is logged at deploy time. +- [x] The agent runtime stays isolated; any host-metrics dashboard is either embedded or a separate `runc` sidecar and does not force the agent tier out of the isolated runtime. +- [x] A preflight probes `/dev/kvm` and each runtime binary, selects the strongest one installed, and logs the choice with an actionable line. +- [x] The first slice is dashboard-only; no chat-platform connector is required for a green deploy. +- [ ] Agent count scales up and down by changing swarm replicas. +- [ ] Agents run on `arm64` and are scheduled across at least two `kata-capable` nodes (Raspberry Pi class); joining an additional labelled node adds capacity without a code change. +- [x] Both agents reach inference only through the [031](031-llm-gateway-model-backends.md) gateway (BYO-model config points at `/v1`); switching a backend is a gateway config change, no agent redeploy. +- [ ] Each agent is configured as an MCP client of at least one [025](025-mcp-role-integration.md) MCP server role over HTTP/SSE, and a tool call through that server succeeds; both roles are added to 025's MCP audit. +- [ ] Creating an agent optionally provisions a dedicated platform user account via the existing `users`/LDAP/Keycloak mechanism; the agent authenticates as that account (OIDC dashboard login, MCP `auth_subject: user`), and deploying against an existing account instead also works. **Partly done:** the account half is implemented and linted (see [Agent identity](#agent-identity)); the MCP half is **blocked** on no deployed provider offering per-user OAuth, which is the bar [035](035-mcp-proxy-expansion.md) sets before `auth_subject: user` may be declared. +- [x] An agent that runs container workloads does so via a nested Docker daemon inside its isolated runtime; no agent mounts the host `/var/run/docker.sock`. Neither agent runs container workloads today, so the enforceable half is the socket ban, held by `tests/lint/ansible/services/test_sandboxed_no_host_socket.py`; wiring a nested daemon is due with the first agent that needs one. +- [ ] (Phase 2) Hermes' and OpenClaw's MCP-server mode is enabled; Flowise connects to both as MCP clients and delegates a task to each. **Blocked:** `stdio_only`, see [Blocked on hardware and on Phase 2](#blocked-on-hardware-and-on-phase-2). +- [ ] (Phase 2) A Flowise supervisor flow runs a cross-agent pipeline that hands a result from one agent to the other and returns a combined output; single-agent use still works without Flowise. **Blocked:** depends on the criterion above. +- [ ] Compose mode brings up an isolated agent via the compose `runtime:` key; swarm mode brings up an isolated agent via the node-default runtime on a placement-labelled node. Both modes are green end to end. +- [x] Each agent role ships a Playwright spec exercising its deployed surface, and both are green. + +## Cross-linking + +- Implementing PR: _to be linked_. + +## See Also + +- Model plane (LLM gateway) this depends on: [031-llm-gateway-model-backends.md](031-llm-gateway-model-backends.md) +- MCP tool plane: [025-mcp-role-integration.md](025-mcp-role-integration.md) +- Hermes Agent: [hermes-agent.nousresearch.com](https://hermes-agent.nousresearch.com/) +- OpenClaw: [openclaw.ai](https://openclaw.ai/) +- Firecracker sandbox reference: [E2B infra](https://github.com/e2b-dev/infra) diff --git a/docs/requirements/033-web-app-homeassistant.md b/docs/requirements/033-web-app-homeassistant.md new file mode 100644 index 0000000000..05551a4f64 --- /dev/null +++ b/docs/requirements/033-web-app-homeassistant.md @@ -0,0 +1,71 @@ +# 033 - Home Assistant Role with MCP Server Surface + +## User Story + +As a platform administrator of Infinito.Nexus, I want a `web-app-homeassistant` role that deploys [Home Assistant](https://www.home-assistant.io/) and exposes its native MCP server, so that agent employees (Hermes on a Pi, [032](032-agent-employees-firecracker.md)) and other MCP clients can control home devices as scoped MCP tools without any host access, making the "isolated home assistant" scenario concrete. + +## Background + +Home Assistant is the open-source home-automation platform. It ships a **native Model Context Protocol Server integration** ([`mcp_server`](https://www.home-assistant.io/integrations/mcp_server/)) that implements Streamable HTTP and exposes Home Assistant's Assist API to MCP clients, with per-entity access control (only explicitly exposed entities are reachable). It can control lights, climate, covers, switches, sensors, media players, fans, locks, vacuums, and cameras. + +This makes Home Assistant a natural [025](025-mcp-role-integration.md) **MCP server role** and the concrete backend for the isolated-home-assistant scenario in [032](032-agent-employees-firecracker.md): the agent stays kernel-isolated and reaches the home only through this MCP surface, never through host access. Home Assistant runs natively on `arm64`/Raspberry Pi, so it co-locates with the Pi agent story. + +## Confirmed Decisions + +These choices are settled at requirement creation time and bound the implementation. Re-opening any of them MUST be recorded in the implementing PR. + +1. **`web-app-homeassistant` deploys Home Assistant in Container mode.** The role uses the official `home-assistant/home-assistant` container (no Supervisor, no add-on store, not privileged), following the standard `web-app-*` contract (`meta/*`). Add-on management is out of scope; the `mcp_server` core integration does not need the Supervisor. +2. **MCP surface is the native `mcp_server` integration under the [025](025-mcp-role-integration.md) contract.** The role's `meta/services.yml` declares `mcp` with `direction: server`, `implementation: native`, `transport: streamable_http`, served under the role's canonical origin per 025. No third-party MCP add-on is used when the native integration covers the need. +3. **Access is entity-scoped and read-mostly by default.** Only entities explicitly exposed to the Assist API are reachable via MCP. Mutating/actuating tools (locks, covers, switches) are off by default and require operator opt-in, per 025's mutating-tools rule. +4. **Consumers discover it via 025.** Agent clients ([032](032-agent-employees-firecracker.md)) and other 025 client roles reach it through the `roles_with_service` lookup; the endpoint is not hard-coded in any consumer. +5. **Auth caveat is documented.** Home Assistant uses its own auth (users + long-lived tokens + `trusted_proxies`), not full OIDC. The MCP endpoint is authenticated with a Home Assistant credential stored in `meta/secrets.yml` `credentials:`; if platform SSO in front of the HA UI is wanted, the trusted-proxy header approach and its limits MUST be documented in the role README. +6. **arm64/Raspberry Pi is supported.** The role runs on `arm64` so it can sit next to the Pi agent from [032](032-agent-employees-firecracker.md). +7. **The UI is published, the MCP surface is not.** *(Revised during implementation; the original decision was internal-only for both.)* Home Assistant follows the `web-app-*` contract and serves its own UI on a canonical domain through the reverse proxy, because every part of that contract โ€” `meta/domains.yml`, `meta/csp.yml`, the guest Playwright persona โ€” assumes a public vhost, and a role without one would have to be shaped as a `svc-*` role instead. The hub's own auth provider guards that surface. The MCP endpoint stays `exposure: internal`: it is reachable in-cluster only, an unauthenticated probe of the public origin is refused, and `files/playwright/test-mcp-guest.js` asserts exactly that. A platform-SSO gate in front of the UI remains a documented follow-up. + +## Architecture + +```mermaid +flowchart LR + user([Household]) -->|UI / voice| ha + subgraph node["Node (arm64 / Pi ok)"] + ha["web-app-homeassistant
+ native mcp_server (025)"] + devices["exposed entities:
lights, climate, locks,
cameras, sensors..."] + ha --- devices + end + + agent["web-app-hermes (032)
isolated MCP client"] + agent -->|"MCP over Streamable HTTP (025)"| ha +``` + +## Where each guarantee is enforced + +| Guarantee | Enforced by | +| --- | --- | +| Only Assist-exposed entities are reachable | `ensure_mcp_entry` binds the MCP config entry to `llm_hass_api: ["assist"]` in [provision_mcp.py](../../roles/web-app-homeassistant/files/python/provision_mcp.py) | +| Mutating tools stay off | the MCP long-lived token belongs to a dedicated account pinned to Home Assistant's `system-read-only` group; `ensure_service_account` re-asserts `group_ids` through `config/auth/update` on every run, so an account promoted by hand is demoted again | +| The endpoint refuses an anonymous caller | [test-mcp-guest.js](../../roles/web-app-homeassistant/files/playwright/test-mcp-guest.js) | +| The stored bearer still authenticates | `tasks/utils/mcp/probe.yml`, which hard-fails the deploy when the hub rejects it | +| The advertised tool contract matches what the hub serves | [files/test/test.sh](../../roles/web-app-homeassistant/files/test/test.sh), which drives the shared MCP contract harness inside the provider's own network | +| The pinned image runs on arm64 | [test_arm64_images.py](../../tests/external/update/docker/test_arm64_images.py) | + +## Acceptance Criteria + +- [x] A `web-app-homeassistant` role deploys Home Assistant in Container mode (no Supervisor/add-ons, not privileged) and it comes up healthy; its MCP endpoint is not published, per the revised Decision 7. +- [x] The native `mcp_server` integration is enabled and declared in `meta/services.yml` as `direction: server`, `implementation: native`, `transport: streamable_http`, conforming to the [025](025-mcp-role-integration.md) schema and lint. +- [x] The MCP endpoint is authenticated; an unauthenticated probe is rejected, and the credential lives in the platform token store โ€” `meta/mcp.yml` `credential.source: token_store`, written by `sys-token-store` โ€” never in a README, an env file or a Playwright trace. *(Revised: 025 and 035 moved MCP bearers out of `meta/secrets.yml` into the token store after this criterion was written.)* +- [x] Only entities explicitly exposed to Assist are reachable via MCP; mutating tools are off unless the operator opts in. +- [ ] An MCP client (e.g. `web-app-hermes` from [032](032-agent-employees-firecracker.md)) discovers the role via `roles_with_service` and reads an exposed entity's state through MCP. +- [x] The role is added to 025's MCP audit as a `server` role. +- [x] The role runs on `arm64`. +- [ ] The role comes up green in both compose and swarm modes. +- [x] A Playwright spec exercises the Home Assistant surface and is green. + +## Cross-linking + +- Implementing PR: *to be linked*. + +## See Also + +- MCP contract: [025-mcp-role-integration.md](025-mcp-role-integration.md) +- Agent that consumes it (isolated home-assistant scenario): [032-agent-employees-firecracker.md](032-agent-employees-firecracker.md) +- Home Assistant MCP Server: [home-assistant.io/integrations/mcp_server](https://www.home-assistant.io/integrations/mcp_server/) diff --git a/docs/requirements/034-svc-ai-robot.md b/docs/requirements/034-svc-ai-robot.md new file mode 100644 index 0000000000..c4f83ad1e8 --- /dev/null +++ b/docs/requirements/034-svc-ai-robot.md @@ -0,0 +1,87 @@ +# 034 - Embodied Robot Platform for Hermes (svc-ai-robot) + +## User Story + +As a platform administrator of Infinito.Nexus, I want a `svc-ai-robot` role that turns one dedicated machine into an embodied platform for Hermes, giving the agent scoped-to-full host access so it can explore its own hardware and act in the physical world, so that Hermes can "come to life" on a robot while this power stays confined to a dedicated, segmented device and never leaks onto shared infrastructure. + +## Background + +Every other agent deployment in [032](032-agent-employees-firecracker.md) keeps the agent kernel-isolated. This role is the deliberate inverse defined by [032](032-agent-employees-firecracker.md) Decision #12 (embodied / dedicated-device mode): for a robot, the useful trust boundary is the **whole device**, because the agent's job is to drive that device's hardware (GPIO, I2C/SPI sensors, cameras, actuators, motors). A microVM around the agent would only get in the way of the very hardware it is meant to control. + +The safety of this design comes entirely from **confinement of the device**, not from confinement of the agent: the machine is dedicated to Hermes, single-tenant, network-segmented, and physically separate from shared infrastructure. `svc-ai-robot` is the role that provisions that device and deploys Hermes on it in privileged mode. It builds on the [`web-app-hermes`](032-agent-employees-firecracker.md) role rather than reimplementing the agent. + +## Confirmed Decisions + +These choices are settled at requirement creation time and bound the implementation. Re-opening any of them MUST be recorded in the implementing PR. + +1. **`svc-ai-robot` deploys Hermes in embodied mode on a dedicated device.** It reuses the `web-app-hermes` agent from [032](032-agent-employees-firecracker.md) and configures it for privileged hardware access. The trust boundary is the device ([032](032-agent-employees-firecracker.md) Decision #12), so no microVM wraps the agent here. +2. **Dedicated, single-tenant, segmented node only.** The role MUST refuse to deploy on a node that carries any shared-workload label or hosts other tenants, and the node MUST be network-segmented from shared infrastructure. This is enforced, not just documented: a placement/preflight guard hard-fails on a shared node. +3. **Hardware access is declared, not blanket-by-accident.** The role exposes a device allowlist (`/dev/*`, GPIO, I2C/SPI, video/camera, serial) that the operator sets; "full access" is an explicit, documented opt-in, not the silent default. The README documents the blast radius: the agent can do anything the granted devices allow. +4. **Control is raw device access plus agent code execution; no robotics middleware is mandated.** Hermes drives the hardware by executing code directly against the granted devices (GPIO/I2C/SPI/serial/video libraries), consistent with its self-exploration. This is the deliberate choice over a ROS2/middleware abstraction: the embodied device is already the trust boundary (there is no microVM here), so the agent runs code on the device itself. A middleware layer MAY be added later per robot but is not required by this role. +5. **Self-exploration is a first-class capability.** Hermes enumerates and probes the granted hardware to build a capability map (which sensors/actuators exist, what they report/do) before or during control, and that map is retrievable. +6. **Models via the [031](031-llm-gateway-model-backends.md) gateway; higher-level tools via [025](025-mcp-role-integration.md) MCP.** Embodiment changes the host boundary, not the model or tool planes: inference still goes through the gateway, and non-hardware tools still come via MCP. +7. **`arm64` robot SBCs are a target.** The role runs on `arm64` single-board computers typical of robotics, not only x86. +8. **Opt-in and off by default.** Privileged embodied mode is never a default; enabling it is an explicit operator action with the guardrails above in force. +9. **Physical safety is the operator's responsibility, and the role MUST say so.** This role does NOT mandate an emergency-stop or motion rate-limits as a platform acceptance criterion. Because an agent driving motors/actuators can cause physical harm, the README MUST prominently warn that hardware safety (e-stop, current/motion limits, fail-safe wiring) is the operator's responsibility and is out of the platform's scope. The role MUST NOT claim any safety guarantee it does not enforce. + +## Architecture + +```mermaid +flowchart TB + operator([Operator]) -->|"opt-in enable"| robot + + subgraph device["Dedicated robot device = trust boundary (032 Decision #12)"] + robot["svc-ai-robot
= web-app-hermes, PRIVILEGED"] + hw["declared devices:
/dev, GPIO, I2C/SPI,
cameras, motors, sensors"] + robot -->|"explore + control"| hw + end + + gw["svc-ai-litellm /v1 (031)"] + mcp["025 MCP tool servers"] + robot -->|models /v1| gw + robot -.->|"non-hardware tools"| mcp + + shared["Shared cluster nodes"]:::no + device -. "segmented, guard hard-fails if shared" .-> shared + classDef no fill:#fdd,stroke:#c00,stroke-dasharray:4 3; +``` + +## Hardware blockers + +Three criteria need a dedicated single-tenant device with real sensors and actuators wired to it. No such device is in the deployment, and the platform cannot simulate one honestly: a stubbed GPIO would make the criteria green while proving nothing about the embodied path. They stay unchecked until the device joins. + +What is already provable without it: the admission guard refuses a shared host or an empty device allowlist, both agent images publish `linux/arm64`, and neither agent is pinned away from arm64. + +Closing probes once the device exists: deploy with `ROBOT_DEVICE_ALLOWLIST` naming the wired devices, ask Hermes for its capability map, then read one granted sensor and drive one granted output. + +## Where each guarantee is enforced + +| Guarantee | Enforced by | +| --- | --- | +| Every embodiable agent runs the admission checks | [test_robot_admission_guard.py](../../tests/lint/ansible/services/test_robot_admission_guard.py), deriving the agent set from `svc-ai-robot`'s own service flags | +| No blanket device grant, no shared host | [admit.yml](../../roles/svc-ai-robot/tasks/utils/admit.yml), included by each agent before it deploys | +| Inference reaches only the gateway | [test_litellm_consumer_contract.py](../../tests/lint/ansible/services/test_litellm_consumer_contract.py) and [test_model_backend_via_gateway.py](../../tests/lint/ansible/jinja/test_model_backend_via_gateway.py) | +| Tools arrive over MCP | `web-app-hermes/meta/mcp.yml` `direction: client`, held to the 025 schema by the MCP lint suite | +| The agent images run on arm64 | [test_arm64_images.py](../../tests/external/update/docker/test_arm64_images.py) | + +## Acceptance Criteria + +- [ ] A `svc-ai-robot` role deploys `web-app-hermes` in privileged embodied mode on a dedicated device and it comes up healthy. **Blocked:** see [Hardware blockers](#hardware-blockers). +- [x] The role hard-fails (placement/preflight guard) when targeted at a node carrying a shared-workload label or hosting other tenants. +- [x] Hardware access is limited to an operator-set device allowlist; no device outside the allowlist is exposed to the agent. +- [ ] Hermes produces a retrievable capability map of the granted hardware (self-exploration). **Blocked:** see [Hardware blockers](#hardware-blockers). +- [ ] The agent can read a granted sensor and actuate a granted output through its embodied access. **Blocked:** see [Hardware blockers](#hardware-blockers). +- [x] Inference still routes through the [031](031-llm-gateway-model-backends.md) gateway; non-hardware tools still come via [025](025-mcp-role-integration.md) MCP. +- [x] The role runs on `arm64`. +- [x] Privileged mode is off by default; enabling it is an explicit, documented operator opt-in, and the README states the blast radius. +- [x] The README prominently warns that physical hardware safety (e-stop, motion/current limits, fail-safe wiring) is the operator's responsibility and out of platform scope; the role claims no safety guarantee it does not enforce. + +## Cross-linking + +- Implementing PR: _to be linked_. + +## See Also + +- Embodied-mode decision and scenario: [032-agent-employees-firecracker.md](032-agent-employees-firecracker.md) +- LLM gateway: [031-llm-gateway-model-backends.md](031-llm-gateway-model-backends.md) +- MCP tool plane: [025-mcp-role-integration.md](025-mcp-role-integration.md) diff --git a/docs/requirements/035-mcp-proxy-expansion.md b/docs/requirements/035-mcp-proxy-expansion.md new file mode 100644 index 0000000000..0343f5288b --- /dev/null +++ b/docs/requirements/035-mcp-proxy-expansion.md @@ -0,0 +1,592 @@ +# 035 - MCP Proxy Expansion and Application Interconnection + +## User Story + +As a platform administrator of Infinito.Nexus, I want every role with an `application_id` to have an explicit, evidence-based MCP disposition and every suitable application to expose a narrowly curated MCP surface to Open WebUI, Flowise, n8n, and other approved clients so that applications can be connected without turning shared administrator credentials, raw infrastructure APIs, or arbitrary network access into agent tools. + +## Scope + +This requirement extends [025 - MCP Role Integration](025-mcp-role-integration.md). +Requirement 025 defines the initial MCP metadata and the first Open WebUI integration; this requirement defines the exhaustive role audit, proxy and workflow-adapter contract, client reconciliation, and the conditions under which the remaining roles may be integrated. + +The repository snapshot evaluated for this requirement contains 172 roles with a literal `application_id` and 18 role-local `mcp:` blocks. +The audit below classifies every one of those 172 roles exactly once. +The snapshot is planning evidence, not a second runtime registry: implemented surfaces remain authoritative in each role's `meta/services.yml`, while a generated lint test MUST prove that every current `application_id` still has a disposition. + +This requirement covers requirement and design work only. +It does not authorize enabling a new MCP endpoint, upgrading an application, installing an upstream plugin, or widening a credential in the same change that introduces this document. + +## Findings That Constrain the Design + +The implementation MUST start from the current code rather than from the completed checkboxes in requirement 025: + +- [`plugins/lookup/mcp_servers.py`](../../plugins/lookup/mcp_servers.py) currently reads every provider token from `users.administrator.tokens` and copies that deployment credential to every selected client. `auth_subject` is returned as metadata but does not select or verify the real credential owner. +- [`plugins/filter/mcp/authorization.py`](../../plugins/filter/mcp/authorization.py) renders `oidc` as a stored bearer value. It does not acquire, refresh, exchange, or revoke an end-user OAuth token. A rendered deployment bearer MUST therefore be classified as `service_account`, never as user delegation or on-behalf-of. +- [`plugins/lookup/roles_with_service.py`](../../plugins/lookup/roles_with_service.py) discovers all shared providers without a consumer allowlist. Several current role flags also name concrete peer roles in `group_names`, which cannot scale to Flowise, n8n, LiteLLM, and future clients. +- [`roles/web-app-openwebui/tasks/utils/mcp.yml`](../../roles/web-app-openwebui/tasks/utils/mcp.yml) and [`roles/web-app-openwebui/files/python/provision_mcp_grants.py`](../../roles/web-app-openwebui/files/python/provision_mcp_grants.py) can resolve or create an Open WebUI group by its path-like name and then write the generated group identifier into `access_grants`. This is the correct deployment-controlled mechanism, but application-specific Keycloak membership, last-group revocation, and restart reconciliation remain mandatory gaps. +- [`roles/web-app-openwebui/templates/env.j2`](../../roles/web-app-openwebui/templates/env.j2) sets `ENABLE_PERSISTENT_CONFIG=false`. API changes to environment-backed connection state MUST be treated as runtime state that has to be reconciled after every container restart; a deploy-only one-shot is insufficient. +- [`roles/web-app-flowise/vars/main.yml`](../../roles/web-app-flowise/vars/main.yml) currently computes discovery data but no task registers it. [`roles/web-app-flowise/templates/env.j2`](../../roles/web-app-flowise/templates/env.j2) disables `HTTP_SECURITY_CHECK` globally when MCP servers are present, and [`roles/web-app-flowise/files/playwright/test-mcp.js`](../../roles/web-app-flowise/files/playwright/test-mcp.js) proves only that an anonymous chatflow call is rejected. +- The exact Flowise 3.1.4 source provides authenticated create, list, update, authorize, delete, and tool-list routes under `/api/v1/custom-mcp-servers`. It stores custom-header authentication encrypted and binds entries to the active workspace. Its authorization path passes `sse` to the toolkit, but that argument only selects stdio versus HTTP: for any URL the toolkit attempts Streamable HTTP first and falls back to SSE through `secureFetch`, whose `node-fetch` response body the MCP SDK rejects with `expected a web ReadableStream`. The pinned release therefore registers Streamable HTTP providers and cannot register SSE ones. +- The exact n8n 1.95.3 source contains an SSE MCP Client Tool and an SSE MCP Server Trigger. Its public API can create credentials and workflows and activate workflows. The newer instance-wide administration MCP service MUST NOT be attributed to this pinned release. +- [`roles/svc-ai-litellm/meta/services.yml`](../../roles/svc-ai-litellm/meta/services.yml) pins `main-v1.77.3.dynamic_rates`. Its current role contract is an inference gateway. It MUST remain only an inference gateway until source inspection and an end-to-end test of a new explicit pin prove the required MCP gateway behavior. +- [`roles/test-e2e-cli/files/shared/mcp/contract.sh`](../../roles/test-e2e-cli/files/shared/mcp/contract.sh) proves the endpoint answers its declared contract, not that any particular client can route to it: it runs in a throwaway container joined to the *provider's* own network, because an `expose:`-only endpoint resolves nowhere else. Per-client routing is therefore still unproven by any test. Measured by hand on compose, Open WebUI resolves `baserow` to `192.168.206.4` and `homeassistant` to `192.168.79.2`, both distinct from the wildcard address, so the topology carries those two pairs; Swarm is unmeasured. [`isolation.sh`](../../roles/test-e2e-cli/files/shared/mcp/isolation.sh) does cover the adapter half, counting networks inside the sidecar for every `implementation: adapter` provider. +- Only Open WebUI carries a per-server user boundary, through the `mcp` RBAC group it grants per provider. Flowise and OpenClaw instead declare an `mcp` role their auth proxy admits alongside `administrator`, which is the documented trust domain the criterion allows: holding it reaches every provider that client is admitted to. n8n's MCP block is disabled. Hermes has neither: `meta/rbac.yml` declares `roles: {}` and `services.sso.enabled` is false, so its whole MCP surface is bounded by the shared `API_SERVER_KEY` alone. Whether that counts as an isolated trust domain is an operator decision, not something the declarations settle. +- The adapter `digest` pins nothing today. All ten `implementation: adapter` roles carry the identical placeholder `sha256:` followed by sixty-four zeros, the schema only checks that prefix, and nothing outside the tests reads the field: the running image is resolved through `lookup('container_image', โ€ฆ)` from `services.mcp-adapter.image`. The immutable-source guarantee is therefore declared and not in force, so a lint that rejects a placeholder digest MUST land together with real digests rather than before them. +- `allowed_consumers` creates no network edge. A client reaches a provider only when the provider declares a `kind: mcp_client` consumer in its `meta/networks.yml`, or when the client happens to declare that provider as a service for an unrelated reason. Four of twenty providers declare the opening (gitlab, homeassistant, moodle, nextcloud); the other sixteen admit consumers they cannot serve, four of them enabled (baserow, gitea, jenkins, mattermost). Measured: deploying Hermes fails at its own probe with `All connection attempts failed` against `http://prometheusmcp:8080/mcp`, because `hermes` joins `[gitlab, hermes, homeassistant, litellm, moodle]` while `prometheusmcp` joins `[prometheus]` alone, and the adapter sidecar's isolation check asserts exactly that single attachment. Open WebUI reaches Baserow only because it also declares `services.baserow`. Per-pair networks therefore have to replace `kind: mcp_client`, which opens a provider to every client rather than to the admitted one. +- Opening an adapter provider's network to its clients collides with the sidecar isolation invariant, so one of the two has to give. A provider that declares the `mcp_client` overlay puts its own containers on it: `homeassistant` joins `[homeassistant, homeassistant_default]`. The same declaration on an adapter provider would give its sidecar a second interface, and [`isolation.sh`](../../roles/test-e2e-cli/files/shared/mcp/isolation.sh) rejects anything but exactly one, because a sidecar holding the provider's credential must reach that provider only. Today `prometheusmcp` satisfies it with a single attachment and is therefore reachable by no client at all. Either the sidecar joins only the pair network and the provider joins it too, or the isolation check becomes an identity check over the admitted peers rather than a count. +- Hermes renders its agent config and its env from the same discovery list within one pass, and they disagree. Measured on compose: `config/config.yaml` written at 17:07:54 carries `web_app_prometheus` with `Authorization: "Bearer ${env:WEB_APP_PROMETHEUS_MCP_TOKEN}"`, while `.env/env` written at 17:07:51 defines no `*_MCP_TOKEN` at all, although [`templates/env.j2`](../../roles/web-app-hermes/templates/env.j2) loops over the same `HERMES_MCP_SERVERS` unconditionally. The client therefore presents an empty bearer and the adapter answers `401`, which is correct behaviour on its side: probed from inside, `prometheusmcp` returns `200` for its own bearer and `401` for a wrong one. Any fix has to make the env and the config provably render from one evaluation of the list rather than two. +- A shared infrastructure network carries lateral reach between the applications that join it, so `allowed_consumers` is an application-layer decision the network does not enforce. Measured on the compose stack: Flowise and Baserow both join `postgres` because both use the central database, and Flowise opens `baserow:80` at `192.168.200.5` although Baserow does not admit Flowise as a consumer. A client whose users can name a URL is bounded only by its deny list, which covers loopback, link-local metadata and multicast but no application host. Reach MUST be measured by resolved address, never by name: an unknown name falls through to a wildcard resolver that answers with one reachable address, so a name-based probe reports every peer as reachable and proves nothing. Bounding lateral reach needs a network policy or per-pair networks rather than the current shared-service topology. + +The implementing agent MUST start its upstream source audit from these project-owned repositories or exact tags and MUST record the selected immutable version in the implementing PR: + +| Capability | Authoritative source entry point | +|---|---| +| Flowise registry at the deployed pin | [Flowise tag `flowise@3.1.4`](https://github.com/FlowiseAI/Flowise/tree/flowise%403.1.4), especially `packages/server/src/routes/custom-mcp-servers/` and `packages/server/src/services/custom-mcp-servers/` | +| n8n client, trigger, and public provisioning API | [n8n tag `n8n@1.95.3`](https://github.com/n8n-io/n8n/tree/n8n%401.95.3), especially `packages/@n8n/nodes-langchain/nodes/mcp/` and `packages/cli/src/public-api/v1/handlers/` | +| WordPress plugin path | [`WordPress/mcp-adapter`](https://github.com/WordPress/mcp-adapter) | +| Discourse sidecar path | [`discourse/discourse-mcp`](https://github.com/discourse/discourse-mcp) | +| Qdrant sidecar path | [`qdrant/mcp-server-qdrant`](https://github.com/qdrant/mcp-server-qdrant) | +| ERPNext/Frappe plugin path | [`frappe/mcp`](https://github.com/frappe/mcp) | +| Matomo plugin candidate | [`matomo-org/plugin-McpServer`](https://github.com/matomo-org/plugin-McpServer) | +| Penpot interactive server | [`penpot/penpot-mcp`](https://github.com/penpot/penpot-mcp) | +| MariaDB isolated sidecar path | [`MariaDB/mcp`](https://github.com/MariaDB/mcp) | +| Redis blocked sidecar path | [`redis/mcp-redis`](https://github.com/redis/mcp-redis) | +| LiteLLM gateway candidate | [`BerriAI/litellm`](https://github.com/BerriAI/litellm) | + +An upstream README or current default branch MAY identify a candidate, but only the source and tests of the exact selected tag or digest may close a compatibility criterion. + +The reconciliation stage MUST run before the end-to-end tests that read the converged state, and MUST NOT sit behind a task that a red test aborts. Placed in the destructor stage it ran after the Playwright suite, and `any_errors_fatal` meant any failing role skipped reconciliation entirely, so the suite asserted a state nothing had produced yet. + +A relative `include_tasks` resolves against the including file's directory when that file was reached by path, and against `tasks/` when it was reached through `tasks_from`. A file under `tasks/utils/` therefore loads from its own role and fails from the reconciler, unchanged. Every include below a `tasks_from` entrypoint MUST name a path that holds under both bases. + +Open WebUI stores its tool servers in its own configuration, so a deployment that already holds connections answers every later read with them. A client MUST reconcile that answer against the declared set instead of adopting it: reading it as the desired state leaves a newly declared provider registered nowhere and a rotated bearer registered stale, in both cases without a failure. Clients that render their whole configuration each run, such as Hermes and OpenClaw, do not carry this class. + +A role that gains a `shared_net` overlay changes its network layout: the project's default network, named after the entity and carrying the declared local subnet, is replaced by an unnamed project default, and the entity name passes to an externally managed network. Docker cannot relabel an existing network, so on a deployment that already ran, the network has to be recreated, and that fails while any consumer holds an endpoint on it: + +```text +Network baserow Removing +Error response from daemon: error while removing network: network baserow has active endpoints (name:"hermes") +``` + +The hazard is ordering-dependent, not universal: it fires only when a consumer already holds an endpoint at the moment the provider first renders with the overlay. A provider that renders first migrates cleanly and never sees it, which is why some roles pass and others abort on the same change. Purging the provider's stack does not help, because the project label lives on the Docker network rather than in the compose directory. A fresh deployment is unaffected, so this never appears in CI. + +The token store is written on `STACK_HOST` while every `lookup('users').tokens` reader executes on the Ansible controller. In compose the two are one machine; in swarm they are not, so a provider that mints and persists its credential still resolves to an empty bearer for every client. The store therefore has to reach the controller as well. + +A client MUST NOT treat an unreachable provider as fatal while the play is still running. Roles deploy in dependency order, so a client that probes during its own role can run before a provider exists at all, and aborting there prevents that provider from ever deploying. This is the same exemption `credential_missing` already carries, and it ends the same way: the reconciliation stage probes with `MCP_RECONCILE_STRICT` once every provider has run, and a provider still unreachable there is a real failure. + +Swarm attaches every task to `docker_gwbridge` for ingress and egress. A sidecar isolation check that compares attached addresses against the provider's declared subnets MUST accept that interface, or it rejects every sidecar in swarm while proving nothing about application reachability. + +An application that authenticates its own API with a bearer MUST expose that path through the SSO ACL whitelist. The proxy cannot validate an application bearer, so a fully gated vhost answers an API call with an identity-provider redirect, which a client following redirects reads as a successful 200. + +## Architecture Decision + +The platform MUST NOT deploy one all-powerful OpenAPI-to-MCP process holding administrator credentials for every application. +It MUST provide one reusable, immutable adapter implementation but instantiate it once per provider application or per equally isolated trust domain. +Each adapter instance MUST attach only to the provider's existing local network, receive only that provider's least-privileged credential, expose a distinct MCP endpoint, and remain addressable by the provider's `application_id`. + +The precedence is: + +1. A supported native MCP endpoint with an enforceable tool policy. +2. A pinned, source-audited upstream plugin. +3. A pinned, isolated upstream sidecar. +4. A repository-owned allowlist adapter or a repository-owned n8n workflow. +5. A documented blocker when none of the above can preserve the application's authorization boundary. + +Flowise and Open WebUI are clients, not generic security gateways. +n8n MAY adapt a workflow to MCP when its project, credential, input schema, and exposed workflow tools are deployment-managed. +LiteLLM MAY become a routing or policy layer only after the exact selected image is pinned and proven; it MUST NOT become the sole holder of all application administrator credentials. + +Every exposed provider remains a separate logical MCP server even when a common proxy implementation serves it. +This preserves the mapping between `roles//mcp`, the client connection, the upstream credential, the tool allowlist, and the audit record. + +## Target Metadata Contract + +Every role with an `application_id` MUST contain one role-local `mcp:` audit mapping in `meta/services.yml`. +This requirement supersedes requirement 025's rule that absence means no upstream path, because absence cannot distinguish a reviewed refusal from a role that nobody examined. +Discovery MUST select only a deployable classification with explicit `enabled: true` and `shared: true`; audit-only mappings MUST never become endpoints. + +An audit-only mapping MUST use this minimal explicit form: + +```yaml +mcp: + classification: no_surface + reason: host_execution_boundary + notes: This desktop role has no isolated remote application identity or endpoint. +``` + +Allowed classifications MUST be `native_server`, `native_client`, `native_both`, `plugin_server`, `sidecar_server`, `adapter_server`, `adapter_candidate`, `blocked`, `enabler`, `subordinate`, and `no_surface`. +Allowed reasons MUST be documented and linted, including `no_remote_surface`, `host_execution_boundary`, `privileged_control_plane`, `shared_engine_isolation`, `administrative_surface`, `duplicate_owner`, `version_unverified`, `licence`, `hosted_only`, `stdio_only`, `interactive_browser_session`, `unreviewed_third_party`, and `missing_dependency`. +A deployable mapping MUST additionally carry the source URL and exact supported version or source commit; a negative classification MUST carry a concrete reason and explanatory notes. + +The shared service schema MUST also add explicit adapter and consumer fields. +There are no implicit security defaults: every field shown below is required for an enabled adapter surface, and a missing value MUST fail lint or deployment. + +```yaml +mcp: + classification: adapter_server + enabled: true + shared: true + direction: server + transport: sse + exposure: internal + auth: bearer_token + auth_subject: service_account + credential: + owner: mcp-service-web-app-example + source: token_store + key: web-app-example + implementation: adapter + maturity: experimental + source_url: https://example.invalid/project/source/tree/v4.5.6 + allowed_consumers: + - web-app-openwebui + - web-app-flowise + endpoint: + service_key: example-mcp + path: /mcp + port_key: http + adapter: + type: openapi_allowlist + image: registry.example.invalid/infinito-mcp-adapter + version: 1.2.3 + digest: sha256:0123456789abcdef + upstream_api_version: v1 + specification_path: files/mcp/openapi-v1.json + specification_sha256: sha256:fedcba9876543210 + limits: + request_bytes: 65536 + response_bytes: 1048576 + timeout_seconds: 15 + concurrent_requests: 4 + page_size: 100 + result_items: 500 + stream_seconds: 300 + tools: + allowlist: + - example_search + - example_get + schema_sha256: sha256:abcdef0123456789 + read_only_default: true + mutating_tools_enabled: false +``` + +Allowed implementation values MUST become `native`, `plugin`, `sidecar`, `adapter`, and `external`. +An `adapter` MUST declare exactly one of these types: + +- `openapi_allowlist`: a checked-in, versioned, hash-pinned API description plus explicit operation identifiers; +- `graphql_allowlist`: checked-in persisted operations only, with runtime introspection and arbitrary query text rejected; +- `named_query`: checked-in parameterized read queries or views through an application-specific read-only database principal, never arbitrary SQL; +- `s3_prefix`: list, head, and get through a dedicated read-only policy restricted to named buckets and prefixes; +- `prometheus_readonly`: query, query-range, labels, metadata, and targets with explicit lookback, sample, response, and timeout limits; +- `n8n_workflow`: a checked-in workflow with a stable ownership marker, explicit input schema, explicit connected tools, and bearer-protected SSE trigger; +- `resource_readonly`: checked-in rules for exposing a bounded, non-secret published content set as MCP resources rather than pretending it is an application action API. + +The schema MUST reject a generic URL, runtime OpenAPI document, free-form GraphQL query, raw SQL tool, unrestricted bucket, arbitrary filesystem root, shell command, Docker socket, or implicit exposure of every operation added by an upstream upgrade. + +`allowed_consumers` MUST contain explicit client `application_id` values. +Discovery MUST require the provider to allow the consumer and the consumer to support the provider's transport and authentication scheme. +Authorized but unrenderable entries MUST fail reconciliation with a machine-readable reason; they MUST NOT disappear silently. + +## Identity, Authorization, and Credential Requirements + +### Provider identity + +Each service-account integration MUST provision a dedicated non-login identity with only the upstream permissions needed by the declared tool allowlist. +The lookup MUST resolve `mcp.credential.owner`, `source`, and `key`; it MUST NOT hard-code `administrator`. +Deployment MUST fail if the resolved principal is missing, empty, more privileged than `auth_subject` declares, or shared with an unrelated provider. + +Where an upstream supports real per-user OAuth, the implementation MAY set `auth_subject: user` only after the exact client and server prove authorization-code or token-exchange behavior, token refresh, audience/resource binding, logout/revocation, and expiry. +Passing a static bearer issued to the deployment is not on-behalf-of and MUST remain `service_account`. +Client-side group gating controls access to that service account; it does not recreate the caller's application permissions. + +Credentials MUST be unique per provider and, when a provider cannot distinguish consumers, per provider-consumer pair. +Rotation MUST use an explicit two-phase procedure: issue new, reconcile every consumer, prove new works, revoke old, and prove old fails. +Disabling a surface or removing a consumer MUST revoke the related credential rather than merely hiding the connection. + +Secrets MUST be sent in authenticated headers or a supported secret reference. +A URL path component selected by `key_credential` MUST be hidden behind an internal header-authenticated proxy or be proven non-secret. +Bearer values and secret path segments MUST be redacted from application logs, reverse-proxy logs, task output, Playwright traces, and exception messages. + +### Application-scoped user grants + +Every client connection MUST map to exactly one provider group named `roles//mcp`. +The deployment MAY create or locate the corresponding client-local group by name after startup and then use the identifier assigned by the client API; it MUST NOT predict a generated group UUID. + +The declarative user schema MUST gain an application-scoped role form, for example: + +```yaml +users: + alice: + application_roles: + web-app-baserow: + - mcp + web-app-zammad: + - mcp +``` + +The exact schema name may change during implementation, but an unscoped `roles: [mcp]` MUST NOT grant every application's `mcp` role. +Direct Keycloak group membership remains valid, but both paths MUST converge on the exact application group in the OIDC claim. + +Open WebUI access tests MUST cover a user with one of several MCP groups, a user with no MCP group, a user in the wrong application's group, and removal of the user's last group. +The known empty-group synchronization behavior MUST be fixed upstream, patched in the pinned image, or compensated by an explicit reconciliation/session-invalidation mechanism before strict revocation is claimed. + +Flowise 3.1.4 binds registry entries to a workspace, not to the platform's per-application Keycloak groups. +Until an exact pinned Flowise version proves per-server user ACLs, deployment-managed MCP connections MUST live in an admin-only workspace or a separate Flowise trust-domain instance. +They MUST NOT be offered to every ordinary flow author merely because the user can sign into Flowise. +The same rule applies to Hermes, OpenClaw, n8n, and any future client lacking a tested per-server user authorization boundary. + +### Keycloak as authorization enabler + +`web-app-keycloak` MUST NOT expose its administration API as a general MCP tool server. +It MAY provide OAuth authorization infrastructure for MCP servers by provisioning an explicit resource/audience, client policy, scope, and redirect contract per provider. +Experimental token exchange MUST remain disabled for MCP until the exact Keycloak, client, and server versions pass user-delegation and revocation tests. + +## Discovery and Reconciliation + +A post-application MCP reconciliation stage MUST run after all selected provider roles have provisioned and probed their endpoints. +The stage MUST create one immutable discovery snapshot and reconcile Open WebUI, Flowise, Hermes, OpenClaw, and n8n from that snapshot. +It MUST run after initial deployment, provider credential rotation, provider MCP enable/disable changes, and a standalone client container restart. + +No provider or client `enabled` or `shared` expression may enumerate concrete peer role names. +Provider enablement MUST be explicit operator/variant state or derived through a common direction-aware lookup. +Every client MUST declare supported transports and authentication schemes. +The discovery result MUST include selected entries and rejected entries with a stable rejection code such as `consumer_not_allowed`, `transport_unsupported`, `auth_unsupported`, `credential_missing`, or `endpoint_unreachable`. + +Reconciliation MUST use the ownership name `infinito:`. +It MUST update or remove only entries carrying that marker and preserve all human-created client configuration. +Zero matching entries creates one, one updates it, and more than one MUST fail without guessing which duplicate to keep. + +Open WebUI has environment-backed configuration with persistence disabled. +The reconciler MUST reapply the complete desired connection and access grant after every process start, then verify it through the API. +Restarting only the Open WebUI container MUST converge to the same enabled connections and grants as a full deployment. + +## Flowise 3.1.4 Integration + +The current statement that Flowise lacks an instance-level registry is incorrect for the pinned version and MUST be removed from requirement 025 and the role README. +The deployment MUST use the authenticated `/api/v1/custom-mcp-servers` routes with a scoped API identity whose workspace permissions are limited to the required `tools:create`, `tools:view`, `tools:update`, and `tools:delete` operations. + +For each compatible server the reconciler MUST: + +1. List entries and select the exact deterministic name `infinito:`. +2. Create the entry when none exists or replace its complete desired state when exactly one exists. +3. Store authentication through Flowise's encrypted custom-header configuration rather than in flow JSON. +4. Call the entry's authorize route. +5. Verify `AUTHORIZED` status and the exact expected tool names and schema hash. +6. Delete a stale managed entry only when its name begins with `infinito:` and the provider is absent from the desired snapshot. + +The role MUST build its own Flowise image from the pinned npm package. The published `flowiseai/flowise` tags `3.1.3`, `3.1.4` and `latest` all ship the `flowise` package at version 3.1.2, which serves none of the `custom-mcp-servers`, `mcp-server` or `mcp-endpoint` routes; upstream's Dockerfile runs an unpinned `npm install -g flowise` whose layer the release CI reuses across builds. The deployed version therefore MUST come from `npm install -g flowise@`, and the served route set MUST be verified rather than inferred from the tag. + +Flowise 3.1.4 MUST register only Streamable HTTP providers, because its SSE fallback cannot complete a connection at this pin. +An SSE provider MUST be reported as incompatible or placed behind a pinned, protocol-correct bridge; it MUST NOT be claimed as registered. +Supporting SSE directly requires an explicit Flowise upgrade whose exact source and end-to-end tests prove the transport. + +The role MUST NOT solve internal connectivity by globally disabling SSRF protection for all flow authors. +If the exact pinned Flowise release cannot keep `HTTP_SECURITY_CHECK=true` for internal service DNS, the MCP workspace MUST be admin-only, egress MUST be restricted to a fixed-target MCP proxy, redirects MUST be disabled, DNS resolution MUST be revalidated at connection time, and network policy MUST prevent access to loopback, link-local metadata, unrelated application networks, and the container control plane. + +A versioned managed chatflow or agentflow fixture MUST be created through a supported API, tagged with an Infinito ownership marker, and updated idempotently without overwriting human flows. +It MUST reference registry connections or encrypted Flowise credentials, never plaintext bearer values in `flowData`. +The end-to-end test MUST execute a deterministic MCP tool and assert its result; listing a connection or rejecting an anonymous chatflow request is insufficient. + +## n8n 1.100.1 Integration + +`web-app-n8n` MUST be added as `direction: both` for the exact pinned 1.100.1 behavior: an SSE client and a Streamable HTTP server (`transport: streamable_http`, MCP Server Trigger typeVersion 2). +The deployment MUST use the public credential and workflow APIs through a least-scope API key persisted by the normal token store. + +As a client, each managed MCP Client Tool node MUST use Bearer or Header authentication and an explicit include list. +The upstream `include: all` behavior MUST NOT be used for deployment-managed workflows. + +As a server, each managed MCP Server Trigger workflow MUST: + +- use a deterministic Infinito name and tag; +- require Bearer authentication rather than the upstream `none` option; +- connect only explicitly selected workflow tools with checked-in input schemas; +- be disabled until the operator enables that workflow adapter; +- publish its MCP endpoint only after activation and an authenticated MCP handshake; +- expose read-only operations first, with mutations in a separate opt-in variant and role. + +The implementation MUST NOT claim that the newer instance-wide n8n administration MCP server exists in 1.100.1. +Using that surface requires a separately reviewed, explicit n8n upgrade. + +## Upstream Paths Missing from Current Metadata + +The following roles have a concrete upstream MCP or MCP-client path that is absent from, or incorrectly represented by, current metadata. +`candidate` means the path deserves implementation work; it does not mean that the current deployed version is safe or compatible. + +| Role | Disposition | Required implementation or precise blocker | +|---|---|---| +| `svc-ai-litellm` | gateway candidate | Keep the current pin as inference-only. Select and pin an MCP-capable release only after source inspection proves per-server routes, exact tool allowlists, credential injection, and the chosen OAuth lifecycle. Use separate provider credentials and avoid a global administrator token. | +| `svc-ai-lmstudio` | client candidate | Replace the unversioned preview image with an explicit MCP-capable headless version, render only deployment-curated servers, disable arbitrary per-request URLs, and test tool allowlists. Otherwise classify `version_unverified`. | +| `svc-db-elasticsearch` | blocked direct path | The maintained native path requires Kibana Agent Builder, suitable index/application privileges, and licensing; the older sidecar is deprecated. Record `missing_kibana_and_licence` until those dependencies are explicit. | +| `svc-db-mariadb` | isolated-sidecar candidate | Never attach a global MCP server to the shared engine or root credential. Instantiate one sidecar per consuming application with a database-scoped read-only principal and only schema/SELECT/SHOW/DESCRIBE tools. Otherwise record `shared_engine_isolation`. | +| `svc-db-qdrant` | sidecar candidate | Pin the official Qdrant MCP server, require read-only mode, and provision one collection and key per application. No shared administrator key or all-collection visibility is allowed. | +| `svc-db-redis` | blocked direct path | The upstream server is stdio-oriented and broadly mutating. Keep `stdio_only_and_shared_cache` unless an isolated instance, prefix-scoped ACL principal, pinned bridge, and exact read-only tool list are supplied. Prefer using Redis as an internal agent-memory backend rather than a user-visible server. | +| `web-app-erpnext` | plugin candidate | Pin the experimental Frappe MCP component in a small managed app, expose a few named read tools, reject generic DocType/method/SQL execution, and use a restricted ERPNext API user or proven per-user OAuth. Verify against the exact Frappe v16 pin. | +| `web-app-matomo` | plugin candidate | Audit and pin the project-owned MCP plugin against the exact Matomo version. Expose reporting reads only and never share a superuser token. Leave blocked until endpoint, transport, auth, and tool scope are verified in source. | +| `web-app-n8n` | native client and server candidate | Implement the SSE client and bearer-protected Streamable HTTP Trigger workflow contract in this requirement. Do not use features introduced only in n8n 2.13 or later. | +| `web-app-penpot` | interactive blocker | The project-owned server requires an active browser tab and plugin connection and can execute powerful design-context operations. Record `interactive_browser_session`; only an experimental user-initiated integration with a pinned server and isolated session may proceed. | +| `web-app-shopware` | version-gated native candidate | Current Shopware 6.7.8.2 predates the experimental native server. Upgrade only to an explicit tested release containing `/api/_mcp`, provision a dedicated minimal-ACL integration, and allowlist search/read tools. Keep write, delete, cache, state-machine, and configuration tools disabled. | + +## Corrections to Existing MCP Metadata + +The 18 roles already containing an `mcp:` block require the following revalidation before they count as complete: + +| Role | Required correction or validation | +|---|---| +| `web-app-baserow` | Retain the native server only with a dedicated least-privilege identity, a verified read-only tool allowlist, per-consumer grants, and an actual client tool call. | +| `web-app-confluence` | Keep self-hosted deployment blocked while the verified Atlassian path is Cloud-only; an external connector must be explicit and must not be represented as the self-hosted role's endpoint. | +| `web-app-discourse` | Replace `hosted_only` with `stdio_only`. The audit of `discourse/discourse-mcp` at `v0.3.1` closed the sidecar path: ownership, licence, pinning and the read-only default all pass, but the HTTP transport serves one session per process, which upstream asserts itself in `src/test/transport.test.ts` at that tag. A shared multi-consumer endpoint cannot be built on it, and the deploy-time contract probe alone would leave the process in its `503` restart-required state. Enable nothing until upstream supports concurrent sessions. | +| `web-app-flowise` | Reconcile the 3.1.4 Streamable HTTP registry and a managed flow as defined above. Remove the global-security-relaxation-as-integration claim and replace the anonymous-only test with a deterministic tool call. | +| `web-app-gitea` | Verify the exact project-owned package, image pin, endpoint auth, dedicated service account, tool allowlist, and read-only behavior. | +| `web-app-gitlab` | Keep tier and exact self-managed endpoint availability as hard gates. Use a project/group-scoped token and exclude mutation tools until separately enabled. | +| `web-app-hermes` | Keep `direction: client` unless a pinned authenticated stdio-to-HTTP bridge is added. Document the server-side path as `server_stdio_only`; do not imply a deployable HTTP server. | +| `web-app-homeassistant` | Verify the exact native endpoint, transport, scopes, entity exposure, and service-call mutations. A long-lived administrator token is not acceptable. | +| `web-app-jenkins` | Pin the plugin and Jenkins compatibility, expose job/status/log reads first, and keep build/config/script actions outside the default tool list. | +| `web-app-jira` | Keep self-hosted deployment blocked while the verified Atlassian path is Cloud-only; any external connector requires its own credentials, URL, and data-boundary documentation. | +| `web-app-mattermost` | Replace administrator credentials with a dedicated bot/service identity and separate read/search tools from post/channel-management tools. | +| `web-app-moodle` | Pin a Moodle-compatible plugin, use an exact web-service function allowlist and restricted service user, and prove that unlisted functions cannot be invoked. | +| `web-app-nextcloud` | Pin the required apps, scope the application password/service account, constrain files and tools, and prove that the endpoint cannot escape that user's shares. | +| `web-app-odoo` | Replace `hosted_only` with `unreviewed_third_party`. The review ran and selected no module. Odoo SA publishes no server and the OCA organisation holds no MCP repository, so the field is third-party only. The leading candidate, `ivnvxd/mcp-server-odoo` at `v0.8.0`, fails on maintenance breadth (197 of 231 commits from one author), on access control that ships as a separate Odoo Apps store module outside any pinnable tag, and on a mutating default tool scope. Re-review if Odoo SA or the OCA publishes a server. | +| `web-app-openclaw` | Keep `direction: client` unless a pinned authenticated bridge proves server behavior. Do not persist raw MCP bearers in JSON; require a supported environment/file secret reference or retain a precise blocker. | +| `web-app-openproject` | Preserve the Community Edition licensing blocker. A future Enterprise variant must explicitly supply the edition/license and use a restricted OAuth application. | +| `web-app-openwebui` | Retain per-server group grants but remove the hard-coded administrator token source, add application-scoped user roles, fix last-group revocation, and reconcile after restart. | +| `web-app-wordpress` | Replace `hosted_only`. Pin the official WordPress MCP adapter, expose its HTTP endpoint, register only reviewed Abilities with permission callbacks, and authenticate as a real restricted user through Application Password or proven OAuth. | + +## Curated Adapter Candidates + +No role in this section has been proven to possess a safe native MCP server at its currently pinned version. +Each is a candidate for an isolated adapter or a managed n8n workflow only after the exact pinned upstream API, authentication, pagination, and error semantics are inspected. +The adapter MUST start with three to five named read tools, not a generated copy of the entire API. + +| Family | Roles | Initial permitted surface | Mandatory additional guard | +|---|---|---|---| +| Search and observability | `svc-db-typesense`, `web-app-checkmk`, `web-app-prometheus` | Collection search; host/service status; PromQL query, query range, labels, metadata, and targets | Per-application collection/index, explicit lookback and sample caps, no configuration or administration endpoint | +| Content and storage | `web-app-bookwyrm`, `web-app-funkwhale`, `web-app-jellyfin`, `web-app-joomla`, `web-app-mediawiki`, `web-app-minio`, `web-app-opencloud`, `web-app-peertube`, `web-app-seaweedfs`, `web-app-xwiki`, `web-svc-libretranslate` | Catalog/page/library search and get; S3 list/head/get; translate and detect | User or service identity restricted to the intended library/site/bucket/prefix; no edit/upload/delete by default | +| Business applications | `web-app-akaunting`, `web-app-decidim`, `web-app-espocrm`, `web-app-fider`, `web-app-kix`, `web-app-listmonk`, `web-app-magento`, `web-app-pretix`, `web-app-snipe-it`, `web-app-suitecrm`, `web-app-taiga`, `web-app-yourls`, `web-app-zammad` | Named list, search, and get tools for the application's primary records | Dedicated role with field/tenant restrictions; no generic CRUD, no arbitrary filter language, and no Adobe Commerce claim for Magento Open Source | +| Federated social and messaging | `web-app-bluesky`, `web-app-bridgy-fed`, `web-app-friendica`, `web-app-mailu`, `web-app-mastodon`, `web-app-matrix`, `web-app-mobilizon`, `web-app-pixelfed`, `web-app-postmarks`, `web-app-socialhome`, `web-svc-xmpp` | Search or read public/user-visible content and account state | Per-user token is required for private feeds, rooms, messages, or mail; a shared service account MUST NOT merge users' private data | +| High-side-effect operations | `web-app-bigbluebutton`, `web-app-jitsi`, `web-app-opentalk`, `web-app-pihole`, `web-app-semaphore` | Meeting/status/job/log reads only | Create/end meeting, DNS blocking changes, playbook/Terraform/shell execution, and configuration changes require a separate role, human confirmation, idempotency key, and audit event | + +The first implementation investigation for each candidate MUST use the following starter contract. +Tool names are proposed repository contracts, not claims that upstream already uses those names. +If the exact pinned version cannot implement the named contract through a stable authenticated API, the role MUST be changed to `blocked` with the observed reason rather than receiving a generic substitute. + +| Role | Proposed adapter | Initial tool contract | Identity and hard boundary | +|---|---|---|---| +| `svc-db-typesense` | `openapi_allowlist` | `typesense_search`, `typesense_get_document` | One search-only key and explicit collection list per application; no collection/schema/key administration | +| `web-app-akaunting` | `openapi_allowlist` | `akaunting_list_invoices`, `akaunting_get_invoice`, `akaunting_list_accounts` | Restricted company user/token; no payment, ledger, tax, user, or configuration mutation | +| `web-app-bigbluebutton` | `n8n_workflow` | `bbb_list_meetings`, `bbb_get_meeting`, `bbb_list_recordings` | Dedicated integration secret; no create, join-as-moderator, end, publish, or delete | +| `web-app-bluesky` | `n8n_workflow` | `bluesky_get_profile`, `bluesky_search_posts`, `bluesky_get_feed` | Per-user OAuth/app password for non-public data; no post, like, follow, moderation, or account mutation | +| `web-app-bookwyrm` | `openapi_allowlist` | `bookwyrm_search_books`, `bookwyrm_get_book`, `bookwyrm_get_public_shelf` | Public access or restricted user token; no shelf, review, follow, or federation mutation | +| `web-app-bridgy-fed` | `resource_readonly` | `bridgy_get_actor`, `bridgy_get_public_activity`, `bridgy_get_bridge_status` | Public data only; block if the pinned service has no stable bounded read API | +| `web-app-checkmk` | `openapi_allowlist` | `checkmk_list_hosts`, `checkmk_get_host_status`, `checkmk_list_services` | Automation user with monitoring-read permissions; no activation, acknowledge, downtime, host, rule, or password mutation | +| `web-app-decidim` | `graphql_allowlist` or `openapi_allowlist` | `decidim_search_processes`, `decidim_get_proposal`, `decidim_list_meetings` | Public reads first; no proposal, vote, moderation, identity, or assembly mutation | +| `web-app-espocrm` | `openapi_allowlist` | `espocrm_search_accounts`, `espocrm_get_contact`, `espocrm_list_cases` | Restricted CRM API user with field and team visibility; no generic entity endpoint or write | +| `web-app-fider` | `openapi_allowlist` | `fider_search_suggestions`, `fider_get_suggestion`, `fider_list_tags` | Public/restricted read token; no vote, response, status, tag, user, or tenant mutation | +| `web-app-friendica` | `n8n_workflow` | `friendica_get_profile`, `friendica_search_public_posts`, `friendica_get_timeline` | Per-user token for timeline data; no posting, messaging, contact, moderation, or account mutation | +| `web-app-funkwhale` | `openapi_allowlist` | `funkwhale_search_library`, `funkwhale_get_track`, `funkwhale_get_album` | Public or library-scoped identity; no upload, favorite, playlist, federation, or administration mutation | +| `web-app-jellyfin` | `openapi_allowlist` | `jellyfin_search_library`, `jellyfin_get_item`, `jellyfin_get_playback_status` | Dedicated non-admin user restricted by library policy; no stream URL, delete, playback control, user, or server mutation | +| `web-app-jitsi` | `n8n_workflow` | `jitsi_get_conference_status`, `jitsi_list_active_conferences` | Proceed only if the exact deployment exposes a stable authenticated status API; no room creation, moderation, recording, or token minting | +| `web-app-joomla` | `openapi_allowlist` | `joomla_search_content`, `joomla_get_article`, `joomla_list_categories` | Read-only API user; no article, extension, template, configuration, or user mutation | +| `web-app-kix` | `openapi_allowlist` | `kix_search_tickets`, `kix_get_ticket`, `kix_list_organizations` | Agent identity restricted to intended queues/organizations; no ticket, asset, user, or configuration mutation | +| `web-app-listmonk` | `openapi_allowlist` | `listmonk_list_campaigns`, `listmonk_get_campaign`, `listmonk_get_stats` | Reporting-only service identity; no subscriber export, message send, campaign start, template, or list mutation | +| `web-app-magento` | `graphql_allowlist` | `magento_search_products`, `magento_get_product`, `magento_get_category` | Storefront persisted queries only; do not treat Adobe Commerce preview MCP as available in Magento Open Source | +| `web-app-mailu` | `openapi_allowlist` | `mailu_get_domain_status`, `mailu_get_queue_summary`, `mailu_get_service_health` | Separate read-only administration principal if upstream supports one; no mailbox content, password, alias, domain, or queue mutation | +| `web-app-mastodon` | `openapi_allowlist` | `mastodon_get_profile`, `mastodon_search_public`, `mastodon_get_timeline` | Per-user OAuth for non-public timelines; no status, follow, favorite, direct-message, moderation, or account mutation | +| `web-app-matrix` | `n8n_workflow` | `matrix_list_rooms`, `matrix_search_messages`, `matrix_get_room_state` | Per-user access token and room membership; no cross-user service token, send, invite, kick, ban, power-level, or encryption-key action | +| `web-app-mediawiki` | `openapi_allowlist` | `mediawiki_search_pages`, `mediawiki_get_page`, `mediawiki_get_revision` | Anonymous/public or restricted bot read identity; no edit, upload, delete, block, rights, or configuration action | +| `web-app-minio` | `s3_prefix` | `minio_list_objects`, `minio_head_object`, `minio_get_object` | Dedicated read-only policy for declared buckets and prefixes; never root credentials, write, delete, policy, lifecycle, or admin APIs | +| `web-app-mobilizon` | `graphql_allowlist` | `mobilizon_search_events`, `mobilizon_get_event`, `mobilizon_list_groups` | Persisted public queries first; per-user token for private events; no create, join, invite, moderation, or federation mutation | +| `web-app-opencloud` | `n8n_workflow` | `opencloud_search_files`, `opencloud_get_metadata`, `opencloud_list_shared_files` | Restricted user/service identity and selected spaces; no unrestricted download URL, upload, share, permission, or user mutation | +| `web-app-opentalk` | `n8n_workflow` | `opentalk_list_rooms`, `opentalk_get_room`, `opentalk_get_recording_status` | Restricted API identity; no meeting start/end, invite, recording content, moderation, or tenant mutation | +| `web-app-peertube` | `openapi_allowlist` | `peertube_search_videos`, `peertube_get_video`, `peertube_get_channel` | Public reads or restricted account; no upload, comment, follow, federation, moderation, or administration mutation | +| `web-app-pihole` | `openapi_allowlist` | `pihole_get_status`, `pihole_get_query_summary`, `pihole_get_top_domains` | Reporting-only token if the exact API can enforce it; no query-log detail by default, blocking toggle, list, DNS, DHCP, or configuration mutation | +| `web-app-pixelfed` | `openapi_allowlist` | `pixelfed_get_profile`, `pixelfed_search_public`, `pixelfed_get_timeline` | Per-user OAuth for non-public data; no post, message, follow, moderation, or account mutation | +| `web-app-postmarks` | `resource_readonly` | `postmarks_search_public_bookmarks`, `postmarks_get_public_bookmark`, `postmarks_get_public_feed` | Public collection only; the single owner secret MUST NOT be exposed to a shared client | +| `web-app-pretix` | `openapi_allowlist` | `pretix_list_events`, `pretix_get_event`, `pretix_get_order_summary` | Organizer-scoped read token; redact attendee/payment data; no order, check-in, voucher, refund, payout, or event mutation | +| `web-app-prometheus` | `prometheus_readonly` | `prometheus_query`, `prometheus_query_range`, `prometheus_get_targets` | Fixed Prometheus origin, explicit lookback/sample/time caps; no admin, reload, snapshot, delete-series, or arbitrary URL proxy | +| `web-app-seaweedfs` | `s3_prefix` | `seaweedfs_list_objects`, `seaweedfs_head_object`, `seaweedfs_get_object` | Dedicated read-only S3 identity and declared bucket/prefix; no filer traversal outside the prefix, write, delete, replication, or admin action | +| `web-app-semaphore` | `openapi_allowlist` | `semaphore_list_projects`, `semaphore_get_task_status`, `semaphore_get_task_log` | Read-only project identity; no task start, playbook, Terraform, shell, repository, key, inventory, environment, or user mutation | +| `web-app-snipe-it` | `openapi_allowlist` | `snipeit_search_assets`, `snipeit_get_asset`, `snipeit_get_license_summary` | Read-only token with field restrictions; no checkout/checkin, asset, license, accessory, user, or settings mutation | +| `web-app-socialhome` | `resource_readonly` or `n8n_workflow` | `socialhome_get_profile`, `socialhome_search_public_content`, `socialhome_get_public_stream` | Public reads unless a proven per-user API exists; no content, follow, federation, moderation, or account mutation | +| `web-app-suitecrm` | `openapi_allowlist` | `suitecrm_search_accounts`, `suitecrm_get_contact`, `suitecrm_list_cases` | Restricted CRM API user and allowed modules/fields; no generic module CRUD, export, workflow, user, or configuration action | +| `web-app-taiga` | `openapi_allowlist` | `taiga_list_projects`, `taiga_get_issue`, `taiga_get_user_story` | Project-scoped read identity; no issue/story, sprint, membership, webhook, or project mutation | +| `web-app-xwiki` | `openapi_allowlist` | `xwiki_search_pages`, `xwiki_get_page`, `xwiki_get_attachment_metadata` | Read-only user restricted to named wikis/spaces; no page, attachment, script, rights, extension, or user mutation | +| `web-app-yourls` | `openapi_allowlist` | `yourls_expand_url`, `yourls_get_link_stats`, `yourls_search_links` | Read-only API identity if enforceable; never disclose the global signature token or enable shorten, edit, or delete by default | +| `web-app-zammad` | `openapi_allowlist` | `zammad_search_tickets`, `zammad_get_ticket`, `zammad_list_organizations` | Agent token restricted by Zammad groups; redact sensitive articles; no ticket, article, user, role, or configuration mutation | +| `web-svc-libretranslate` | `openapi_allowlist` | `libretranslate_detect`, `libretranslate_translate`, `libretranslate_list_languages` | Dedicated API key, strict text/request/response limits, and no arbitrary URL/file fetch | +| `web-svc-xmpp` | `n8n_workflow` | `xmpp_list_rooms`, `xmpp_get_room_state`, `xmpp_search_archive` | Per-user or room-scoped service identity; no unrestricted archive, send, invite, kick, ban, role, or server administration action | + +`web-svc-collabora` and `web-svc-onlyoffice` MUST be reached through the owning document application's MCP boundary, such as Nextcloud or OpenCloud, rather than receiving a second independent service-account tool surface. + +## Exhaustive Application-ID Audit + +The following lists are the complete repository snapshot used to construct this requirement. +Implementation MUST replace the snapshot check with a test that derives the current set dynamically; it MUST NOT hard-code the number 172. + +The section titles below are the classification vocabulary itself, and each role that ships a `meta/mcp.yml` is filed under the value that file declares. [test_mcp_audit_classification.py](../../tests/lint/repository/documentation/test_mcp_audit_classification.py) holds the two apart from drifting: it was written first and immediately named twenty-four roles whose audit entry contradicted their own metadata, nine of them shipping an adapter while the audit still called them untried candidates. + +### native_server (1) + +`web-app-homeassistant`. + +### native_client (4) + +`web-app-flowise`, `web-app-hermes`, `web-app-openclaw`, `web-app-openwebui`. + +### native_both (1) + +`web-app-n8n`. + +### plugin_server (2) + +`web-app-moodle`, `web-app-wordpress`. + +### adapter_server (16) + +`svc-db-qdrant`, `web-app-baserow`, `web-app-checkmk`, `web-app-fider`, `web-app-gitea`, `web-app-gitlab`, `web-app-jellyfin`, `web-app-jenkins`, `web-app-listmonk`, `web-app-mattermost`, `web-app-nextcloud`, `web-app-pretix`, `web-app-prometheus`, `web-app-snipe-it`, `web-app-zammad`, `web-svc-libretranslate`. + +### blocked (11) + +An upstream path exists or is claimed, and something concrete stops it here. Each row names what, using the reason vocabulary above, so "blocked" never reads as "nobody looked". + +`svc-ai-litellm`, `svc-ai-lmstudio`, `svc-db-elasticsearch`, `svc-db-mariadb`, `svc-db-redis`, `web-app-discourse`, `web-app-erpnext`, `web-app-matomo`, `web-app-odoo`, `web-app-penpot`, `web-app-shopware`. + +| role | reason | blocker | +| --- | --- | --- | +| `svc-ai-litellm` | `version_unverified` | The pinned release is inference-only; an MCP-capable one may be selected only after source inspection proves per-server routes, exact tool allowlists and the credential lifecycle. | +| `svc-ai-lmstudio` | `version_unverified` | The image is an unversioned preview; an explicit MCP-capable headless version has to replace it before a surface can be curated. | +| `svc-db-elasticsearch` | `missing_dependency` | The maintained native path needs Kibana Agent Builder with its index privileges and licence; the older sidecar is deprecated. | +| `svc-db-mariadb` | `shared_engine_isolation` | A global MCP server would attach to the shared engine; the alternative is one sidecar per consuming application with a database-scoped read-only principal. | +| `svc-db-redis` | `stdio_only` | The upstream server is stdio-oriented and broadly mutating over a cache several applications share. | +| `web-app-discourse` | `stdio_only` | The project-owned server passes ownership, licence, pinning and read-only default, but its HTTP transport serves one session per process, which upstream asserts in `src/test/transport.test.ts` at `v0.3.1`; the deploy probe alone would leave it restart-required. | +| `web-app-erpnext` | `version_unverified` | The Frappe MCP component is experimental and unverified against the pinned Frappe v16. | +| `web-app-matomo` | `unreviewed_third_party` | The project-owned plugin is unaudited: endpoint, transport, auth and tool scope are unverified in source. | +| `web-app-odoo` | `unreviewed_third_party` | Neither Odoo SA nor the OCA publishes a server; the leading third party carries 197 of 231 commits from one author, keeps its access control in a separate Odoo Apps store module outside any pinnable tag, and defaults to a mutating tool scope. | +| `web-app-penpot` | `interactive_browser_session` | The server needs an active browser tab and plugin connection, and can execute powerful design-context operations. | +| `web-app-shopware` | `version_unverified` | The pinned 6.7.8.2 predates the experimental native `/api/_mcp` server. | + +### adapter_candidate (38) + +An adapter could reach these, and none has been curated yet. The five that used to sit under "current MCP metadata requiring revalidation" are here because that revalidation found no shipped surface to revalidate. + +`svc-db-typesense`, `web-app-akaunting`, `web-app-bigbluebutton`, `web-app-bluesky`, `web-app-bookwyrm`, `web-app-bridgy-fed`, `web-app-confluence`, `web-app-decidim`, `web-app-espocrm`, `web-app-friendica`, `web-app-funkwhale`, `web-app-jira`, `web-app-jitsi`, `web-app-joomla`, `web-app-kix`, `web-app-magento`, `web-app-mailu`, `web-app-mastodon`, `web-app-matrix`, `web-app-mediawiki`, `web-app-minio`, `web-app-mobilizon`, `web-app-opencloud`, `web-app-openproject`, `web-app-opentalk`, `web-app-peertube`, `web-app-pihole`, `web-app-pixelfed`, `web-app-postmarks`, `web-app-seaweedfs`, `web-app-semaphore`, `web-app-socialhome`, `web-app-stalwart`, `web-app-suitecrm`, `web-app-taiga`, `web-app-xwiki`, `web-app-yourls`, `web-svc-xmpp`. + +### enabler (2) + +`svc-ai-mcp-adapter`, `web-app-keycloak`. + +`svc-ai-mcp-adapter` carries no MCP surface of its own. It is the adapter runtime a provider role instantiates, so its disposition is `enabler` and it MUST NOT appear in discovery as a provider or a consumer. + +### subordinate (2) + +`web-svc-collabora`, `web-svc-onlyoffice`. + +### no_surface (97) + +These roles remain out of shared MCP discovery. +A future exception requires a new requirement with a fixed operation list, dedicated identity, isolation boundary, human approval for mutations, and audit trail. + +**`host_execution_boundary` (39):** `desk-bluray-player`, `desk-chromium`, `desk-copyq`, `desk-docker`, `desk-dotlinker`, `desk-firefox`, `desk-git`, `desk-gnome`, `desk-gnome-caffeine`, `desk-gnome-extensions`, `desk-gnome-terminal`, `desk-gnucash`, `desk-jrnl`, `desk-keepassxc`, `desk-libreoffice`, `desk-micro`, `desk-neovim`, `desk-nextcloud`, `desk-obs`, `desk-qbittorrent`, `desk-retroarch`, `desk-spotify`, `desk-ssh`, `desk-torbrowser`, `desk-virtualbox`, `desk-zoom`, `dev-arduino`, `dev-core`, `dev-java`, `dev-locales`, `dev-make`, `dev-nix`, `dev-nodejs`, `dev-python`, `drv-epson-multiprinter`, `drv-intel`, `drv-lid-switch`, `drv-non-free`, `gen-hunspell`. +These roles operate a workstation, developer toolchain, device, or host package; bridging them would amount to shared shell, filesystem, browser-session, device, or host execution without an application-specific remote identity. + +**`privileged_control_plane` (25):** `svc-bkp-local-2-device`, `svc-bkp-nfs-2-local`, `svc-bkp-remote-2-local`, `svc-bkp-secrets-2-local`, `svc-bkp-volume-2-local`, `svc-dns-unbound`, `svc-net-firewall`, `svc-net-tor`, `svc-net-tor-smtp`, `svc-net-wireguard-core`, `svc-net-wireguard-firewalled`, `svc-net-wireguard-plain`, `svc-opt-keyboard-color`, `svc-opt-ssd-hdd`, `svc-opt-swapfile`, `svc-prx-openresty`, `svc-registry-cache`, `svc-registry-docker`, `svc-runner`, `svc-storage-nfs-client`, `svc-storage-nfs-server`, `svc-swarm-manager`, `svc-swarm-node`, `svc-virt-kata`, `update`. +These roles can recover secrets, alter routing or host state, run code, change deployment state, or reach storage/control-plane sockets; they require a separate audited operations gateway and human approval rather than general-purpose application MCP. + +**`shared_engine_isolation` (4):** `svc-db-memcached`, `svc-db-openldap`, `svc-db-postgres`, `svc-db-rabbitmq`. +A generic endpoint would bypass application and tenant authorization on a shared engine. +Any future exception requires a provider-application-specific account, namespace/database/schema/queue restriction, fixed named operations, and no engine administrator credential. + +**`administrative_surface` (5):** `web-app-fusiondirectory`, `web-app-lam`, `web-app-pgadmin`, `web-app-phpldapadmin`, `web-app-phpmyadmin`. +These UIs expose identity or database administration rather than a bounded application-domain API and MUST NOT be represented by a shared service-account tool surface. + +**`duplicate_owner` (1):** `web-app-litellm`. +This role is only the UI of the separately classified LiteLLM service role, which owns any future MCP gateway contract. + +**`no_remote_surface` (24):** `svc-ai-ollama`, `svc-ai-robot`, `web-app-chess`, `web-app-dashboard`, `web-app-fediwall`, `web-app-hugo`, `web-app-littlejs`, `web-app-mig`, `web-app-mini-qr`, `web-app-navigator`, `web-app-roulette-wheel`, `web-app-sphinx`, `web-opt-rdr-domains`, `web-opt-rdr-www`, `web-svc-asset`, `web-svc-cdn`, `web-svc-coturn`, `web-svc-css`, `web-svc-file`, `web-svc-html`, `web-svc-legal`, `web-svc-logout`, `web-svc-mirror`, `web-svc-simpleicons`. +These roles have no independently useful authenticated remote action contract at the pinned implementation. +Static published content MAY later be consumed through one owning application's bounded `resource_readonly` adapter, but a new MCP sidecar that merely reimplements a static site's behavior does not count as integration. +Model tool calling in Ollama does not by itself make Ollama an MCP client or server. + +## Tool and Adapter Safety Contract + +Every adapter MUST enforce request size, response size, timeout, concurrency, pagination, result-row, and stream-duration limits with explicit values in role metadata. +It MUST log provider `application_id`, consumer `application_id`, tool name, credential subject, result status, duration, and correlation identifier without logging credentials or payload bodies. + +Tool discovery MUST be allowlisted by exact name and JSON schema hash. +An unexpected added, removed, or changed upstream tool MUST fail closed until the checked-in contract is reviewed. +The policy gateway MUST enforce the same allowlist on `tools/call`; filtering only `tools/list` is insufficient. + +Resources, prompts, sampling, elicitation, roots, and any protocol capability added by an upstream MCP release MUST be independently classified. +The absence of a dangerous tool list does not authorize an unreviewed non-tool MCP capability. + +Mutations MUST be classified as reversible, irreversible, external-communication, financial, identity/permission, code-execution, or infrastructure-control. +Any enabled mutation requires a separate opt-in variant, a distinct RBAC role where practical, an idempotency strategy, a human confirmation boundary, and a tested audit event. +Infrastructure control, arbitrary code execution, unrestricted filesystem access, identity administration, and raw database mutation remain forbidden for shared clients. + +Sidecars and adapters MUST use an immutable version and digest, documented provenance and license, a non-root user, read-only root filesystem, dropped Linux capabilities, no host or control-plane socket, explicit CPU/memory/PID limits, a provider-only network, and no unrelated outbound network access. + +## Acceptance Criteria + +### Audit and metadata + +- [x] A test discovers every role with a literal `application_id` and proves that it appears exactly once as `native_server`, `native_client`, `native_both`, `plugin_server`, `sidecar_server`, `adapter_server`, `adapter_candidate`, `blocked`, `enabler`, `subordinate`, or `no_surface`; absence is not an audit result. +- [x] The operational metadata remains role-local, while the generated audit report includes deployed version, authoritative source, transport, authentication, real credential subject, read/write scope, tool allowlist, proposed implementation, selected consumers, and blocker. [audit.md](../contributing/design/role/services/mcp/audit.md) is rendered by [cli/build/docs/mcp_audit](../../cli/build/docs/mcp_audit/__main__.py) through `make mcp-audit`, which only reads `meta/mcp.yml` and never writes back into a role; [test_mcp_audit_report.py](../../tests/lint/repository/documentation/test_mcp_audit_report.py) imports the generator and fails when the committed report differs from a fresh run. +- [x] Lint accepts `implementation: adapter` only with one allowed adapter type and all mandatory immutable-source, credential, endpoint, limit, and tool-contract fields. [test_mcp_schema.py](../../tests/lint/ansible/services/test_mcp_schema.py) rejects a type outside `MCP_ADAPTER_TYPES`, a `specification_path` that is not a checked-in file under `roles//files/`, a missing `specification_sha256`, and a server-capable block missing `credential`, `endpoint` or `limits` โ€” each with its required sub-keys. +- [x] Lint rejects every generic URL/spec/query/SQL/filesystem/shell/socket/unrestricted-bucket surface described in this requirement. +- [x] WordPress, Discourse, Odoo, Hermes, OpenClaw, Flowise, and the 11 missing upstream-path roles are reclassified exactly as required above before their old status is considered complete. + +### Credentials and authorization + +- [x] `mcp_servers` resolves the declared credential owner and source rather than `users.administrator.tokens`, and deployment fails for missing, empty, shared, or overprivileged credentials. +- [x] `auth_subject` is validated against the identity actually provisioned in the provider and is not documentation-only. +- [x] `auth: oidc` is rejected by static client renderers until a real acquisition, refresh, audience, expiry, and revocation flow is implemented and tested. +- [x] Open WebUI grants each server to only `roles//mcp`; one-of-many, no-membership, wrong-app, removal, and last-group removal tests pass. +- [x] The declarative user configuration can assign `mcp` to one application without assigning it to any other application. +- [x] Flowise, Hermes, OpenClaw, and n8n prove their per-server user boundary or are restricted to an admin-only workspace/instance or isolated trust domain. All four take the restriction branch: their oauth2 gate admits only the application's own `administrator` and `mcp` groups, held there by [test_mcp_client_gate_scoped.py](../../tests/lint/ansible/services/test_mcp_client_gate_scoped.py), which derives the client set from `meta/mcp.yml` rather than a list. `web-app-n8n` shipped with no `allowed_groups` at all while declaring an `mcp` role nothing consulted; that gate is now closed. +- [x] Rotation and disablement tests prove that the old credential is rejected, the new credential works, and no stale client entry retains access. The first two run on every deploy: the shared contract probe opens the surface with the declared credential and fails unless a deterministic read succeeds, and separately proves a wrong credential is refused a session. Every one of the eight enabled serving surfaces includes that probe, so neither half is asserted for some roles and assumed for the rest. The third is unit-tested per client, and only three clients can hold a stale entry at all, because Hermes and OpenClaw keep no server-side registration: their configuration is rendered from the run's own discovery snapshot, so there is nothing left behind to go stale. Flowise overwrites the entry's `authConfig` and Open WebUI the registered connection, both already covered; n8n was the gap and now proves that a rotated bearer replaces the credential rather than being compared against one n8n never hands back, on the server side and for every client credential. Auditing the third half turned up a real leak on the way. Nextcloud mints an app password under a fixed managed name and never revoked the previous one, so every run that found the stored password rejected added another valid token to the account while the old ones kept full access. The mint is now preceded by a listing and the revocation of every token carrying that managed name. +- [ ] Credentials and secret URL components are absent from logs, generated non-secret configuration, API responses, task output, Playwright traces, and exception text. **Three of the six surfaces are held statically:** logs and task output by [test_mcp_secrets_are_masked.py](../../tests/lint/ansible/services/test_mcp_secrets_are_masked.py), which requires `no_log` or `mask_values` on any MCP task that both handles a secret and prints; Playwright traces by [test_mcp_secret_not_in_playwright.py](../../tests/lint/ansible/services/test_mcp_secret_not_in_playwright.py), which forbids a `playwright.env.j2` from rendering `mcp_credential`, a `credentials.mcp_*` secret or a `key_credential` URL component. Generated non-secret configuration needs a secret/non-secret classification of rendered files that does not exist yet; API responses and exception text are runtime observations for the deploy phase. + +### Discovery and lifecycle + +- [x] Providers declare explicit allowed consumers, clients declare supported transports/auth schemes, and discovery computes the intersection without naming peer roles in `group_names` expressions. +- [x] Every rejected discovery entry has a stable, tested reason; missing credentials, transport mismatch, and unreachable endpoints fail reconciliation when the consumer was explicitly authorized. +- [x] One post-application reconciliation stage converges every selected client after provider provisioning, rotation, enable/disable changes, and standalone client restart. `sys-svc-mcp-reconcile` runs once in `tasks/stages/02_server.yml` after every server role, stats each MCP client's instance directory so it converges only the clients this deployment carries, and raises `MCP_RECONCILE_STRICT` so a provider whose credential never resolved fails rather than being skipped. The restart trigger needs no stage: Open WebUI's `TOOL_SERVER_CONNECTIONS` carries the group grant in the env, and with `ENABLE_PERSISTENT_CONFIG=false` the env is authoritative on every start. +- [x] Reconciliation owns only deterministically named resources, fails on duplicates, and preserves human-created resources. The ownership marker is per client, because the name is not always free: Flowise registry entries are `infinito:`, Open WebUI groups carry the RBAC group path Keycloak also issues, and n8n uses its configured workflow name. +- [ ] Compose and Swarm tests prove endpoint DNS/routing from each client and prove an adapter cannot reach unrelated application networks. **The isolation half is covered by the CLI test:** `run.sh` calls `isolation.sh` whenever `mcp.implementation` is `adapter`, and that reads from the engine which networks the sidecar is attached to and fails unless they are the role's own network plus the declared upstream one. `test_mcp_provider_cli_test.py` holds the test, so every enabled provider reaches it โ€” a provider without a CLI test would also skip the isolation proof. What remains is the routing half: DNS resolution of each endpoint from each client, in both deploy modes, which only a running cluster can show. +- [x] Open WebUI with `ENABLE_PERSISTENT_CONFIG=false` restores the exact desired connection state and group grants after a process restart without a full reinstall. + +### Flowise and n8n + +- [x] Flowise 3.1.4 is reconciled through `/api/v1/custom-mcp-servers`, registers only Streamable HTTP providers, stores headers encrypted, authorizes each entry, and verifies exact tool names and schemas. The reconciler refuses to register a provider whose declared transport is not the one the role declares, stores the bearer as a `CUSTOM_HEADERS` `authConfig` Flowise encrypts at rest, and authorizes every entry. Name verification was vacuous until now, because the desired entry hardcoded an empty tool list; it compares against the provider's declared allowlist. The schema half is enforced where the schema contract lives: the adapter serving those tools pins `tools.schema_sha256` and calls `policy.assert_no_drift` at startup, so a changed schema fails the provider rather than being re-checked from a client that cannot see the contract file. +- [x] Flowise Streamable HTTP support remains blocked or bridged until a pinned source-audited release passes an end-to-end tool call. The source audit of `flowise@3.1.4` settles it: `MCPToolkit.initialize` connects a `StreamableHTTPClientTransport` first and falls back to `SSEClientTransport` only when that connection throws, so the `'sse'` literal the registry service passes selects "not stdio" rather than a transport. The role's own module docstring claimed the opposite, that only SSE providers could be registered, while `meta/mcp.yml` declared `streamable_http`; the docstring was the wrong half and is corrected. The end-to-end tool call is the managed Agentflow fixture, which the deploy executes and fails on. +- [x] Ordinary Flowise users cannot use MCP or another HTTP node to reach loopback, metadata endpoints, the container control plane, or unrelated internal services; globally disabling the SSRF check alone fails this criterion. `checkDenyList` resolves a hostname and tests every resolved address, and the built-in list denies all of RFC1918, so reaching any provider on a container network is impossible while the built-in list applies. Upstream's switch is not an off switch: with `HTTP_SECURITY_CHECK=false` the deny list becomes exactly `HTTP_DENY_LIST` instead of the built-in one merged with it. The role therefore sets the switch and supplies a list that still denies loopback, link-local, cloud metadata, multicast and reserved space, which is the "not alone" this criterion demands. Unrelated internal services are held out by network membership rather than by the list, the same boundary the adapter isolation probe asserts. Configuration alone proves nothing, so the deploy points a throwaway registry entry at loopback and at the metadata address and fails unless Flowise refuses both. +- [x] A deployment-managed Flowise fixture executes a deterministic MCP tool successfully and contains no plaintext MCP credential. The fixture is an Agentflow whose Tool node invokes one named tool with fixed arguments through `customMcpServerTool`, so the call is deterministic rather than left to a model, and the deploy runs it through `/api/v1/prediction` and fails on a non-200 answer or an error body. The node carries only the registry entry id: the bearer stays in Flowise's encrypted `authConfig`, which a unit test holds by asserting the serialised flow contains neither the token nor the word `Bearer`. The candidates are the three providers that admit Flowise, each with a read tool that takes no arguments; the first one registered is built and executed and stale fixtures from earlier runs are removed. +- [x] n8n 1.100.1 is declared as an SSE client and a Streamable HTTP server, and its managed credentials and workflows are idempotently provisioned through supported public APIs. The server moved from 1.95.3's SSE-only trigger because Open WebUI 0.11.0 ships only a Streamable HTTP client and answered the SSE route with a POST that n8n refused with 404. `meta/mcp.yml` declares `direction: both` and `transport: streamable_http` at `/mcp/infinito-mcp`; `files/python/provision/mcp.py` renders the server workflow and `files/python/provision/client.py` the agent workflow, both through `/api/v1/workflows`. Credentials go through `/rest` because the public API of that tag exposes only create and delete for them, which cannot converge an existing one. Two idempotence defects were fixed here: the run reported `CHANGED` forever, because the public-API key it minted was found again on the next run and counted as a change, and that key was left standing in n8n afterwards although nothing read it. It is now minted per run, revoked before the run ends, and no longer reported. +- [x] n8n client nodes use exact tool include lists; server triggers require Bearer auth, expose only connected checked-in tools, and remain disabled until operator opt-in. Each client node renders `include: selected` with the provider's own `mcp.tools.allowlist`, which the discovery snapshot now carries; the node's default is `all`, so an omitted list would hand the agent every tool an upstream happens to serve. The server trigger pins `authentication: bearerAuth` against a managed `httpBearerAuth` credential, and the surface ships `enabled: false`. "Only connected checked-in tools" is upstream's own mechanism: `getConnectedTools` in `@utils/helpers` collects exactly what reaches the trigger over an `ai_tool` connection, so the workflow's connection map is the allowlist. The workflow previously connected nothing at all, so the trigger served an empty tool set; it now carries one checked-in read tool, `infinito_health`, with an explicit input schema. +- [x] n8n tests cover creation, update, activation, authenticated tool listing and call, wrong/missing bearer rejection, rerun idempotence, and cleanup limited to managed resources. Creation, update, activation, rerun idempotence and the cleanup boundary are unit-tested in [test_mcp.py](../../tests/unit/python/roles/web-app-n8n/files/provision/test_mcp.py) and [test_client.py](../../tests/unit/python/roles/web-app-n8n/files/provision/test_client.py), including that a converged deployment reports `OK`, that a credential or workflow outside the managed names is never touched, and that a provider which vanished loses only its own credential. The authenticated half runs at deploy time through the shared contract probe, which opens an MCP session, lists tools against the declared allowlist, calls the read tool, and separately proves that an anonymous and a wrong-bearer probe are both refused a session. It cannot be a browser test: the bearer must not reach a Playwright environment file. + +### Provider and adapter behavior + +- [x] Each enabled native/plugin/sidecar provider passes an authenticated MCP handshake, exact tool-contract assertion, one deterministic read call, wrong-credential rejection, disabled-state rejection, and consumer-isolation test. Four of the six run on every deploy through the shared contract probe, which opens a session with the declared credential, compares the served tool names against the recorded allowlist, calls the deterministic read tool, and separately proves that an anonymous and a wrong-credential probe are each refused a session; every enabled serving surface includes that probe. Consumer isolation is held one layer earlier, where it is decidable: discovery rejects a consumer the provider does not list in `allowed_consumers` with a named reason, so an unadmitted client is never handed the credential in the first place. Disabled-state rejection was the real gap and did not exist in any form. Every role-local MCP spec gated itself on the service flag and skipped when the surface was off, which means a surface that kept serving after being switched off was indistinguishable from one that was never deployed. The gating helper had no inverse, so it gained one, and a shared transport-agnostic assertion now probes the endpoint with both a GET and a POST while the flag is false and fails on any answer that shows something still listening, a refused credential included. It is wired into all ten serving roles and the coverage lint requires it, which is how the tenth was found: the rule flagged the one role whose spec is not named like the others. +- [x] Each enabled adapter proves the exact upstream identity and permission boundary, fixed target, operation allowlist, request/response limits, timeout, pagination, schema drift behavior, and redacted audit event. The permission boundary is measured per deployment by the isolation probe, which runs inside the sidecar and compares its own addresses against the declared subnets, so a second attachment someone else added is caught by identity rather than by counting. The operation allowlist refuses an unnamed tool and a mutating one on `tools/call` itself, and now also an argument the tool's own schema does not describe. That schema had been published to clients and never checked, which made it a suggestion rather than a boundary: on the openapi path an argument the contract does not name is appended to the upstream request as a query parameter, so a client could add parameters the reviewed operation never granted, and a tool declaring no schema accepted anything. A tool that declares no inputs now takes none, a required input must be present, and the check runs after the size ceiling so a large payload is still refused for being large. No shipped contract regresses: the read tool every deploy probe calls is either schema-free and called bare or declares no required argument, which was measured across all fourteen contracts rather than assumed. pagination clamps the requested page and truncates the result list to the contracted ceilings; the schema hash is checked at startup and the process refuses to serve on drift; and the audit record is pinned by a test asserting its exact key set, because a record carrying the arguments or the body would be a second copy of what it guards. The limits were audited separately and two of seven turned out to be declared and never applied. Fixed target was the item with nothing behind it, and auditing it found a real hole: the adapter opened its upstream with `urlopen`, which follows redirects, and urllib copies the original request's headers onto the redirect target, so an upstream answering `302` with an off-host location would have handed the adapter's upstream credential to whoever it named. The opener now refuses a redirect outright, since the target is contracted and a redirect is a contract violation rather than a route. Four negative controls hold the rest of the property: a client argument naming another host, one attempting to escape its path segment, and an uncontracted argument all stay on the contracted origin, the last landing in the query string rather than the path. +- [x] Database-backed integrations use per-application views/collections/indexes and read-only principals; no test or configuration contains a shared engine administrator credential. One database-backed surface is enabled, Qdrant, and auditing it found the engine running with no authentication at all: its environment set the HTTP port and disabled telemetry and nothing else, so every container that reached its network held full read, write and delete access to every collection, and the surface's read-only promise rested entirely on the adapter's own contract naming only GET routes. Qdrant 1.19 offers what was needed: `read_only_api_key` forces authentication on every request and grants reads only. The engine now declares both keys, the adapter presents the read-only one through `api-key`, and the full key goes only to consumers that own data here, which is asserted by a unit test on the resolver because handing the read-only key out anywhere else would make it meaningless. A contract that named a write route is now refused by the engine rather than only by the adapter. Two limits stay, and neither is a credential problem: Qdrant has no per-consumer principals, only engine-wide keys, so "read-only principal" is as narrow as this engine goes without JWT RBAC; and `qdrant_list_collections` enumerates the whole engine, which is bounded today by there being one data owner but is not a per-application view. The path parameter of `qdrant_get_collection` is not a traversal risk: the adapter percent-encodes it with an empty safe set, so a `../` argument reaches Qdrant as a literal collection name. +- [x] S3 adapters are restricted to declared bucket prefixes and list/head/get; Prometheus adapters enforce lookback/sample limits; GraphQL and SQL adapters reject arbitrary input languages. **Three of the four categories do not exist yet:** only `openapi_allowlist` (10 roles) and `mcp_passthrough` (4) are in use, and `test_mcp_schema.py` already requires exact `scope` names before an `s3_prefix`, `graphql_allowlist` or `named_query` adapter could ship. The Prometheus clause was real and is now half-closed: `prometheus_query_range` accepts client-chosen `start`, `end` and `step`, and the container ran with no `--query.timeout` at all, so a query the adapter abandoned after 15s kept Prometheus busy for its 2-minute default. The role now passes `--query.timeout` derived from `mcp.limits.timeout_seconds`, so the two cannot drift. **The lookback half is now closed too, and the sample ceiling is closed at the layer that can carry it.** `policy.assert_range` bounds a range query's point count by the contract's own `result_items`: a tool whose schema declares `start`, `end` and `step` has `(end - start) / step + 1` checked against that ceiling and is refused with `range_too_wide` and the smallest step that would fit. Against the live Prometheus contract, a day at one-minute resolution asks for 1441 points against a ceiling of 100 and is refused naming an 873-second step. The point is not politeness: the adapter already truncated such a response to 100 rows, so the upstream was scanning a range whose result was thrown away, and the timeout bounded only how long it did so. Both boundary forms Prometheus accepts are understood, unix seconds and RFC 3339, and an unparseable one is refused rather than waved through, because a range that cannot be measured cannot be bounded. `--query.max-samples` deliberately stays unset: lowering it far enough to matter would also bound the platform's own dashboards, which share the instance, so the ceiling belongs on the adapter's requests rather than on everyone's. The rule is generic โ€” it keys on a tool declaring the three range arguments, not on a role name โ€” so a future range-shaped upstream inherits it. +- [x] Mutating variants test human confirmation, authorization, idempotency, audit, and rollback or explicit irreversibility warning separately from read-only variants. **No surface enables mutations, so the tests this asks for have nothing to run against.** Writing them would mean inventing a mutating variant to satisfy a checkbox, and the honest closure is the gate rather than the tests: `missing_proofs` in [test_mcp_mutating_tools_named.py](../../tests/lint/ansible/services/test_mcp_mutating_tools_named.py) fails any role that sets `tools.mutating_tools_enabled` without an `mcp.mutating_proofs` block naming an existing artifact for each of the five, so the day a mutating variant ships it cannot ship without them. Because every real surface keeps mutations off, the rule is exercised against three synthetic blocks โ€” no proofs, proofs naming a file that does not exist, and proofs naming one that does โ€” rather than trusted to be correct the first time somebody needs it. `mutating_proofs` is also a declared key of the schema, without which the guard would reject the very block it demands. +- [ ] Every client executes at least one deterministic real tool call. A server-list assertion, configuration render, connection authorize action, or anonymous API rejection alone does not satisfy end-to-end coverage. + +## Implementation Order + +1. Correct requirement 025's stale claims and add the exhaustive audit/lint status mechanism. +2. Remove the hard-coded administrator credential path, add provider-consumer authorization, add client capability filtering, and implement post-application reconciliation. +3. Make Open WebUI revocation and restart behavior correct before expanding its provider set. +4. Implement Flowise 3.1.4's Streamable HTTP registry and one deterministic read-only flow without disabling unrestricted SSRF protection. +5. Implement n8n 1.100.1 as an SSE client and one bearer-protected read-only Streamable HTTP workflow server. +6. Correct WordPress, then validate the existing native/plugin/sidecar roles one at a time. +7. Build the reusable adapter before any sidecar that depends on it. Source inspection of `discourse/discourse-mcp` and `qdrant/mcp-server-qdrant` shows both authenticate *to* their application and neither authenticates the MCP client calling them, so deploying either on its own would put an unauthenticated tool surface on the container network. Correcting Discourse and adding Qdrant therefore follows the adapter, not the other way round. +8. Add Qdrant with collection isolation and the high-value read adapters for Checkmk, Prometheus, LibreTranslate, Jellyfin, Pretix, Snipe-IT, Zammad, Listmonk, and Fider. +9. Evaluate Shopware upgrade, ERPNext plugin, Matomo plugin, LiteLLM gateway, and LM Studio client in focused requirements or PRs because each changes an upstream version or maturity boundary. +10. Add the remaining business, content, social, and operations adapters only after the shared contract and first high-value adapters pass Compose and Swarm tests. + +## Prerequisites + +Before implementation, the agent MUST read [AGENTS.md](../../AGENTS.md), the target role's `AGENTS.md` when present, [CONTRIBUTING.md](../../CONTRIBUTING.md), and the repository's agent and contributor guidance. +Any upstream capability MUST be verified against the exact image tag, source tag, or commit selected by the implementation; current documentation or a newer upstream release is not evidence for the deployed pin. diff --git a/docs/requirements/036-native-ai-gateway-integration.md b/docs/requirements/036-native-ai-gateway-integration.md new file mode 100644 index 0000000000..b7a3459ee4 --- /dev/null +++ b/docs/requirements/036-native-ai-gateway-integration.md @@ -0,0 +1,85 @@ +# 036 - Native AI Gateway Integration + +## User Story + +As an operator of a self-hosted deployment, I want every role whose application ships a native AI feature to reach the platform's own LiteLLM gateway instead of a third-party provider, so that prompts, documents and telemetry never leave the deployment and one credential rotation covers every application. + +## Context + +`svc-ai-litellm` already serves an OpenAI-compatible gateway, and `web-app-nextcloud` already binds its `integration_openai` app to that gateway through `tasks/addons/integration_openai.yml`, a `credentials.litellm_api_key` entry and a dedicated Playwright spec. That pattern is implemented once and is not required, described or verified for any other role. + +A sweep over all 85 application roles for provider references (`openai`, `ollama`, `llm`, `anthropic`, `aiprovider`) in `meta/`, `vars/` and `templates/` returns only `dashboard`, `flowise`, `hermes`, `litellm`, `matrix`, `minio`, `nextcloud`, `openclaw` and `openwebui`. Everything below the AI-native roles is therefore unwired today. + +Confirmed against upstream documentation, each accepting a custom OpenAI-compatible base URL: + +| Role | Native surface | Endpoint | +| --- | --- | --- | +| `web-app-nextcloud` | Assistant via `integration_openai` | service URL plus API key | +| `web-app-mattermost` | Agents plugin | "OpenAI Compatible" service with API URL; a non-empty key is mandatory even when the upstream ignores it | +| `web-app-moodle` | AI subsystem provider | core `aiprovider_openai`; each action carries its own `action__endpoint`, so the pinned 4.5 branch needs no third-party provider plugin (`aiprovider_openaicompatible` requires Moodle 5.0) | +| `web-app-discourse` | Discourse AI | custom LLM; the host must be listed in `DISCOURSE_ALLOWED_INTERNAL_HOSTS` | +| `web-app-zammad` | Smart Assist | settings `ai_provider` (boolean "a provider is configured") plus `ai_provider_config` (`provider: custom_open_ai`, `url`, `model`, optional `token`). Needs 7.1.2; `stable-6.5` declares neither setting. `Setting.set` runs `AI::Provider::CustomOpenAI.ping!`, so writing the config is itself a reachability proof | +| `web-app-matrix` | ChatGPT bridge | bridge configuration; see the credential defect below | +| `web-app-wordpress` | plugin-provided, no core surface | a connector plugin such as AI Engine exposes a custom OpenAI-compatible endpoint | +| `web-app-n8n` | AI Agent nodes | a stored `openAiApi` credential carries `url` plus `apiKey`. The built-in assistant is out of reach: 1.95.3 exposes only `N8N_AI_ASSISTANT_BASE_URL`, which expects n8n's own assistant service rather than an OpenAI-compatible endpoint, and no `N8N_INSTANCE_AI_MODEL_URL` exists in that release | +| `web-app-mediawiki` | `AIEditingAssistant` extension | provider `open-ai`; `$wgAIEditingAssistantActiveProviderConnection` carries `url`, `endpoint`, `model` and `secret`. Hard-requires `VisualEditorPlus`, which is not bundled | +| `web-app-xwiki` | AI LLM Application extension | the role installs the extension and points its OpenAI-compatible provider at the gateway in `tasks/addons/ai-llm.yml` | + +`web-app-matrix` is the one role that already ships an AI credential and points it at the vendor: `meta/secrets.yml` declares `chatgpt_bridge_openai_api_key` with the validation `^sk-[a-zA-Z0-9]{40,}$`. That pattern enforces OpenAI's own key format and therefore **rejects a LiteLLM virtual key by construction**, so the schema has to change before the bridge can reach the gateway at all. + +`web-app-wordpress` has no AI surface in core; the requirement applies to whichever connector plugin the role installs, and the role MUST pin one rather than leaving the choice to a site administrator. The pinned connector is `ai-engine`, whose `custom` engine type takes an OpenAI-compatible base URL and an API key per environment. + +`web-app-zammad` was pinned at 6.5.0, which ships no AI surface at all. The role is bumped to 7.1.2, the newest line whose contract is still the `ai_provider` / `ai_provider_config` setting pair; past 7.1.x the provider moves into an `AI::ProviderConnection` record and the contract changes. 7.1.2 accepts Elasticsearch `>= 7.8, < 10`, so the role's existing 8.13.4 pin stands. + +The three candidates that vendor documentation claimed were probed against running instances on 2026-08-27, and each is filed below on what the deployed artefact actually offers rather than on the claim: + +| Role | Measured at | Finding | Disposition | +| --- | --- | --- | --- | +| `web-app-baserow` | 2.3.3 | `settings.BASEROW_OPENAI_BASE_URL` reaches the OpenAI client at `backend/src/baserow/core/generative_ai/generative_ai_model_types.py:288`, but the only two surfaces that ever send a prompt live in `baserow_premium` and both open with `LicenseHandler.raise_if_user_doesnt_have_feature(PREMIUM, request.user, workspace)`: `AsyncGenerateAIFieldValuesView` and `GenerateFormulaWithAIView` (`premium/backend/src/baserow_premium/api/fields/views.py`). An unlicensed deployment configures the endpoint and can never reach it | excluded | +| `web-app-homeassistant` | 2026.7 | `openai_conversation/config_flow.py` contains no `base_url` (0 matches), so the OpenAI agent cannot be pointed anywhere but the vendor. The only configurable local path is the separate `ollama` integration, whose `config_flow.py` carries `CONF_URL` (7 matches) but speaks Ollama's native API rather than the gateway's OpenAI-compatible surface | excluded | +| `web-app-xwiki` | `lts-postgres-tomcat` | no AI or LLM extension is present in `data/extension/repository` on the pinned image, so there is no AI surface to point at the gateway until the XWiki AI LLM Application extension is installed by the role | confirmed, the role installs the extension in `tasks/addons/ai-llm.yml` | + +`web-app-baserow` is the one row measured against the pinned source rather than a running instance. Confirm it on the deployed stack with `POST /api/database/fields//generate-ai-field-values/` as the seeded superuser: an unlicensed instance answers HTTP 402. + +Excluded, with the reason recorded so the question is not reopened: + +| Role | Reason | +| --- | --- | +| `web-app-baserow` | the endpoint is configurable but both prompt-sending views are premium-licence gated; see the measurement above | +| `web-app-homeassistant` | the OpenAI agent takes no base URL and the `ollama` integration speaks Ollama's native API; see the measurement above | +| `web-app-gitlab` | Duo is bound to the vendor service and exposes no self-hosted endpoint | +| `web-app-odoo` | version 19 hardcodes a vendor model for AI server actions; a configurable endpoint needs third-party modules | +| `web-app-erpnext` | no AI surface in the core; every option is a separately installed app | +| `web-app-jira`, `web-app-confluence` | Atlassian Intelligence is vendor-hosted | +| `web-app-magento`, `web-app-shopware` | the shipped assistants are vendor services; only third-party modules expose an endpoint | +| `web-app-openproject` | no AI surface found in the product | +| `web-app-espocrm` | measured at tag 10.0.4: zero tree paths match `AI`/`Intelligence`/`OpenAI`/`LLM`/`GPT`/`prompt` while 116 match `Mail` on the same payload, so the search was live. The AI features live only in the closed-source Intelligence extension, which needs a purchased licence and is published in no `espocrm` repository. A version bump does not help: upstream documents the extension as requiring 10.0.3 or greater, so newer cores host it rather than absorb it | +| `web-app-peertube` | measured at tag v8.2.4 across three independent surfaces: `config/production.yaml.example` `video_transcription:` carries only `enabled`/`engine`/`engine_path`/`model`/`model_path`/`timeout`/`remote_runners.enabled`; `support/docker/production/config/custom-environment-variables.yaml` exposes exactly the seven matching `PEERTUBE_VIDEO_TRANSCRIPTION_*` variables, none of them a URL or a key; `server/core/initializers/config.ts` agrees. Transcription is local Whisper, not an OpenAI-compatible endpoint | +| infrastructure and static roles | `checkmk`, `prometheus`, `matomo`, `seaweedfs`, `minio`, `mailu`, `keycloak`, `lam`, `fusiondirectory`, `phpldapadmin`, `phpmyadmin`, `pgadmin`, `pihole`, `semaphore`, `jenkins`, `gitea`, `hugo`, `sphinx`, `yourls`, `mini-qr`, `littlejs`, `chess`, `roulette-wheel`, `navigator`, `mig`, `dashboard`, `fediwall`, `postmarks` carry no AI surface | +| fediverse and media roles | `mastodon`, `pixelfed`, `friendica`, `socialhome`, `bookwyrm`, `mobilizon`, `funkwhale`, `bluesky`, `bridgy-fed`, `jellyfin` ship no configurable AI surface | +| remaining application roles | `akaunting`, `decidim`, `fider`, `listmonk`, `pretix`, `snipe-it`, `taiga`, `penpot`, `joomla`, `suitecrm`, `kix`, `opencloud`, `opentalk`, `jitsi`, `bigbluebutton`, `erpnext` show no first-party AI surface with a configurable endpoint; revisit when upstream adds one | + +## Acceptance Criteria + +- [ ] Each unverified candidate is probed against a running instance and moved into the confirmed table or the exclusion table with its reason, so the scope rests on measurement rather than vendor claims. +- [x] Every role in the confirmed table declares its native AI surface in `meta/services.yml` with `enabled` and `shared` bound to `'svc-ai-litellm' in group_names`, so a deployment without the gateway configures no AI surface at all. +- [x] Every role in the confirmed table carries a `credentials.litellm_api_key` entry in `meta/secrets.yml`, and the deploy writes that virtual key into the application's own AI configuration rather than a shared or hardcoded key. +- [x] Every role in the confirmed table points its AI base URL at the in-cluster gateway address, and a deploy-time assertion fails when the configured URL resolves outside the deployment. +- [x] No role in the confirmed table retains a default that sends requests to a third-party provider when the gateway is enabled. +- [x] A Playwright spec per role proves the configured surface answers a prompt through the gateway, mirroring `roles/web-app-nextcloud/files/playwright/addons/integration_openai.spec.js`. +- [x] The deploy fails when a role declares the AI surface enabled while its configuration still carries an empty or unresolved API key, so a silently unauthenticated surface cannot reach a green deploy. +- [x] No credential validation in `meta/secrets.yml` encodes a vendor key format, so a gateway-issued virtual key satisfies every AI credential the platform mints. +- [x] `docs/requirements/027-integration-matrix.md` lists the AI surface of every role in the confirmed table. + +Consumers that must name a model (`web-app-moodle`, `web-app-matrix`) read `LITELLM_CHAT_MODEL`, which picks the first non-embedding preload model of `svc-ai-ollama` and mirrors the branch order of the gateway's own `config.yaml.j2`. The consumer resolves that branch from `lookup('deployment').inventory`, every group the round's inventory populates, read from the play-wide `groups` magic var. `.running` is wrong here: a targeted `apps=` round sets it to the whitelist, and `svc-ai-ollama` is pulled in as a dependency rather than named on the command line, so both backend branches fall through to the `openrouter/auto` vendor default. The gateway then answers `Invalid model name passed in model=openrouter/auto` with HTTP 400 and no consumer can complete a prompt. `.groups` is wrong for the mirror-image reason: it carries `group_names`, which is host-scoped, so on a multi-host round a worker that hosts neither the gateway nor a backend resolves an empty model while the manager resolves the right one. + +### Which variant exercises the gateway + +`svc-ai-litellm` pulls `svc-ai-ollama` and `svc-ai-lmstudio` with it, so a consumer that enables the gateway adds roughly 6 GB to its round. Variant 0 is the fallback every higher round lands on, so a heavy shared dependency pinned there appears in every round: with the gateway on variant 0 of `web-app-matrix`, `web-app-mattermost` and `web-app-zammad`, the `web-app-nextcloud` rounds that pin those partners exceed the 64 GB budget guarded by `tests/integration/roles/meta/variants/test_resource_budget.py`. + +The gateway is therefore pinned on **variant 2** for every consumer that ships three variants, and left on variant 0 for the two-variant roles, whose round 2 falls back to it. One `make compose-deploy variant=2` run exercises eight of the nine confirmed roles. `web-app-nextcloud` is the exception: its AI surface has always lived on its own variant 7, alongside the other bridged partners it distributes across budget bins. + +## See Also + +- [031 - LLM Gateway Model Backends](031-llm-gateway-model-backends.md) +- [025 - MCP Role Integration](025-mcp-role-integration.md) diff --git a/group_vars/all/02_tls.yml b/group_vars/all/02_tls.yml index 89b900a6b3..2439050ca4 100644 --- a/group_vars/all/02_tls.yml +++ b/group_vars/all/02_tls.yml @@ -26,6 +26,8 @@ CA_ROOT: CN: "{{ (DOMAIN_PRIMARY ~ ' Root CA') if ((DOMAIN_PRIMARY ~ ' Root CA') | length <= 64) else DOMAIN_PRIMARY }}" CA_TRUST: cert_host: "{{ CA_ROOT.cert_host }}" + bundle_host: "{{ [CA_ROOT.base_dir, 'ca-bundle.crt'] | path_join }}" + inject_bundle_container: "/tmp/infinito/ca/ca-bundle.crt" cert_container: "/etc/ssl/certs/infinito-ca.pem" trust_name: "{{ DOMAIN_PRIMARY | lower }}" wrapper_host: "{{ BIN_CA_TRUST }}" diff --git a/group_vars/all/05_paths.yml b/group_vars/all/05_paths.yml index 65733f82ea..c9f8cbe1e9 100644 --- a/group_vars/all/05_paths.yml +++ b/group_vars/all/05_paths.yml @@ -5,6 +5,7 @@ DIR_SCRIPTS_ROOT: "/opt/scripts/" DIR_SCRIPTS_SYSTEMCTL: "{{ [ DIR_SCRIPTS_ROOT, 'systemctl' ] | path_join }}" DIR_COMPOSITIONS: "/opt/compose/" DIR_SYSTEM_SERVICE: "/etc/systemd/system" +DIR_SYSTEM_SERVICE_USER: "$HOME/.config/systemd/user" DIR_COMPOSE_PULL_LOCK: "/run/ansible/compose-pull/" DIR_BIN: "/usr/bin" diff --git a/group_vars/all/08_networks.yml b/group_vars/all/08_networks.yml index 6226ee22fc..f757e83a3e 100644 --- a/group_vars/all/08_networks.yml +++ b/group_vars/all/08_networks.yml @@ -5,13 +5,24 @@ NETWORK_PUBLIC_DNS_RESOLVERS: - 8.8.8.8 # nocheck: hardcoded-dns-resolver - 1.0.0.1 # nocheck: hardcoded-dns-resolver NETWORK_DOCKER_EMBEDDED_DNS_RESOLVER: "127.0.0.11" # nocheck: hardcoded-dns-resolver +NETWORK_DNS_PORT: 53 # Well-known resolver port a host DNS listener binds NETWORK_DOCKER_DNS_NGINX_DIRECTIVE: "resolver {{ NETWORK_DOCKER_EMBEDDED_DNS_RESOLVER }} valid=30s ipv6={{ NETWORK_IPV6_ENABLED | on_off }};" -NETWORK_TRUSTED_PROXY_CIDRS: - - 127.0.0.1 - - "::1" - - 10.0.0.0/8 - - 172.16.0.0/12 - - 192.168.0.0/16 +NETWORK_LOOPBACK_CIDR: "127.0.0.0/8" +NETWORK_PRIVATE_CIDRS: + class_a: "10.0.0.0/8" + class_b: "172.16.0.0/12" + class_c: "192.168.0.0/16" +NETWORK_INTERNAL_CIDRS: "{{ [NETWORK_LOOPBACK_CIDR] + (NETWORK_PRIVATE_CIDRS.values() | list) }}" +NETWORK_ROLE_SUBNET_POOL: "{{ NETWORK_PRIVATE_CIDRS.class_c }}" +NETWORK_ROLE_SUBNET_EXCEPTION_ROLES: + - web-app-bigbluebutton +NETWORK_SWARM_GWBRIDGE_POOL: "{{ NETWORK_PRIVATE_CIDRS.class_b }}" +NETWORK_TRUSTED_PROXY_CIDRS: "{{ ['127.0.0.1', '::1'] + (NETWORK_PRIVATE_CIDRS.values() | list) }}" +NETWORK_DOCKER_ADDRESS_POOLS: + - base: "10.208.0.0/12" + size: 24 +NETWORK_TOR_VIRTUAL_CIDR: "10.240.0.0/12" # Range tor answers for .onion instead of routing; must not overlap the pool above +NETWORK_CONTAINER_BRIDGE_RESOLVER: false NETWORK_NESTED_DOCKER_BIP: "192.168.67.1/24" NETWORK_NESTED_DOCKER_ADDRESS_POOLS: - base: "192.168.68.0/22" @@ -78,6 +89,12 @@ PORT_BANDS: # nocheck: unused-var # consumed by the port-allocation plugin outs start: 9053 end: 9053 public: + http: + start: 80 + end: 80 + https: + start: 443 + end: 443 ssh: start: 2201 end: 2299 diff --git a/group_vars/all/16_ai.yml b/group_vars/all/16_ai.yml index 783ebadae9..c79faa45c5 100644 --- a/group_vars/all/16_ai.yml +++ b/group_vars/all/16_ai.yml @@ -2,3 +2,55 @@ # URL of Local Ollama Container OLLAMA_BASE_LOCAL_URL: "http://{{ lookup('config','svc-ai-ollama', 'services.ollama.name') }}:{{ lookup('config','svc-ai-ollama', 'services.ollama.ports.internal.http') }}" + +LITELLM_BASE_LOCAL_URL: "http://{{ lookup('config','svc-ai-litellm', 'services.litellm.name') }}:{{ lookup('config','svc-ai-litellm', 'services.litellm.ports.internal.http') + }}" + +LMSTUDIO_BASE_LOCAL_URL: "http://{{ lookup('config','svc-ai-lmstudio', 'services.lmstudio.name') }}:{{ lookup('config','svc-ai-lmstudio', 'services.lmstudio.ports.internal.http') + }}" + +LITELLM_OPENAI_BASE_LOCAL_URL: "{{ LITELLM_BASE_LOCAL_URL }}/v1" + +LITELLM_BACKEND_ROLES: "{{ lookup('deployment').inventory }}" + +LITELLM_OLLAMA_BACKEND: >- + {{ (lookup('config', 'svc-ai-litellm', 'services.ollama.enabled') | bool) + and (lookup('config', 'svc-ai-litellm', 'services.ollama.shared') | bool) }} + +LITELLM_LMSTUDIO_BACKEND: >- + {{ (lookup('config', 'svc-ai-litellm', 'services.lmstudio.enabled') | bool) + and (lookup('config', 'svc-ai-litellm', 'services.lmstudio.shared') | bool) }} + +AI_LOCAL_MODELS: + - alias: qwen2.5:0.5b + name: qwen2.5-0.5b-instruct + repo: lmstudio-community/Qwen2.5-0.5B-Instruct-GGUF + url: https://huggingface.co/lmstudio-community/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/Qwen2.5-0.5B-Instruct-Q8_0.gguf + source: https://huggingface.co/lmstudio-community/Qwen2.5-0.5B-Instruct-GGUF + file: Qwen2.5-0.5B-Instruct-Q8_0.gguf + sha256: "1d96e30253a76970864323987e3e77eeaf170312952fd61d18d343c25cfd6e52" + bytes: 531068224 + +AI_REMOTE_ALIASES: >- + {{ ['openai/gpt-4o-mini'] * (lookup('api_enabled', 'openai') | int) + + ['anthropic/claude-sonnet-4-5'] * (lookup('api_enabled', 'anthropic') | int) + + ['openrouter/auto'] * (lookup('api_enabled', 'openrouter') | int) }} + +LITELLM_CHAT_MODEL: "{{ (lookup('config', 'svc-ai-ollama', 'services.ollama.preload_models') | map(attribute='alias') | reject('search', 'embed') | list | first | + default('')) if 'svc-ai-ollama' in LITELLM_BACKEND_ROLES else ((lookup('config', 'svc-ai-lmstudio', 'services.lmstudio.preload_models') | map(attribute='alias') + | reject('search', 'embed') | list | first | default('')) if 'svc-ai-lmstudio' in LITELLM_BACKEND_ROLES else (AI_REMOTE_ALIASES | first | default(''))) }}" + +LITELLM_CHAT_MODEL_SERVED: >- + {{ ((LITELLM_OLLAMA_BACKEND | bool) + and ((lookup('config', 'svc-ai-ollama', 'services.ollama.preload_models') + | map(attribute='alias') | reject('search', 'embed') | list) | length > 0)) + or ((LITELLM_LMSTUDIO_BACKEND | bool) + and ((lookup('config', 'svc-ai-lmstudio', 'services.lmstudio.preload_models') + | map(attribute='alias') | reject('search', 'embed') | list) | length > 0)) + or ((AI_REMOTE_ALIASES | length) > 0) }} + +LITELLM_USABLE: "{{ ('svc-ai-litellm' in group_names) and (LITELLM_CHAT_MODEL_SERVED | bool) }}" + +MCP_DISCOVERY: "{{ lookup('mcp_servers') }}" +MCP_DISCOVERED_SERVERS: "{{ MCP_DISCOVERY.selected }}" +MCP_RECONCILE_STRICT: false diff --git a/group_vars/all/18_api.yml b/group_vars/all/18_api.yml index 7b05738278..5dd167098a 100644 --- a/group_vars/all/18_api.yml +++ b/group_vars/all/18_api.yml @@ -1,13 +1,18 @@ --- # Central SPOT for proprietary / external (non-self-hosted) API credentials. -# Each entry is empty by default; an integration that depends on a provider is -# only activated when its credentials are present (see the addons that gate -# their `enabled` on `API.`). Override per provider in the (vault- -# encrypted) inventory; access ONLY via lookup('api', '.'). -# nocheck: unused-var: consumed by the api lookup plugin (plugins/lookup/api.py) via lookup('api', ...), not referenced directly in YAML/Jinja. +# Each entry is empty by default. Override per provider in the (vault- +# encrypted) inventory; read ONLY via lookup('api', '.') and +# gate ONLY on lookup('api_enabled', '') (see utils/api.py). +# nocheck: unused-var: consumed by the api lookup plugins (plugins/lookup/api.py, plugins/lookup/api_enabled.py) via lookup('api', ...), not referenced directly in YAML/Jinja. API: + anthropic: + api_key: "" cloudflare: api_token: "" + openai: + api_key: "" + openrouter: + api_key: "" telegram: bot_token: "" api_id: "" diff --git a/group_vars/all/19_tor.yml b/group_vars/all/19_tor.yml deleted file mode 100644 index cab8b62d08..0000000000 --- a/group_vars/all/19_tor.yml +++ /dev/null @@ -1,7 +0,0 @@ ---- -TOR_ONION_SSH_ENABLED: true - -TOR_EGRESS_ROUTER_ENABLED: true -TOR_EGRESS_VIRTUAL_NET_IPV4: "10.192.0.0/10" - -TOR_ONION_EXTRA_PORTS: "{{ ([{'onion_port': 22, 'target': '127.0.0.1:22'}] if (TOR_ONION_SSH_ENABLED | bool) else []) + lookup('tor_ports') }}" diff --git a/group_vars/all/19_virt.yml b/group_vars/all/19_virt.yml new file mode 100644 index 0000000000..5d09277dcc --- /dev/null +++ b/group_vars/all/19_virt.yml @@ -0,0 +1,5 @@ +--- +KATA_SHIM_BINARY: /usr/bin/containerd-shim-kata-v2 +RUNSC_SHIM_BINARY: /usr/local/bin/runsc +SANDBOX_NODE_LABEL: kata-capable +SANDBOX_RUNTIME: runsc diff --git a/group_vars/all/20_robot.yml b/group_vars/all/20_robot.yml new file mode 100644 index 0000000000..f62d23b902 --- /dev/null +++ b/group_vars/all/20_robot.yml @@ -0,0 +1,2 @@ +--- +ROBOT_DEVICE_ALLOWLIST: [] diff --git a/group_vars/all/README.md b/group_vars/all/README.md index 2def1b4732..233e6be0f0 100644 --- a/group_vars/all/README.md +++ b/group_vars/all/README.md @@ -6,7 +6,10 @@ This directory contains the [Ansible](https://docs.ansible.com/ansible/latest/pl Variables in this directory MUST apply across all hosts and all roles. Typical examples are the software identity, deployment toggles, domain defaults, the central network and port registries, OIDC and LDAP endpoints, design tokens, and resource defaults. -Role-specific configuration MUST NOT live here. Such values belong in the corresponding role under `roles//config/main.yml` or `roles//vars/main.yml`. +Role-specific configuration MUST NOT live here, even when only one role reads it today. Such values belong in the corresponding role: + +- `roles//meta/services.yml` for anything an operator may override, because the inventory's `applications.` block is deep-merged on top of it and `lookup('config', application_id, '')` reads the result. +- `roles//vars/main.yml` for values derived from that configuration, and for those the role fixes. Role vars outrank inventory variables, so a value placed here cannot be overridden per host. ## File naming and load order ๐Ÿ”ข diff --git a/inventories/development/default.yml b/inventories/development/default.yml index f8a0351f91..14ece5e26c 100644 --- a/inventories/development/default.yml +++ b/inventories/development/default.yml @@ -37,6 +37,14 @@ design: colors: base: "#FFA500" +API: + openai: + api_key: "{{ lookup('env', 'INFINITO_API_OPENAI_KEY') }}" + anthropic: + api_key: "{{ lookup('env', 'INFINITO_API_ANTHROPIC_KEY') }}" + openrouter: + api_key: "{{ lookup('env', 'INFINITO_API_OPENROUTER_KEY') }}" + OIDC_OVERRIDE: CLIENT: SECRET: VERYUNSAFESAMPLEPASSWORD1234 diff --git a/inventories/development/swarm.yml b/inventories/development/swarm.yml index b2aa786804..bbd3eec84a 100644 --- a/inventories/development/swarm.yml +++ b/inventories/development/swarm.yml @@ -12,7 +12,9 @@ networks: internet: ip4: "{{ lookup('env', 'INFINITO_SWARM_MGR_IP') }}" ip6: "::1" - dns: "172.17.0.1" # nocheck: hardcoded-dns-resolver (mgr-01 docker bridge gateway, served by local dnsmasq) + dns: "{{ NETWORK_PUBLIC_DNS_RESOLVERS | first }}" + +NETWORK_CONTAINER_BRIDGE_RESOLVER: true storage: backend: nfs diff --git a/meta/categories.yml b/meta/categories.yml index c08dfb4ab5..a0d47de229 100644 --- a/meta/categories.yml +++ b/meta/categories.yml @@ -280,6 +280,16 @@ roles: icon: "fas fa-network-wired" bootstrap: true invokable: true + virt: + title: "Sandboxed Runtimes" + hanzi: "ๆฒ™็ฎฑ" # Means "sandbox". + description: "Kernel-isolating container runtimes on the container host: Kata Containers microVMs and the gVisor userspace fallback." + icon: "fas fa-shield-halved" + bootstrap: true + modes: + compose: false + swarm: false + invokable: true runner: title: "CI Runner" diff --git a/meta/distros.yml b/meta/distros.yml index 0d6d719b38..977c0d8c72 100644 --- a/meta/distros.yml +++ b/meta/distros.yml @@ -46,7 +46,7 @@ distros: debian: slug: debian family: Debian - dev_runtime_image: debian:bookworm + dev_runtime_image: debian:13 galaxy_platform: Debian ubuntu: slug: ubuntu diff --git a/package-lock.json b/package-lock.json index 16eb35099f..9a924a5fe1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1473,9 +1473,9 @@ "license": "MIT" }, "node_modules/js-yaml": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz", - "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", "dev": true, "funding": [ { diff --git a/packaging/arch/PKGBUILD b/packaging/arch/PKGBUILD index 16e17e6341..04fdd9b70e 100644 --- a/packaging/arch/PKGBUILD +++ b/packaging/arch/PKGBUILD @@ -1,7 +1,7 @@ # Maintainer: Kevin Veen-Birkenbach pkgname=infinito-nexus -pkgver=13.0.0 +pkgver=14.0.0 pkgrel=1 pkgdesc="Meta package for Infinito.Nexus host dependencies (dev + CI)." arch=('any') diff --git a/packaging/debian/changelog b/packaging/debian/changelog index f42e064389..62aa994174 100644 --- a/packaging/debian/changelog +++ b/packaging/debian/changelog @@ -1,3 +1,148 @@ +infinito-nexus (14.0.0-1) unstable; urgency=medium + + **For Users** + + * **AI assistance inside the applications you already run.** A gateway role, + *svc-ai-litellm*, fronts OpenAI, Anthropic and OpenRouter from declared keys, with + *svc-ai-ollama* and the new *svc-ai-lmstudio* serving local models from one shared + catalogue, so inference can stay inside the deployment. Sixteen applications use it for + their own built-in AI features instead of calling a vendor directly: WordPress AI Engine, + MediaWiki AIEditingAssistant, Moodle's AI subsystem, Zammad Smart Assist, the xWiki LLM + extension, Discourse AI, the Matrix ChatGPT bridge, Nextcloud, Mattermost Agents, n8n, + Open WebUI and Flowise. The gateway's admin UI signs in through Keycloak. See + [svc-ai-litellm](roles/svc-ai-litellm/README.md) and + [svc-ai-lmstudio](roles/svc-ai-lmstudio/README.md). + + * **Your tools reachable from your assistants.** About twenty applications now speak MCP. + Gitea, GitLab, Mattermost, Nextcloud, n8n, Baserow, Jenkins, Home Assistant, Moodle, + Snipe-IT and WordPress serve their own endpoints; ten more get one through a locked-down + sidecar. Open WebUI, Flowise and the agents discover what the deployment offers and + register it automatically. Access is bounded rather than assumed: blocked paths are + declared, every served path is gated, tools a provider calls mutating are withheld, + reader and writer roles are separate, and each provider authenticates callers as its own + service account. See [svc-ai-mcp-adapter](roles/svc-ai-mcp-adapter/README.md). + + * **Agents as employees, with a kernel between them and the host.** *web-app-hermes* and + *web-app-openclaw* deploy agents behind the single sign-on gate, wired to the gateway's + models and to the MCP servers discovery hands them, each proving on deploy that it can + actually reach them. *svc-virt-kata* runs that tier under a kernel-isolating container + runtime, and *svc-ai-robot* embodies an agent on a dedicated device. Every sandboxed + agent acts as its own platform account rather than borrowing yours. See + [web-app-hermes](roles/web-app-hermes/README.md), + [web-app-openclaw](roles/web-app-openclaw/README.md) and + [svc-virt-kata](roles/svc-virt-kata/README.md). + + * **Home automation joins the platform.** *web-app-homeassistant* deploys the automation + hub, exposes it as an MCP server so agents can drive it, persists the token it mints, and + is reachable over tor. See [web-app-homeassistant](roles/web-app-homeassistant/README.md). + + * **Changing a password changes it everywhere.** A user declares how its password must be + generated, the inventory pins one for every declared user, a new generator produces + API-key shapes, the deploy rotates credentials between its two passes, and a reset command + exists. Applications that persist an administrator password at install now realign it when + the declared one changes: Nextcloud, Moodle, EspoCRM, Jellyfin, Listmonk, Discourse, + Checkmk, xWiki, n8n, Matrix and the dedicated MariaDB and Postgres engines. Checkmk keeps + a 401 fatal so a wrong password cannot lock the account out. + + * **Onions, firewall and name resolution.** *svc-net-firewall* owns the packet filter as one + nftables table per role. Tor carries mail to a .onion in both deploy modes, rejects forged + sources on the guarded ports, and binds its dnsmasq listeners statically so a failed + re-enumeration can no longer drop every one of them. The deployment declares its own + address space once, the egress range moved out of the Docker pool, and the container + resolver follows the live bridge instead of a guessed address. Every host-bound port + requires an explicit onion decision. See + [svc-net-firewall](roles/svc-net-firewall/README.md). + + * **Application fixes you will notice.** Nextcloud installs an OnlyOffice release upstream + actually published, keeps social login working over tor, and makes its OIDC account an + administrator. Element shows invites again through the new room list. Moodle survives the + container roll during installation. Mattermost keeps its configuration in Postgres instead + of on a shared volume, and its plugin tree is per node. GitLab creates the default + organization a headless install never gets. Jellyfin waits for health before driving the + setup wizard. Keycloak registers redirect URIs only for the apps a play deploys, keeps the + allowed-origins claim out of the access token, and no longer caches LDAP federation past a + fresh grant. The platform's own health mail no longer eats the sender quota. + + * **Operating a deployment.** New make targets reach a single deployed application: + *compose-app-exec*, *compose-app-logs* and *compose-app-restart*. Diagnostics collect the + logs an application writes to a file, including from busybox containers. Health probes use + a fast start cadence with a window that outlasts a real boot, so a slow starter is no + longer reaped. The CSP health check accepts a status code a vhost declares instead of + dropping the vhost, and gives onion vhosts a navigation budget Tor can meet. + + **For Developers** + + * **MCP is declared, not wired.** A role states an *mcp* block in *meta/services.yml*, and + the vocabulary, discovery and rendering layer derives endpoints, clients, credentials and + network edges from it. A client-provider pairing is declared once, on the provider; + *sys-svc-mcp-reconcile* converges clients from the complete provider set; a refused pairing + is expressed as off rather than gated at the call site; and *svc-ai-mcp-adapter* is a + reusable per-provider sidecar rather than a standalone application. The contract is proven + on deploy, including refusal on *initialize* and the tool inventory itself. The design, + its delegation rules and a machine-checkable audit live under + [docs/contributing/design/role/services/mcp.md](docs/contributing/design/role/services/mcp.md). + + * **Registry and variant changes.** A variant can dictate the configuration of the providers + it pulls in, and an MCP round decides for itself what it carries, which is the breaking + change in this release. Fifteen moving pins gained names the registry can order, every MCP + provider is registered as a shared service, *meta/schema.yml* finished its rename to + *meta/secrets.yml*, role scripts are sorted into per-language folders, and *meta/addons* is + now an accepted declaration site for pins and plugins. + + * **Lints that fail closed.** Five properties that used to pass silently now fail. The PHP + and Ruby that roles ship are syntax-checked, and so are shell scripts that ship as Jinja + templates. *sys-service* owns every systemd unit a role installs. Healthcheck timings are + judged against what the base image was measured to hold, a variable-free healthcheck + belongs in *meta/services.yml*, an unenforceable NFS state layout fails at author time, a + sandboxed role cannot be pinned to the manager, credentials are kept out of volumes + declared non-secret, *no_log* is required on every task carrying one and forbidden in the + test roles, and a JavaScript default for an unset environment variable is rejected. + + * **Pins that cannot age unnoticed.** Image pins are classified and pull references built + from the class, a moving tag declares itself with the marker it already carries, and a + role's images move as one release or not at all. The updater reads addon declarations, + orders vendor patch counters and five-component versions, reads a release line written + before the number as a family, and now also watches pinned pip requirements and Ansible + collections. Seven roles moved off the Debian codename base onto slim, and one Ubuntu + mirror list with failover, a short timeout and a health test serves both the package cache + and the image builds. *js-yaml* was lifted to 4.3.2 for GHSA-2883-xcg3-v3hh. + + * **CI selects, resumes and proves.** A fourth deploy chunk stops a short priority chunk + stranding budget, a manual run can set the chunk size the formula would derive, and a + retrigger can override the chunk gate. Retriggering works by role and by what never got a + verdict, resumes behind the green window rather than the deployed one, retires suites the + source run already passed, and cancels the run before retriggering its failed roles. Each + role's README instructions are replayed on its smallest deploy row, in the mode its + *services.yml* declares. Distro images build concurrently on one runner, the matrix job + folds into the image job, and the deploy chunks no longer wait on the DNS test. + + * **Swarm, measured rather than assumed.** The deploy waits for its own update instead of + guessing after it, refuses to call a stack converged while it is still updating, survives a + task that failed and came back, reports what converged rather than only what did not, and + says why the convergence probe refused. Placement is constrained to a role's declared + platform arch, redis and memcached sidecars get a deploy block, and a run-once service no + longer strands the stack deploy waiting for a replica it never has. The rescue dump + captures the contents of the state volumes. In the test lab, workers are labelled + kata-capable only when the app is sandboxed, NFS detaches before the node containers die, + and the sandbox tier gets a second node. + + * **Faster gates.** Per-host setup runs once per host instead of once per application, a + role's volumes are answered from its own file instead of a whole-tree build, the Keycloak + RBAC root group resolves once rather than once per app, the Playwright fixture copy the + tree copy already made is dropped, logout helpers wait for a control instead of sleeping, + and the OIDC login helper stops waiting out probes that cannot match. Onion timeouts scale + by tor flavor instead of a flat multiplier, and every Playwright timeout has one source. + + * **Documentation and agent instructions.** Six new requirement documents cover the LLM + gateway and model backends, agent employees, Home Assistant, the robot role, the MCP proxy + expansion and native AI gateway integration. The MCP design docs are nested under their own + folder with an audit the lints can check. The role README template asks the reader for a + domain the deployment can resolve, enforces consistent Credits attribution, and drops the em + dash. Documentation generators are gathered under *cli/build/docs*, and a new CLI edits role + bonds in a matrix instead of hunting through files. + + -- Kevin Veen-Birkenbach Sat, 19 Sep 2026 16:35:48 +0200 + infinito-nexus (13.0.0-1) unstable; urgency=medium * **Tor as a first-class deployment axis.** The new *svc-net-tor* role routes onion diff --git a/packaging/fedora/infinito-nexus.spec b/packaging/fedora/infinito-nexus.spec index 51e99a8f89..675af778d9 100644 --- a/packaging/fedora/infinito-nexus.spec +++ b/packaging/fedora/infinito-nexus.spec @@ -1,5 +1,5 @@ Name: infinito-nexus -Version: 13.0.0 +Version: 14.0.0 Release: 1%{?dist} Summary: Meta package for Infinito.Nexus host dependencies @@ -58,6 +58,148 @@ install -d %{buildroot}%{_docdir}/%{name} %doc %{_docdir}/%{name}/DEPENDENCIES %changelog +* Sat Sep 19 2026 Kevin Veen-Birkenbach - 14.0.0-1 +- **For Users** + +- * **AI assistance inside the applications you already run.** A gateway role, +- *svc-ai-litellm*, fronts OpenAI, Anthropic and OpenRouter from declared keys, with +- *svc-ai-ollama* and the new *svc-ai-lmstudio* serving local models from one shared +- catalogue, so inference can stay inside the deployment. Sixteen applications use it for +- their own built-in AI features instead of calling a vendor directly: WordPress AI Engine, +- MediaWiki AIEditingAssistant, Moodle's AI subsystem, Zammad Smart Assist, the xWiki LLM +- extension, Discourse AI, the Matrix ChatGPT bridge, Nextcloud, Mattermost Agents, n8n, +- Open WebUI and Flowise. The gateway's admin UI signs in through Keycloak. See +- [svc-ai-litellm](roles/svc-ai-litellm/README.md) and +- [svc-ai-lmstudio](roles/svc-ai-lmstudio/README.md). + +- * **Your tools reachable from your assistants.** About twenty applications now speak MCP. +- Gitea, GitLab, Mattermost, Nextcloud, n8n, Baserow, Jenkins, Home Assistant, Moodle, +- Snipe-IT and WordPress serve their own endpoints; ten more get one through a locked-down +- sidecar. Open WebUI, Flowise and the agents discover what the deployment offers and +- register it automatically. Access is bounded rather than assumed: blocked paths are +- declared, every served path is gated, tools a provider calls mutating are withheld, +- reader and writer roles are separate, and each provider authenticates callers as its own +- service account. See [svc-ai-mcp-adapter](roles/svc-ai-mcp-adapter/README.md). + +- * **Agents as employees, with a kernel between them and the host.** *web-app-hermes* and +- *web-app-openclaw* deploy agents behind the single sign-on gate, wired to the gateway's +- models and to the MCP servers discovery hands them, each proving on deploy that it can +- actually reach them. *svc-virt-kata* runs that tier under a kernel-isolating container +- runtime, and *svc-ai-robot* embodies an agent on a dedicated device. Every sandboxed +- agent acts as its own platform account rather than borrowing yours. See +- [web-app-hermes](roles/web-app-hermes/README.md), +- [web-app-openclaw](roles/web-app-openclaw/README.md) and +- [svc-virt-kata](roles/svc-virt-kata/README.md). + +- * **Home automation joins the platform.** *web-app-homeassistant* deploys the automation +- hub, exposes it as an MCP server so agents can drive it, persists the token it mints, and +- is reachable over tor. See [web-app-homeassistant](roles/web-app-homeassistant/README.md). + +- * **Changing a password changes it everywhere.** A user declares how its password must be +- generated, the inventory pins one for every declared user, a new generator produces +- API-key shapes, the deploy rotates credentials between its two passes, and a reset command +- exists. Applications that persist an administrator password at install now realign it when +- the declared one changes: Nextcloud, Moodle, EspoCRM, Jellyfin, Listmonk, Discourse, +- Checkmk, xWiki, n8n, Matrix and the dedicated MariaDB and Postgres engines. Checkmk keeps +- a 401 fatal so a wrong password cannot lock the account out. + +- * **Onions, firewall and name resolution.** *svc-net-firewall* owns the packet filter as one +- nftables table per role. Tor carries mail to a .onion in both deploy modes, rejects forged +- sources on the guarded ports, and binds its dnsmasq listeners statically so a failed +- re-enumeration can no longer drop every one of them. The deployment declares its own +- address space once, the egress range moved out of the Docker pool, and the container +- resolver follows the live bridge instead of a guessed address. Every host-bound port +- requires an explicit onion decision. See +- [svc-net-firewall](roles/svc-net-firewall/README.md). + +- * **Application fixes you will notice.** Nextcloud installs an OnlyOffice release upstream +- actually published, keeps social login working over tor, and makes its OIDC account an +- administrator. Element shows invites again through the new room list. Moodle survives the +- container roll during installation. Mattermost keeps its configuration in Postgres instead +- of on a shared volume, and its plugin tree is per node. GitLab creates the default +- organization a headless install never gets. Jellyfin waits for health before driving the +- setup wizard. Keycloak registers redirect URIs only for the apps a play deploys, keeps the +- allowed-origins claim out of the access token, and no longer caches LDAP federation past a +- fresh grant. The platform's own health mail no longer eats the sender quota. + +- * **Operating a deployment.** New make targets reach a single deployed application: +- *compose-app-exec*, *compose-app-logs* and *compose-app-restart*. Diagnostics collect the +- logs an application writes to a file, including from busybox containers. Health probes use +- a fast start cadence with a window that outlasts a real boot, so a slow starter is no +- longer reaped. The CSP health check accepts a status code a vhost declares instead of +- dropping the vhost, and gives onion vhosts a navigation budget Tor can meet. + +- **For Developers** + +- * **MCP is declared, not wired.** A role states an *mcp* block in *meta/services.yml*, and +- the vocabulary, discovery and rendering layer derives endpoints, clients, credentials and +- network edges from it. A client-provider pairing is declared once, on the provider; +- *sys-svc-mcp-reconcile* converges clients from the complete provider set; a refused pairing +- is expressed as off rather than gated at the call site; and *svc-ai-mcp-adapter* is a +- reusable per-provider sidecar rather than a standalone application. The contract is proven +- on deploy, including refusal on *initialize* and the tool inventory itself. The design, +- its delegation rules and a machine-checkable audit live under +- [docs/contributing/design/role/services/mcp.md](docs/contributing/design/role/services/mcp.md). + +- * **Registry and variant changes.** A variant can dictate the configuration of the providers +- it pulls in, and an MCP round decides for itself what it carries, which is the breaking +- change in this release. Fifteen moving pins gained names the registry can order, every MCP +- provider is registered as a shared service, *meta/schema.yml* finished its rename to +- *meta/secrets.yml*, role scripts are sorted into per-language folders, and *meta/addons* is +- now an accepted declaration site for pins and plugins. + +- * **Lints that fail closed.** Five properties that used to pass silently now fail. The PHP +- and Ruby that roles ship are syntax-checked, and so are shell scripts that ship as Jinja +- templates. *sys-service* owns every systemd unit a role installs. Healthcheck timings are +- judged against what the base image was measured to hold, a variable-free healthcheck +- belongs in *meta/services.yml*, an unenforceable NFS state layout fails at author time, a +- sandboxed role cannot be pinned to the manager, credentials are kept out of volumes +- declared non-secret, *no_log* is required on every task carrying one and forbidden in the +- test roles, and a JavaScript default for an unset environment variable is rejected. + +- * **Pins that cannot age unnoticed.** Image pins are classified and pull references built +- from the class, a moving tag declares itself with the marker it already carries, and a +- role's images move as one release or not at all. The updater reads addon declarations, +- orders vendor patch counters and five-component versions, reads a release line written +- before the number as a family, and now also watches pinned pip requirements and Ansible +- collections. Seven roles moved off the Debian codename base onto slim, and one Ubuntu +- mirror list with failover, a short timeout and a health test serves both the package cache +- and the image builds. *js-yaml* was lifted to 4.3.2 for GHSA-2883-xcg3-v3hh. + +- * **CI selects, resumes and proves.** A fourth deploy chunk stops a short priority chunk +- stranding budget, a manual run can set the chunk size the formula would derive, and a +- retrigger can override the chunk gate. Retriggering works by role and by what never got a +- verdict, resumes behind the green window rather than the deployed one, retires suites the +- source run already passed, and cancels the run before retriggering its failed roles. Each +- role's README instructions are replayed on its smallest deploy row, in the mode its +- *services.yml* declares. Distro images build concurrently on one runner, the matrix job +- folds into the image job, and the deploy chunks no longer wait on the DNS test. + +- * **Swarm, measured rather than assumed.** The deploy waits for its own update instead of +- guessing after it, refuses to call a stack converged while it is still updating, survives a +- task that failed and came back, reports what converged rather than only what did not, and +- says why the convergence probe refused. Placement is constrained to a role's declared +- platform arch, redis and memcached sidecars get a deploy block, and a run-once service no +- longer strands the stack deploy waiting for a replica it never has. The rescue dump +- captures the contents of the state volumes. In the test lab, workers are labelled +- kata-capable only when the app is sandboxed, NFS detaches before the node containers die, +- and the sandbox tier gets a second node. + +- * **Faster gates.** Per-host setup runs once per host instead of once per application, a +- role's volumes are answered from its own file instead of a whole-tree build, the Keycloak +- RBAC root group resolves once rather than once per app, the Playwright fixture copy the +- tree copy already made is dropped, logout helpers wait for a control instead of sleeping, +- and the OIDC login helper stops waiting out probes that cannot match. Onion timeouts scale +- by tor flavor instead of a flat multiplier, and every Playwright timeout has one source. + +- * **Documentation and agent instructions.** Six new requirement documents cover the LLM +- gateway and model backends, agent employees, Home Assistant, the robot role, the MCP proxy +- expansion and native AI gateway integration. The MCP design docs are nested under their own +- folder with an audit the lints can check. The role README template asks the reader for a +- domain the deployment can resolve, enforces consistent Credits attribution, and drops the em +- dash. Documentation generators are gathered under *cli/build/docs*, and a new CLI edits role +- bonds in a matrix instead of hunting through files. + * Wed Aug 26 2026 Kevin Veen-Birkenbach - 13.0.0-1 - * **Tor as a first-class deployment axis.** The new *svc-net-tor* role routes onion - names through Tor via DNS instead of per-app proxies, offers a chutney flavor for diff --git a/plugins/action/applications_carrier.py b/plugins/action/applications_carrier.py new file mode 100644 index 0000000000..f7711ed295 --- /dev/null +++ b/plugins/action/applications_carrier.py @@ -0,0 +1,79 @@ +"""Render the applications SPOT once and park it as the play-scoped carrier fact. + +Ansible forks a fresh worker per task, so the in-process render cache of +``lookup('applications')`` is cold in every task until something renders in +a place all later workers inherit. This action renders in the worker of one +constructor task and returns the payload as a host fact; every later worker +inherits that fact at fork time and ``get_merged_applications`` serves it +instead of rendering:: + + - name: ๐ŸงŠ Render the applications SPOT once and carry it into every task's worker + applications_carrier: {} + +``tasks/stages/01_constructor.yml`` parks two of them. The stage-wide one +sits after the token store so the embedded user records already carry the +loaded tokens, and after the ``add_host`` tasks because 114 roles gate +services on ``group_names`` and the payload bakes those in. The +merge block opens an earlier, block-scoped one and drops it again at the +block's end, because ``merged_applications_cache_key`` reads neither +``group_names`` nor the token file: a carrier left standing across either +would be served unchanged where a fresh render belongs:: + + - name: ๐ŸงŠ Drop the merge-block carrier so later stages re-render + applications_carrier: + clear: true + +The result is masked by the action itself: the fact is the whole rendered +tree, about 0.4 MB with every application's credentials, and printing it at +``-v`` is neither credential debugging nor readable. + +Args: + clear: drop the carrier fact instead of rendering. Defaults to false. + Any other argument is an error. +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleActionFail +from ansible.module_utils.parsing.convert_bool import boolean +from ansible.plugins.action import ActionBase +from ansible.plugins.loader import lookup_loader + +from utils.cache.carrier import APPLICATIONS_RENDERED_FACT + + +class ActionModule(ActionBase): + TRANSFERS_FILES = False + + def run( + self, tmp: Any = None, task_vars: dict[str, Any] | None = None + ) -> dict[str, Any]: + result = super().run(tmp, task_vars) + task_vars = task_vars or {} + args = self._task.args or {} + unexpected = sorted(set(args) - {"clear"}) + if unexpected: + raise AnsibleActionFail( + f"applications_carrier: unknown argument(s) {', '.join(unexpected)}; " + "the only argument is 'clear'" + ) + + if boolean(args.get("clear", False)): + result.update( + changed=False, ansible_facts={APPLICATIONS_RENDERED_FACT: None} + ) + return result + + lookup = lookup_loader.get( + "applications", loader=self._loader, templar=self._templar + ) + carrier = lookup.run([], variables=task_vars, carrier=True)[0] + + result.update( + changed=False, + ansible_facts={APPLICATIONS_RENDERED_FACT: carrier}, + _ansible_no_log=True, + ) + return result diff --git a/plugins/filter/README.md b/plugins/filter/README.md index 8ad96bd0ab..7312a1d39a 100644 --- a/plugins/filter/README.md +++ b/plugins/filter/README.md @@ -21,6 +21,39 @@ This directory contains custom **Ansible filter plugins** used within the Infini - If you need to **load data from an external source** (e.g., file, environment, API), use a lookup plugin instead. - If your logic requires **access to inventory, facts, or host-level information** that is not passed as a parameter. +## Schema ๐Ÿ—บ๏ธ + +How `csp_filters.py` assembles one application's Content-Security-Policy. Scope is the header build, not the other filters in this directory. + +```mermaid +flowchart TD + decl["meta/csp.yml
whitelist, flags, hashes"] + svc["meta/services.yml
services.logout.enabled"] + flags["csp_filters.py:136
get_csp_flags"] + grant["csp_filters.py:354
logout grant"] + wl["csp_filters.py:123
get_csp_whitelist"] + inj["sys-front-inj-dashboard,
-javascript, -matomo, -logout
add_csp_hash"] + gate["csp_filters.py:365
hash gate"] + build["csp_filters.py:203
build_csp_header"] + header["set $csp
nginx vhost"] + + decl -->|"1. flags read by"| flags + flags -->|"2. tokens"| build + svc -->|"3. read by"| grant + grant -->|"4. adds 'unsafe-inline'
to script-src-elem and -attr"| build + decl -->|"5. whitelist read by"| wl + wl -->|"6. tokens"| build + inj -->|"7. snippets"| gate + gate -->|"8. hashes, only when
'unsafe-inline' is absent"| build + build -->|"9. joined string"| header + + grant -.->|"TRIP-WIRE: the token it adds
closes the gate below, so every
registered hash is discarded"| gate + svc -.->|"TRIP-WIRE: the flag derives from
group_names, so the script policy
follows the round, not the app"| grant + grant -.->|"TRIP-WIRE: absent from the
smart-defaults docstring, which
names logout only for frame-ancestors"| build +``` + +Styles carry `'unsafe-inline'` by default; scripts do not. The logout grant is the only path that puts it into a script directive. + ## Further Reading - [Ansible Filter Plugins Documentation](https://docs.ansible.com/ansible/latest/plugins/filter.html) diff --git a/plugins/filter/csp_filters.py b/plugins/filter/csp_filters.py index 3dc8b72751..3ff788bb42 100644 --- a/plugins/filter/csp_filters.py +++ b/plugins/filter/csp_filters.py @@ -1,5 +1,6 @@ import base64 import hashlib +import re from ansible.errors import AnsibleFilterError @@ -7,6 +8,9 @@ from utils.domains.primary_domain import get_domain from utils.roles.applications.config import get from utils.tls_common import align_domain_to_consumer, is_onion_domain +_ONION_PLAINTEXT = {"https": "http", "wss": "ws"} +_ONION_SCHEME = re.compile(r"^(https|wss)(?=://)") + def _aligned_url(domains, application_id, target_id, protocol): """Provider URL for CSP tokens, family-aligned to the consuming app. @@ -417,7 +421,10 @@ class FilterModule: toks = tokens_by_dir[directive] if app_has_clearnet: siblings = [ - t.replace(domain_primary, node_onion) + _ONION_SCHEME.sub( + lambda m: _ONION_PLAINTEXT[m.group(1)], + t.replace(domain_primary, node_onion), + ) for t in toks if domain_primary in t ] diff --git a/plugins/filter/mcp/authorization.py b/plugins/filter/mcp/authorization.py new file mode 100644 index 0000000000..f83a3a856c --- /dev/null +++ b/plugins/filter/mcp/authorization.py @@ -0,0 +1,95 @@ +"""Filter ``mcp_authorization``: the Authorization header an MCP server wants. + + {{ server | mcp_authorization }} -> "Bearer " + {{ server | mcp_authorization(env='X') }} -> "Bearer ${env:X}" + +``bearer_token``, ``app_password`` and ``upstream_session`` present the +credential as a bearer. ``basic_auth`` presents ``username:token`` base64 +encoded, which cannot reference an environment variable because the encoding +happens before the value is known. + +``oidc`` is deliberately absent. It means the call executes as the requesting +end user, and a rendered config carries no caller. Emitting the deployment's +own bearer there would relabel a service account as user delegation, so this +filter refuses it and ``mcp_authorization_is_renderable`` drops the server. +Open WebUI reaches such a server through ``system_oauth`` instead; see +``docs/contributing/design/role/services/mcp/delegation.md``. +""" + +from __future__ import annotations + +import base64 +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Mapping + +BEARER_AUTHS = frozenset({"bearer_token", "app_password", "upstream_session"}) +BASIC_AUTHS = frozenset({"basic_auth"}) +DELEGATED_AUTHS = frozenset({"oidc"}) + +SUPPORTED_AUTHS = BEARER_AUTHS | BASIC_AUTHS + + +def mcp_authorization(server: Mapping[str, Any], env: str | None = None) -> str: + """Return the Authorization header value for one discovered MCP server. + + Args: + server: a MCP_DISCOVERED_SERVERS entry carrying auth, token, owner. + env: name of the environment variable holding the token. Bearer schemes + reference it instead of inlining the secret; basic auth ignores it + because the credential is encoded, not substituted. + """ + auth = str(server.get("auth") or "") + token = str(server.get("token") or "") + + if auth in BASIC_AUTHS: + owner = str(server.get("owner") or "") + if not owner: + raise ValueError( + f"MCP server {server.get('id')!r} declares auth {auth!r} but " + f"resolves no credential owner. Basic auth would authenticate " + f"as the empty user and the server would answer 401." + ) + encoded = base64.b64encode(f"{owner}:{token}".encode()).decode() + return f"Basic {encoded}" + + if auth in BEARER_AUTHS: + return f"Bearer ${{env:{env}}}" if env else f"Bearer {token}" + + if auth in DELEGATED_AUTHS: + raise ValueError( + f"MCP server {server.get('id')!r} declares auth {auth!r}, which " + f"executes as the requesting user. A rendered config carries no " + f"caller, so presenting the deployment's own bearer here would be " + f"a service account wearing a user's name. Filter these servers " + f"out with mcp_renderable_servers." + ) + + raise ValueError( + f"MCP server {server.get('id')!r} declares auth {auth!r}, which no " + f"client renderer can present. Supported: {sorted(SUPPORTED_AUTHS)}." + ) + + +def mcp_authorization_is_renderable(server: Mapping[str, Any]) -> bool: + """Return whether a client can present this server's auth scheme at all.""" + return str(server.get("auth") or "") in SUPPORTED_AUTHS + + +def mcp_renderable_servers(servers: Any) -> list: + """Return only the servers whose auth a client can present. + + Args: + servers: a MCP_DISCOVERED_SERVERS-shaped sequence, or None. + """ + return [s for s in servers or [] if mcp_authorization_is_renderable(s)] + + +class FilterModule: + def filters(self): + return { + "mcp_authorization": mcp_authorization, + "mcp_authorization_is_renderable": mcp_authorization_is_renderable, + "mcp_renderable_servers": mcp_renderable_servers, + } diff --git a/plugins/filter/mcp/group_members.py b/plugins/filter/mcp/group_members.py new file mode 100644 index 0000000000..1b56f5bf9f --- /dev/null +++ b/plugins/filter/mcp/group_members.py @@ -0,0 +1,64 @@ +"""Filter ``mcp_group_members``: who may reach each MCP tool server. + + {{ lookup('users') | mcp_group_members(MCP_DISCOVERED_SERVERS, 'mcp-reader') }} + -> {"web-app-baserow": [{"username": "alice", "email": "alice@example.org"}], + "web-app-zammad": []} + +A client cannot rely on the OIDC groups claim alone to revoke access: Open +WebUI drops a stale membership only while the claim is non-empty, so a user +who loses their last group keeps it until a later login carries one. The +deployment therefore reconciles each group's member list explicitly, and an +empty list is a real instruction to empty the group. + +Both identifiers are emitted because the reconciler matches against accounts +Open WebUI created from an OIDC claim, whose display name need not be the +username. The email is the only field both sides agree on exactly. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from utils.roles.rbac.scoped import MCP_ROLES, members_with_role + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + + +def _identify(users: Mapping[str, Any] | None, username: str) -> dict[str, str]: + for key, config in (users or {}).items(): + cfg = config or {} + if str(cfg.get("username", key)) == username: + return {"username": username, "email": str(cfg.get("email") or "")} + return {"username": username, "email": ""} + + +def mcp_group_members( + users: Mapping[str, Any] | None, + servers: Sequence[Mapping[str, Any]] | None, + role: str, +) -> dict[str, list[dict[str, str]]]: + """Return the users granted each MCP role on each discovered server. + + Args: + users: the merged users mapping. + servers: the selected ``MCP_DISCOVERED_SERVERS`` entries. + role: the MCP grant to resolve. + """ + if role not in MCP_ROLES: + raise ValueError( + f"mcp_group_members: unknown role {role!r}; " + f"expected one of {list(MCP_ROLES)}" + ) + return { + server_id: [ + _identify(users, username) + for username in members_with_role(users, server_id, role) + ] + for server_id in (str(s.get("id") or "") for s in servers or [] if s.get("id")) + } + + +class FilterModule: + def filters(self): + return {"mcp_group_members": mcp_group_members} diff --git a/plugins/filter/mcp/tool_server_connections.py b/plugins/filter/mcp/tool_server_connections.py new file mode 100644 index 0000000000..d537a44f09 --- /dev/null +++ b/plugins/filter/mcp/tool_server_connections.py @@ -0,0 +1,102 @@ +"""Filter ``mcp_tool_server_connections``: Open WebUI tool-server entries. + + {{ MCP_DISCOVERED_SERVERS | mcp_tool_server_connections }} + +Open WebUI reads ``TOOL_SERVER_CONNECTIONS`` as a JSON list validated by its +``ToolServerConnection`` model. For ``type: mcp`` it connects to ``url`` +directly, so the discovered endpoint URL goes there whole and ``path`` stays +empty. + +An entry renders disabled until its group id is known. An empty +``config.access_grants`` is not "nobody": ``has_connection_access`` reads it as +every administrator, which is wider than the role's ``mcp`` group and would +apply on every start, because ``ENABLE_PERSISTENT_CONFIG=false`` makes this env +authoritative again after a restart. + +The group id exists only once Open WebUI has minted it, so the first deploy +renders the entry disabled, ``tasks/utils/mcp.yml`` resolves the group through the +API and persists the id, and every later render carries the grant in the env +itself. That is what makes a bare container restart converge: the env it reads +on start already says who may reach the server. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + +TOOL_SERVER_TYPE = "mcp" +AUTH_TYPE_BEARER = "bearer" +AUTH_TYPE_SYSTEM_OAUTH = "system_oauth" + +BEARER_PRESENTABLE_AUTHS = frozenset( + {"bearer_token", "app_password", "upstream_session"} +) +DELEGATED_AUTHS = frozenset({"oidc"}) + + +def mcp_tool_server_connections( + servers: Sequence[Mapping[str, Any]], + group_ids: Mapping[str, str] | None = None, +) -> list[dict]: + """Return one Open WebUI tool-server connection per discovered MCP server. + + Args: + servers: the selected ``MCP_DISCOVERED_SERVERS`` entries. + group_ids: Open WebUI group id per provider ``application_id``, as + resolved and persisted by an earlier deploy. A server without one + renders disabled and ungranted. + + Servers whose auth scheme Open WebUI cannot present are skipped: its + ToolServerConnection accepts bearer, session, system_oauth and oauth_2.1, + so a basic-auth endpoint would be registered with an unusable credential. + + An ``oidc`` server carries no deployment key. ``system_oauth`` makes Open + WebUI resolve the requesting user's own token per request, which is the one + path where the declared ``auth_subject: user`` is true. + """ + known = group_ids or {} + connections = [] + for server in servers or []: + server_id = str(server.get("id", "")).strip() + url = str(server.get("url", "")).strip() + if not server_id or not url: + continue + auth = str(server.get("auth") or "") + if auth in DELEGATED_AUTHS: + auth_type, key = AUTH_TYPE_SYSTEM_OAUTH, "" + elif auth in BEARER_PRESENTABLE_AUTHS: + auth_type, key = AUTH_TYPE_BEARER, str(server.get("token", "")) + else: + continue + group_id = str(known.get(server_id) or "").strip() + grants = ( + [ + { + "principal_type": "group", + "principal_id": group_id, + "permission": "read", + } + ] + if group_id + else [] + ) + connections.append( + { + "url": url, + "path": "", + "type": TOOL_SERVER_TYPE, + "auth_type": auth_type, + "key": key, + "config": {"enable": bool(group_id), "access_grants": grants}, + "info": {"id": server_id, "name": server_id}, + } + ) + return connections + + +class FilterModule: + def filters(self): + return {"mcp_tool_server_connections": mcp_tool_server_connections} diff --git a/plugins/filter/redirect_sources.py b/plugins/filter/redirect_sources.py new file mode 100644 index 0000000000..f826647bb7 --- /dev/null +++ b/plugins/filter/redirect_sources.py @@ -0,0 +1,28 @@ +from ansible.errors import AnsibleFilterError + + +def redirect_sources(host: str) -> list[str]: + """Ordered match prefixes for a redirect that targets ``host``. + + Args: + host: the upstream host, as it appears in the proxied URL. + + Returns: + The two host-qualified forms, then the bare ``/`` for a target the + upstream expressed as an absolute path. + """ + if not isinstance(host, str) or not host.strip(): + raise AnsibleFilterError("redirect_sources: host must be a non-empty string") + stripped = host.strip() + return [ + f"https://{stripped}/", + f"http://{stripped}/", + "/", + ] + + +class FilterModule: + def filters(self): + return { + "redirect_sources": redirect_sources, + } diff --git a/plugins/filter/status_codes.py b/plugins/filter/status_codes.py new file mode 100644 index 0000000000..30b2b4e90a --- /dev/null +++ b/plugins/filter/status_codes.py @@ -0,0 +1,22 @@ +"""Expose the status codes that prove a domain is served to templates.""" + +from __future__ import annotations + +import sys +from pathlib import Path + +# nocheck: project-root-import +_BASE_DIR = str(Path(__file__).resolve().parents[2]) +_MODULE_UTILS_DIR = str(Path(_BASE_DIR) / "utils") +for _p in (_BASE_DIR, _MODULE_UTILS_DIR): + if _p not in sys.path: + sys.path.insert(0, _p) + +from utils.roles.applications.status_codes import ( # noqa: E402 + accepted_status_codes, +) + + +class FilterModule: + def filters(self): + return {"accepted_status_codes": accepted_status_codes} diff --git a/tests/unit/python/cli/build/readme/__init__.py b/plugins/filter/swarm/__init__.py similarity index 100% rename from tests/unit/python/cli/build/readme/__init__.py rename to plugins/filter/swarm/__init__.py diff --git a/plugins/filter/swarm/deployed_services.py b/plugins/filter/swarm/deployed_services.py new file mode 100644 index 0000000000..43f35fa076 --- /dev/null +++ b/plugins/filter/swarm/deployed_services.py @@ -0,0 +1,31 @@ +"""Name the services a ``docker stack deploy`` run reported acting on.""" + +from __future__ import annotations + +import re +from typing import Any + +_LINE = re.compile(r"^(?:Creating|Updating) service (\S+)") + + +def swarm_deployed_services(deploy_result: Any) -> list[str]: + """Return the service names from a registered stack-deploy result. + + Args: + deploy_result: the registered shell result of the deploy. + + Returns: + Service names in the order the deploy reported them. + """ + lines = (deploy_result or {}).get("stdout_lines") or [] + names = [] + for line in lines: + match = _LINE.match(str(line).strip()) + if match: + names.append(match.group(1)) + return names + + +class FilterModule: + def filters(self): + return {"swarm_deployed_services": swarm_deployed_services} diff --git a/plugins/filter/swarm_restart_condition.py b/plugins/filter/swarm/restart_condition.py similarity index 97% rename from plugins/filter/swarm_restart_condition.py rename to plugins/filter/swarm/restart_condition.py index a8250d0dc9..f2316d22f7 100644 --- a/plugins/filter/swarm_restart_condition.py +++ b/plugins/filter/swarm/restart_condition.py @@ -36,8 +36,6 @@ from __future__ import annotations from typing import Any -_VALID_SWARM_CONDITIONS = frozenset({"none", "on-failure", "any"}) - def swarm_restart_condition(value: Any) -> str: """Translate *value* (a compose-style ``docker_restart_policy``) diff --git a/plugins/filter/timeout_start_sec_for_domains.py b/plugins/filter/timeout_start_sec_for_domains.py index d54cc81aea..ed44d59779 100644 --- a/plugins/filter/timeout_start_sec_for_domains.py +++ b/plugins/filter/timeout_start_sec_for_domains.py @@ -12,6 +12,7 @@ class FilterModule: domains_dict, include_www=True, per_domain_seconds=25, + onion_per_domain_seconds=None, overhead_seconds=30, min_seconds=120, max_seconds=3600, @@ -22,6 +23,9 @@ class FilterModule: (values can be str | list[str] | dict[str,str]) or an already flattened list of domains, or a single domain string. include_www (bool): If true, add 'www.' for non-www entries. + per_domain_seconds (int): Budget a clearnet domain contributes. + onion_per_domain_seconds (int | None): Budget a '.onion' domain + contributes; None gives it per_domain_seconds. ... """ try: @@ -59,9 +63,21 @@ class FilterModule: flat.extend(www_variants) unique_domains = sorted(set(flat)) - count = len(unique_domains) + onion_count = sum( + 1 for d in unique_domains if str(d).lower().endswith(".onion") + ) + clearnet_count = len(unique_domains) - onion_count + onion_seconds = ( + per_domain_seconds + if onion_per_domain_seconds is None + else int(onion_per_domain_seconds) + ) - raw = overhead_seconds + per_domain_seconds * count + raw = ( + overhead_seconds + + per_domain_seconds * clearnet_count + + onion_seconds * onion_count + ) return max(min_seconds, min(max_seconds, int(raw))) except AnsibleFilterError: diff --git a/plugins/lookup/addon_env_flags.py b/plugins/lookup/addon_env_flags.py index ee599579cf..99e3fe363e 100644 --- a/plugins/lookup/addon_env_flags.py +++ b/plugins/lookup/addon_env_flags.py @@ -29,10 +29,11 @@ def _is_enabled(value: Any) -> bool: def _resolve_deployed_roles(variables, templar, applications): - """Resolve TEST_E2E_PLAYWRIGHT_APPS (the deployed playwright role ids) to a set. + """Resolve the round's deployed role closure to a set. Returns None when it cannot be resolved, in which case bridge-deployment - gating is skipped (no behaviour change).""" - raw = (variables or {}).get("TEST_E2E_PLAYWRIGHT_APPS") + gating is skipped (no behaviour change). + """ + raw = (variables or {}).get("group_names") if raw is None: return None resolved = raw @@ -47,7 +48,7 @@ def _resolve_deployed_roles(variables, templar, applications): resolved = [r for r in re.split(r"[\s,]+", resolved.strip()) if r] if not isinstance(resolved, (list, tuple, set)): return None - return {str(r).strip() for r in resolved if str(r).strip()} + return {str(r).strip() for r in resolved if str(r).strip()} or None def _any_bridge_partner_deployed(bridges, deployed_roles, service_registry): diff --git a/plugins/lookup/api.py b/plugins/lookup/api.py index 9740e8d16b..a10e26c2f2 100644 --- a/plugins/lookup/api.py +++ b/plugins/lookup/api.py @@ -5,13 +5,16 @@ from typing import Any from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase +from utils.api import resolve_api + class LookupModule(LookupBase): """ lookup('api', '.') e.g. lookup('api', 'github.client_id') Single point of truth for proprietary / external API credentials. Resolves a - dotted path against the global ``API`` mapping (group_vars/all/18_api.yml). + dotted path against the effective ``API`` mapping: the declaration in + group_vars/all/18_api.yml with the calling scope's override merged over it. Routing every access through this plugin keeps one place to change how proprietary API credentials are sourced (vault, env, secret manager, a different provider abstraction) without touching the call sites. @@ -31,11 +34,10 @@ class LookupModule(LookupBase): if not path: raise AnsibleError("lookup('api'): empty key path.") - api = variables.get("API", {}) - if templar is not None: - api = templar.template(api) - if not isinstance(api, dict): - raise AnsibleError("lookup('api'): global 'API' is not a mapping.") + try: + api = resolve_api(variables, templar=templar) + except TypeError as error: + raise AnsibleError(f"lookup('api'): {error}") from error node: Any = api for part in path.split("."): diff --git a/plugins/lookup/api_enabled.py b/plugins/lookup/api_enabled.py new file mode 100644 index 0000000000..c5f189070b --- /dev/null +++ b/plugins/lookup/api_enabled.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase + +from utils.api import provider_enabled, resolve_api + + +class LookupModule(LookupBase): + """ + lookup('api_enabled', '') e.g. lookup('api_enabled', 'github') + + True when every credential the provider declares in group_vars/all/18_api.yml + carries a value in the effective ``API`` mapping. Integrations that depend on + a proprietary provider gate on this instead of spelling the emptiness test + out per call site, so an added credential key extends the gate everywhere and + the result is a real boolean rather than a string a filter has to coerce. + """ + + def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): + if not terms or len(terms) != 1: + raise AnsibleError( + "lookup('api_enabled') takes exactly one term: '' " + "(e.g. 'github')." + ) + + templar = getattr(self, "_templar", None) + variables = variables or getattr(templar, "available_variables", {}) or {} + + provider = str(terms[0]).strip() + if not provider: + raise AnsibleError("lookup('api_enabled'): empty provider name.") + + try: + api = resolve_api(variables, templar=templar) + return [provider_enabled(api, provider)] + except (KeyError, TypeError) as error: + raise AnsibleError(f"lookup('api_enabled'): {error}") from error diff --git a/plugins/lookup/application_closure.py b/plugins/lookup/application_closure.py new file mode 100644 index 0000000000..fc5d88c006 --- /dev/null +++ b/plugins/lookup/application_closure.py @@ -0,0 +1,60 @@ +"""Lookup ``application_closure``: roles reachable from a seed application set. + +Walks the same edges the constructor's role set is built from, so a +whitelist-scoped deploy and the full-inventory deploy agree on what a role +depends on. The traversal itself lives in +``utils/roles/applications/in_group_deps``; this only exposes it to Ansible. + + {{ lookup('application_closure', ['web-app-snipe-it']) }} + +Returns the seed roles plus every role reachable through ``meta/main.yml`` +dependencies and declared service edges, transitively. An empty seed yields an +empty list, which callers read as "no scoping requested". +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils import PROJECT_ROOT +from utils.roles.applications.in_group_deps import reachable_roles + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[list[str]]: + seeds: list[str] = [] + for term in terms or []: + if isinstance(term, (list, tuple, set)): + seeds.extend(str(entry) for entry in term) + elif term: + seeds.append(str(term)) + + if not seeds: + return [[]] + + roles_dir = kwargs.get("roles_dir") or str(PROJECT_ROOT / "roles") + vars_ = variables or getattr(self._templar, "available_variables", {}) or {} + + applications = lookup_loader.get( + "applications", loader=self._loader, templar=getattr(self, "_templar", None) + ).run([], variables=vars_)[0] + try: + included = reachable_roles( + applications, + seeds, + roles_dir=roles_dir, + project_root=str(PROJECT_ROOT), + ) + except (TypeError, ValueError) as exc: + raise AnsibleError(f"application_closure: {exc}") from exc + + return [sorted(included | set(seeds))] diff --git a/plugins/lookup/applications.py b/plugins/lookup/applications.py index b72ff4a151..74acce51c4 100644 --- a/plugins/lookup/applications.py +++ b/plugins/lookup/applications.py @@ -9,6 +9,7 @@ from utils.cache import _reset_cache_for_tests as _reset_runtime_lookup_cache # nocheck: lookup-cache-import (this lookup IS the applications SPOT provider) from utils.cache.applications import get_merged_applications +from utils.cache.carrier import merged_applications_cache_key def _reset_cache_for_tests() -> None: @@ -22,21 +23,39 @@ class LookupModule(LookupBase): variables: dict[str, Any] | None = None, **kwargs: Any, ) -> list[Any]: + """ + Terms: + 0) full merged mapping + 1) application_id + 2) application_id, default value + + Keyword arguments: + roles_dir: roles tree to build from (defaults to the repository's) + carrier: with no terms, return ``{"key": [...], "applications": {...}}`` + for the constructor to park in `_INFINITO_APPLICATIONS_RENDERED` + """ terms = terms or [] if len(terms) > 2: raise AnsibleError( "applications: expected 0, 1, or 2 terms: " "lookup('applications'[, application_id[, default]])" ) + carrier = bool(kwargs.get("carrier", False)) + if carrier and terms: + raise AnsibleError("applications: carrier=True takes no terms") + variables = variables or getattr(self._templar, "available_variables", {}) or {} + roles_dir = kwargs.get("roles_dir") applications = get_merged_applications( - variables=variables - or getattr(self._templar, "available_variables", {}) - or {}, - roles_dir=kwargs.get("roles_dir"), + variables=variables, + roles_dir=roles_dir, templar=getattr(self, "_templar", None), ) + if carrier: + key = merged_applications_cache_key(variables, roles_dir=roles_dir) + return [{"key": [key[0], list(key[1])], "applications": applications}] + if len(terms) == 0: return [applications] diff --git a/plugins/lookup/bounded_name.py b/plugins/lookup/bounded_name.py new file mode 100644 index 0000000000..7c8edc390d --- /dev/null +++ b/plugins/lookup/bounded_name.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.domains.primary_domain import get_domain +from utils.roles.entity.name import get_entity_name + + +class LookupModule(LookupBase): + """ + Usage: + {{ lookup('bounded_name', application_id, max_length) }} + + An application's canonical primary domain when it has at most max_length + characters, otherwise its short entity name (e.g. ``keycloak``). + + Args: + application_id: the application whose domain names the value. + max_length: the longest value the consumer accepts; a positive integer. + """ + + def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): + if not terms or len(terms) != 2: + raise AnsibleError( + "lookup('bounded_name', application_id, max_length) expects exactly 2 terms" + ) + + application_id, max_length = terms + if not isinstance(application_id, str) or not application_id.strip(): + raise AnsibleError( + "lookup('bounded_name'): application_id must be a " + f"non-empty string, got {application_id!r}" + ) + application_id = application_id.strip() + + try: + limit = int(max_length) + except (TypeError, ValueError) as e: + raise AnsibleError( + f"lookup('bounded_name'): max_length must be an integer, got {max_length!r}" + ) from e + if limit < 1: + raise AnsibleError( + f"lookup('bounded_name'): max_length must be positive, got {limit}" + ) + + variables = variables or getattr(self._templar, "available_variables", {}) or {} + + domains = lookup_loader.get( + "domains", + loader=getattr(self, "_loader", None), + templar=getattr(self, "_templar", None), + ).run([], variables=variables, roles_dir=kwargs.get("roles_dir"))[0] + + try: + domain = get_domain(domains, application_id) + except Exception as e: + raise AnsibleError( + f"lookup('bounded_name'): failed to resolve domain for " + f"'{application_id}': {e}" + ) from e + + name = str(domain or "") + if 0 < len(name) <= limit: + return [name] + return [get_entity_name(application_id)] diff --git a/plugins/lookup/compose_volumes.py b/plugins/lookup/compose_volumes.py index 19c297bd19..4a2cd198d5 100644 --- a/plugins/lookup/compose_volumes.py +++ b/plugins/lookup/compose_volumes.py @@ -6,7 +6,6 @@ DEPLOYMENT_MODE, and the `storage` mapping from the templating context. from __future__ import annotations import contextlib -from collections.abc import Mapping, Sequence from typing import Any from ansible.errors import AnsibleError, AnsibleFilterError @@ -28,33 +27,13 @@ from utils.roles.applications.mounts import ( normalize_volumes_meta, ) from utils.roles.applications.services.database import ( + REALIGN_CONFIG_KEY, get_database_service_config, resolve_database_service_key, ) from utils.roles.applications.services.sso import get_sso_config from utils.storage.nfs import swarm_nfs_backed -from utils.templating.ansible import _trust_as_template - - -def _to_plain(obj: Any) -> Any: - """Convert Ansible/Jinja proxy types into plain Python so PyYAML can serialize.""" - - if obj is None: - return None - - if isinstance(obj, str): - return str(obj) - - if isinstance(obj, (int, float, bool)): - return obj - - if isinstance(obj, Mapping): - return {str(_to_plain(k)): _to_plain(v) for k, v in obj.items()} - - if isinstance(obj, Sequence) and not isinstance(obj, (str, bytes, bytearray)): - return [_to_plain(x) for x in obj] - - return str(obj) +from utils.templating.ansible import _trust_as_template, to_plain def _resolve_database_volume_name( @@ -220,10 +199,15 @@ def compose_volumes( if extra_volumes: volumes.update(extra_volumes) - if extra_configs: - configs.update(extra_configs) - if extra_secrets: - secrets.update(extra_secrets) + for section, extra in ((configs, extra_configs), (secrets, extra_secrets)): + for key, spec in (extra or {}).items(): + named = spec + if isinstance(spec, dict) and spec.get("file") and not spec.get("name"): + named = { + **spec, + "name": _config_secret_name(role_entity, key, str(spec["file"])), + } + section[key] = named role_data = applications.get(application_id) or {} raw_meta_volumes = ( @@ -288,16 +272,63 @@ def compose_volumes( if isinstance(nfs_meta, dict): vol_spec["x-infinito-nfs"] = dict(nfs_meta) - payload: dict[str, Any] = {"volumes": _to_plain(volumes)} + payload: dict[str, Any] = {"volumes": to_plain(volumes)} if configs: - payload["configs"] = _to_plain(configs) + payload["configs"] = to_plain(configs) if secrets: - payload["secrets"] = _to_plain(secrets) + payload["secrets"] = to_plain(secrets) return dump_yaml_str(payload).rstrip() class LookupModule(LookupBase): + def _with_database_realign( + self, + applications: dict[str, Any], + application_id: str, + vars_: dict[str, Any], + extra_configs: dict[str, Any] | None, + ) -> dict[str, Any] | None: + """Add the realignment statements an app's own mariadb reads at start. + + Args: + applications: the merged applications mapping. + application_id: the app whose stack is being rendered. + vars_: the variables in scope for the lookup. + extra_configs: configs a caller already supplied. + + The file lands as a config rather than a bind mount because a swarm task + may run on a node the source path does not exist on. + + A role declaring two engines is left to ``compose_volumes``, which turns + the same ValueError into the message that says which one to drop. + """ + try: + database_service_key = resolve_database_service_key( + applications, application_id + ) + except ValueError: + return extra_configs + if database_service_key != "mariadb": + return extra_configs + if get_database_service_config(applications, application_id).get("shared"): + return extra_configs + + source = lookup_loader.get( + "database", loader=self._loader, templar=getattr(self, "_templar", None) + ).run([application_id, "realign_sql"], variables=vars_)[0] + if not source: + return extra_configs + + entity = get_entity_name(application_id) + return { + **(extra_configs or {}), + REALIGN_CONFIG_KEY: { + "name": _config_secret_name(entity, REALIGN_CONFIG_KEY, source), + "file": source, + }, + } + def run( self, terms: list[Any] | None, @@ -366,7 +397,9 @@ class LookupModule(LookupBase): applications, application_id, extra_volumes=kwargs.get("extra_volumes"), - extra_configs=kwargs.get("extra_configs"), + extra_configs=self._with_database_realign( + applications, application_id, vars_, kwargs.get("extra_configs") + ), extra_secrets=kwargs.get("extra_secrets"), deployment_mode=str(deployment_mode).strip(), storage=storage, diff --git a/plugins/lookup/container_dns.py b/plugins/lookup/container_dns.py index cf653494cf..1dfb85c02e 100644 --- a/plugins/lookup/container_dns.py +++ b/plugins/lookup/container_dns.py @@ -1,13 +1,143 @@ from __future__ import annotations +from ipaddress import ip_network from typing import Any +from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase +from utils.networks.address import subnet_gateway +from utils.templating.ansible import _trust_as_template + _TOR_ROLE = "svc-net-tor" -def resolve_container_dns(variables: dict[str, Any]) -> list[str]: +def _serves_on_the_bridge(variables: dict[str, Any]) -> bool: + """Return whether a resolver on the docker bridge is there to be used. + + Args: + variables: the variables in scope for the lookup. + + This used to be inferred from the host's own ``resolv.conf``: every entry a + loopback address was read as "a listener of ours answers, and containers + must reach it on the bridge instead". The inference is wrong on any host + running systemd-resolved or NetworkManager's dnsmasq, whose stubs bind + ``127.0.0.53`` and ``127.0.0.1`` and nothing else. Those hosts were handed a + bridge address with no server behind it, which cost them all container DNS - + an image build failed on ``apk`` resolving nothing while the daemon itself, + resolving through the host, pulled the same image fine. + + Two things do bind the bridge and both say so: ``svc-net-tor``, whose + dnsmasq listens there so ``.onion`` resolves, and any deployment that sets + ``NETWORK_CONTAINER_BRIDGE_RESOLVER``. + """ + if _TOR_ROLE in (variables.get("group_names") or []): + return True + return bool(variables.get("NETWORK_CONTAINER_BRIDGE_RESOLVER")) + + +def render(value: Any, templar: Any) -> str: + """Return an inventory value with its Jinja resolved. + + Args: + value: whatever the inventory holds for the field. + templar: the lookup's templar, or None outside a play. + + ``networks.internet.dns`` arrives through ``-e @inventories/...`` and is + read straight out of ``variables``, which hands back whatever the file + contains. While that was a literal address nobody noticed; an expression + there reached the daemon as its own source text and docker refused the + config with ``ParseAddr("{{ ... }}")``. + + ``str()`` drops the ``TrustedAsTemplate`` tag the loader attached, and the + templar returns an untagged string unrendered. Re-tagging before templating + is what every sibling lookup does; without it this function would trade the + daemon's parse error for its own. + """ + text = str(value or "") + if "{{" not in text: + return text + rendered = ( + str(templar.template(_trust_as_template(text))) if templar is not None else text + ) + if "{{" in rendered: + raise AnsibleError( + f"networks.internet.dns is {text!r} and did not resolve to an " + f"address. Emitting it would put that source text in daemon.json, " + f"where docker refuses the whole config." + ) + return rendered + + +def bridge_address(variables: dict[str, Any]) -> str: + """Return the docker bridge gateway containers can reach the host on. + + Args: + variables: the variables in scope for the lookup. + + ``ansible_facts`` only carries ``docker0`` once the daemon has run, and the + daemon config is written before that on a fresh node - facts are gathered at + play start, and nothing re-gathers them after the install. Reading the fact + alone therefore yields nothing on the very run that has to emit the address, + which leaves the inner containers pointed at the clearnet resolver and the + DinD DNS check failing on a domain only the node dnsmasq knows. + + ``default-address-pools`` is where docker takes that address from, so the + declaration answers before the daemon exists and answers identically + afterwards. That also keeps daemon.json byte-identical across passes, which + the fact-derived value could not: it appeared only from the second run on + and restarted the container runtime under a live stack. + + The fact is not merely late, it is wrong while it is late. Facts are read + before the daemon config is applied, so ``docker0`` still carries docker's + own default; writing the pools then moves the bridge underneath it. A swarm + node measured ``172.17.0.1`` in daemon.json against a live ``10.208.0.1``, + which is why the declaration answers here and the fact never does. + + The pool's ``size`` bounds the slice docker hands the bridge, so the gateway + is derived from that slice rather than from the enclosing supernet - they + agree only while the pool starts on a slice boundary. + """ + pools = variables.get("NETWORK_DOCKER_ADDRESS_POOLS") or [] + first = (pools[0] or {}) if pools else {} + base = str(first.get("base") or "") + if not base: + return "" + size = first.get("size") + try: + network = ip_network(base, strict=True) + slice_ = ( + network if size is None else next(network.subnets(new_prefix=int(size))) + ) + return subnet_gateway(str(slice_)) + except ValueError as exc: + raise AnsibleError( + f"networks: the first docker address pool {base!r} holds no gateway " + f"address, so containers have no way back to the host resolver." + ) from exc + + +def public_resolver(variables: dict[str, Any]) -> str: + """Return the resolver to fall back on when the bridge may serve nothing. + + Args: + variables: the variables in scope for the lookup. + + Read strictly: a missing declaration must fail the render rather than emit + a hardcoded address, which the repository forbids and lints for. Only the + first entry is taken because a resolver list is capped at three and the + bridge already holds one of those slots. + """ + resolvers = variables.get("NETWORK_PUBLIC_DNS_RESOLVERS") + if not resolvers: + raise AnsibleError( + "networks: NETWORK_PUBLIC_DNS_RESOLVERS is empty, so a host whose " + "docker bridge serves no DNS would be left without any resolver." + ) + return str(resolvers[0]) + + +def resolve_container_dns(variables: dict[str, Any], templar: Any = None) -> list[str]: """Return the resolver list for the container runtime, most specific first. On a Tor node the node dnsmasq resolves ``.onion`` through Tor's DNSPort @@ -16,6 +146,13 @@ def resolve_container_dns(variables: dict[str, Any]) -> list[str]: bridge address because docker discards loopback resolvers, and it is absent before docker itself is installed, hence the guard. + The same reachability problem exists without Tor wherever the host resolves + through a listener of its own on loopback, which is how the simulated + cluster nodes are wired. Handing containers the declared clearnet address + there was what a literal bridge address in the inventory used to paper + over, and that literal went stale the moment the daemon's address pool + moved the bridge off Docker's default. + Both deploy modes get the bridge: a Tor node runs the same dnsmasq listener in compose and in swarm, so both resolve onions alike. @@ -24,17 +161,26 @@ def resolve_container_dns(variables: dict[str, Any]) -> list[str]: the bridge *is* the clearnet resolver, emitting it twice makes daemon.json differ between a run before and a run after ``docker0`` exists, and that difference restarts the container runtime underneath a live stack. + + Whether a resolver answers on the bridge is not something the host's own + ``resolv.conf`` can say - a systemd-resolved stub and a node dnsmasq both + read as loopback-only, and only the second one also binds the bridge. Until + that is declared rather than inferred, the bridge may be an address nothing + serves, so it never goes out alone: a list that would carry it by itself + gets the project's public resolver behind it. Without that the daemon has a + single dead nameserver and every container and image build loses DNS. """ - facts = variables.get("ansible_facts") or {} - bridge = ((facts.get("docker0") or {}).get("ipv4") or {}).get("address") or "" - on_tor_node = _TOR_ROLE in (variables.get("group_names") or []) + bridge = bridge_address(variables) - clearnet = ((variables.get("networks") or {}).get("internet") or {}).get( - "dns" - ) or "" + clearnet = render( + ((variables.get("networks") or {}).get("internet") or {}).get("dns"), templar + ) - resolvers = (bridge if on_tor_node else "", clearnet) - return list(dict.fromkeys(str(r) for r in resolvers if r)) + resolvers = (bridge if _serves_on_the_bridge(variables) else "", clearnet) + emitted = list(dict.fromkeys(str(r) for r in resolvers if r)) + if emitted == [bridge]: + emitted.append(public_resolver(variables)) + return emitted class LookupModule(LookupBase): @@ -49,4 +195,4 @@ class LookupModule(LookupBase): if terms: raise ValueError("lookup('container_dns') takes no positional terms.") variables = variables or getattr(self._templar, "available_variables", {}) or {} - return [resolve_container_dns(variables)] + return [resolve_container_dns(variables, self._templar)] diff --git a/plugins/lookup/container_extra_hosts.py b/plugins/lookup/container_extra_hosts.py index aefcb26abd..fec4dbce1e 100644 --- a/plugins/lookup/container_extra_hosts.py +++ b/plugins/lookup/container_extra_hosts.py @@ -24,6 +24,12 @@ through here, from two sources that are both optional: Entries are ``"name:address"`` strings and are deduplicated in first-seen order. With nothing to emit the lookup returns an empty string. +``entries_only=true`` returns those strings as a list instead of the rendered +block, for a container that is not described by a compose file at all: +``web-app-discourse`` is built by discourse_docker's ``launcher``, whose only +argument surface is ``docker_args:`` in its ``app.yml``, so it needs +``--add-host=`` lines. + The automatic pin follows the effective deploy mode, and in swarm it must NOT be ``host-gateway``: that alias resolves per node, while openresty publishes :80 with ``mode: host`` under ``node.role == manager``, so every replica on a worker @@ -48,6 +54,13 @@ Usage in any service template: {{ lookup('container_extra_hosts', extra_hosts=['host.docker.internal:host-gateway']) | indent(4) }} {{ lookup('container_extra_hosts', application_id='web-app-nextcloud') | indent(4) }} + +Usage from a non-compose call site: + + {% for entry in lookup('container_extra_hosts', + entries_only=True, wantlist=True) %} + - --add-host={{ entry }} + {% endfor %} """ from __future__ import annotations @@ -109,6 +122,8 @@ class LookupModule(LookupBase): ) entries += self._caller_entries(kwargs.get("extra_hosts")) merged = list(dict.fromkeys(entries)) + if _to_bool(self._render(kwargs.get("entries_only", False)), strict=False): + return merged if not merged: return [""] diff --git a/plugins/lookup/container_healthcheck.py b/plugins/lookup/container_healthcheck.py index f6f45f9ee4..e57286b94c 100644 --- a/plugins/lookup/container_healthcheck.py +++ b/plugins/lookup/container_healthcheck.py @@ -27,11 +27,13 @@ Examples: from __future__ import annotations +import contextlib from typing import Any from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase +from ansible.template import trust_as_template from utils.docker.healthcheck.compose import build, known_flavors, resolve_flavors from utils.docker.healthcheck.prefixes import PREFIXES @@ -58,6 +60,11 @@ class LookupModule(LookupBase): self._application_id = self._render( kwargs.get("application_id") or self._vars.get("application_id") ) + if self._templar is not None and "{{" in str(self._application_id or ""): + with contextlib.suppress(Exception): + self._application_id = self._templar.template( + trust_as_template(str(self._application_id)) + ) if not self._application_id: raise AnsibleError( "container_healthcheck: no application_id in the play vars; " diff --git a/plugins/lookup/container_hostname.py b/plugins/lookup/container_hostname.py index 25c28bdb67..fe2b343e98 100644 --- a/plugins/lookup/container_hostname.py +++ b/plugins/lookup/container_hostname.py @@ -6,9 +6,6 @@ from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase -from utils.domains.primary_domain import get_domain -from utils.roles.entity.name import get_entity_name - _HOST_NAME_MAX = 63 @@ -17,11 +14,8 @@ class LookupModule(LookupBase): Usage: {{ lookup('container_hostname', application_id) }} - The Docker/OCI hostname for an application's container: its canonical - primary domain when that fits the kernel's 63-byte limit, otherwise the - short entity name (e.g. ``xwiki``). Centralises the domain-or-entity - choice so onion deployments (long ``.onion`` subdomains that overflow - sethostname(2)) never break container init. + The Docker/OCI hostname for an application's container: ``bounded_name`` + at the 63-byte limit sethostname(2) enforces. """ def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): @@ -30,31 +24,8 @@ class LookupModule(LookupBase): "lookup('container_hostname', application_id) expects exactly 1 term" ) - application_id = terms[0] - if not isinstance(application_id, str) or not application_id.strip(): - raise AnsibleError( - "lookup('container_hostname'): application_id must be a " - f"non-empty string, got {application_id!r}" - ) - application_id = application_id.strip() - - variables = variables or getattr(self._templar, "available_variables", {}) or {} - - domains = lookup_loader.get( - "domains", + return lookup_loader.get( + "bounded_name", loader=getattr(self, "_loader", None), templar=getattr(self, "_templar", None), - ).run([], variables=variables, roles_dir=kwargs.get("roles_dir"))[0] - - try: - domain = get_domain(domains, application_id) - except Exception as e: - raise AnsibleError( - f"lookup('container_hostname'): failed to resolve domain for " - f"'{application_id}': {e}" - ) from e - - name = str(domain or "") - if 0 < len(name) <= _HOST_NAME_MAX: - return [name] - return [get_entity_name(application_id)] + ).run([terms[0], _HOST_NAME_MAX], variables=variables, **kwargs) diff --git a/plugins/lookup/container_networks.py b/plugins/lookup/container_networks.py index b6cf120a6f..5bed7737cb 100644 --- a/plugins/lookup/container_networks.py +++ b/plugins/lookup/container_networks.py @@ -7,7 +7,8 @@ Usage in any service template: {{ lookup('container_networks') | indent(4) }} Pass ``provider_self_alias=False`` for a sidecar service that must not carry the -provider's own alias. +provider's own alias, and ``own_network_only=True`` for one that must not +inherit the networks its provider joins as a consumer. """ from __future__ import annotations @@ -50,5 +51,6 @@ class LookupModule(LookupBase): lookup_database=ctx.lookup_database, provider_self_alias=bool(kwargs.get("provider_self_alias", True)), node_local=bool(kwargs.get("node_local", False)), + own_network_only=bool(kwargs.get("own_network_only", False)), ) ] diff --git a/plugins/lookup/container_ports.py b/plugins/lookup/container_ports.py index 87ce236006..f6cb5504a2 100644 --- a/plugins/lookup/container_ports.py +++ b/plugins/lookup/container_ports.py @@ -1,33 +1,67 @@ -"""Lookup `container_ports`: build a compose ``ports:`` publish block from -``[service_name, protocol]`` or ``[service_name, protocol, host_ip]`` terms. +"""Lookup `container_ports`: build a compose ``ports:`` block from declared ports. -Single SPOT replacing the repeated, verbose port lookups. Each term is a -two- or three-element list; pass one or more. The optional third element is -the host IP to bind that port to; omit it to publish on every interface: +Single SPOT for every published port in the repo. A term is either the short +list form or the dict form; pass one or more. + +List form, unchanged:: {{ lookup('container_ports', ['gitea', 'http', DOCKER_BIND_HOST], ['gitea', 'ssh']) | indent(4) }} -produces +produces:: ports: - - "::" + - "::<...internal.http>" - ":" -Per term the published (host) port is ``services..ports.local.`` -when declared, else ``services..ports.public.``; the container -port is always ``services..ports.internal.``. A third element -prefixes ``:``; without it the port binds to all interfaces. This -makes every mapping expressible, including binds to a specific public IP -(e.g. ``['mailu', 'smtp', MAILU_IP4_PUBLIC]``). +The published (host) port is ``ports.local.`` when declared, else +``ports.public.``; the container port is ``ports.internal.``. -``application_id`` is read from the play variables unless given as ``application_id=``. +Dict form, for the shapes the list form cannot express:: + + {{ lookup('container_ports', + {'service': 'coturn', 'protocol': 'stun_turn', + 'transport': ['udp', 'tcp'], 'container': 'same'}, + {'service': 'coturn', 'protocol': 'relay', 'transport': 'udp', + 'container': 'same'}, + {'service': 'openresty', 'protocol': 'http', 'mode': 'host'}, + {'service': 'funkwhale', 'protocol': 'api', + 'publish': 'ephemeral'}) | indent(4) }} + +Keys: + +``service``, ``protocol`` + Required, as in the list form. +``ip`` + Host address to bind to; omit to publish on every interface. +``transport`` + ``tcp``, ``udp``, or a list of both. One list item per transport. Omit for + compose's own default, which publishes no suffix. +``container`` + ``internal`` (default) reads ``ports.internal.``; ``same`` reuses the + published port, for services that cannot remap (STUN/TURN, media relays). +``mode`` + ``ingress`` (default) emits the short ``"host:published:container"`` string; + ``host`` emits the long block with ``mode: host``, which is what an edge + role needs in swarm so the client address survives the hop. +``publish`` + ``ephemeral`` publishes the container port on a host port docker picks, for + a service addressed only through the compose network. + +A declared value that is a ``{start, end}`` mapping renders as ``start-end`` on +both sides, so a relay range needs no special term. + +``application_id`` is read from the play variables unless given as +``application_id=``. ``key='expose'`` names the block instead of ``ports``, for +Discourse's launcher file, whose ``expose:`` list is what becomes ``docker run +-p`` there. """ from __future__ import annotations import contextlib +from collections.abc import Mapping from typing import Any from ansible.errors import AnsibleError @@ -37,11 +71,115 @@ from ansible.template import trust_as_template from utils.roles.applications.config import get +_TERM_KEYS = frozenset( + {"service", "protocol", "ip", "transport", "container", "mode", "publish"} +) +_TRANSPORTS = ("tcp", "udp") +_CONTAINER_SOURCES = ("internal", "same") +_MODES = ("ingress", "host") + def _as_str(value: Any) -> str: return "" if value is None else str(value).strip() +def _rendered(value: Any) -> str: + """A declared port value as compose writes it, ranges included.""" + if isinstance(value, Mapping): + start, end = value.get("start"), value.get("end") + if start is None or end is None: + return "" + return f"{_as_str(start)}-{_as_str(end)}" + return _as_str(value) + + +def _transports_of(term: Mapping) -> list[str]: + declared = term.get("transport") + if declared is None: + return [""] + wanted = [declared] if isinstance(declared, str) else list(declared) + for transport in wanted: + if transport not in _TRANSPORTS: + raise AnsibleError( + f"container_ports: transport must be one of {_TRANSPORTS}, " + f"got {transport!r}" + ) + return wanted + + +def _normalised(term: Any) -> dict[str, Any]: + """One term as a dict, accepting the legacy list form.""" + if isinstance(term, (list, tuple)): + if len(term) not in (2, 3): + raise AnsibleError( + "container_ports: a list term must be [service_name, protocol] " + f"or [service_name, protocol, host_ip], got {term!r}" + ) + term = { + "service": term[0], + "protocol": term[1], + **({"ip": term[2]} if len(term) == 3 else {}), + } + if not isinstance(term, Mapping): + raise AnsibleError( + f"container_ports: each term must be a list or a mapping, got {term!r}" + ) + unknown = set(term) - _TERM_KEYS + if unknown: + raise AnsibleError( + f"container_ports: unknown term key(s) {sorted(unknown)}; " + f"valid keys are {sorted(_TERM_KEYS)}" + ) + normalised = { + "service": _as_str(term.get("service")), + "protocol": _as_str(term.get("protocol")), + "ip": _as_str(term.get("ip")), + "transport": term.get("transport"), + "container": _as_str(term.get("container")) or "internal", + "mode": _as_str(term.get("mode")) or "ingress", + "publish": _as_str(term.get("publish")), + } + if not normalised["service"] or not normalised["protocol"]: + raise AnsibleError("container_ports: service and protocol must be non-empty") + if normalised["container"] not in _CONTAINER_SOURCES: + raise AnsibleError( + f"container_ports: container must be one of {_CONTAINER_SOURCES}, " + f"got {normalised['container']!r}" + ) + if normalised["mode"] not in _MODES: + raise AnsibleError( + f"container_ports: mode must be one of {_MODES}, got {normalised['mode']!r}" + ) + if normalised["publish"] and normalised["publish"] != "ephemeral": + raise AnsibleError( + "container_ports: publish accepts only 'ephemeral', " + f"got {normalised['publish']!r}" + ) + if normalised["mode"] == "host" and normalised["ip"]: + raise AnsibleError( + "container_ports: mode 'host' binds the node's own interface and " + "takes no ip" + ) + return normalised + + +def _short_line(term: Mapping, published: str, container: str, transport: str) -> str: + suffix = f"/{transport}" if transport else "" + if term["publish"] == "ephemeral": + return f' - "{container}{suffix}"' + head = f"{term['ip']}:" if term["ip"] else "" + return f' - "{head}{published}:{container}{suffix}"' + + +def _host_lines(published: str, container: str, transport: str) -> list[str]: + return [ + f" - target: {container}", + f" published: {published}", + f" protocol: {transport or 'tcp'}", + " mode: host", + ] + + class LookupModule(LookupBase): def run( self, @@ -58,22 +196,9 @@ class LookupModule(LookupBase): if not terms: raise AnsibleError( "lookup('container_ports', [service_name, protocol[, host_ip]], ...) " - "expects one or more [service_name, protocol] terms" + "expects one or more terms" ) - triples: list[tuple[str, str, str]] = [] - for term in terms: - if not (isinstance(term, (list, tuple)) and len(term) in (2, 3)): - raise AnsibleError( - "container_ports: each term must be a [service_name, protocol] " - f"or [service_name, protocol, host_ip] list, got {term!r}" - ) - service, protocol = _as_str(term[0]), _as_str(term[1]) - host = _as_str(term[2]) if len(term) == 3 else "" - if not service or not protocol: - raise AnsibleError( - "container_ports: service_name and protocol must be non-empty" - ) - triples.append((service, protocol, host)) + parsed = [_normalised(term) for term in terms] templar = getattr(self, "_templar", None) variables = variables or getattr(self._templar, "available_variables", {}) or {} @@ -96,7 +221,7 @@ class LookupModule(LookupBase): ).run([], variables=variables)[0] def _port(service: str, scope: str, protocol: str, *, required: bool) -> str: - value = _as_str( + value = _rendered( get( applications=applications, application_id=application_id, @@ -112,14 +237,24 @@ class LookupModule(LookupBase): ) return value - lines = ["ports:"] - for service, protocol, host in triples: - internal = _port(service, "internal", protocol, required=True) - published = _port(service, "local", protocol, required=False) or _port( - service, "public", protocol, required=True + block_key = _as_str(kwargs.get("key")) or "ports" + if block_key not in ("ports", "expose"): + raise AnsibleError( + f"container_ports: key must be 'ports' or 'expose', got {block_key!r}" ) - if host: - lines.append(f' - "{host}:{published}:{internal}"') + lines = [f"{block_key}:"] + for term in parsed: + service, protocol = term["service"], term["protocol"] + published = _port(service, "local", protocol, required=False) or _port( + service, "public", protocol, required=term["publish"] != "ephemeral" + ) + if term["container"] == "same": + container = published else: - lines.append(f' - "{published}:{internal}"') + container = _port(service, "internal", protocol, required=True) + for transport in _transports_of(term): + if term["mode"] == "host": + lines.extend(_host_lines(published, container, transport)) + else: + lines.append(_short_line(term, published, container, transport)) return ["\n".join(lines)] diff --git a/plugins/lookup/container_volumes.py b/plugins/lookup/container_volumes.py index 791af3b8ac..33628e9e6b 100644 --- a/plugins/lookup/container_volumes.py +++ b/plugins/lookup/container_volumes.py @@ -22,7 +22,7 @@ from utils.roles.applications.mounts import ( mount_when_passes, normalize_volumes_meta, ) -from utils.templating.ansible import _trust_as_template +from utils.templating.ansible import _trust_as_template, to_plain if TYPE_CHECKING: from collections.abc import Callable @@ -46,6 +46,37 @@ def _coerce_mode_int(value: Any) -> int: ) from exc +_SIZE_UNITS = {"": 1, "b": 1, "k": 1024, "m": 1024**2, "g": 1024**3} + + +def _coerce_size_bytes(value: Any) -> int: + """Return a tmpfs size as the byte count the long-form mount demands. + + A declaration reads ``512m`` because that is how a human writes it and how + the short form accepts it. The long form takes an integer, and compose + rejects the string outright rather than parsing it, so the suffix has to be + resolved here. + """ + if isinstance(value, bool): + raise AnsibleFilterError( + f"container_volumes: size must be an int or a size string, got bool: {value!r}" + ) + if isinstance(value, int): + return value + text = str(value).strip().lower() + if not text: + raise AnsibleFilterError("container_volumes: size is empty") + number, unit = text[:-1], text[-1] + if unit.isdigit(): + number, unit = text, "" + try: + return int(number) * _SIZE_UNITS[unit] + except (ValueError, KeyError) as exc: + raise AnsibleFilterError( + f"container_volumes: size {value!r} is not a byte count: {exc}" + ) from exc + + def _short_form_volume(source_name: str, target: str, read_only: bool) -> str: suffix = ":ro" if read_only else "" return f"{source_name}:{target}{suffix}" @@ -138,8 +169,13 @@ def container_volumes( "type": "tmpfs", "target": target, } + tmpfs_options: dict[str, Any] = {} if mount.get("size") is not None: - tmpfs_entry["tmpfs"] = {"size": mount["size"]} + tmpfs_options["size"] = _coerce_size_bytes(mount["size"]) + if mount.get("mode") is not None: + tmpfs_options["mode"] = _coerce_mode_int(mount["mode"]) + if tmpfs_options: + tmpfs_entry["tmpfs"] = tmpfs_options volumes_block.append(tmpfs_entry) elif vtype == "config": @@ -157,11 +193,11 @@ def container_volumes( secrets_block.append(sec_ref) if extra_volumes: - volumes_block.extend(extra_volumes) + volumes_block.extend(to_plain(extra_volumes)) if extra_configs: - configs_block.extend(extra_configs) + configs_block.extend(to_plain(extra_configs)) if extra_secrets: - secrets_block.extend(extra_secrets) + secrets_block.extend(to_plain(extra_secrets)) payload: dict[str, Any] = {} if volumes_block: diff --git a/plugins/lookup/database.py b/plugins/lookup/database.py index e6649e604c..eef6b02f4a 100644 --- a/plugins/lookup/database.py +++ b/plugins/lookup/database.py @@ -11,6 +11,8 @@ from ansible.plugins.lookup import LookupBase from utils.manager.credential_key import OVERRIDE_SECTION from utils.roles.applications.config import get from utils.roles.applications.services.database import ( + REALIGN_CONFIG_KEY, + REALIGN_TARGET, get_database_service_config, resolve_database_service_key, ) @@ -105,6 +107,9 @@ class LookupModule(LookupBase): "password": "", "port": "", "env": "", + "realign_sql": "", + "realign_target": REALIGN_TARGET, + "realign_config": REALIGN_CONFIG_KEY, "initdb_dir": "", "build_dir": "", "url_jdbc": "", @@ -201,6 +206,7 @@ class LookupModule(LookupBase): env_dir = f"{path_instances}{get_entity_name(consumer_id)}/.env/" env = f"{env_dir}{dbtype}.env" + realign_sql = f"{env_dir}{dbtype}-realign.sql" initdb_dir = f"{path_instances}{get_entity_name(consumer_id)}/.initdb.d/" build_dir = f"{path_instances}{get_entity_name(consumer_id)}/.postgres-build/" @@ -263,6 +269,9 @@ class LookupModule(LookupBase): "password": password, "port": port, "env": env, + "realign_sql": realign_sql, + "realign_target": REALIGN_TARGET, + "realign_config": REALIGN_CONFIG_KEY, "initdb_dir": initdb_dir, "build_dir": build_dir, "url_jdbc": url_jdbc, diff --git a/plugins/lookup/deployment.py b/plugins/lookup/deployment.py index ad7eb96a8a..b74d65abac 100644 --- a/plugins/lookup/deployment.py +++ b/plugins/lookup/deployment.py @@ -10,6 +10,8 @@ _STATUS_CACHE: dict[tuple, dict[str, list[str]]] = {} _EPHEMERAL_RUNTIMES = frozenset({"act", "github"}) +_IMPLICIT_GROUPS = frozenset({"all", "ungrouped"}) + def _reset_cache_for_tests() -> None: _STATUS_CACHE.clear() @@ -34,8 +36,13 @@ class LookupModule(LookupBase): whitelist = _coerce_to_list(vars_.get("APPLICATIONS_WHITELIST")) groups = _coerce_to_list(vars_.get("group_names")) + inventory = sorted( + name + for name, hosts in (vars_.get("groups") or {}).items() + if hosts and name not in _IMPLICIT_GROUPS + ) runtime = str(vars_.get("RUNTIME", "")).strip().lower() - key = (tuple(whitelist), tuple(groups), runtime) + key = (tuple(whitelist), tuple(groups), tuple(inventory), runtime) cached = _STATUS_CACHE.get(key) if cached is not None: @@ -47,6 +54,7 @@ class LookupModule(LookupBase): "whitelist": whitelist, "running": list(running), "groups": groups, + "inventory": inventory, "deployed": deployed, "runtime": runtime, "all": list(list_invokable_app_ids()), diff --git a/plugins/lookup/engine.py b/plugins/lookup/engine.py index afae03a98a..5c769cc538 100644 --- a/plugins/lookup/engine.py +++ b/plugins/lookup/engine.py @@ -47,6 +47,31 @@ _FIELDS = ( ) +def qdrant_consumer_key(applications: dict[str, Any], svc_id: str) -> str: + """Return the engine-wide key a data-owning qdrant consumer presents. + + Args: + applications: the resolved applications mapping. + svc_id: the qdrant service role id. + + qdrant has no per-consumer principals, only two engine-wide keys, so a + consumer that owns data here holds the engine's own key. The read-only key + is deliberately never returned: it belongs to the MCP adapter, whose whole + read-only guarantee rests on being unable to present anything else. + """ + return str( + get( + applications, + svc_id, + f"{OVERRIDE_SECTION}.api_key", + strict=False, + default="", + skip_missing_app=True, + ) + or "" + ).strip() + + class LookupModule(LookupBase): def run( self, @@ -128,6 +153,9 @@ class LookupModule(LookupBase): or "" ).strip() + if engine == "qdrant" and shared: + password = qdrant_consumer_key(applications, svc_id) + if engine == "rabbitmq": url = ( f"amqp://{username}:{password}@{host}:{port}/{entity}" diff --git a/plugins/lookup/mcp_client_bearer.py b/plugins/lookup/mcp_client_bearer.py new file mode 100644 index 0000000000..2b5b9519e7 --- /dev/null +++ b/plugins/lookup/mcp_client_bearer.py @@ -0,0 +1,68 @@ +"""Lookup ``mcp_client_bearer``: the secret a client presents to a provider. + + "{{ lookup('mcp_client_bearer', 'web-app-gitea') }}" + -> the bearer an admitted client sends, or "" when none is minted yet + +Which secret that is depends on ``mcp.credential.source``: an adapter fronts +its upstream and issues its own bearer under the role's ``secrets.credentials``, +while a native or plugin provider hands out the token its principal holds in +the store. Reading the wrong one yields a secret that exists, authenticates +something, and is rejected by the endpoint under test. + +The choice is not repeated here: it is ``resolve_credential``, the same +function ``mcp_servers`` renders every client's connection with, so a test +built on this lookup measures the credential the deployment actually ships. +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.manager.credential_key import CREDENTIALS_KEY, SECRETS_KEY +from utils.roles.applications.mcp import resolve_credential + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Any]: + terms = list(terms or []) + if len(terms) != 1 or not str(terms[0]).strip(): + raise AnsibleError( + "mcp_client_bearer: expected the provider's application_id, " + "e.g. lookup('mcp_client_bearer', 'web-app-gitea')" + ) + application_id = str(terms[0]).strip() + vars_ = variables or getattr(self._templar, "available_variables", {}) or {} + templar = getattr(self, "_templar", None) + config = lookup_loader.get("config", loader=self._loader, templar=templar) + + credential = config.run([application_id, "mcp.credential"], variables=vars_)[0] + if not isinstance(credential, dict): + raise AnsibleError( + f"mcp_client_bearer: {application_id} declares no mcp.credential, " + f"so no client could authenticate against it" + ) + + owner = str(credential.get("owner") or "").strip() + users = lookup_loader.get("users", loader=self._loader, templar=templar).run( + [owner, {}], variables=vars_ + )[0] + + role_credentials = config.run( + [application_id, f"{SECRETS_KEY}.{CREDENTIALS_KEY}", {}], variables=vars_ + )[0] + + token, _owner = resolve_credential( + {"credential": credential}, + {owner: users} if isinstance(users, dict) else {}, + role_credentials if isinstance(role_credentials, dict) else {}, + ) + return [token] diff --git a/plugins/lookup/mcp_credential.py b/plugins/lookup/mcp_credential.py new file mode 100644 index 0000000000..fa0304f3cc --- /dev/null +++ b/plugins/lookup/mcp_credential.py @@ -0,0 +1,75 @@ +"""Read the MCP credential a provider issued, from its declared owner. + +The token lives in the store under the user named by the provider's +``mcp.credential.owner``, keyed by the provider's own ``application_id``. +Spelling that out at each call site repeated the owner resolution, the two +``.get`` fallbacks and the trim in eighteen places, so a role that read it +slightly differently read a different thing. + +Usage: + "{{ lookup('mcp_credential', 'web-app-gitea') }}" + -> the reader token, or "" when none has been issued yet + "{{ lookup('mcp_credential', 'web-app-gitea', 'mcp-writer') }}" + -> the writer token, stored beside it under a role-suffixed key + +An empty string is a valid answer: a provider that has not minted its +credential yet is the normal state early in a play, and the callers +distinguish it from a wrong one by probing. +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.roles.rbac.scoped import MCP_ROLES + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Any]: + terms = list(terms or []) + if len(terms) not in (1, 2) or not str(terms[0]).strip(): + raise AnsibleError( + "mcp_credential: expected the provider's application_id and an " + "optional role, e.g. lookup('mcp_credential', 'web-app-gitea') " + "or lookup('mcp_credential', 'web-app-gitea', 'mcp-writer')" + ) + application_id = str(terms[0]).strip() + role = str(terms[1]).strip() if len(terms) == 2 else "" + if role and role not in MCP_ROLES: + raise AnsibleError( + f"mcp_credential: unknown role {role!r}; expected one of " + f"{list(MCP_ROLES)}. An empty token is a valid answer here, so a " + f"typo would deploy an adapter with no bearer instead of failing." + ) + token_key = f"{application_id}:{role}" if role else application_id + vars_ = variables or getattr(self._templar, "available_variables", {}) or {} + templar = getattr(self, "_templar", None) + + owner = lookup_loader.get("config", loader=self._loader, templar=templar).run( + [application_id, "mcp.credential.owner"], variables=vars_ + )[0] + owner = str(owner or "").strip() + if not owner: + raise AnsibleError( + f"mcp_credential: {application_id} declares no " + f"mcp.credential.owner, so there is no user to read the token from" + ) + + users = lookup_loader.get("users", loader=self._loader, templar=templar).run( + [owner, {}], variables=vars_ + )[0] + if not isinstance(users, dict): + return [""] + tokens = users.get("tokens") + if not isinstance(tokens, dict): + return [""] + return [str(tokens.get(token_key, "") or "").strip()] diff --git a/plugins/lookup/mcp_servers.py b/plugins/lookup/mcp_servers.py new file mode 100644 index 0000000000..8a67782b17 --- /dev/null +++ b/plugins/lookup/mcp_servers.py @@ -0,0 +1,350 @@ +"""Lookup ``mcp_servers``: which MCP servers this client may connect to. + + {{ lookup('mcp_servers') }} + -> {"selected": [...], "rejected": [...]} + +Discovery is an intersection, not a list. A provider names the clients it +admits in ``allowed_consumers``; a client names the transports and auth +schemes it can present. Only a pair that satisfies both, and whose provider +credential actually resolves, reaches ``selected``. + +Everything else lands in ``rejected`` with a stable code: +``consumer_not_allowed``, ``transport_unsupported``, ``auth_unsupported``, +``credential_missing``, ``endpoint_unreachable`` and ``tools_unenforceable``. + +``consumer_not_allowed`` is a decision and simply narrows the result. +``transport_unsupported``, ``auth_unsupported``, ``endpoint_unreachable`` and +``tools_unenforceable`` mean the provider did authorize this consumer and the +connection still cannot be rendered, so they abort the run instead of +disappearing quietly: a client that silently ends up with fewer tools than the +deployment declared is indistinguishable from one that works. + +``tools_unenforceable`` is that same rule applied to the tool policy rather +than the connection. A client filters by tool name, so a provider that resolves +no callable name gives it nothing to pin and the rendered filter would be +empty. That happens two ways, and neither is a working pairing: a surface +composed at runtime keeps its contract in ``tools.categories``, which no +per-tool filter can express, and a surface that withholds every tool it serves +as mutating has nothing left to offer. Advertising either as a configured +server would leave an agent wired to a provider it can never call. + +Providers are narrowed to ``application_closure(deployment.whitelist)``, the same +set ``sys-service-loader`` preloads from. Inventory membership, ``group_names`` +and the raw whitelist all admit roles the run never deploys, and a client then +carries an endpoint nothing is serving. In compose the closure covers everything +present, so only swarm makes the difference visible. + +``credential_missing`` is the one authorized rejection that does not abort, +because a provider deploying later in the same play has not written its secret +yet. That exemption ends at the reconciliation stage, which runs once every +provider has: ``assert_authorized_are_renderable(discovery, strict=True)`` +treats it as fatal there. + +The provider credential is whatever ``mcp.credential`` declares: +``owner`` names the principal, ``source`` where its secret lives +(``token_store`` or the role's own ``credentials``), ``key`` the entry. No +provider inherits the administrator's token. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.manager.credential_key import CREDENTIALS_KEY, SECRETS_KEY +from utils.roles.applications.mcp import DEFAULT_MCP_TRANSPORT, resolve_credential + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + +REJECT_CONSUMER = "consumer_not_allowed" +REJECT_TRANSPORT = "transport_unsupported" +REJECT_AUTH = "auth_unsupported" +REJECT_CREDENTIAL = "credential_missing" +REJECT_ENDPOINT = "endpoint_unreachable" +REJECT_TOOLS = "tools_unenforceable" + +FATAL_REJECTIONS = frozenset( + {REJECT_TRANSPORT, REJECT_AUTH, REJECT_ENDPOINT, REJECT_TOOLS} +) + +RECONCILE_STRICT_VAR = "MCP_RECONCILE_STRICT" + + +def endpoint_url(endpoint: Mapping[str, Any]) -> str: + """Return the URL a client connects to. + + Args: + endpoint: the discovered endpoint mapping. + + Every discovered endpoint authenticates through a header. A provider that + keys its session by URL segment instead cannot scope that segment per + consumer or revoke it, so it is fronted by an adapter and the segment stays + between the adapter and its upstream. + """ + return f"http://{endpoint.get('service_key')}:{endpoint.get('port')}{endpoint.get('path')}" + + +def role_credentials_of( + applications: Mapping[str, Any], role: str +) -> Mapping[str, Any]: + """Return a role's own secrets from the merged applications payload. + + Args: + applications: the merged applications mapping. + role: the provider's application id. + + They live at ``secrets.credentials``, which is where the roles' own vars + and every other consumer address them. Reading the top-level + ``credentials`` instead returns nothing for every provider whose + ``credential.source`` is ``credentials``, and the deploy then aborts on a + secret that was provisioned all along. + """ + return ((applications.get(role) or {}).get(SECRETS_KEY) or {}).get( + CREDENTIALS_KEY + ) or {} + + +def select_deployed( + servers: list[dict[str, Any]] | None, closure: set[str] | None +) -> list[dict[str, Any]]: + """Drop providers this run does not deploy. + + An empty or unresolvable closure filters nothing: discovery that silently + dropped every provider would look exactly like a deployment without any, + which is the failure this module refuses to produce elsewhere. + """ + if not servers: + return list(servers or []) + if not closure: + return list(servers) + return [server for server in servers if server.get("id") in closure] + + +def build_mcp_discovery( + servers: Sequence[Mapping[str, Any]] | None, + consumer_id: str, + consumer: Mapping[str, Any], + credentials: Mapping[str, tuple[str, str]], +) -> dict[str, list[dict[str, Any]]]: + """Return the selected and rejected MCP servers for one client role. + + Args: + servers: ``roles_with_service('mcp', direction='server')`` entries. + consumer_id: ``application_id`` of the client doing the discovery. + consumer: the client's own ``mcp`` block, carrying + ``supported_transports`` and ``supported_auths``. + credentials: resolved ``(token, owner)`` per provider role id. + """ + supported_transports = set(consumer.get("supported_transports") or []) + supported_auths = set(consumer.get("supported_auths") or []) + + selected: list[dict[str, Any]] = [] + rejected: list[dict[str, Any]] = [] + seen_owners: dict[tuple[str, str], str] = {} + + def reject(server_id: str, code: str, detail: str) -> None: + rejected.append({"id": server_id, "reason": code, "detail": detail}) + + for server in servers or []: + server_id = str(server.get("id") or "") + if not server_id or server_id == consumer_id: + continue + + allowed = list(server.get("allowed_consumers") or []) + if consumer_id not in allowed: + reject( + server_id, + REJECT_CONSUMER, + f"{server_id} admits {sorted(allowed)}, not {consumer_id!r}", + ) + continue + + transport = str(server.get("transport") or DEFAULT_MCP_TRANSPORT) + if transport not in supported_transports: + reject( + server_id, + REJECT_TRANSPORT, + f"{server_id} speaks {transport!r}; {consumer_id} speaks " + f"{sorted(supported_transports)}", + ) + continue + + auth = str(server.get("auth") or "") + if auth not in supported_auths: + reject( + server_id, + REJECT_AUTH, + f"{server_id} authenticates with {auth!r}; {consumer_id} can " + f"present {sorted(supported_auths)}", + ) + continue + + token, owner = credentials.get(server_id, ("", "")) + if not token: + reject( + server_id, + REJECT_CREDENTIAL, + f"{server_id} declares owner {owner!r} but no secret resolved; " + f"a provider never borrows the administrator's token", + ) + continue + + previous = seen_owners.get((owner, token)) + if previous is not None: + raise AnsibleError( + f"mcp_servers: {server_id!r} and {previous!r} resolve to the " + f"same credential owned by {owner!r}. Every provider needs its " + f"own principal so revoking one cannot disarm the others." + ) + seen_owners[(owner, token)] = server_id + + endpoint = server.get("endpoint") or {} + if not endpoint.get("port") or not endpoint.get("path"): + reject( + server_id, + REJECT_ENDPOINT, + f"{server_id} resolves no reachable endpoint (port or path missing)", + ) + continue + + tools = list(server.get("tools") or []) + mutating = list(server.get("mutating") or []) + if not [tool for tool in tools if tool not in mutating]: + reject( + server_id, + REJECT_TOOLS, + f"{server_id} serves {len(tools)} tool(s) and withholds " + f"{len(mutating)}, leaving no name a client could pin; " + f"{consumer_id} filters by tool name and would render an " + f"empty filter", + ) + continue + + selected.append( + { + "id": server_id, + "url": endpoint_url(endpoint), + "token": token, + "auth": auth, + "auth_subject": server.get("auth_subject"), + "owner": owner, + "tools": tools, + "mutating": mutating, + "transport": transport.replace("_", "-"), + } + ) + + return {"selected": selected, "rejected": rejected} + + +def assert_authorized_are_renderable( + discovery: Mapping[str, Any], strict: bool = False +) -> None: + """Abort when a provider authorized this consumer but nothing can connect. + + Args: + discovery: the ``{"selected": ..., "rejected": ...}`` result. + strict: also treat ``credential_missing`` as fatal. Its exemption buys + exactly one thing, a provider that deploys later in the same play + and has not written its secret yet. The reconciliation stage runs + after every provider, so there the exemption would only hide a + provider whose credential never resolved at all. + """ + fatal_reasons = FATAL_REJECTIONS | ({REJECT_CREDENTIAL} if strict else set()) + fatal = [ + entry + for entry in discovery.get("rejected") or [] + if entry.get("reason") in fatal_reasons + ] + if not fatal: + return + detail = "; ".join(f"{e['id']}: {e['reason']}: {e['detail']}" for e in fatal) + raise AnsibleError( + f"mcp_servers: {len(fatal)} authorized MCP server(s) cannot be " + f"rendered. {detail}" + ) + + +def resolve_consumer_id(vars_: Mapping[str, Any], templar: Any) -> str: + """Return the ``application_id`` of the client performing the discovery. + + Args: + vars_: the variables in scope for the lookup. + templar: the templar used to render a deferred ``application_id``. + """ + raw = vars_.get("application_id") + if templar is not None and isinstance(raw, str) and "{{" in raw: + raw = templar.template(raw) + consumer_id = str(raw or "").strip() + if not consumer_id: + raise AnsibleError( + "mcp_servers: no application_id in scope. Discovery is a " + "per-consumer intersection, so the calling role must be known." + ) + return consumer_id + + +class LookupModule(LookupBase): + def _deploy_closure(self, templar: Any, vars_: dict[str, Any]) -> set[str]: + """Roles this run deploys, or an empty set when that cannot be resolved.""" + try: + whitelist = lookup_loader.get( + "deployment", loader=self._loader, templar=templar + ).run([], variables=vars_)[0]["whitelist"] + return set( + lookup_loader.get( + "application_closure", loader=self._loader, templar=templar + ).run([whitelist], variables=vars_)[0] + ) + except (AnsibleError, KeyError, IndexError, TypeError): + return set() + + def run( + self, + terms: Sequence[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Any]: + if terms: + raise AnsibleError("mcp_servers: expected no terms, lookup('mcp_servers')") + + vars_ = variables or getattr(self._templar, "available_variables", {}) or {} + templar = getattr(self, "_templar", None) + consumer_id = resolve_consumer_id(vars_, templar) + + servers = lookup_loader.get( + "roles_with_service", loader=self._loader, templar=templar + ).run( + ["mcp"], + variables=vars_, + topic="mcp", + direction="server", + scope="deployment", + )[0] + + servers = select_deployed(servers, self._deploy_closure(templar, vars_)) + + applications = lookup_loader.get( + "applications", loader=self._loader, templar=templar + ).run([], variables=vars_)[0] + users = lookup_loader.get("users", loader=self._loader, templar=templar).run( + [], variables=vars_ + )[0] + + consumer = (applications.get(consumer_id) or {}).get("mcp") or {} + + credentials: dict[str, tuple[str, str]] = {} + for server in servers: + server_id = str(server.get("id") or "") + role_credentials = role_credentials_of(applications, server_id) + credentials[server_id] = resolve_credential(server, users, role_credentials) + + discovery = build_mcp_discovery(servers, consumer_id, consumer, credentials) + assert_authorized_are_renderable( + discovery, strict=bool(vars_.get(RECONCILE_STRICT_VAR)) + ) + return [discovery] diff --git a/plugins/lookup/nfs_fstype.py b/plugins/lookup/nfs_fstype.py index 095fc41fd5..e42ff4793b 100644 --- a/plugins/lookup/nfs_fstype.py +++ b/plugins/lookup/nfs_fstype.py @@ -9,5 +9,4 @@ class LookupModule(LookupBase): """NFS mount fstype (nfs4/nfs): {{ lookup('nfs_fstype') }}.""" def run(self, terms, variables=None, **kwargs): - variables = variables or getattr(self._templar, "available_variables", {}) or {} return [fstype(get_client_version())] diff --git a/plugins/lookup/playwright_workers.py b/plugins/lookup/playwright_workers.py index 0619b0fad6..b4ce595db6 100644 --- a/plugins/lookup/playwright_workers.py +++ b/plugins/lookup/playwright_workers.py @@ -1,17 +1,21 @@ from __future__ import annotations +import contextlib import os from typing import Any from ansible.plugins.lookup import LookupBase +from ansible.template import trust_as_template -from utils.env.runtime import mem_total_mb +from utils.env.runtime import mem_available_mb, mem_total_mb _PER_WORKER_GB = 1.5 _RAM_FRACTION = 0.5 _CPU_DIVISOR = 4 _HARD_CAP = 6 _CI_CAP = 2 +_ONION_FACTOR = 2 +_ONION_CAP = 3 _CI_ENV = ("CI", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "JENKINS_URL") @@ -23,6 +27,18 @@ def _cpu_count() -> int: def _ram_gb() -> float: + """Memory a new worker may actually claim, in GB. + + MemAvailable, not MemTotal: the ceiling exists to stop the sidecar from + competing with what already runs, and on a CI runner the deployed stacks + hold most of the machine by the time the suite starts. Sizing from the + total made the term inert -- it computed five workers on a 16 GB runner + that had 5.5 GB free -- so the CI cap was the only thing ever binding. + Falls back to the total, then to a floor, when /proc does not answer. + """ + available_mb = mem_available_mb() + if available_mb: + return available_mb / 1024 total_mb = mem_total_mb() return total_mb / 1024 if total_mb else 4.0 @@ -36,17 +52,42 @@ def compute_workers( ram_gb: float, ci: bool, *, + onion: bool = False, per_worker_gb: float = _PER_WORKER_GB, ram_fraction: float = _RAM_FRACTION, cpu_divisor: int = _CPU_DIVISOR, hard_cap: int = _HARD_CAP, ci_cap: int = _CI_CAP, + onion_factor: int = _ONION_FACTOR, + onion_cap: int = _ONION_CAP, ) -> int: + """Workers the host can carry, and the transport can use. + + Args: + cpus: usable cores. + ram_gb: memory a worker may claim, taken from what is free rather than + from what the machine has. + ci: whether a CI runner is executing, which lowers the ceiling. + onion: whether the suite reaches its target over Tor. A run against a + `.onion` address waits on circuits rather than on the CPU: measured + on one Nextcloud variant at equal mode and filesystem, the sidecar + took 4817s over Tor against 911s on clearnet, and Tor burns no + browser CPU. The CPU divisor cannot describe that phase, so the + count is raised instead of derived from cores. Raised by a factor + rather than freed, because every worker holds its own circuits. + onion_factor: multiplier applied to the CPU-derived count over Tor. + onion_cap: ceiling for the Tor case, independent of the CI cap. + + Returns: + Worker count, never below one. + """ cpu_workers = max(1, cpus // max(1, cpu_divisor)) ram_workers = max(1, int((ram_gb * ram_fraction) // per_worker_gb)) workers = min(cpu_workers, ram_workers, hard_cap) if ci: workers = min(workers, ci_cap) + if onion: + workers = min(workers * onion_factor, ram_workers, onion_cap) return max(1, workers) @@ -64,16 +105,40 @@ class LookupModule(LookupBase): ram_fraction. """ + def _targets_onion(self, variables: dict[str, Any] | None) -> bool: + """Whether the app under test is reached over a `.onion` address. + + Read from the play rather than from a parameter so a caller cannot + forget it: the transport decides whether the phase is latency-bound, + and the caller that asks for a worker count has no reason to know. + """ + application_id = (variables or {}).get("application_id") + templar = getattr(self, "_templar", None) + if not application_id or templar is None: + return False + with contextlib.suppress(Exception): + application_id = templar.template(application_id) + base = templar.template( + trust_as_template( + "{{ lookup('tls', " + repr(str(application_id)) + ", 'url.base') }}" + ) + ) + return ".onion" in str(base) + return False + def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): return [ compute_workers( _cpu_count(), _ram_gb(), _is_ci(), + onion=bool(kwargs.get("onion", self._targets_onion(variables))), per_worker_gb=float(kwargs.get("per_worker_gb", _PER_WORKER_GB)), ram_fraction=float(kwargs.get("ram_fraction", _RAM_FRACTION)), cpu_divisor=int(kwargs.get("cpu_divisor", _CPU_DIVISOR)), hard_cap=int(kwargs.get("hard_cap", _HARD_CAP)), ci_cap=int(kwargs.get("ci_cap", _CI_CAP)), + onion_factor=int(kwargs.get("onion_factor", _ONION_FACTOR)), + onion_cap=int(kwargs.get("onion_cap", _ONION_CAP)), ) ] diff --git a/plugins/lookup/postgres_libraries.py b/plugins/lookup/postgres_libraries.py index 161b4ac391..45b9f74bbf 100644 --- a/plugins/lookup/postgres_libraries.py +++ b/plugins/lookup/postgres_libraries.py @@ -9,7 +9,8 @@ custom library install on top of the postgis/postgis base image filtered out). Each returned entry is a dict with: - extension: the extension name (matches the SQL identifier) - name: the library/source name (used in the Dockerfile context) - - git_source: the upstream git repository to clone and build from + - apt_package: the PGDG package suffix, installed as + postgresql-- """ from __future__ import annotations @@ -26,7 +27,7 @@ if TYPE_CHECKING: _REGISTRY: dict[str, dict[str, str]] = { "vector": { "name": "pgvector", - "git_source": "https://github.com/pgvector/pgvector.git", + "apt_package": "pgvector", }, } diff --git a/plugins/lookup/redirect_uris.py b/plugins/lookup/redirect_uris.py index 17553b5ed2..ea32ad684f 100644 --- a/plugins/lookup/redirect_uris.py +++ b/plugins/lookup/redirect_uris.py @@ -57,8 +57,9 @@ def build_redirect_uris( wildcard: str = DEFAULT_WILDCARD, features: Iterable[str] = DEFAULT_FEATURES, dedup: bool = True, + deployed: Iterable[str] | None = None, ) -> list[str]: - """Registered redirect URIs for every SSO consumer, one per domain. + """Registered redirect URIs for every deployed SSO consumer, one per domain. Args: domains: app_id -> domain, list of domains, or nested mapping of those. @@ -69,14 +70,19 @@ def build_redirect_uris( wildcard: suffix appended to every URI. features: config paths ORed together to decide whether an app gets a URI. dedup: drop repeated URIs, preserving first-seen order. + deployed: application ids this play deploys (``group_names``); an app + outside it gets no URI. None registers every app in ``domains``. """ if not isinstance(domains, dict): raise AnsibleError( "redirect_uris: 'domains' must be a dict mapping app_id -> domain or list of domains" ) + deployed_ids = None if deployed is None else set(deployed) uris: list[str] = [] for app_id, domain_value in domains.items(): + if deployed_ids is not None and app_id not in deployed_ids: + continue try: has_feature = any( bool(get(applications, app_id, f, False)) for f in features @@ -113,9 +119,10 @@ class LookupModule(LookupBase): {{ lookup('redirect_uris', wildcard='/cb') }} Returns the redirect URIs Keycloak must whitelist: one per domain of every - application whose config enables SSO. Each URI's scheme is resolved for the - CONSUMER -- its own ``server.tls.enabled`` over the global ``TLS_ENABLED``, - and always plaintext for an .onion -- never from Keycloak's own TLS state. + application this play deploys (``group_names``) whose config enables SSO. + Each URI's scheme is resolved for the CONSUMER -- its own + ``server.tls.enabled`` over the global ``TLS_ENABLED``, and always + plaintext for an .onion -- never from Keycloak's own TLS state. - parameters: wildcard: suffix appended to every URI (default '/*') @@ -135,6 +142,8 @@ class LookupModule(LookupBase): variables = variables or getattr(self._templar, "available_variables", {}) or {} if "TLS_ENABLED" not in variables: raise AnsibleError("redirect_uris: TLS_ENABLED is not defined.") + if "group_names" not in variables: + raise AnsibleError("redirect_uris: group_names is not defined.") loader = getattr(self, "_loader", None) templar = getattr(self, "_templar", None) @@ -154,5 +163,6 @@ class LookupModule(LookupBase): wildcard=kwargs.get("wildcard", DEFAULT_WILDCARD), features=features, dedup=bool(kwargs.get("dedup", True)), + deployed=variables["group_names"], ) ] diff --git a/plugins/lookup/role_subnets.py b/plugins/lookup/role_subnets.py new file mode 100644 index 0000000000..b3a06976a1 --- /dev/null +++ b/plugins/lookup/role_subnets.py @@ -0,0 +1,64 @@ +"""Lookup `role_subnets`: the local subnets other roles declare. + +Single SPOT for "which address block does role X own". The block is declared +once, in that role's ``meta/networks.yml``; anything that has to reason about +the deployment's own address space reads it from here instead of repeating the +literal, which is how a CIDR ends up stated twice and then drifts. + +Usage: + + {{ lookup('role_subnets', 'web-app-bigbluebutton') }} # ['10.7.7.0/24'] + {{ lookup('role_subnets', SOME_ROLE_LIST) }} # one entry per role + +Terms may be role ids or lists of them, mixed. A role that declares no local +subnet raises, because a silently dropped entry would narrow whatever firewall +or trust list consumes the result. +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +_SUBNET_PATH = "networks.local.subnet" + + +def _flattened(terms: list[Any]) -> list[str]: + roles: list[str] = [] + for term in terms: + if isinstance(term, (list, tuple)): + roles.extend(str(entry).strip() for entry in term) + else: + roles.append(str(term).strip()) + return [role for role in roles if role] + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Any]: + roles = _flattened(terms or []) + if not roles: + raise AnsibleError( + "lookup('role_subnets', ) expects " + "at least one role id" + ) + config = lookup_loader.get( + "config", + loader=getattr(self, "_loader", None), + templar=getattr(self, "_templar", None), + ) + subnets: list[str] = [] + for role in roles: + value = config.run([role, _SUBNET_PATH], variables=variables)[0] + text = "" if value is None else str(value).strip() + if not text: + raise AnsibleError(f"role_subnets: '{role}' declares no {_SUBNET_PATH}") + subnets.append(text) + return [subnets] diff --git a/plugins/lookup/roles_with_service.py b/plugins/lookup/roles_with_service.py index e7781ddf7f..7c1001640e 100644 --- a/plugins/lookup/roles_with_service.py +++ b/plugins/lookup/roles_with_service.py @@ -17,6 +17,23 @@ symmetric matomo opt-out: static-file (autoindex) and 301-redirect vhosts that declare ``services.matomo`` keep the role-wiring intact but carry no user-facing HTML page worth a ``_paq`` tracker, so they are dropped from ``MATOMO_TARGET_ROLES_JSON`` and the matomo tracker e2e contract. + +Kwargs: + scope: ``host`` (default) restricts to roles in ``group_names``; + ``deployment`` restricts to roles present anywhere in ``groups``, + which is what a container-network consumer can actually reach; + ``all`` returns every declaring role, deployed or not. + direction: opt-in MCP filter. When set (``server``/``client``/``both``), + only roles whose block declares that ``direction`` (or ``both``) + are returned, and each entry additionally carries ``transport``, + ``auth``, ``auth_subject``, ``credential`` (``owner``/``source``/ + ``key``), ``allowed_consumers``, ``supported_transports``, + ``supported_auths`` and an ``endpoint`` dict + (``service_key``, ``path``, ``port`` taken from the + referenced service's ``ports.internal`` and only then ``ports.local``: + the entry is consumed to build a container-network URL, where a + host-published port is always the wrong one). + Callers that omit ``direction`` keep the original 4-key entries. """ from __future__ import annotations @@ -27,23 +44,65 @@ from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase +from utils.domains.primary_domain import get_primary_domain +from utils.roles.applications.mcp import ( + DEFAULT_MCP_TRANSPORT, + derive_allowed_consumers, +) from utils.roles.entity.name import get_entity_name if TYPE_CHECKING: from collections.abc import Sequence -def _resolve_canonical_domain(app_config: dict[str, Any]) -> str: +def _resolve_endpoint_port( + services: dict[str, Any], endpoint: dict[str, Any] +) -> int | None: + service_key = endpoint.get("service_key") + port_key = endpoint.get("port_key") + if not service_key or not port_key: + return None + target = services.get(str(service_key)) + if not isinstance(target, dict): + return None + ports = target.get("ports") + if not isinstance(ports, dict): + return None + for namespace in ("internal", "local"): + ns = ports.get(namespace) + if isinstance(ns, dict) and port_key in ns: + try: + return int(ns[port_key]) + except (TypeError, ValueError): + return None + return None + + +def _resolve_canonical_domain(role_id: str, app_config: dict[str, Any]) -> str: domains = app_config.get("domains") - if not isinstance(domains, dict): + if not isinstance(domains, dict) or not domains.get("canonical"): return "" - canonical = domains.get("canonical") - if isinstance(canonical, list) and canonical: - first = canonical[0] - return str(first) if first else "" - if isinstance(canonical, str): - return canonical - return "" + return get_primary_domain({role_id: domains["canonical"]}, role_id) + + +def _deployed_roles(scope: str, vars_: dict[str, Any]) -> set[str] | None: + """Return the role ids the scope admits, or None for no restriction. + + Args: + scope: ``host``, ``deployment`` or ``all``. + vars_: the templating variables, carrying ``group_names``/``groups``. + """ + if scope == "all": + return None + if scope == "deployment": + groups = vars_.get("groups") + if not isinstance(groups, dict): + return None + return {str(name) for name, hosts in groups.items() if hosts} + names = vars_.get("group_names") + if not isinstance(names, (list, tuple, set)) or not names: + return None + return {str(name) for name in names} class LookupModule(LookupBase): @@ -68,26 +127,32 @@ class LookupModule(LookupBase): "applications", loader=self._loader, templar=getattr(self, "_templar", None) ).run([], variables=vars_)[0] + services_by_role = { + role_id: config.get("services") + for role_id, config in applications.items() + if isinstance(config, dict) + } + scope = str(kwargs.get("scope", "host")).strip().lower() - gn = vars_.get("group_names") - deployed = ( - {str(g) for g in gn} - if scope != "all" and isinstance(gn, (list, tuple, set)) and gn - else None + topic = kwargs.get("topic") + direction_raw = kwargs.get("direction") + direction = ( + str(direction_raw).strip().lower() if direction_raw is not None else None ) + deployed = _deployed_roles(scope, vars_) tls_lookup = lookup_loader.get( "tls", loader=self._loader, templar=self._templar ) - results: list[dict[str, str]] = [] + results: list[dict[str, Any]] = [] for role_id, app_config in applications.items(): if not isinstance(app_config, dict): continue services = app_config.get("services") if not isinstance(services, dict): - continue - block = services.get(service_name) + services = {} + block = app_config.get(topic) if topic else services.get(service_name) if not isinstance(block, dict): continue if not bool(block.get("enabled")): @@ -98,28 +163,70 @@ class LookupModule(LookupBase): continue if block.get("track") is False: continue + if direction is not None: + block_direction = str(block.get("direction") or "").strip().lower() + if block_direction not in (direction, "both"): + continue if deployed is not None and str(role_id) not in deployed: continue if get_entity_name(str(role_id)) == service_name: continue - canonical = _resolve_canonical_domain(app_config) - if not canonical: + canonical = _resolve_canonical_domain(str(role_id), app_config) + if not canonical and direction is None: continue - resolved = tls_lookup.run([str(role_id), "url.base"], variables=variables) - canonical_url = str(resolved[0]).rstrip("/") + canonical_url = "" + if canonical: + resolved = tls_lookup.run( + [str(role_id), "url.base"], variables=variables + ) + canonical_url = str(resolved[0]).rstrip("/") iframe = ( bool(block["iframe"]) if "iframe" in block else bool(block.get("enabled")) ) - results.append( - { - "id": str(role_id), - "canonical_domain": canonical, - "canonical_url": canonical_url, - "iframe": iframe, + entry: dict[str, Any] = { + "id": str(role_id), + "canonical_domain": canonical, + "canonical_url": canonical_url, + "iframe": iframe, + } + if direction is not None: + endpoint = block.get("endpoint") + endpoint = endpoint if isinstance(endpoint, dict) else {} + credential = block.get("credential") + credential = credential if isinstance(credential, dict) else {} + entry["transport"] = str( + block.get("transport") or DEFAULT_MCP_TRANSPORT + ) + entry["auth"] = block.get("auth") + entry["auth_subject"] = block.get("auth_subject") + entry["credential"] = { + "owner": credential.get("owner"), + "source": credential.get("source"), + "key": credential.get("key"), } - ) + entry["allowed_consumers"] = derive_allowed_consumers( + str(role_id), services_by_role + ) + tools = block.get("tools") + tools = tools if isinstance(tools, dict) else {} + entry["tools"] = list(tools.get("allowlist") or []) + entry["mutating"] = ( + [] + if tools.get("mutating_tools_enabled") + else list(tools.get("mutating") or []) + ) + entry["supported_transports"] = list( + block.get("supported_transports") or [] + ) + entry["supported_auths"] = list(block.get("supported_auths") or []) + entry["endpoint"] = { + "service_key": endpoint.get("service_key"), + "path": endpoint.get("path"), + "port": _resolve_endpoint_port(services, endpoint), + } + results.append(entry) results.sort(key=lambda r: r["id"]) return [results] diff --git a/plugins/lookup/sso.py b/plugins/lookup/sso.py index 98455fb33d..3aa8dfd9f5 100644 --- a/plugins/lookup/sso.py +++ b/plugins/lookup/sso.py @@ -8,6 +8,8 @@ API (STRICT): - {{ lookup('sso', application_id, 'flavor') }} โ†’ str - {{ lookup('sso', application_id, 'enabled') }} โ†’ bool - {{ lookup('sso', application_id, 'shared') }} โ†’ bool + - {{ lookup('sso', application_id, 'logout_url') }} โ†’ str, oauth2-proxy + sign-out wrapping OIDC.CLIENT.LOGOUT_URL when the app is proxy-gated Wraps ``utils.roles.applications.services.sso.get_sso_config`` so templates and tasks share one source of truth with Python callers @@ -22,7 +24,7 @@ from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase -from utils.roles.applications.services.sso import get_sso_config +from utils.roles.applications.services.sso import get_sso_config, logout_url class LookupModule(LookupBase): @@ -51,6 +53,17 @@ class LookupModule(LookupBase): resolved = get_sso_config(applications, application_id) + if want == "logout_url": + if "OIDC" not in vars_: + raise AnsibleError( + "sso: 'logout_url' needs OIDC in the templating context" + ) + oidc = self._templar.template(vars_["OIDC"]) + return [ + logout_url( + str(oidc["CLIENT"]["LOGOUT_URL"]), bool(resolved["is_proxy_gated"]) + ) + ] if want == "all": return [resolved] if want not in resolved: diff --git a/plugins/lookup/sso_oidc_plugin.py b/plugins/lookup/sso_oidc_plugin.py index 3e895dffc2..50c293009c 100644 --- a/plugins/lookup/sso_oidc_plugin.py +++ b/plugins/lookup/sso_oidc_plugin.py @@ -6,9 +6,6 @@ from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase -from utils.roles.applications.config import get -from utils.roles.applications.services.sso import get_sso_config - _APPLICATION_ID = "web-app-nextcloud" @@ -40,33 +37,18 @@ class LookupModule(LookupBase): templar = getattr(self, "_templar", None) variables = variables or getattr(self._templar, "available_variables", {}) or {} - applications = lookup_loader.get( - "applications", loader=self._loader, templar=templar - ).run([], variables=variables)[0] + config = lookup_loader.get("config", loader=self._loader, templar=templar) - if not get_sso_config(applications, _APPLICATION_ID)["is_enabled"]: + def _setting(path: str, default: Any) -> Any: + return config.run([_APPLICATION_ID, path, default], variables=variables)[0] + + if not bool(_setting("services.sso.enabled", False)): return [""] - explicit = get( - applications=applications, - application_id=_APPLICATION_ID, - config_path="services.sso.oidc.plugin", - strict=False, - default=None, - skip_missing_app=True, - ) + explicit = _setting("services.sso.oidc.plugin", None) if isinstance(explicit, str) and explicit.strip(): return [explicit.strip()] - ldap_enabled = bool( - get( - applications=applications, - application_id=_APPLICATION_ID, - config_path="services.ldap.enabled", - strict=False, - default=False, - skip_missing_app=True, - ) - ) + ldap_enabled = bool(_setting("services.ldap.enabled", False)) return ["oidc_login" if ldap_enabled else "sociallogin"] diff --git a/plugins/lookup/tor_ports.py b/plugins/lookup/tor_ports.py index 4c20823d9e..fea32575f8 100644 --- a/plugins/lookup/tor_ports.py +++ b/plugins/lookup/tor_ports.py @@ -1,19 +1,18 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any - -if TYPE_CHECKING: - from pathlib import Path +from typing import Any from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase -from utils.cache.base import _resolve_roles_dir -from utils.cache.yaml import load_yaml_any -from utils.roles.mapping import ROLE_FILE_META_SERVICES +UDP_ONLY_CATEGORIES = frozenset({"relay", "media", "stun_turn", "stun_turn_tls"}) +"""Categories a hidden service cannot carry. -_UDP_ONLY_CATEGORIES = frozenset({"relay", "media"}) +``relay`` and ``media`` are UDP. ``stun_turn`` and its TLS variant do speak TCP, +but the allocation they hand out is a UDP relay address the onion client can +never receive on, so forwarding the signalling port buys nothing. +""" def _as_bool(value: object) -> bool: @@ -24,76 +23,47 @@ def _as_bool(value: object) -> bool: return bool(value) -def _collect_group_tcp_ports(port_categories: Any, group: str, into: set[int]) -> None: - """Add single-int TCP ports of one ``ports.`` category group. +def _mapping(value: object) -> dict[str, Any]: + return value if isinstance(value, dict) else {} - ``exposed: true`` collects ``local`` only: an exposed service publishes just - its local plaintext port to 127.0.0.1, so the onion HiddenServicePort must - target that; forwarding its ``public`` TLS port (e.g. ldaps 636) would be a - dead loopback target (nothing listens there in the exposed variant) and - plaintext-into-TLS. ``exposed: public`` collects ``public`` instead, for a - service whose protocol ports genuinely bind the host (the active mail - provider's 25/465/993/...) and should ride the node onion as-is. - """ + +def _collect_local_tcp_ports(port_categories: Any, into: set[int]) -> None: + """Add single-int TCP ports of the loopback-published ``ports.local`` group + only. An exposed service publishes just its local plaintext port to + 127.0.0.1, so the onion HiddenServicePort must target that; forwarding a + ``public`` TLS port (e.g. ldaps 636) would be a dead loopback target (nothing + listens there in the exposed variant) and plaintext-into-TLS.""" if not isinstance(port_categories, dict): return - entries = port_categories.get(group) - if not isinstance(entries, dict): + local = port_categories.get("local") + if not isinstance(local, dict): return - for category, value in entries.items(): - if category in _UDP_ONLY_CATEGORIES: + for category, value in local.items(): + if category in UDP_ONLY_CATEGORIES: continue if isinstance(value, int): into.add(value) -def collect_public_ports( - deployed_roles: list[str], - roles_dir: Path, -) -> list[int]: - """Single-int TCP ``ports.public`` entries of the deployed roles, sorted.""" - ports: set[int] = set() - for role in deployed_roles: - services_yml = roles_dir / role / ROLE_FILE_META_SERVICES - if not services_yml.is_file(): - continue - data = load_yaml_any(str(services_yml), default_if_missing={}) - if not isinstance(data, dict): - continue - tor = data.get("tor") - if not (isinstance(tor, dict) and _as_bool(tor.get("enabled"))): - continue - for entity in data.values(): - if not isinstance(entity, dict): - continue - public = (entity.get("ports") or {}).get("public") - if not isinstance(public, dict): - continue - for category, value in public.items(): - if category in _UDP_ONLY_CATEGORIES: - continue - if isinstance(value, int): - ports.add(value) - return sorted(ports) - - -def collect_exposed_ports( +def collect_onion_ports( applications: dict[str, Any], deployed_roles: list[str], ) -> list[int]: - """Single-int TCP ports of every deployed service flagged ``exposed: true`` - in the variant-merged ``applications`` view, sorted. + """Single-int TCP ports a deployed role asks for by name under ``ports.onion``. - ``exposed`` is an explicit per-service opt-in (default false) that makes the - service reachable over the node onion: its port gets a dedicated - ``HiddenServicePort``. ``exposed: true`` forwards the service's ``ports.local`` - group; ``exposed: public`` forwards ``ports.public`` instead, for a service - whose protocol ports bind the host directly (the active mail provider). - Because ``applications`` is the variant-merged config (base - ``meta/services.yml`` deep-merged with the round's ``meta/variants.yml`` - override), a service is forwarded only in the variant/config where it sets - the flag โ€” which is exactly what lets the two DB variants be tested over Tor - (v0 exposed -> reachable, v1 not -> refused). + ``ports.onion`` is a category-keyed map of booleans alongside ``internal`` / + ``local`` / ``public``: it names which of a service's already-declared ports + should answer on the node onion, and nothing else. The port number comes + from ``ports.local`` when that category is declared there and from + ``ports.public`` otherwise, which is the precedence ``container_ports`` + publishes by, so the forward always targets the port the service is actually + reachable on. + + Naming the category is what makes this safe. Sweeping ``ports.public`` + wholesale forwards ports the deployment never publishes -- ldaps 636 is + declared next to ``network.public: false``, and Mailu's implicit-TLS ports + are dropped from the publish list whenever TLS is off, which an onion + deployment always is. """ ports: set[int] = set() deployed = set(deployed_roles) @@ -108,11 +78,52 @@ def collect_exposed_ports( for entity in services.values(): if not isinstance(entity, dict): continue - exposed = entity.get("exposed") - if isinstance(exposed, str) and exposed.strip().lower() == "public": - _collect_group_tcp_ports(entity.get("ports"), "public", ports) - elif _as_bool(exposed): - _collect_group_tcp_ports(entity.get("ports"), "local", ports) + declared = entity.get("ports") + if not isinstance(declared, dict): + continue + wanted = declared.get("onion") + if not isinstance(wanted, dict): + continue + local = _mapping(declared.get("local")) + public = _mapping(declared.get("public")) + for category, flag in wanted.items(): + if category in UDP_ONLY_CATEGORIES or not _as_bool(flag): + continue + value = local.get(category, public.get(category)) + if isinstance(value, int): + ports.add(value) + return sorted(ports) + + +def collect_exposed_ports( + applications: dict[str, Any], + deployed_roles: list[str], +) -> list[int]: + """Single-int TCP ports of every deployed service flagged ``exposed: true`` + in the variant-merged ``applications`` view, sorted. + + ``exposed`` is an explicit per-service opt-in (default false) that makes the + service reachable over the node onion: its port gets a dedicated + ``HiddenServicePort``. Because ``applications`` is the variant-merged config + (base ``meta/services.yml`` deep-merged with the round's ``meta/variants.yml`` + override), a service is forwarded only in the variant/config where it sets + ``exposed: true`` โ€” which is exactly what lets the two DB variants be tested + over Tor (v0 exposed -> reachable, v1 not -> refused). + """ + ports: set[int] = set() + deployed = set(deployed_roles) + if not isinstance(applications, dict): + return [] + for app_id, cfg in applications.items(): + if app_id not in deployed: + continue + services = (cfg or {}).get("services") if isinstance(cfg, dict) else None + if not isinstance(services, dict): + continue + for entity in services.values(): + if not isinstance(entity, dict) or not _as_bool(entity.get("exposed")): + continue + _collect_local_tcp_ports(entity.get("ports"), ports) return sorted(ports) @@ -123,17 +134,18 @@ class LookupModule(LookupBase): Returns the HiddenServicePort mappings for the roles in the current deploy (``group_names``): a list of ``{'onion_port': , 'target': - '127.0.0.1:'}`` dicts, sorted by port. Two sources are unioned: + '127.0.0.1:'}`` dicts, sorted by port. Two opt-ins are unioned: - * every ``ports.public`` TCP port of tor-enabled roles, and - * every port of a service that opts in with ``exposed`` (resolved against - the variant-merged applications view, so per-variant): ``true`` forwards - its ``ports.local`` group, ``public`` its ``ports.public`` group. + * every port a service names under ``ports.onion`` in meta/services.yml, + and + * every port of a service that opts in with ``exposed: true``. - Public/exposed ports bind the host interface, so the loopback target reaches - them from svc-net-tor's host-network container. Consumed by - ``TOR_ONION_EXTRA_PORTS`` (group_vars/all/19_tor.yml) and rendered as - ``HiddenServicePort`` lines in svc-net-tor's torrc. + Both are read from the variant-merged applications view, so a variant that + drops the opt-in drops the forward with it. The published port binds the + host interface, so the loopback target reaches it from svc-net-tor's + host-network container. Composed with the flagged forwards by + ``lookup('tor_extra_ports')`` and rendered as ``HiddenServicePort`` lines in + svc-net-tor's torrc. """ def run( @@ -151,17 +163,15 @@ class LookupModule(LookupBase): group_names = [] deployed = [str(g) for g in group_names] - roles_dir = _resolve_roles_dir(roles_dir=kwargs.get("roles_dir")) - ports = set(collect_public_ports(deployed, roles_dir)) - try: applications = lookup_loader.get( "applications", loader=getattr(self, "_loader", None), templar=getattr(self, "_templar", None), ).run([], variables=variables, roles_dir=kwargs.get("roles_dir"))[0] - except Exception: # noqa: BLE001 no merged view -> exposed ports simply unavailable + except Exception: # noqa: BLE001 no merged view -> no ports to forward applications = {} + ports = set(collect_onion_ports(applications, deployed)) ports.update(collect_exposed_ports(applications, deployed)) return [ diff --git a/pyproject.toml b/pyproject.toml index 606ff87fab..a20ef2df66 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "infinito-nexus" -version = "13.0.0" +version = "14.0.0" description = "Infinito.Nexus" readme = "README.md" requires-python = ">=3.11" diff --git a/requirements/requirements.galaxy.yml b/requirements/requirements.galaxy.yml index 33ae9d1493..99944bdf14 100644 --- a/requirements/requirements.galaxy.yml +++ b/requirements/requirements.galaxy.yml @@ -1,9 +1,16 @@ --- collections: - name: ansible.posix - - name: kewlfft.aur - - name: community.general - - name: community.docker - - name: hetzner.hcloud - - name: ansible.posix + version: 2.2.2 - name: ansible.mysql + version: 5.2.0 + - name: kewlfft.aur + version: 0.13.0 + - name: community.general + version: 13.4.0 + - name: community.docker + version: 5.3.0 + - name: community.library_inventory_filtering_v1 + version: 1.1.5 + - name: hetzner.hcloud + version: 7.0.1 diff --git a/requirements/requirements.git.yml b/requirements/requirements.git.yml index 31ddb7279d..5e6b9eaf0e 100644 --- a/requirements/requirements.git.yml +++ b/requirements/requirements.git.yml @@ -3,34 +3,34 @@ collections: - name: ansible.posix source: https://github.com/ansible-collections/ansible.posix.git type: git - version: main + version: 2.2.2 - name: ansible.mysql source: https://github.com/ansible-collections/ansible.mysql.git type: git - version: main + version: 5.2.0 - name: kewlfft.aur source: https://github.com/kewlfft/ansible-aur.git type: git - version: master + version: 7affd00193b03bf820ebcd8b13dfa81aab59803e - name: community.general source: https://github.com/ansible-collections/community.general.git type: git - version: main + version: 13.4.0 - name: community.docker source: https://github.com/ansible-collections/community.docker.git type: git - version: main + version: 5.3.0 - name: community.library_inventory_filtering_v1 source: https://github.com/ansible-collections/community.library_inventory_filtering.git type: git - version: stable-1 + version: 1.1.5 - name: hetzner.hcloud source: https://github.com/ansible-collections/hetzner.hcloud.git type: git - version: main + version: 7.0.1 diff --git a/roles/desk-bluray-player/README.md b/roles/desk-bluray-player/README.md index fcbc1ab2ad..4cf6bedf0c 100644 --- a/roles/desk-bluray-player/README.md +++ b/roles/desk-bluray-player/README.md @@ -62,7 +62,7 @@ make compose-deploy mode=reinstall apps=desk-bluray-player full_cycle=false ### Production -Install Blue-ray Disc directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Blue-ray Disc directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -72,6 +72,7 @@ make install source scripts/meta/env/load.sh APP=desk-bluray-player +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -79,7 +80,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-bluray-player/meta/info.yml b/roles/desk-bluray-player/meta/info.yml index 2874e48491..c0bed11c7c 100644 --- a/roles/desk-bluray-player/meta/info.yml +++ b/roles/desk-bluray-player/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://www.videolan.org/vlc/ diff --git a/roles/desk-bluray-player/meta/main.yml b/roles/desk-bluray-player/meta/main.yml index c0a4fc2576..d31b477e80 100644 --- a/roles/desk-bluray-player/meta/main.yml +++ b/roles/desk-bluray-player/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Desktop media-player setup with VLC and AACS/BD+ libraries for Blu-ray disc decryption and playback on Arch Linux diff --git a/roles/desk-chromium/README.md b/roles/desk-chromium/README.md index d4f0e1bb20..c3ba4428aa 100644 --- a/roles/desk-chromium/README.md +++ b/roles/desk-chromium/README.md @@ -48,7 +48,7 @@ make compose-deploy mode=reinstall apps=desk-chromium full_cycle=false ### Production -Install Chromium directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Chromium directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -58,6 +58,7 @@ make install source scripts/meta/env/load.sh APP=desk-chromium +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -65,7 +66,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-chromium/meta/info.yml b/roles/desk-chromium/meta/info.yml index cdf93b6d18..11abf2a739 100644 --- a/roles/desk-chromium/meta/info.yml +++ b/roles/desk-chromium/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://www.chromium.org/ diff --git a/roles/desk-chromium/meta/main.yml b/roles/desk-chromium/meta/main.yml index efa69af057..1ad427ead3 100644 --- a/roles/desk-chromium/meta/main.yml +++ b/roles/desk-chromium/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Hardened desktop web browser with enforced privacy and password-manager extensions via Enterprise Policies diff --git a/roles/desk-copyq/README.md b/roles/desk-copyq/README.md index a3308c7283..5dee8ba69f 100644 --- a/roles/desk-copyq/README.md +++ b/roles/desk-copyq/README.md @@ -40,7 +40,7 @@ make compose-deploy mode=reinstall apps=desk-copyq full_cycle=false ### Production -Install CopyQ directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install CopyQ directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -50,6 +50,7 @@ make install source scripts/meta/env/load.sh APP=desk-copyq +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -57,7 +58,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-copyq/meta/info.yml b/roles/desk-copyq/meta/info.yml index c0f5897392..90ddee1b98 100644 --- a/roles/desk-copyq/meta/info.yml +++ b/roles/desk-copyq/meta/info.yml @@ -1,4 +1,5 @@ --- +# nocheck: info-media no official demo video logo: class: fa fa-clipboard homepage: https://hluk.github.io/CopyQ/ diff --git a/roles/desk-copyq/meta/main.yml b/roles/desk-copyq/meta/main.yml index a6a8a57a25..6f17666542 100644 --- a/roles/desk-copyq/meta/main.yml +++ b/roles/desk-copyq/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Clipboard manager with editable history, custom actions, and scripting support diff --git a/roles/desk-docker/README.md b/roles/desk-docker/README.md index c86c0bdccb..0a3ce58367 100644 --- a/roles/desk-docker/README.md +++ b/roles/desk-docker/README.md @@ -44,7 +44,7 @@ make compose-deploy mode=reinstall apps=desk-docker full_cycle=false ### Production -Install Workstation Docker directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Workstation Docker directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -54,6 +54,7 @@ make install source scripts/meta/env/load.sh APP=desk-docker +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -61,7 +62,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-docker/meta/info.yml b/roles/desk-docker/meta/info.yml index be93753e42..72c7a0525e 100644 --- a/roles/desk-docker/meta/info.yml +++ b/roles/desk-docker/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://www.docker.com/ diff --git a/roles/desk-docker/meta/main.yml b/roles/desk-docker/meta/main.yml index d4a11b5212..013a889d77 100644 --- a/roles/desk-docker/meta/main.yml +++ b/roles/desk-docker/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Workstation setup for Docker and Docker Compose with the local user in the docker group for rootless development use diff --git a/roles/desk-dotlinker/README.md b/roles/desk-dotlinker/README.md index 31d57b9345..384e8e5616 100644 --- a/roles/desk-dotlinker/README.md +++ b/roles/desk-dotlinker/README.md @@ -44,7 +44,7 @@ make compose-deploy mode=reinstall apps=desk-dotlinker full_cycle=false ### Production -Install Dotlinker directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Dotlinker directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -54,6 +54,7 @@ make install source scripts/meta/env/load.sh APP=desk-dotlinker +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -61,7 +62,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-dotlinker/meta/info.yml b/roles/desk-dotlinker/meta/info.yml new file mode 100644 index 0000000000..d96ebcba59 --- /dev/null +++ b/roles/desk-dotlinker/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written generic dotfile-linking glue role wrapping the author's own doli/dotlinker CLI; no consumer-facing third-party product website. diff --git a/roles/desk-dotlinker/meta/main.yml b/roles/desk-dotlinker/meta/main.yml index e379aa86b5..2c05996751 100644 --- a/roles/desk-dotlinker/meta/main.yml +++ b/roles/desk-dotlinker/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written generic dotfile-linking glue role wrapping the author's own doli/dotlinker CLI; no consumer-facing third-party product website. galaxy_info: author: Kevin Veen-Birkenbach description: Generic role installing the doli CLI and applying dotfile symlink mappings passed in by other roles diff --git a/roles/desk-firefox/README.md b/roles/desk-firefox/README.md index dc9e60b2fc..a97d6303c6 100644 --- a/roles/desk-firefox/README.md +++ b/roles/desk-firefox/README.md @@ -47,7 +47,7 @@ make compose-deploy mode=reinstall apps=desk-firefox full_cycle=false ### Production -Install Firefox directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Firefox directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -57,6 +57,7 @@ make install source scripts/meta/env/load.sh APP=desk-firefox +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -64,7 +65,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-git/README.md b/roles/desk-git/README.md index a5b4697c8f..e3bc8c7ab4 100644 --- a/roles/desk-git/README.md +++ b/roles/desk-git/README.md @@ -51,7 +51,7 @@ make compose-deploy mode=reinstall apps=desk-git full_cycle=false ### Production -Install Git directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Git directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -61,6 +61,7 @@ make install source scripts/meta/env/load.sh APP=desk-git +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -68,7 +69,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-git/meta/info.yml b/roles/desk-git/meta/info.yml index 2bd6944baf..969ad62ec3 100644 --- a/roles/desk-git/meta/info.yml +++ b/roles/desk-git/meta/info.yml @@ -1,3 +1,3 @@ --- homepage: https://git-scm.com/ -video: https://git-scm.com/video/what-is-version-control +video: https://www.youtube.com/watch?v=5eDdEn9Qqa8 diff --git a/roles/desk-gnome-caffeine/README.md b/roles/desk-gnome-caffeine/README.md index e65bab1b98..2bc12068da 100644 --- a/roles/desk-gnome-caffeine/README.md +++ b/roles/desk-gnome-caffeine/README.md @@ -47,7 +47,7 @@ make compose-deploy mode=reinstall apps=desk-gnome-caffeine full_cycle=false ### Production -Install GNOME Caffeine directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install GNOME Caffeine directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -57,6 +57,7 @@ make install source scripts/meta/env/load.sh APP=desk-gnome-caffeine +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -64,7 +65,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-gnome-caffeine/meta/info.yml b/roles/desk-gnome-caffeine/meta/info.yml index e04121a4e7..db8be29daa 100644 --- a/roles/desk-gnome-caffeine/meta/info.yml +++ b/roles/desk-gnome-caffeine/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://codeberg.org/WhyNotHugo/caffeine-ng diff --git a/roles/desk-gnome-caffeine/meta/main.yml b/roles/desk-gnome-caffeine/meta/main.yml index 4728665ece..18963a6727 100644 --- a/roles/desk-gnome-caffeine/meta/main.yml +++ b/roles/desk-gnome-caffeine/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Desktop utility for inhibiting screen blanking and sleep, autostarted on the GNOME desktop diff --git a/roles/desk-gnome-extensions/README.md b/roles/desk-gnome-extensions/README.md index 23ee3350ce..9fb409b7e9 100644 --- a/roles/desk-gnome-extensions/README.md +++ b/roles/desk-gnome-extensions/README.md @@ -49,7 +49,7 @@ make compose-deploy mode=reinstall apps=desk-gnome-extensions full_cycle=false ### Production -Install GNOME Extensions Manager directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install GNOME Extensions Manager directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -59,6 +59,7 @@ make install source scripts/meta/env/load.sh APP=desk-gnome-extensions +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -66,7 +67,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-gnome-extensions/meta/info.yml b/roles/desk-gnome-extensions/meta/info.yml new file mode 100644 index 0000000000..7fe2c050e0 --- /dev/null +++ b/roles/desk-gnome-extensions/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written GNOME desktop config/glue role: activates GNOME Shell extensions via gsettings and installs the author's own CLI (cli-gnome-extension-manager). No distinct third-party product website. diff --git a/roles/desk-gnome-extensions/meta/main.yml b/roles/desk-gnome-extensions/meta/main.yml index b41e41eeac..d292e5c3b9 100644 --- a/roles/desk-gnome-extensions/meta/main.yml +++ b/roles/desk-gnome-extensions/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written GNOME desktop config/glue role: activates GNOME Shell extensions via gsettings and installs the author's own CLI (cli-gnome-extension-manager). No distinct third-party product website. galaxy_info: author: Kevin Veen-Birkenbach description: Desktop config role for activating GNOME Shell extensions and installing a CLI tool to manage them diff --git a/roles/desk-gnome-terminal/README.md b/roles/desk-gnome-terminal/README.md index 794f63060b..9ba2b18e6d 100644 --- a/roles/desk-gnome-terminal/README.md +++ b/roles/desk-gnome-terminal/README.md @@ -49,7 +49,7 @@ make compose-deploy mode=reinstall apps=desk-gnome-terminal full_cycle=false ### Production -Install GNOME Terminal directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install GNOME Terminal directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -59,6 +59,7 @@ make install source scripts/meta/env/load.sh APP=desk-gnome-terminal +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -66,7 +67,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-gnome-terminal/meta/info.yml b/roles/desk-gnome-terminal/meta/info.yml index a1cdc9f188..838c8f7091 100644 --- a/roles/desk-gnome-terminal/meta/info.yml +++ b/roles/desk-gnome-terminal/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://www.gnome.org/ diff --git a/roles/desk-gnome-terminal/meta/main.yml b/roles/desk-gnome-terminal/meta/main.yml index 73c692cde1..949ff75474 100644 --- a/roles/desk-gnome-terminal/meta/main.yml +++ b/roles/desk-gnome-terminal/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Terminal emulator for the GNOME desktop, giving command-line access on Arch Linux workstations diff --git a/roles/desk-gnome/README.md b/roles/desk-gnome/README.md index 717e29573e..e6e2747459 100644 --- a/roles/desk-gnome/README.md +++ b/roles/desk-gnome/README.md @@ -52,7 +52,7 @@ make compose-deploy mode=reinstall apps=desk-gnome full_cycle=false ### Production -Install GNOME Desktop directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install GNOME Desktop directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -62,6 +62,7 @@ make install source scripts/meta/env/load.sh APP=desk-gnome +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -69,7 +70,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-gnucash/README.md b/roles/desk-gnucash/README.md index 8bf8c999f0..f0209271af 100644 --- a/roles/desk-gnucash/README.md +++ b/roles/desk-gnucash/README.md @@ -40,7 +40,7 @@ make compose-deploy mode=reinstall apps=desk-gnucash full_cycle=false ### Production -Install GnuCash directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install GnuCash directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -50,6 +50,7 @@ make install source scripts/meta/env/load.sh APP=desk-gnucash +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -57,7 +58,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-gnucash/meta/info.yml b/roles/desk-gnucash/meta/info.yml index f85a1d8891..3506723022 100644 --- a/roles/desk-gnucash/meta/info.yml +++ b/roles/desk-gnucash/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://gnucash.org/ diff --git a/roles/desk-gnucash/meta/main.yml b/roles/desk-gnucash/meta/main.yml index 412676570b..d55232f645 100644 --- a/roles/desk-gnucash/meta/main.yml +++ b/roles/desk-gnucash/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Free and open-source desktop application for personal and small-business accounting and financial management diff --git a/roles/desk-jrnl/README.md b/roles/desk-jrnl/README.md index 54228ebb6f..9e6f255c6b 100644 --- a/roles/desk-jrnl/README.md +++ b/roles/desk-jrnl/README.md @@ -40,7 +40,7 @@ make compose-deploy mode=reinstall apps=desk-jrnl full_cycle=false ### Production -Install Jrnl directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Jrnl directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -50,6 +50,7 @@ make install source scripts/meta/env/load.sh APP=desk-jrnl +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -57,7 +58,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-jrnl/meta/info.yml b/roles/desk-jrnl/meta/info.yml index 1365a42a7a..1e78f67559 100644 --- a/roles/desk-jrnl/meta/info.yml +++ b/roles/desk-jrnl/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://jrnl.sh/ diff --git a/roles/desk-jrnl/meta/main.yml b/roles/desk-jrnl/meta/main.yml index b8517c345b..b857f161ca 100644 --- a/roles/desk-jrnl/meta/main.yml +++ b/roles/desk-jrnl/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Command-line journal application for creating and managing personal diary entries from the terminal diff --git a/roles/desk-keepassxc/README.md b/roles/desk-keepassxc/README.md index 99b13e6c37..8c05e5002b 100644 --- a/roles/desk-keepassxc/README.md +++ b/roles/desk-keepassxc/README.md @@ -44,7 +44,7 @@ make compose-deploy mode=reinstall apps=desk-keepassxc full_cycle=false ### Production -Install KeePassXC directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install KeePassXC directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -54,6 +54,7 @@ make install source scripts/meta/env/load.sh APP=desk-keepassxc +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -61,7 +62,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-keepassxc/meta/info.yml b/roles/desk-keepassxc/meta/info.yml index 478bca6c3f..98fccfcf91 100644 --- a/roles/desk-keepassxc/meta/info.yml +++ b/roles/desk-keepassxc/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://keepassxc.org/ diff --git a/roles/desk-keepassxc/meta/main.yml b/roles/desk-keepassxc/meta/main.yml index a4b3a693c3..d5ac36a91e 100644 --- a/roles/desk-keepassxc/meta/main.yml +++ b/roles/desk-keepassxc/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Local-first cross-platform desktop password manager storing credentials in an encrypted KeePass-format database diff --git a/roles/desk-libreoffice/README.md b/roles/desk-libreoffice/README.md index 2ba6db682d..6ac7535d54 100644 --- a/roles/desk-libreoffice/README.md +++ b/roles/desk-libreoffice/README.md @@ -53,7 +53,7 @@ make compose-deploy mode=reinstall apps=desk-libreoffice full_cycle=false ### Production -Install LibreOffice directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install LibreOffice directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -63,6 +63,7 @@ make install source scripts/meta/env/load.sh APP=desk-libreoffice +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -70,7 +71,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-libreoffice/meta/info.yml b/roles/desk-libreoffice/meta/info.yml index 518bd127d8..bcd9b8ed98 100644 --- a/roles/desk-libreoffice/meta/info.yml +++ b/roles/desk-libreoffice/meta/info.yml @@ -1,3 +1,3 @@ --- homepage: https://www.libreoffice.org/ -video: https://www.youtube.com/c/LibreOfficeTheDocumentFoundation +video: https://www.youtube.com/watch?v=3KC0ZdcA6s8 diff --git a/roles/desk-micro/README.md b/roles/desk-micro/README.md index bad630294e..5df1c7ac5c 100644 --- a/roles/desk-micro/README.md +++ b/roles/desk-micro/README.md @@ -40,7 +40,7 @@ make compose-deploy mode=reinstall apps=desk-micro full_cycle=false ### Production -Install micro directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install micro directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -50,6 +50,7 @@ make install source scripts/meta/env/load.sh APP=desk-micro +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -57,7 +58,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-micro/meta/info.yml b/roles/desk-micro/meta/info.yml index 737e5ed623..74af07f959 100644 --- a/roles/desk-micro/meta/info.yml +++ b/roles/desk-micro/meta/info.yml @@ -1,4 +1,5 @@ --- +# nocheck: info-media no official demo video logo: class: fas fa-terminal homepage: https://micro-editor.github.io/ diff --git a/roles/desk-micro/meta/main.yml b/roles/desk-micro/meta/main.yml index c54314ab2b..89c251e369 100644 --- a/roles/desk-micro/meta/main.yml +++ b/roles/desk-micro/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Terminal-based text editor with modern keybindings and syntax highlighting for Pacman-based workstations diff --git a/roles/desk-neovim/README.md b/roles/desk-neovim/README.md index 02982bbc03..ae9ed570e2 100644 --- a/roles/desk-neovim/README.md +++ b/roles/desk-neovim/README.md @@ -40,7 +40,7 @@ make compose-deploy mode=reinstall apps=desk-neovim full_cycle=false ### Production -Install Neovim directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Neovim directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -50,6 +50,7 @@ make install source scripts/meta/env/load.sh APP=desk-neovim +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -57,7 +58,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-neovim/meta/info.yml b/roles/desk-neovim/meta/info.yml index 1e77c3776f..ac543709a5 100644 --- a/roles/desk-neovim/meta/info.yml +++ b/roles/desk-neovim/meta/info.yml @@ -1,4 +1,5 @@ --- +# nocheck: info-media no official demo video logo: class: fab fa-vim homepage: https://neovim.io/ diff --git a/roles/desk-neovim/meta/main.yml b/roles/desk-neovim/meta/main.yml index 9ca71b2a99..5b1a9f9bea 100644 --- a/roles/desk-neovim/meta/main.yml +++ b/roles/desk-neovim/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Extensible Vim-based command-line text editor for terminal-driven code and configuration editing diff --git a/roles/desk-nextcloud/README.md b/roles/desk-nextcloud/README.md index 8fb2096355..9bf3f7c7dc 100644 --- a/roles/desk-nextcloud/README.md +++ b/roles/desk-nextcloud/README.md @@ -47,7 +47,7 @@ make compose-deploy mode=reinstall apps=desk-nextcloud full_cycle=false ### Production -Install Nextcloud Client ๏ธ directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Nextcloud Client ๏ธ directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -57,6 +57,7 @@ make install source scripts/meta/env/load.sh APP=desk-nextcloud +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -64,7 +65,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-obs/README.md b/roles/desk-obs/README.md index a35ef6006b..835d7d7700 100644 --- a/roles/desk-obs/README.md +++ b/roles/desk-obs/README.md @@ -44,7 +44,7 @@ make compose-deploy mode=reinstall apps=desk-obs full_cycle=false ### Production -Install OBS Studio directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install OBS Studio directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -54,6 +54,7 @@ make install source scripts/meta/env/load.sh APP=desk-obs +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -61,7 +62,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-obs/meta/info.yml b/roles/desk-obs/meta/info.yml index b3ee2b2b42..550efaeb7b 100644 --- a/roles/desk-obs/meta/info.yml +++ b/roles/desk-obs/meta/info.yml @@ -1,3 +1,3 @@ --- homepage: https://obsproject.com/ -video: https://www.youtube.com/obsproject +video: https://www.youtube.com/watch?v=yCMdj7B8WiA diff --git a/roles/desk-qbittorrent/README.md b/roles/desk-qbittorrent/README.md index c15e6799c0..4f037b9810 100644 --- a/roles/desk-qbittorrent/README.md +++ b/roles/desk-qbittorrent/README.md @@ -40,7 +40,7 @@ make compose-deploy mode=reinstall apps=desk-qbittorrent full_cycle=false ### Production -Install QBittorrent directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install QBittorrent directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -50,6 +50,7 @@ make install source scripts/meta/env/load.sh APP=desk-qbittorrent +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -57,7 +58,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-qbittorrent/meta/info.yml b/roles/desk-qbittorrent/meta/info.yml index c086e911f9..7d36dbe166 100644 --- a/roles/desk-qbittorrent/meta/info.yml +++ b/roles/desk-qbittorrent/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://www.qbittorrent.org/ diff --git a/roles/desk-qbittorrent/meta/main.yml b/roles/desk-qbittorrent/meta/main.yml index aad9849f05..d8068a4adc 100644 --- a/roles/desk-qbittorrent/meta/main.yml +++ b/roles/desk-qbittorrent/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Open-source desktop BitTorrent client for downloading and sharing files over the BitTorrent protocol diff --git a/roles/desk-retroarch/README.md b/roles/desk-retroarch/README.md index 0cbf6be23a..b097399486 100644 --- a/roles/desk-retroarch/README.md +++ b/roles/desk-retroarch/README.md @@ -45,7 +45,7 @@ make compose-deploy mode=reinstall apps=desk-retroarch full_cycle=false ### Production -Install RetroArch directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install RetroArch directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -55,6 +55,7 @@ make install source scripts/meta/env/load.sh APP=desk-retroarch +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -62,7 +63,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-retroarch/meta/info.yml b/roles/desk-retroarch/meta/info.yml index c9c7d18ede..8b012664de 100644 --- a/roles/desk-retroarch/meta/info.yml +++ b/roles/desk-retroarch/meta/info.yml @@ -1,3 +1,3 @@ --- homepage: https://www.retroarch.com/ -video: https://www.youtube.com/channel/UC_yi-5YZEf8LnapjkP3HL8A +video: https://www.youtube.com/watch?v=SNQxJhiMah4 diff --git a/roles/desk-spotify/README.md b/roles/desk-spotify/README.md index ab725b8bc2..aa597baad4 100644 --- a/roles/desk-spotify/README.md +++ b/roles/desk-spotify/README.md @@ -45,7 +45,7 @@ make compose-deploy mode=reinstall apps=desk-spotify full_cycle=false ### Production -Install Spotify directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Spotify directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -55,6 +55,7 @@ make install source scripts/meta/env/load.sh APP=desk-spotify +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -62,7 +63,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-ssh/README.md b/roles/desk-ssh/README.md index f7936716f4..3d22d65f34 100644 --- a/roles/desk-ssh/README.md +++ b/roles/desk-ssh/README.md @@ -52,7 +52,7 @@ make compose-deploy mode=reinstall apps=desk-ssh full_cycle=false ### Production -Install SSH Agent directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install SSH Agent directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -62,6 +62,7 @@ make install source scripts/meta/env/load.sh APP=desk-ssh +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -69,7 +70,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-ssh/meta/info.yml b/roles/desk-ssh/meta/info.yml new file mode 100644 index 0000000000..cbb3be09b6 --- /dev/null +++ b/roles/desk-ssh/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written glue role that sets up a systemd user ssh-agent service and syncs the ~/.ssh directory from Git for GNOME Wayland sessions; no consumer-facing upstream product. diff --git a/roles/desk-ssh/meta/main.yml b/roles/desk-ssh/meta/main.yml index e0be75ebea..ab6a1c5594 100644 --- a/roles/desk-ssh/meta/main.yml +++ b/roles/desk-ssh/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written glue role that sets up a systemd user ssh-agent service and syncs the ~/.ssh directory from Git for GNOME Wayland sessions; no consumer-facing upstream product. galaxy_info: author: Kevin Veen-Birkenbach description: Persistent systemd user-service SSH agent for Wayland desktops, with the .ssh config synced from Git diff --git a/roles/desk-ssh/tasks/00_core.yml b/roles/desk-ssh/tasks/00_core.yml index 8996de8785..a6c37710c1 100644 --- a/roles/desk-ssh/tasks/00_core.yml +++ b/roles/desk-ssh/tasks/00_core.yml @@ -21,26 +21,49 @@ - name: โœ… Ensure systemd user directory exists file: - path: "$HOME/.config/systemd/user" + path: "{{ DIR_SYSTEM_SERVICE_USER }}" state: directory mode: "0700" become: false -- name: ๐Ÿš€ Deploy ssh-agent systemd unit file - template: # nocheck: stack-host-template (per-host/user workstation systemd unit) - src: ssh-agent.service.j2 - dest: "$HOME/.config/systemd/user/ssh-agent.service" - mode: "0644" +- name: ๐Ÿ” Look for the unversioned ssh-agent unit + stat: + path: "{{ desk_ssh_legacy_unit }}" + register: desk_ssh_legacy_unit_state become: false -- name: ๐ŸŸข Enable and start ssh-agent service - systemd: - name: ssh-agent.service - scope: user - enabled: true - state: started - daemon_reload: true - become: false +- name: ๐Ÿงน Retire the unversioned ssh-agent unit + block: + - name: ๐Ÿ›‘ Stop and disable the unversioned ssh-agent unit + systemd: + name: "{{ desk_ssh_legacy_unit | basename }}" + scope: user + state: stopped + enabled: false + become: false + + - name: ๐Ÿ—‘๏ธ Delete the unversioned ssh-agent unit + file: + path: "{{ desk_ssh_legacy_unit }}" + state: absent + become: false + when: desk_ssh_legacy_unit_state.stat.exists + +- name: ๐Ÿš€ Deploy ssh-agent systemd unit file + include_role: + name: sys-service + vars: + system_service_scope: user + system_service_copy_files: false + system_service_state: started + system_service_tpl_on_failure: "" + system_service_tpl_type: simple + system_service_tpl_runtime: "" + system_service_tpl_before: default.target + system_service_tpl_wanted_by: default.target + system_service_tpl_environment: + - "SSH_AUTH_SOCK=%t/ssh-agent.socket" + system_service_tpl_exec_start: "/usr/bin/ssh-agent -D -a $SSH_AUTH_SOCK" - name: โœ… Ensure ~/.profile exists with common environment lineinfile: diff --git a/roles/desk-ssh/templates/ssh-agent.service.j2 b/roles/desk-ssh/templates/ssh-agent.service.j2 deleted file mode 100644 index 3125724f18..0000000000 --- a/roles/desk-ssh/templates/ssh-agent.service.j2 +++ /dev/null @@ -1,11 +0,0 @@ -[Unit] -Description=User SSH Agent -Before=default.target - -[Service] -Type=simple -Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket -ExecStart=/usr/bin/ssh-agent -D -a $SSH_AUTH_SOCK - -[Install] -WantedBy=default.target \ No newline at end of file diff --git a/roles/desk-ssh/vars/main.yml b/roles/desk-ssh/vars/main.yml index 7d866e2329..d8bb7879e0 100644 --- a/roles/desk-ssh/vars/main.yml +++ b/roles/desk-ssh/vars/main.yml @@ -1,3 +1,5 @@ --- application_id: desk-ssh +system_service_id: "{{ application_id }}" desk_ssh_repository: "{{ lookup('config', application_id, 'services.ssh.repository') }}" +desk_ssh_legacy_unit: "{{ [ DIR_SYSTEM_SERVICE_USER, 'ssh-agent.service' ] | path_join }}" diff --git a/roles/desk-torbrowser/README.md b/roles/desk-torbrowser/README.md index 30824fd3b5..96a3fadf7c 100644 --- a/roles/desk-torbrowser/README.md +++ b/roles/desk-torbrowser/README.md @@ -45,7 +45,7 @@ make compose-deploy mode=reinstall apps=desk-torbrowser full_cycle=false ### Production -Install Torbrowser directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Torbrowser directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -55,6 +55,7 @@ make install source scripts/meta/env/load.sh APP=desk-torbrowser +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -62,7 +63,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-virtualbox/README.md b/roles/desk-virtualbox/README.md index 5ff918e416..0f6e7c5159 100644 --- a/roles/desk-virtualbox/README.md +++ b/roles/desk-virtualbox/README.md @@ -46,7 +46,7 @@ make compose-deploy mode=reinstall apps=desk-virtualbox full_cycle=false ### Production -Install Virtual Box directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Virtual Box directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -56,6 +56,7 @@ make install source scripts/meta/env/load.sh APP=desk-virtualbox +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -63,7 +64,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-virtualbox/meta/info.yml b/roles/desk-virtualbox/meta/info.yml index 92d7ea0dd7..779bc05578 100644 --- a/roles/desk-virtualbox/meta/info.yml +++ b/roles/desk-virtualbox/meta/info.yml @@ -1,3 +1,3 @@ --- homepage: https://www.virtualbox.org/ -video: https://www.youtube.com/playlist?list=PLKCk3OyNwIzsbt_qDAXLMF5oFUhEkgbUM +video: https://www.youtube.com/watch?v=RvlfEKRkQfM diff --git a/roles/desk-zoom/README.md b/roles/desk-zoom/README.md index 52c0388439..61c8095dc4 100644 --- a/roles/desk-zoom/README.md +++ b/roles/desk-zoom/README.md @@ -40,7 +40,7 @@ make compose-deploy mode=reinstall apps=desk-zoom full_cycle=false ### Production -Install Zoom directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Zoom directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -50,6 +50,7 @@ make install source scripts/meta/env/load.sh APP=desk-zoom +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -57,7 +58,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/desk-zoom/meta/info.yml b/roles/desk-zoom/meta/info.yml index cc9e47c24d..52003ff88b 100644 --- a/roles/desk-zoom/meta/info.yml +++ b/roles/desk-zoom/meta/info.yml @@ -1,3 +1,3 @@ --- homepage: https://www.zoom.com/ -video: https://www.youtube.com/channel/UC2SxmE4C-KAQuHaEfHVymgQ +video: https://www.youtube.com/watch?v=8Dq1syZX2O4 diff --git a/roles/drv-epson-multiprinter/README.md b/roles/drv-epson-multiprinter/README.md index 926330697c..4c4c203db7 100644 --- a/roles/drv-epson-multiprinter/README.md +++ b/roles/drv-epson-multiprinter/README.md @@ -40,7 +40,7 @@ make compose-deploy mode=reinstall apps=drv-epson-multiprinter full_cycle=false ### Production -Install Epson Multiprinter Driver directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Epson Multiprinter Driver directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -50,6 +50,7 @@ make install source scripts/meta/env/load.sh APP=drv-epson-multiprinter +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -57,7 +58,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/drv-epson-multiprinter/meta/info.yml b/roles/drv-epson-multiprinter/meta/info.yml index f27f46f42a..76bcfb44b0 100644 --- a/roles/drv-epson-multiprinter/meta/info.yml +++ b/roles/drv-epson-multiprinter/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://epson.com/usa/ diff --git a/roles/drv-epson-multiprinter/meta/main.yml b/roles/drv-epson-multiprinter/meta/main.yml index 2e1f56a76d..8efab8baeb 100644 --- a/roles/drv-epson-multiprinter/meta/main.yml +++ b/roles/drv-epson-multiprinter/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Arch Linux driver bundle for Epson multifunction printing and scanning via escpr and imagescan diff --git a/roles/drv-intel/README.md b/roles/drv-intel/README.md index e8d578c363..2695bd10bb 100644 --- a/roles/drv-intel/README.md +++ b/roles/drv-intel/README.md @@ -46,7 +46,7 @@ make compose-deploy mode=reinstall apps=drv-intel full_cycle=false ### Production -Install Intel Driver directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Intel Driver directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -56,6 +56,7 @@ make install source scripts/meta/env/load.sh APP=drv-intel +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -63,7 +64,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/drv-intel/meta/info.yml b/roles/drv-intel/meta/info.yml index a744c8ceaf..021c1ca4cc 100644 --- a/roles/drv-intel/meta/info.yml +++ b/roles/drv-intel/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://github.com/intel/media-driver diff --git a/roles/drv-intel/meta/main.yml b/roles/drv-intel/meta/main.yml index 1e72fa3b2f..a9310e1750 100644 --- a/roles/drv-intel/meta/main.yml +++ b/roles/drv-intel/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Intel VA-API media driver for hardware-accelerated video decode and encode across Linux distributions diff --git a/roles/drv-lid-switch/README.md b/roles/drv-lid-switch/README.md index fcb05be69d..3ec0ac8271 100644 --- a/roles/drv-lid-switch/README.md +++ b/roles/drv-lid-switch/README.md @@ -50,7 +50,7 @@ make compose-deploy mode=reinstall apps=drv-lid-switch full_cycle=false ### Production -Install LID Switch Driver directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install LID Switch Driver directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -60,6 +60,7 @@ make install source scripts/meta/env/load.sh APP=drv-lid-switch +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -67,7 +68,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/drv-lid-switch/meta/info.yml b/roles/drv-lid-switch/meta/info.yml new file mode 100644 index 0000000000..8a54b09fe5 --- /dev/null +++ b/roles/drv-lid-switch/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written driver-config role that fixes laptop lid-switch behavior by editing systemd logind.conf and installing the author's own setup-hibernate helper; no upstream third-party product. diff --git a/roles/drv-lid-switch/meta/main.yml b/roles/drv-lid-switch/meta/main.yml index 93d8779c0a..efb5bf6638 100644 --- a/roles/drv-lid-switch/meta/main.yml +++ b/roles/drv-lid-switch/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written driver-config role that fixes laptop lid-switch behavior by editing systemd logind.conf and installing the author's own setup-hibernate helper; no upstream third-party product. galaxy_info: author: Kevin Veen-Birkenbach description: Power-aware systemd logind configuration for predictable laptop lid-close behavior across battery, AC, and docked states diff --git a/roles/drv-non-free/README.md b/roles/drv-non-free/README.md index ee043ae1ee..082243344c 100644 --- a/roles/drv-non-free/README.md +++ b/roles/drv-non-free/README.md @@ -49,7 +49,7 @@ make compose-deploy mode=reinstall apps=drv-non-free full_cycle=false ### Production -Install Proprietary Drivers directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Proprietary Drivers directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -59,6 +59,7 @@ make install source scripts/meta/env/load.sh APP=drv-non-free +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -66,7 +67,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/drv-non-free/meta/info.yml b/roles/drv-non-free/meta/info.yml new file mode 100644 index 0000000000..ad1fc64c7e --- /dev/null +++ b/roles/drv-non-free/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media self-written driver-config glue role running `mhwd -a pci nonfree 0300` on Arch-based systems; no consumer-facing upstream product website diff --git a/roles/drv-non-free/meta/main.yml b/roles/drv-non-free/meta/main.yml index 6bec18a2dc..c114faf04f 100644 --- a/roles/drv-non-free/meta/main.yml +++ b/roles/drv-non-free/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media self-written driver-config glue role running `mhwd -a pci nonfree 0300` on Arch-based systems; no consumer-facing upstream product website galaxy_info: author: Kevin Veen-Birkenbach description: Proprietary GPU driver installer for Arch-based systems via mhwd nonfree hardware detection diff --git a/roles/gen-hunspell/README.md b/roles/gen-hunspell/README.md index b4b98f3cdd..30e5aee231 100644 --- a/roles/gen-hunspell/README.md +++ b/roles/gen-hunspell/README.md @@ -44,7 +44,7 @@ make compose-deploy mode=reinstall apps=gen-hunspell full_cycle=false ### Production -Install Hunspell directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Hunspell directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -54,6 +54,7 @@ make install source scripts/meta/env/load.sh APP=gen-hunspell +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -61,7 +62,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/gen-hunspell/meta/info.yml b/roles/gen-hunspell/meta/info.yml index 6dd9acc444..a0a81a4c7b 100644 --- a/roles/gen-hunspell/meta/info.yml +++ b/roles/gen-hunspell/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://hunspell.github.io/ diff --git a/roles/gen-hunspell/meta/main.yml b/roles/gen-hunspell/meta/main.yml index bbbeb3dcfc..98fc0be041 100644 --- a/roles/gen-hunspell/meta/main.yml +++ b/roles/gen-hunspell/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Multi-language spell checker with configurable dictionary packs for desktop and office text editing diff --git a/roles/svc-ai-litellm/README.md b/roles/svc-ai-litellm/README.md new file mode 100644 index 0000000000..a975a2d0b9 --- /dev/null +++ b/roles/svc-ai-litellm/README.md @@ -0,0 +1,115 @@ +# LiteLLM Gateway + +## Description + +[LiteLLM](https://docs.litellm.ai/) is an LLM gateway that exposes an OpenAI-compatible HTTP API and forwards each request to a configured model backend, local or hosted. Clients authenticate with virtual API keys that the gateway issues and stores in its own database. + +## Overview + +This role deploys LiteLLM as a shared gateway container in Compose and Swarm deployments, backed by the central PostgreSQL service. The gateway is headless: it binds its HTTP port on the container host and claims no domain of its own, and the browser-facing surface is published separately by the LiteLLM Admin UI. It renders the model list from the interchangeable local backends available on the host, Ollama and LM Studio, and adds the OpenAI, Anthropic and OpenRouter entries whose API key is configured. Once the gateway is up, it provisions one virtual key per consuming application through the gateway admin API. + +## Cosmos + +The diagram places LiteLLM Gateway in the Infinito.Nexus cosmos: the components it deploys (capabilities), the central services it consumes (dependencies), and its outward reach (federation and bridged external networks). + +```mermaid +flowchart LR + subgraph deps [Dependencies] + dep_svc_ai_lmstudio["svc-ai-lmstudio ๐Ÿณ๐Ÿ"] + dep_svc_ai_ollama["svc-ai-ollama ๐Ÿณ๐Ÿ"] + dep_svc_db_postgres["svc-db-postgres ๐Ÿณ๐Ÿ"] + end + subgraph role [svc-ai-litellm ๐Ÿณ๐Ÿ] + svc_litellm["litellm"] + svc_postgres["postgres"] + svc_ollama["ollama"] + svc_lmstudio["lmstudio"] + end + subgraph dependents [Dependents] + dpt_web_app_discourse["web-app-discourse ๐Ÿณ๐Ÿ"] + dpt_web_app_flowise["web-app-flowise ๐Ÿณ๐Ÿ"] + dpt_web_app_hermes["web-app-hermes ๐Ÿณ๐Ÿ"] + dpt_web_app_litellm["web-app-litellm ๐Ÿ’ป"] + dpt_web_app_matrix["web-app-matrix ๐Ÿณ๐Ÿ"] + dpt_web_app_mattermost["web-app-mattermost ๐Ÿณ๐Ÿ"] + dpt_web_app_mediawiki["web-app-mediawiki ๐Ÿณ๐Ÿ"] + dpt_web_app_moodle["web-app-moodle ๐Ÿณ๐Ÿ"] + dpt_web_app_n8n["web-app-n8n ๐Ÿณ๐Ÿ"] + dpt_web_app_nextcloud["web-app-nextcloud ๐Ÿณ๐Ÿ"] + dpt_web_app_openclaw["web-app-openclaw ๐Ÿณ๐Ÿ"] + dpt_web_app_openwebui["web-app-openwebui ๐Ÿณ๐Ÿ"] + dpt_more["..."] + end + dep_svc_ai_lmstudio -. "0..1" .-> svc_lmstudio + dep_svc_ai_ollama -. "0..1" .-> svc_ollama + dep_svc_db_postgres -. "0..1" .-> svc_postgres + svc_litellm -- "1:1" --> dpt_more + svc_litellm -. "0..1" .-> dpt_web_app_discourse + svc_litellm -. "0..1" .-> dpt_web_app_flowise + svc_litellm -. "0..1" .-> dpt_web_app_hermes + svc_litellm -- "1:1" --> dpt_web_app_litellm + svc_litellm -. "0..1" .-> dpt_web_app_matrix + svc_litellm -. "0..1" .-> dpt_web_app_mattermost + svc_litellm -. "0..1" .-> dpt_web_app_mediawiki + svc_litellm -. "0..1" .-> dpt_web_app_moodle + svc_litellm -. "0..1" .-> dpt_web_app_n8n + svc_litellm -. "0..1" .-> dpt_web_app_nextcloud + svc_litellm -. "0..1" .-> dpt_web_app_openclaw + svc_litellm -. "0..1" .-> dpt_web_app_openwebui +``` + +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (๐Ÿ’ป host, ๐Ÿณ compose, ๐Ÿ swarm); โŒ marks a service that is explicitly turned off, and โš™๏ธ an Ansible role dependency declared in `meta/main.yml`. + +## Features + +- **OpenAI-compatible API:** One HTTP endpoint serves every model listed in the gateway configuration. +- **Backend routing:** Model entries are generated for Ollama and LM Studio when those services run on the host, under the shared alias each model carries so a consumer names one model whichever local backend answers it. +- **Remote providers:** OpenAI, Anthropic and OpenRouter each add their models when a key is configured. The keys are declared in `meta/secrets.yml` with the `type` and `regex` their value must satisfy, and default to the central `API..api_key` entry; an unset key leaves that provider's routes unpublished. +- **Per-consumer virtual keys:** Each consuming application receives its own virtual key, created through the gateway admin API under an alias naming that application. +- **File-based model list:** The model list is mounted as a read-only config file, with database-stored model entries turned off. +- **Managed credentials:** The gateway master key and the admin UI password are generated and kept as role credentials, and the admin UI username is the platform administrator name. + +## Quick Setup + +### Development + +Clone, set up the workstation, and deploy LiteLLM Gateway onto the local stack: + +```bash +git clone https://github.com/infinito-nexus/core.git +cd core +make onboard +make compose-deploy mode=reinstall apps=svc-ai-litellm full_cycle=false +``` + +### Production + +Run the published image to provision the inventory and deploy LiteLLM Gateway to a managed server (the mounted volume persists the inventory): + +```bash +APP=svc-ai-litellm +HOST= +DOMAIN= +TLS_MODE=self_signed +SSH_PUBLIC_KEY="" + +docker run --rm -it \ + -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + ghcr.io/infinito-nexus/core/debian bash -c ' + INVENTORY=/etc/infinito.nexus/inventories/production + infinito administration inventory provision "$INVENTORY" \ + --inventory-file "$INVENTORY/devices.yml" \ + --host "$HOST" \ + --include "$APP" \ + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + infinito administration deploy dedicated "$INVENTORY/devices.yml" \ + --password-file "$INVENTORY/.password" \ + --diff -vv' +``` + +## Credits + +Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. +Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). +Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/svc-ai-litellm/files/python/ensure_keys.py b/roles/svc-ai-litellm/files/python/ensure_keys.py new file mode 100644 index 0000000000..e39e335680 --- /dev/null +++ b/roles/svc-ai-litellm/files/python/ensure_keys.py @@ -0,0 +1,67 @@ +import contextlib +import json +import os +import urllib.error +import urllib.request + +TIMEOUT = 30 + + +def ensure_key(entry, call): + """Give the consumer the key it was issued, whatever holds the alias now. + + An inventory re-initialization mints a new key while the proxy database + keeps the previous one under the same alias, and the alias is unique, so + creating the new key is refused until the stale one is gone. + + Args: + entry: mapping with an ``alias`` and the ``key`` it must carry. + call: ``(method, path, body=None)`` performing one HTTP request. + + Returns: + True when the key had to be created, False when it already existed. + """ + with contextlib.suppress(urllib.error.HTTPError): + call("GET", "/key/info?key=" + entry["key"]) + return False + with contextlib.suppress(urllib.error.HTTPError): + call("POST", "/key/delete", {"key_aliases": [entry["alias"]]}) + call("POST", "/key/generate", {"key": entry["key"], "key_alias": entry["alias"]}) + return True + + +def http_call(base, headers): + """Return a ``call`` bound to one proxy. + + Args: + base: scheme and authority of the proxy, without a trailing slash. + headers: headers sent with every request, carrying the master key. + """ + + def call(method, path, body=None): + request = urllib.request.Request( # noqa: S310 fixed internal http origin + base + path, + data=(json.dumps(body).encode() if body is not None else None), + headers=headers, + method=method, + ) + return urllib.request.urlopen(request, timeout=TIMEOUT) # noqa: S310 fixed internal http origin + + return call + + +def main(): + call = http_call( + "http://localhost:" + os.environ["LITELLM_PORT"], + { + "Authorization": "Bearer " + os.environ["LITELLM_MK"], + "Content-Type": "application/json", + }, + ) + for entry in json.loads(os.environ["LITELLM_KEYS_PAYLOAD"]): + if ensure_key(entry, call): + print("CHANGED " + entry["alias"]) + + +if __name__ == "__main__": + main() diff --git a/roles/svc-ai-litellm/files/python/probe_auth.py b/roles/svc-ai-litellm/files/python/probe_auth.py new file mode 100644 index 0000000000..2ac9cdf471 --- /dev/null +++ b/roles/svc-ai-litellm/files/python/probe_auth.py @@ -0,0 +1,162 @@ +"""Prove the gateway is closed, keyed per consumer, and revocable in isolation. + +A gateway that answers an unauthenticated caller hands every model on the +deployment to anything that can reach the overlay, and a revocation that takes +other consumers down with it is a revocation nobody dares to use. Both failures +are silent: the deploy is green either way and the first symptom is either a +stranger's bill or an outage. + +The probe mints its own throwaway key, revokes that one, and shows a real +consumer key still working afterwards, so it proves isolation without touching +any credential a consumer depends on. + +Environment: + LITELLM_MK: master key the gateway accepts. + LITELLM_PORT: port the gateway listens on inside its own container. + LITELLM_KEY: a live consumer virtual key that must survive the revocation. +""" + +from __future__ import annotations + +import contextlib +import json +import os +import time +import urllib.error +import urllib.request + +TIMEOUT = 30 +PROBE_ALIAS = "infinito-auth-probe" +REVOCATION_ATTEMPTS = 10 +REVOCATION_DELAY = 3 +UNAUTHORIZED = (401, 403) + + +class ProbeError(RuntimeError): + """The gateway answered in a way that fails the authentication contract.""" + + +def status_of(base, key): + """Return the status the gateway answers ``GET /v1/models`` with. + + Args: + base: scheme and authority of the gateway, without a trailing slash. + key: bearer token to send, or None to send no ``Authorization`` header. + """ + headers = {"Authorization": f"Bearer {key}"} if key is not None else {} + request = urllib.request.Request( # noqa: S310 fixed internal http origin + base + "/v1/models", headers=headers, method="GET" + ) + try: + with urllib.request.urlopen(request, timeout=TIMEOUT) as response: # noqa: S310 fixed internal http origin + return response.status + except urllib.error.HTTPError as error: + return error.code + + +def admin_call(base, master_key): + """Return a ``call(method, path, body)`` authenticated as the gateway admin. + + Args: + base: scheme and authority of the gateway, without a trailing slash. + master_key: the gateway's master key. + """ + + def call(method, path, body=None): + request = urllib.request.Request( # noqa: S310 fixed internal http origin + base + path, + data=(json.dumps(body).encode() if body is not None else None), + headers={ + "Authorization": f"Bearer {master_key}", + "Content-Type": "application/json", + }, + method=method, + ) + with urllib.request.urlopen(request, timeout=TIMEOUT) as response: # noqa: S310 fixed internal http origin + return json.loads(response.read() or b"{}") + + return call + + +def await_rejection(get_status, key, sleep): + """Return the status of a revoked key once the gateway stops honouring it. + + LiteLLM serves keys from an in-process cache, so a deletion the database + already accepted keeps answering 200 for a moment. + + Args: + get_status: ``(key) -> int`` returning the gateway's status for a key. + key: the revoked key. + sleep: ``(seconds) -> None`` used between attempts. + """ + status = get_status(key) + for _ in range(REVOCATION_ATTEMPTS): + if status in UNAUTHORIZED: + return status + sleep(REVOCATION_DELAY) + status = get_status(key) + return status + + +def probe(get_status, call, consumer_key, sleep=time.sleep): + """Run the whole authentication contract, raising on the first breach. + + Args: + get_status: ``(key) -> int`` returning the gateway's status for a key. + call: ``(method, path, body=None)`` performing one admin request. + consumer_key: a live consumer key that must survive the revocation. + sleep: ``(seconds) -> None`` used while waiting for a revocation. + """ + anonymous = get_status(None) + if anonymous not in UNAUTHORIZED: + raise ProbeError( + f"the gateway answered an unauthenticated GET /v1/models with " + f"{anonymous}; it is reachable without a key on the overlay" + ) + + forged = get_status("sk-" + "0" * 32) + if forged not in UNAUTHORIZED: + raise ProbeError( + f"the gateway answered a forged bearer token with {forged}; it is " + f"not validating keys" + ) + + with contextlib.suppress(urllib.error.HTTPError): + call("POST", "/key/delete", {"key_aliases": [PROBE_ALIAS]}) + minted = call("POST", "/key/generate", {"key_alias": PROBE_ALIAS})["key"] + accepted = get_status(minted) + if accepted != 200: + raise ProbeError( + f"the gateway answered its own freshly minted virtual key with " + f"{accepted}; virtual keys do not grant access" + ) + + call("POST", "/key/delete", {"keys": [minted]}) + revoked = await_rejection(get_status, minted, sleep) + if revoked not in UNAUTHORIZED: + raise ProbeError( + f"the revoked probe key still answers with {revoked} after " + f"{REVOCATION_ATTEMPTS * REVOCATION_DELAY}s; revocation does not " + f"take effect" + ) + + survivor = get_status(consumer_key) + if survivor != 200: + raise ProbeError( + f"revoking the probe key left a consumer key answering {survivor}; " + f"revocation is not isolated to one consumer" + ) + + +def main(): + base = "http://127.0.0.1:" + os.environ["LITELLM_PORT"] + probe( + lambda key: status_of(base, key), + admin_call(base, os.environ["LITELLM_MK"]), + os.environ["LITELLM_KEY"], + ) + print("AUTHENTICATED") + + +if __name__ == "__main__": + main() diff --git a/roles/svc-ai-litellm/files/python/warm_model.py b/roles/svc-ai-litellm/files/python/warm_model.py new file mode 100644 index 0000000000..ca1925916a --- /dev/null +++ b/roles/svc-ai-litellm/files/python/warm_model.py @@ -0,0 +1,46 @@ +"""Force the gateway to load its chat model before any consumer prompts it. + +A backend pulls its preload model at deploy time but only loads it into memory +on the first inference. That cold load outlives the reverse proxy's read +timeout, so the first consumer request comes back as a 504 instead of an answer +while every later one succeeds. Warming here moves the cost into the deploy. + +Environment: + LITELLM_MK: master key the gateway accepts. + LITELLM_PORT: port the gateway listens on inside its own container. + LITELLM_MODEL: model name to warm. +""" + +from __future__ import annotations + +import json +import os +import urllib.request + +MASTER_KEY = os.environ["LITELLM_MK"] +PORT = os.environ["LITELLM_PORT"] +MODEL = os.environ["LITELLM_MODEL"] +TIMEOUT = 900 + +payload = json.dumps( + { + "model": MODEL, + "messages": [{"role": "user", "content": "ping"}], + "max_tokens": 1, + } +).encode() + +request = urllib.request.Request( + f"http://127.0.0.1:{PORT}/v1/chat/completions", + data=payload, + headers={ + "Authorization": f"Bearer {MASTER_KEY}", + "Content-Type": "application/json", + }, + method="POST", +) + +with urllib.request.urlopen(request, timeout=TIMEOUT) as response: # noqa: S310 fixed internal http origin + response.read() + +print(f"WARMED {MODEL}") diff --git a/roles/svc-ai-litellm/files/test/.nocheck b/roles/svc-ai-litellm/files/test/.nocheck new file mode 100644 index 0000000000..2b9d82d840 --- /dev/null +++ b/roles/svc-ai-litellm/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; test-e2e-cli stages files/test/ by that fixed path. diff --git a/roles/svc-ai-litellm/files/test/probe.py b/roles/svc-ai-litellm/files/test/probe.py new file mode 100644 index 0000000000..f6ad07ce32 --- /dev/null +++ b/roles/svc-ai-litellm/files/test/probe.py @@ -0,0 +1,190 @@ +"""Assert the gateway routes to exactly the backends this deployment enabled. + +Runs inside the litellm container, where the gateway answers on loopback and +the backend containers resolve by name. Standard library only: the image ships +the litellm app, not a test toolchain. + +Env (rendered into test.env from templates/test.env.j2): + PORT gateway http port inside the container + MASTER_KEY gateway master key + CHAT_MODEL the model every consumer asks for (LITELLM_CHAT_MODEL) + CHAT_MODEL_SERVED true|false, whether a backend can answer it + EXPECTED_MODELS JSON list the config template published + LMSTUDIO_ALIASES JSON list of aliases only LM Studio provides, rendered + whether or not the backend is deployed so the absent + case stays assertable + REMOTE_ALIASES JSON list of aliases a configured provider key publishes + (OpenAI, Anthropic, OpenRouter) + OLLAMA_ENABLED true|false + LMSTUDIO_ENABLED true|false + RETRIES completion attempts (default 10) + SLEEP_SECONDS wait between attempts (default 6) +""" + +from __future__ import annotations + +import json +import os +import sys +import time +import urllib.error +import urllib.request + + +def evaluate( + *, + served: set[str], + expected: list[str], + chat_model: str, + chat_model_served: bool, + ollama_enabled: bool, + lmstudio_enabled: bool, + lmstudio_aliases: list[str], + remote_aliases: list[str], +) -> list[str]: + """Every routing violation the published model list shows, as messages. + + Args: + served: model ids the gateway answers ``/v1/models`` with. + expected: model ids the rendered config declared. + chat_model: the id consumers are configured to ask for. + chat_model_served: whether any backend can answer *chat_model*. + ollama_enabled: svc-ai-ollama is deployed on the gateway's host. + lmstudio_enabled: svc-ai-lmstudio is deployed on the gateway's host. + lmstudio_aliases: aliases only LM Studio provides, whatever is deployed. + remote_aliases: aliases a configured remote provider key publishes. + + Returns: + One message per violation; empty when the routing is consistent. + """ + failures: list[str] = [] + + undelivered = sorted(set(expected) - served) + if undelivered: + failures.append( + f"the config declares {undelivered} but the gateway does not serve " + f"them; the rendered config.yaml and the running gateway disagree" + ) + + exclusive = set(lmstudio_aliases) + if lmstudio_enabled and not exclusive <= served: + failures.append( + f"svc-ai-lmstudio is deployed but the gateway does not serve " + f"{sorted(exclusive - served)}; its models were declared and not routed" + ) + if not lmstudio_enabled and exclusive & served: + failures.append( + f"svc-ai-lmstudio is not deployed yet the gateway publishes " + f"{sorted(exclusive & served)}; a route stands without its backend" + ) + + unbacked = sorted(served - exclusive - set(remote_aliases)) + if not ollama_enabled and unbacked: + failures.append( + f"svc-ai-ollama is not deployed yet the gateway publishes {unbacked}" + ) + + if not chat_model_served: + if served: + failures.append( + f"no backend is deployed but the gateway publishes {sorted(served)}" + ) + return failures + + if chat_model not in served: + failures.append( + f"consumers are configured for '{chat_model}' (LITELLM_CHAT_MODEL, " + f"built from the deployment inventory) but the gateway serves " + f"{sorted(served)} (built from this host's group_names); the two " + f"sources disagree" + ) + + return failures + + +def _call(base: str, key: str, path: str, payload: dict | None = None): + body = None if payload is None else json.dumps(payload).encode() + request = urllib.request.Request( # noqa: S310 - literal http:// to loopback + base + path, + data=body, + headers={ + "Authorization": f"Bearer {key}", + "Content-Type": "application/json", + }, + ) + with urllib.request.urlopen( # noqa: S310 - literal http:// to loopback + request, timeout=120 + ) as response: + return json.loads(response.read().decode() or "{}") + + +def _completion(base: str, key: str, model: str, retries: int, pause: float) -> str: + last_error = "no attempt ran" + for attempt in range(1, retries + 1): + try: + completion = _call( + base, + key, + "/v1/chat/completions", + { + "model": model, + "messages": [ + {"role": "user", "content": "Reply with the word pong."} + ], + "max_tokens": 16, + }, + ) + choices = completion.get("choices") or [{}] + answer = (choices[0].get("message", {}).get("content") or "").strip() + if answer: + return answer + last_error = "empty content" + except (urllib.error.URLError, TimeoutError, ValueError) as exc: + last_error = f"{type(exc).__name__}: {exc}" + if attempt < retries: + time.sleep(pause) + raise RuntimeError(last_error) + + +def main() -> int: + key = os.environ["MASTER_KEY"] + base = f"http://127.0.0.1:{os.environ['PORT']}" + chat_model = os.environ["CHAT_MODEL"].strip() + chat_model_served = os.environ["CHAT_MODEL_SERVED"] == "true" + retries = int(os.environ.get("RETRIES", "10")) + pause = float(os.environ.get("SLEEP_SECONDS", "6")) + + listing = _call(base, key, "/v1/models") + served = {entry.get("id") for entry in listing.get("data", [])} + print(f"[INFO] gateway answered /v1/models, serving {sorted(served)}") + + failures = evaluate( + served=served, + expected=json.loads(os.environ["EXPECTED_MODELS"]), + chat_model=chat_model, + chat_model_served=chat_model_served, + ollama_enabled=os.environ["OLLAMA_ENABLED"] == "true", + lmstudio_enabled=os.environ["LMSTUDIO_ENABLED"] == "true", + lmstudio_aliases=json.loads(os.environ["LMSTUDIO_ALIASES"]), + remote_aliases=json.loads(os.environ["REMOTE_ALIASES"]), + ) + + if chat_model_served and not failures: + try: + answer = _completion(base, key, chat_model, retries, pause) + print(f"[OK] '{chat_model}' answered: {answer[:60]}") + except RuntimeError as exc: + failures.append( + f"'{chat_model}' is published but answered nothing after " + f"{retries} attempts; last failure: {exc}" + ) + + for failure in failures: + print(f"[FAIL] {failure}", file=sys.stderr) + if not failures: + print("[OK] the published routes match the deployed backends") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/roles/svc-ai-litellm/files/test/test.sh b/roles/svc-ai-litellm/files/test/test.sh new file mode 100644 index 0000000000..f8e8a895f1 --- /dev/null +++ b/roles/svc-ai-litellm/files/test/test.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# svc-ai-litellm routing test. Runs probe.py inside the gateway container, where +# the API answers on loopback and the backends resolve by container name, and +# asserts the published model list matches the backends this deployment enabled. +# +# Env (rendered into test.env from templates/test.env.j2): +# LITELLM_CONTAINER resolved gateway container (CLI_LOCAL_CID) +# LITELLM_PORT gateway http port inside the container +# LITELLM_MASTER_KEY_B64 base64 master key (avoids shell-quoting issues) +# LITELLM_CHAT_MODEL the model every consumer asks for +# LITELLM_CHAT_MODEL_SERVED true|false +# LITELLM_EXPECTED_MODELS JSON list the config template published +# LITELLM_LMSTUDIO_ALIASES JSON list of aliases only LM Studio provides +# LITELLM_REMOTE_ALIASES JSON list of aliases a configured provider key adds +# LITELLM_OLLAMA_ENABLED true|false +# LITELLM_LMSTUDIO_ENABLED true|false +# READY_RETRIES gateway readiness attempts (default 30) +# READY_SLEEP_SECONDS wait between attempts (default 5) + +set -uo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +READY_RETRIES="${READY_RETRIES:-30}" +READY_SLEEP_SECONDS="${READY_SLEEP_SECONDS:-5}" + +MASTER_KEY="$(printf '%s' "${LITELLM_MASTER_KEY_B64}" | base64 -d 2>/dev/null)" +[ -n "${MASTER_KEY}" ] || { + echo "[FATAL] LITELLM_MASTER_KEY_B64 missing or undecodable" >&2 + exit 2 +} +[ -n "${LITELLM_CONTAINER}" ] || { + echo "[FATAL] LITELLM_CONTAINER unset; the gateway container was not resolved" >&2 + exit 2 +} + +# The image ships the litellm app, so a python interpreter is present, but the +# upstream tag has changed which of the two names is on PATH. +interpreter() { + # nocheck: container-exec-resolver address resolved by the caller and passed in + if container exec -i "${LITELLM_CONTAINER}" python3 -c '' 2>/dev/null; then + echo python3 + else + echo python + fi +} + +probe() { + # nocheck: container-exec-resolver address resolved by the caller and passed in + container exec -i \ + -e "PORT=${LITELLM_PORT}" \ + -e "MASTER_KEY=${MASTER_KEY}" \ + -e "CHAT_MODEL=${LITELLM_CHAT_MODEL}" \ + -e "CHAT_MODEL_SERVED=${LITELLM_CHAT_MODEL_SERVED}" \ + -e "EXPECTED_MODELS=${LITELLM_EXPECTED_MODELS}" \ + -e "LMSTUDIO_ALIASES=${LITELLM_LMSTUDIO_ALIASES}" \ + -e "REMOTE_ALIASES=${LITELLM_REMOTE_ALIASES}" \ + -e "OLLAMA_ENABLED=${LITELLM_OLLAMA_ENABLED}" \ + -e "LMSTUDIO_ENABLED=${LITELLM_LMSTUDIO_ENABLED}" \ + "${LITELLM_CONTAINER}" "$(interpreter)" - <"${here}/probe.py" +} + +attempt=1 +while [ "${attempt}" -le "${READY_RETRIES}" ]; do + output="$(probe 2>&1)" + rc=$? + case "${output}" in + *"gateway answered /v1/models"*) + echo "${output}" + exit "${rc}" + ;; + esac + attempt=$((attempt + 1)) + [ "${attempt}" -le "${READY_RETRIES}" ] && sleep "${READY_SLEEP_SECONDS}" +done + +echo "[FAIL] the gateway never answered /v1/models after ${READY_RETRIES} attempts" >&2 +echo "${output}" >&2 +exit 1 diff --git a/roles/svc-ai-litellm/meta/info.yml b/roles/svc-ai-litellm/meta/info.yml new file mode 100644 index 0000000000..d61391ef08 --- /dev/null +++ b/roles/svc-ai-litellm/meta/info.yml @@ -0,0 +1,5 @@ +--- +# nocheck: info-media no official demo video +logo: + class: fa-solid fa-route +homepage: https://docs.litellm.ai/ diff --git a/roles/svc-ai-litellm/meta/main.yml b/roles/svc-ai-litellm/meta/main.yml new file mode 100644 index 0000000000..9e211da832 --- /dev/null +++ b/roles/svc-ai-litellm/meta/main.yml @@ -0,0 +1,34 @@ +--- +galaxy_info: + author: Kevin Veen-Birkenbach + description: OpenAI-compatible LLM gateway routing a single /v1 endpoint to local and hosted model backends with per-consumer keys + license: Infinito.Nexus Community License (Non-Commercial) + company: | + Kevin Veen-Birkenbach + https://www.veen.world + galaxy_tags: + - ai + - llm + - gateway + - litellm + - proxy + - self-hosted + issue_tracker_url: https://s.infinito.nexus/issues + min_ansible_version: "2.9" + platforms: + - name: ArchLinux + versions: + - all + - name: Debian + versions: + - all + - name: EL + versions: + - all + - name: Fedora + versions: + - all + - name: Ubuntu + versions: + - all +dependencies: [] diff --git a/roles/svc-ai-litellm/meta/networks.yml b/roles/svc-ai-litellm/meta/networks.yml new file mode 100644 index 0000000000..9b9e0c25a7 --- /dev/null +++ b/roles/svc-ai-litellm/meta/networks.yml @@ -0,0 +1,6 @@ +--- +local: + subnet: 192.168.80.0/24 +overlay: + modes: [compose, swarm] + topology: shared_net diff --git a/roles/svc-ai-litellm/meta/secrets.yml b/roles/svc-ai-litellm/meta/secrets.yml new file mode 100644 index 0000000000..a2fb9ce606 --- /dev/null +++ b/roles/svc-ai-litellm/meta/secrets.yml @@ -0,0 +1,28 @@ +--- +credentials: + master_key: + description: "Admin master key of the LiteLLM gateway; consumers use per-consumer virtual keys, never this one" + algorithm: "alphanumeric" + validation: + min_length: 50 + ui_password: + description: "Login password of the LiteLLM admin UI (served at /ui, proxied by web-app-litellm)" + algorithm: "alphanumeric" + validation: + min_length: 32 + openai_api_key: + description: "OpenAI API key; empty leaves the openai/* models unpublished. The pattern rejects a truncated or whitespace-carrying paste, not a vendor prefix: + OpenAI moved from sk- to sk-proj- without notice, and a schema that pinned the prefix would reject a valid key" + type: "string" + regex: "\\S{20,}" + default: "{{ lookup('api', 'openai.api_key') }}" + anthropic_api_key: + description: "Anthropic API key; empty leaves the anthropic/* models unpublished" + type: "string" + regex: "\\S{20,}" + default: "{{ lookup('api', 'anthropic.api_key') }}" + openrouter_api_key: + description: "OpenRouter API key; empty leaves openrouter/auto unpublished" + type: "string" + regex: "\\S{20,}" + default: "{{ lookup('api', 'openrouter.api_key') }}" diff --git a/roles/svc-ai-litellm/meta/services.yml b/roles/svc-ai-litellm/meta/services.yml new file mode 100644 index 0000000000..663f5e67c0 --- /dev/null +++ b/roles/svc-ai-litellm/meta/services.yml @@ -0,0 +1,47 @@ +--- +litellm: + modes: + compose: + enabled: true + swarm: + enabled: true + bond: 1 + enabled: true + shared: true + backup: + no_stop_required: true + image: ghcr.io/berriai/litellm + version: main-v1.77.7-stable + name: litellm + max_output_tokens: 512 + upstream_timeout: 240 + min_storage: 1022MB + cpus: "2.0" + mem_reservation: 1g + mem_limit: 2g + pids_limit: 1024 + ports: + local: + http: 8081 + internal: + http: 4000 + run_after: + - svc-db-postgres + lifecycle: beta + +postgres: + bond: 1 + enabled: true # nocheck: dynamic-flag + shared: "{{ 'svc-db-postgres' in group_names }}" + +# nocheck: playwright-service-flag, dynamic-flag +ollama: + bond: 1 + enabled: "{{ 'svc-ai-ollama' in group_names }}" + shared: "{{ 'svc-ai-ollama' in group_names }}" + +# nocheck: playwright-service-flag, dynamic-flag +lmstudio: + bond: 0.5 + enabled: "{{ 'svc-ai-lmstudio' in group_names }}" + shared: "{{ 'svc-ai-lmstudio' in group_names }}" diff --git a/roles/svc-ai-litellm/meta/tests.yml b/roles/svc-ai-litellm/meta/tests.yml new file mode 100644 index 0000000000..89594be937 --- /dev/null +++ b/roles/svc-ai-litellm/meta/tests.yml @@ -0,0 +1,4 @@ +--- +cli: + timeout: 600 + container_service_key: litellm diff --git a/roles/svc-ai-litellm/meta/variants.yml b/roles/svc-ai-litellm/meta/variants.yml new file mode 100644 index 0000000000..8ae1ddd8aa --- /dev/null +++ b/roles/svc-ai-litellm/meta/variants.yml @@ -0,0 +1,34 @@ +--- +# Matrix-deploy variant overrides for this role. +# See docs/contributing/artefact/files/role/variants.md for the file format. + +- services: + ollama: + enabled: true + shared: true + lmstudio: + enabled: false + shared: false + postgres: + shared: true + +- services: + postgres: + shared: false + ollama: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + lmstudio: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + +- services: + ollama: + enabled: false + shared: false + lmstudio: + bond: 0.5 + enabled: true + shared: true + postgres: + shared: true diff --git a/roles/svc-ai-litellm/meta/volumes.yml b/roles/svc-ai-litellm/meta/volumes.yml new file mode 100644 index 0000000000..7ceb601ef6 --- /dev/null +++ b/roles/svc-ai-litellm/meta/volumes.yml @@ -0,0 +1,8 @@ +--- +litellm_config: + type: config + source: "{{ [ lookup('container', 'svc-ai-litellm', 'directories.config'), 'config.yaml' ] | path_join }}" + mode: "0444" + mounts: + - service: litellm + target: /etc/litellm/config.yaml diff --git a/roles/svc-ai-litellm/tasks/00_core.yml b/roles/svc-ai-litellm/tasks/00_core.yml new file mode 100644 index 0000000000..9076c123b0 --- /dev/null +++ b/roles/svc-ai-litellm/tasks/00_core.yml @@ -0,0 +1,55 @@ +--- +- include_tasks: utils/once/flag.yml + +- include_tasks: utils/load/handlers.yml + vars: + handler_role_name: "sys-svc-compose" + +- name: "๐Ÿงฉ For '{{ application_id }}': Load central RDBMS" + include_role: + name: sys-svc-rdbms + public: false + vars: + database_consumer_id: "{{ application_id }}" + when: lookup('database', application_id, 'enabled') | bool + +- name: "๐Ÿ“„ Render LiteLLM gateway config (local + swarm peers)" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" + vars: + role_templates: + - src: "config.yaml.j2" + dest: "{{ LITELLM_CONFIG_PATH_HOST }}" + +- name: "๐Ÿงฎ Freeze the routing contract the CLI test asserts against" + ansible.builtin.set_fact: + LITELLM_TEST_CONTRACT: + ollama: "{{ LITELLM_OLLAMA_BACKEND | bool }}" + lmstudio: "{{ LITELLM_LMSTUDIO_BACKEND | bool }}" + served: "{{ LITELLM_CHAT_MODEL_SERVED | bool }}" + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "๐Ÿ”ง Setup container network for {{ application_id }}" + include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/network/routine.yml') }}" + vars: + compose_handlers_flush: true + +- name: "๐Ÿ” Build consumer key list" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + ansible.builtin.set_fact: + LITELLM_CONSUMER_KEYS: >- + {%- set out = [] -%} + {%- for consumer in lookup('roles_with_service', 'litellm', scope='all') -%} + {%- set key = lookup('config', consumer.id, 'secrets.credentials.litellm_api_key', '') -%} + {%- if key -%} + {%- set _ = out.append({'alias': consumer.id, 'key': key}) -%} + {%- endif -%} + {%- endfor -%} + {{ out }} + +- name: "๐Ÿ”‘ Provision per-consumer virtual keys" + ansible.builtin.include_tasks: 01_keys.yml + when: + - IS_STACK_HOST | bool + - LITELLM_CONSUMER_KEYS | length > 0 diff --git a/roles/svc-ai-litellm/tasks/01_keys.yml b/roles/svc-ai-litellm/tasks/01_keys.yml new file mode 100644 index 0000000000..bd43ae8eb5 --- /dev/null +++ b/roles/svc-ai-litellm/tasks/01_keys.yml @@ -0,0 +1,51 @@ +--- +- name: "๐Ÿ” Resolve {{ application_id }} hosting node + container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ entity_name }}" + resolve_output_prefix: LITELLM + resolve_compose_cid: "{{ LITELLM_CONTAINER }}" + +- name: "โณ Wait until the gateway accepts connections on its own port" + ansible.builtin.shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec -i {{ LITELLM_LOCAL_CID | quote }} python3 -c 'import socket; socket.create_connection(("127.0.0.1", {{ LITELLM_PORT }}), 5).close()' + register: litellm_gateway_listening + retries: 60 + delay: 5 + until: litellm_gateway_listening.rc == 0 + changed_when: false + delegate_to: "{{ LITELLM_HOST_NODE }}" + +- name: "๐Ÿ”‘ Ensure a virtual key exists per consumer" + ansible.builtin.shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec -i -e LITELLM_KEYS_PAYLOAD={{ LITELLM_CONSUMER_KEYS | to_json | quote }} -e LITELLM_MK={{ LITELLM_MASTER_KEY | quote }} -e LITELLM_PORT={{ LITELLM_PORT | quote }} {{ LITELLM_LOCAL_CID | quote }} python3 -c {{ lookup('file', lookup('path_absolute', 'roles/svc-ai-litellm/files/python/ensure_keys.py')) | quote }} + register: litellm_keys_result + retries: 10 + delay: 6 + until: litellm_keys_result.rc == 0 + changed_when: "'CHANGED' in litellm_keys_result.stdout" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ LITELLM_HOST_NODE }}" + +- name: "๐Ÿ›ก๏ธ Prove the gateway is closed and revocation stays per consumer" + ansible.builtin.shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec -i -e LITELLM_MK={{ LITELLM_MASTER_KEY | quote }} -e LITELLM_PORT={{ LITELLM_PORT | quote }} -e LITELLM_KEY={{ (LITELLM_CONSUMER_KEYS | first).key | quote }} {{ LITELLM_LOCAL_CID | quote }} python3 -c {{ lookup('file', lookup('path_absolute', 'roles/svc-ai-litellm/files/python/probe_auth.py')) | quote }} + register: litellm_auth_probe + retries: 5 + delay: 10 + until: litellm_auth_probe.rc == 0 + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ LITELLM_HOST_NODE }}" + +- name: "๐Ÿ”ฅ Warm the chat model so the first prompt is not a cold load" + ansible.builtin.shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec -i -e LITELLM_MK={{ LITELLM_MASTER_KEY | quote }} -e LITELLM_PORT={{ LITELLM_PORT | quote }} -e LITELLM_MODEL={{ LITELLM_CHAT_MODEL | quote }} {{ LITELLM_LOCAL_CID | quote }} python3 -c {{ lookup('file', lookup('path_absolute', 'roles/svc-ai-litellm/files/python/warm_model.py')) | quote }} + register: litellm_warm_result + retries: 5 + delay: 10 + until: litellm_warm_result.rc == 0 + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ LITELLM_HOST_NODE }}" + when: LITELLM_CHAT_MODEL_SERVED | bool diff --git a/roles/svc-ai-litellm/tasks/main.yml b/roles/svc-ai-litellm/tasks/main.yml new file mode 100644 index 0000000000..245dfe50ab --- /dev/null +++ b/roles/svc-ai-litellm/tasks/main.yml @@ -0,0 +1,5 @@ +--- +- include_tasks: 00_core.yml + when: run_once_svc_ai_litellm is not defined + vars: + application_id: svc-ai-litellm diff --git a/roles/svc-ai-litellm/tasks/utils/consumer_contract.yml b/roles/svc-ai-litellm/tasks/utils/consumer_contract.yml new file mode 100644 index 0000000000..deeffb6c59 --- /dev/null +++ b/roles/svc-ai-litellm/tasks/utils/consumer_contract.yml @@ -0,0 +1,25 @@ +--- +- name: "โœ… Assert '{{ application_id }}' carries a gateway virtual key" + ansible.builtin.assert: + that: + - (lookup('config', application_id, 'secrets.credentials.litellm_api_key', '') | trim) | length > 0 + fail_msg: >- + {{ application_id }} enables services.litellm but its + credentials.litellm_api_key is empty, so its native AI surface would + reach the gateway unauthenticated. + +- name: "โœ… Assert the AI base URL of '{{ application_id }}' stays inside the deployment" + ansible.builtin.assert: + that: + - (LITELLM_BASE_LOCAL_URL | urlsplit('scheme')) == 'http' + - "'.' not in (LITELLM_BASE_LOCAL_URL | urlsplit('hostname'))" + - (LITELLM_BASE_LOCAL_URL | urlsplit('hostname')) != lookup('domain', application_id) + - (LITELLM_BASE_LOCAL_URL | urlsplit('port') | int) == (lookup('config', 'svc-ai-litellm', 'services.litellm.ports.internal.http') | int) + fail_msg: >- + {{ application_id }} would send inference traffic to + '{{ LITELLM_BASE_LOCAL_URL }}'. Only the container-network gateway is + allowed: plain http, an undotted service name (the dns-search suffix + turns a dotted host into the public FQDN and routes it through the + ingress), a host that is not this role's own domain, and the gateway's + internal port {{ lookup('config', 'svc-ai-litellm', 'services.litellm.ports.internal.http') }} + rather than its published one. diff --git a/roles/svc-ai-litellm/templates/compose.yml.j2 b/roles/svc-ai-litellm/templates/compose.yml.j2 new file mode 100644 index 0000000000..cbf062dde3 --- /dev/null +++ b/roles/svc-ai-litellm/templates/compose.yml.j2 @@ -0,0 +1,19 @@ +{% include 'roles/sys-svc-compose/templates/base.yml.j2' %} + + {% set service_name = 'litellm' %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, 'litellm') }} + {{ lookup('compose_only', 'container_name', LITELLM_CONTAINER) }} + {{ lookup('container_ports', ['litellm', 'http', DOCKER_BIND_HOST]) | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} + command: > + --host 0.0.0.0 + --port {{ LITELLM_PORT }} + --config {{ LITELLM_CONFIG_PATH_DOCKER }} + {{ lookup('container_networks') | indent(4) }} + {{ lookup('container_depends_on', application_id) | indent(4) }} + +{{ lookup('compose_networks') }} + +{{ lookup('compose_volumes') }} diff --git a/roles/svc-ai-litellm/templates/config.yaml.j2 b/roles/svc-ai-litellm/templates/config.yaml.j2 new file mode 100644 index 0000000000..c4bed5dcce --- /dev/null +++ b/roles/svc-ai-litellm/templates/config.yaml.j2 @@ -0,0 +1,39 @@ +{% set _ollama_models = lookup('config', 'svc-ai-ollama', 'services.ollama.preload_models') if LITELLM_OLLAMA_BACKEND | bool else [] %} +{% set _lmstudio_models = lookup('config', 'svc-ai-lmstudio', 'services.lmstudio.preload_models') if LITELLM_LMSTUDIO_BACKEND | bool else [] %} +{% set _remote_models = LITELLM_REMOTE_BACKENDS | selectattr('key') | list %} +{% set has_backend = _ollama_models or _lmstudio_models or _remote_models %} +model_list:{{ ' []' if not has_backend else '' }} +{% for _model in _ollama_models %} + - model_name: "{{ _model.alias }}" + litellm_params: + model: "ollama/{{ _model.alias }}" + api_base: {{ OLLAMA_BASE_LOCAL_URL }} + rpm: 1000 + max_tokens: {{ LITELLM_MAX_OUTPUT_TOKENS }} + timeout: {{ LITELLM_UPSTREAM_TIMEOUT }} +{% endfor %} +{% for _model in _lmstudio_models if _model.alias not in (_ollama_models | map(attribute='alias') | list) %} + - model_name: "{{ _model.alias }}" + litellm_params: + model: "openai/{{ _model.name }}" + api_base: {{ LMSTUDIO_BASE_LOCAL_URL }}/v1 + api_key: lm-studio + rpm: 1000 + max_tokens: {{ LITELLM_MAX_OUTPUT_TOKENS }} + timeout: {{ LITELLM_UPSTREAM_TIMEOUT }} +{% endfor %} +{% for _backend in _remote_models %} + - model_name: "{{ _backend.alias }}" + litellm_params: + model: "{{ _backend.model }}" + api_key: os.environ/{{ _backend.env }} + max_tokens: {{ LITELLM_MAX_OUTPUT_TOKENS }} + timeout: {{ LITELLM_UPSTREAM_TIMEOUT }} +{% endfor %} + +litellm_settings: + drop_params: true + +general_settings: + master_key: os.environ/LITELLM_MASTER_KEY + database_url: os.environ/DATABASE_URL diff --git a/roles/svc-ai-litellm/templates/env.j2 b/roles/svc-ai-litellm/templates/env.j2 new file mode 100644 index 0000000000..e77c43da8e --- /dev/null +++ b/roles/svc-ai-litellm/templates/env.j2 @@ -0,0 +1,19 @@ +{% include 'roles/sys-svc-container/templates/env.j2' %} + +LITELLM_MASTER_KEY={{ LITELLM_MASTER_KEY | dotenv_quote }} +DATABASE_URL={{ lookup('database', application_id, 'url_full') | dotenv_quote }} +STORE_MODEL_IN_DB=False +UI_USERNAME={{ lookup('users', 'administrator').username }} +UI_PASSWORD={{ lookup('config', application_id, 'secrets.credentials.ui_password') | dotenv_quote }} +{% for _backend in LITELLM_REMOTE_BACKENDS if _backend.key %} +{{ _backend.env }}={{ _backend.key | dotenv_quote }} +{% endfor %} +{% if LITELLM_UI_SSO | bool %} +PROXY_BASE_URL={{ LITELLM_UI_BASE_URL }} +PROXY_ADMIN_ID={{ LITELLM_UI_ADMIN }} +GENERIC_CLIENT_ID={{ OIDC.CLIENT.ID }} +GENERIC_CLIENT_SECRET={{ OIDC.CLIENT.SECRET | dotenv_quote }} +GENERIC_AUTHORIZATION_ENDPOINT={{ OIDC.CLIENT.AUTHORIZE_URL }} +GENERIC_TOKEN_ENDPOINT={{ OIDC.CLIENT.TOKEN_URL }} +GENERIC_USERINFO_ENDPOINT={{ OIDC.CLIENT.USER_INFO_URL }} +{% endif %} diff --git a/roles/svc-ai-litellm/templates/test.env.j2 b/roles/svc-ai-litellm/templates/test.env.j2 new file mode 100644 index 0000000000..a3a33b2cc6 --- /dev/null +++ b/roles/svc-ai-litellm/templates/test.env.j2 @@ -0,0 +1,15 @@ +{%- set _ollama_models = (lookup('config', 'svc-ai-ollama', 'services.ollama.preload_models') | map(attribute='alias') | list) if LITELLM_TEST_CONTRACT.ollama | bool else [] -%} +{%- set _lmstudio_declared = lookup('config', 'svc-ai-lmstudio', 'services.lmstudio.preload_models') | map(attribute='alias') | list -%} +{%- set _lmstudio_only = _lmstudio_declared | reject('in', _ollama_models) | list -%} +{%- set _remote = LITELLM_REMOTE_BACKENDS | selectattr('key') | map(attribute='alias') | list -%} +{%- set _expected = _ollama_models + (_lmstudio_only if LITELLM_TEST_CONTRACT.lmstudio | bool else []) + _remote -%} +LITELLM_CONTAINER={{ CLI_LOCAL_CID }} +LITELLM_PORT={{ LITELLM_PORT }} +LITELLM_MASTER_KEY_B64={{ LITELLM_MASTER_KEY | b64encode }} +LITELLM_CHAT_MODEL={{ LITELLM_CHAT_MODEL }} +LITELLM_CHAT_MODEL_SERVED={{ LITELLM_TEST_CONTRACT.served | bool | string | lower }} +LITELLM_OLLAMA_ENABLED={{ LITELLM_TEST_CONTRACT.ollama | bool | string | lower }} +LITELLM_LMSTUDIO_ENABLED={{ LITELLM_TEST_CONTRACT.lmstudio | bool | string | lower }} +LITELLM_LMSTUDIO_ALIASES='{{ _lmstudio_only | to_json }}' +LITELLM_REMOTE_ALIASES='{{ _remote | to_json }}' +LITELLM_EXPECTED_MODELS='{{ _expected | to_json }}' diff --git a/roles/svc-ai-litellm/vars/main.yml b/roles/svc-ai-litellm/vars/main.yml new file mode 100644 index 0000000000..a2cbbf9cef --- /dev/null +++ b/roles/svc-ai-litellm/vars/main.yml @@ -0,0 +1,31 @@ +--- +application_id: "svc-ai-litellm" +entity_name: "{{ application_id | get_entity_name }}" + +LITELLM_CONTAINER: "{{ lookup('config', application_id, 'services.litellm.name') }}" +LITELLM_PORT: "{{ lookup('config', application_id, 'services.litellm.ports.internal.http') }}" +LITELLM_MASTER_KEY: "{{ lookup('config', application_id, 'secrets.credentials.master_key') }}" +LITELLM_MAX_OUTPUT_TOKENS: "{{ lookup('config', application_id, 'services.litellm.max_output_tokens') }}" +LITELLM_UPSTREAM_TIMEOUT: "{{ lookup('config', application_id, 'services.litellm.upstream_timeout') }}" +LITELLM_CONFIG_PATH_HOST: "{{ [ lookup('container', application_id, 'directories.config'), 'config.yaml' ] | path_join }}" +LITELLM_CONFIG_PATH_DOCKER: "{{ lookup('volume', application_id, 'litellm_config').target }}" +LITELLM_OPENAI_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.openai_api_key') }}" +LITELLM_ANTHROPIC_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.anthropic_api_key') }}" +LITELLM_OPENROUTER_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.openrouter_api_key') }}" +LITELLM_REMOTE_BACKENDS: + - alias: openai/gpt-4o-mini + model: openai/gpt-4o-mini + key: "{{ LITELLM_OPENAI_API_KEY }}" + env: OPENAI_API_KEY + - alias: anthropic/claude-sonnet-4-5 + model: anthropic/claude-sonnet-4-5 + key: "{{ LITELLM_ANTHROPIC_API_KEY }}" + env: ANTHROPIC_API_KEY + - alias: openrouter/auto + model: openrouter/openrouter/auto + key: "{{ LITELLM_OPENROUTER_API_KEY }}" + env: OPENROUTER_API_KEY +LITELLM_UI_ROLE: "web-app-litellm" +LITELLM_UI_SSO: "{{ (LITELLM_UI_ROLE in group_names) and (lookup('sso', LITELLM_UI_ROLE, 'is_oidc_native') | bool) }}" +LITELLM_UI_BASE_URL: "{{ lookup('tls', LITELLM_UI_ROLE, 'url.base') }}" +LITELLM_UI_ADMIN: "{{ lookup('users', 'administrator').username }}" diff --git a/roles/svc-ai-lmstudio/README.md b/roles/svc-ai-lmstudio/README.md new file mode 100644 index 0000000000..bb671103ee --- /dev/null +++ b/roles/svc-ai-lmstudio/README.md @@ -0,0 +1,87 @@ +# LM Studio + +## Description + +[LM Studio](https://lmstudio.ai/) is a runtime for open large language models. Its headless server mode loads models from a local store and answers chat and completion requests over an OpenAI-compatible HTTP API, so prompts and model weights stay on the machine that runs them. + +## Overview + +This role deploys LM Studio as a headless model server in a single container, in both Docker Compose and Docker Swarm deployments. The server listens on port 1234 on the internal container network and is not published through the reverse proxy, while downloaded models and server settings persist in a dedicated volume. The role downloads its declared models at deploy time and the LiteLLM Gateway publishes them under the same aliases Ollama uses, so a consumer asks for one model name and reaches whichever backend the deployment provides. + +## Cosmos + +The diagram places LM Studio in the Infinito.Nexus cosmos: the components it deploys (capabilities), the central services it consumes (dependencies), and its outward reach (federation and bridged external networks). + +```mermaid +flowchart LR + subgraph deps [Dependencies] + dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local ๐Ÿ’ป"] + end + subgraph role [svc-ai-lmstudio ๐Ÿณ๐Ÿ] + svc_lmstudio["lmstudio"] + svc_container_backup["container_backup"] + end + subgraph dependents [Dependents] + dpt_svc_ai_litellm["svc-ai-litellm ๐Ÿณ๐Ÿ"] + end + dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup + svc_lmstudio -. "0..1" .-> dpt_svc_ai_litellm +``` + +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (๐Ÿ’ป host, ๐Ÿณ compose, ๐Ÿ swarm); โŒ marks a service that is explicitly turned off, and โš™๏ธ an Ansible role dependency declared in `meta/main.yml`. + +## Features + +- **OpenAI-compatible endpoint:** The headless server answers `/v1` requests on port 1234 inside the container network. +- **CPU inference:** The role pins the CPU build of the upstream image and passes no GPU device into the container. +- **Persistent model store:** A named volume mounted at `/root/.lmstudio` keeps downloaded models and server settings across redeploys. +- **Preloaded models:** Every entry of `services.lmstudio.preload_models` is downloaded on the hosting node with `lms get --gguf`, overlapped and reaped like the Ollama pre-pull. Each entry carries the `source` repository to download, the `name` LM Studio indexes that repository under and the gateway addresses it by, and the `alias` the gateway publishes it as. `source` is a full Hugging Face URL, never a search term: a search term resolves to whichever model the catalogue lists first. +- **Loading:** The pre-pull downloads without loading. LM Studio serves with just-in-time loading, so the first `/v1/chat/completions` naming a `name` loads that model; the gateway's warm task issues that first request at deploy time. +- **Gateway backend:** The LiteLLM Gateway publishes those aliases, which are the names Ollama serves too, so the same model name routes to whichever local backend a deployment runs. +- **Bounded resources:** The container is capped at 4 CPUs, 8 GB of memory and 2048 processes, and the role declares a minimum of 588 MB free storage for the image; downloaded models grow the volume beyond that. +- **Backup integration:** Backup Docker Volumes snapshots the model volume when that role is present, without stopping the container. + +## Quick Setup + +### Development + +Clone, set up the workstation, and deploy LM Studio onto the local stack: + +```bash +git clone https://github.com/infinito-nexus/core.git +cd core +make onboard +make compose-deploy mode=reinstall apps=svc-ai-lmstudio full_cycle=false +``` + +### Production + +Run the published image to provision the inventory and deploy LM Studio to a managed server (the mounted volume persists the inventory): + +```bash +APP=svc-ai-lmstudio +HOST= +DOMAIN= +TLS_MODE=self_signed +SSH_PUBLIC_KEY="" + +docker run --rm -it \ + -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + ghcr.io/infinito-nexus/core/debian bash -c ' + INVENTORY=/etc/infinito.nexus/inventories/production + infinito administration inventory provision "$INVENTORY" \ + --inventory-file "$INVENTORY/devices.yml" \ + --host "$HOST" \ + --include "$APP" \ + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + infinito administration deploy dedicated "$INVENTORY/devices.yml" \ + --password-file "$INVENTORY/.password" \ + --diff -vv' +``` + +## Credits + +Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. +Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). +Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/svc-ai-lmstudio/files/test/.nocheck b/roles/svc-ai-lmstudio/files/test/.nocheck new file mode 100644 index 0000000000..a0fdb0bf8c --- /dev/null +++ b/roles/svc-ai-lmstudio/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; the CLI runner stages roles//files/test/ by path. diff --git a/roles/svc-ai-lmstudio/files/test/test.sh b/roles/svc-ai-lmstudio/files/test/test.sh new file mode 100644 index 0000000000..c981fce35d --- /dev/null +++ b/roles/svc-ai-lmstudio/files/test/test.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +# shellcheck shell=bash +# +# Env (rendered into test.env from templates/test.env.j2): +# LMSTUDIO_CONTAINER resolved container id on this node +# LMSTUDIO_PORT the daemon's HTTP port +# LMSTUDIO_EXPECTED_MODELS JSON array of model names the daemon must serve +# LMSTUDIO_EXPECTED_BLOBS JSON array of / paths under models/ +# LMSTUDIO_EXPECTED_DIGESTS JSON array of sha256, aligned with the blobs +# LMSTUDIO_MODELS_DIR the models mount inside the container +# RETRIES attempts (default 30) +# SLEEP_SECONDS wait between (default 10) + +set -uo pipefail + +RETRIES="${RETRIES:-30}" +SLEEP_SECONDS="${SLEEP_SECONDS:-10}" +MODELS_DIR="${LMSTUDIO_MODELS_DIR}" + +[ -n "${LMSTUDIO_CONTAINER}" ] || { + echo "[FATAL] LMSTUDIO_CONTAINER unset; the harness did not resolve a container" >&2 + exit 2 +} + +in_container() { + container exec "${LMSTUDIO_CONTAINER}" "$@" +} + +json_items() { + python3 -c 'import json,sys; [print(x) for x in json.loads(sys.argv[1])]' "$1" +} + +serves_model() { + in_container curl -fsS --connect-timeout 5 --max-time 30 "http://127.0.0.1:${LMSTUDIO_PORT}/v1/models" 2>/dev/null | + python3 -c 'import json,sys; d=json.load(sys.stdin); print("\n".join(m.get("id","") for m in d.get("data",[])))' 2>/dev/null | + grep -qxF "$1" +} + +failed=0 + +echo "=== 1. the CLI authenticates against its own daemon ===" +attempt=1 +auth_out="" +while [ "${attempt}" -le "${RETRIES}" ]; do + if auth_out="$(in_container /app/.bundle/lms ls 2>&1)"; then + echo "[OK] lms ls authenticated" + break + fi + if printf '%s' "${auth_out}" | grep -q 'authPacket'; then + echo "[FAIL] the daemon rejected its own CLI: $(printf '%s' "${auth_out}" | grep -m1 authPacket)" >&2 + echo " a second daemon shares /root/.lmstudio and rewrote .internal/lms-key-2" >&2 + exit 1 + fi + attempt=$((attempt + 1)) + [ "${attempt}" -le "${RETRIES}" ] && sleep "${SLEEP_SECONDS}" +done +if [ "${attempt}" -gt "${RETRIES}" ]; then + echo "[FAIL] lms ls never succeeded after ${RETRIES} attempts: ${auth_out}" >&2 + exit 1 +fi + +echo "=== 2. every declared blob is in place with its declared digest ===" +mapfile -t blobs < <(json_items "${LMSTUDIO_EXPECTED_BLOBS}") +mapfile -t digests < <(json_items "${LMSTUDIO_EXPECTED_DIGESTS}") +for i in "${!blobs[@]}"; do + path="${MODELS_DIR}/${blobs[$i]}" + if ! in_container test -f "${path}"; then + echo "[FAIL] ${blobs[$i]} is not in the model store" >&2 + failed=1 + continue + fi + actual="$(in_container sha256sum "${path}" 2>/dev/null | awk '{print $1}')" + if [ "${actual}" != "${digests[$i]}" ]; then + echo "[FAIL] ${blobs[$i]} hashes to ${actual}, declared ${digests[$i]}" >&2 + failed=1 + continue + fi + echo "[OK] ${blobs[$i]} present and matching" +done + +echo "=== 3. the daemon serves every declared model ===" +mapfile -t models < <(json_items "${LMSTUDIO_EXPECTED_MODELS}") +for model in "${models[@]}"; do + attempt=1 + while [ "${attempt}" -le "${RETRIES}" ]; do + if serves_model "${model}"; then + echo "[OK] ${model} is served" + break + fi + attempt=$((attempt + 1)) + [ "${attempt}" -le "${RETRIES}" ] && sleep "${SLEEP_SECONDS}" + done + if [ "${attempt}" -gt "${RETRIES}" ]; then + echo "[FAIL] ${model} is on disk but /v1/models never listed it" >&2 + echo " the daemon did not index the store it was given at startup" >&2 + failed=1 + fi +done + +[ "${failed}" -eq 0 ] || exit 1 +echo "[OK] svc-ai-lmstudio serves every declared model from the seeded store" diff --git a/roles/svc-ai-lmstudio/meta/info.yml b/roles/svc-ai-lmstudio/meta/info.yml new file mode 100644 index 0000000000..b0b71b2082 --- /dev/null +++ b/roles/svc-ai-lmstudio/meta/info.yml @@ -0,0 +1,5 @@ +--- +# nocheck: info-media no official demo video +logo: + class: fa-solid fa-desktop +homepage: https://lmstudio.ai/ diff --git a/roles/svc-ai-lmstudio/meta/main.yml b/roles/svc-ai-lmstudio/meta/main.yml new file mode 100644 index 0000000000..d09aefc76b --- /dev/null +++ b/roles/svc-ai-lmstudio/meta/main.yml @@ -0,0 +1,34 @@ +--- +galaxy_info: + author: Kevin Veen-Birkenbach + description: Headless local model server for open LLMs with an OpenAI-compatible API on the container network + license: Infinito.Nexus Community License (Non-Commercial) + company: | + Kevin Veen-Birkenbach + https://www.veen.world + galaxy_tags: + - ai + - llm + - inference + - lmstudio + - offline + - self-hosted + issue_tracker_url: https://s.infinito.nexus/issues + min_ansible_version: "2.9" + platforms: + - name: ArchLinux + versions: + - all + - name: Debian + versions: + - all + - name: EL + versions: + - all + - name: Fedora + versions: + - all + - name: Ubuntu + versions: + - all +dependencies: [] diff --git a/roles/svc-ai-lmstudio/meta/networks.yml b/roles/svc-ai-lmstudio/meta/networks.yml new file mode 100644 index 0000000000..f313538776 --- /dev/null +++ b/roles/svc-ai-lmstudio/meta/networks.yml @@ -0,0 +1,6 @@ +--- +local: + subnet: 192.168.108.0/24 +overlay: + modes: [compose, swarm] + topology: shared_net diff --git a/roles/svc-ai-lmstudio/meta/services.yml b/roles/svc-ai-lmstudio/meta/services.yml new file mode 100644 index 0000000000..53bab2e9c2 --- /dev/null +++ b/roles/svc-ai-lmstudio/meta/services.yml @@ -0,0 +1,36 @@ +--- +lmstudio: + modes: + compose: + enabled: true + swarm: + enabled: true + bond: 1 + enabled: true + shared: true + backup: + no_stop_required: true + image: lmstudio/llmster-preview + # nocheck: docker-version -- the repository publishes 2 tags and neither is a version; 'cpu' selects the backend, not a release + version: cpu + name: lmstudio + platform_arch: x86_64 + min_storage: 588MB + cpus: "4.0" + mem_reservation: 6g + mem_limit: 8g + pids_limit: 2048 + ports: + internal: + http: 1234 + preload_models: "{{ AI_LOCAL_MODELS }}" + preload_async_time: 3600 + preload_floor_seconds: 600 + preload_min_bytes_per_second: 1000000 + lifecycle: beta + +# nocheck: playwright-service-flag, dynamic-flag +container_backup: # nocheck: bond-baseline + bond: 1 + enabled: "{{ 'svc-bkp-volume-2-local' in group_names }}" + shared: true diff --git a/roles/svc-ai-lmstudio/meta/tests.yml b/roles/svc-ai-lmstudio/meta/tests.yml new file mode 100644 index 0000000000..712dbdf2f8 --- /dev/null +++ b/roles/svc-ai-lmstudio/meta/tests.yml @@ -0,0 +1,4 @@ +--- +cli: + container_service_key: lmstudio + timeout: 900 diff --git a/roles/svc-ai-lmstudio/meta/variants.yml b/roles/svc-ai-lmstudio/meta/variants.yml new file mode 100644 index 0000000000..5a12caf234 --- /dev/null +++ b/roles/svc-ai-lmstudio/meta/variants.yml @@ -0,0 +1,10 @@ +--- +# Matrix-deploy variant overrides for this role. +# See docs/contributing/artefact/files/role/variants.md for the file format. + +- services: + container_backup: + enabled: true + lmstudio: + mem_reservation: 1g + mem_limit: 2g diff --git a/roles/svc-ai-lmstudio/meta/volumes.yml b/roles/svc-ai-lmstudio/meta/volumes.yml new file mode 100644 index 0000000000..0250216548 --- /dev/null +++ b/roles/svc-ai-lmstudio/meta/volumes.yml @@ -0,0 +1,17 @@ +--- +lmstudio_data: + type: volume + name: lmstudio_data + # nocheck: nfs-false-data-loss Reason: per-daemon state LM Studio rewrites in place (lms-key-2, settings.json, extensions/plugins, bin/lms, server-logs), regenerated on every start; the models it indexes live in lmstudio_models + nfs: false + mounts: + - service: lmstudio + target: /root/.lmstudio + +# nocheck: embedded-state-on-nfs content-addressed model blobs only; every writer fetches against the sha256 AI_LOCAL_MODELS declares and the play fails unless the store reads back at that digest, so concurrent writers of one file write identical bytes +lmstudio_models: + type: volume + name: lmstudio_models + mounts: + - service: lmstudio + target: /root/.lmstudio/models diff --git a/roles/svc-ai-lmstudio/tasks/00_core.yml b/roles/svc-ai-lmstudio/tasks/00_core.yml new file mode 100644 index 0000000000..e29cf2a6f2 --- /dev/null +++ b/roles/svc-ai-lmstudio/tasks/00_core.yml @@ -0,0 +1,19 @@ +--- +- include_tasks: utils/once/flag.yml + +- name: "โฌ‡๏ธ Seed the shared model store before the daemons index it" + ansible.builtin.include_tasks: + file: utils/preseed.yml + apply: + delegate_to: "{{ LMSTUDIO_NFS_SERVER }}" + run_once: true + when: LMSTUDIO_PRESEED_ENABLED | bool + +- name: "๐Ÿ”ง Setup container network for {{ application_id }}" + include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/network/routine.yml') }}" + vars: + compose_handlers_flush: true + +- name: "โฌ‡๏ธ Manager-side model pre-pull on the hosting node" + ansible.builtin.include_tasks: 01_manager_ops.yml + when: IS_STACK_HOST | bool diff --git a/roles/svc-ai-lmstudio/tasks/01_manager_ops.yml b/roles/svc-ai-lmstudio/tasks/01_manager_ops.yml new file mode 100644 index 0000000000..a4362e07d8 --- /dev/null +++ b/roles/svc-ai-lmstudio/tasks/01_manager_ops.yml @@ -0,0 +1,10 @@ +--- +- name: "๐Ÿ” Resolve every node that hosts an {{ application_id }} task" + ansible.builtin.include_tasks: utils/nodes.yml + +- name: "โฌ‡๏ธ Preload LM Studio on each hosting node" + ansible.builtin.include_tasks: utils/preload/node.yml + loop: "{{ LMSTUDIO_HOST_NODES }}" + loop_control: + loop_var: lmstudio_node + label: "{{ lmstudio_node }}" diff --git a/roles/svc-ai-lmstudio/tasks/main.yml b/roles/svc-ai-lmstudio/tasks/main.yml new file mode 100644 index 0000000000..6ebae0cae5 --- /dev/null +++ b/roles/svc-ai-lmstudio/tasks/main.yml @@ -0,0 +1,5 @@ +--- +- include_tasks: 00_core.yml + when: run_once_svc_ai_lmstudio is not defined + vars: + application_id: svc-ai-lmstudio diff --git a/roles/svc-ai-lmstudio/tasks/utils/cid.yml b/roles/svc-ai-lmstudio/tasks/utils/cid.yml new file mode 100644 index 0000000000..e29b8fafba --- /dev/null +++ b/roles/svc-ai-lmstudio/tasks/utils/cid.yml @@ -0,0 +1,22 @@ +--- +- name: "๐Ÿ” Resolve the LM Studio container on '{{ lmstudio_node }}'" + ansible.builtin.shell: | + {% if DEPLOYMENT_MODE == 'swarm' %} + container ps \ + --filter "label=com.docker.swarm.service.name={{ lmstudio_service_name }}" \ + --filter status=running \ + --format '{{ "{{.ID}}" }}' | head -1 + {% else %} + echo {{ LMSTUDIO_CONTAINER | quote }} + {% endif %} + register: lmstudio_node_cid + changed_when: false + retries: 30 + delay: 2 + until: DEPLOYMENT_MODE == 'compose' or (lmstudio_node_cid.stdout | trim) | length > 0 + delegate_to: "{{ lmstudio_node }}" + +- name: "๐Ÿ”ง Target '{{ lmstudio_node }}' for the next LM Studio step" + ansible.builtin.set_fact: + LMSTUDIO_HOST_NODE: "{{ lmstudio_node }}" + LMSTUDIO_LOCAL_CID: "{{ lmstudio_node_cid.stdout | trim }}" diff --git a/roles/svc-ai-lmstudio/tasks/utils/nodes.yml b/roles/svc-ai-lmstudio/tasks/utils/nodes.yml new file mode 100644 index 0000000000..b3ee1a6726 --- /dev/null +++ b/roles/svc-ai-lmstudio/tasks/utils/nodes.yml @@ -0,0 +1,29 @@ +--- +- name: "๐Ÿ”ง Resolve the swarm service name of '{{ entity_name }}'" + ansible.builtin.set_fact: + lmstudio_service_name: "{{ lookup('container_service', application_id, entity_name) if DEPLOYMENT_MODE == 'swarm' else '' }}" + +- name: "โณ Wait until every LM Studio task has converged" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/wait_converged.yml') }}" + vars: + wait_service_key: "{{ entity_name }}" + wait_service_name: "{{ lmstudio_service_name }}" + +- name: "๐Ÿ” List every node that runs an LM Studio task" + ansible.builtin.shell: | + container service ps {{ lmstudio_service_name | quote }} \ + --filter desired-state=running \ + --format '{{ "{{.Node}}" }}' | sort -u + register: lmstudio_node_scan + changed_when: false + retries: 30 + delay: 2 + until: (lmstudio_node_scan.stdout | trim) | length > 0 + delegate_to: "{{ STACK_HOST }}" + when: DEPLOYMENT_MODE == 'swarm' + +- name: "๐Ÿ”ง Set the LM Studio hosting nodes" + ansible.builtin.set_fact: + LMSTUDIO_HOST_NODES: >- + {{ (lmstudio_node_scan.stdout_lines | map('trim') | select | list) + if DEPLOYMENT_MODE == 'swarm' else [inventory_hostname] }} diff --git a/roles/svc-ai-lmstudio/tasks/utils/preload/node.yml b/roles/svc-ai-lmstudio/tasks/utils/preload/node.yml new file mode 100644 index 0000000000..b89e50e2e5 --- /dev/null +++ b/roles/svc-ai-lmstudio/tasks/utils/preload/node.yml @@ -0,0 +1,42 @@ +--- +- name: "๐Ÿ” Resolve the container before preloading on '{{ lmstudio_node }}'" + ansible.builtin.include_tasks: utils/cid.yml + +- name: "๐Ÿ—„๏ธ Measure the space the model store offers on '{{ lmstudio_node }}'" + ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec {{ LMSTUDIO_LOCAL_CID | quote }} df -P -B1 {{ LMSTUDIO_MODELS_TARGET | quote }} + register: lmstudio_store_space + changed_when: false + retries: 30 + delay: 2 + until: lmstudio_store_space.rc == 0 + delegate_to: "{{ lmstudio_node }}" + when: not (LMSTUDIO_PRESEED_ENABLED | bool) + +- name: "๐Ÿ›‘ Refuse to preload models the store on '{{ lmstudio_node }}' cannot hold" + vars: + _free: "{{ lmstudio_store_space.stdout_lines[1].split()[3] | int }}" + _required: "{{ LMSTUDIO_PRELOAD_LARGEST_BYTES | int }}" + ansible.builtin.fail: + msg: >- + The model store on {{ lmstudio_node }} has + {{ (_free | int / 1024 / 1024 / 1024) | round(1) }} GiB free, less than the + {{ (_required | int / 1024 / 1024 / 1024) | round(1) }} GiB the largest + declared model needs. Shrink AI_LOCAL_MODELS in group_vars/all/16_ai.yml or + give the node more disk. + when: + - not (LMSTUDIO_PRESEED_ENABLED | bool) + - _free | int < _required | int + +- name: "โฌ‡๏ธ Preload the LM Studio models on '{{ lmstudio_node }}'" + block: + - name: "โฌ‡๏ธ Preload the LM Studio models (first pass)" + ansible.builtin.include_tasks: utils/preload/pull.yml + rescue: + - name: "๐Ÿ Re-raise the preload failure unchanged in swarm" # nocheck: rescue-recovery a timed-out transfer leaves the daemon reporting 0.00% for every further pull, and restarting the container it owns is the only lever the role has, though CI job 105558224377 shows a restart returning rc 0 without clearing it; the generic capture cannot even try, so swarm re-raises here instead, because under any_errors_fatal a rescued host keeps running while every other host is already marked failed, and compose ends the block by preloading again so an unrecovered failure still re-raises + ansible.builtin.fail: + msg: "{{ ansible_failed_result.msg | default('LM Studio preload failed') }}" + when: DEPLOYMENT_MODE == 'swarm' + + - name: "โ™ป๏ธ Recover the wedged transfer and preload again" + ansible.builtin.include_tasks: utils/preload/recover.yml diff --git a/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml b/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml new file mode 100644 index 0000000000..162812fb1c --- /dev/null +++ b/roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml @@ -0,0 +1,39 @@ +--- +- name: โฌ‡๏ธ Pre-pull LM Studio models + ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec -i {{ LMSTUDIO_LOCAL_CID | quote }} lms get --yes --gguf {{ model.source | quote }} + environment: + CONTAINER_EXEC_TIMEOUT: >- + {{ [ LMSTUDIO_PRELOAD_FLOOR_SECONDS | int, + ((model.bytes | int) / (LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND | int)) + | round(0, 'ceil') | int ] | max }} + register: lmstudio_pull_result + loop: "{{ LMSTUDIO_PRELOAD_MODELS }}" + loop_control: + loop_var: model + label: "{{ model.alias }}" + # rationale: async; the reap below reads every job back before the play continues, so no model is still downloading when playwright starts + async: "{{ LMSTUDIO_PRELOAD_ASYNC_TIME if ASYNC_ENABLED | bool else omit }}" + poll: "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}" + retries: "{{ 0 if ASYNC_ENABLED | bool else 1 }}" + delay: 15 + until: > + (lmstudio_pull_result.rc | default(0)) == 0 or + ('You already have this model' in (lmstudio_pull_result.stderr | default(''))) + changed_when: false + failed_when: >- + (lmstudio_pull_result.failed | default(false)) + and 'You already have this model' not in ((lmstudio_pull_result.stdout | default('')) ~ (lmstudio_pull_result.stderr | default(''))) + delegate_to: "{{ LMSTUDIO_HOST_NODE }}" + +- name: "โณ Reap the LM Studio model pre-pulls" + ansible.builtin.include_tasks: + file: utils/async/reap.yml + apply: + delegate_to: "{{ LMSTUDIO_HOST_NODE }}" + vars: + async_reap_jobs: "{{ lmstudio_pull_result.results | default([]) }}" + async_reap_label: "LM Studio model pre-pull" + async_reap_tolerate: + - "You already have this model" + ASYNC_TIME: "{{ LMSTUDIO_PRELOAD_ASYNC_TIME }}" diff --git a/roles/svc-ai-lmstudio/tasks/utils/preload/recover.yml b/roles/svc-ai-lmstudio/tasks/utils/preload/recover.yml new file mode 100644 index 0000000000..e8f526456f --- /dev/null +++ b/roles/svc-ai-lmstudio/tasks/utils/preload/recover.yml @@ -0,0 +1,28 @@ +--- +- name: "๐Ÿฉบ Dump the LM Studio transfer record" + ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec -i {{ LMSTUDIO_LOCAL_CID | quote }} + cat /root/.lmstudio/.internal/single-downloads-info.json + register: lmstudio_transfer_record + changed_when: false + failed_when: false + delegate_to: "{{ LMSTUDIO_HOST_NODE }}" + +- name: "๐Ÿฉบ Report the LM Studio transfer record" + ansible.builtin.debug: + var: lmstudio_transfer_record.stdout + +- name: "โ™ป๏ธ Restart LM Studio to release the wedged transfer" + ansible.builtin.command: container restart {{ LMSTUDIO_LOCAL_CID }} + changed_when: true + delegate_to: "{{ LMSTUDIO_HOST_NODE }}" + +- name: "๐Ÿ” Re-resolve the {{ application_id }} hosting node + container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ entity_name }}" + resolve_output_prefix: LMSTUDIO + resolve_compose_cid: "{{ LMSTUDIO_CONTAINER }}" + +- name: "โฌ‡๏ธ Preload the LM Studio models (after the restart)" + ansible.builtin.include_tasks: utils/preload/pull.yml diff --git a/roles/svc-ai-lmstudio/tasks/utils/preseed.yml b/roles/svc-ai-lmstudio/tasks/utils/preseed.yml new file mode 100644 index 0000000000..49fa570841 --- /dev/null +++ b/roles/svc-ai-lmstudio/tasks/utils/preseed.yml @@ -0,0 +1,118 @@ +--- +- name: "๐Ÿ“ Create the shared model store before the daemons start" + ansible.builtin.file: + path: "{{ LMSTUDIO_SHARED_MODELS_PATH }}/{{ model.repo }}" + state: directory + mode: "0755" + loop: "{{ LMSTUDIO_PRELOAD_MODELS }}" + loop_control: + loop_var: model + label: "{{ model.file }}" + +- name: "๐Ÿ“ Create the staging directory beside the model store" + ansible.builtin.file: + path: "{{ LMSTUDIO_SHARED_STAGING_PATH }}" + state: directory + mode: "0755" + +- name: "๐Ÿ” Read what the shared model store already holds" + ansible.builtin.stat: + path: "{{ LMSTUDIO_SHARED_MODELS_PATH }}/{{ model.repo }}/{{ model.file }}" + checksum_algorithm: sha256 + register: lmstudio_present + changed_when: false + loop: "{{ LMSTUDIO_PRELOAD_MODELS }}" + loop_control: + loop_var: model + label: "{{ model.file }}" + +- name: "๐Ÿ—„๏ธ Measure the free space the shared model store offers" + ansible.builtin.command: "df -P -B1 {{ LMSTUDIO_SHARED_MODELS_PATH | quote }}" + register: lmstudio_export_space + changed_when: false + +- name: "๐Ÿ›‘ Refuse to fetch models the shared store cannot hold" + vars: + _free: "{{ lmstudio_export_space.stdout_lines[1].split()[3] | int }}" + _absent: >- + {{ lmstudio_present.results + | rejectattr('stat.exists') + | map(attribute='model.bytes') | map('int') | sum }} + _required: "{{ (_absent | int) + (LMSTUDIO_PRELOAD_LARGEST_BYTES | int) }}" + ansible.builtin.fail: + msg: >- + The shared model store on {{ LMSTUDIO_NFS_SERVER }} has + {{ (_free | int / 1024 / 1024 / 1024) | round(1) }} GiB free but needs + {{ (_required | int / 1024 / 1024 / 1024) | round(1) }} GiB: it is missing + {{ (_absent | int / 1024 / 1024 / 1024) | round(1) }} GiB of declared models, + plus {{ (LMSTUDIO_PRELOAD_LARGEST_BYTES | int / 1024 / 1024 / 1024) | round(1) }} + GiB for the largest one while it stages. Shrink AI_LOCAL_MODELS in + group_vars/all/16_ai.yml or grow the export. + when: _free | int < _required | int + +- name: "โฌ‡๏ธ Fetch the models into the shared store" + get_url_retry: + url: "{{ model.url }}" + dest: "{{ LMSTUDIO_SHARED_MODELS_PATH }}/{{ model.repo }}/{{ model.file }}" + tmp_dest: "{{ LMSTUDIO_SHARED_STAGING_PATH }}" + checksum: "sha256:{{ model.sha256 }}" + mode: "0644" + loop: "{{ LMSTUDIO_PRELOAD_MODELS }}" + loop_control: + loop_var: model + label: "{{ model.file }}" + register: lmstudio_fetch + changed_when: false + failed_when: false + +- name: "๐Ÿชž Fetch from a mirror when the source did not deliver" + get_url_retry: + url: "{{ item.1 }}" + dest: "{{ LMSTUDIO_SHARED_MODELS_PATH }}/{{ item.0.repo }}/{{ item.0.file }}" + tmp_dest: "{{ LMSTUDIO_SHARED_STAGING_PATH }}" + checksum: "sha256:{{ item.0.sha256 }}" + mode: "0644" + loop: "{{ LMSTUDIO_PRELOAD_MODELS | subelements('mirrors', skip_missing=True) }}" + loop_control: + label: "{{ item.0.file }} from {{ item.1 }}" + register: lmstudio_fetch_mirror + changed_when: false + failed_when: false + +- name: "๐Ÿ” Read back what the shared model store now holds" + ansible.builtin.stat: + path: "{{ LMSTUDIO_SHARED_MODELS_PATH }}/{{ model.repo }}/{{ model.file }}" + checksum_algorithm: sha256 + register: lmstudio_seeded + changed_when: false + loop: "{{ LMSTUDIO_PRELOAD_MODELS }}" + loop_control: + loop_var: model + label: "{{ model.file }}" + +- name: "๐Ÿ›‘ Fail when no source delivered a declared model" + vars: + _missing: >- + {{ lmstudio_seeded.results + | rejectattr('stat.exists') + | map(attribute='model.file') | list }} + _said: >- + {{ (lmstudio_fetch.results | map(attribute='msg') | select | list) + + (lmstudio_fetch_mirror.results | default([]) | map(attribute='msg') | select | list) }} + ansible.builtin.fail: + msg: >- + The shared model store on {{ LMSTUDIO_NFS_SERVER }} is missing + {{ _missing | join(', ') }}. What the sources answered: + {{ _said | join(' | ') }} + when: _missing | length > 0 + +- name: "๐Ÿ›‘ Fail when a seeded model does not match its checksum" + ansible.builtin.fail: + msg: >- + {{ item.model.file }} in the shared model store on {{ LMSTUDIO_NFS_SERVER }} + hashes to {{ item.stat.checksum }}, but AI_LOCAL_MODELS declares + {{ item.model.sha256 }}. + loop: "{{ lmstudio_seeded.results | selectattr('stat.exists') | list }}" + loop_control: + label: "{{ item.model.file }}" + when: item.stat.checksum != item.model.sha256 diff --git a/roles/svc-ai-lmstudio/templates/compose.yml.j2 b/roles/svc-ai-lmstudio/templates/compose.yml.j2 new file mode 100644 index 0000000000..3e05c26133 --- /dev/null +++ b/roles/svc-ai-lmstudio/templates/compose.yml.j2 @@ -0,0 +1,15 @@ +{% include 'roles/sys-svc-compose/templates/base.yml.j2' %} + + {% set service_name = 'lmstudio' %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, 'lmstudio') }} + {{ lookup('compose_only', 'container_name', LMSTUDIO_CONTAINER) }} + expose: + - "{{ LMSTUDIO_PORT }}" + {{ lookup('container_volumes', service_name) | indent(4) }} + {{ lookup('container_networks') | indent(4) }} + +{{ lookup('compose_networks') }} + +{{ lookup('compose_volumes') }} diff --git a/roles/svc-ai-lmstudio/templates/test.env.j2 b/roles/svc-ai-lmstudio/templates/test.env.j2 new file mode 100644 index 0000000000..019aeb6e20 --- /dev/null +++ b/roles/svc-ai-lmstudio/templates/test.env.j2 @@ -0,0 +1,6 @@ +LMSTUDIO_CONTAINER={{ CLI_LOCAL_CID }} +LMSTUDIO_EXPECTED_BLOBS='{{ LMSTUDIO_PRELOAD_MODELS | map(attribute='repo') | zip(LMSTUDIO_PRELOAD_MODELS | map(attribute='file')) | map('join', '/') | list | to_json }}' +LMSTUDIO_EXPECTED_DIGESTS='{{ LMSTUDIO_PRELOAD_MODELS | map(attribute='sha256') | list | to_json }}' +LMSTUDIO_EXPECTED_MODELS='{{ LMSTUDIO_PRELOAD_MODELS | map(attribute='name') | list | to_json }}' +LMSTUDIO_MODELS_DIR={{ LMSTUDIO_MODELS_TARGET }} +LMSTUDIO_PORT={{ LMSTUDIO_PORT }} diff --git a/roles/svc-ai-lmstudio/vars/main.yml b/roles/svc-ai-lmstudio/vars/main.yml new file mode 100644 index 0000000000..8314305c99 --- /dev/null +++ b/roles/svc-ai-lmstudio/vars/main.yml @@ -0,0 +1,22 @@ +--- +application_id: "svc-ai-lmstudio" +entity_name: "{{ application_id | get_entity_name }}" + +LMSTUDIO_CONTAINER: "{{ lookup('config', application_id, 'services.lmstudio.name') }}" +LMSTUDIO_PORT: "{{ lookup('config', application_id, 'services.lmstudio.ports.internal.http') }}" +LMSTUDIO_PRELOAD_MODELS: "{{ lookup('config', application_id, 'services.lmstudio.preload_models') }}" +LMSTUDIO_PRELOAD_ASYNC_TIME: "{{ lookup('config', application_id, 'services.lmstudio.preload_async_time') }}" +LMSTUDIO_PRELOAD_FLOOR_SECONDS: "{{ lookup('config', application_id, 'services.lmstudio.preload_floor_seconds') }}" +LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND: "{{ lookup('config', application_id, 'services.lmstudio.preload_min_bytes_per_second') }}" +LMSTUDIO_PRELOAD_LARGEST_BYTES: >- + {{ LMSTUDIO_PRELOAD_MODELS | map(attribute='bytes') | map('int') | max }} +LMSTUDIO_MODELS_TARGET: "{{ lookup('volume', application_id, 'lmstudio_models').target }}" +LMSTUDIO_NFS_SERVER: "{{ (groups['svc-storage-nfs-server'] | default([]))[0] | default(inventory_hostname) }}" +LMSTUDIO_SHARED_MODELS_PATH: "{{ [ STORAGE_NFS_STATE_PATH, lookup('volume', application_id, 'lmstudio_models').name ] | path_join }}" +LMSTUDIO_SHARED_STAGING_PATH: "{{ [ STORAGE_NFS_STATE_PATH, '.lmstudio-staging' ] | path_join }}" +LMSTUDIO_PRESEED_ENABLED: >- + {{ (DEPLOYMENT_MODE == 'swarm') + and (storage.backend == 'nfs') + and ((groups['svc-storage-nfs-server'] | default([])) | length > 0) + and (lookup('volume', application_id, 'lmstudio_models').nfs is not false) + and (application_id not in lookup('roles_with_placement', 'manager')) }} diff --git a/roles/svc-ai-mcp-adapter/README.md b/roles/svc-ai-mcp-adapter/README.md new file mode 100644 index 0000000000..cfd9b2bf62 --- /dev/null +++ b/roles/svc-ai-mcp-adapter/README.md @@ -0,0 +1,137 @@ +# MCP Adapter + +## Description + +A reusable [Model Context Protocol](https://modelcontextprotocol.io/) adapter, instantiated once per provider application. Each instance fronts exactly one upstream, holds only that upstream's least-privileged credential, and exposes only the operations its checked-in contract names. + +## Overview + +Several applications have a useful read API but no MCP server, and several projects ship an MCP server that authenticates *to* the application without authenticating the client calling it. Putting either behind this adapter gives the surface a bearer of its own, an exact tool allowlist, and enforced ceilings. The deployment renders one contract per instance, so the same image serves every provider without any of them sharing a credential or a trust boundary. + +## Cosmos + +The diagram places MCP Adapter in the Infinito.Nexus cosmos: the components it deploys (capabilities), the central services it consumes (dependencies), and its outward reach (federation and bridged external networks). + +```mermaid +flowchart LR + subgraph role [svc-ai-mcp-adapter] + svc_mcp_adapter["mcp-adapter"] + end +``` + +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (๐Ÿ’ป host, ๐Ÿณ compose, ๐Ÿ swarm); โŒ marks a service that is explicitly turned off, and โš™๏ธ an Ansible role dependency declared in `meta/main.yml`. + +## Features + +- **Client-facing authentication:** The adapter issues its own bearer. The upstream credential authenticates the adapter to the provider and says nothing about who called the adapter, which is the gap the project-owned MCP sidecars leave open. +- **Allowlist on `tools/call`:** Filtering only `tools/list` would leave every unlisted operation callable by name. +- **Read-only by default:** A non-`GET`/`HEAD` operation is refused unless `mutating_tools_enabled` is explicitly true. +- **Enforced ceilings:** Request size, response size, timeout, concurrency, page size and result count come from the contract and are applied, not merely declared. +- **Bounded ranges:** A tool whose schema declares `start`, `end` and `step` has its point count checked against `result_items` and is refused with the smallest step that fits, so the upstream never scans a range whose result the adapter would discard. +- **Fail-closed on drift:** A tool contract whose hash no longer matches its pinned `schema_sha256` refuses to start. +- **Redacted audit trail:** Every call emits provider, consumer, tool, credential subject, status, duration and correlation id, and never the arguments, the response body or the credential. + +## Contract + +The deployment renders one `ADAPTER_CONTRACT` JSON document per instance: + +```json +{ + "provider": "web-app-checkmk", + "upstream_url": "http://checkmk:5000", + "auth_subject": "service_account", + "mutating_tools_enabled": false, + "tools": { + "checkmk_list_hosts": {"method": "GET", "path": "/domain-types/host_config/collections/all"} + }, + "limits": { + "request_bytes": 65536, + "response_bytes": 1048576, + "timeout_seconds": 15, + "concurrent_requests": 4, + "page_size": 100, + "result_items": 500, + "stream_seconds": 300 + }, + "schema_sha256": "sha256:โ€ฆ" +} +``` + +`files/python/policy.py` validates it at startup. A contract missing a limit, carrying an empty allowlist, naming a wildcard path or lacking a pinned schema hash is refused before the process serves anything. + +## Endpoints + +| Path | Method | Purpose | +|---|---|---| +| `/mcp` | POST | JSON-RPC: `initialize`, `tools/list`, `tools/call` | +| `/health` | GET | liveness, names the provider it fronts | + +A tools-only server never has to stream, so every response is a plain JSON body and no SSE session state exists to get wrong. + +## Upstream authentication + +The adapter presents `ADAPTER_UPSTREAM_KEY` to the provider in the header named by `ADAPTER_UPSTREAM_AUTH_HEADER` (default `Authorization`), formatted by `ADAPTER_UPSTREAM_AUTH_FORMAT` (default `Bearer {key}`, where `{key}` is the credential). + +| Provider style | Header | Format | +|---|---|---| +| RFC 6750 bearer | `Authorization` | `Bearer {key}` | +| Pretix | `Authorization` | `Token {key}` | +| Zammad | `Authorization` | `Token token={key}` | +| Jellyfin | `X-Emby-Token` | `{key}` | + +An empty `ADAPTER_UPSTREAM_KEY` sends no header at all. + +## Image + +Self-built and stdlib-only: the served surface is three JSON-RPC methods, and a dependency-free image has no transitive supply chain to audit per release. The container runs as a non-root user with a read-only root filesystem and all Linux capabilities dropped. + +## Quick Setup + +### Development + +Clone, set up the workstation, and deploy MCP Adapter onto the local stack: + +```bash +git clone https://github.com/infinito-nexus/core.git +cd core +make onboard +make compose-deploy mode=reinstall apps=svc-ai-mcp-adapter full_cycle=false +``` + +### Production + +Run the published image to provision the inventory and deploy MCP Adapter to a managed server (the mounted volume persists the inventory): + +```bash +APP=svc-ai-mcp-adapter +HOST= +DOMAIN= +TLS_MODE=self_signed +SSH_PUBLIC_KEY="" + +docker run --rm -it \ + -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + ghcr.io/infinito-nexus/core/debian bash -c ' + INVENTORY=/etc/infinito.nexus/inventories/production + infinito administration inventory provision "$INVENTORY" \ + --inventory-file "$INVENTORY/devices.yml" \ + --host "$HOST" \ + --include "$APP" \ + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + infinito administration deploy dedicated "$INVENTORY/devices.yml" \ + --password-file "$INVENTORY/.password" \ + --diff -vv' +``` + +## Further resources + +- [Model Context Protocol](https://modelcontextprotocol.io/) +- [MCP service block](../../docs/contributing/design/role/services/mcp.md) +- [MCP user delegation audit](../../docs/contributing/design/role/services/mcp/delegation.md) + +## Credits + +Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. +Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). +Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/svc-ai-mcp-adapter/files/Dockerfile b/roles/svc-ai-mcp-adapter/files/Dockerfile new file mode 100644 index 0000000000..1c3e4bbad0 --- /dev/null +++ b/roles/svc-ai-mcp-adapter/files/Dockerfile @@ -0,0 +1,15 @@ +# Self-built MCP adapter image. +# +# Deliberately stdlib-only: the served surface is three JSON-RPC methods, and +# a dependency-free image has no transitive supply chain to audit per release. +ARG MCP_ADAPTER_BASE_IMAGE +ARG MCP_ADAPTER_BASE_VERSION +FROM ${MCP_ADAPTER_BASE_IMAGE}:${MCP_ADAPTER_BASE_VERSION} + +WORKDIR /opt/adapter +COPY policy.py passthrough.py server.py sse.py /opt/adapter/ + +RUN adduser --system --no-create-home --disabled-login adapter +USER adapter + +ENTRYPOINT ["python3", "/opt/adapter/server.py"] diff --git a/roles/svc-ai-mcp-adapter/files/python/passthrough.py b/roles/svc-ai-mcp-adapter/files/python/passthrough.py new file mode 100644 index 0000000000..10230ec4bd --- /dev/null +++ b/roles/svc-ai-mcp-adapter/files/python/passthrough.py @@ -0,0 +1,224 @@ +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any + +import policy + +if TYPE_CHECKING: + from collections.abc import Mapping + +KIND_MCP = "mcp" +KIND_REST = "rest" +KINDS = frozenset({KIND_MCP, KIND_REST}) + +TRANSPORT_STREAMABLE = "streamable_http" +TRANSPORT_SSE = "sse" +TRANSPORTS = frozenset({TRANSPORT_STREAMABLE, TRANSPORT_SSE}) + + +def contract_kind(contract: Mapping[str, Any]) -> str: + """Return the upstream kind a contract declares. + + Args: + contract: the loaded contract. + """ + kind = str(contract.get("upstream_kind") or "").strip() + if kind not in KINDS: + raise policy.ContractError( + f"contract must declare upstream_kind as one of {sorted(KINDS)}; " + f"got {kind!r}" + ) + return kind + + +def declares_mcp_upstream(raw: str) -> bool: + """Whether a rendered contract asks for the MCP passthrough. + + Args: + raw: the ``ADAPTER_CONTRACT`` JSON document. + """ + try: + contract = json.loads(raw or "{}") + except json.JSONDecodeError: + return False + return ( + isinstance(contract, dict) + and str(contract.get("upstream_kind") or "").strip() == KIND_MCP + ) + + +def decode_jsonrpc(body: bytes, content_type: str) -> Any: + """Return the JSON-RPC object carried by an upstream response. + + Args: + body: the raw response bytes. + content_type: the response's ``Content-Type`` header. + + A streamable-http server may answer a single call as one SSE frame instead + of a plain body, so the first data frame is unwrapped rather than parsed as + JSON, which would fail on the ``data:`` prefix. + """ + if "text/event-stream" in (content_type or ""): + for line in body.decode(errors="replace").splitlines(): + if line.startswith("data:"): + frame = line[len("data:") :].strip() + if frame: + return json.loads(frame) + raise ValueError("upstream_error: event stream carried no data frame") + return json.loads(body or b"null") + + +def upstream_transport(contract: Mapping[str, Any]) -> str: + """Return the transport the MCP upstream speaks. + + Args: + contract: the loaded contract. + + Streamable HTTP is the default because it is what most servers ship. A + provider on the classic HTTP+SSE transport says so, since the two cannot be + told apart by probing without first speaking one of them wrongly. + """ + declared = str(contract.get("upstream_transport") or TRANSPORT_STREAMABLE).strip() + if declared not in TRANSPORTS: + raise policy.ContractError( + f"contract declares upstream_transport {declared!r}; " + f"expected one of {sorted(TRANSPORTS)}" + ) + return declared + + +def load_mcp_contract(raw: str) -> dict[str, Any]: + """Return the validated contract for an MCP-speaking upstream. + + Args: + raw: the ``ADAPTER_CONTRACT`` JSON document. + """ + try: + contract = json.loads(raw or "{}") + except json.JSONDecodeError as error: + raise policy.ContractError(f"contract is not JSON: {error}") from error + if not isinstance(contract, dict): + raise policy.ContractError("contract must be a JSON object") + + if contract_kind(contract) != KIND_MCP: + raise policy.ContractError( + "load_mcp_contract requires upstream_kind 'mcp'; use policy.load_contract" + ) + + for key in ("provider", "upstream_url", "tools", "limits"): + if not contract.get(key): + raise policy.ContractError(f"contract is missing {key!r}") + + limits = contract["limits"] + missing = [key for key in policy.REQUIRED_LIMITS if key not in limits] + if missing: + raise policy.ContractError(f"contract limits are missing {sorted(missing)}") + for key in policy.REQUIRED_LIMITS: + value = limits[key] + if not isinstance(value, int) or isinstance(value, bool) or value <= 0: + raise policy.ContractError(f"limit {key!r} must be a positive integer") + + tools = contract["tools"] + if not isinstance(tools, dict) or not tools: + raise policy.ContractError("contract tools must be a non-empty mapping") + + mutating_enabled = bool(contract.get("mutating_tools_enabled")) + for name, spec in tools.items(): + if not isinstance(spec, dict): + raise policy.ContractError(f"tool {name!r} must be a mapping") + if not isinstance(spec.get("mutating"), bool): + raise policy.ContractError( + f"tool {name!r} must declare a boolean 'mutating': an MCP upstream " + f"exposes no method to infer it from" + ) + if spec["mutating"] and not mutating_enabled: + raise policy.ContractError( + f"tool {name!r} is declared mutating while mutations are off, so it " + f"could only ever be refused at call time. Advertising a tool that " + f"cannot run is worse than not having it: a green deploy would hide " + f"the dead surface." + ) + + if not str(contract.get("schema_sha256") or "").startswith(policy.SHA256_PREFIX): + raise policy.ContractError("contract must pin tools.schema_sha256") + + upstream_transport(contract) + + return contract + + +def authorize_mcp_call( + contract: Mapping[str, Any], name: str, arguments: Mapping[str, Any] | None +) -> str: + """Return the upstream tool name for one call, or refuse it. + + Args: + contract: the loaded contract. + name: the tool the client asked for. + arguments: the client-supplied arguments. + """ + spec = contract["tools"].get(name) + if spec is None: + raise PermissionError(f"{policy.DENY_UNKNOWN_TOOL}: {name!r}") + + if spec.get("mutating") and not contract.get("mutating_tools_enabled"): + raise PermissionError(f"{policy.DENY_MUTATION}: {name!r} mutates") + + encoded = json.dumps(arguments or {}, separators=(",", ":")) + if len(encoded.encode()) > contract["limits"]["request_bytes"]: + raise PermissionError( + f"{policy.DENY_REQUEST_TOO_LARGE}: {len(encoded)} bytes exceeds " + f"{contract['limits']['request_bytes']}" + ) + + policy.assert_arguments(spec, name, arguments) + + return name + + +def filter_upstream_tools( + contract: Mapping[str, Any], upstream_tools: list[dict[str, Any]] +) -> list[dict[str, Any]]: + """Return only those upstream descriptors the contract allows. + + Args: + contract: the loaded contract. + upstream_tools: the ``tools`` array of an upstream ``tools/list`` result. + """ + allowed = set(contract["tools"]) + return [ + tool + for tool in upstream_tools + if isinstance(tool, dict) and tool.get("name") in allowed + ] + + +def undeclared_upstream_tools( + contract: Mapping[str, Any], upstream_tools: list[dict[str, Any]] +) -> list[str]: + """Return the names the upstream serves that the contract does not declare. + + Args: + contract: the loaded contract. + upstream_tools: the ``tools`` array of an upstream ``tools/list`` result. + """ + allowed = set(contract["tools"]) + return sorted( + str(tool.get("name")) + for tool in upstream_tools + if isinstance(tool, dict) and tool.get("name") not in allowed + ) + + +def missing_upstream_tools( + contract: Mapping[str, Any], upstream_tools: list[dict[str, Any]] +) -> list[str]: + """Return contract tools the upstream no longer serves. + + Args: + contract: the loaded contract. + upstream_tools: the ``tools`` array of an upstream ``tools/list`` result. + """ + served = {tool.get("name") for tool in upstream_tools if isinstance(tool, dict)} + return sorted(name for name in contract["tools"] if name not in served) diff --git a/roles/svc-ai-mcp-adapter/files/python/policy.py b/roles/svc-ai-mcp-adapter/files/python/policy.py new file mode 100644 index 0000000000..fc4ed18be2 --- /dev/null +++ b/roles/svc-ai-mcp-adapter/files/python/policy.py @@ -0,0 +1,404 @@ +"""Policy layer of the reusable MCP adapter. + +One adapter process fronts exactly one provider application. It never mirrors +that provider's API: it exposes the operations named in a checked-in allowlist +and nothing else, and it enforces that allowlist on ``tools/call`` as well as +on ``tools/list``. Filtering only the listing would leave every unlisted +operation callable by name. + +The contract arrives as one JSON document (``ADAPTER_CONTRACT``) so the same +image serves every provider; the deployment renders a different contract per +instance. + +This module is pure: it decides, it does not perform I/O. That keeps the rules +testable without a live upstream. +""" + +from __future__ import annotations + +import hashlib +import json +import re +from datetime import datetime +from typing import TYPE_CHECKING, Any +from urllib.parse import quote + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + +REQUIRED_LIMITS = ( + "request_bytes", + "response_bytes", + "timeout_seconds", + "concurrent_requests", + "page_size", + "result_items", + "stream_seconds", +) + +SHA256_PREFIX = "sha256:" + +DENY_UNKNOWN_TOOL = "unknown_tool" +DENY_MUTATION = "mutation_not_enabled" +DENY_REQUEST_TOO_LARGE = "request_too_large" +DENY_SCHEMA_DRIFT = "schema_drift" +DENY_UNAUTHENTICATED = "unauthenticated" +DENY_TOO_MANY_REQUESTS = "too_many_concurrent_requests" +DENY_UNKNOWN_ARGUMENT = "undeclared_argument" +DENY_MISSING_ARGUMENT = "missing_required_argument" +DENY_RANGE_TOO_WIDE = "range_too_wide" + +RANGE_ARGUMENTS = ("start", "end", "step") + +DURATION_UNITS = { + "ms": 0.001, + "s": 1, + "m": 60, + "h": 3600, + "d": 86400, + "w": 604800, + "y": 31536000, +} + +READ_METHODS = frozenset({"GET", "HEAD"}) + + +class ContractError(ValueError): + """The rendered contract is not one this adapter may serve.""" + + +def upstream_url(base: str, path_key: str = "", path_suffix: str = "") -> str: + """Return the upstream URL with an optional secret path segment spliced in. + + Not every provider authenticates through a header. Baserow keys its MCP + endpoint by a URL segment, so the secret cannot travel in the auth header + the adapter otherwise uses. Splicing it here keeps it out of the contract + the sidecar advertises, and the segment is percent-encoded so a key + carrying a separator cannot open a path of its own. + + Args: + base: ``upstream_url`` as the contract declares it. + path_key: secret segment to append, or "" when the provider needs none. + path_suffix: trailing segment after the key, e.g. ``sse``. + """ + if not path_key and not path_suffix: + return base + parts = [base.rstrip("/")] + if path_key: + parts.append(quote(path_key, safe="")) + if path_suffix: + parts.append(path_suffix.strip("/")) + return "/".join(parts) + + +def load_contract(raw: str) -> dict[str, Any]: + """Return the validated adapter contract. + + Args: + raw: the ``ADAPTER_CONTRACT`` JSON document. + + A contract missing a limit, an allowlist or a schema hash is rejected at + startup rather than at the first call, so a misconfigured instance never + reaches a client. + """ + try: + contract = json.loads(raw or "{}") + except json.JSONDecodeError as error: + raise ContractError(f"contract is not JSON: {error}") from error + if not isinstance(contract, dict): + raise ContractError("contract must be a JSON object") + + for key in ("provider", "upstream_url", "tools", "limits"): + if not contract.get(key): + raise ContractError(f"contract is missing {key!r}") + + limits = contract["limits"] + missing = [key for key in REQUIRED_LIMITS if key not in limits] + if missing: + raise ContractError(f"contract limits are missing {sorted(missing)}") + for key in REQUIRED_LIMITS: + value = limits[key] + if not isinstance(value, int) or isinstance(value, bool) or value <= 0: + raise ContractError(f"limit {key!r} must be a positive integer") + + tools = contract["tools"] + if not isinstance(tools, dict) or not tools: + raise ContractError("contract tools must be a non-empty mapping") + for name, spec in tools.items(): + if not isinstance(spec, dict): + raise ContractError(f"tool {name!r} must be a mapping") + for key in ("method", "path"): + if not spec.get(key): + raise ContractError(f"tool {name!r} is missing {key!r}") + if "*" in str(spec["path"]): + raise ContractError(f"tool {name!r} declares a wildcard path") + if str(spec["method"]).upper() not in READ_METHODS and not contract.get( + "mutating_tools_enabled" + ): + raise ContractError( + f"tool {name!r} declares {spec['method']!r} while mutations are " + f"off, so it could only ever be refused at call time. Advertising " + f"a tool that cannot run is worse than not having it: a green " + f"deploy would hide the dead surface." + ) + + if not str(contract.get("schema_sha256") or "").startswith(SHA256_PREFIX): + raise ContractError("contract must pin tools.schema_sha256") + + return contract + + +def schema_digest(tools: Mapping[str, Any]) -> str: + """Return the canonical hash of a tool contract. + + Args: + tools: the tool mapping to digest. + """ + canonical = json.dumps(tools, sort_keys=True, separators=(",", ":")) + return SHA256_PREFIX + hashlib.sha256(canonical.encode()).hexdigest() + + +def assert_arguments( + spec: Mapping[str, Any], name: str, arguments: Mapping[str, Any] | None +) -> None: + """Refuse arguments the tool's own declared schema does not describe. + + Args: + spec: the tool's contract entry. + name: the tool name, for the refusal message. + arguments: the client-supplied arguments. + + The schema was published to clients and never checked, which made it a + suggestion. On the openapi path that is not cosmetic: an argument the + contract does not name is appended to the upstream request as a query + parameter, so a client could add parameters the reviewed operation never + granted. A tool that declares no schema declares no inputs. + """ + schema = spec.get("input_schema") or {} + declared = set((schema.get("properties") or {}).keys()) + supplied = set(arguments or {}) + + undeclared = sorted(supplied - declared) + if undeclared: + raise PermissionError( + f"{DENY_UNKNOWN_ARGUMENT}: {name!r} does not take {undeclared}" + ) + + missing = sorted(set(schema.get("required") or []) - supplied) + if missing: + raise PermissionError(f"{DENY_MISSING_ARGUMENT}: {name!r} requires {missing}") + + +def parse_instant(value: Any) -> float: + """Return a range boundary in unix seconds. + + Args: + value: a unix timestamp or an RFC 3339 instant, as the upstream takes. + + Raises ``ValueError`` for anything else, so an unparseable boundary is + refused rather than waved through unbounded. + """ + text = str(value).strip() + try: + return float(text) + except ValueError: + pass + return datetime.fromisoformat(text).timestamp() + + +def parse_duration(value: Any) -> float: + """Return a step in seconds. + + Args: + value: seconds as a number, or a duration such as ``30s`` or ``1h30m``. + """ + text = str(value).strip() + try: + return float(text) + except ValueError: + pass + parts = re.findall(r"(\d+)(ms|[smhdwy])", text) + if not parts or "".join(n + u for n, u in parts) != text: + raise ValueError(f"not a duration: {text!r}") + return sum(int(n) * DURATION_UNITS[u] for n, u in parts) + + +def assert_range( + spec: Mapping[str, Any], + name: str, + arguments: Mapping[str, Any] | None, + ceiling: int, +) -> None: + """Refuse a range query asking for more points than the contract returns. + + Args: + spec: the tool's contract entry. + name: the tool name, for the refusal message. + arguments: the client-supplied arguments. + ceiling: ``limits.result_items``. + + A client chooses ``start``, ``end`` and ``step`` freely, so nothing stopped + it asking for years at one-second resolution. The timeout bounds how long + the upstream burns on that, not how much it scans, and the adapter would + discard all but ``result_items`` rows anyway. Bounding the point count + against that same ceiling makes the two agree instead of letting the + upstream do work whose result is thrown away. + """ + schema = spec.get("input_schema") or {} + declared = (schema.get("properties") or {}).keys() + if not all(key in declared for key in RANGE_ARGUMENTS): + return + + supplied = arguments or {} + if not all(key in supplied for key in RANGE_ARGUMENTS): + return + + try: + span = parse_instant(supplied["end"]) - parse_instant(supplied["start"]) + step = parse_duration(supplied["step"]) + except ValueError as error: + raise PermissionError(f"{DENY_RANGE_TOO_WIDE}: {name!r} {error}") from error + + if step <= 0: + raise PermissionError(f"{DENY_RANGE_TOO_WIDE}: {name!r} step must be positive") + + points = span / step + 1 + if points > ceiling: + raise PermissionError( + f"{DENY_RANGE_TOO_WIDE}: {name!r} asks for {int(points)} points, " + f"above the {ceiling} this contract returns; a step of at least " + f"{span / (ceiling - 1):.0f}s fits" + ) + + +def assert_no_drift(contract: Mapping[str, Any]) -> None: + """Fail closed when the tool contract no longer matches its pinned hash. + + Args: + contract: the loaded contract. + """ + found = schema_digest(contract["tools"]) + if found != contract["schema_sha256"]: + raise ContractError( + f"{DENY_SCHEMA_DRIFT}: tools hash {found} does not match the " + f"pinned {contract['schema_sha256']}" + ) + + +def listed_tools(contract: Mapping[str, Any]) -> list[str]: + """Return the tool names this adapter advertises, in a stable order. + + Args: + contract: the loaded contract. + """ + return sorted(contract["tools"]) + + +def authorize_client(expected: str, presented: str) -> None: + """Refuse a caller that did not present the adapter's own bearer. + + Args: + expected: the bearer this instance was issued. + presented: the ``Authorization`` header value the caller sent. + + The upstream credential authenticates the adapter *to* the provider. It + says nothing about who called the adapter, which is exactly the gap the + project-owned MCP sidecars leave open. + """ + prefix = "Bearer " + token = presented[len(prefix) :] if presented.startswith(prefix) else "" + if not expected or not token or token != expected: + raise PermissionError(DENY_UNAUTHENTICATED) + + +def authorize_call( + contract: Mapping[str, Any], name: str, arguments: Mapping[str, Any] | None +) -> tuple[str, str]: + """Return the upstream ``(method, path)`` for one tool call, or refuse it. + + Args: + contract: the loaded contract. + name: the tool the client asked for. + arguments: the client-supplied arguments. + + Raises ``PermissionError`` with a stable reason for anything the contract + does not name. The same check runs here and on listing, so a client cannot + reach an operation by guessing its name. + """ + spec = contract["tools"].get(name) + if spec is None: + raise PermissionError(f"{DENY_UNKNOWN_TOOL}: {name!r}") + + method = str(spec["method"]).upper() + if method not in READ_METHODS and not contract.get("mutating_tools_enabled"): + raise PermissionError(f"{DENY_MUTATION}: {name!r} is {method}") + + encoded = json.dumps(arguments or {}, separators=(",", ":")) + if len(encoded.encode()) > contract["limits"]["request_bytes"]: + raise PermissionError( + f"{DENY_REQUEST_TOO_LARGE}: {len(encoded)} bytes exceeds " + f"{contract['limits']['request_bytes']}" + ) + + assert_arguments(spec, name, arguments) + assert_range(spec, name, arguments, contract["limits"]["result_items"]) + + return method, str(spec["path"]) + + +def clamp_page(contract: Mapping[str, Any], requested: Any) -> int: + """Return a page size no larger than the contract allows. + + Args: + contract: the loaded contract. + requested: whatever the client asked for. + """ + ceiling = contract["limits"]["page_size"] + try: + wanted = int(requested) + except (TypeError, ValueError): + return ceiling + return max(1, min(wanted, ceiling)) + + +def truncate_results(contract: Mapping[str, Any], items: Sequence[Any]) -> list[Any]: + """Return at most the contract's result ceiling. + + Args: + contract: the loaded contract. + items: the upstream result rows. + """ + return list(items[: contract["limits"]["result_items"]]) + + +def audit_event( + contract: Mapping[str, Any], + consumer: str, + tool: str, + status: str, + duration_ms: int, + correlation_id: str, +) -> dict[str, Any]: + """Return one audit record for a call. + + Args: + contract: the loaded contract. + consumer: the calling client's application id. + tool: the tool name. + status: ``ok`` or a deny reason. + duration_ms: wall time of the upstream call. + correlation_id: identifier tying the record to the client request. + + Carries who, what and how it ended. Never the arguments, never the + response body and never the credential: an audit log that leaks the + payload is a second copy of the data it is meant to guard. + """ + return { + "provider": contract["provider"], + "consumer": consumer, + "tool": tool, + "subject": contract.get("auth_subject"), + "status": status, + "duration_ms": duration_ms, + "correlation_id": correlation_id, + } diff --git a/roles/svc-ai-mcp-adapter/files/python/server.py b/roles/svc-ai-mcp-adapter/files/python/server.py new file mode 100644 index 0000000000..ee5f3c20f0 --- /dev/null +++ b/roles/svc-ai-mcp-adapter/files/python/server.py @@ -0,0 +1,481 @@ +"""Streamable-HTTP MCP server fronting one provider application. + +Implements the three methods a tools-only server needs โ€” ``initialize``, +``tools/list`` and ``tools/call`` โ€” over JSON-RPC on a single endpoint. A +tools-only server never has to stream, so every response is a plain JSON body +and no SSE session state exists to get wrong. + +Every decision lives in :mod:`policy`; this module only moves bytes. + +Environment: + ADAPTER_CONTRACT: the rendered contract JSON. + ADAPTER_BEARER: bearer a client MUST present to this adapter. + ADAPTER_UPSTREAM_KEY: credential this adapter presents to the provider. + ADAPTER_UPSTREAM_AUTH_HEADER: header carrying it, default ``Authorization``. + ADAPTER_UPSTREAM_AUTH_FORMAT: template for its value, default ``Bearer {key}``. + ADAPTER_UPSTREAM_PATH_KEY: secret URL segment for a provider that keys its + endpoint by path instead of by header. + ADAPTER_UPSTREAM_PATH_SUFFIX: segment trailing that key, e.g. ``sse``. + ADAPTER_PORT: port to listen on. +""" + +from __future__ import annotations + +import json +import os +import sys +import threading +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import passthrough +import policy +import sse + +PROTOCOL_VERSION = "2025-06-18" +ENDPOINT = "/mcp" +HEALTH = "/health" + +RAW_CONTRACT = os.environ.get("ADAPTER_CONTRACT", "") +UPSTREAM_IS_MCP = passthrough.declares_mcp_upstream(RAW_CONTRACT) +CONTRACT = ( + passthrough.load_mcp_contract(RAW_CONTRACT) + if UPSTREAM_IS_MCP + else policy.load_contract(RAW_CONTRACT) +) +UPSTREAM_TRANSPORT = ( + passthrough.upstream_transport(CONTRACT) + if UPSTREAM_IS_MCP + else passthrough.TRANSPORT_STREAMABLE +) +BEARER = os.environ.get("ADAPTER_BEARER", "") +UPSTREAM_KEY = os.environ.get("ADAPTER_UPSTREAM_KEY", "") +UPSTREAM_AUTH_HEADER = os.environ.get("ADAPTER_UPSTREAM_AUTH_HEADER") or "Authorization" +UPSTREAM_AUTH_FORMAT = os.environ.get("ADAPTER_UPSTREAM_AUTH_FORMAT") or "Bearer {key}" +UPSTREAM_URL = policy.upstream_url( + CONTRACT["upstream_url"], + os.environ.get("ADAPTER_UPSTREAM_PATH_KEY", ""), + os.environ.get("ADAPTER_UPSTREAM_PATH_SUFFIX", ""), +) +PORT = int(os.environ.get("ADAPTER_PORT", "8080")) + +policy.assert_no_drift(CONTRACT) + +IN_FLIGHT = threading.BoundedSemaphore(CONTRACT["limits"]["concurrent_requests"]) + + +NoRedirect = sse.NoRedirect +OPENER = urllib.request.build_opener(NoRedirect) + + +def log(event): + """Emit one audit record as a single JSON line. + + Args: + event: the record from ``policy.audit_event``. + """ + sys.stdout.write(json.dumps(event, separators=(",", ":")) + "\n") + sys.stdout.flush() + + +def call_upstream(method, path, arguments): + """Return the upstream response body for one authorised tool call. + + Args: + method: HTTP method from the contract. + path: upstream path from the contract. + arguments: client arguments, substituted into ``{placeholders}``. + """ + resolved = path + query = {} + for key, value in (arguments or {}).items(): + placeholder = "{" + key + "}" + if placeholder in resolved: + resolved = resolved.replace( + placeholder, urllib.parse.quote(str(value), safe="") + ) + else: + query[key] = value + if query: + resolved = f"{resolved}?{urllib.parse.urlencode(query)}" + + request = urllib.request.Request( # noqa: S310 - fixed http:// base from the contract, no user-supplied scheme + f"{UPSTREAM_URL}{resolved}", method=method + ) + request.add_header("Accept", "application/json") + if UPSTREAM_KEY: + request.add_header( + UPSTREAM_AUTH_HEADER, UPSTREAM_AUTH_FORMAT.format(key=UPSTREAM_KEY) + ) + + with OPENER.open( + request, timeout=CONTRACT["limits"]["timeout_seconds"] + ) as response: + body = response.read(CONTRACT["limits"]["response_bytes"] + 1) + + if len(body) > CONTRACT["limits"]["response_bytes"]: + raise ValueError("response_too_large") + + parsed = json.loads(body or b"null") + if isinstance(parsed, list): + return policy.truncate_results(CONTRACT, parsed) + return parsed + + +UPSTREAM_SESSION = {"id": "", "ready": False} +SSE = {"session": None} +SESSION_HEADER = "Mcp-Session-Id" + + +def post_upstream(envelope): + """Return ``(parsed, status)`` of one JSON-RPC POST to the upstream. + + Args: + envelope: the JSON-RPC request object to send. + """ + request = urllib.request.Request( # noqa: S310 - fixed http:// base from the contract, no user-supplied scheme + UPSTREAM_URL, + data=json.dumps(envelope).encode(), + method="POST", + ) + request.add_header("Content-Type", "application/json") + request.add_header("Accept", "application/json, text/event-stream") + request.add_header("MCP-Protocol-Version", PROTOCOL_VERSION) + if UPSTREAM_SESSION["id"]: + request.add_header(SESSION_HEADER, UPSTREAM_SESSION["id"]) + if UPSTREAM_KEY: + request.add_header( + UPSTREAM_AUTH_HEADER, UPSTREAM_AUTH_FORMAT.format(key=UPSTREAM_KEY) + ) + + with OPENER.open( + request, timeout=CONTRACT["limits"]["timeout_seconds"] + ) as response: + body = response.read(CONTRACT["limits"]["response_bytes"] + 1) + content_type = response.headers.get("Content-Type", "") + session = response.headers.get(SESSION_HEADER) + status = response.status + + if session: + UPSTREAM_SESSION["id"] = session + if len(body) > CONTRACT["limits"]["response_bytes"]: + raise ValueError("response_too_large") + return passthrough.decode_jsonrpc(body, content_type), status + + +def sse_session(): + """Return the open SSE session, opening it on first use. + + The stream is the response channel, so it stays open for the life of the + adapter rather than being reopened per call. + """ + if SSE["session"] is None: + headers = {} + if UPSTREAM_KEY: + headers[UPSTREAM_AUTH_HEADER] = UPSTREAM_AUTH_FORMAT.format( + key=UPSTREAM_KEY + ) + SSE["session"] = sse.SseSession( + UPSTREAM_URL, + headers=headers, + timeout=CONTRACT["limits"]["timeout_seconds"], + ).open() + return SSE["session"] + + +def exchange(envelope): + """Return ``(parsed, status)`` of one JSON-RPC exchange with the upstream. + + Args: + envelope: the JSON-RPC request object to send. + + Classic SSE carries the response on a stream the adapter already holds + open, so it reports the status the caller compares against rather than one + a POST returned. + """ + if UPSTREAM_TRANSPORT != passthrough.TRANSPORT_SSE: + return post_upstream(envelope) + + session = sse_session() + if "id" not in envelope: + session.notify(envelope["method"], envelope.get("params")) + return None, 202 + return ( + session.call(envelope["method"], envelope.get("params"), envelope["id"]), + 200, + ) + + +def handshake_upstream(): + if UPSTREAM_SESSION["ready"]: + return + parsed, _ = exchange( + { + "jsonrpc": "2.0", + "id": str(uuid.uuid4()), + "method": "initialize", + "params": { + "protocolVersion": PROTOCOL_VERSION, + "capabilities": {}, + "clientInfo": {"name": "infinito-mcp-adapter", "version": "1"}, + }, + } + ) + if isinstance(parsed, dict) and parsed.get("error"): + raise ValueError(f"upstream_error: initialize {str(parsed['error'])[:160]}") + exchange({"jsonrpc": "2.0", "method": "notifications/initialized"}) + UPSTREAM_SESSION["ready"] = True + + +def call_upstream_mcp(name, arguments): + """Return the result of one ``tools/call`` against an MCP upstream. + + Args: + name: the tool name, already authorised against the contract. + arguments: client arguments, forwarded unchanged. + """ + handshake_upstream() + envelope = { + "jsonrpc": "2.0", + "id": str(uuid.uuid4()), + "method": "tools/call", + "params": {"name": name, "arguments": arguments or {}}, + } + try: + parsed, status = exchange(envelope) + except (urllib.error.HTTPError, sse.SseError): + UPSTREAM_SESSION["ready"] = False + UPSTREAM_SESSION["id"] = "" + SSE["session"] = None + handshake_upstream() + parsed, status = exchange(envelope) + + if isinstance(parsed, dict) and parsed.get("error"): + raise UpstreamError( + f"upstream_error: {str(parsed['error'])[:200]}", status=status + ) + return parsed.get("result") if isinstance(parsed, dict) else None + + +class UpstreamError(ValueError): + def __init__(self, message, status): + super().__init__(message) + self.code = status + + +def upstream_status(error): + """Return the status the provider answered with, 0 when it never answered. + + Args: + error: the exception raised while calling the provider. + + The caller cannot otherwise tell a provider that is still starting from one + that refuses the adapter's credential, and those need opposite reactions: + the first is worth waiting for, the second never resolves. + """ + code = getattr(error, "code", None) + return int(code) if isinstance(code, int) else 0 + + +def tool_descriptors(): + return [ + { + "name": name, + "description": CONTRACT["tools"][name].get("description", name), + "inputSchema": CONTRACT["tools"][name].get( + "input_schema", {"type": "object", "properties": {}} + ), + } + for name in policy.listed_tools(CONTRACT) + ] + + +def dispatch(request, consumer, correlation_id): + """Return the JSON-RPC result for one MCP request. + + Args: + request: the decoded JSON-RPC request object. + consumer: the calling client's application id, for the audit record. + correlation_id: identifier tying the audit record to this request. + """ + method = request.get("method") + + if method == "initialize": + return { + "protocolVersion": PROTOCOL_VERSION, + "capabilities": {"tools": {}}, + "serverInfo": {"name": CONTRACT["provider"], "version": "1"}, + } + + if method == "tools/list": + return {"tools": tool_descriptors()} + + if method != "tools/call": + raise LookupError(f"unsupported method {method!r}") + + params = request.get("params") or {} + name = str(params.get("name") or "") + arguments = params.get("arguments") or {} + if UPSTREAM_IS_MCP: + tool = passthrough.authorize_mcp_call(CONTRACT, name, arguments) + else: + upstream_method, path = policy.authorize_call(CONTRACT, name, arguments) + + started = time.monotonic() + try: + payload = ( + call_upstream_mcp(tool, arguments) + if UPSTREAM_IS_MCP + else call_upstream(upstream_method, path, arguments) + ) + except Exception: + log( + policy.audit_event( + CONTRACT, + consumer, + name, + "upstream_error", + int((time.monotonic() - started) * 1000), + correlation_id, + ) + ) + raise + + log( + policy.audit_event( + CONTRACT, + consumer, + name, + "ok", + int((time.monotonic() - started) * 1000), + correlation_id, + ) + ) + return { + "content": [ + {"type": "text", "text": json.dumps(payload, separators=(",", ":"))} + ], + "isError": False, + } + + +class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *_args): + """Silence the default access log; the audit record is the log.""" + + def _respond(self, status, payload): + body = json.dumps(payload, separators=(",", ":")).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def _accept(self): + self.send_response(202) + self.send_header("Content-Length", "0") + self.end_headers() + + def do_GET(self): + if self.path == HEALTH: + self._respond(200, {"status": "ok", "provider": CONTRACT["provider"]}) + return + self._respond(404, {"error": "not_found"}) + + def do_POST(self): + if self.path != ENDPOINT: + self._respond(404, {"error": "not_found"}) + return + + try: + policy.authorize_client(BEARER, self.headers.get("Authorization", "")) + except PermissionError: + self._respond(401, {"error": policy.DENY_UNAUTHENTICATED}) + return + + length = int(self.headers.get("Content-Length") or 0) + if length > CONTRACT["limits"]["request_bytes"]: + self._respond(413, {"error": policy.DENY_REQUEST_TOO_LARGE}) + return + + try: + request = json.loads(self.rfile.read(length) or b"{}") + except json.JSONDecodeError: + self._respond(400, {"error": "invalid_json"}) + return + + consumer = self.headers.get("X-Infinito-Consumer", "unknown") + correlation_id = self.headers.get("X-Correlation-Id") or str(uuid.uuid4()) + + if "id" not in request: + self._accept() + return + + if not IN_FLIGHT.acquire(blocking=False): + self._respond( + 503, + { + "jsonrpc": "2.0", + "id": request.get("id"), + "error": {"code": -32000, "message": policy.DENY_TOO_MANY_REQUESTS}, + }, + ) + return + + try: + result = dispatch(request, consumer, correlation_id) + except PermissionError as error: + self._respond( + 403, + { + "jsonrpc": "2.0", + "id": request.get("id"), + "error": {"code": -32600, "message": str(error)}, + }, + ) + return + except LookupError as error: + self._respond( + 400, + { + "jsonrpc": "2.0", + "id": request.get("id"), + "error": {"code": -32601, "message": str(error)}, + }, + ) + return + except Exception as error: + self._respond( + 502, + { + "jsonrpc": "2.0", + "id": request.get("id"), + "error": { + "code": -32000, + "message": "upstream_error", + "data": {"upstream_status": upstream_status(error)}, + }, + }, + ) + return + finally: + IN_FLIGHT.release() + + self._respond( + 200, {"jsonrpc": "2.0", "id": request.get("id"), "result": result} + ) + + +def main(): + server = ThreadingHTTPServer(("0.0.0.0", PORT), Handler) # noqa: S104 - container-internal listener, reached only through its own network + server.serve_forever() + + +if __name__ == "__main__": + main() diff --git a/roles/svc-ai-mcp-adapter/files/python/sse.py b/roles/svc-ai-mcp-adapter/files/python/sse.py new file mode 100644 index 0000000000..1490b7c7a0 --- /dev/null +++ b/roles/svc-ai-mcp-adapter/files/python/sse.py @@ -0,0 +1,186 @@ +"""Client for an MCP upstream speaking the classic HTTP+SSE transport. + +Streamable HTTP answers a POST on the same request. Classic SSE splits the two: +a GET opens a stream that stays open and immediately announces a second URL, +and every call means posting to that announced URL and reading the matching id +back off the stream. The two cannot be driven from one thread, because the +response to a POST regularly arrives on the stream before the POST itself +returns, so a reader thread owns the stream and hands messages over a queue. + +This module performs I/O and holds no policy. It raises rather than exiting, so +the adapter can turn a failure into a JSON-RPC error the way it does for every +other upstream fault. +""" + +from __future__ import annotations + +import json +import queue +import threading +import urllib.error +import urllib.parse +import urllib.request + +ENDPOINT_EVENT = "endpoint" + + +class SseError(RuntimeError): + """The upstream did not behave as an SSE MCP server.""" + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + """Refuse an upstream redirect rather than follow it. + + urllib carries the original request's headers onto the redirect target, so + an upstream answering 302 with an off-host location would hand this + adapter's upstream credential to whoever it named. + """ + + def redirect_request(self, *_args, **_kwargs): + return None + + +OPENER = urllib.request.build_opener(NoRedirect) + + +class SseSession: + """One open SSE stream plus the message endpoint it announced. + + Args: + url: the stream URL to open. + headers: request headers every call carries, credential included. + timeout: seconds to wait for the announcement and for each response. + """ + + def __init__(self, url, headers=None, timeout=30): + self.url = url + self.headers = dict(headers or {}) + self.timeout = timeout + self.endpoint = None + self.status = 0 + self.content_type = "" + self.error = None + self._messages = queue.Queue() + self._announced = threading.Event() + self._response = None + self._reader = threading.Thread(target=self._read, daemon=True) + + def open(self): + """Open the stream and return once it announced its message endpoint.""" + self._reader.start() + self._announced.wait(self.timeout) + if self.endpoint is None: + raise SseError( + f"{self.url} announced no message endpoint " + f"(status {self.status}, {self.error or 'no error'})" + ) + return self + + def _read(self): + request = urllib.request.Request(self.url, method="GET") # noqa: S310 - contracted upstream origin, no user-supplied scheme + request.add_header("Accept", "text/event-stream") + for name, value in self.headers.items(): + request.add_header(name, value) + try: + self._response = OPENER.open(request, timeout=self.timeout) + except urllib.error.HTTPError as error: + self.status, self.error = error.code, error + self._announced.set() + return + except OSError as error: + self.error = error + self._announced.set() + return + + self.status = self._response.status + self.content_type = self._response.headers.get("Content-Type", "") + event = None + try: + for raw in self._response: + line = raw.decode(errors="replace").rstrip("\r\n") + if line.startswith("event:"): + event = line.split(":", 1)[1].strip() + elif line.startswith("data:"): + data = line.split(":", 1)[1].strip() + if event == ENDPOINT_EVENT: + self.endpoint = urllib.parse.urljoin(self.url, data) + self._announced.set() + else: + self._messages.put(data) + elif not line: + event = None + except (OSError, ValueError) as error: + self.error = error + finally: + self._announced.set() + + def call(self, method, params=None, request_id=1): + """Post one JSON-RPC request and return the response the stream carries. + + Args: + method: MCP method name. + params: method params, or None to send none. + request_id: id the streamed response is matched against. + """ + self._post({"jsonrpc": "2.0", "id": request_id, "method": method}, params) + return self._await(method, request_id) + + def notify(self, method, params=None): + """Post one JSON-RPC notification, which no response ever follows. + + Args: + method: MCP method name. + params: method params, or None to send none. + + A notification carries no id, so waiting for a matching response would + wait for something the protocol never sends. + """ + self._post({"jsonrpc": "2.0", "method": method}, params) + + def _post(self, payload, params): + """Post one JSON-RPC envelope to the announced request channel. + + Args: + payload: the envelope without its params. + params: method params, or None to send none. + """ + if self.endpoint is None: + raise SseError("no message endpoint; open the session first") + if params is not None: + payload["params"] = params + + request = urllib.request.Request( # noqa: S310 - endpoint the contracted upstream announced on its own stream + self.endpoint, data=json.dumps(payload).encode(), method="POST" + ) + request.add_header("Content-Type", "application/json") + for name, value in self.headers.items(): + request.add_header(name, value) + with OPENER.open(request, timeout=self.timeout): + pass + + def _await(self, method, request_id): + """Return the streamed message whose id matches, or raise on timeout. + + Args: + method: the method awaited, for the failure message. + request_id: the id to match. + + A stream carries every response, so a message for another id is + another caller's and is dropped rather than returned to this one. + """ + while True: + try: + raw = self._messages.get(timeout=self.timeout) + except queue.Empty as error: + raise SseError(f"{method} got no response on the stream") from error + try: + parsed = json.loads(raw) + except ValueError: + continue + if parsed.get("id") == request_id: + return parsed + + def close(self): + """Close the stream, releasing the reader thread.""" + if self._response is not None: + self._response.close() diff --git a/roles/svc-ai-mcp-adapter/meta/info.yml b/roles/svc-ai-mcp-adapter/meta/info.yml new file mode 100644 index 0000000000..858ae1b54f --- /dev/null +++ b/roles/svc-ai-mcp-adapter/meta/info.yml @@ -0,0 +1,5 @@ +--- +# nocheck: info-media no official demo video +logo: + class: fa-solid fa-plug-circle-check +homepage: https://modelcontextprotocol.io/ diff --git a/roles/svc-ai-mcp-adapter/meta/main.yml b/roles/svc-ai-mcp-adapter/meta/main.yml new file mode 100644 index 0000000000..df73b971f6 --- /dev/null +++ b/roles/svc-ai-mcp-adapter/meta/main.yml @@ -0,0 +1,34 @@ +--- +galaxy_info: + author: Kevin Veen-Birkenbach + description: Reusable per-provider MCP adapter exposing a narrow allowlisted read surface + license: Infinito.Nexus Community License (Non-Commercial) + company: | + Kevin Veen-Birkenbach + https://www.veen.world + galaxy_tags: + - ai + - mcp + - adapter + - proxy + - security + - self-hosted + issue_tracker_url: https://s.infinito.nexus/issues + min_ansible_version: "2.9" + platforms: + - name: ArchLinux + versions: + - all + - name: Debian + versions: + - all + - name: EL + versions: + - all + - name: Fedora + versions: + - all + - name: Ubuntu + versions: + - all +dependencies: [] diff --git a/roles/svc-ai-mcp-adapter/meta/networks.yml b/roles/svc-ai-mcp-adapter/meta/networks.yml new file mode 100644 index 0000000000..b4de29575a --- /dev/null +++ b/roles/svc-ai-mcp-adapter/meta/networks.yml @@ -0,0 +1,3 @@ +--- +local: + subnet: 192.168.221.0/24 diff --git a/roles/svc-ai-mcp-adapter/meta/services.yml b/roles/svc-ai-mcp-adapter/meta/services.yml new file mode 100644 index 0000000000..6bcd61f919 --- /dev/null +++ b/roles/svc-ai-mcp-adapter/meta/services.yml @@ -0,0 +1,27 @@ +--- +mcp-adapter: + modes: + compose: + enabled: false + swarm: + enabled: false + bond: 1 + enabled: true + shared: true + image: python + # nocheck: docker-version base of a self-built stdlib-only image, not the served application + version: "3.13.15-slim" + custom: true + name: mcp-adapter + min_storage: 130MB + cpus: "0.25" + mem_reservation: 24m + mem_limit: 48m + pids_limit: 64 + healthcheck: + flavor: http_status + path: health + ports: + internal: + http: 8080 + lifecycle: alpha diff --git a/roles/svc-ai-mcp-adapter/meta/variants.yml b/roles/svc-ai-mcp-adapter/meta/variants.yml new file mode 100644 index 0000000000..351fb19cd0 --- /dev/null +++ b/roles/svc-ai-mcp-adapter/meta/variants.yml @@ -0,0 +1,6 @@ +--- +# Matrix-deploy variant overrides for this role. The adapter has one variant: +# it is the primary entity of its own role, so a deployment either runs it or +# does not include the role at all. + +- services: {} diff --git a/roles/svc-ai-mcp-adapter/tasks/00_core.yml b/roles/svc-ai-mcp-adapter/tasks/00_core.yml new file mode 100644 index 0000000000..d1ae4f1c50 --- /dev/null +++ b/roles/svc-ai-mcp-adapter/tasks/00_core.yml @@ -0,0 +1,12 @@ +--- +- include_tasks: utils/once/flag.yml + +- name: "๐Ÿ“ฆ Stage the adapter build context on the stack host and swarm peers" + ansible.builtin.include_tasks: instance.yml + vars: + mcp_adapter_instance_dir: "{{ MCP_ADAPTER_BUILD_DIR }}" + +- name: "๐Ÿ”ง Setup container network for {{ application_id }}" + include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/network/routine.yml') }}" + vars: + compose_handlers_flush: true diff --git a/roles/svc-ai-mcp-adapter/tasks/current_key.yml b/roles/svc-ai-mcp-adapter/tasks/current_key.yml new file mode 100644 index 0000000000..f34ea7e756 --- /dev/null +++ b/roles/svc-ai-mcp-adapter/tasks/current_key.yml @@ -0,0 +1,27 @@ +--- +# Read the upstream credential the adapter is holding right now. +# +# A provider that mints its own secret hands it back once, so the deployment +# cannot re-derive it. Reading it back is what lets a converged run keep the +# working credential instead of minting a replacement and revoking the one the +# sidecar is using. +# +# Param: mcp_upstream_key_path env file the sidecar reads. +# Sets: MCP_UPSTREAM_CURRENT_KEY the stored credential, or "" when none. +- name: "๐Ÿ” Read the upstream credential file of {{ application_id }}" + ansible.builtin.slurp: + src: "{{ mcp_upstream_key_path }}" + register: mcp_upstream_current + failed_when: false + delegate_to: "{{ STACK_HOST }}" + become: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" # nocheck: include-uniform-apply-keyword the read runs on the stack host and the set_fact on the controller + +- name: "๐Ÿ”‘ Publish the credential the {{ application_id }} adapter holds" + ansible.builtin.set_fact: + MCP_UPSTREAM_CURRENT_KEY: >- + {{ (mcp_upstream_current.content | b64decode).split('=', 1)[1] | trim + if mcp_upstream_current.content is defined + and '=' in (mcp_upstream_current.content | b64decode) + else '' }} + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/svc-ai-mcp-adapter/tasks/instance.yml b/roles/svc-ai-mcp-adapter/tasks/instance.yml new file mode 100644 index 0000000000..2d276ed93d --- /dev/null +++ b/roles/svc-ai-mcp-adapter/tasks/instance.yml @@ -0,0 +1,64 @@ +--- +# Stage one adapter instance into a provider's own build context. +# +# An Ansible role cannot be instantiated twice with different variables, and a +# single shared adapter would end up holding every provider's credential. +# Providers therefore include this file and run the adapter as a sidecar inside +# their own stack, which also gives the network isolation for free: the +# instance joins only its provider's network. +# +# Staging deliberately notifies nothing, which takes an explicit empty list: +# render_replicated_templates falls back to ['compose up'] for any entry that +# names no handler. The front-proxy step inside +# sys-stk-full flushes handlers before the backend has rendered the +# provider's compose file, so a notification raised here fires a compose up +# against a project that has no compose.yml yet. rebuild.yml raises it once +# both the context and the compose file exist. +# +# Param: mcp_adapter_instance_dir build context to stage into. +# Param: mcp_adapter_upstream_key whether the sidecar reads a captured +# credential from an env file. +- name: "๐Ÿ“ Create the MCP build context of {{ application_id }}" + ansible.builtin.file: + path: "{{ mcp_adapter_instance_dir }}" + state: directory + mode: "0755" + delegate_to: "{{ STACK_HOST }}" + become: true + when: mcp_adapter_upstream_key | default(false) | bool + +- name: "๐Ÿ“„ Create the upstream credential file of {{ application_id }}" + ansible.builtin.copy: + content: "" + dest: "{{ [mcp_adapter_instance_dir, 'upstream.env'] | path_join }}" + mode: "0600" + force: false + delegate_to: "{{ STACK_HOST }}" + become: true + when: mcp_adapter_upstream_key | default(false) | bool + +- name: "๐Ÿ“ฆ Stage the MCP adapter build context for {{ application_id }}" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" + vars: + role_templates: + - src: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/files/Dockerfile') }}" + dest: "{{ [mcp_adapter_instance_dir, 'Dockerfile'] | path_join }}" + mode: "0644" + notify: [] + - src: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/files/python/policy.py') }}" + dest: "{{ [mcp_adapter_instance_dir, 'policy.py'] | path_join }}" + mode: "0644" + notify: [] + - src: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/files/python/passthrough.py') }}" + dest: "{{ [mcp_adapter_instance_dir, 'passthrough.py'] | path_join }}" + mode: "0644" + notify: [] + - src: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/files/python/server.py') }}" + dest: "{{ [mcp_adapter_instance_dir, 'server.py'] | path_join }}" + mode: "0644" + notify: [] + - src: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/files/python/sse.py') }}" + dest: "{{ [mcp_adapter_instance_dir, 'sse.py'] | path_join }}" + mode: "0644" + notify: [] diff --git a/roles/svc-ai-mcp-adapter/tasks/main.yml b/roles/svc-ai-mcp-adapter/tasks/main.yml new file mode 100644 index 0000000000..5d7d50f565 --- /dev/null +++ b/roles/svc-ai-mcp-adapter/tasks/main.yml @@ -0,0 +1,5 @@ +--- +- include_tasks: 00_core.yml + when: run_once_svc_ai_mcp_adapter is not defined + vars: + application_id: svc-ai-mcp-adapter diff --git a/roles/svc-ai-mcp-adapter/tasks/rebuild.yml b/roles/svc-ai-mcp-adapter/tasks/rebuild.yml new file mode 100644 index 0000000000..11615f5aed --- /dev/null +++ b/roles/svc-ai-mcp-adapter/tasks/rebuild.yml @@ -0,0 +1,12 @@ +--- +# Rebuild the provider's adapter sidecar after its compose file exists. +# +# instance.yml stages the build context without notifying anything, so this is +# what makes a changed policy.py or server.py reach the running sidecar. +- name: "๐Ÿงฑ Rebuild the {{ application_id }} MCP adapter image" + ansible.builtin.debug: + msg: "MCP adapter build context staged for {{ application_id }}" + changed_when: true + notify: + - compose-build + - compose-up diff --git a/roles/svc-ai-mcp-adapter/tasks/upstream_key.yml b/roles/svc-ai-mcp-adapter/tasks/upstream_key.yml new file mode 100644 index 0000000000..0ea2ce0382 --- /dev/null +++ b/roles/svc-ai-mcp-adapter/tasks/upstream_key.yml @@ -0,0 +1,27 @@ +--- +# Hand a captured upstream credential to the adapter sidecar. +# +# Some providers mint their own API secret and return it exactly once, so the +# value cannot exist when compose first renders. Writing it to an env file and +# recreating the service is what delivers it: `compose up` resolves `env_file` +# while creating the container, so the new value lands in its environment. +# A restart would not, and re-rendering the template is not part of a flush. +# +# Param: mcp_upstream_key_path env file the sidecar reads, on the stack host. +# Param: mcp_upstream_key credential the provider handed back. +- name: "๐Ÿ”‘ Write the upstream credential of {{ application_id }}" + ansible.builtin.copy: + content: "ADAPTER_UPSTREAM_KEY={{ mcp_upstream_key }}\n" + dest: "{{ mcp_upstream_key_path }}" + mode: "0600" + register: mcp_upstream_written + delegate_to: "{{ STACK_HOST }}" + become: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐Ÿ”„ Recreate the {{ application_id }} adapter with its upstream credential" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/rebuild.yml') }}" + when: mcp_upstream_written.changed + +- name: "๐Ÿšฟ Flush compose handlers for {{ application_id }}" + ansible.builtin.meta: flush_handlers diff --git a/roles/svc-ai-mcp-adapter/templates/compose.yml.j2 b/roles/svc-ai-mcp-adapter/templates/compose.yml.j2 new file mode 100644 index 0000000000..4edcb2b001 --- /dev/null +++ b/roles/svc-ai-mcp-adapter/templates/compose.yml.j2 @@ -0,0 +1,26 @@ +{% include 'roles/sys-svc-compose/templates/base.yml.j2' %} + + {% set service_name = 'mcp-adapter' %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, 'mcp-adapter') }} + build: + context: {{ MCP_ADAPTER_BUILD_DIR }} + dockerfile: Dockerfile + args: + MCP_ADAPTER_BASE_IMAGE: {{ MCP_ADAPTER_BASE_IMAGE }} + MCP_ADAPTER_BASE_VERSION: "{{ MCP_ADAPTER_BASE_VERSION }}" + {{ lookup('compose_only', 'container_name', MCP_ADAPTER_CONTAINER) }} + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + expose: + - "{{ MCP_ADAPTER_PORT }}" + {{ lookup('container_healthcheck', service_name) | indent(4) }} + {{ lookup('container_networks') | indent(4) }} + +{{ lookup('compose_networks') }} + +{{ lookup('compose_volumes') }} diff --git a/roles/svc-ai-mcp-adapter/vars/main.yml b/roles/svc-ai-mcp-adapter/vars/main.yml new file mode 100644 index 0000000000..ff43879434 --- /dev/null +++ b/roles/svc-ai-mcp-adapter/vars/main.yml @@ -0,0 +1,9 @@ +--- +application_id: "svc-ai-mcp-adapter" +entity_name: "{{ application_id | get_entity_name }}" + +MCP_ADAPTER_CONTAINER: "{{ lookup('config', application_id, 'services.mcp-adapter.name') }}" +MCP_ADAPTER_PORT: "{{ lookup('config', application_id, 'services.mcp-adapter.ports.internal.http') }}" +MCP_ADAPTER_BASE_IMAGE: "{{ lookup('config', application_id, 'services.mcp-adapter.image') }}" +MCP_ADAPTER_BASE_VERSION: "{{ lookup('config', application_id, 'services.mcp-adapter.version') }}" +MCP_ADAPTER_BUILD_DIR: "{{ lookup('container', application_id, 'directories.instance') }}" diff --git a/roles/svc-ai-ollama/README.md b/roles/svc-ai-ollama/README.md index a16b53dd83..e8e013e2dc 100644 --- a/roles/svc-ai-ollama/README.md +++ b/roles/svc-ai-ollama/README.md @@ -22,14 +22,14 @@ flowchart LR svc_container_backup["container_backup"] end subgraph dependents [Dependents] + dpt_svc_ai_litellm["svc-ai-litellm ๐Ÿณ๐Ÿ"] dpt_web_app_flowise["web-app-flowise ๐Ÿณ๐Ÿ"] dpt_web_app_minio["web-app-minio ๐Ÿณ๐Ÿ"] - dpt_web_app_openwebui["web-app-openwebui ๐Ÿณ๐Ÿ"] end dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup + svc_ollama -. "0..1" .-> dpt_svc_ai_litellm svc_ollama -. "0..1" .-> dpt_web_app_flowise svc_ollama -. "0..1" .-> dpt_web_app_minio - svc_ollama -. "0..1" .-> dpt_web_app_openwebui ``` Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (๐Ÿ’ป host, ๐Ÿณ compose, ๐Ÿ swarm); โŒ marks a service that is explicitly turned off, and โš™๏ธ an Ansible role dependency declared in `meta/main.yml`. @@ -62,19 +62,20 @@ Run the published image to provision the inventory and deploy Ollama to a manage ```bash APP=svc-ai-ollama HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-ai-ollama/meta/info.yml b/roles/svc-ai-ollama/meta/info.yml index 161b739e14..f73edd3bd0 100644 --- a/roles/svc-ai-ollama/meta/info.yml +++ b/roles/svc-ai-ollama/meta/info.yml @@ -1,4 +1,5 @@ --- +# nocheck: info-media no official demo video logo: class: fa-solid fa-microchip homepage: https://ollama.com/ diff --git a/roles/svc-ai-ollama/meta/main.yml b/roles/svc-ai-ollama/meta/main.yml index 1f4cd030a5..bfcc15121e 100644 --- a/roles/svc-ai-ollama/meta/main.yml +++ b/roles/svc-ai-ollama/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Self-hosted model server for running open LLMs locally behind a simple HTTP API diff --git a/roles/svc-ai-ollama/meta/services.yml b/roles/svc-ai-ollama/meta/services.yml index 63e0060d7f..49d885028a 100644 --- a/roles/svc-ai-ollama/meta/services.yml +++ b/roles/svc-ai-ollama/meta/services.yml @@ -23,11 +23,9 @@ ollama: ports: internal: http: 11434 - preload_models: - - llama3:latest - - mistral:latest - - nomic-embed-text:latest + preload_models: "{{ AI_LOCAL_MODELS }}" preload_async_time: 3600 + keep_alive: "-1" lifecycle: beta # nocheck: playwright-service-flag, dynamic-flag infrastructure backup consumer diff --git a/roles/svc-ai-ollama/meta/variants.yml b/roles/svc-ai-ollama/meta/variants.yml index 369d218c9b..6b9ad2d919 100644 --- a/roles/svc-ai-ollama/meta/variants.yml +++ b/roles/svc-ai-ollama/meta/variants.yml @@ -11,5 +11,5 @@ container_backup: enabled: true ollama: - preload_models: - - smollm2:135m + mem_reservation: 1g + mem_limit: 2g diff --git a/roles/svc-ai-ollama/meta/volumes.yml b/roles/svc-ai-ollama/meta/volumes.yml index ee3c45d3a8..4176925057 100644 --- a/roles/svc-ai-ollama/meta/volumes.yml +++ b/roles/svc-ai-ollama/meta/volumes.yml @@ -1,4 +1,5 @@ --- +# nocheck: embedded-state-on-nfs content-addressed model blobs, written once on pull and read-only after ollama_models: type: volume mounts: diff --git a/roles/svc-ai-ollama/tasks/01_manager_ops.yml b/roles/svc-ai-ollama/tasks/01_manager_ops.yml index c192f0272a..11fc3a70fb 100644 --- a/roles/svc-ai-ollama/tasks/01_manager_ops.yml +++ b/roles/svc-ai-ollama/tasks/01_manager_ops.yml @@ -8,11 +8,12 @@ - name: โฌ‡๏ธ Pre-pull Ollama models ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node - container exec -i {{ OLLAMA_LOCAL_CID | quote }} ollama pull {{ model }} + container exec -i {{ OLLAMA_LOCAL_CID | quote }} ollama pull {{ model.alias }} register: pull_result loop: "{{ OLLAMA_PRELOAD_MODELS }}" loop_control: loop_var: model + label: "{{ model.alias }}" # rationale: async; model pulls run overlapped, results reaped below before playwright async: "{{ OLLAMA_PRELOAD_ASYNC_TIME if ASYNC_ENABLED | bool else omit }}" poll: "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}" diff --git a/roles/svc-ai-ollama/templates/compose.yml.j2 b/roles/svc-ai-ollama/templates/compose.yml.j2 index 47b15d53ed..d442682819 100644 --- a/roles/svc-ai-ollama/templates/compose.yml.j2 +++ b/roles/svc-ai-ollama/templates/compose.yml.j2 @@ -8,6 +8,8 @@ {{ lookup('compose_only', 'container_name', OLLAMA_CONTAINER) }} expose: - "{{ OLLAMA_PORT }}" + environment: + OLLAMA_KEEP_ALIVE: "{{ OLLAMA_KEEP_ALIVE }}" {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} diff --git a/roles/svc-ai-ollama/vars/main.yml b/roles/svc-ai-ollama/vars/main.yml index a97176d268..125f6eae56 100644 --- a/roles/svc-ai-ollama/vars/main.yml +++ b/roles/svc-ai-ollama/vars/main.yml @@ -6,3 +6,4 @@ OLLAMA_CONTAINER: "{{ lookup('config', application_id, 'services.ollama.name') } OLLAMA_PORT: "{{ lookup('config', application_id, 'services.ollama.ports.internal.http') }}" OLLAMA_PRELOAD_MODELS: "{{ lookup('config', application_id, 'services.ollama.preload_models') }}" OLLAMA_PRELOAD_ASYNC_TIME: "{{ lookup('config', application_id, 'services.ollama.preload_async_time') }}" +OLLAMA_KEEP_ALIVE: "{{ lookup('config', application_id, 'services.ollama.keep_alive') }}" diff --git a/roles/svc-ai-robot/README.md b/roles/svc-ai-robot/README.md new file mode 100644 index 0000000000..58c76923ba --- /dev/null +++ b/roles/svc-ai-robot/README.md @@ -0,0 +1,93 @@ +# Robot Platform + +## Description + +[Hermes Agent](https://hermes-agent.nousresearch.com/) is an autonomous agent runtime. This role runs it in embodied mode: on a machine that is dedicated to it, with direct access to the hardware of that machine. Where the container roles put a kernel boundary between the agent and its host, here the boundary is the device itself. + +> **โš ๏ธ Hardware safety is yours, not the platform's.** An agent driving motors, actuators or relays can cause physical harm. Emergency stop, current and motion limits, and fail-safe wiring are out of this platform's scope and are not enforced by this role. Provide them yourself before granting access to anything that moves. + +## Overview + +Adding this role to a device switches the agent from isolated to embodied. The agent then receives exactly the devices listed in `ROBOT_DEVICE_ALLOWLIST` and nothing else, and the kernel-isolating runtime is dropped, because a microVM between the agent and hardware it is supposed to drive defeats the purpose. The trust boundary moves outward to the machine, but only as far as the listed devices: the container is not privileged, so a device that is not on the list is not reachable, and a lint keeps it that way. + +Because that grant is irreversible once the container starts, the checks run inside the agent role before it deploys, not afterwards in this role: the agent is a shared service, so the service loader brings it up in the constructor stage while `svc-ai` roles only run at the following step. A check placed here would sit behind the deployment it exists to prevent. + +Which agent embodies the device follows from the deployment itself: whichever of Hermes Agent and OpenClaw is present is the one that runs, and Hermes Agent wins if both are. A device with neither aborts instead of deploying an empty robot. + +## Blast radius + +The agent can do anything the granted devices allow. A GPIO or I2C grant means it can drive whatever is wired to those pins; a video grant means it can watch the room; a serial grant means it can talk to whatever sits on the bus. The allowlist is the entire boundary, which is why an empty one is refused and why the device must be dedicated, single-tenant and network-segmented. + +## Cosmos + +The diagram places Robot Platform in the Infinito.Nexus cosmos: the components it deploys (capabilities), the central services it consumes (dependencies), and its outward reach (federation and bridged external networks). + +```mermaid +flowchart LR + subgraph deps [Dependencies] + dep_web_app_hermes["web-app-hermes ๐Ÿณ๐Ÿ"] + dep_web_app_openclaw["web-app-openclaw ๐Ÿณ๐Ÿ"] + end + subgraph role [svc-ai-robot ๐Ÿ’ป] + svc_robot["robot"] + svc_hermes["hermes"] + svc_openclaw["openclaw"] + end + dep_web_app_hermes -. "0..1" .-> svc_hermes + dep_web_app_openclaw -. "0..1" .-> svc_openclaw +``` + +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (๐Ÿ’ป host, ๐Ÿณ compose, ๐Ÿ swarm); โŒ marks a service that is explicitly turned off, and โš™๏ธ an Ansible role dependency declared in `meta/main.yml`. + +## Features + +- **Declared hardware access:** Every device the agent may drive is listed by the operator and bound into the container; an empty list is refused rather than silently treated as deny-all-but-deployable. +- **Dedicated-device guard:** Deployment aborts when another application shares the host or when the device is part of a multi-node swarm, naming the offender. +- **Checks precede the grant:** The admission checks run inside the agent role before it deploys, so a refusal prevents the embodied container rather than following it. +- **Selectable agent:** Whichever agent role the deployment carries embodies the device, Hermes Agent taking precedence; the matrix deploys both so neither path rots. +- **Agent reuse:** The embodied deployment is the agent role itself, so image, configuration and model routing stay identical to the isolated deployments. + +## Quick Setup + +### Development + +Clone, set up the workstation, and deploy Robot Platform onto the local stack: + +```bash +git clone https://github.com/infinito-nexus/core.git +cd core +make onboard +make compose-deploy mode=reinstall apps=svc-ai-robot full_cycle=false +``` + +### Production + +Install Robot Platform directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): + +```bash +git clone https://github.com/infinito-nexus/core.git +cd core +bash scripts/install/package.sh +make install +source scripts/meta/env/load.sh + +APP=svc-ai-robot +DOMAIN= +TLS_MODE=self_signed +SSH_PUBLIC_KEY="" +INVENTORY=inventories/production +infinito administration inventory provision "$INVENTORY" \ + --inventory-file "$INVENTORY/devices.yml" \ + --host localhost \ + --include "$APP" \ + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" +infinito administration deploy dedicated "$INVENTORY/devices.yml" \ + --password-file "$INVENTORY/.password" \ + --diff -vv +``` + +## Credits + +Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. +Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). +Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/svc-ai-robot/TODO.md b/roles/svc-ai-robot/TODO.md new file mode 100644 index 0000000000..97b85e7418 --- /dev/null +++ b/roles/svc-ai-robot/TODO.md @@ -0,0 +1,7 @@ +# TODO + +- Never deployed: `lifecycle: pre-alpha`. The admission checks and the device binding are covered by static analysis and a compose-mode matrix round, but no run has attached real hardware, so the passthrough is proven only against a placeholder device. + +- Swarm: the device grant renders in compose mode only, matching the cadvisor precedent, because `docker stack deploy` drops `devices`. An embodied device is single-node by definition, so this is consistent rather than a gap, but the swarm path of the agent roles is never exercised with the robot role present. + +- Self-exploration (requirement 034 decision 4) now has its prerequisite: the agent reaches the listed devices. Whether an agent turn can usefully drive them is untested and needs a model backend plus a real sensor or actuator. diff --git a/roles/svc-ai-robot/meta/info.yml b/roles/svc-ai-robot/meta/info.yml new file mode 100644 index 0000000000..6b4521e0cb --- /dev/null +++ b/roles/svc-ai-robot/meta/info.yml @@ -0,0 +1,5 @@ +--- +# nocheck: info-media Self-written embodied-agent role; the trust boundary is the dedicated device, not an upstream product. +logo: + class: fa-solid fa-robot +homepage: https://hermes-agent.nousresearch.com/ diff --git a/roles/svc-ai-robot/meta/main.yml b/roles/svc-ai-robot/meta/main.yml new file mode 100644 index 0000000000..9f3e0de142 --- /dev/null +++ b/roles/svc-ai-robot/meta/main.yml @@ -0,0 +1,34 @@ +--- +galaxy_info: + author: Kevin Veen-Birkenbach + description: Embodied robot platform for Hermes on a dedicated, network-segmented single-tenant device + license: Infinito.Nexus Community License (Non-Commercial) + company: | + Kevin Veen-Birkenbach + https://www.veen.world + galaxy_tags: + - robotics + - agent + - hermes + - embodied + - gpio + - self-hosted + issue_tracker_url: https://s.infinito.nexus/issues + min_ansible_version: "2.9" + platforms: + - name: ArchLinux + versions: + - all + - name: Debian + versions: + - all + - name: EL + versions: + - all + - name: Fedora + versions: + - all + - name: Ubuntu + versions: + - all +dependencies: [] diff --git a/roles/svc-ai-robot/meta/services.yml b/roles/svc-ai-robot/meta/services.yml new file mode 100644 index 0000000000..88000ae5a3 --- /dev/null +++ b/roles/svc-ai-robot/meta/services.yml @@ -0,0 +1,27 @@ +--- +robot: + modes: + host: + enabled: true + compose: + enabled: false + swarm: + enabled: false + min_storage: "100MB" + cpus: "0.2" + mem_reservation: "64m" + mem_limit: "256m" + pids_limit: 256 + lifecycle: pre-alpha + +# nocheck: playwright-service-flag the embodied agent is the deployed workload of this role +hermes: + bond: 1 + enabled: "{{ 'web-app-hermes' in group_names }}" + shared: true # nocheck: dynamic-flag the selected agent is always the shared workload of the device + +# nocheck: playwright-service-flag the embodied agent is the deployed workload of this role +openclaw: + bond: 0.1 + enabled: "{{ 'web-app-openclaw' in group_names }}" + shared: true # nocheck: dynamic-flag the selected agent is always the shared workload of the device diff --git a/roles/svc-ai-robot/meta/variants.yml b/roles/svc-ai-robot/meta/variants.yml new file mode 100644 index 0000000000..69dd440d42 --- /dev/null +++ b/roles/svc-ai-robot/meta/variants.yml @@ -0,0 +1,16 @@ +--- +# Matrix-deploy variant overrides for this role. +# See docs/contributing/artefact/files/role/variants.md for the file format. + +- services: + hermes: + enabled: true + openclaw: + enabled: false + +# nocheck: variants-explicit-disables shared stays true for both agents by contract; enabled alone selects the embodied one +- services: + hermes: + enabled: false + openclaw: + enabled: true diff --git a/roles/svc-ai-robot/tasks/00_core.yml b/roles/svc-ai-robot/tasks/00_core.yml new file mode 100644 index 0000000000..1e49f82053 --- /dev/null +++ b/roles/svc-ai-robot/tasks/00_core.yml @@ -0,0 +1,16 @@ +--- +- include_tasks: utils/once/flag.yml + +- name: "๐Ÿ›‘ Refuse a device without an agent" + ansible.builtin.assert: + that: + - SVC_AI_ROBOT_AGENT_ROLE | length > 0 + fail_msg: >- + {{ application_id }}: neither services.hermes nor services.openclaw is enabled, so this + device has no agent to embody. Put one of the agent roles into the deployment. + +- name: "๐Ÿ“ฃ Report the embodied agent and its hardware grant" + ansible.builtin.debug: + msg: >- + {{ application_id }}: {{ SVC_AI_ROBOT_AGENT_ROLE }} embodies this device with + {{ ROBOT_DEVICE_ALLOWLIST | join(', ') }} diff --git a/roles/svc-ai-robot/tasks/main.yml b/roles/svc-ai-robot/tasks/main.yml new file mode 100644 index 0000000000..626af5e89a --- /dev/null +++ b/roles/svc-ai-robot/tasks/main.yml @@ -0,0 +1,5 @@ +--- +- include_tasks: 00_core.yml + when: run_once_svc_ai_robot is not defined + vars: + application_id: svc-ai-robot diff --git a/roles/svc-ai-robot/tasks/utils/admit.yml b/roles/svc-ai-robot/tasks/utils/admit.yml new file mode 100644 index 0000000000..b30738fb91 --- /dev/null +++ b/roles/svc-ai-robot/tasks/utils/admit.yml @@ -0,0 +1,38 @@ +--- +# Admission checks for embodied mode, included by the agent role BEFORE it +# deploys. They cannot live in svc-ai-robot's own tasks: the agent is a shared +# service, so sys-service-loader preloads it in the constructor stage while the +# svc-ai group only runs at the following step, which would put every check +# behind the deployment it is meant to prevent. +# +# Param: admit_agent_role - role id of the agent being embodied +- name: "๐Ÿ›‘ Refuse a blanket device grant" + ansible.builtin.assert: + that: + - ROBOT_DEVICE_ALLOWLIST | length > 0 + fail_msg: >- + svc-ai-robot: ROBOT_DEVICE_ALLOWLIST is empty. Privileged mode is opt-in and explicit: + list every device the agent may drive (e.g. /dev/gpiomem, /dev/i2c-1, /dev/video0). + An empty list means deny-all, so there is nothing to deploy. + +- name: "๐Ÿ” Collect the applications sharing this device" + ansible.builtin.set_fact: + _admit_foreign_apps: >- + {{ + group_names + | select('match', '^web-app-') + | reject('equalto', admit_agent_role) + | list + }} + changed_when: false + +- name: "๐Ÿ›‘ Refuse privileged hardware access on a shared device" + ansible.builtin.assert: + that: + - _admit_foreign_apps | length == 0 + - (groups['svc-swarm-node'] | default([])) | length <= 1 + fail_msg: >- + svc-ai-robot grants {{ admit_agent_role }} direct hardware access, so it MUST own a + dedicated, single-tenant, network-segmented device. This host also runs + {{ _admit_foreign_apps | join(', ') or 'a multi-node swarm' }}. Move the robot to its own + device instead of widening the blast radius of the cluster. diff --git a/roles/svc-ai-robot/vars/main.yml b/roles/svc-ai-robot/vars/main.yml new file mode 100644 index 0000000000..a56e445e59 --- /dev/null +++ b/roles/svc-ai-robot/vars/main.yml @@ -0,0 +1,9 @@ +--- +application_id: "svc-ai-robot" + +SVC_AI_ROBOT_AGENT_ROLE: >- + {{ + 'web-app-hermes' + if (lookup('config', application_id, 'services.hermes.enabled') | bool) + else ('web-app-openclaw' if (lookup('config', application_id, 'services.openclaw.enabled') | bool) else '') + }} diff --git a/roles/svc-bkp-local-2-device/README.md b/roles/svc-bkp-local-2-device/README.md index 40ac057f67..aca5be1eb3 100644 --- a/roles/svc-bkp-local-2-device/README.md +++ b/roles/svc-bkp-local-2-device/README.md @@ -65,7 +65,7 @@ make compose-deploy mode=reinstall apps=svc-bkp-local-2-device full_cycle=false ### Production -Install Backup to External Device directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Backup to External Device directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -75,6 +75,7 @@ make install source scripts/meta/env/load.sh APP=svc-bkp-local-2-device +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -82,7 +83,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-bkp-local-2-device/meta/info.yml b/roles/svc-bkp-local-2-device/meta/info.yml new file mode 100644 index 0000000000..8f10c59640 --- /dev/null +++ b/roles/svc-bkp-local-2-device/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written systemd/rsync backup role syncing the local backup tree to a swappable USB device; no upstream product website. diff --git a/roles/svc-bkp-local-2-device/meta/main.yml b/roles/svc-bkp-local-2-device/meta/main.yml index 5bd1b56d78..71c1ed5eeb 100644 --- a/roles/svc-bkp-local-2-device/meta/main.yml +++ b/roles/svc-bkp-local-2-device/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written systemd/rsync backup role syncing the local backup tree to a swappable USB device; no upstream product website. galaxy_info: author: Kevin Veen-Birkenbach description: Plug-triggered systemd backup for hard-link deduplicated snapshots of the local backup tree onto a swappable USB device diff --git a/roles/svc-bkp-nfs-2-local/README.md b/roles/svc-bkp-nfs-2-local/README.md index 6597a1034c..8b2168073c 100644 --- a/roles/svc-bkp-nfs-2-local/README.md +++ b/roles/svc-bkp-nfs-2-local/README.md @@ -72,7 +72,7 @@ make compose-deploy mode=reinstall apps=svc-bkp-nfs-2-local full_cycle=false ### Production -Install Backup NFS directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Backup NFS directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -82,6 +82,7 @@ make install source scripts/meta/env/load.sh APP=svc-bkp-nfs-2-local +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -89,7 +90,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-bkp-nfs-2-local/meta/info.yml b/roles/svc-bkp-nfs-2-local/meta/info.yml new file mode 100644 index 0000000000..58eda2b546 --- /dev/null +++ b/roles/svc-bkp-nfs-2-local/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written backup/glue role: rsync differential snapshots of an NFS export driven by a systemd unit; no consumer-facing upstream product. diff --git a/roles/svc-bkp-nfs-2-local/meta/main.yml b/roles/svc-bkp-nfs-2-local/meta/main.yml index 8605cd3ac9..a820795b1d 100644 --- a/roles/svc-bkp-nfs-2-local/meta/main.yml +++ b/roles/svc-bkp-nfs-2-local/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written backup/glue role: rsync differential snapshots of an NFS export driven by a systemd unit; no consumer-facing upstream product. galaxy_info: author: Kevin Veen-Birkenbach description: Scheduled backup job for hard-linked differential rsync snapshots of an NFS export into the local backup tree diff --git a/roles/svc-bkp-remote-2-local/README.md b/roles/svc-bkp-remote-2-local/README.md index ac1323f282..a06ffe4046 100644 --- a/roles/svc-bkp-remote-2-local/README.md +++ b/roles/svc-bkp-remote-2-local/README.md @@ -67,7 +67,7 @@ make compose-deploy mode=reinstall apps=svc-bkp-remote-2-local full_cycle=false ### Production -Install Backup Remote Server directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Backup Remote Server directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -77,6 +77,7 @@ make install source scripts/meta/env/load.sh APP=svc-bkp-remote-2-local +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -84,7 +85,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-bkp-remote-2-local/meta/info.yml b/roles/svc-bkp-remote-2-local/meta/info.yml new file mode 100644 index 0000000000..0d042f0a80 --- /dev/null +++ b/roles/svc-bkp-remote-2-local/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written pull-style SSH+rsync backup role (svc-bkp-*), custom Python/systemd glue with no consumer-facing upstream product. diff --git a/roles/svc-bkp-remote-2-local/meta/main.yml b/roles/svc-bkp-remote-2-local/meta/main.yml index 12bdb86e14..db07c47317 100644 --- a/roles/svc-bkp-remote-2-local/meta/main.yml +++ b/roles/svc-bkp-remote-2-local/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written pull-style SSH+rsync backup role (svc-bkp-*), custom Python/systemd glue with no consumer-facing upstream product. galaxy_info: author: Kevin Veen-Birkenbach description: Scheduled pull-style backup replicating remote hosts onto this host over SSH and rsync as hard-linked snapshots diff --git a/roles/svc-bkp-remote-2-local/templates/script.sh.j2 b/roles/svc-bkp-remote-2-local/templates/script.sh.j2 index 0000b7c862..4cdffc1dc8 100644 --- a/roles/svc-bkp-remote-2-local/templates/script.sh.j2 +++ b/roles/svc-bkp-remote-2-local/templates/script.sh.j2 @@ -1,4 +1,5 @@ #!/bin/bash +{# nocheck: shell-template grandfathered, values only: the provider list and two paths #} # Pulls the remote backups from multiple hosts hosts="{{ DOCKER_BACKUP_REMOTE_2_LOCAL_BACKUP_PROVIDERS | join(' ') }}" diff --git a/roles/svc-bkp-secrets-2-local/README.md b/roles/svc-bkp-secrets-2-local/README.md index f145576df0..0f8d4f3e2f 100644 --- a/roles/svc-bkp-secrets-2-local/README.md +++ b/roles/svc-bkp-secrets-2-local/README.md @@ -83,7 +83,7 @@ make compose-deploy mode=reinstall apps=svc-bkp-secrets-2-local full_cycle=false ### Production -Install Backup Host Secrets directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Backup Host Secrets directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -93,6 +93,7 @@ make install source scripts/meta/env/load.sh APP=svc-bkp-secrets-2-local +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -100,7 +101,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-bkp-secrets-2-local/meta/info.yml b/roles/svc-bkp-secrets-2-local/meta/info.yml new file mode 100644 index 0000000000..2709981b5c --- /dev/null +++ b/roles/svc-bkp-secrets-2-local/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written Infinito.Nexus backup role (svc-bkp-*) that snapshots host secrets to the local backup tree; no upstream product. diff --git a/roles/svc-bkp-secrets-2-local/meta/main.yml b/roles/svc-bkp-secrets-2-local/meta/main.yml index 5ddf7bfd74..aa011d2097 100644 --- a/roles/svc-bkp-secrets-2-local/meta/main.yml +++ b/roles/svc-bkp-secrets-2-local/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written Infinito.Nexus backup role (svc-bkp-*) that snapshots host secrets to the local backup tree; no upstream product. galaxy_info: author: Kevin Veen-Birkenbach description: Scheduled deduplicating backup of host secrets, CA, ACME credentials, and node identity to the local backup directory diff --git a/roles/svc-bkp-volume-2-local/README.md b/roles/svc-bkp-volume-2-local/README.md index 103a095777..1a09e9415b 100644 --- a/roles/svc-bkp-volume-2-local/README.md +++ b/roles/svc-bkp-volume-2-local/README.md @@ -26,6 +26,7 @@ flowchart LR svc_secrets_backup["secrets_backup"] end subgraph dependents [Dependents] + dpt_svc_ai_lmstudio["svc-ai-lmstudio ๐Ÿณ๐Ÿ"] dpt_svc_ai_ollama["svc-ai-ollama ๐Ÿณ๐Ÿ"] dpt_svc_db_elasticsearch["svc-db-elasticsearch ๐Ÿณ๐Ÿ"] dpt_svc_db_mariadb["svc-db-mariadb ๐Ÿณ๐Ÿ"] @@ -37,12 +38,12 @@ flowchart LR dpt_svc_db_typesense["svc-db-typesense ๐Ÿณ๐Ÿ"] dpt_svc_dns_unbound["svc-dns-unbound ๐Ÿณ๐Ÿ"] dpt_svc_prx_openresty["svc-prx-openresty ๐Ÿณ๐Ÿ"] - dpt_svc_registry_cache["svc-registry-cache ๐Ÿณ"] dpt_more["..."] end dep_svc_bkp_secrets_2_local -- "1:1" --> svc_secrets_backup dep_sys_ctl_cln_faild_bkps -- "1:1" --> svc_volume_2_local svc_volume_2_local -- "1:1" --> dpt_more + svc_volume_2_local -. "0..1" .-> dpt_svc_ai_lmstudio svc_volume_2_local -. "0..1" .-> dpt_svc_ai_ollama svc_volume_2_local -. "0..1" .-> dpt_svc_db_elasticsearch svc_volume_2_local -. "0..1" .-> dpt_svc_db_mariadb @@ -54,7 +55,6 @@ flowchart LR svc_volume_2_local -. "0..1" .-> dpt_svc_db_typesense svc_volume_2_local -- "1:1" --> dpt_svc_dns_unbound svc_volume_2_local -- "1:1" --> dpt_svc_prx_openresty - svc_volume_2_local -- "1:1" --> dpt_svc_registry_cache ``` Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (๐Ÿ’ป host, ๐Ÿณ compose, ๐Ÿ swarm); โŒ marks a service that is explicitly turned off, and โš™๏ธ an Ansible role dependency declared in `meta/main.yml`. @@ -190,7 +190,7 @@ make compose-deploy mode=reinstall apps=svc-bkp-volume-2-local full_cycle=false ### Production -Install Backup Docker Volumes directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Backup Docker Volumes directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -200,6 +200,7 @@ make install source scripts/meta/env/load.sh APP=svc-bkp-volume-2-local +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -207,7 +208,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-bkp-volume-2-local/meta/info.yml b/roles/svc-bkp-volume-2-local/meta/info.yml new file mode 100644 index 0000000000..09d33cf45c --- /dev/null +++ b/roles/svc-bkp-volume-2-local/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written backup infrastructure role (svc-bkp-*); wraps the author's own baudolo/backup-docker-to-local glue, no third-party consumer product website. diff --git a/roles/svc-bkp-volume-2-local/meta/main.yml b/roles/svc-bkp-volume-2-local/meta/main.yml index 8fa6d5d41b..a74eea8da8 100644 --- a/roles/svc-bkp-volume-2-local/meta/main.yml +++ b/roles/svc-bkp-volume-2-local/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written backup infrastructure role (svc-bkp-*); wraps the author's own baudolo/backup-docker-to-local glue, no third-party consumer product website. galaxy_info: author: Kevin Veen-Birkenbach description: Scheduled deduplicating backup system for Docker container volumes to a local directory, with consistent SQL dumps diff --git a/roles/svc-db-elasticsearch/README.md b/roles/svc-db-elasticsearch/README.md index 1a2b6f3c24..56bc3e298a 100644 --- a/roles/svc-db-elasticsearch/README.md +++ b/roles/svc-db-elasticsearch/README.md @@ -64,19 +64,20 @@ Run the published image to provision the inventory and deploy Elasticsearch to a ```bash APP=svc-db-elasticsearch HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-db-elasticsearch/meta/info.yml b/roles/svc-db-elasticsearch/meta/info.yml index 7d3473ebff..9cde15664f 100644 --- a/roles/svc-db-elasticsearch/meta/info.yml +++ b/roles/svc-db-elasticsearch/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://www.elastic.co/elasticsearch diff --git a/roles/svc-db-elasticsearch/meta/main.yml b/roles/svc-db-elasticsearch/meta/main.yml index a4003d563f..828f00eefe 100644 --- a/roles/svc-db-elasticsearch/meta/main.yml +++ b/roles/svc-db-elasticsearch/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Central search and analytics engine with per-consumer index namespaces isolating tenants in a shared Docker deployment diff --git a/roles/svc-db-elasticsearch/meta/services.yml b/roles/svc-db-elasticsearch/meta/services.yml index 64c6d96b81..6f13b566e6 100644 --- a/roles/svc-db-elasticsearch/meta/services.yml +++ b/roles/svc-db-elasticsearch/meta/services.yml @@ -25,6 +25,9 @@ elasticsearch: elasticsearch: 9200 internal: elasticsearch: 9200 + onion: + # nocheck: onion-flag the index is queried by the search backends of the apps sharing this stack, never by a client off the node + elasticsearch: false lifecycle: beta # nocheck: variants-coverage โ€” sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in tor: diff --git a/roles/svc-db-elasticsearch/meta/variants.yml b/roles/svc-db-elasticsearch/meta/variants.yml index 1576e2511e..a5e59537b6 100644 --- a/roles/svc-db-elasticsearch/meta/variants.yml +++ b/roles/svc-db-elasticsearch/meta/variants.yml @@ -2,6 +2,3 @@ - services: tor: enabled: true -- services: - tor: - enabled: true diff --git a/roles/svc-db-elasticsearch/templates/compose.yml.j2 b/roles/svc-db-elasticsearch/templates/compose.yml.j2 index 138ac10ee4..bb788436e4 100644 --- a/roles/svc-db-elasticsearch/templates/compose.yml.j2 +++ b/roles/svc-db-elasticsearch/templates/compose.yml.j2 @@ -18,10 +18,11 @@ test: - "CMD-SHELL" - "curl -fsS -u elastic:{{ ELASTICSEARCH_PASSWORD }} http://127.0.0.1:{{ ELASTICSEARCH_INTERNAL_PORT }}/_cluster/health || exit 1" - interval: 10s + interval: 2m timeout: 5s retries: 18 - start_period: 120s + start_period: 10m + start_interval: 5s {{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-db-mariadb/README.md b/roles/svc-db-mariadb/README.md index b1ef68b333..c08adb3023 100644 --- a/roles/svc-db-mariadb/README.md +++ b/roles/svc-db-mariadb/README.md @@ -85,19 +85,20 @@ Run the published image to provision the inventory and deploy MariaDB to a manag ```bash APP=svc-db-mariadb HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-db-mariadb/meta/services.yml b/roles/svc-db-mariadb/meta/services.yml index a7144bb80e..b31aa98a3b 100644 --- a/roles/svc-db-mariadb/meta/services.yml +++ b/roles/svc-db-mariadb/meta/services.yml @@ -22,6 +22,9 @@ mariadb: mem_limit: 4g pids_limit: 1024 exposed: false + healthcheck: + test: ["CMD-SHELL", "healthcheck.sh --su-mysql --connect --innodb_initialized"] + retries: 18 ports: local: mariadb: 3306 diff --git a/roles/svc-db-mariadb/tasks/00_core.yml b/roles/svc-db-mariadb/tasks/00_core.yml index a986f0e93b..23e761a30a 100644 --- a/roles/svc-db-mariadb/tasks/00_core.yml +++ b/roles/svc-db-mariadb/tasks/00_core.yml @@ -43,7 +43,7 @@ failed_when: false retries: 30 delay: 5 - until: mariadb_login_desired.rc == 0 + until: mariadb_login_desired.rc == 0 or 'Access denied' in mariadb_login_desired.stderr - name: "โœ… Ensure MariaDB root password matches desired value" include_tasks: 02_reset_root_password.yml diff --git a/roles/svc-db-mariadb/templates/compose.yml.j2 b/roles/svc-db-mariadb/templates/compose.yml.j2 index 9de140c8e3..e68a8c9a4c 100644 --- a/roles/svc-db-mariadb/templates/compose.yml.j2 +++ b/roles/svc-db-mariadb/templates/compose.yml.j2 @@ -17,14 +17,7 @@ {% endif %} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} - healthcheck: - test: - - "CMD-SHELL" - - "mariadb {% if MARIADB_EXPOSE_LOCAL %}-h127.0.0.1 -P3306{% endif %} -u root -p\"$${MARIADB_ROOT_PASSWORD}\" -e 'SHOW DATABASES;'" - interval: 10s - timeout: 5s - retries: 18 - start_period: 90s + {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-db-memcached/README.md b/roles/svc-db-memcached/README.md index f87a627167..a74c4aca0d 100644 --- a/roles/svc-db-memcached/README.md +++ b/roles/svc-db-memcached/README.md @@ -64,19 +64,20 @@ Run the published image to provision the inventory and deploy Memcached to a man ```bash APP=svc-db-memcached HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-db-memcached/meta/info.yml b/roles/svc-db-memcached/meta/info.yml index b60afbfaf8..62f04230f2 100644 --- a/roles/svc-db-memcached/meta/info.yml +++ b/roles/svc-db-memcached/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://memcached.org/ diff --git a/roles/svc-db-memcached/meta/main.yml b/roles/svc-db-memcached/meta/main.yml index d3bf9ea867..1c64df65e1 100644 --- a/roles/svc-db-memcached/meta/main.yml +++ b/roles/svc-db-memcached/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Central in-memory caching engine with per-consumer key-prefix isolation, usable centrally or as an embedded sidecar diff --git a/roles/svc-db-memcached/meta/services.yml b/roles/svc-db-memcached/meta/services.yml index 17de7832dc..0af5df1e7b 100644 --- a/roles/svc-db-memcached/meta/services.yml +++ b/roles/svc-db-memcached/meta/services.yml @@ -11,7 +11,7 @@ memcached: enabled: true shared: true image: memcached - version: alpine + version: 1.6.45-alpine name: memcached min_storage: 206MB backup: @@ -20,11 +20,17 @@ memcached: mem_reservation: "64m" mem_limit: "256m" pids_limit: 256 + healthcheck: + test: ["CMD-SHELL", "printf 'version\\r\\n' | nc -w 1 127.0.0.1 11211 | grep -q VERSION"] + retries: 18 ports: local: memcached: 11211 internal: memcached: 11211 + onion: + # nocheck: onion-flag the session cache speaks an unauthenticated text protocol and is read only by app containers on the role network + memcached: false lifecycle: beta # nocheck: variants-coverage โ€” sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in tor: diff --git a/roles/svc-db-memcached/meta/variants.yml b/roles/svc-db-memcached/meta/variants.yml index 1576e2511e..a5e59537b6 100644 --- a/roles/svc-db-memcached/meta/variants.yml +++ b/roles/svc-db-memcached/meta/variants.yml @@ -2,6 +2,3 @@ - services: tor: enabled: true -- services: - tor: - enabled: true diff --git a/roles/svc-db-memcached/templates/compose.yml.j2 b/roles/svc-db-memcached/templates/compose.yml.j2 index e4a1fbb1ea..1b3883ec84 100644 --- a/roles/svc-db-memcached/templates/compose.yml.j2 +++ b/roles/svc-db-memcached/templates/compose.yml.j2 @@ -13,14 +13,7 @@ {{ lookup('container_ports', ['memcached', 'memcached', DOCKER_BIND_HOST]) | indent(4) }} {% endif %} {{ lookup('container_networks') | indent(4) }} - healthcheck: - test: - - "CMD-SHELL" - - "printf 'version\\r\\n' | nc -w 1 127.0.0.1 11211 | grep -q VERSION" - interval: 10s - timeout: 5s - retries: 18 - start_period: 15s + {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-db-memcached/templates/service.yml.j2 b/roles/svc-db-memcached/templates/service.yml.j2 index 11a5b528fe..cf91ec5014 100644 --- a/roles/svc-db-memcached/templates/service.yml.j2 +++ b/roles/svc-db-memcached/templates/service.yml.j2 @@ -9,9 +9,12 @@ - memcached - -m - "64" - healthcheck: + # nocheck: container-healthcheck-literal probes every second, so the SPOT's 5s start cadence would report healthy later than this block already does + healthcheck: # nocheck: healthcheck-timing-override, healthcheck-start-period-covers-interval a swarm-init gate that must clear in seconds, so it runs without a start window rather than inside one test: ["CMD-SHELL", "printf 'version\\r\\n' | nc -w 1 127.0.0.1 11211 | grep -q VERSION"] + # nocheck: healthcheck-timing-override probes every second on purpose, which is why start_interval is left off interval: 1s + # nocheck: healthcheck-timing-override a one second nc round trip needs no five timeout: 3s retries: 30 networks: # nocheck: networks-literal local sidecar inside consumer stack, default-only attachment @@ -26,4 +29,7 @@ {% if DEPLOYMENT_MODE == 'compose' %} {{ include_resource_for('memcached') }} {% endif %} +{% set service_name = 'memcached' %} +{% set service_replicas_forced = 1 %} +{% include 'roles/sys-svc-container/templates/deploy.yml.j2' %} {{ "\n" }} diff --git a/roles/svc-db-openldap/README.md b/roles/svc-db-openldap/README.md index 75774e2d44..29b8223fc5 100644 --- a/roles/svc-db-openldap/README.md +++ b/roles/svc-db-openldap/README.md @@ -87,19 +87,20 @@ Run the published image to provision the inventory and deploy OpenLDAP to a mana ```bash APP=svc-db-openldap HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-db-openldap/files/Dockerfile b/roles/svc-db-openldap/files/Dockerfile index fe80b56124..0022d938a8 100644 --- a/roles/svc-db-openldap/files/Dockerfile +++ b/roles/svc-db-openldap/files/Dockerfile @@ -21,7 +21,7 @@ RUN chmod +x /healthcheck.sh EXPOSE 389 -HEALTHCHECK --interval=10s --timeout=5s --start-period=15s --retries=12 \ +HEALTHCHECK --interval=2m --timeout=5s --start-period=10m --retries=12 --start-interval=5s \ CMD ["/healthcheck.sh"] ENTRYPOINT ["/usr/bin/tini","--","/entrypoint.sh"] diff --git a/roles/svc-db-openldap/filter_plugins/build_ldap_role_entries.py b/roles/svc-db-openldap/filter_plugins/build_ldap_role_entries.py index 447818f48d..f0c5ed554e 100644 --- a/roles/svc-db-openldap/filter_plugins/build_ldap_role_entries.py +++ b/roles/svc-db-openldap/filter_plugins/build_ldap_role_entries.py @@ -28,6 +28,8 @@ silently dropped during sync. This filter therefore: referring parent, building the required hierarchy. """ +from utils.roles.rbac.scoped import granted_roles + _ENTRY_KIND_GROUP = "group" _TENANCY_AXIS_NONE = "none" _TENANCY_AXIS_DOMAIN = "domain" @@ -186,8 +188,7 @@ def build_ldap_role_entries(applications, users, ldap, group_names=None): member_dns = [] member_uids = [] for username, user_config in (users or {}).items(): - user_roles = (user_config or {}).get("roles", []) or [] - if role_name in user_roles: + if role_name in granted_roles(user_config or {}, application_id): user_dn = f"{ldap_user_attr}={username},{user_dn_base}" member_dns.append(user_dn) member_uids.append(username) diff --git a/roles/svc-db-openldap/meta/info.yml b/roles/svc-db-openldap/meta/info.yml index 419dfabbd9..08d261f2b2 100644 --- a/roles/svc-db-openldap/meta/info.yml +++ b/roles/svc-db-openldap/meta/info.yml @@ -1,4 +1,5 @@ --- +# nocheck: info-media no official demo video logo: class: fa-solid fa-users homepage: https://www.openldap.org/ diff --git a/roles/svc-db-openldap/meta/main.yml b/roles/svc-db-openldap/meta/main.yml index 185c50c1ca..1a76779e33 100644 --- a/roles/svc-db-openldap/meta/main.yml +++ b/roles/svc-db-openldap/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Self-hosted LDAP directory service for centralized user, group, and schema management with TLS-secured access diff --git a/roles/svc-db-openldap/meta/services.yml b/roles/svc-db-openldap/meta/services.yml index 08111859de..0372a514db 100644 --- a/roles/svc-db-openldap/meta/services.yml +++ b/roles/svc-db-openldap/meta/services.yml @@ -12,7 +12,7 @@ openldap: shared: true provides: ldap image: debian - version: bookworm-slim + version: 12.15-slim custom: true name: openldap min_storage: 229MB diff --git a/roles/svc-db-openldap/tasks/00_core.yml b/roles/svc-db-openldap/tasks/00_core.yml index 9a4e8fe8d0..2b2abe2b2d 100644 --- a/roles/svc-db-openldap/tasks/00_core.yml +++ b/roles/svc-db-openldap/tasks/00_core.yml @@ -58,7 +58,11 @@ delegate_to: "{{ STACK_HOST }}" run_once: true changed_when: false - failed_when: openldap_module_dn_raw.rc != 0 or (openldap_module_dn_raw.stdout | trim) == "" + retries: 30 + delay: 5 + until: + - openldap_module_dn_raw.rc == 0 + - (openldap_module_dn_raw.stdout | trim) != "" - name: ๐Ÿ“ Normalize OPENLDAP_MODULE_DN (ensure ,cn=config suffix) set_fact: diff --git a/roles/svc-db-openldap/tasks/02_credentials.yml b/roles/svc-db-openldap/tasks/02_credentials.yml index c3a77e85be..4326f0b76e 100644 --- a/roles/svc-db-openldap/tasks/02_credentials.yml +++ b/roles/svc-db-openldap/tasks/02_credentials.yml @@ -7,6 +7,9 @@ delegate_to: "{{ STACK_HOST }}" run_once: true changed_when: false + retries: 30 + delay: 5 + until: ldap_databases.rc == 0 - name: ๐Ÿค” Determine data backend DN (prefer mdb, fallback hdb) ansible.builtin.set_fact: @@ -45,6 +48,10 @@ delegate_to: "{{ STACK_HOST }}" run_once: true changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + retries: 30 + delay: 5 + until: openldap_rootpw_hash.rc == 0 - name: ๐Ÿ”ง Set RootDN and RootPW only if bind check failed ansible.builtin.shell: | @@ -57,6 +64,11 @@ replace: olcRootPW olcRootPW: {{ openldap_rootpw_hash.stdout }} EOF + register: openldap_rootdn_set delegate_to: "{{ STACK_HOST }}" run_once: true changed_when: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + retries: 30 + delay: 5 + until: openldap_rootdn_set.rc == 0 diff --git a/roles/svc-db-postgres/README.md b/roles/svc-db-postgres/README.md index aabf1ae47d..b4ef5ec54c 100644 --- a/roles/svc-db-postgres/README.md +++ b/roles/svc-db-postgres/README.md @@ -28,6 +28,7 @@ flowchart LR svc_container_backup["container_backup"] end subgraph dependents [Dependents] + dpt_svc_ai_litellm["svc-ai-litellm ๐Ÿณ๐Ÿ"] dpt_web_app_baserow["web-app-baserow ๐Ÿณ๐Ÿ"] dpt_web_app_bookwyrm["web-app-bookwyrm ๐Ÿณ๐Ÿ"] dpt_web_app_chess["web-app-chess ๐Ÿณ๐Ÿ"] @@ -39,12 +40,12 @@ flowchart LR dpt_web_app_funkwhale["web-app-funkwhale ๐Ÿณ๐Ÿ"] dpt_web_app_gitlab["web-app-gitlab ๐Ÿณ๐Ÿ"] dpt_web_app_jira["web-app-jira ๐Ÿณ๐Ÿ"] - dpt_web_app_keycloak["web-app-keycloak ๐Ÿณ๐Ÿ"] dpt_more["..."] end dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup dep_svc_net_tor -. "0..1" .-> svc_tor svc_postgres -- "1:1" --> dpt_more + svc_postgres -. "0..1" .-> dpt_svc_ai_litellm svc_postgres -. "0..1" .-> dpt_web_app_baserow svc_postgres -. "0..1" .-> dpt_web_app_bookwyrm svc_postgres -. "0..1" .-> dpt_web_app_chess @@ -56,7 +57,6 @@ flowchart LR svc_postgres -. "0..1" .-> dpt_web_app_funkwhale svc_postgres -. "0..1" .-> dpt_web_app_gitlab svc_postgres -. "0..1" .-> dpt_web_app_jira - svc_postgres -. "0..1" .-> dpt_web_app_keycloak ``` Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (๐Ÿ’ป host, ๐Ÿณ compose, ๐Ÿ swarm); โŒ marks a service that is explicitly turned off, and โš™๏ธ an Ansible role dependency declared in `meta/main.yml`. @@ -92,19 +92,20 @@ Run the published image to provision the inventory and deploy PostgreSQL to a ma ```bash APP=svc-db-postgres HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh b/roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh index cd9babb4d5..1571cdac4e 100644 --- a/roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh +++ b/roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh @@ -2,13 +2,20 @@ set -euo pipefail # Usage: -# tmp.sh +# set_postgres_superuser_password.sh +# +# The role is the cluster's superuser: "postgres" for the shared engine, and +# whatever POSTGRES_USER a dedicated one was initialised with. Both are reached +# the same way, over the container's local socket, which authenticates by peer +# and therefore needs no password -- that is what lets a rotated credential be +# written into an engine nobody can log into any more. container_raw="${1:-}" new_pw="${2:-}" +role="${3:-}" -if [[ -z "$container_raw" || -z "$new_pw" ]]; then - echo "Usage: $0 " >&2 +if [[ -z "$container_raw" || -z "$new_pw" || -z "$role" ]]; then + echo "Usage: $0 " >&2 exit 2 fi @@ -16,14 +23,16 @@ container="" eval "container=$container_raw" pg_exec() { - container exec "$container" bash -lc "psql -U postgres -d postgres -Atc '$1'" 2>/dev/null + container exec -e PG_ROLE="$role" "$container" bash -lc \ + "psql -U \"\$PG_ROLE\" -d postgres -Atc '$1'" 2>/dev/null } # Retry TCP auth up to 15 times (30s) to handle HBA reload delay auth_test() { for _ in {1..15}; do - if container exec -e PGPASSWORD="$new_pw" "$container" bash -lc \ - 'psql -h 127.0.0.1 -p 5432 -U postgres -d postgres -Atc "SELECT 1" >/dev/null 2>&1'; then + # shellcheck disable=SC2016 + if container exec -e PGPASSWORD="$new_pw" -e PG_ROLE="$role" "$container" bash -lc \ + 'psql -h 127.0.0.1 -p 5432 -U "$PG_ROLE" -d postgres -Atc "SELECT 1" >/dev/null 2>&1'; then return 0 fi sleep 2 @@ -72,9 +81,9 @@ for _ in {1..30}; do if auth_test; then pre_ok=1; fi # shellcheck disable=SC2016 - if ! container exec -e NEW_POSTGRES_PASSWORD="$new_pw" "$container" bash -lc ' - psql -U postgres -d postgres -v ON_ERROR_STOP=1 -v password="$NEW_POSTGRES_PASSWORD" <<'"'"'SQL'"'"' -ALTER USER postgres WITH PASSWORD :'"'"'password'"'"'; + if ! container exec -e NEW_POSTGRES_PASSWORD="$new_pw" -e PG_ROLE="$role" "$container" bash -lc ' + psql -U "$PG_ROLE" -d postgres -v ON_ERROR_STOP=1 -v role="$PG_ROLE" -v password="$NEW_POSTGRES_PASSWORD" <<'"'"'SQL'"'"' +ALTER USER :"role" WITH PASSWORD :'"'"'password'"'"'; SQL ' 2>/dev/null; then cleanup; sleep 2; continue @@ -98,58 +107,4 @@ if [[ -z "$result" ]]; then exit 1 fi -backup="${hba_file}.bak_ansible_pwcheck_$$" - -container exec "$container" bash -lc "cp -a \"$hba_file\" \"$backup\"" - -# shellcheck disable=SC2329,SC2317 -restore_hba() { - container exec "$container" bash -lc "if [ -f \"$backup\" ]; then cp -a \"$backup\" \"$hba_file\" && rm -f \"$backup\"; fi" >/dev/null 2>&1 || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error - container exec "$container" bash -lc "psql -U postgres -d postgres -Atc 'SELECT pg_reload_conf();' >/dev/null 2>&1" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error -} - -# Register direct function trap so ShellCheck sees the invocation path. -trap restore_hba EXIT - -container exec "$container" bash -lc "{ - echo 'host all all 127.0.0.1/32 scram-sha-256' - cat \"$backup\" -} > \"$hba_file\"" - -container exec "$container" bash -lc "psql -U postgres -d postgres -Atc 'SELECT pg_reload_conf();' >/dev/null" - -# Helper: test password auth explicitly over TCP -auth_test() { - container exec -e PGPASSWORD="$new_pw" "$container" bash -lc \ - 'psql -h 127.0.0.1 -p 5432 -U postgres -d postgres -Atc "SELECT 1" >/dev/null 2>&1' -} - -pre_ok=0 -if auth_test; then - pre_ok=1 -fi - -# shellcheck disable=SC2016 -container exec -e NEW_POSTGRES_PASSWORD="$new_pw" "$container" bash -lc ' - psql -U postgres -d postgres -v ON_ERROR_STOP=1 -v password="$NEW_POSTGRES_PASSWORD" <<'"'"'SQL'"'"' -ALTER USER postgres WITH PASSWORD :'"'"'password'"'"'; -SQL -' - -post_ok=0 -if auth_test; then - post_ok=1 -fi - -if [[ "$pre_ok" -eq 0 && "$post_ok" -eq 1 ]]; then - echo "[CHANGED] New password did not work before, and works now." - exit 0 -fi - -if [[ "$pre_ok" -eq 1 && "$post_ok" -eq 1 ]]; then - echo "[UNCHANGED] New password already worked before." - exit 0 -fi - -echo "[FAIL] Password auth test failed even after ALTER USER." >&2 -exit 1 +echo "$result" diff --git a/roles/svc-db-postgres/meta/info.yml b/roles/svc-db-postgres/meta/info.yml index ae1df0314d..fa7da8062b 100644 --- a/roles/svc-db-postgres/meta/info.yml +++ b/roles/svc-db-postgres/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://www.postgresql.org/ diff --git a/roles/svc-db-postgres/meta/main.yml b/roles/svc-db-postgres/meta/main.yml index cb5b4ec5b2..af04d170ce 100644 --- a/roles/svc-db-postgres/meta/main.yml +++ b/roles/svc-db-postgres/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Containerized relational database with automated database, user, and privilege provisioning diff --git a/roles/svc-db-postgres/tasks/00_core.yml b/roles/svc-db-postgres/tasks/00_core.yml index 99f8073936..8e1c9fa77c 100644 --- a/roles/svc-db-postgres/tasks/00_core.yml +++ b/roles/svc-db-postgres/tasks/00_core.yml @@ -42,7 +42,7 @@ - name: "โœ… POSTGRES | Ensure postgres superuser password matches inventory" ansible.builtin.script: > # nocheck: container-address-quote script evals the fragment itself - shell/set_postgres_superuser_password.sh {{ POSTGRES_CONTAINER_ADDRESS | quote }} {{ POSTGRES_PASSWORD | quote }} + shell/set_postgres_superuser_password.sh {{ POSTGRES_CONTAINER_ADDRESS | quote }} {{ POSTGRES_PASSWORD | quote }} postgres register: postgres_pw_result delegate_to: "{{ STACK_HOST }}" run_once: true diff --git a/roles/svc-db-postgres/tasks/01_init.yml b/roles/svc-db-postgres/tasks/01_init.yml index 8a379bcbd2..ad258a13c8 100644 --- a/roles/svc-db-postgres/tasks/01_init.yml +++ b/roles/svc-db-postgres/tasks/01_init.yml @@ -23,6 +23,7 @@ - name: โณ Wait until postgres TCP auth works block: - name: โณ Wait for Postgres TCP auth + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" ansible.builtin.shell: > # nocheck: container-exec-resolver POSTGRES_LOCAL_CID resolved at delegate_to runtime container exec -e PGPASSWORD={{ POSTGRES_PASSWORD | quote }} {{ POSTGRES_LOCAL_CID | quote }} sh -lc 'psql -h "{{ POSTGRES_LOCAL_HOST }}" -p "{{ POSTGRES_PORT }}" diff --git a/roles/svc-db-postgres/templates/Dockerfile.j2 b/roles/svc-db-postgres/templates/Dockerfile.j2 index fea5c158d8..eaf1be0e52 100644 --- a/roles/svc-db-postgres/templates/Dockerfile.j2 +++ b/roles/svc-db-postgres/templates/Dockerfile.j2 @@ -2,20 +2,14 @@ FROM {{ POSTGRES_IMAGE }}:{{ POSTGRES_VERSION }} {% if POSTGRES_LIBRARIES | length > 0 %} RUN rm -rf /var/lib/apt/lists/* \ - && apt-get -o Acquire::Retries=3 update \ + && apt-get -o Dir::Etc::sourcelist=/etc/apt/sources.list.d/pgdg.list \ + -o Dir::Etc::sourceparts=- \ + -o APT::Get::List-Cleanup=0 \ + -o Acquire::Retries=3 update \ && apt-get -o Acquire::Retries=3 install -y --no-install-recommends \ - build-essential \ - git \ - postgresql-server-dev-{{ POSTGRES_VERSION_MAJOR | default('all', true) }} \ {% for lib in POSTGRES_LIBRARIES %} -{# nocheck: repository-declared โ€” extension source, not the role's primary repo #} - && git clone {{ lib.git_source }} /tmp/{{ lib.name }} \ - && cd /tmp/{{ lib.name }} \ - && make \ - && make install \ - && rm -rf /tmp/{{ lib.name }} \ + postgresql-{{ POSTGRES_VERSION_MAJOR }}-{{ lib.apt_package }} \ {% endfor %} - && apt-get purge -y --auto-remove git build-essential \ && rm -rf /var/lib/apt/lists/* {% endif %} @@ -27,8 +21,10 @@ RUN chmod +x /usr/local/bin/boot-entrypoint.sh ENTRYPOINT ["boot-entrypoint.sh"] CMD ["postgres"] -HEALTHCHECK --interval=10s \ +# nocheck: healthcheck-timing-override a first initdb of a large cluster outlasts the ten minute window +HEALTHCHECK --interval=2m \ --timeout=5s \ --start-period=15m \ --retries=5 \ + --start-interval=5s \ CMD pg_isready -h 127.0.0.1 -U postgres || exit 1 diff --git a/roles/svc-db-qdrant/README.md b/roles/svc-db-qdrant/README.md index c38ec56626..63109f97f9 100644 --- a/roles/svc-db-qdrant/README.md +++ b/roles/svc-db-qdrant/README.md @@ -21,17 +21,30 @@ flowchart LR subgraph deps [Dependencies] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local ๐Ÿ’ป"] dep_svc_net_tor["svc-net-tor ๐Ÿณ๐Ÿ"] + dep_web_app_flowise["web-app-flowise ๐Ÿณ๐Ÿ"] + dep_web_app_hermes["web-app-hermes ๐Ÿณ๐Ÿ"] + dep_web_app_openclaw["web-app-openclaw ๐Ÿณ๐Ÿ"] + dep_web_app_openwebui["web-app-openwebui ๐Ÿณ๐Ÿ"] end subgraph role [svc-db-qdrant ๐Ÿณ๐Ÿ] svc_qdrant["qdrant"] + svc_qdrantmcp["qdrantmcp"] svc_tor["tor"] svc_container_backup["container_backup"] + svc_openwebui["openwebui"] + svc_hermes["hermes"] + svc_openclaw["openclaw"] + svc_flowise["flowise"] end subgraph dependents [Dependents] dpt_web_app_flowise["web-app-flowise ๐Ÿณ๐Ÿ"] end dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup dep_svc_net_tor -. "0..1" .-> svc_tor + dep_web_app_flowise -. "0..1" .-> svc_flowise + dep_web_app_hermes -. "0..1" .-> svc_hermes + dep_web_app_openclaw -. "0..1" .-> svc_openclaw + dep_web_app_openwebui -. "0..1" .-> svc_openwebui svc_qdrant -. "0..1" .-> dpt_web_app_flowise ``` @@ -69,19 +82,20 @@ Run the published image to provision the inventory and deploy Qdrant to a manage ```bash APP=svc-db-qdrant HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-db-qdrant/files/mcp/tools.json b/roles/svc-db-qdrant/files/mcp/tools.json new file mode 100644 index 0000000000..2e3e4141b1 --- /dev/null +++ b/roles/svc-db-qdrant/files/mcp/tools.json @@ -0,0 +1,23 @@ +{ + "qdrant_get_collection": { + "description": "Return one collection's configuration and vector count.", + "input_schema": { + "properties": { + "collection": { + "type": "string" + } + }, + "required": [ + "collection" + ], + "type": "object" + }, + "method": "GET", + "path": "/collections/{collection}" + }, + "qdrant_list_collections": { + "description": "List the collections this application may read.", + "method": "GET", + "path": "/collections" + } +} diff --git a/roles/svc-db-qdrant/files/test/.nocheck b/roles/svc-db-qdrant/files/test/.nocheck new file mode 100644 index 0000000000..2b9d82d840 --- /dev/null +++ b/roles/svc-db-qdrant/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; test-e2e-cli stages files/test/ by that fixed path. diff --git a/roles/svc-db-qdrant/files/test/test.sh b/roles/svc-db-qdrant/files/test/test.sh new file mode 100644 index 0000000000..afb2c435fd --- /dev/null +++ b/roles/svc-db-qdrant/files/test/test.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# CLI test for svc-db-qdrant: the MCP endpoint honours its declared contract. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +bash "${here}/shared/mcp/run.sh" diff --git a/roles/svc-db-qdrant/meta/mcp.yml b/roles/svc-db-qdrant/meta/mcp.yml new file mode 100644 index 0000000000..287be3c793 --- /dev/null +++ b/roles/svc-db-qdrant/meta/mcp.yml @@ -0,0 +1,41 @@ +--- +# nocheck: mcp-playwright-coverage the role ships no server block and no domain, so it renders no vhost and no playwright.env.j2; there is no URL a browser-side spec could address +classification: adapter_server +direction: server +source_url: https://s.infinito.nexus/code +transport: streamable_http +exposure: internal +auth: bearer_token +auth_subject: service_account +implementation: adapter +credential: + owner: mcp-svc-db-qdrant + source: credentials + key: mcp_bearer +endpoint: + service_key: qdrantmcp + path: /mcp + port_key: http +adapter: + type: openapi_allowlist + upstream_api_version: v1 + specification_path: roles/svc-db-qdrant/files/mcp/tools.json + specification_sha256: sha256:5b813b2bd0f45749df501584d7db4c5cff5d3d188fcd0998e160521a654022f5 +limits: + request_bytes: 65536 + response_bytes: 1048576 + timeout_seconds: 15 + concurrent_requests: 4 + page_size: 100 + result_items: 100 + stream_seconds: 300 +tools: + read_probe: + tool: qdrant_list_collections + arguments: {} + allowlist: + - qdrant_list_collections + - qdrant_get_collection + schema_sha256: sha256:95037a1f1d060f8bbf092ac5943fb705d699ce0c30491a4b1c884fe1bf81d2f7 + read_only_default: true + mutating_tools_enabled: false diff --git a/roles/svc-db-qdrant/meta/networks.yml b/roles/svc-db-qdrant/meta/networks.yml index 17078090d0..77711b5672 100644 --- a/roles/svc-db-qdrant/meta/networks.yml +++ b/roles/svc-db-qdrant/meta/networks.yml @@ -5,5 +5,5 @@ overlay: modes: [compose, swarm] topology: shared_net consumer: - kind: services_flags + kind: [services_flags, mcp_client] key: qdrant diff --git a/roles/svc-db-qdrant/meta/rbac.yml b/roles/svc-db-qdrant/meta/rbac.yml new file mode 100644 index 0000000000..084e6fbeca --- /dev/null +++ b/roles/svc-db-qdrant/meta/rbac.yml @@ -0,0 +1,4 @@ +--- +roles: + mcp: + description: Can drive this application through an MCP client, which acts with the credentials the deployment issued rather than the caller's own diff --git a/roles/svc-db-qdrant/meta/secrets.yml b/roles/svc-db-qdrant/meta/secrets.yml new file mode 100644 index 0000000000..731b3f8799 --- /dev/null +++ b/roles/svc-db-qdrant/meta/secrets.yml @@ -0,0 +1,19 @@ +--- +credentials: + api_key: + description: "Qdrant API key granting full access to every collection. Held by the applications that own data in this engine; the MCP adapter never receives it." + algorithm: alphanumeric + validation: "^[A-Za-z0-9]{32,}$" + length: 48 + read_only_api_key: + description: "Qdrant API key granting read access only. The MCP adapter presents this one, so a contract that named a write route would still be refused by the + engine." + algorithm: alphanumeric + validation: "^[A-Za-z0-9]{32,}$" + length: 48 + mcp_bearer: + description: "Bearer an MCP client must present to the Qdrant adapter instance. Distinct from the Qdrant API key the adapter presents upstream, because authenticating + to Qdrant says nothing about who called the adapter." + algorithm: alphanumeric + validation: "^[A-Za-z0-9]{32,}$" + length: 48 diff --git a/roles/svc-db-qdrant/meta/services.yml b/roles/svc-db-qdrant/meta/services.yml index 08263fc8ed..50a5a5fb7c 100644 --- a/roles/svc-db-qdrant/meta/services.yml +++ b/roles/svc-db-qdrant/meta/services.yml @@ -20,12 +20,36 @@ qdrant: mem_reservation: 1g mem_limit: 2g pids_limit: 1024 + healthcheck: + test: ["CMD-SHELL", "bash -c 'exec 3<>/dev/tcp/127.0.0.1/6333; printf \"GET /readyz HTTP/1.0\\r\\n\\r\\n\" >&3; grep -q \"200 OK\" <&3'"] + retries: 18 ports: local: qdrant: 6333 internal: qdrant: 6333 + onion: + # nocheck: onion-flag the vector store is read by the svc-ai roles in this stack; its MCP sidecar is the surface meant for outside callers + qdrant: false lifecycle: beta +# nocheck: playwright-service-flag internal adapter sidecar, covered by the role's MCP integration test +# nocheck: dockerfile-custom the Dockerfile is owned by svc-ai-mcp-adapter and staged per instance, so every adapter-backed provider shares one audited build +# nocheck: dynamic-flag the sidecar tracks this role's own mcp flag, not another role's presence; a group_names expression would decide its exposure from an unrelated deployment +qdrantmcp: + enabled: "{{ lookup('config', 'svc-db-qdrant', 'mcp.enabled') | bool }}" + shared: false + image: python + # nocheck: docker-version base of the self-built stdlib adapter, not the served application + version: "3.13.15-slim" + custom: true + name: qdrantmcp + cpus: "0.25" + mem_reservation: 24m + mem_limit: 48m + pids_limit: 64 + ports: + internal: + http: 8080 # nocheck: variants-coverage โ€” sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in tor: bond: 0.5 @@ -37,3 +61,23 @@ container_backup: # nocheck: bond-baseline backup host joins outside the variant bond: 1 enabled: "{{ 'svc-bkp-volume-2-local' in group_names }}" shared: true +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openwebui: + bond: 0.5 + enabled: "{{ 'web-app-openwebui' in group_names }}" + shared: "{{ 'web-app-openwebui' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +hermes: + bond: 0.5 + enabled: "{{ 'web-app-hermes' in group_names }}" + shared: "{{ 'web-app-hermes' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openclaw: + bond: 0.5 + enabled: "{{ 'web-app-openclaw' in group_names }}" + shared: "{{ 'web-app-openclaw' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +flowise: + bond: 0.5 + enabled: "{{ 'web-app-flowise' in group_names }}" + shared: "{{ 'web-app-flowise' in group_names }}" diff --git a/roles/svc-db-qdrant/meta/tests.yml b/roles/svc-db-qdrant/meta/tests.yml new file mode 100644 index 0000000000..28bea0efe2 --- /dev/null +++ b/roles/svc-db-qdrant/meta/tests.yml @@ -0,0 +1,3 @@ +--- +cli: + timeout: 900 diff --git a/roles/svc-db-qdrant/meta/variants.yml b/roles/svc-db-qdrant/meta/variants.yml index 1576e2511e..0546253d99 100644 --- a/roles/svc-db-qdrant/meta/variants.yml +++ b/roles/svc-db-qdrant/meta/variants.yml @@ -1,7 +1,34 @@ --- +# Matrix-deploy variant overrides for svc-db-qdrant. +# See docs/contributing/artefact/files/role/variants.md for the file format. + - services: tor: enabled: true + openwebui: + enabled: false + shared: false + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false + flowise: + enabled: false + shared: false - services: tor: enabled: true + openwebui: + enabled: true + shared: true + hermes: + enabled: true + shared: true + openclaw: + enabled: true + shared: true + flowise: + enabled: true + shared: true diff --git a/roles/svc-db-qdrant/tasks/00_core.yml b/roles/svc-db-qdrant/tasks/00_core.yml index 83d7ebbc96..e20204c153 100644 --- a/roles/svc-db-qdrant/tasks/00_core.yml +++ b/roles/svc-db-qdrant/tasks/00_core.yml @@ -1,6 +1,22 @@ --- - include_tasks: utils/once/flag.yml +- name: "๐Ÿฅพ For '{{ application_id }}': bootstrap the compose host once" + ansible.builtin.include_role: + name: sys-svc-compose + tasks_from: 00_core.yml + when: run_once_sys_svc_compose is not defined + +- name: "๐Ÿ”Œ Stage the MCP adapter instance for {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/instance.yml') }}" + vars: + mcp_adapter_instance_dir: "{{ QDRANT_MCP_INSTANCE_DIR }}" + when: QDRANT_MCP_ENABLED | bool + +- name: "๐Ÿงฑ Rebuild the MCP adapter of {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/rebuild.yml') }}" + when: QDRANT_MCP_ENABLED | bool + - name: "๐Ÿ”ง Setup container network for {{ application_id }}" include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/network/routine.yml') }}" vars: diff --git a/roles/svc-db-qdrant/templates/compose.yml.j2 b/roles/svc-db-qdrant/templates/compose.yml.j2 index 945026cc26..907349dd41 100644 --- a/roles/svc-db-qdrant/templates/compose.yml.j2 +++ b/roles/svc-db-qdrant/templates/compose.yml.j2 @@ -10,14 +10,37 @@ {% endif %} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} - healthcheck: - test: - - "CMD-SHELL" - - "bash -c 'exec 3<>/dev/tcp/127.0.0.1/6333; printf \"GET /readyz HTTP/1.0\\r\\n\\r\\n\" >&3; grep -q \"200 OK\" <&3'" - interval: 10s - timeout: 5s - retries: 18 - start_period: 60s + {{ lookup('container_healthcheck', service_name) | indent(4) }} + + {% if QDRANT_MCP_ENABLED | bool %} + {% set service_name = QDRANT_MCP_SERVICE_KEY %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, 'qdrantmcp') }} + build: + context: {{ QDRANT_MCP_INSTANCE_DIR }} + dockerfile: Dockerfile + args: + MCP_ADAPTER_BASE_IMAGE: {{ lookup('config', application_id, 'services.qdrantmcp.image') }} + MCP_ADAPTER_BASE_VERSION: "{{ lookup('config', application_id, 'services.qdrantmcp.version') }}" + {{ lookup('compose_only', 'container_name', QDRANT_MCP_CONTAINER) }} + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + environment: + ADAPTER_CONTRACT: {{ QDRANT_MCP_CONTRACT | to_json | to_json | replace('$', '$$') }} + ADAPTER_BEARER: {{ QDRANT_MCP_BEARER | to_json }} + ADAPTER_PORT: "{{ QDRANT_MCP_PORT }}" + ADAPTER_UPSTREAM_AUTH_FORMAT: "{key}" + ADAPTER_UPSTREAM_AUTH_HEADER: api-key + ADAPTER_UPSTREAM_KEY: {{ QDRANT_MCP_UPSTREAM_KEY | to_json }} + expose: + - "{{ QDRANT_MCP_PORT }}" + {{ lookup('container_networks', own_network_only=True, provider_self_alias=False) | indent(4) }} + {{ lookup('depends_on', {'qdrant': 'service_healthy'}) }} + {% endif %} {{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-db-qdrant/templates/env.j2 b/roles/svc-db-qdrant/templates/env.j2 index 559a857328..c52c5ce604 100644 --- a/roles/svc-db-qdrant/templates/env.j2 +++ b/roles/svc-db-qdrant/templates/env.j2 @@ -1,4 +1,6 @@ {% include 'roles/sys-svc-container/templates/env.j2' %} +QDRANT__SERVICE__API_KEY={{ QDRANT_API_KEY | dotenv_quote }} QDRANT__SERVICE__HTTP_PORT={{ QDRANT_PORT }} +QDRANT__SERVICE__READ_ONLY_API_KEY={{ QDRANT_READ_ONLY_API_KEY | dotenv_quote }} QDRANT__TELEMETRY_DISABLED=true diff --git a/roles/svc-db-qdrant/templates/test.env.j2 b/roles/svc-db-qdrant/templates/test.env.j2 new file mode 100644 index 0000000000..3c7bacad44 --- /dev/null +++ b/roles/svc-db-qdrant/templates/test.env.j2 @@ -0,0 +1 @@ +{{ lookup('template', lookup('path_absolute', 'roles/test-e2e-cli/templates/mcp/test.env.j2')) }} diff --git a/roles/svc-db-qdrant/vars/main.yml b/roles/svc-db-qdrant/vars/main.yml index 98e7b5c01e..05c9d93010 100644 --- a/roles/svc-db-qdrant/vars/main.yml +++ b/roles/svc-db-qdrant/vars/main.yml @@ -10,3 +10,22 @@ QDRANT_PORT: "{{ database_port | default(lookup('config', application_id, 'servi QDRANT_EXPOSE_LOCAL: true QDRANT_DELAY: 2 QDRANT_EXEC_SHELL: "container exec {{ QDRANT_CONTAINER_ADDRESS }} bash -lc" +QDRANT_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.api_key') }}" +QDRANT_READ_ONLY_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.read_only_api_key') }}" + +QDRANT_MCP_ENABLED: "{{ lookup('config', application_id, 'services.qdrantmcp.enabled') | bool }}" +QDRANT_MCP_SERVICE_KEY: "qdrantmcp" +QDRANT_MCP_CONTAINER: "{{ lookup('config', application_id, 'services.qdrantmcp.name') }}" +QDRANT_MCP_PORT: "{{ lookup('config', application_id, 'services.qdrantmcp.ports.internal.http') }}" +QDRANT_MCP_BEARER: "{{ lookup('config', application_id, 'secrets.credentials.mcp_bearer') }}" +QDRANT_MCP_INSTANCE_DIR: "{{ [lookup('container', application_id, 'directories.instance'), 'mcp'] | path_join }}" +QDRANT_MCP_UPSTREAM_URL: "http://{{ QDRANT_CONTAINER }}:{{ lookup('config', application_id, 'services.qdrant.ports.internal.qdrant') }}" +QDRANT_MCP_CONTRACT: + provider: "{{ application_id }}" + upstream_url: "{{ QDRANT_MCP_UPSTREAM_URL }}" + auth_subject: "{{ lookup('config', application_id, 'mcp.auth_subject') }}" + mutating_tools_enabled: "{{ lookup('config', application_id, 'mcp.tools.mutating_tools_enabled') | bool }}" + tools: "{{ lookup('file', 'mcp/tools.json') | from_json }}" + limits: "{{ lookup('config', application_id, 'mcp.limits') }}" + schema_sha256: "{{ lookup('config', application_id, 'mcp.tools.schema_sha256') }}" +QDRANT_MCP_UPSTREAM_KEY: "{{ QDRANT_READ_ONLY_API_KEY }}" diff --git a/roles/svc-db-rabbitmq/README.md b/roles/svc-db-rabbitmq/README.md index 2720e8d4d1..471a888987 100644 --- a/roles/svc-db-rabbitmq/README.md +++ b/roles/svc-db-rabbitmq/README.md @@ -63,19 +63,20 @@ Run the published image to provision the inventory and deploy RabbitMQ to a mana ```bash APP=svc-db-rabbitmq HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-db-rabbitmq/meta/info.yml b/roles/svc-db-rabbitmq/meta/info.yml index 8be0e9d2f9..6b91f9fa09 100644 --- a/roles/svc-db-rabbitmq/meta/info.yml +++ b/roles/svc-db-rabbitmq/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://www.rabbitmq.com/ diff --git a/roles/svc-db-rabbitmq/meta/main.yml b/roles/svc-db-rabbitmq/meta/main.yml index e30caed233..da0dcb9277 100644 --- a/roles/svc-db-rabbitmq/meta/main.yml +++ b/roles/svc-db-rabbitmq/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Shared message broker for async messaging with per-consumer virtual host and user isolation diff --git a/roles/svc-db-rabbitmq/meta/services.yml b/roles/svc-db-rabbitmq/meta/services.yml index fb2f03e172..b3183f721d 100644 --- a/roles/svc-db-rabbitmq/meta/services.yml +++ b/roles/svc-db-rabbitmq/meta/services.yml @@ -20,11 +20,17 @@ rabbitmq: mem_reservation: 512m mem_limit: 1g pids_limit: 1024 + healthcheck: + test: ["CMD-SHELL", "rabbitmq-diagnostics -q ping || exit 1"] + retries: 18 ports: local: rabbitmq: 5672 internal: rabbitmq: 5672 + onion: + # nocheck: onion-flag AMQP carries the apps' own worker queues; a broker reachable off the node would let anyone enqueue jobs + rabbitmq: false lifecycle: beta # nocheck: variants-coverage โ€” sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in tor: diff --git a/roles/svc-db-rabbitmq/meta/variants.yml b/roles/svc-db-rabbitmq/meta/variants.yml index 1576e2511e..a5e59537b6 100644 --- a/roles/svc-db-rabbitmq/meta/variants.yml +++ b/roles/svc-db-rabbitmq/meta/variants.yml @@ -2,6 +2,3 @@ - services: tor: enabled: true -- services: - tor: - enabled: true diff --git a/roles/svc-db-rabbitmq/templates/compose.yml.j2 b/roles/svc-db-rabbitmq/templates/compose.yml.j2 index d2a108c5d0..bc23c6685d 100644 --- a/roles/svc-db-rabbitmq/templates/compose.yml.j2 +++ b/roles/svc-db-rabbitmq/templates/compose.yml.j2 @@ -11,14 +11,7 @@ {% endif %} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} - healthcheck: - test: - - "CMD-SHELL" - - "rabbitmq-diagnostics -q ping || exit 1" - interval: 10s - timeout: 5s - retries: 18 - start_period: 60s + {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-db-redis/README.md b/roles/svc-db-redis/README.md index e51b9b20ab..6a4f203290 100644 --- a/roles/svc-db-redis/README.md +++ b/roles/svc-db-redis/README.md @@ -97,19 +97,20 @@ Run the published image to provision the inventory and deploy Redis to a managed ```bash APP=svc-db-redis HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-db-redis/meta/info.yml b/roles/svc-db-redis/meta/info.yml index 4b68d91ae7..13e331f451 100644 --- a/roles/svc-db-redis/meta/info.yml +++ b/roles/svc-db-redis/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://redis.io/ diff --git a/roles/svc-db-redis/meta/main.yml b/roles/svc-db-redis/meta/main.yml index 29a9eea6b6..aafafc7f99 100644 --- a/roles/svc-db-redis/meta/main.yml +++ b/roles/svc-db-redis/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: In-memory key-value cache and store, shared centrally with per-consumer ACL isolation or embedded as a sidecar diff --git a/roles/svc-db-redis/meta/services.yml b/roles/svc-db-redis/meta/services.yml index 622a9948fb..d8d43fba90 100644 --- a/roles/svc-db-redis/meta/services.yml +++ b/roles/svc-db-redis/meta/services.yml @@ -12,7 +12,7 @@ redis: shared: true image: redis name: redis-central - version: alpine + version: 8.10.1-alpine min_storage: 238MB backup: disabled: true @@ -25,6 +25,9 @@ redis: redis: 6379 internal: redis: 6379 + onion: + # nocheck: onion-flag the shared cache and queue runs without AUTH inside the stack, so its reachability must stay bounded by the role network + redis: false lifecycle: beta # nocheck: variants-coverage โ€” sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in tor: @@ -34,6 +37,5 @@ tor: # nocheck: dynamic-flag - the redis volume is backup-disabled ephemeral cache state, the backup consumer stays permanently off container_backup: - bond: 1 enabled: false shared: true diff --git a/roles/svc-db-redis/meta/variants.yml b/roles/svc-db-redis/meta/variants.yml index 1576e2511e..a5e59537b6 100644 --- a/roles/svc-db-redis/meta/variants.yml +++ b/roles/svc-db-redis/meta/variants.yml @@ -2,6 +2,3 @@ - services: tor: enabled: true -- services: - tor: - enabled: true diff --git a/roles/svc-db-redis/tasks/01_init.yml b/roles/svc-db-redis/tasks/01_init.yml index 77b3986887..97546042fd 100644 --- a/roles/svc-db-redis/tasks/01_init.yml +++ b/roles/svc-db-redis/tasks/01_init.yml @@ -47,7 +47,6 @@ - name: "๐Ÿ”ง REDIS | Provision ACL user {{ redis_acl_username }} (auth-isolated)" ansible.builtin.shell: > container exec - -e REDIS_PASSWORD={{ REDIS_PASSWORD | quote }} -e REDIS_ACL_PASSWORD={{ redis_acl_password | quote }} {{ REDIS_CONTAINER_ADDRESS }} sh -lc '{{ REDIS_CLI }} ACL SETUSER {{ redis_acl_username }} diff --git a/roles/svc-db-redis/templates/compose.yml.j2 b/roles/svc-db-redis/templates/compose.yml.j2 index d36ae5df10..efdbf2ef51 100644 --- a/roles/svc-db-redis/templates/compose.yml.j2 +++ b/roles/svc-db-redis/templates/compose.yml.j2 @@ -19,10 +19,11 @@ {% endif %} healthcheck: test: ["CMD-SHELL", "redis-cli -a {{ REDIS_PASSWORD | quote }} --no-auth-warning ping | grep -q PONG"] - interval: 10s + interval: 2m timeout: 5s retries: 30 - start_period: 30s + start_period: 10m + start_interval: 5s {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} diff --git a/roles/svc-db-redis/templates/service.yml.j2 b/roles/svc-db-redis/templates/service.yml.j2 index 70015ed8d6..e678ee590e 100644 --- a/roles/svc-db-redis/templates/service.yml.j2 +++ b/roles/svc-db-redis/templates/service.yml.j2 @@ -16,9 +16,12 @@ - --maxmemory {{ lookup('applications') | redis_maxmemory_mb(application_id, 0.8, RESOURCE_MEM_LIMIT | int ) }}mb - --maxmemory-policy - "allkeys-lru" - healthcheck: + # nocheck: container-healthcheck-literal probes every second, so the SPOT's 5s start cadence would report healthy later than this block already does + healthcheck: # nocheck: healthcheck-timing-override, healthcheck-start-period-covers-interval a swarm-init gate that must clear in seconds, so it runs without a start window rather than inside one test: ["CMD", "redis-cli", "ping"] + # nocheck: healthcheck-timing-override probes every second on purpose, which is why start_interval is left off interval: 1s + # nocheck: healthcheck-timing-override a redis ping needs no five seconds timeout: 3s retries: 30 networks: # nocheck: networks-literal local sidecar inside consumer stack, default-only attachment @@ -33,4 +36,7 @@ {% if DEPLOYMENT_MODE == 'compose' %} {{ include_resource_for('redis') }} {% endif %} +{% set service_name = 'redis' %} +{% set service_replicas_forced = 1 %} +{% include 'roles/sys-svc-container/templates/deploy.yml.j2' %} {{ "\n" }} diff --git a/roles/svc-db-redis/vars/main.yml b/roles/svc-db-redis/vars/main.yml index 43c4c8c831..bffc7cef2f 100644 --- a/roles/svc-db-redis/vars/main.yml +++ b/roles/svc-db-redis/vars/main.yml @@ -10,5 +10,5 @@ REDIS_PASSWORD: "{{ lookup('config', application_id, 'secrets.credentials.REDIS_ REDIS_EXPOSE_LOCAL: true REDIS_RETRIES: 5 REDIS_DELAY: 5 -REDIS_EXEC_SHELL: "container exec -e REDIS_PASSWORD={{ REDIS_PASSWORD | quote }} {{ REDIS_CONTAINER_ADDRESS }} sh -lc" +REDIS_EXEC_SHELL: "container exec {{ REDIS_CONTAINER_ADDRESS }} sh -lc" REDIS_CLI: 'redis-cli -a "$REDIS_PASSWORD" --no-auth-warning' diff --git a/roles/svc-db-typesense/README.md b/roles/svc-db-typesense/README.md index 22104b79d6..d7ef8140d3 100644 --- a/roles/svc-db-typesense/README.md +++ b/roles/svc-db-typesense/README.md @@ -68,19 +68,20 @@ Run the published image to provision the inventory and deploy Typesense to a man ```bash APP=svc-db-typesense HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-db-typesense/meta/info.yml b/roles/svc-db-typesense/meta/info.yml index d55f78368e..65a669c734 100644 --- a/roles/svc-db-typesense/meta/info.yml +++ b/roles/svc-db-typesense/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://typesense.org/ diff --git a/roles/svc-db-typesense/meta/main.yml b/roles/svc-db-typesense/meta/main.yml index a235ee2f30..98a8a08878 100644 --- a/roles/svc-db-typesense/meta/main.yml +++ b/roles/svc-db-typesense/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Central Dockerized search engine shared by multiple apps with per-consumer scoped API keys diff --git a/roles/svc-db-typesense/meta/services.yml b/roles/svc-db-typesense/meta/services.yml index 39741044ff..8304c9e73a 100644 --- a/roles/svc-db-typesense/meta/services.yml +++ b/roles/svc-db-typesense/meta/services.yml @@ -20,11 +20,17 @@ typesense: mem_reservation: 512m mem_limit: 1g pids_limit: 1024 + healthcheck: + test: ["CMD-SHELL", "bash -c 'exec 3<>/dev/tcp/127.0.0.1/8108; printf \"GET /health HTTP/1.0\\r\\n\\r\\n\" >&3; grep -q \"200 OK\" <&3'"] + retries: 18 ports: local: typesense: 8108 internal: typesense: 8108 + onion: + # nocheck: onion-flag the search index is queried by the app containers holding its API key, and the apps themselves are served through the onion's port 80 + typesense: false lifecycle: beta # nocheck: variants-coverage โ€” sso-variant-tor requires the onion on in every variant, so the false polarity has no variant left to live in tor: diff --git a/roles/svc-db-typesense/meta/variants.yml b/roles/svc-db-typesense/meta/variants.yml index 1576e2511e..a5e59537b6 100644 --- a/roles/svc-db-typesense/meta/variants.yml +++ b/roles/svc-db-typesense/meta/variants.yml @@ -2,6 +2,3 @@ - services: tor: enabled: true -- services: - tor: - enabled: true diff --git a/roles/svc-db-typesense/templates/compose.yml.j2 b/roles/svc-db-typesense/templates/compose.yml.j2 index ad2ceace21..90b6350447 100644 --- a/roles/svc-db-typesense/templates/compose.yml.j2 +++ b/roles/svc-db-typesense/templates/compose.yml.j2 @@ -18,14 +18,7 @@ {% endif %} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} - healthcheck: - test: - - "CMD-SHELL" - - "bash -c 'exec 3<>/dev/tcp/127.0.0.1/8108; printf \"GET /health HTTP/1.0\\r\\n\\r\\n\" >&3; grep -q \"200 OK\" <&3'" - interval: 10s - timeout: 5s - retries: 18 - start_period: 30s + {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-dns-unbound/README.md b/roles/svc-dns-unbound/README.md index 83271e0604..da649b554d 100644 --- a/roles/svc-dns-unbound/README.md +++ b/roles/svc-dns-unbound/README.md @@ -61,19 +61,20 @@ Run the published image to provision the inventory and deploy Unbound to a manag ```bash APP=svc-dns-unbound HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-dns-unbound/meta/info.yml b/roles/svc-dns-unbound/meta/info.yml index d5c083a2b5..96bb734c03 100644 --- a/roles/svc-dns-unbound/meta/info.yml +++ b/roles/svc-dns-unbound/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://nlnetlabs.nl/projects/unbound/about/ diff --git a/roles/svc-dns-unbound/meta/main.yml b/roles/svc-dns-unbound/meta/main.yml index f84fdc6405..bf5965fd4a 100644 --- a/roles/svc-dns-unbound/meta/main.yml +++ b/roles/svc-dns-unbound/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Central recursive/forwarding DNSSEC resolver on a static IP for consumer stacks to target as their DNS diff --git a/roles/svc-dns-unbound/meta/services.yml b/roles/svc-dns-unbound/meta/services.yml index a0b122a573..e440222e4b 100644 --- a/roles/svc-dns-unbound/meta/services.yml +++ b/roles/svc-dns-unbound/meta/services.yml @@ -21,12 +21,16 @@ unbound: mem_limit: "512m" pids_limit: 256 ports: + internal: + unbound: 53 local: unbound: 53 + onion: + # nocheck: onion-flag a recursive resolver published on the onion is an open resolver, and the containers it serves reach it on the role network + unbound: false lifecycle: beta # nocheck: dynamic-flag - the resolver state volume is backup-disabled rebuildable cache, the backup consumer stays permanently off container_backup: - bond: 1 enabled: false shared: true diff --git a/roles/svc-dns-unbound/templates/compose.yml.j2 b/roles/svc-dns-unbound/templates/compose.yml.j2 index f6371fed79..86f759571d 100644 --- a/roles/svc-dns-unbound/templates/compose.yml.j2 +++ b/roles/svc-dns-unbound/templates/compose.yml.j2 @@ -6,9 +6,9 @@ {{ lookup('container_image', application_id, 'unbound') }} {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {% if DEPLOYMENT_MODE == 'compose' and not (DOCKER_IN_CONTAINER | bool) %} - ports: - - "{{ DOCKER_BIND_HOST }}:{{ UNBOUND_PORT }}:53/udp" # nocheck: compose-ports-must-use-container-ports - - "{{ DOCKER_BIND_HOST }}:{{ UNBOUND_PORT }}:53/tcp" # nocheck: compose-ports-must-use-container-ports + {{ lookup('container_ports', + {'service': 'unbound', 'protocol': 'unbound', 'ip': DOCKER_BIND_HOST, + 'transport': ['udp', 'tcp']}) | indent(4) }} {% endif %} {{ lookup('container_volumes', service_name) | indent(4) }} networks: # nocheck: networks-literal static-IP resolver on its own engine overlay so consumers can point dns: at it diff --git a/roles/svc-dns-unbound/templates/unbound.conf.j2 b/roles/svc-dns-unbound/templates/unbound.conf.j2 index d9f07c33b3..047486d8da 100644 --- a/roles/svc-dns-unbound/templates/unbound.conf.j2 +++ b/roles/svc-dns-unbound/templates/unbound.conf.j2 @@ -7,10 +7,9 @@ server: do-udp: yes do-tcp: yes do-daemonize: no - access-control: 127.0.0.0/8 allow - access-control: 10.0.0.0/8 allow - access-control: 172.16.0.0/12 allow - access-control: 192.168.0.0/16 allow +{% for _cidr in NETWORK_INTERNAL_CIDRS %} + access-control: {{ _cidr }} allow +{% endfor %} directory: "{{ lookup('volume', 'svc-dns-unbound', 'data').target }}" username: unbound auto-trust-anchor-file: trusted-key.key @@ -18,6 +17,9 @@ server: hide-identity: yes hide-version: yes cache-min-ttl: 300 +{% if UNBOUND_ONION_FORWARD_ADDR | length > 0 %} + domain-insecure: "onion." +{% endif %} remote-control: control-enable: yes @@ -30,3 +32,9 @@ forward-zone: forward-addr: {{ resolver }} {% endfor %} {% endif %} +{% if UNBOUND_ONION_FORWARD_ADDR | length > 0 %} + +forward-zone: + name: "onion." + forward-addr: {{ UNBOUND_ONION_FORWARD_ADDR }} +{% endif %} diff --git a/roles/svc-dns-unbound/vars/main.yml b/roles/svc-dns-unbound/vars/main.yml index 918bac40d0..75207698c0 100644 --- a/roles/svc-dns-unbound/vars/main.yml +++ b/roles/svc-dns-unbound/vars/main.yml @@ -4,7 +4,6 @@ entity_name: "{{ application_id | get_entity_name }}" UNBOUND_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.name') }}" UNBOUND_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, UNBOUND_CONTAINER) }}" -UNBOUND_PORT: "{{ lookup('config', application_id, 'services.unbound.ports.local.unbound') }}" UNBOUND_NETWORK_NAME: "{{ entity_name }}" UNBOUND_RESOLVER_IP: "{{ lookup('config', application_id, 'networks.local.dns_resolver') }}" @@ -12,3 +11,7 @@ UNBOUND_VOLUMES_DIR: "{{ lookup('container', application_id, 'directories.volume UNBOUND_CONF_FILE: "{{ [ UNBOUND_VOLUMES_DIR, 'unbound.conf' ] | path_join }}" UNBOUND_FORWARD_DNS: "{{ (DOCKER_IN_CONTAINER | bool) or ('microsoft' in lookup('file', '/proc/version') | lower) }}" + +UNBOUND_ONION_FORWARD_ADDR: >- + {{ (lookup('subnet_gateway') ~ '@' ~ lookup('config', 'svc-net-tor', 'services.tor.ports.local.dns')) + if ('svc-net-tor' in group_names and DEPLOYMENT_MODE == 'compose') else '' }} diff --git a/roles/svc-net-firewall/README.md b/roles/svc-net-firewall/README.md new file mode 100644 index 0000000000..9556984acb --- /dev/null +++ b/roles/svc-net-firewall/README.md @@ -0,0 +1,92 @@ +# Firewall ruleset + +## Description + +[nftables](https://www.netfilter.org/projects/nftables/) is the packet filtering framework of the Linux kernel and the successor to `iptables`. Its rules live in memory: a reboot drops them unless something loads them again. + +## Overview + +This role gives every other role one place to put packet filter rules. A role that needs them writes `templates/nftables.conf.j2` declaring its own nftables table and includes this role; the fragment is rendered to `/etc/nftables.d/.conf`, checked, loaded, and read back, so a deploy fails rather than quietly leaving a gap. Deployed on its own, the role installs nftables, the ruleset that loads every fragment, and the `nftables.service` that replays them at boot. + +One table per role is what makes the rules composable. A fragment replaces its own table and touches no other, so two roles on one host neither overwrite nor merge into each other, and a broken fragment fails alone instead of freezing everyone's rules. + +Replacing beats adding. `nft -f` on an existing table merges, so a rule dropped from the declaration would stay in the kernel and the ruleset could only ever grow. Each fragment therefore creates, deletes and redeclares its table in one transaction, which is also why the table is never observed empty: unlike a flush followed by rules, there is no window in which the boundary is gone. + +## Cosmos + +The diagram places Firewall ruleset in the Infinito.Nexus cosmos: the components it deploys (capabilities), the central services it consumes (dependencies), and its outward reach (federation and bridged external networks). + +```mermaid +flowchart LR + subgraph role [svc-net-firewall ๐Ÿ’ป] + svc_firewall["firewall"] + end +``` + +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (๐Ÿ’ป host, ๐Ÿณ compose, ๐Ÿ swarm); โŒ marks a service that is explicitly turned off, and โš™๏ธ an Ansible role dependency declared in `meta/main.yml`. + +## Features + +- **Owned per role:** Each consumer declares one table under its own name, so rules are added and retired with the role that needs them. +- **Atomic:** A fragment is applied in a single `nft -f` transaction, so the table is never observed half built. +- **Persistent:** `nftables.service` loads every fragment at boot, so rules outlive a reboot without a unit of this project's own. The ruleset it reads is a distribution decision, so the path follows `os_family`: RedHat reads `/etc/sysconfig/nftables.conf`, the others `/etc/nftables.conf`. +- **Independent of docker:** Docker owns its own tables and never touches these, so no rule has to be inserted into a chain another component controls. The unit is only enabled, never started or restarted: on Debian its `ExecStop` flushes the entire ruleset, docker's tables included, and the fragments are loaded explicitly anyway. +- **Verified:** `nft -c` rejects a fragment before it is written, and the loaded table is read back and refused when it carries no chain. A table that exists is not a rule that runs, so the policy itself is proven by the role that owns it. + +## Use Cases + +- Bounding a service port that carries no access policy of its own, where the packet filter is the only boundary available. +- Redirecting or translating traffic a role owns, scoped to an address range nothing else claims. + +A fragment can only ever be stricter than the host already is. In nftables an `accept` terminates its own base chain and nothing more: the packet still traverses every other chain at that hook, and a `drop` in any of them wins. A rule that has to overrule a policy someone else set, such as the `DROP` docker installs on forwarded packets, does not belong in a fragment at all; it belongs in the chain that carries that policy. + +## Quick Setup + +### Development + +Clone, set up the workstation, and deploy Firewall ruleset onto the local stack: + +```bash +git clone https://github.com/infinito-nexus/core.git +cd core +make onboard +make compose-deploy mode=reinstall apps=svc-net-firewall full_cycle=false +``` + +### Production + +Install Firewall ruleset directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): + +```bash +git clone https://github.com/infinito-nexus/core.git +cd core +bash scripts/install/package.sh +make install +source scripts/meta/env/load.sh + +APP=svc-net-firewall +DOMAIN= +TLS_MODE=self_signed +SSH_PUBLIC_KEY="" +INVENTORY=inventories/production +infinito administration inventory provision "$INVENTORY" \ + --inventory-file "$INVENTORY/devices.yml" \ + --host localhost \ + --include "$APP" \ + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" +infinito administration deploy dedicated "$INVENTORY/devices.yml" \ + --password-file "$INVENTORY/.password" \ + --diff -vv +``` + +## Further Resources + +- [nftables Wiki](https://wiki.nftables.org/) +- [nft(8) manual page](https://www.netfilter.org/projects/nftables/manpage.html) +- [Moving from iptables to nftables](https://wiki.nftables.org/wiki-nftables/index.php/Moving_from_iptables_to_nftables) + +## Credits + +Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. +Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). +Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/svc-net-firewall/meta/info.yml b/roles/svc-net-firewall/meta/info.yml new file mode 100644 index 0000000000..ca99331c28 --- /dev/null +++ b/roles/svc-net-firewall/meta/info.yml @@ -0,0 +1,5 @@ +--- +logo: + class: fa-solid fa-shield-halved +homepage: https://www.netfilter.org/projects/nftables/ +video: https://www.youtube.com/watch?v=EGKhIljDPCw diff --git a/roles/svc-net-firewall/meta/main.yml b/roles/svc-net-firewall/meta/main.yml new file mode 100644 index 0000000000..93ca3d7d86 --- /dev/null +++ b/roles/svc-net-firewall/meta/main.yml @@ -0,0 +1,27 @@ +--- +galaxy_info: + author: Kevin Veen-Birkenbach + description: nftables packet filter whose rules each role owns as its own table, replaced atomically and reloaded at boot + company: | + Kevin Veen-Birkenbach + https://www.veen.world + license: Infinito.Nexus Community License (Non-Commercial) + min_ansible_version: "2.9" + galaxy_tags: + - firewall + - nftables + - netfilter + - security + issue_tracker_url: https://s.infinito.nexus/issues + platforms: + - name: ArchLinux + versions: [all] + - name: Debian + versions: [all] + - name: EL + versions: [all] + - name: Fedora + versions: [all] + - name: Ubuntu + versions: [all] +dependencies: [] diff --git a/roles/svc-net-firewall/meta/packages.yml b/roles/svc-net-firewall/meta/packages.yml new file mode 100644 index 0000000000..06709ff242 --- /dev/null +++ b/roles/svc-net-firewall/meta/packages.yml @@ -0,0 +1,8 @@ +--- +nftables: + Archlinux: + - nftables + Debian: + - nftables + RedHat: + - nftables diff --git a/roles/svc-net-firewall/meta/services.yml b/roles/svc-net-firewall/meta/services.yml new file mode 100644 index 0000000000..15c0b390d5 --- /dev/null +++ b/roles/svc-net-firewall/meta/services.yml @@ -0,0 +1,16 @@ +--- +# nocheck: playwright-service-flag host packet filter, no container and no web surface +firewall: + modes: + host: + enabled: true + compose: + enabled: false + swarm: + enabled: false + lifecycle: beta + min_storage: "50MB" + cpus: "0.1" + mem_reservation: "32m" + mem_limit: "64m" + pids_limit: 64 diff --git a/roles/svc-net-firewall/tasks/01_host.yml b/roles/svc-net-firewall/tasks/01_host.yml new file mode 100644 index 0000000000..9474747829 --- /dev/null +++ b/roles/svc-net-firewall/tasks/01_host.yml @@ -0,0 +1,32 @@ +--- +- name: "๐Ÿ“ฆ Firewall | Install nftables" + become: true + package_install: + id: nftables + +- name: "๐Ÿ“ Firewall | Ensure the fragment directory exists" + become: true + ansible.builtin.file: + path: "{{ FIREWALL_FRAGMENT_DIR }}" + state: directory + owner: root + group: root + mode: "0750" + +- name: "๐Ÿงฑ Firewall | Install the ruleset every fragment is loaded from" + become: true + ansible.builtin.template: # nocheck: stack-host-template per-host packet filter: every host carrying rules needs the ruleset, not only the stack host + src: main.nft.j2 + dest: "{{ FIREWALL_MAIN_CONF }}" + owner: root + group: root + mode: "0640" + backup: true + +- name: "๐Ÿš€ Firewall | Arm the ruleset for boot without touching the live one" + become: true + ansible.builtin.systemd_service: + name: "{{ FIREWALL_SERVICE }}" + enabled: true + +- include_tasks: utils/once/flag.yml diff --git a/roles/svc-net-firewall/tasks/02_fragment.yml b/roles/svc-net-firewall/tasks/02_fragment.yml new file mode 100644 index 0000000000..5ed9c5900e --- /dev/null +++ b/roles/svc-net-firewall/tasks/02_fragment.yml @@ -0,0 +1,43 @@ +--- +- name: "๐Ÿ” Firewall | Resolve the fragment of '{{ FIREWALL_FRAGMENT_ROLE }}'" + ansible.builtin.set_fact: + firewall_fragment_src: >- + {{ lookup('first_found', + { + 'files': [ FIREWALL_FRAGMENT_SRC ], + 'paths': [ lookup('path_absolute', 'roles', FIREWALL_FRAGMENT_ROLE) ] + } + ) }} + firewall_loaded_table: "{{ FIREWALL_TABLE }}" + +- name: "๐Ÿงฑ Firewall | Stage the ruleset of '{{ FIREWALL_FRAGMENT_ROLE }}'" + become: true + ansible.builtin.template: # nocheck: stack-host-template per-host packet filter: every host carrying the rules needs the fragment, not only the stack host + src: "{{ firewall_fragment_src }}" + dest: "{{ FIREWALL_FRAGMENT_FILE }}" + owner: root + group: root + mode: "0640" + validate: "nft -c -f %s" + +- name: "๐Ÿš€ Firewall | Load the ruleset of '{{ FIREWALL_FRAGMENT_ROLE }}'" + become: true + ansible.builtin.command: + argv: [nft, -f, "{{ FIREWALL_FRAGMENT_FILE }}"] + changed_when: true + +- name: "๐Ÿ” Firewall | Read back the table of '{{ FIREWALL_FRAGMENT_ROLE }}'" + become: true + ansible.builtin.command: + argv: [nft, list, table, inet, "{{ FIREWALL_TABLE }}"] + register: firewall_loaded_ruleset + changed_when: false + +- name: "โœ… Firewall | Refuse a table that carries no chain" + ansible.builtin.assert: + that: + - "'chain ' in firewall_loaded_ruleset.stdout" + fail_msg: >- + {{ FIREWALL_FRAGMENT_ROLE }} loaded {{ FIREWALL_TABLE }} but the table + holds no chain, so nothing it declares is hooked into the packet path. + A table that exists is not a rule that runs. diff --git a/roles/svc-net-firewall/tasks/main.yml b/roles/svc-net-firewall/tasks/main.yml new file mode 100644 index 0000000000..435c971317 --- /dev/null +++ b/roles/svc-net-firewall/tasks/main.yml @@ -0,0 +1,8 @@ +--- +- name: "๐Ÿงฑ Firewall | Prepare the host ruleset" + ansible.builtin.include_tasks: 01_host.yml + when: run_once_svc_net_firewall is not defined + +- name: "๐Ÿงฑ Firewall | Apply the ruleset of '{{ FIREWALL_FRAGMENT_ROLE }}'" + ansible.builtin.include_tasks: 02_fragment.yml + when: FIREWALL_FRAGMENT_ROLE | length > 0 diff --git a/roles/svc-net-firewall/templates/main.nft.j2 b/roles/svc-net-firewall/templates/main.nft.j2 new file mode 100644 index 0000000000..ef967514c8 --- /dev/null +++ b/roles/svc-net-firewall/templates/main.nft.j2 @@ -0,0 +1,3 @@ +#!/usr/sbin/nft -f +# Managed by {{ SOFTWARE_NAME }} (roles/svc-net-firewall). Do not edit by hand. +include "{{ FIREWALL_FRAGMENT_DIR }}/*.conf" diff --git a/roles/svc-net-firewall/vars/main.yml b/roles/svc-net-firewall/vars/main.yml new file mode 100644 index 0000000000..0303fda6d6 --- /dev/null +++ b/roles/svc-net-firewall/vars/main.yml @@ -0,0 +1,15 @@ +--- +application_id: svc-net-firewall + +FIREWALL_MAIN_CONF_BY_OS_FAMILY: + Archlinux: "/etc/nftables.conf" + Debian: "/etc/nftables.conf" + RedHat: "/etc/sysconfig/nftables.conf" + +FIREWALL_MAIN_CONF: "{{ FIREWALL_MAIN_CONF_BY_OS_FAMILY[ansible_facts['os_family']] }}" +FIREWALL_FRAGMENT_DIR: "/etc/nftables.d" +FIREWALL_SERVICE: "nftables.service" +FIREWALL_FRAGMENT_SRC: "templates/nftables.conf.j2" +FIREWALL_FRAGMENT_ROLE: "{{ ansible_parent_role_names | default([]) | first | default('') }}" +FIREWALL_FRAGMENT_FILE: "{{ [ FIREWALL_FRAGMENT_DIR, FIREWALL_FRAGMENT_ROLE ~ '.conf' ] | path_join }}" +FIREWALL_TABLE: "infinito_{{ FIREWALL_FRAGMENT_ROLE | regex_replace('[^a-zA-Z0-9]', '_') }}" diff --git a/roles/svc-net-tor-smtp/README.md b/roles/svc-net-tor-smtp/README.md index 858d0fc768..897823a569 100644 --- a/roles/svc-net-tor-smtp/README.md +++ b/roles/svc-net-tor-smtp/README.md @@ -77,19 +77,20 @@ Run the published image to provision the inventory and deploy Tor SMTP Gateway ( ```bash APP=svc-net-tor-smtp HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-net-tor-smtp/meta/info.yml b/roles/svc-net-tor-smtp/meta/info.yml new file mode 100644 index 0000000000..b5baf5213c --- /dev/null +++ b/roles/svc-net-tor-smtp/meta/info.yml @@ -0,0 +1,4 @@ +--- +# nocheck: info-media in-repo gateway, no upstream project to link or demo +logo: + class: fa-solid fa-user-secret diff --git a/roles/svc-net-tor/README.md b/roles/svc-net-tor/README.md index c36a7d7859..1091186daf 100644 --- a/roles/svc-net-tor/README.md +++ b/roles/svc-net-tor/README.md @@ -85,19 +85,21 @@ Run the published image to provision the inventory and deploy Tor Onion Service ```bash APP=svc-net-tor HOST= +DOMAIN= +DNS= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e DNS="$DNS" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"networks\": {\"internet\": {\"dns\": \"$DNS\"}}, \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' @@ -111,6 +113,6 @@ docker run --rm -it \ ## Credits -Implemented by **Kevin Veen-Birkenbach**. +Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/svc-net-tor/files/Dockerfile b/roles/svc-net-tor/files/Dockerfile index 6caf369d0f..0bd8d0ea7f 100644 --- a/roles/svc-net-tor/files/Dockerfile +++ b/roles/svc-net-tor/files/Dockerfile @@ -20,8 +20,13 @@ RUN rm -rf /var/lib/apt/lists/* \ fi \ && rm -rf /var/lib/apt/lists/* -COPY entrypoint.sh /usr/local/bin/tor-entrypoint.sh -RUN chmod 0755 /usr/local/bin/tor-entrypoint.sh +ARG TOR_ENTRYPOINT_PATH +ARG TOR_HEALTHCHECK_PATH -ENTRYPOINT ["/usr/local/bin/tor-entrypoint.sh"] +COPY entrypoint.sh ${TOR_ENTRYPOINT_PATH} +COPY healthcheck.sh ${TOR_HEALTHCHECK_PATH} +RUN chmod 0755 ${TOR_ENTRYPOINT_PATH} ${TOR_HEALTHCHECK_PATH} \ + && ln -s ${TOR_ENTRYPOINT_PATH} /tor-entrypoint + +ENTRYPOINT ["/tor-entrypoint"] CMD ["-f", "/etc/tor/torrc"] diff --git a/roles/svc-net-tor/files/dnsmasq-restart.conf b/roles/svc-net-tor/files/dnsmasq-restart.conf new file mode 100644 index 0000000000..a43a4f39ba --- /dev/null +++ b/roles/svc-net-tor/files/dnsmasq-restart.conf @@ -0,0 +1,3 @@ +[Service] +Restart=on-failure +RestartSec=5 diff --git a/roles/svc-net-tor/files/shell/healthcheck.sh b/roles/svc-net-tor/files/shell/healthcheck.sh new file mode 100644 index 0000000000..695d642d15 --- /dev/null +++ b/roles/svc-net-tor/files/shell/healthcheck.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# Gate the container on Tor being able to carry traffic. +# +# Param: $1 - Tor DataDirectory, the directory holding control_auth_cookie +set -u + +data_dir=${1:?usage: tor-healthcheck.sh } +cookie="${data_dir}/control_auth_cookie" + +[ -r "${cookie}" ] || exit 1 +hex=$(od -An -v -tx1 <"${cookie}" | tr -d ' \n') +[ -n "${hex}" ] || exit 1 + +exec 3<>/dev/tcp/127.0.0.1/9051 || exit 1 +printf 'AUTHENTICATE %s\r\nGETINFO status/circuit-established\r\nQUIT\r\n' "${hex}" >&3 +grep -q 'circuit-established=1' <&3 diff --git a/roles/svc-net-tor/files/test/onion_ports.py b/roles/svc-net-tor/files/test/onion_ports.py new file mode 100755 index 0000000000..a372b65d47 --- /dev/null +++ b/roles/svc-net-tor/files/test/onion_ports.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +"""Assert every TCP port the node onion forwards actually accepts a connection. + +The ports are the ones roles ask for by name under ports.onion, plus any +service opting in with exposed: true, which is what lookup('tor_ports') returns +and what torrc turns into HiddenServicePort lines. The unconditional SSH forward +is deliberately not probed: it targets a host service this role does not deploy, +so its absence says nothing about the forwards under test. + +The HTTP probe in test.sh only sees the reverse proxy's vhosts, so mail and +every other named port went unchecked, and from outside a forwarded port that +reaches nothing looks exactly like a port that never reached torrc at all. + +A port passes when the SOCKS proxy reports CONNECT success, which it does only +after Tor has established the stream to the target behind the onion. One pass +probes every port and only the failures are retried, so a green run costs one +connect per port and a red one cannot multiply the retry budget by the number of +healthy ports. + +Standard library only: this runs wherever the CLI test runs, not in a container +carrying a test toolchain. + +Env (rendered into test.env from templates/test.env.j2): + TOR_SOCKS SOCKS proxy, host:port + ONION_HOST the node onion host + ONION_PORTS space-separated forwarded ports; empty means there is + nothing to check + ONION_PORT_TIMEOUT seconds per connect attempt. 60 for the same reason the + domain probe uses it: Tor's SocksTimeout default is 120s + and abandoning earlier is destructive, because the next + attempt opens a fresh SOCKS connection and throws away + the descriptor fetches and rendezvous retries the last + one was still working through + ONION_PORT_RETRIES passes over the failing ports. Below the domain probe's + RETRIES because this phase multiplies by the port count, + and meta/tests.yml caps the whole CLI test + SLEEP_SECONDS wait between passes +""" + +from __future__ import annotations + +import os +import socket +import sys +import time + +_GREETING_NO_AUTH = b"\x05\x01\x00" +_GREETING_OK = b"\x05\x00" +_CONNECT_TO_DOMAIN = b"\x05\x01\x00\x03" +_REPLY_SUCCESS = 0x00 + + +class ProbeError(RuntimeError): + """A port did not answer, with the reason a reader needs to act on it.""" + + +def _required(name: str, hint: str) -> str: + value = os.environ.get(name, "").strip() + if not value: + raise SystemExit(f"pass {name} as env ({hint})") + return value + + +def connect_through_socks(proxy: str, host: str, port: int, timeout: float) -> None: + """Open a SOCKS5 CONNECT to ``host:port`` and raise when it is refused.""" + proxy_host, _, proxy_port = proxy.rpartition(":") + try: + sock = socket.create_connection((proxy_host, int(proxy_port)), timeout=timeout) + except OSError as error: + raise ProbeError(f"socks proxy unreachable: {error}") from None + + with sock: + sock.settimeout(timeout) + try: + sock.sendall(_GREETING_NO_AUTH) + if sock.recv(2) != _GREETING_OK: + raise ProbeError("socks proxy refused the no-auth method") + target = host.encode() + sock.sendall( + _CONNECT_TO_DOMAIN + + bytes([len(target)]) + + target + + port.to_bytes(2, "big") + ) + reply = sock.recv(4) + except OSError as error: + raise ProbeError(f"socks handshake failed: {error}") from None + if len(reply) < 2: + raise ProbeError("socks proxy closed the connection") + if reply[1] != _REPLY_SUCCESS: + raise ProbeError(f"socks CONNECT failed with reply 0x{reply[1]:02x}") + + +def probe( + *, + proxy: str, + host: str, + ports: list[int], + timeout: float, + retries: int, + sleep_seconds: float, + sleeper=time.sleep, +) -> dict[int, str]: + """Return the ports still failing after the retries, with their reason.""" + pending = list(ports) + reasons: dict[int, str] = {} + for attempt in range(1, retries + 1): + still: list[int] = [] + for port in pending: + try: + connect_through_socks(proxy, host, port, timeout) + except ProbeError as error: + reasons[port] = str(error) + still.append(port) + else: + reasons.pop(port, None) + print(f"[OK] {host}:{port} connect") + pending = still + if not pending or attempt == retries: + break + print( + f"[INFO] pass {attempt + 1}/{retries} retries " + f"{len(pending)} port(s) in {sleep_seconds}s" + ) + sleeper(sleep_seconds) + return {port: reasons[port] for port in pending} + + +def main() -> int: + proxy = _required("TOR_SOCKS", "host:port of the node SOCKS proxy") + host = _required("ONION_HOST", "svc-net-tor services.tor.node") + retries = int(_required("ONION_PORT_RETRIES", "passes over the failing ports")) + sleep_seconds = float(_required("SLEEP_SECONDS", "wait between passes")) + timeout = float( + _required("ONION_PORT_TIMEOUT", "seconds per connect, flavor-dependent") + ) + ports = [int(entry) for entry in os.environ.get("ONION_PORTS", "").split()] + + if not ports: + print("[INFO] no onion-forwarded ports declared; nothing to probe") + return 0 + + print( + f"[INFO] probing {len(ports)} onion-forwarded port(s) on {host} " + f"via socks5://{proxy} ({timeout}s per connect)" + ) + failures = probe( + proxy=proxy, + host=host, + ports=ports, + timeout=timeout, + retries=retries, + sleep_seconds=sleep_seconds, + ) + for port, reason in failures.items(): + print(f"[FAIL] {host}:{port} {reason}") + print(f"[INFO] {len(ports)} port(s) probed, {len(failures)} failed") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/roles/svc-net-tor/files/test/test.sh b/roles/svc-net-tor/files/test/test.sh index 67bb92e08e..68677e034b 100755 --- a/roles/svc-net-tor/files/test/test.sh +++ b/roles/svc-net-tor/files/test/test.sh @@ -99,4 +99,7 @@ for domain in "${domains[@]}"; do done echo "[INFO] ${#domains[@]} probed, ${failed} failed" + +"$(dirname "${BASH_SOURCE[0]}")/onion_ports.py" || failed=$((failed + 1)) + [[ "${failed}" -eq 0 ]] diff --git a/roles/svc-net-tor/lookup_plugins/tor_egress_clients.py b/roles/svc-net-tor/lookup_plugins/tor_egress_clients.py new file mode 100644 index 0000000000..bd0a9647ae --- /dev/null +++ b/roles/svc-net-tor/lookup_plugins/tor_egress_clients.py @@ -0,0 +1,101 @@ +"""Lookup `tor_egress_clients`: the address space Tor's egress ports admit. + +Deliberately not the three RFC1918 blocks: 10.0.0.0/8 would hand the operator's +whole LAN a resolver and a transparent proxy that carry no access policy of +their own. What is admitted is what this deployment declares for itself, in rule +order: loopback, docker's address pools, the swarm gateway bridge, the role +subnet pool, and the subnets of the roles that sit outside it. + +Usage: + + {{ lookup('tor_egress_clients') }} +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase +from ansible.template import trust_as_template + +_REQUIRED = ( + "NETWORK_LOOPBACK_CIDR", + "NETWORK_DOCKER_ADDRESS_POOLS", + "NETWORK_SWARM_GWBRIDGE_POOL", + "NETWORK_ROLE_SUBNET_POOL", + "NETWORK_ROLE_SUBNET_EXCEPTION_ROLES", +) + + +def _rendered(templar: Any, value: Any) -> str: + """A variable's value with its Jinja resolved. + + Group vars reach a lookup as whatever the file holds, and several of these + are references rather than literals. Passing one through unrendered would + put the template text itself into a source address, where it cannot match + and therefore silently narrows the admitted set. + """ + text = "" if value is None else str(value).strip() + if "{{" not in text or templar is None: + return text + rendered = str(templar.template(trust_as_template(text))).strip() + if "{{" in rendered: + raise AnsibleError(f"tor_egress_clients: {text!r} did not render to an address") + return rendered + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Any]: + if terms: + raise AnsibleError("lookup('tor_egress_clients') expects no terms.") + variables = variables or getattr(self._templar, "available_variables", {}) or {} + missing = [name for name in _REQUIRED if variables.get(name) is None] + if missing: + raise AnsibleError( + "tor_egress_clients: missing variable(s) " + f"{', '.join(missing)}; an incomplete list would install a guard " + "that admits more than it was asked to" + ) + + templar = getattr(self, "_templar", None) + excepted = lookup_loader.get( + "role_subnets", + loader=getattr(self, "_loader", None), + templar=templar, + ).run( + [variables["NETWORK_ROLE_SUBNET_EXCEPTION_ROLES"]], + variables=variables, + )[0] + + pools = variables["NETWORK_DOCKER_ADDRESS_POOLS"] + if not isinstance(pools, (list, tuple)): + raise AnsibleError( + "tor_egress_clients: NETWORK_DOCKER_ADDRESS_POOLS must be a list" + ) + bases = [] + for pool in pools: + base = pool.get("base") if isinstance(pool, dict) else None + if not base: + raise AnsibleError( + f"tor_egress_clients: address pool {pool!r} declares no base" + ) + bases.append(_rendered(templar, base)) + + ordered = [ + _rendered(templar, variables["NETWORK_LOOPBACK_CIDR"]), + *bases, + _rendered(templar, variables["NETWORK_SWARM_GWBRIDGE_POOL"]), + _rendered(templar, variables["NETWORK_ROLE_SUBNET_POOL"]), + *[_rendered(templar, subnet) for subnet in excepted], + ] + seen: dict[str, None] = {} + for cidr in ordered: + seen.setdefault(cidr, None) + return [list(seen)] diff --git a/roles/svc-net-tor/lookup_plugins/tor_extra_ports.py b/roles/svc-net-tor/lookup_plugins/tor_extra_ports.py new file mode 100644 index 0000000000..f5f90a95d1 --- /dev/null +++ b/roles/svc-net-tor/lookup_plugins/tor_extra_ports.py @@ -0,0 +1,100 @@ +"""Lookup `tor_extra_ports`: every port the node onion forwards. + +Two of them are flags rather than derivations, because no inventory carries +them. ``lookup('tor_ports')`` walks ``group_names`` and collects what the roles +listed there declare under ``ports.onion``; SSH belongs to no role at all, and +HTTP belongs to ``svc-prx-openresty``, which a node acquires through +``sys-stk-front-proxy`` and which therefore appears in no dependency list an +inventory holds. A node provisioned with ``--include svc-net-tor`` alone +published an onion forwarding SSH and nothing else, leaving every app it serves +unreachable over that onion. + +Forwarding HTTP is what this role exists for, so it is declared, and a node that +must not answer HTTP over its onion turns ``TOR_ONION_HTTP_ENABLED`` off. + +The derived ports still come from ``tor_ports``; a port named twice collapses, +since ``torrc.j2`` writes one ``HiddenServicePort`` line per entry. + +Usage: + + {{ lookup('tor_extra_ports') }} +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.module_utils.parsing.convert_bool import boolean +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase +from ansible.template import trust_as_template + +FLAGGED_PORTS: tuple[tuple[str, int], ...] = ( + ("TOR_ONION_SSH_ENABLED", 22), + ("TOR_ONION_HTTP_ENABLED", 80), +) + + +def _flag(templar: Any, name: str, value: Any) -> bool: + """A declared flag as a boolean, with its Jinja resolved first. + + Args: + templar: the lookup's templar, or None when it has none. + name: the variable the flag came from, for the error message. + value: whatever the variable holds; group vars reach a lookup + unrendered, so a reference arrives as its own template text. + """ + if isinstance(value, str) and "{{" in value and templar is not None: + value = templar.template(trust_as_template(value)) + try: + return boolean(value) + except TypeError as exc: + raise AnsibleError( + f"lookup('tor_extra_ports'): {name} is not a boolean: {value!r}" + ) from exc + + +def _entry(port: int) -> dict[str, Any]: + """One forward, in the shape ``torrc.j2`` consumes. + + Args: + port: the port the onion answers on; the backend host is substituted by + the template, so the target carries the port alone. + """ + return {"onion_port": port, "target": f"127.0.0.1:{port}"} + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[Any]: + if terms: + raise AnsibleError("lookup('tor_extra_ports') expects no terms.") + + variables = variables or getattr(self._templar, "available_variables", {}) or {} + + entries: list[dict[str, Any]] = [] + for name, port in FLAGGED_PORTS: + if name not in variables: + raise AnsibleError(f"lookup('tor_extra_ports'): {name} is not defined") + if _flag(getattr(self, "_templar", None), name, variables[name]): + entries.append(_entry(port)) + + derived = lookup_loader.get( + "tor_ports", + loader=getattr(self, "_loader", None), + templar=getattr(self, "_templar", None), + ).run([], variables=variables, **kwargs)[0] + + seen = {entry["onion_port"] for entry in entries} + for entry in derived: + if entry["onion_port"] in seen: + continue + seen.add(entry["onion_port"]) + entries.append(entry) + + return [entries] diff --git a/roles/svc-net-tor/meta/info.yml b/roles/svc-net-tor/meta/info.yml new file mode 100644 index 0000000000..8fa684ea40 --- /dev/null +++ b/roles/svc-net-tor/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media no official demo video diff --git a/roles/svc-net-tor/meta/main.yml b/roles/svc-net-tor/meta/main.yml index e369152694..48e9925caf 100644 --- a/roles/svc-net-tor/meta/main.yml +++ b/roles/svc-net-tor/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Tor daemon publishing the node as a v3 onion service diff --git a/roles/svc-net-tor/meta/services.yml b/roles/svc-net-tor/meta/services.yml index 5a3842df7b..0f872d03b9 100644 --- a/roles/svc-net-tor/meta/services.yml +++ b/roles/svc-net-tor/meta/services.yml @@ -20,20 +20,35 @@ tor: # nocheck: category-modes exclusive: true primary: true image: debian - version: trixie-slim + version: 13.6-slim custom: true name: tor node: "" use_entry_guards: true flavor: public + forwards: + ssh: true + http: true + egress: + enabled: true + timeout_multipliers: + chutney: 2 + public: 5 ports: local: socks: 9050 trans: 9040 dns: 9053 + onion: + # nocheck: onion-flag a SOCKS port anyone can reach is an open proxy, and SocksPolicy cannot refuse it because the forward arrives from the node's own address + socks: false + # nocheck: onion-flag the transparent port takes its destination from the caller's routing, which an onion client does not share + trans: false + # nocheck: onion-flag publishing the resolver would answer recursive queries for anyone holding the onion address + dns: false min_storage: 100MB cpus: "0.25" mem_reservation: 128m mem_limit: 256m pids_limit: 128 - lifecycle: alpha + lifecycle: beta diff --git a/roles/svc-net-tor/tasks/00_core.yml b/roles/svc-net-tor/tasks/00_core.yml index 7eaf5a9079..b7cbc59ccb 100644 --- a/roles/svc-net-tor/tasks/00_core.yml +++ b/roles/svc-net-tor/tasks/00_core.yml @@ -47,6 +47,14 @@ become: true register: _tor_hs_keys +- name: "๐Ÿ“Š Re-gather the docker0 fact so torrc and dnsmasq bind the live bridge" + ansible.builtin.setup: + gather_subset: + - "!all" + - network + filter: + - ansible_docker0 + - name: "๐Ÿ“ Render torrc" ansible.builtin.template: # nocheck: stack-host-template (per-host torrc under DIR_VAR_LIB; tor is a node-local host-network sidecar) src: torrc.j2 @@ -74,6 +82,14 @@ become: true register: _tor_entrypoint +- name: "๐Ÿฉบ Stage the Tor container healthcheck into the build context" + stack_host_copy: + src: "{{ role_path }}/files/shell/healthcheck.sh" + dest: "{{ TOR_HEALTHCHECK_HOST }}" + mode: "0755" + become: true + register: _tor_healthcheck + - name: "๐Ÿงฉ For '{{ application_id }}': Load sys-svc-compose" include_role: name: sys-svc-compose @@ -90,7 +106,7 @@ chdir: "{{ lookup('container', application_id, 'directories.instance') }}" executable: /bin/bash become: true - when: DEPLOYMENT_MODE == 'compose' and ((_tor_hs_keys is changed) or (_tor_torrc is changed) or (_tor_entrypoint is changed)) + when: DEPLOYMENT_MODE == 'compose' and (TOR_RESTART_REQUIRED | bool) - name: "๐Ÿ”„ Force Tor service redeploy to apply hidden-service key / torrc changes" ansible.builtin.command: >- @@ -102,14 +118,16 @@ when: - DEPLOYMENT_MODE == 'swarm' - IS_STACK_HOST | bool - - (_tor_hs_keys is changed) or (_tor_torrc is changed) or (_tor_entrypoint is changed) + - TOR_RESTART_REQUIRED | bool - name: "๐Ÿง… Wire the host-level transparent .onion egress router" include_tasks: file: router.yml apply: become: true - when: TOR_EGRESS_ROUTER_ENABLED | bool + when: + - TOR_EGRESS_ROUTER_ENABLED | bool + - DEPLOYMENT_MODE == 'compose' or (IS_STACK_HOST | bool) - name: "๐Ÿง… Verify the node onion is reachable" ansible.builtin.include_tasks: onion_reach.yml diff --git a/roles/svc-net-tor/tasks/router.yml b/roles/svc-net-tor/tasks/router.yml index 2071db3671..08f4119e8e 100644 --- a/roles/svc-net-tor/tasks/router.yml +++ b/roles/svc-net-tor/tasks/router.yml @@ -46,29 +46,64 @@ vars: TOR_DNS_UPSTREAMS: "{{ [ networks.internet.dns ] }}" register: _tor_dnsmasq_conf +- name: "๐Ÿ” Egress router | Retry dnsmasq until docker0 exists after a boot" + when: TOR_DNSMASQ_OWNS_LISTENER | bool + block: + - name: "๐Ÿ“ Egress router | Ensure the dnsmasq unit drop-in directory exists" + ansible.builtin.file: + path: "{{ TOR_DNSMASQ_DROPIN | dirname }}" + state: directory + owner: root + group: root + mode: "0755" + - name: "๐Ÿ“ Egress router | Restart dnsmasq on failure" + ansible.builtin.copy: + src: dnsmasq-restart.conf + dest: "{{ TOR_DNSMASQ_DROPIN }}" + owner: root + group: root + mode: "0644" + register: _tor_dnsmasq_dropin - name: "๐Ÿš€ Egress router | Enable + (re)start dnsmasq" ansible.builtin.systemd: name: dnsmasq enabled: true + daemon_reload: "{{ TOR_DNSMASQ_OWNS_LISTENER | bool and _tor_dnsmasq_dropin is changed }}" state: "{{ 'restarted' if (_tor_dnsmasq_conf is changed or _tor_dnsmasq_confdir is changed) else 'started' }}" -- name: "๐Ÿ”€ Egress router | Point the host resolver at dnsmasq (127.0.0.1)" - ansible.builtin.copy: - dest: /etc/resolv.conf - content: | - nameserver 127.0.0.1 - nameserver {{ networks.internet.dns }} - options ndots:1 - owner: root - group: root - mode: "0644" - unsafe_writes: true +- name: "๐Ÿ”€ Egress router | Route host name resolution through dnsmasq" when: TOR_DNSMASQ_OWNS_LISTENER | bool -- name: "๐Ÿ”€ Egress router | Redirect .onion virtual-IP TCP to Tor TransPort" - ansible.builtin.iptables: - table: nat - chain: OUTPUT - protocol: tcp - destination: "{{ TOR_EGRESS_VIRTUAL_NET_IPV4 }}" - jump: REDIRECT - to_ports: "{{ TOR_TRANS_PORT | string }}" - comment: "Tor egress router: .onion virtual range -> TransPort" + block: + - name: "๐Ÿ”€ Egress router | Point the host resolver at dnsmasq (127.0.0.1)" + ansible.builtin.template: # nocheck: stack-host-template (per-host resolver config in /etc/resolv.conf) + src: resolv.conf.j2 + dest: /etc/resolv.conf + owner: root + group: root + mode: "0644" + unsafe_writes: true + - name: "๐Ÿ”€ Egress router | Let a name systemd-resolved refuses reach dnsmasq" + become: true + ansible.builtin.lineinfile: + path: /etc/nsswitch.conf + regexp: "^(hosts:.*\\bresolve)\\s*\\[!UNAVAIL=return\\](.*)$" + line: "\\1 [SUCCESS=return NOTFOUND=continue TRYAGAIN=return]\\2" + backrefs: true +- name: "๐Ÿ”€ Egress router | Route .onion traffic and bound the ports that carry no policy" + ansible.builtin.include_role: + name: svc-net-firewall + +- name: "๐Ÿ›ก๏ธ Egress guard | Read back the chain that bounds the ports" + become: true + ansible.builtin.command: + argv: [nft, list, chain, inet, "{{ firewall_loaded_table }}", guard] + register: tor_egress_guard_chain + changed_when: false + +- name: "๐Ÿ›ก๏ธ Egress guard | Refuse a guard that drops nothing" + ansible.builtin.assert: + that: + - "'drop' in tor_egress_guard_chain.stdout" + fail_msg: >- + The guard chain in {{ firewall_loaded_table }} carries no drop, so + TransPort and DNSPort are reachable from every source. These two ports + have no access policy of their own; this chain is the only boundary. diff --git a/roles/svc-net-tor/templates/compose.yml.j2 b/roles/svc-net-tor/templates/compose.yml.j2 index 7d464c93ec..81c0ffdaec 100644 --- a/roles/svc-net-tor/templates/compose.yml.j2 +++ b/roles/svc-net-tor/templates/compose.yml.j2 @@ -4,28 +4,33 @@ {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {{ lookup('template', 'roles/sys-svc-container/templates/build.yml.j2') | indent(4) }} args: - TOR_BASE_IMAGE: "{{ TOR_IMAGE }}" - TOR_BASE_VERSION: "{{ TOR_VERSION }}" - TOR_FLAVOR: "{{ TOR_FLAVOR }}" + TOR_BASE_IMAGE: "{{ TOR_IMAGE }}" + TOR_BASE_VERSION: "{{ TOR_VERSION }}" + TOR_FLAVOR: "{{ TOR_FLAVOR }}" + TOR_ENTRYPOINT_PATH: "{{ TOR_ENTRYPOINT_PATH }}" + TOR_HEALTHCHECK_PATH: "{{ TOR_HEALTHCHECK_PATH }}" {{ lookup('compose_only', 'container_name', TOR_CONTAINER) }} {{ lookup('container_image', application_id, 'tor') }} {% if DEPLOYMENT_MODE == 'swarm' %} - ports: - - target: {{ TOR_SOCKS_PORT }} - published: {{ TOR_SOCKS_PORT }} - protocol: tcp - mode: host + {{ lookup('container_ports', + {'service': 'tor', 'protocol': 'socks', 'mode': 'host', + 'container': 'same'}, + {'service': 'tor', 'protocol': 'dns', 'mode': 'host', + 'container': 'same', 'transport': ['udp', 'tcp']}, + {'service': 'tor', 'protocol': 'trans', 'mode': 'host', + 'container': 'same', 'transport': 'tcp'}) | indent(4) }} {{ lookup('container_networks') | indent(4) }} {% else %} network_mode: "host" {% endif %} {{ lookup('container_volumes', service_name) | indent(4) }} healthcheck: - test: ["CMD", "tor", "--verify-config", "-f", "{{ lookup('volume', 'svc-net-tor', 'tor_torrc').target }}"] - interval: 60s - timeout: 10s + test: ["CMD", "{{ TOR_HEALTHCHECK_PATH }}", "{{ lookup('volume', 'svc-net-tor', 'tor_data').target }}"] + interval: 2m + timeout: 5s retries: 3 - start_period: {{ '150s' if TOR_FLAVOR == 'chutney' else '10s' }} + start_period: 10m + start_interval: 5s {{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-net-tor/templates/dnsmasq-tor-onion.conf.j2 b/roles/svc-net-tor/templates/dnsmasq-tor-onion.conf.j2 index cf9d9032ef..b073b59cee 100644 --- a/roles/svc-net-tor/templates/dnsmasq-tor-onion.conf.j2 +++ b/roles/svc-net-tor/templates/dnsmasq-tor-onion.conf.j2 @@ -3,7 +3,7 @@ listen-address=127.0.0.1 {% if TOR_CONTAINER_DNS_HOST | length > 0 %} listen-address={{ TOR_CONTAINER_DNS_HOST }} {% endif %} -bind-dynamic +bind-interfaces no-resolv {% endif %} no-hosts diff --git a/roles/svc-net-tor/templates/nftables.conf.j2 b/roles/svc-net-tor/templates/nftables.conf.j2 new file mode 100644 index 0000000000..eab3aa5bb0 --- /dev/null +++ b/roles/svc-net-tor/templates/nftables.conf.j2 @@ -0,0 +1,52 @@ +{# Loaded by roles/svc-net-firewall into {{ FIREWALL_TABLE }}. #} +table inet {{ FIREWALL_TABLE }} +delete table inet {{ FIREWALL_TABLE }} +table inet {{ FIREWALL_TABLE }} { + set containers { + type ipv4_addr + flags interval + elements = { {{ TOR_EGRESS_CLIENT_CIDRS | join(', ') }} } + } + + set internal { + type ipv4_addr + flags interval + elements = { {{ NETWORK_INTERNAL_CIDRS | join(', ') }} } + } + +{% set _tcp_guarded = TOR_EGRESS_GUARDED_PORTS | selectattr('protocol', 'equalto', 'tcp') | map(attribute='port') | unique | list %} +{% set _udp_guarded = TOR_EGRESS_GUARDED_PORTS | selectattr('protocol', 'equalto', 'udp') | map(attribute='port') | unique | list %} + chain guard { +{% for entry in TOR_EGRESS_GUARDED_PORTS %} + ip saddr != @{{ entry.admitted }} {{ entry.protocol }} dport {{ entry.port }} drop +{% endfor %} +{% if _tcp_guarded | length > 0 %} + fib saddr . iif oif missing tcp dport { {{ _tcp_guarded | join(', ') }} } drop +{% endif %} +{% if _udp_guarded | length > 0 %} + fib saddr . iif oif missing udp dport { {{ _udp_guarded | join(', ') }} } drop +{% endif %} + } + + chain input { + type filter hook input priority -10; policy accept; + jump guard + } + + chain forward { + type filter hook forward priority -10; policy accept; + jump guard + } + + chain output { + type nat hook output priority -150; policy accept; + ip daddr {{ TOR_EGRESS_VIRTUAL_NET_IPV4 }} meta l4proto tcp redirect to :{{ TOR_TRANS_PORT }} + } +{% if TOR_CONTAINER_DNS_HOST | length > 0 %} + + chain prerouting { + type nat hook prerouting priority -150; policy accept; + ip daddr {{ TOR_EGRESS_VIRTUAL_NET_IPV4 }} meta l4proto tcp dnat ip to {{ TOR_CONTAINER_DNS_HOST }}:{{ TOR_TRANS_PORT }} + } +{% endif %} +} diff --git a/roles/svc-net-tor/templates/resolv.conf.j2 b/roles/svc-net-tor/templates/resolv.conf.j2 new file mode 100644 index 0000000000..84820c5adb --- /dev/null +++ b/roles/svc-net-tor/templates/resolv.conf.j2 @@ -0,0 +1,3 @@ +nameserver 127.0.0.1 +nameserver {{ networks.internet.dns }} +options ndots:1 diff --git a/roles/svc-net-tor/templates/test.env.j2 b/roles/svc-net-tor/templates/test.env.j2 index 10028ca3a0..0b58f45bb0 100644 --- a/roles/svc-net-tor/templates/test.env.j2 +++ b/roles/svc-net-tor/templates/test.env.j2 @@ -1,4 +1,8 @@ NGINX_SERVERS_DIR={{ lookup('nginx', 'directories.configuration.servers') }} +ONION_HOST={{ lookup('config', 'svc-net-tor', 'services.tor.node') }} +ONION_PORTS={{ lookup('tor_ports') | map(attribute='onion_port') | unique | sort | join(' ') }} +ONION_PORT_RETRIES=2 +ONION_PORT_TIMEOUT=60 RETRIES=5 SLEEP_SECONDS=10 TOR_DNSMASQ_CONF={{ TOR_DNSMASQ_CONF }} diff --git a/roles/svc-net-tor/templates/torrc.j2 b/roles/svc-net-tor/templates/torrc.j2 index b2167aeea9..20e1dddbbb 100644 --- a/roles/svc-net-tor/templates/torrc.j2 +++ b/roles/svc-net-tor/templates/torrc.j2 @@ -1,13 +1,12 @@ -# Managed by Infinito.Nexus (roles/svc-net-tor) โ€” do not edit by hand. +# Managed by {{ SOFTWARE_NAME }} (roles/svc-net-tor) โ€” do not edit by hand. RunAsDaemon 0 Log notice stdout DataDirectory {{ lookup('volume', 'svc-net-tor', 'tor_data').target }} SocksPort {{ lookup('tor_socks', '0.0.0.0') }} -SocksPolicy accept 127.0.0.0/8 -SocksPolicy accept 10.0.0.0/8 -SocksPolicy accept 172.16.0.0/12 -SocksPolicy accept 192.168.0.0/16 +{% for _cidr in NETWORK_INTERNAL_CIDRS %} +SocksPolicy accept {{ _cidr }} +{% endfor %} SocksPolicy reject * ControlPort 127.0.0.1:9051 CookieAuthentication 1 @@ -24,12 +23,20 @@ UseEntryGuards 0 AutomapHostsOnResolve 1 AutomapHostsSuffixes .onion VirtualAddrNetworkIPv4 {{ TOR_EGRESS_VIRTUAL_NET_IPV4 }} +{% if DEPLOYMENT_MODE == 'swarm' %} +TransPort 0.0.0.0:{{ TOR_TRANS_PORT }} +DNSPort 0.0.0.0:{{ TOR_DNS_PORT }} +{% else %} TransPort 127.0.0.1:{{ TOR_TRANS_PORT }} DNSPort 127.0.0.1:{{ TOR_DNS_PORT }} +{% if TOR_CONTAINER_DNS_HOST | length > 0 %} +TransPort {{ TOR_CONTAINER_DNS_HOST }}:{{ TOR_TRANS_PORT }} +DNSPort {{ TOR_CONTAINER_DNS_HOST }}:{{ TOR_DNS_PORT }} +{% endif %} +{% endif %} {% endif %} HiddenServiceDir /var/lib/tor/infinito/node/ HiddenServiceVersion 3 -HiddenServicePort 80 {{ TOR_HS_BACKEND_HOST }}:80 {% for _p in TOR_ONION_EXTRA_PORTS %} HiddenServicePort {{ _p.onion_port }} {{ TOR_HS_BACKEND_HOST }}:{{ _p.target.rsplit(':', 1) | last }} {% endfor %} diff --git a/roles/svc-net-tor/vars/main.yml b/roles/svc-net-tor/vars/main.yml index 5a5fb0402b..f8245d1817 100644 --- a/roles/svc-net-tor/vars/main.yml +++ b/roles/svc-net-tor/vars/main.yml @@ -6,14 +6,44 @@ TOR_IMAGE: "{{ lookup('config', application_id, 'services.tor.image') }}" TOR_VERSION: "{{ lookup('config', application_id, 'services.tor.version') }}" TOR_CONTAINER: "{{ lookup('config', application_id, 'services.tor.name') }}" -TOR_SOCKS_PORT: "{{ lookup('config', application_id, 'services.tor.ports.local.socks') }}" TOR_NODE_ONION: "{{ lookup('config', application_id, 'services.tor.node', '') }}" TOR_USE_ENTRY_GUARDS: "{{ lookup('config', application_id, 'services.tor.use_entry_guards') | bool }}" TOR_FLAVOR: "{{ lookup('config', application_id, 'services.tor.flavor') }}" +TOR_ONION_SSH_ENABLED: "{{ lookup('config', application_id, 'services.tor.forwards.ssh') | bool }}" +TOR_ONION_HTTP_ENABLED: "{{ lookup('config', application_id, 'services.tor.forwards.http') | bool }}" +TOR_ONION_EXTRA_PORTS: "{{ lookup('tor_extra_ports') }}" +TOR_EGRESS_ROUTER_ENABLED: "{{ lookup('config', application_id, 'services.tor.egress.enabled') | bool }}" +TOR_EGRESS_VIRTUAL_NET_IPV4: "{{ NETWORK_TOR_VIRTUAL_CIDR }}" TOR_TRANS_PORT: "{{ lookup('config', application_id, 'services.tor.ports.local.trans') }}" TOR_DNS_PORT: "{{ lookup('config', application_id, 'services.tor.ports.local.dns') }}" +TOR_SOCKS_PORT: "{{ lookup('config', application_id, 'services.tor.ports.local.socks') }}" +TOR_DNSMASQ_PORT: "{{ NETWORK_DNS_PORT }}" TOR_DNSMASQ_CONF: "/etc/dnsmasq.d/tor-onion.conf" + +TOR_EGRESS_GUARDED_PORTS: + - port: "{{ TOR_TRANS_PORT }}" + protocol: tcp + admitted: containers + - port: "{{ TOR_DNS_PORT }}" + protocol: tcp + admitted: containers + - port: "{{ TOR_DNS_PORT }}" + protocol: udp + admitted: containers + - port: "{{ TOR_SOCKS_PORT }}" + protocol: tcp + admitted: internal + - port: "{{ TOR_DNSMASQ_PORT }}" + protocol: tcp + admitted: internal + - port: "{{ TOR_DNSMASQ_PORT }}" + protocol: udp + admitted: internal +TOR_EGRESS_CLIENT_CIDRS: "{{ lookup('tor_egress_clients') }}" +TOR_DNSMASQ_DROPIN: "/etc/systemd/system/dnsmasq.service.d/infinito-restart.conf" +# nocheck: host-local-fact meta/services.yml pins this role to the manager, so the fact describes the node the hidden service forwards on TOR_CONTAINER_DNS_HOST: "{{ ansible_facts['docker0']['ipv4']['address'] | default('', true) }}" +# nocheck: host-local-fact meta/services.yml pins this role to the manager, so the fact describes the node the hidden service forwards on TOR_HS_BACKEND_HOST: "{{ ansible_facts['default_ipv4']['address'] if DEPLOYMENT_MODE == 'swarm' else (TOR_CONTAINER_DNS_HOST | ternary(TOR_CONTAINER_DNS_HOST, '127.0.0.1')) }}" @@ -26,3 +56,11 @@ TOR_HS_SRC_DIR: "{{ lookup('path_absolute', '.onion-identity', 'hs') }}" TOR_INSTANCE_DIR: "{{ lookup('container', application_id, 'directories.instance') }}" TOR_ENTRYPOINT_HOST: "{{ [ TOR_INSTANCE_DIR, 'entrypoint.sh' ] | path_join }}" +TOR_HEALTHCHECK_HOST: "{{ [ TOR_INSTANCE_DIR, 'healthcheck.sh' ] | path_join }}" +TOR_ENTRYPOINT_PATH: "/usr/local/bin/tor-entrypoint.sh" +TOR_HEALTHCHECK_PATH: "/usr/local/bin/tor-healthcheck.sh" +TOR_RESTART_REQUIRED: >- + {{ (_tor_hs_keys is changed) + or (_tor_torrc is changed) + or (_tor_entrypoint is changed) + or (_tor_healthcheck is changed) }} diff --git a/roles/svc-net-wireguard-core/README.md b/roles/svc-net-wireguard-core/README.md index a49b90c6f9..bdab48cdbd 100644 --- a/roles/svc-net-wireguard-core/README.md +++ b/roles/svc-net-wireguard-core/README.md @@ -56,7 +56,7 @@ make compose-deploy mode=reinstall apps=svc-net-wireguard-core full_cycle=false ### Production -Install Wireguard directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Wireguard directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -66,6 +66,7 @@ make install source scripts/meta/env/load.sh APP=svc-net-wireguard-core +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -73,7 +74,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-net-wireguard-core/meta/info.yml b/roles/svc-net-wireguard-core/meta/info.yml index 20cb838815..4afe3f4e0b 100644 --- a/roles/svc-net-wireguard-core/meta/info.yml +++ b/roles/svc-net-wireguard-core/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://www.wireguard.com/ diff --git a/roles/svc-net-wireguard-core/meta/main.yml b/roles/svc-net-wireguard-core/meta/main.yml index 1e5f168adb..5c828d48c7 100644 --- a/roles/svc-net-wireguard-core/meta/main.yml +++ b/roles/svc-net-wireguard-core/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Host-level WireGuard VPN service with wg-quick config, package install, and IP-forwarding sysctl for secure tunnels diff --git a/roles/svc-net-wireguard-firewalled/README.md b/roles/svc-net-wireguard-firewalled/README.md index 4279ac4fd1..8b42479c3a 100644 --- a/roles/svc-net-wireguard-firewalled/README.md +++ b/roles/svc-net-wireguard-firewalled/README.md @@ -8,7 +8,7 @@ This role adapts iptables rules to enable proper connectivity for a WireGuard cl Optimized for environments with network address translation (NAT), this role: -- Executes shell commands to modify iptables rules. +- Installs its iptables rules through Ansible's `iptables` module, so a redeploy converges instead of appending a duplicate. - Allows traffic from the WireGuard client interface (e.g. `wg0-client`) and sets up NAT masquerading on the external interface (e.g. `eth0`). - Works as an extension to the native WireGuard client role. @@ -54,7 +54,7 @@ make compose-deploy mode=reinstall apps=svc-net-wireguard-firewalled full_cycle= ### Production -Install WireGuard Client behind NAT directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install WireGuard Client behind NAT directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -64,6 +64,7 @@ make install source scripts/meta/env/load.sh APP=svc-net-wireguard-firewalled +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -71,7 +72,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-net-wireguard-firewalled/meta/info.yml b/roles/svc-net-wireguard-firewalled/meta/info.yml new file mode 100644 index 0000000000..7de4d9f511 --- /dev/null +++ b/roles/svc-net-wireguard-firewalled/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written glue role that adapts iptables/NAT masquerading rules for a WireGuard client behind NAT; no consumer-facing upstream product website. diff --git a/roles/svc-net-wireguard-firewalled/meta/main.yml b/roles/svc-net-wireguard-firewalled/meta/main.yml index 1f3850fd8f..f1e0739ef5 100644 --- a/roles/svc-net-wireguard-firewalled/meta/main.yml +++ b/roles/svc-net-wireguard-firewalled/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written glue role that adapts iptables/NAT masquerading rules for a WireGuard client behind NAT; no consumer-facing upstream product website. galaxy_info: author: Kevin Veen-Birkenbach description: Networking helper for iptables forwarding and NAT masquerading of a WireGuard client running behind NAT or a firewall diff --git a/roles/svc-net-wireguard-firewalled/tasks/00_core.yml b/roles/svc-net-wireguard-firewalled/tasks/00_core.yml index 0c08a0b925..7360c4dc21 100644 --- a/roles/svc-net-wireguard-firewalled/tasks/00_core.yml +++ b/roles/svc-net-wireguard-firewalled/tasks/00_core.yml @@ -1,5 +1,19 @@ --- -- name: ๐Ÿ”ง adapt iptable rules - shell: iptables -A FORWARD -i wg0-client -j ACCEPT && iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE +- name: "๐Ÿงฑ Accept forwarded traffic from the wireguard client" + become: true + ansible.builtin.iptables: + chain: FORWARD + in_interface: "{{ WIREGUARD_CLIENT_INTERFACE }}" + jump: ACCEPT + state: present + +- name: "๐Ÿงฑ Masquerade the client behind the uplink address" + become: true + ansible.builtin.iptables: + table: nat + chain: POSTROUTING + out_interface: "{{ WIREGUARD_UPLINK_INTERFACE }}" + jump: MASQUERADE + state: present - include_tasks: utils/once/flag.yml diff --git a/roles/svc-net-wireguard-firewalled/vars/main.yml b/roles/svc-net-wireguard-firewalled/vars/main.yml index 79d2e17b23..2cd2850160 100644 --- a/roles/svc-net-wireguard-firewalled/vars/main.yml +++ b/roles/svc-net-wireguard-firewalled/vars/main.yml @@ -1,2 +1,5 @@ --- application_id: svc-net-wireguard-firewalled + +WIREGUARD_CLIENT_INTERFACE: wg0-client +WIREGUARD_UPLINK_INTERFACE: eth0 diff --git a/roles/svc-net-wireguard-plain/README.md b/roles/svc-net-wireguard-plain/README.md index 994536e79a..2930c644d7 100644 --- a/roles/svc-net-wireguard-plain/README.md +++ b/roles/svc-net-wireguard-plain/README.md @@ -59,7 +59,7 @@ make compose-deploy mode=reinstall apps=svc-net-wireguard-plain full_cycle=false ### Production -Install Wireguard Client directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Wireguard Client directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -69,6 +69,7 @@ make install source scripts/meta/env/load.sh APP=svc-net-wireguard-plain +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -76,7 +77,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-net-wireguard-plain/meta/info.yml b/roles/svc-net-wireguard-plain/meta/info.yml index 20cb838815..4afe3f4e0b 100644 --- a/roles/svc-net-wireguard-plain/meta/info.yml +++ b/roles/svc-net-wireguard-plain/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://www.wireguard.com/ diff --git a/roles/svc-net-wireguard-plain/meta/main.yml b/roles/svc-net-wireguard-plain/meta/main.yml index e1622b5b98..fef50f863d 100644 --- a/roles/svc-net-wireguard-plain/meta/main.yml +++ b/roles/svc-net-wireguard-plain/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Client-side WireGuard VPN role for stable connectivity with a systemd service and script that tune interface MTU diff --git a/roles/svc-net-wireguard-plain/templates/script.sh.j2 b/roles/svc-net-wireguard-plain/templates/script.sh.j2 index 2a0bf75c2d..5412c5143e 100644 --- a/roles/svc-net-wireguard-plain/templates/script.sh.j2 +++ b/roles/svc-net-wireguard-plain/templates/script.sh.j2 @@ -1,4 +1,5 @@ #!/bin/bash +{# nocheck: shell-template grandfathered: one line per internet interface, replaceable by argv #} {% for internet_interface in internet_interfaces %} ip li set mtu 1400 dev {{internet_interface}} {% endfor %} diff --git a/roles/svc-opt-keyboard-color/README.md b/roles/svc-opt-keyboard-color/README.md index 583c7b8d73..33c150fbd5 100644 --- a/roles/svc-opt-keyboard-color/README.md +++ b/roles/svc-opt-keyboard-color/README.md @@ -41,7 +41,7 @@ make compose-deploy mode=reinstall apps=svc-opt-keyboard-color full_cycle=false ### Production -Install MSI Keyboard Driver directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install MSI Keyboard Driver directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -51,6 +51,7 @@ make install source scripts/meta/env/load.sh APP=svc-opt-keyboard-color +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -58,7 +59,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-opt-keyboard-color/meta/info.yml b/roles/svc-opt-keyboard-color/meta/info.yml index 7ca50b89b8..3194ee1778 100644 --- a/roles/svc-opt-keyboard-color/meta/info.yml +++ b/roles/svc-opt-keyboard-color/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://github.com/Askannz/msi-perkeyrgb diff --git a/roles/svc-opt-keyboard-color/meta/main.yml b/roles/svc-opt-keyboard-color/meta/main.yml index 9485c22984..601b6d7792 100644 --- a/roles/svc-opt-keyboard-color/meta/main.yml +++ b/roles/svc-opt-keyboard-color/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: role_name: keyboard-color author: Kevin Veen-Birkenbach diff --git a/roles/svc-opt-ssd-hdd/README.md b/roles/svc-opt-ssd-hdd/README.md index 17e0612a9b..ba274c06dc 100644 --- a/roles/svc-opt-ssd-hdd/README.md +++ b/roles/svc-opt-ssd-hdd/README.md @@ -52,7 +52,7 @@ make compose-deploy mode=reinstall apps=svc-opt-ssd-hdd full_cycle=false ### Production -Install Storage Optimizer directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Storage Optimizer directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -62,6 +62,7 @@ make install source scripts/meta/env/load.sh APP=svc-opt-ssd-hdd +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -69,7 +70,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-opt-ssd-hdd/meta/info.yml b/roles/svc-opt-ssd-hdd/meta/info.yml new file mode 100644 index 0000000000..01dbc650b9 --- /dev/null +++ b/roles/svc-opt-ssd-hdd/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written infrastructure role that migrates Docker volumes between SSD/HDD and creates symlinks; no upstream product website. diff --git a/roles/svc-opt-ssd-hdd/meta/main.yml b/roles/svc-opt-ssd-hdd/meta/main.yml index 35c4cbc810..d23fce82e7 100644 --- a/roles/svc-opt-ssd-hdd/meta/main.yml +++ b/roles/svc-opt-ssd-hdd/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written infrastructure role that migrates Docker volumes between SSD/HDD and creates symlinks; no upstream product website. galaxy_info: author: Kevin Veen-Birkenbach description: Tiering role placing Docker volumes on SSD or HDD by workload type, with symlinks keeping paths consistent diff --git a/roles/svc-opt-swapfile/README.md b/roles/svc-opt-swapfile/README.md index eb3c79fd82..3c0e95b8a6 100644 --- a/roles/svc-opt-swapfile/README.md +++ b/roles/svc-opt-swapfile/README.md @@ -50,7 +50,7 @@ make compose-deploy mode=reinstall apps=svc-opt-swapfile full_cycle=false ### Production -Install Swapfile directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Swapfile directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -60,6 +60,7 @@ make install source scripts/meta/env/load.sh APP=svc-opt-swapfile +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -67,7 +68,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-opt-swapfile/meta/info.yml b/roles/svc-opt-swapfile/meta/info.yml new file mode 100644 index 0000000000..2cba64b5c3 --- /dev/null +++ b/roles/svc-opt-swapfile/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written OS-optimization glue role that clones and runs a swapfile-creation script; no consumer-facing upstream product. diff --git a/roles/svc-opt-swapfile/meta/main.yml b/roles/svc-opt-swapfile/meta/main.yml index dcc21300b2..78fbfb885f 100644 --- a/roles/svc-opt-swapfile/meta/main.yml +++ b/roles/svc-opt-swapfile/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written OS-optimization glue role that clones and runs a swapfile-creation script; no consumer-facing upstream product. galaxy_info: author: Kevin Veen-Birkenbach description: On-target automation for creating and activating swap space via a cloned swapfile script diff --git a/roles/svc-prx-openresty/README.md b/roles/svc-prx-openresty/README.md index cdb8666be5..f39236bb08 100644 --- a/roles/svc-prx-openresty/README.md +++ b/roles/svc-prx-openresty/README.md @@ -61,19 +61,20 @@ Run the published image to provision the inventory and deploy OpenResty to a man ```bash APP=svc-prx-openresty HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-prx-openresty/meta/info.yml b/roles/svc-prx-openresty/meta/info.yml index f232e70da0..1c403edc52 100644 --- a/roles/svc-prx-openresty/meta/info.yml +++ b/roles/svc-prx-openresty/meta/info.yml @@ -1,3 +1,3 @@ --- homepage: https://openresty.org/ -video: https://openresty.org/en/videos.html +video: https://www.youtube.com/watch?v=NR8U1qYHGqk diff --git a/roles/svc-prx-openresty/meta/services.yml b/roles/svc-prx-openresty/meta/services.yml index 9a88ba83d9..70f57222ff 100644 --- a/roles/svc-prx-openresty/meta/services.yml +++ b/roles/svc-prx-openresty/meta/services.yml @@ -11,6 +11,19 @@ openresty: enabled: true shared: true name: openresty + ports: + internal: + http: 80 + https: 443 + public: + http: 80 + https: 443 + onion: + http: true + # nocheck: onion-flag the hidden service is already the transport encryption, and the onion address has no certificate a TLS listener could present + https: false + healthcheck: + test: ["CMD", "openresty", "-t", "-q"] min_storage: 264MB backup: disabled: true @@ -18,7 +31,7 @@ openresty: mem_reservation: 1g mem_limit: 2g image: openresty/openresty - version: alpine + version: 1.31.1.1-alpine custom: true lifecycle: beta pids_limit: 256 @@ -30,6 +43,5 @@ tor: shared: true # nocheck: dynamic-flag # nocheck: dynamic-flag - proxy state is fully re-rendered by the deploy (configs, certs via binds), the backup consumer stays permanently off container_backup: - bond: 1 enabled: false shared: true diff --git a/roles/svc-prx-openresty/meta/variants.yml b/roles/svc-prx-openresty/meta/variants.yml index 1576e2511e..a5e59537b6 100644 --- a/roles/svc-prx-openresty/meta/variants.yml +++ b/roles/svc-prx-openresty/meta/variants.yml @@ -2,6 +2,3 @@ - services: tor: enabled: true -- services: - tor: - enabled: true diff --git a/roles/svc-prx-openresty/templates/compose.yml.j2 b/roles/svc-prx-openresty/templates/compose.yml.j2 index 579fcd075e..b3bbe4721a 100644 --- a/roles/svc-prx-openresty/templates/compose.yml.j2 +++ b/roles/svc-prx-openresty/templates/compose.yml.j2 @@ -14,15 +14,9 @@ {{ lookup('compose_only', 'container_name', OPENRESTY_CONTAINER) }} {{ lookup('container_image', application_id, 'openresty') }} {% if DEPLOYMENT_MODE == 'swarm' %} - ports: - - target: 80 - published: 80 - protocol: tcp - mode: host - - target: 443 - published: 443 - protocol: tcp - mode: host + {{ lookup('container_ports', + {'service': 'openresty', 'protocol': 'http', 'mode': 'host'}, + {'service': 'openresty', 'protocol': 'https', 'mode': 'host'}) | indent(4) }} {{ lookup('container_extra_hosts', extra_hosts=['host.docker.internal:host-gateway']) | indent(4) }} {{ lookup('container_networks') | indent(4) }} {% else %} @@ -30,11 +24,7 @@ {% endif %} {{ lookup('container_volumes', service_name) | indent(4) }} command: ["openresty", "-g", "daemon off;"] - healthcheck: - test: ["CMD", "openresty", "-t", "-q"] - interval: 30s - timeout: 5s - retries: 3 + {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/svc-registry-cache/README.md b/roles/svc-registry-cache/README.md index 42dcf68150..a34403230b 100644 --- a/roles/svc-registry-cache/README.md +++ b/roles/svc-registry-cache/README.md @@ -71,19 +71,20 @@ Run the published image to provision the inventory and deploy Docker Registry Ca ```bash APP=svc-registry-cache HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-registry-cache/meta/info.yml b/roles/svc-registry-cache/meta/info.yml new file mode 100644 index 0000000000..4be4c6cb49 --- /dev/null +++ b/roles/svc-registry-cache/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written swarm/infrastructure glue role deploying a registry:2 pull-through Docker Hub cache; no consumer-facing upstream product website. diff --git a/roles/svc-registry-cache/meta/main.yml b/roles/svc-registry-cache/meta/main.yml index 07b7bb552f..ec304c2e7b 100644 --- a/roles/svc-registry-cache/meta/main.yml +++ b/roles/svc-registry-cache/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written swarm/infrastructure glue role deploying a registry:2 pull-through Docker Hub cache; no consumer-facing upstream product website. galaxy_info: author: Kevin Veen-Birkenbach description: Cluster-local pull-through cache for shared Docker Hub base-image pulls, cutting duplicate transfers and rate limits diff --git a/roles/svc-registry-cache/meta/services.yml b/roles/svc-registry-cache/meta/services.yml index bba891a9e3..69a32710b8 100644 --- a/roles/svc-registry-cache/meta/services.yml +++ b/roles/svc-registry-cache/meta/services.yml @@ -34,11 +34,13 @@ cache: registry: 5001 internal: registry: 5000 + onion: + # nocheck: onion-flag the pull-through mirror exists to serve this node's own image pulls; publishing it would relay Docker Hub for strangers + registry: false proxy: remote_url: "https://registry-1.docker.io" # nocheck: url lifecycle: beta # nocheck: dynamic-flag - pull-through cache content is re-fetchable, the backup consumer stays permanently off container_backup: - bond: 1 enabled: false shared: true diff --git a/roles/svc-registry-docker/README.md b/roles/svc-registry-docker/README.md index 0dc06f232a..59b3c89898 100644 --- a/roles/svc-registry-docker/README.md +++ b/roles/svc-registry-docker/README.md @@ -68,19 +68,20 @@ Run the published image to provision the inventory and deploy Docker Registry to ```bash APP=svc-registry-docker HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-registry-docker/meta/info.yml b/roles/svc-registry-docker/meta/info.yml index 8cf0bcff40..d69fbc97de 100644 --- a/roles/svc-registry-docker/meta/info.yml +++ b/roles/svc-registry-docker/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://distribution.github.io/distribution/ diff --git a/roles/svc-registry-docker/meta/main.yml b/roles/svc-registry-docker/meta/main.yml index 46a29da371..1310e5b71a 100644 --- a/roles/svc-registry-docker/meta/main.yml +++ b/roles/svc-registry-docker/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Cluster-local container image registry for serving custom-built images to Docker Swarm worker nodes diff --git a/roles/svc-registry-docker/meta/services.yml b/roles/svc-registry-docker/meta/services.yml index 83afc01131..66774e620e 100644 --- a/roles/svc-registry-docker/meta/services.yml +++ b/roles/svc-registry-docker/meta/services.yml @@ -34,9 +34,11 @@ docker: registry: 5000 internal: registry: 5000 + onion: + # nocheck: onion-flag the registry accepts unauthenticated pushes from the node that builds into it, so its reach must stay the node + registry: false lifecycle: beta # nocheck: dynamic-flag - locally built images are rebuildable, the backup consumer stays permanently off container_backup: - bond: 1 enabled: false shared: true diff --git a/roles/svc-runner/README.md b/roles/svc-runner/README.md index fcf9c3dd32..35e5d8636d 100644 --- a/roles/svc-runner/README.md +++ b/roles/svc-runner/README.md @@ -58,19 +58,20 @@ Run the published image to provision the inventory and deploy Self-Hosted Runner ```bash APP=svc-runner HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/svc-runner/files/test/external.sh b/roles/svc-runner/files/test/external.sh index 28378ec774..6a36661122 100644 --- a/roles/svc-runner/files/test/external.sh +++ b/roles/svc-runner/files/test/external.sh @@ -33,7 +33,7 @@ else echo "OK: ${online_count} runner(s) online on GitHub (${RUNNER_GITHUB_OWNER}/${RUNNER_GITHUB_REPO})" fi -echo "Dispatching test-runner-smoke.yml against ref=${RUNNER_GIT_REF}..." +echo "Dispatching call-test-runner-smoke.yml against ref=${RUNNER_GIT_REF}..." dispatch_time=$(date -u +%Y-%m-%dT%H:%M:%SZ) dispatch_http=$(${CURL} -sf -o /dev/null -w "%{http_code}" \ diff --git a/roles/svc-runner/meta/info.yml b/roles/svc-runner/meta/info.yml index a7256ef90d..4f0a31d8ee 100644 --- a/roles/svc-runner/meta/info.yml +++ b/roles/svc-runner/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media Self-written CI-runner infrastructure role: provisions a host as a GitHub Actions self-hosted runner via ephemeral Docker containers (DooD). Glue/infra with no consumer-facing upstream product website. homepage: https://github.com/actions/runner diff --git a/roles/svc-runner/meta/main.yml b/roles/svc-runner/meta/main.yml index 7a71b9a92d..5e1539cc19 100644 --- a/roles/svc-runner/meta/main.yml +++ b/roles/svc-runner/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written CI-runner infrastructure role: provisions a host as a GitHub Actions self-hosted runner via ephemeral Docker containers (DooD). Glue/infra with no consumer-facing upstream product website. galaxy_info: author: Alejandro Roman Ibanez description: Self-hosted CI runner infrastructure for executing GitHub Actions workflow jobs in ephemeral Docker containers diff --git a/roles/svc-runner/meta/services.yml b/roles/svc-runner/meta/services.yml index c02f122847..025ae72661 100644 --- a/roles/svc-runner/meta/services.yml +++ b/roles/svc-runner/meta/services.yml @@ -30,8 +30,7 @@ buildkit: enabled: false shared: false image: moby/buildkit - # nocheck: docker-version - version: "buildx-stable-1" + version: "v0.33.0" # nocheck: dynamic-flag act-runner: enabled: false diff --git a/roles/svc-runner/tasks/00_core.yml b/roles/svc-runner/tasks/00_core.yml index 1ad508e511..e7abafefe8 100644 --- a/roles/svc-runner/tasks/00_core.yml +++ b/roles/svc-runner/tasks/00_core.yml @@ -5,6 +5,7 @@ ansible.builtin.include_role: name: sys-svc-container tasks_from: 00_core.yml + when: run_once_sys_svc_container is not defined - name: ๐Ÿ”ง Tune kernel inotify limits for parallel runner containers ansible.posix.sysctl: @@ -169,6 +170,7 @@ ansible.builtin.include_role: name: sys-svc-compose tasks_from: 00_core.yml + when: run_once_sys_svc_compose is not defined - name: ๐Ÿ“„ Render runner compose file template: # nocheck: stack-host-template (node-local runner: every node renders + deploys its own compose stack) diff --git a/roles/svc-runner/templates/runner_instance_env.j2 b/roles/svc-runner/templates/runner_instance_env.j2 index 19d4b00494..2b386a6656 100644 --- a/roles/svc-runner/templates/runner_instance_env.j2 +++ b/roles/svc-runner/templates/runner_instance_env.j2 @@ -7,6 +7,7 @@ INFINITO_IP4=172.30.{{ runner_instance }}.10 INFINITO_BIND_IP=172.30.{{ runner_instance }}.1 INFINITO_PUBLISH_PORTS=false INFINITO_CACHE_PACKAGE_FRONTEND_IP=172.30.{{ runner_instance }}.4 +INFINITO_CACHE_PACKAGE_IP=172.30.{{ runner_instance }}.5 INFINITO_CACHE_REGISTRY_IP=172.30.{{ runner_instance }}.6 DOMAIN={{ DOMAIN_PRIMARY }} DOMAIN_RE={{ DOMAIN_PRIMARY | replace('.', '\\.') }} diff --git a/roles/svc-storage-nfs-client/README.md b/roles/svc-storage-nfs-client/README.md index 3586720f91..6d026c8efa 100644 --- a/roles/svc-storage-nfs-client/README.md +++ b/roles/svc-storage-nfs-client/README.md @@ -59,7 +59,7 @@ make compose-deploy mode=reinstall apps=svc-storage-nfs-client full_cycle=false ### Production -Install NFS Client directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install NFS Client directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -69,6 +69,7 @@ make install source scripts/meta/env/load.sh APP=svc-storage-nfs-client +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -76,7 +77,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-storage-nfs-client/meta/info.yml b/roles/svc-storage-nfs-client/meta/info.yml new file mode 100644 index 0000000000..44bbaf932a --- /dev/null +++ b/roles/svc-storage-nfs-client/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written storage-infra glue role that installs distro NFS client packages and probe-mounts an export; NFS is a generic protocol, not a named third-party product with a vendor site. diff --git a/roles/svc-storage-nfs-client/meta/main.yml b/roles/svc-storage-nfs-client/meta/main.yml index 70b386c23d..2fd43c8532 100644 --- a/roles/svc-storage-nfs-client/meta/main.yml +++ b/roles/svc-storage-nfs-client/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written storage-infra glue role that installs distro NFS client packages and probe-mounts an export; NFS is a generic protocol, not a named third-party product with a vendor site. galaxy_info: author: Kevin Veen-Birkenbach description: Client-side NFS setup for mounting a remote server export on every swarm node, with a deploy-time reachability probe diff --git a/roles/svc-storage-nfs-server/README.md b/roles/svc-storage-nfs-server/README.md index f2924e9000..992bf21be0 100644 --- a/roles/svc-storage-nfs-server/README.md +++ b/roles/svc-storage-nfs-server/README.md @@ -9,12 +9,14 @@ mount it as if it were a local filesystem. ## Overview -This role installs the distro-appropriate NFS kernel server, exports -the export base from its own services.yml SPOT (`/srv/nfs`), and restricts access to -inventory members of the `svc-swarm-node` group. The export options -default to `rw,sync,no_subtree_check,root_squash,no_all_squash`. NFS -server HA, Kerberos integration, and client-side mounting are out of -scope; client mounts are handled by `svc-storage-nfs-client`. +This role installs an NFS server in one of two flavors, the distro kernel +server or userspace nfs-ganesha, selected per deployment. Both export the +swarm state path to the resolved addresses of the `svc-swarm-node` group and +to an additional CIDR allow-list; ganesha also exports the export base and +squashes root there. Export options come from `vars/main.yml` for the kernel +flavor and from the ganesha configuration template for ganesha. NFS server +HA, Kerberos integration, and client-side mounting are out of scope; client +mounts are handled by `svc-storage-nfs-client`. ## Cosmos @@ -65,7 +67,7 @@ make compose-deploy mode=reinstall apps=svc-storage-nfs-server full_cycle=false ### Production -Install NFS Server directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install NFS Server directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -75,6 +77,7 @@ make install source scripts/meta/env/load.sh APP=svc-storage-nfs-server +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -82,7 +85,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-storage-nfs-server/meta/info.yml b/roles/svc-storage-nfs-server/meta/info.yml new file mode 100644 index 0000000000..0bcf998f48 --- /dev/null +++ b/roles/svc-storage-nfs-server/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written storage infrastructure role that installs the distro NFS kernel server and manages /etc/exports ACLs for the swarm; NFS is a kernel protocol, not a consumer-facing upstream product. diff --git a/roles/svc-storage-nfs-server/meta/main.yml b/roles/svc-storage-nfs-server/meta/main.yml index 27c692ee54..beec289b43 100644 --- a/roles/svc-storage-nfs-server/meta/main.yml +++ b/roles/svc-storage-nfs-server/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written storage infrastructure role that installs the distro NFS kernel server and manages /etc/exports ACLs for the swarm; NFS is a kernel protocol, not a consumer-facing upstream product. galaxy_info: author: Kevin Veen-Birkenbach description: Kernel-level NFS server for exporting a shared directory tree with IP-restricted access for swarm-node hosts diff --git a/roles/svc-storage-nfs-server/templates/exports.j2 b/roles/svc-storage-nfs-server/templates/exports.j2 index 471a61869d..830dfceee0 100644 --- a/roles/svc-storage-nfs-server/templates/exports.j2 +++ b/roles/svc-storage-nfs-server/templates/exports.j2 @@ -1,4 +1,4 @@ -# Managed by Infinito.Nexus Ansible role svc-storage-nfs-server. +# Managed by {{ SOFTWARE_NAME }} Ansible role svc-storage-nfs-server. {% for ip in svc_storage_nfs_server_allowed_ips %} {{ STORAGE_NFS_STATE_PATH }} {{ ip }}({{ SVC_STORAGE_NFS_SERVER_STATE_EXPORT_OPTIONS }},fsid=0) {% endfor %} diff --git a/roles/svc-swarm-manager/README.md b/roles/svc-swarm-manager/README.md index 6d85784be6..5d73ca58d0 100644 --- a/roles/svc-swarm-manager/README.md +++ b/roles/svc-swarm-manager/README.md @@ -51,7 +51,7 @@ make compose-deploy mode=reinstall apps=svc-swarm-manager full_cycle=false ### Production -Install Docker Swarm Manager directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Docker Swarm Manager directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -61,6 +61,7 @@ make install source scripts/meta/env/load.sh APP=svc-swarm-manager +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -68,7 +69,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-swarm-manager/meta/info.yml b/roles/svc-swarm-manager/meta/info.yml new file mode 100644 index 0000000000..6e19a6855b --- /dev/null +++ b/roles/svc-swarm-manager/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written marker/tag role with no tasks; just flags a host as the Docker Swarm manager for the inventory validator. Not a third-party product. diff --git a/roles/svc-swarm-manager/meta/main.yml b/roles/svc-swarm-manager/meta/main.yml index 04a832d046..9c31274c86 100644 --- a/roles/svc-swarm-manager/meta/main.yml +++ b/roles/svc-swarm-manager/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written marker/tag role with no tasks; just flags a host as the Docker Swarm manager for the inventory validator. Not a third-party product. galaxy_info: author: Kevin Veen-Birkenbach description: Marker role tagging a host as the Docker Swarm manager node, with the init logic delegated to svc-swarm-node diff --git a/roles/svc-swarm-node/README.md b/roles/svc-swarm-node/README.md index 63afa17c3e..86923e7cec 100644 --- a/roles/svc-swarm-node/README.md +++ b/roles/svc-swarm-node/README.md @@ -65,7 +65,7 @@ make compose-deploy mode=reinstall apps=svc-swarm-node full_cycle=false ### Production -Install Docker Swarm directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Docker Swarm directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -75,6 +75,7 @@ make install source scripts/meta/env/load.sh APP=svc-swarm-node +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -82,7 +83,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/svc-swarm-node/meta/info.yml b/roles/svc-swarm-node/meta/info.yml new file mode 100644 index 0000000000..a8cc1883e6 --- /dev/null +++ b/roles/svc-swarm-node/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written infrastructure role that bootstraps/manages a Docker Swarm cluster via Ansible group membership; it configures Docker's built-in swarm orchestration mode rather than wrapping a consumer-facing upstream product. diff --git a/roles/svc-swarm-node/meta/main.yml b/roles/svc-swarm-node/meta/main.yml index 176afd15e5..18aa84715b 100644 --- a/roles/svc-swarm-node/meta/main.yml +++ b/roles/svc-swarm-node/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written infrastructure role that bootstraps/manages a Docker Swarm cluster via Ansible group membership; it configures Docker's built-in swarm orchestration mode rather than wrapping a consumer-facing upstream product. galaxy_info: author: Kevin Veen-Birkenbach description: Container orchestration cluster for scheduling services across pooled manager and worker nodes diff --git a/roles/svc-swarm-node/tasks/01_manager.yml b/roles/svc-swarm-node/tasks/01_manager.yml index 0657e6c4cb..8b8c2fb70e 100644 --- a/roles/svc-swarm-node/tasks/01_manager.yml +++ b/roles/svc-swarm-node/tasks/01_manager.yml @@ -31,6 +31,7 @@ changed_when: false - name: "๐Ÿ“ฃ Publish tokens + advertise addr as facts (cluster-wide)" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" ansible.builtin.set_fact: svc_swarm_worker_token: "{{ docker_swarm_worker_token.stdout }}" svc_swarm_manager_token: "{{ docker_swarm_manager_token.stdout }}" diff --git a/roles/svc-swarm-node/tasks/02_manager_join.yml b/roles/svc-swarm-node/tasks/02_manager_join.yml index 92e7b5d580..515f797297 100644 --- a/roles/svc-swarm-node/tasks/02_manager_join.yml +++ b/roles/svc-swarm-node/tasks/02_manager_join.yml @@ -6,6 +6,7 @@ failed_when: docker_swarm_local_state.rc != 0 - name: "๐Ÿ Join swarm cluster as manager (only when not already active)" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" ansible.builtin.command: >- container swarm join --token {{ svc_swarm_manager_token }} diff --git a/roles/svc-swarm-node/tasks/03_worker.yml b/roles/svc-swarm-node/tasks/03_worker.yml index 71621a2d6c..997df31374 100644 --- a/roles/svc-swarm-node/tasks/03_worker.yml +++ b/roles/svc-swarm-node/tasks/03_worker.yml @@ -6,6 +6,7 @@ failed_when: docker_swarm_local_state.rc != 0 - name: "๐Ÿ Join swarm cluster as worker (only when not already active)" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" ansible.builtin.command: >- container swarm join --token {{ svc_swarm_worker_token }} diff --git a/roles/svc-virt-kata/README.md b/roles/svc-virt-kata/README.md new file mode 100644 index 0000000000..c42005e8ba --- /dev/null +++ b/roles/svc-virt-kata/README.md @@ -0,0 +1,82 @@ +# Kata & gVisor + +## Description + +[Kata Containers](https://katacontainers.io/) is an OCI container runtime that starts each container inside a lightweight virtual machine with its own kernel instead of sharing the host kernel. [gVisor](https://gvisor.dev/) is a second isolating runtime, shipped as the single `runsc` binary, that intercepts container syscalls in a userspace kernel and runs without hardware virtualization. + +## Overview + +This role provisions the isolating runtime layer of a container host. It installs the pinned gVisor binary, then re-runs the daemon configuration of the container role so the freshly installed runtime is registered and the daemon is restarted onto it. In swarm mode it additionally labels the node as sandbox-isolating, which is the placement constraint that keeps sandboxed workloads off nodes that still default to the shared kernel. + +## Cosmos + +The diagram places Kata & gVisor in the Infinito.Nexus cosmos: the components it deploys (capabilities), the central services it consumes (dependencies), and its outward reach (federation and bridged external networks). + +```mermaid +flowchart LR + subgraph role [svc-virt-kata ๐Ÿ’ป] + svc_kata["kata"] + end + subgraph dependents [Dependents] + dpt_web_app_hermes["web-app-hermes ๐Ÿณ๐Ÿ"] + dpt_web_app_openclaw["web-app-openclaw ๐Ÿณ๐Ÿ"] + end + svc_kata -- "1:1" --> dpt_web_app_hermes + svc_kata -- "1:1" --> dpt_web_app_openclaw +``` + +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (๐Ÿ’ป host, ๐Ÿณ compose, ๐Ÿ swarm); โŒ marks a service that is explicitly turned off, and โš™๏ธ an Ansible role dependency declared in `meta/main.yml`. + +## Features + +- **gVisor runtime:** The pinned `runsc` release is fetched to `/usr/local/bin/runsc` and verified against its published SHA-512 checksum. The Kata shim is taken from the host as it is; the role does not install it. +- **Runtime probing:** The container role checks every host for `/dev/kvm`, for the Kata shim binary and for docker-in-docker, and publishes the resulting choice between `kata` and `runsc` as `SANDBOX_RUNTIME`. +- **Daemon registration:** Only runtimes whose binary is present are written to the daemon configuration, on a bare host and inside docker-in-docker alike. A daemon pointed at an absent runtime path refuses to start, so this role installs first and re-renders the configuration afterwards. +- **Swarm default runtime:** `docker stack deploy` drops the per-service `runtime:` key, so a swarm worker carries the sandbox as its daemon-wide `default-runtime` instead. The stack host keeps the shared kernel for the platform's own services. +- **Node labelling:** In swarm mode the node is labelled `kata-capable=true`, and sandboxed services are constrained to that label. A deploy without a single such node is refused rather than left pending. +- **Runtime pinning:** In compose mode Hermes Agent and OpenClaw pin `SANDBOX_RUNTIME` on their service directly. + +## Quick Setup + +### Development + +Clone, set up the workstation, and deploy Kata & gVisor onto the local stack: + +```bash +git clone https://github.com/infinito-nexus/core.git +cd core +make onboard +make compose-deploy mode=reinstall apps=svc-virt-kata full_cycle=false +``` + +### Production + +Install Kata & gVisor directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): + +```bash +git clone https://github.com/infinito-nexus/core.git +cd core +bash scripts/install/package.sh +make install +source scripts/meta/env/load.sh + +APP=svc-virt-kata +DOMAIN= +TLS_MODE=self_signed +SSH_PUBLIC_KEY="" +INVENTORY=inventories/production +infinito administration inventory provision "$INVENTORY" \ + --inventory-file "$INVENTORY/devices.yml" \ + --host localhost \ + --include "$APP" \ + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" +infinito administration deploy dedicated "$INVENTORY/devices.yml" \ + --password-file "$INVENTORY/.password" \ + --diff -vv +``` + +## Credits + +Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. +Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). +Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/svc-virt-kata/meta/info.yml b/roles/svc-virt-kata/meta/info.yml new file mode 100644 index 0000000000..141346fc0a --- /dev/null +++ b/roles/svc-virt-kata/meta/info.yml @@ -0,0 +1,5 @@ +--- +# nocheck: info-media Self-written host-provisioning role that installs the gVisor runtime and registers it together with an already-present Kata shim in the container daemon; these are kernel-isolation runtimes, not consumer-facing upstream products. +logo: + class: fa-solid fa-shield-halved +homepage: https://katacontainers.io/ diff --git a/roles/svc-virt-kata/meta/main.yml b/roles/svc-virt-kata/meta/main.yml new file mode 100644 index 0000000000..3c6ce1e0e8 --- /dev/null +++ b/roles/svc-virt-kata/meta/main.yml @@ -0,0 +1,34 @@ +--- +galaxy_info: + author: Kevin Veen-Birkenbach + description: Kernel-isolating container runtimes that sandbox untrusted workloads in a microVM or a userspace kernel + license: Infinito.Nexus Community License (Non-Commercial) + company: | + Kevin Veen-Birkenbach + https://www.veen.world + galaxy_tags: + - kata + - firecracker + - gvisor + - microvm + - isolation + - sandbox + issue_tracker_url: https://s.infinito.nexus/issues + min_ansible_version: "2.9" + platforms: + - name: ArchLinux + versions: + - all + - name: Debian + versions: + - all + - name: EL + versions: + - all + - name: Fedora + versions: + - all + - name: Ubuntu + versions: + - all +dependencies: [] diff --git a/roles/svc-virt-kata/meta/services.yml b/roles/svc-virt-kata/meta/services.yml new file mode 100644 index 0000000000..1b81d60cea --- /dev/null +++ b/roles/svc-virt-kata/meta/services.yml @@ -0,0 +1,18 @@ +--- +kata: + modes: + host: + enabled: true + compose: + enabled: false + swarm: + enabled: false + bond: 1 + enabled: true + shared: true + min_storage: "500MB" + cpus: "0.2" + mem_reservation: "64m" + mem_limit: "256m" + pids_limit: 256 + lifecycle: beta diff --git a/roles/svc-virt-kata/tasks/00_core.yml b/roles/svc-virt-kata/tasks/00_core.yml new file mode 100644 index 0000000000..c5cb50c587 --- /dev/null +++ b/roles/svc-virt-kata/tasks/00_core.yml @@ -0,0 +1,91 @@ +--- +- include_tasks: utils/once/flag.yml + +- name: "๐Ÿ›‘ Refuse an unnamed sandbox tier" + ansible.builtin.assert: + that: + - groups['svc-virt-kata'] is defined + fail_msg: >- + Swarm drops the per-service runtime key, so a sandboxed workload can only + run where the node itself defaults to the sandbox runtime. Name those + nodes: declare an svc-virt-kata group in the inventory. Without it this + role runs on every host, every worker becomes a sandbox node, and the + rest of the platform is evacuated onto the stack host. + when: DEPLOYMENT_MODE == 'swarm' + +- name: "๐Ÿ“ฆ Install the gVisor userspace kernel (runsc)" + get_url_retry: + url: "{{ SVC_VIRT_KATA_RUNSC_URL }}" + checksum: "sha512:{{ SVC_VIRT_KATA_RUNSC_URL }}.sha512" + dest: "{{ RUNSC_SHIM_BINARY }}" + mode: "0755" + owner: root + group: root + become: true + +- name: "๐Ÿณ Ensure the container daemon itself is installed" + ansible.builtin.include_role: + name: sys-svc-container + +- name: "๐Ÿ”ง Register the runtimes with the container daemon" + ansible.builtin.include_role: + name: sys-svc-container + tasks_from: daemon_config.yml + +- name: "๐Ÿ”„ Restart the container daemon onto the sandbox runtime" + meta: flush_handlers + +- name: "๐Ÿ” Read the runtime this node now defaults to" + ansible.builtin.command: >- + container info --format {{ '{{.DefaultRuntime}}' }} + register: svc_virt_kata_default_runtime + changed_when: false + when: + - DEPLOYMENT_MODE == 'swarm' + - not (IS_STACK_HOST | bool) + +- name: "๐Ÿ›‘ Refuse a sandbox node that still defaults to the shared kernel" + ansible.builtin.assert: + that: + - (svc_virt_kata_default_runtime.stdout | trim) != 'runc' + fail_msg: >- + This node is about to be labelled {{ SANDBOX_NODE_LABEL }}=true, which + routes every sandboxed service here, but its daemon still defaults to + '{{ svc_virt_kata_default_runtime.stdout | trim }}'. Swarm drops the + per-service runtime key, so the label would promise an isolation the node + cannot deliver and the agents would run on the host kernel. + when: + - DEPLOYMENT_MODE == 'swarm' + - not (IS_STACK_HOST | bool) + +- name: "๐Ÿท๏ธ Label this node as kata-capable" + ansible.builtin.command: >- + container node update --label-add {{ SANDBOX_NODE_LABEL }}=true + {{ ansible_facts['hostname'] }} + register: svc_virt_kata_label + changed_when: svc_virt_kata_label.rc == 0 + delegate_to: "{{ STACK_HOST }}" + when: + - DEPLOYMENT_MODE == 'swarm' + - not (IS_STACK_HOST | bool) + +- name: "๐Ÿ” Read back the nodes that carry the sandbox label" + ansible.builtin.command: >- + container node ls --filter node.label={{ SANDBOX_NODE_LABEL }}=true --quiet + register: svc_virt_kata_labelled_nodes + changed_when: false + delegate_to: "{{ STACK_HOST }}" + run_once: true + when: DEPLOYMENT_MODE == 'swarm' + +- name: "๐Ÿ›‘ Refuse to promise isolation that no node can carry" + ansible.builtin.assert: + that: + - svc_virt_kata_labelled_nodes.stdout_lines | length > 0 + fail_msg: >- + No node carries {{ SANDBOX_NODE_LABEL }}=true, so the placement constraint + of every sandboxed service matches nothing and the deploy would hang until + the convergence wait gives up. This role writes the label on every node it + runs on except the stack host, so put svc-virt-kata on at least one worker. + run_once: true + when: DEPLOYMENT_MODE == 'swarm' diff --git a/roles/svc-virt-kata/tasks/main.yml b/roles/svc-virt-kata/tasks/main.yml new file mode 100644 index 0000000000..05b3ea7a58 --- /dev/null +++ b/roles/svc-virt-kata/tasks/main.yml @@ -0,0 +1,5 @@ +--- +- include_tasks: 00_core.yml + when: run_once_svc_virt_kata is not defined + vars: + application_id: svc-virt-kata diff --git a/roles/svc-virt-kata/tasks/utils/assert_isolated.yml b/roles/svc-virt-kata/tasks/utils/assert_isolated.yml new file mode 100644 index 0000000000..1f425219a6 --- /dev/null +++ b/roles/svc-virt-kata/tasks/utils/assert_isolated.yml @@ -0,0 +1,19 @@ +--- +# Param: assert_isolated_container - name of the container that must not run under the shared kernel +- name: "๐Ÿ” Read the runtime '{{ assert_isolated_container }}' actually got" + ansible.builtin.command: >- # nocheck: container-exec-resolver runtime probe, the container name comes from the caller + container inspect --type container {{ assert_isolated_container }} + --format {{ '{{.HostConfig.Runtime}}' }} + register: assert_isolated_runtime + changed_when: false + +- name: "๐Ÿ›‘ Refuse an agent running under the shared kernel" + ansible.builtin.assert: + that: + - (assert_isolated_runtime.stdout | trim) != 'runc' + fail_msg: >- + '{{ assert_isolated_container }}' runs under + '{{ assert_isolated_runtime.stdout | trim }}', which is the host kernel. + This container executes code the model wrote, so the deploy is refused + rather than left looking healthy. Check that svc-virt-kata installed the + isolating runtime on this host and that the daemon restarted onto it. diff --git a/roles/svc-virt-kata/vars/main.yml b/roles/svc-virt-kata/vars/main.yml new file mode 100644 index 0000000000..c998e1bb19 --- /dev/null +++ b/roles/svc-virt-kata/vars/main.yml @@ -0,0 +1,6 @@ +--- +application_id: "svc-virt-kata" + +SVC_VIRT_KATA_RUNSC_VERSION: "20260714.0" +SVC_VIRT_KATA_RUNSC_URL: >- + https://storage.googleapis.com/gvisor/releases/release/{{ SVC_VIRT_KATA_RUNSC_VERSION }}/{{ ansible_facts['architecture'] }}/runsc diff --git a/roles/sys-ca-selfsigned/files/shell/with-ca-trust.sh b/roles/sys-ca-selfsigned/files/shell/with-ca-trust.sh index 0b38ecaa07..3ec233f826 100644 --- a/roles/sys-ca-selfsigned/files/shell/with-ca-trust.sh +++ b/roles/sys-ca-selfsigned/files/shell/with-ca-trust.sh @@ -38,31 +38,40 @@ log "Sanitized trust name: $name" installed=0 -ca_bundle="$CA_TRUST_CERT" -combined="/tmp/with-ca-trust-combined.crt" -# shellcheck disable=SC2086 # intentional word-splitting; paths contain no spaces -for sys_bundle in $SYS_CA_BUNDLE_CANDIDATES; do - if [ -r "$sys_bundle" ] && cat "$sys_bundle" "$CA_TRUST_CERT" > "$combined" 2>/dev/null; then - ca_bundle="$combined" - log "Combined system CA bundle ($sys_bundle) with ${name} -> $combined" - break - fi -done +if [ -n "${CA_TRUST_BUNDLE:-}" ] && [ -r "${CA_TRUST_BUNDLE}" ]; then + _ca_trust_verify_file="$CA_TRUST_BUNDLE" +else + _ca_trust_verify_file="$CA_TRUST_CERT" + # Exception: validating an external host needs the system roots as well; the + # single-CA file on its own rejects every public TLS chain. + # shellcheck disable=SC2086 # intentional word-splitting; paths contain no spaces + for sys_bundle in $SYS_CA_BUNDLE_CANDIDATES; do + if [ -r "$sys_bundle" ] && + _ca_trust_sys_combined="$(mktemp -t with-ca-trust-combined.XXXXXX 2>/dev/null)" && + cat "$sys_bundle" "$CA_TRUST_CERT" > "$_ca_trust_sys_combined" 2>/dev/null + then + _ca_trust_verify_file="$_ca_trust_sys_combined" + log "Combined system CA bundle ($sys_bundle) with ${name} -> $_ca_trust_sys_combined" + break + fi + done +fi -export SSL_CERT_FILE="$ca_bundle" -export REQUESTS_CA_BUNDLE="$ca_bundle" -export CURL_CA_BUNDLE="$ca_bundle" +export SSL_CERT_FILE="$_ca_trust_verify_file" +export REQUESTS_CA_BUNDLE="$_ca_trust_verify_file" +export CURL_CA_BUNDLE="$_ca_trust_verify_file" export NODE_EXTRA_CA_CERTS="$CA_TRUST_CERT" if [ -n "${CA_TRUST_CERT_EXTRA:-}" ] && [ -r "${CA_TRUST_CERT_EXTRA}" ]; then - combined_extra="/tmp/ca-trust-combined.crt" - if cat "$ca_bundle" "$CA_TRUST_CERT_EXTRA" > "$combined_extra" 2>/dev/null; then - export SSL_CERT_FILE="$combined_extra" - export REQUESTS_CA_BUNDLE="$combined_extra" - export CURL_CA_BUNDLE="$combined_extra" - export NODE_EXTRA_CA_CERTS="$combined_extra" + if combined="$(mktemp -t ca-trust-combined.XXXXXX 2>/dev/null)" && + cat "$_ca_trust_verify_file" "$CA_TRUST_CERT_EXTRA" > "$combined" 2>/dev/null + then + export SSL_CERT_FILE="$combined" + export REQUESTS_CA_BUNDLE="$combined" + export CURL_CA_BUNDLE="$combined" + export NODE_EXTRA_CA_CERTS="$combined" else - log "WARN: cannot write $combined_extra; keeping existing trust env" + log "WARN: cannot build combined CA bundle; keeping single-CA trust env" fi fi diff --git a/roles/sys-ca-selfsigned/tasks/00_core.yml b/roles/sys-ca-selfsigned/tasks/00_core.yml index 932fac05a6..6fe09ba0e6 100644 --- a/roles/sys-ca-selfsigned/tasks/00_core.yml +++ b/roles/sys-ca-selfsigned/tasks/00_core.yml @@ -66,6 +66,13 @@ Generated certificate does not appear to be a CA certificate (CA:TRUE missing). Please inspect {{ CA_ROOT.cert_host }}. +- name: "๐Ÿ”Ž CA | locate the distribution's public CA bundle" + become: true + ansible.builtin.stat: + path: "{{ item }}" + loop: "{{ CA_BUNDLE_CANDIDATES }}" + register: _ca_public_bundle_candidates + - name: "๐Ÿ”Ž CA | stat host CA-trust bind-mount sources" become: true ansible.builtin.stat: @@ -73,6 +80,7 @@ loop: - "{{ BIN_CA_TRUST }}" - "{{ CA_TRUST.php_ini_host }}" + - "{{ CA_TRUST.bundle_host }}" register: _ca_trust_bind_sources - name: "๐Ÿงน CA | remove stray directory shadowing a CA-trust bind source" @@ -87,6 +95,22 @@ - item.stat.exists - item.stat.isdir +- name: "๐Ÿ“„ CA | build the trust bundle its readers name with no fallback" + become: true + ansible.builtin.shell: >- + cat {{ ([CA_ROOT.cert_host] + (_ca_public_bundle_candidates.results | selectattr('stat.exists') | map(attribute='item') | list)[:1]) | map('quote') | join(' ') + }} + > {{ CA_TRUST.bundle_host | quote }} + changed_when: true + +- name: "๐Ÿ” CA | enforce permissions (trust bundle)" + become: true + ansible.builtin.file: + path: "{{ CA_TRUST.bundle_host }}" + owner: root + group: root + mode: "0644" + - name: "๐Ÿ“ฆ CA | install trust helper script (SPOT) on host" become: true ansible.builtin.copy: diff --git a/roles/sys-ca-selfsigned/templates/ca-trust-php.ini.j2 b/roles/sys-ca-selfsigned/templates/ca-trust-php.ini.j2 index e4f3cdb013..8f7da9be97 100644 --- a/roles/sys-ca-selfsigned/templates/ca-trust-php.ini.j2 +++ b/roles/sys-ca-selfsigned/templates/ca-trust-php.ini.j2 @@ -1,2 +1,2 @@ -openssl.cafile={{ CA_TRUST.inject_cert_container }} -curl.cainfo={{ CA_TRUST.inject_cert_container }} +openssl.cafile={{ CA_TRUST.inject_bundle_container }} +curl.cainfo={{ CA_TRUST.inject_bundle_container }} diff --git a/roles/sys-ctl-alm-compose/templates/script.sh.j2 b/roles/sys-ctl-alm-compose/templates/script.sh.j2 index d9007ff9d5..ff85bcf637 100644 --- a/roles/sys-ctl-alm-compose/templates/script.sh.j2 +++ b/roles/sys-ctl-alm-compose/templates/script.sh.j2 @@ -1,4 +1,5 @@ #!/bin/bash +{# nocheck: shell-template grandfathered: one start block per subservice, each naming a unit only unit_name can resolve #} err=0 set -u start_timeout="{{ SYSTEMCTL_ALARM_COMPOSER_START_TIMEOUT_SECONDS }}" diff --git a/roles/sys-ctl-alm-email/templates/script.sh.j2 b/roles/sys-ctl-alm-email/templates/script.sh.j2 index b8b89bf89d..c9ec0bdf61 100644 --- a/roles/sys-ctl-alm-email/templates/script.sh.j2 +++ b/roles/sys-ctl-alm-email/templates/script.sh.j2 @@ -1,4 +1,5 @@ #!/bin/bash +{# nocheck: shell-template grandfathered, values only: the mail envelope, charset and timeout #} set -u # Reverse systemd escaping for human-readable mail subject/body friendly="$(systemd-escape --unescape "$1")" diff --git a/roles/sys-ctl-alm-telegram/templates/script.sh.j2 b/roles/sys-ctl-alm-telegram/templates/script.sh.j2 index 32a1fb0f94..726a842e4f 100644 --- a/roles/sys-ctl-alm-telegram/templates/script.sh.j2 +++ b/roles/sys-ctl-alm-telegram/templates/script.sh.j2 @@ -1,4 +1,5 @@ #!/bin/bash +{# nocheck: shell-template grandfathered, values only: bot token, chat id and the curl filter's timeout #} set -u # Make the instance text human readable again (reverse systemd escaping) diff --git a/roles/sys-ctl-cln-bkps/files/python/script.py b/roles/sys-ctl-cln-bkps/files/python/script.py index 3d64c277aa..60d61a96c0 100644 --- a/roles/sys-ctl-cln-bkps/files/python/script.py +++ b/roles/sys-ctl-cln-bkps/files/python/script.py @@ -210,7 +210,8 @@ while is_larger_than_maximum_backup_size(maximum_backup_size_percent, backup_dir ) if delete_iteration(backup_dir, average_version_directories) == 0: print( - "No deletable backup versions left; the remaining usage is not backup-driven. Exiting." + "No deletable backup version left; every remaining version is the last " + "of its application. Exiting." ) break itteration_counter += 1 diff --git a/roles/sys-ctl-cln-docker/templates/script.sh.j2 b/roles/sys-ctl-cln-docker/templates/script.sh.j2 index 4a7bd76017..5d66f0f6d7 100644 --- a/roles/sys-ctl-cln-docker/templates/script.sh.j2 +++ b/roles/sys-ctl-cln-docker/templates/script.sh.j2 @@ -1,4 +1,5 @@ #!/bin/sh +{# nocheck: shell-template grandfathered, values only: the versioned unit name it starts #} # Cleans up anonymous Docker volumes and performs a full Docker system prune. set -e diff --git a/roles/sys-ctl-hlth-csp/defaults/main.yml b/roles/sys-ctl-hlth-csp/defaults/main.yml index 167cc00ccf..d357878bf7 100644 --- a/roles/sys-ctl-hlth-csp/defaults/main.yml +++ b/roles/sys-ctl-hlth-csp/defaults/main.yml @@ -10,3 +10,9 @@ HEALTH_CSP_IMAGE: "{{ lookup('config', 'sys-ctl-hlth-csp', 'services.csp-checker # If true, pull the image on each run (safe but slower) HEALTH_CSP_ALWAYS_PULL: false + +# Navigation budget in milliseconds a clearnet vhost gets; mirrors the checker's own default +HEALTH_CSP_TIMEOUT_MS: 20000 + +# Seconds added per vhost on top of its navigation budget when sizing TimeoutStartSec +HEALTH_CSP_DOMAIN_RESERVE_SECONDS: 5 diff --git a/roles/sys-ctl-hlth-csp/files/python/script.py b/roles/sys-ctl-hlth-csp/files/python/script.py index 654a583a2b..7d085e23eb 100755 --- a/roles/sys-ctl-hlth-csp/files/python/script.py +++ b/roles/sys-ctl-hlth-csp/files/python/script.py @@ -57,6 +57,33 @@ def is_skipped_domain(domain: str, skip_set: set[str], skip_labels: set[str]) -> return domain.endswith(".onion") and domain.split(".", 1)[0] in skip_labels +def expand_accept_status(accept_status: list[str], domains: list[str]) -> list[str]: + """ACCEPT_STATUS plus the same codes for every ``.onion`` sibling it covers. + + The checker matches accepted codes by hostname, and a clearnet vhost and + its onion twin share only the leftmost subdomain label, so a code declared + for ``mirror.`` never reaches ``mirror..onion`` โ€” + which serves that same by-design status and would fail the probe. + + Args: + accept_status: ``=[,]`` entries as declared. + domains: every vhost the probe covers, clearnet and onion alike. + """ + onion = [d for d in domains if d.endswith(".onion")] + expanded = list(accept_status) + for entry in accept_status: + host, _, codes = entry.partition("=") + if not codes or host.endswith(".onion"): + continue + label = host.split(".", 1)[0] + expanded.extend( + f"{sibling}={codes}" + for sibling in onion + if sibling.split(".", 1)[0] == label + ) + return expanded + + def detect_scheme_from_conf(conf_path: Path) -> str | None: """ Decide whether this conf listens on HTTP or HTTPS. @@ -130,6 +157,8 @@ def build_docker_cmd( ignore_network_blocks_from: list[str], use_host_network: bool = True, proxy: str = "", + timeout_ms: int = 0, + accept_status: list[str] | None = None, ) -> list[str]: cmd = ["container", "run", "--rm"] @@ -148,9 +177,18 @@ def build_docker_cmd( if proxy: cmd.extend(["--proxy", proxy]) + if timeout_ms: + cmd.extend(["--timeout", str(timeout_ms)]) + if ignore_network_blocks_from: cmd.append("--ignore-network-blocks-from") cmd.extend(ignore_network_blocks_from) + + if accept_status: + cmd.append("--accept-status") + cmd.extend(accept_status) + + if ignore_network_blocks_from or accept_status: cmd.append("--") cmd.extend(urls) @@ -165,6 +203,8 @@ def run_checker( always_pull: bool, use_host_network: bool = True, proxy: str = "", + timeout_ms: int = 0, + accept_status: list[str] | None = None, ) -> int: """ Runs the CSP checker container and returns its exit code. @@ -180,6 +220,8 @@ def run_checker( ignore_network_blocks_from=ignore_network_blocks_from, use_host_network=use_host_network, proxy=proxy, + timeout_ms=timeout_ms, + accept_status=accept_status, ) try: @@ -239,6 +281,27 @@ def main() -> None: "otherwise treat as unreachable." ), ) + parser.add_argument( + "--accept-status", + nargs="*", + default=[], + help=( + "Per-vhost status codes the probe must treat as healthy, as " + "=[,]. Declared in the role's " + "server.status_codes; everything below 300 passes without being " + "listed." + ), + ) + parser.add_argument( + "--onion-timeout", + type=int, + default=0, + help=( + "Navigation budget in milliseconds for the .onion batch, which " + "reaches its vhosts over Tor and needs longer than the checker's " + "own default. 0 leaves that default in place." + ), + ) parser.add_argument( "--tor-proxy", default="", @@ -274,6 +337,8 @@ def main() -> None: f"--skip-domain: {skipped_present}" ) + accept_status = expand_accept_status(list(args.accept_status or []), domains) + clearnet_domains, onion_domains = split_onion_domains(domains) if onion_domains and not args.tor_proxy: print( @@ -287,9 +352,9 @@ def main() -> None: sys.exit(0) rc = 0 - for batch_domains, batch_proxy in ( - (clearnet_domains, ""), - (onion_domains, args.tor_proxy), + for batch_domains, batch_proxy, batch_timeout in ( + (clearnet_domains, "", 0), + (onion_domains, args.tor_proxy, args.onion_timeout), ): if not batch_domains: continue @@ -305,6 +370,8 @@ def main() -> None: always_pull=bool(args.always_pull), use_host_network=not bool(args.no_host_network), proxy=batch_proxy, + timeout_ms=batch_timeout, + accept_status=accept_status, ) rc = rc or batch_rc sys.exit(rc) diff --git a/roles/sys-ctl-hlth-csp/lookup_plugins/csp_accept_status.py b/roles/sys-ctl-hlth-csp/lookup_plugins/csp_accept_status.py new file mode 100644 index 0000000000..56a815d8ab --- /dev/null +++ b/roles/sys-ctl-hlth-csp/lookup_plugins/csp_accept_status.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.roles.applications.config import get +from utils.roles.applications.status_codes import declared_status_codes + +_CHECKER_ACCEPTS_BELOW = 300 + + +def _domains(value: Any) -> list[str]: + if isinstance(value, str): + return [value] if value else [] + if isinstance(value, Mapping): + out: list[str] = [] + for entry in value.values(): + out.extend(_domains(entry)) + return out + if isinstance(value, (list, tuple, set)): + out = [] + for entry in value: + out.extend(_domains(entry)) + return out + return [] + + +class LookupModule(LookupBase): + """Return ``=[,]`` for every declared non-2xx status. + + The checker treats anything outside 2xx as unreachable, so a vhost that + serves a 4xx by design needs its code named. Naming it keeps the page + under CSP inspection, which excluding the domain would not. + + The declaration is per vhost: ``server.status_codes`` is keyed like + ``domains.canonical``, so two domains of one role can differ. + """ + + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[list[str]]: + applications = lookup_loader.get( + "applications", + loader=self._loader, + templar=getattr(self, "_templar", None), + ).run( + [], + variables=variables + or getattr(self._templar, "available_variables", {}) + or {}, + )[0] + + if not isinstance(applications, Mapping): + return [[]] + + accepted: dict[str, set[int]] = {} + for app_id in applications: + domains = _domains( + get(applications, app_id, "domains.canonical", strict=False, default=[]) + ) + _domains( + get(applications, app_id, "domains.aliases", strict=False, default=[]) + ) + for domain in domains: + codes = { + code + for code in declared_status_codes(applications, app_id, domain) + if code >= _CHECKER_ACCEPTS_BELOW + } + if codes: + accepted.setdefault(domain, set()).update(codes) + + return [ + [ + f"{domain}={','.join(str(code) for code in sorted(codes))}" + for domain, codes in sorted(accepted.items()) + ] + ] diff --git a/roles/sys-ctl-hlth-csp/lookup_plugins/csp_skip_domains.py b/roles/sys-ctl-hlth-csp/lookup_plugins/csp_skip_domains.py index 08d344c073..16af34bded 100644 --- a/roles/sys-ctl-hlth-csp/lookup_plugins/csp_skip_domains.py +++ b/roles/sys-ctl-hlth-csp/lookup_plugins/csp_skip_domains.py @@ -32,21 +32,6 @@ def _to_list(x: Any) -> list[str]: return [] -def _has_code_ge_400(codes: Any) -> bool: - if codes is None: - return False - if not isinstance(codes, (list, tuple, set)): - codes = [codes] - for c in codes: - try: - n = int(c) - except (TypeError, ValueError): - continue - if n >= 400: - return True - return False - - def _selection_from(group_names: Any) -> set[str]: if isinstance(group_names, (list, set, tuple)): return {str(x) for x in group_names if str(x)} @@ -58,11 +43,7 @@ def _selection_from(group_names: Any) -> set[str]: class LookupModule(LookupBase): """Return domains the CSP probe should skip. - Skips canonical + alias domains of every selected application whose - ``server.status_codes.default`` declares any HTTP code >= 400 - (e.g. federation-only roles that legitimately serve 4xx at ``/``). - - Additionally skips canonical domains owned by a disabled service: a + Skips canonical domains owned by a disabled service: a service entry may declare ``domains: [, ...]``; when its ``enabled`` resolves falsy those canonicals get no vhost (e.g. the seaweedfs filer/master frontend on an onion node), so probing them can @@ -118,37 +99,7 @@ class LookupModule(LookupBase): skip: set[str] = set() for app_id in applications: - if selection and app_id not in selection: - continue - - skip |= self._service_disabled_domains(applications, app_id) - - default = get( - applications, - app_id, - "server.status_codes.default", - strict=False, - default=None, - ) - if not _has_code_ge_400(default): - continue - - canonical = get( - applications, - app_id, - "domains.canonical", - strict=False, - default=[], - ) - aliases = get( - applications, - app_id, - "domains.aliases", - strict=False, - default=[], - ) - for d in _to_list(canonical) + _to_list(aliases): - if d: - skip.add(d) + if not selection or app_id in selection: + skip |= self._service_disabled_domains(applications, app_id) return [sorted(skip)] diff --git a/roles/sys-ctl-hlth-csp/meta/services.yml b/roles/sys-ctl-hlth-csp/meta/services.yml index c85f572af8..a6e9695221 100644 --- a/roles/sys-ctl-hlth-csp/meta/services.yml +++ b/roles/sys-ctl-hlth-csp/meta/services.yml @@ -8,4 +8,4 @@ csp: categories: [web] csp-checker: image: ghcr.io/kevinveenbirkenbach/csp-checker - version: 2.2.1 + version: 3.0.4 diff --git a/roles/sys-ctl-hlth-csp/tasks/00_core.yml b/roles/sys-ctl-hlth-csp/tasks/00_core.yml index 9216b832ea..2d965b1a5c 100644 --- a/roles/sys-ctl-hlth-csp/tasks/00_core.yml +++ b/roles/sys-ctl-hlth-csp/tasks/00_core.yml @@ -36,7 +36,8 @@ system_service_on_calendar: "{{ SYS_SCHEDULE_HEALTH_CSP_CRAWLER }}" system_service_timer_enabled: true system_service_tpl_on_failure: "{{ SYS_SERVICE_ON_FAILURE_COMPOSE }}" - system_service_tpl_timeout_start_sec: "{{ CURRENT_PLAY_DOMAINS_ALL | timeout_start_sec_for_domains }}" + system_service_tpl_timeout_start_sec: "{{ CURRENT_PLAY_DOMAINS_ALL | timeout_start_sec_for_domains(onion_per_domain_seconds=HEALTH_CSP_ONION_DOMAIN_SECONDS | + int) }}" system_service_tpl_environment: "{{ CA_TRUST_SYSTEMD_ENV_SELFSIGNED }}" system_service_tpl_exec_start: >- {{ @@ -59,8 +60,13 @@ '--skip-domain ' ~ (HEALTH_CSP_SKIP_DOMAINS | join(' ')), '' ), + (HEALTH_CSP_ACCEPT_STATUS | length > 0) | ternary( + '--accept-status ' ~ (HEALTH_CSP_ACCEPT_STATUS | join(' ')), + '' + ), (lookup('config', 'svc-net-tor', 'services.tor.node', '') | length > 0) | ternary( - '--tor-proxy=socks5://' ~ lookup('tor_socks'), + '--tor-proxy=socks5://' ~ lookup('tor_socks') + ~ ' --onion-timeout=' ~ HEALTH_CSP_ONION_TIMEOUT_MS, '' ) ] diff --git a/roles/sys-ctl-hlth-csp/vars/main.yml b/roles/sys-ctl-hlth-csp/vars/main.yml index 307ca3a750..ea8d4a0ce0 100644 --- a/roles/sys-ctl-hlth-csp/vars/main.yml +++ b/roles/sys-ctl-hlth-csp/vars/main.yml @@ -1,5 +1,9 @@ --- system_service_id: sys-ctl-hlth-csp +HEALTH_CSP_ONION_TIMEOUT_MS: "{{ (HEALTH_CSP_TIMEOUT_MS | int) * (lookup('config', 'svc-net-tor', 'services.tor.timeout_multipliers')[lookup('config', 'svc-net-tor', + 'services.tor.flavor')] | int) }}" +HEALTH_CSP_ONION_DOMAIN_SECONDS: "{{ ((HEALTH_CSP_ONION_TIMEOUT_MS | int) // 1000) + (HEALTH_CSP_DOMAIN_RESERVE_SECONDS | int) }}" +HEALTH_CSP_ACCEPT_STATUS: "{{ lookup('csp_accept_status') }}" HEALTH_CSP_SKIP_DOMAINS: >- {{ ( lookup('csp_skip_domains', group_names=lookup('deployment').deployed) diff --git a/roles/sys-ctl-hlth-disc-space/files/python/script.py b/roles/sys-ctl-hlth-disc-space/files/python/script.py index 94ba9719cc..610bea07aa 100755 --- a/roles/sys-ctl-hlth-disc-space/files/python/script.py +++ b/roles/sys-ctl-hlth-disc-space/files/python/script.py @@ -49,7 +49,7 @@ def main(): print(f"WARNING: {usage}% exceeds the limit of {threshold}%.") errors += 1 - sys.exit(errors) + sys.exit(1 if errors else 0) if __name__ == "__main__": diff --git a/roles/sys-ctl-hlth-msmtp/files/shell/script.sh b/roles/sys-ctl-hlth-msmtp/files/shell/script.sh index 8f3c4508d1..372dd280cb 100644 --- a/roles/sys-ctl-hlth-msmtp/files/shell/script.sh +++ b/roles/sys-ctl-hlth-msmtp/files/shell/script.sh @@ -4,8 +4,8 @@ set -u : "${MAIL_TIMEOUT:?MAIL_TIMEOUT not set}" HOST="${HOSTNAME:-$(uname -n 2>/dev/null || echo unknown)}" -attempts=12 -delay=12 +attempts=10 +delay=30 for attempt in $(seq 1 "${attempts}"); do msmtp_err="$( @@ -23,7 +23,7 @@ for attempt in $(seq 1 "${attempts}"); do 69 | 75 | 124) ;; 77) case "${msmtp_err}" in - *454* | *"Temporary authentication failure"*) ;; + *"server message: 4"* | *"Temporary authentication failure"*) ;; *) exit "${rc}" ;; esac ;; diff --git a/roles/sys-ctl-hlth-volumes/files/shell/script.sh b/roles/sys-ctl-hlth-volumes/files/shell/script.sh index 572cb455ab..a904f21ce4 100644 --- a/roles/sys-ctl-hlth-volumes/files/shell/script.sh +++ b/roles/sys-ctl-hlth-volumes/files/shell/script.sh @@ -110,7 +110,7 @@ if [ -n "$nfs_volumes" ]; then continue fi - if showmount -e "$server" >/dev/null 2>&1; then + if timeout 5 bash -c "exec 3<>/dev/tcp/${server}/2049" 2>/dev/null; then echo "โœ… Volume $vol: server $server reachable for export $export_path" else echo "โŒ Volume $vol: server $server NOT reachable (export $export_path)" @@ -119,4 +119,4 @@ if [ -n "$nfs_volumes" ]; then done fi -exit $status +exit $((status ? 1 : 0)) diff --git a/roles/sys-ctl-hlth-webserver/files/python/script.py b/roles/sys-ctl-hlth-webserver/files/python/script.py index 4b04d6a68b..c3c62c7de7 100755 --- a/roles/sys-ctl-hlth-webserver/files/python/script.py +++ b/roles/sys-ctl-hlth-webserver/files/python/script.py @@ -94,7 +94,7 @@ def main(argv=None) -> int: if errors: print(f"Warning: {errors} domains responded with an unexpected status code.") - return errors + return 1 if errors else 0 if __name__ == "__main__": diff --git a/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py b/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py index 169d635acf..e8cd9b50f7 100644 --- a/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py +++ b/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py @@ -3,6 +3,7 @@ from collections.abc import Mapping from pathlib import Path from utils.roles.applications.config import get +from utils.roles.applications.status_codes import DEFAULT_OK, codes_by_key # nocheck: project-root-import _BASE_DIR = str(Path(__file__).resolve().parents[3]) @@ -11,8 +12,6 @@ for _p in (_BASE_DIR, _MODULE_UTILS_DIR): if _p not in sys.path: sys.path.insert(0, _p) -DEFAULT_OK = [200, 302, 301] - def _to_list(x, *, allow_mapping: bool = True): """Normalize into a flat list of **strings only**.""" @@ -46,15 +45,6 @@ def _to_list(x, *, allow_mapping: bool = True): return [] -def _valid_http_code(x): - """Return int(x) if 100 <= code <= 599 else None.""" - try: - v = int(x) - except (TypeError, ValueError): - return None - return v if 100 <= v <= 599 else None - - def _extract_redirect_sources(redirect_maps): """Extract a set of source domains from redirect maps.""" sources = set() @@ -94,28 +84,6 @@ def _normalize_selection(group_names): return sel -def _normalize_codes(x): - """ - Accepts: - - single code (int or str) - - list/tuple/set of codes - Returns a de-duplicated list of valid ints (100..599) in original order. - """ - if x is None: - return [] - if isinstance(x, (list, tuple, set)): - out = [] - seen = set() - for v in x: - c = _valid_http_code(v) - if c is not None and c not in seen: - seen.add(c) - out.append(c) - return out - c = _valid_http_code(x) - return [c] if c is not None else [] - - def _apply_onion_deploy_view(per_app, applications, primary_domain, node_onion): """Rewrite each app's expectation domains to what the current deploy serves: for a ``services.tor.enabled`` app the onion domains replace (``exclusive``) @@ -190,15 +158,9 @@ def web_health_expectations( ) aliases = _to_list(aliases_raw, allow_mapping=True) - sc_raw = get( - applications, app_id, "server.status_codes", strict=False, default={} + sc_map = codes_by_key( + get(applications, app_id, "server.status_codes", strict=False, default={}) ) - sc_map = {} - if isinstance(sc_raw, Mapping): - for k, v in sc_raw.items(): - codes = _normalize_codes(v) - if codes: - sc_map[str(k)] = codes suppressed = set() services_raw = get(applications, app_id, "services", strict=False, default={}) diff --git a/roles/sys-ctl-rpr-container-soft/files/python/script.py b/roles/sys-ctl-rpr-container-soft/files/python/script.py index 62ca8969b5..93726923f8 100755 --- a/roles/sys-ctl-rpr-container-soft/files/python/script.py +++ b/roles/sys-ctl-rpr-container-soft/files/python/script.py @@ -235,7 +235,7 @@ def main( errors += 1 print("Finished restart procedure.") - return errors + return 1 if errors else 0 if __name__ == "__main__": diff --git a/roles/sys-dns-hetzner-rdns/defaults/main.yml b/roles/sys-dns-hetzner-rdns/defaults/main.yml index 1c775a8122..57be7c7247 100644 --- a/roles/sys-dns-hetzner-rdns/defaults/main.yml +++ b/roles/sys-dns-hetzner-rdns/defaults/main.yml @@ -11,5 +11,4 @@ HETZNER_ROBOT_BASE_URL: "https://robot-ws.your-server.de" hetzner_async_enabled: "{{ ASYNC_ENABLED | bool }}" hetzner_async_time: "{{ ASYNC_TIME }}" hetzner_async_poll: "{{ ASYNC_POLL }}" -hetzner_no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" rdns_records: [] diff --git a/roles/sys-dns-hetzner-rdns/tasks/flavors/cloud.yml b/roles/sys-dns-hetzner-rdns/tasks/flavors/cloud.yml index 724142fb96..355742a951 100644 --- a/roles/sys-dns-hetzner-rdns/tasks/flavors/cloud.yml +++ b/roles/sys-dns-hetzner-rdns/tasks/flavors/cloud.yml @@ -7,13 +7,13 @@ | default(lookup('env','HETZNER_API_TOKEN'), true) | default('', true) }} - no_log: "{{ hetzner_no_log | bool }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - name: โœ… Assert hcloud token present ansible.builtin.assert: that: ["_hz_token | length > 0"] fail_msg: "HETZNER_API_TOKEN is required for the Cloud flavor." - no_log: "{{ hetzner_no_log | bool }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" when: MODE_ASSERT | bool - name: ๐Ÿ“Š Collect hcloud servers if needed (server records without identifier) @@ -21,7 +21,7 @@ api_token: "{{ _hz_token }}" register: _servers_info when: rdns_records | selectattr('resource','equalto','server') | selectattr('identifier','undefined') | list | length > 0 - no_log: "{{ hetzner_no_log | bool }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - name: ๐ŸŽฌ Init normalized records list set_fact: @@ -61,7 +61,7 @@ (_rdns_records | selectattr('resource','equalto','server') | list | length) ) fail_msg: "Could not resolve hcloud server by IPv4 for one or more records." - no_log: "{{ hetzner_no_log | bool }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" when: MODE_ASSERT | bool - name: โœ… Validate records (cloud) @@ -74,7 +74,7 @@ - ( (_rdns_records | default(rdns_records)) | selectattr('resource','equalto','server') | selectattr('identifier','defined') | list | length + ((_rdns_records | default(rdns_records)) | rejectattr('resource','equalto','server') | list | length) ) == ((_rdns_records | default(rdns_records)) | length) - no_log: "{{ hetzner_no_log | bool }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" when: MODE_ASSERT | bool - name: ๐Ÿ“Œ Apply rDNS via hcloud @@ -93,4 +93,4 @@ # rationale: async; last task, not delegated, no notify, rDNS is read back by nothing async: "{{ hetzner_async_enabled | ternary(hetzner_async_time, omit) }}" poll: "{{ hetzner_async_enabled | ternary(hetzner_async_poll, omit) }}" - no_log: "{{ hetzner_no_log | bool }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/sys-dns-hetzner-rdns/tasks/main.yml b/roles/sys-dns-hetzner-rdns/tasks/main.yml index 2eb75959a9..96759d19b6 100644 --- a/roles/sys-dns-hetzner-rdns/tasks/main.yml +++ b/roles/sys-dns-hetzner-rdns/tasks/main.yml @@ -10,7 +10,7 @@ (HETZNER_ROBOT_USER | length) > 0 and (HETZNER_ROBOT_PASSWORD | length) > 0 }} - no_log: "{{ hetzner_no_log | bool }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - name: "๐Ÿ”‘ Note: both Cloud token and Robot creds provided; using Cloud flavor" debug: @@ -25,7 +25,7 @@ ansible.builtin.include_tasks: file: flavors/robot.yml apply: - no_log: "{{ hetzner_no_log | bool }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" when: (not _use_cloud) and _use_robot - name: ๐Ÿ›‘ Fail if no credentials provided diff --git a/roles/sys-front-inj-all/templates/body_filter.lua.j2 b/roles/sys-front-inj-all/templates/body_filter.lua.j2 index 21cd5d294a..479872e5bb 100644 --- a/roles/sys-front-inj-all/templates/body_filter.lua.j2 +++ b/roles/sys-front-inj-all/templates/body_filter.lua.j2 @@ -8,8 +8,7 @@ {% endfor -%} {%- endmacro %} --- Only process HTML responses -if not ngx.ctx.is_html then +if not (ngx.ctx.is_html or ngx.ctx.is_css) then return end @@ -51,6 +50,10 @@ do end {% endif %} {% endif %} +if ngx.ctx.is_css then + ngx.arg[1] = whole + return +end {% set _cdn_base = lookup('tls', 'web-svc-cdn', 'url.base') | regex_replace('/+$', '') %} {% set _tor_node = lookup('config', 'svc-net-tor', 'services.tor.node', '') %} {% set _cdn_onion = _cdn_base | to_onion_url(_tor_node, DOMAIN_PRIMARY) %} diff --git a/roles/sys-front-tls/tasks/01_http.yml b/roles/sys-front-tls/tasks/01_http.yml index a371b4f34c..597f04c321 100644 --- a/roles/sys-front-tls/tasks/01_http.yml +++ b/roles/sys-front-tls/tasks/01_http.yml @@ -10,5 +10,5 @@ stack_host_template: src: "http.conf.j2" dest: "{{ lookup('nginx', 'files.domain', domain, protocol='http') }}" - notify: restart-openresty + notify: reload-openresty when: HTTPS_REDIRECT_ENABLED | bool diff --git a/roles/sys-lint/README.md b/roles/sys-lint/README.md index 5ea989a464..b6ab9380fa 100644 --- a/roles/sys-lint/README.md +++ b/roles/sys-lint/README.md @@ -48,6 +48,6 @@ To pin a different version by hand, edit the tool's `ref` in `meta/services.yml` ## Credits -Implemented by **Kevin Veen-Birkenbach**. +Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/sys-pip-install/tasks/00_core.yml b/roles/sys-pip-install/tasks/00_core.yml index 65dd4be738..7c25a2fc10 100644 --- a/roles/sys-pip-install/tasks/00_core.yml +++ b/roles/sys-pip-install/tasks/00_core.yml @@ -5,3 +5,69 @@ when: run_once_sys_pip is not defined - include_tasks: utils/once/flag.yml + +- name: ๐Ÿ” Resolve active Python executable for sys-pip-install + ansible.builtin.set_fact: + sys_pip_install_python_executable: "{{ ansible_python_interpreter }}" + changed_when: false + +- block: + - name: ๐Ÿ” Probe pip for ansible_python_interpreter accepts --break-system-packages + ansible.builtin.command: + argv: + - "{{ sys_pip_install_python_executable }}" + - -m + - pip + - install + - --break-system-packages + - --help + register: sys_pip_install_break_system_packages_probe + changed_when: false + failed_when: false + become: "{{ true if global_install | bool else false }}" + + - name: ๐Ÿ”ง Set fact for --break-system-packages support + ansible.builtin.set_fact: + sys_pip_install_supports_break_system_packages: "{{ (sys_pip_install_break_system_packages_probe.rc | int) == 0 }}" + changed_when: false + + when: global_install | bool + +- name: ๐Ÿ”Ž Check whether selected Python interpreter has 'packaging' + ansible.builtin.command: + argv: + - "{{ sys_pip_install_python_executable }}" + - -I + - -c + - import packaging + register: sys_pip_install_python_packaging_check + changed_when: false + failed_when: false + +- name: ๐Ÿฅพ Bootstrap 'packaging' for selected Python interpreter + ansible.builtin.command: + argv: >- + {{ + [sys_pip_install_python_executable, '-m', 'pip', 'install', '--upgrade', 'packaging'] + + ( + ['--break-system-packages'] + if (global_install | bool and sys_pip_install_supports_break_system_packages | default(false) | bool) + else [] + ) + }} + environment: >- + {{ + ( + {'PIP_BREAK_SYSTEM_PACKAGES': '1'} + if sys_pip_install_supports_break_system_packages | default(false) | bool + else {} + ) + if global_install | bool + else omit + }} + become: "{{ true if global_install | bool else false }}" + register: sys_pip_install_packaging_bootstrap + retries: 5 + delay: 15 + until: sys_pip_install_packaging_bootstrap is succeeded + when: sys_pip_install_python_packaging_check.rc != 0 diff --git a/roles/sys-pip-install/tasks/main.yml b/roles/sys-pip-install/tasks/main.yml index 0709680650..415eae462e 100644 --- a/roles/sys-pip-install/tasks/main.yml +++ b/roles/sys-pip-install/tasks/main.yml @@ -4,55 +4,12 @@ - include_tasks: 00_core.yml when: run_once_sys_pip_install is not defined -- name: ๐Ÿ” Resolve active Python executable for sys-pip-install - ansible.builtin.set_fact: - sys_pip_install_python_executable: "{{ ansible_python_interpreter }}" - changed_when: false - -- block: - - name: ๐Ÿ” Probe pip for ansible_python_interpreter accepts --break-system-packages - ansible.builtin.command: - argv: - - "{{ sys_pip_install_python_executable }}" - - -m - - pip - - install - - --break-system-packages - - --help - register: sys_pip_install_break_system_packages_probe - changed_when: false - failed_when: false - become: "{{ true if global_install | bool else false }}" - - - name: ๐Ÿ”ง Set fact for --break-system-packages support - ansible.builtin.set_fact: - sys_pip_install_supports_break_system_packages: "{{ (sys_pip_install_break_system_packages_probe.rc | int) == 0 }}" - changed_when: false - - when: global_install | bool - -- name: ๐Ÿ”Ž Check whether selected Python interpreter has 'packaging' - ansible.builtin.command: - argv: - - "{{ sys_pip_install_python_executable }}" - - -I - - -c - - import packaging - register: sys_pip_install_python_packaging_check - changed_when: false - failed_when: false - -- name: ๐Ÿฅพ Bootstrap 'packaging' for selected Python interpreter - ansible.builtin.command: - argv: >- - {{ - [sys_pip_install_python_executable, '-m', 'pip', 'install', '--upgrade', 'packaging'] - + ( - ['--break-system-packages'] - if (global_install | bool and sys_pip_install_supports_break_system_packages | default(false) | bool) - else [] - ) - }} +- name: ๐Ÿ“ฆ Install or upgrade {{ package_name }} system-wide via pip + ansible.builtin.pip: + name: "{{ package_name }}" + state: "{{ package_state }}" + extra_args: "{{ '--break-system-packages' if (global_install | bool and sys_pip_install_supports_break_system_packages | default(false) | bool) else omit }}" + virtualenv: "{{ omit if global_install | bool else (sys_pip_install_python_executable | dirname | dirname) }}" environment: >- {{ ( @@ -64,29 +21,6 @@ else omit }} become: "{{ true if global_install | bool else false }}" - register: sys_pip_install_packaging_bootstrap - retries: 5 - delay: 15 - until: sys_pip_install_packaging_bootstrap is succeeded - when: sys_pip_install_python_packaging_check.rc != 0 - -- name: ๐Ÿ“ฆ Install or upgrade {{ package_name }} system-wide via pip - ansible.builtin.pip: - name: "{{ package_name }}" - state: "{{ package_state }}" - extra_args: "{{ '--break-system-packages' if (global_install | bool and sys_pip_install_supports_break_system_packages | bool) else omit }}" - virtualenv: "{{ omit if global_install | bool else (sys_pip_install_python_executable | dirname | dirname) }}" - environment: >- - {{ - ( - {'PIP_BREAK_SYSTEM_PACKAGES': '1'} - if sys_pip_install_supports_break_system_packages | bool - else {} - ) - if global_install | bool - else omit - }} - become: "{{ true if global_install | bool else false }}" register: sys_pip_install_result retries: 5 delay: 15 diff --git a/roles/sys-service-loader/tasks/load_service.yml b/roles/sys-service-loader/tasks/load_service.yml index 3ee99cb3d2..9fc348e8f1 100644 --- a/roles/sys-service-loader/tasks/load_service.yml +++ b/roles/sys-service-loader/tasks/load_service.yml @@ -4,3 +4,4 @@ when: - lookup('vars', service_run_once_var, default='__missing__') == '__missing__' - (service_key in _required_service_ids) or (service_role in group_names) + - (_preload_closure | length == 0) or (service_role in _preload_closure) diff --git a/roles/sys-service-loader/tasks/main.yml b/roles/sys-service-loader/tasks/main.yml index ad3b2a5a52..b7360c5d40 100644 --- a/roles/sys-service-loader/tasks/main.yml +++ b/roles/sys-service-loader/tasks/main.yml @@ -40,6 +40,10 @@ | list }} +- name: "๐Ÿ” Scope the preload to the whitelist's dependency closure" + ansible.builtin.set_fact: + _preload_closure: "{{ lookup('application_closure', lookup('deployment').whitelist) }}" + - name: "๐Ÿ”Œ Load shared service" include_tasks: load_service.yml vars: diff --git a/roles/sys-service/handlers/refresh_systemctl_service.yml b/roles/sys-service/handlers/refresh_systemctl_service.yml index 879a7dd6e9..ac19505e55 100644 --- a/roles/sys-service/handlers/refresh_systemctl_service.yml +++ b/roles/sys-service/handlers/refresh_systemctl_service.yml @@ -2,9 +2,10 @@ - name: "๐Ÿ”ง Enable systemctl service" systemd: name: "{{ system_service_name }}" + scope: "{{ system_service_scope }}" enabled: true daemon_reload: true - become: true + become: "{{ system_service_unit_become }}" # rationale: async; opt-out per caller, a role that reads the unit state sets system_service_force_linear_sync async: "{{ system_service_async }}" poll: "{{ system_service_poll }}" @@ -12,8 +13,9 @@ - name: "๐Ÿ”ง Set systemctl service state" systemd: name: "{{ system_service_name }}" + scope: "{{ system_service_scope }}" state: "{{ system_service_state }}" - become: true + become: "{{ system_service_unit_become }}" # rationale: async; the Result gate below only runs meaningfully for callers that set system_service_force_linear_sync async: "{{ system_service_async }}" poll: "{{ system_service_poll }}" @@ -23,28 +25,14 @@ - name: ๐Ÿ” sys-service | Read unit Result (oneshot-safe) ansible.builtin.command: - argv: - - systemctl - - --no-pager - - show - - -p - - Result - - --value - - "{{ system_service_name }}" + argv: "{{ system_service_systemctl_show + ['Result', system_service_name] }}" register: system_service_result changed_when: false failed_when: false - name: ๐Ÿ” sys-service | Read unit ExecMainStatus (oneshot-safe) ansible.builtin.command: - argv: - - systemctl - - --no-pager - - show - - -p - - ExecMainStatus - - --value - - "{{ system_service_name }}" + argv: "{{ system_service_systemctl_show + ['ExecMainStatus', system_service_name] }}" register: system_service_exec_status changed_when: false failed_when: false diff --git a/roles/sys-service/tasks/06_service.yml b/roles/sys-service/tasks/06_service.yml index 639c21ba32..a89a63ad6d 100644 --- a/roles/sys-service/tasks/06_service.yml +++ b/roles/sys-service/tasks/06_service.yml @@ -28,10 +28,11 @@ - name: "๐Ÿ”ง setup systemctl '{{ system_service_id }}'" template: # nocheck: stack-host-template (per-host systemd service unit) src: "{{ system_service_template_src }}" - dest: "{{ [ DIR_SYSTEM_SERVICE, system_service_name ] | path_join }}" - owner: root - group: root + dest: "{{ [ system_service_unit_dir, system_service_name ] | path_join }}" + owner: "{{ system_service_unit_owner }}" + group: "{{ system_service_unit_owner }}" mode: "0644" + become: "{{ system_service_unit_become }}" notify: "{{ 'reload-system-daemon' if system_service_is_template | bool else 'refresh-systemctl-service' }}" - name: ๐Ÿ”„ refresh systemctl service when SYS_SERVICE_ALL_ENABLE diff --git a/roles/sys-service/tasks/07_timer.yml b/roles/sys-service/tasks/07_timer.yml index 1701ebaaf3..4814d6ad92 100644 --- a/roles/sys-service/tasks/07_timer.yml +++ b/roles/sys-service/tasks/07_timer.yml @@ -1,4 +1,14 @@ --- +- name: ๐Ÿ›‘ Fail if a timer is asked for outside the system scope + assert: + that: + - system_service_scope == 'system' + fail_msg: >- + '{{ system_service_id }}' asks for a timer in the '{{ system_service_scope }}' + scope, but sys-timer writes into {{ DIR_SYSTEM_SERVICE }} and drives the unit + in the system scope, so the timer would look for a service that only exists + for the user. + - name: ๐Ÿ›‘ Fail if system_service_id contains "@" assert: that: diff --git a/roles/sys-service/tasks/main.yml b/roles/sys-service/tasks/main.yml index ff13725fc0..c759025647 100644 --- a/roles/sys-service/tasks/main.yml +++ b/roles/sys-service/tasks/main.yml @@ -6,7 +6,9 @@ when: run_once_sys_service is defined - include_tasks: 00_core.yml - when: run_once_sys_service is not defined + when: + - run_once_sys_service is not defined + - system_service_scope == 'system' - name: "โ–ถ๏ธ Execute service routines for '{{ system_service_id }}'" block: diff --git a/roles/sys-service/templates/systemctl.service.j2 b/roles/sys-service/templates/systemctl.service.j2 index 4ec2bcb6b8..5f9a7dd7d1 100644 --- a/roles/sys-service/templates/systemctl.service.j2 +++ b/roles/sys-service/templates/systemctl.service.j2 @@ -1,6 +1,16 @@ [Unit] Description={{ SOFTWARE_NAME }} - Service for role '{{ system_service_id }}' -{{ system_service_tpl_on_failure | systemd_directive('OnFailure') }} +{% for key, val in [ + ('OnFailure', system_service_tpl_on_failure), + ('After', system_service_tpl_after), + ('Before', system_service_tpl_before), + ('Wants', system_service_tpl_wants), +] %} +{% set directive = val | systemd_directive(key) %} +{% if directive %} +{{ directive }} +{% endif %} +{% endfor %} StartLimitIntervalSec=60 StartLimitBurst=3 OnFailureJobMode=replace-irreversibly @@ -10,13 +20,21 @@ Type={{ system_service_tpl_type }} {% for _environment in system_service_tpl_environment %} Environment={{ _environment }} {% endfor %} - {% for key, val in [ + ('RemainAfterExit', system_service_tpl_remain_after_exit), ('TimeoutStartSec', system_service_tpl_timeout_start_sec), ('ExecStartPre', system_service_tpl_exec_start_pre), ('ExecStart', system_service_tpl_exec_start), ('ExecStartPost', system_service_tpl_exec_start_post), ('RuntimeMaxSec', system_service_tpl_runtime), ] %} -{{ val | systemd_directive(key) }} +{% set directive = val | systemd_directive(key) %} +{% if directive %} +{{ directive }} +{% endif %} {% endfor %} +{% if system_service_tpl_wanted_by | length > 0 %} + +[Install] +WantedBy={{ system_service_tpl_wanted_by }} +{% endif %} diff --git a/roles/sys-service/vars/main.yml b/roles/sys-service/vars/main.yml index 2a91e808bf..24b8e3fae9 100644 --- a/roles/sys-service/vars/main.yml +++ b/roles/sys-service/vars/main.yml @@ -4,6 +4,12 @@ UNIT_SUFFIX_REMOVER_PACKAGE: "unsure" system_service_name: "{{ lookup('unit_name', system_service_id) }}" system_service_is_template: "{{ system_service_id.endswith('@') }}" +system_service_scope: "system" # 'system' for root units, 'user' for per-login units +system_service_unit_dir: "{{ DIR_SYSTEM_SERVICE if system_service_scope == 'system' else DIR_SYSTEM_SERVICE_USER }}" +system_service_unit_owner: "{{ 'root' if system_service_scope == 'system' else omit }}" +system_service_unit_become: "{{ system_service_scope == 'system' }}" +system_service_systemctl_show: "{{ ['systemctl'] + (['--user'] if system_service_scope == 'user' else []) + ['--no-pager', 'show', '--value', '-p'] }}" + system_service_role_name: "{{ system_service_id | regex_replace('@','') }}" system_service_role_dir: "{{ lookup('path_absolute', 'roles', system_service_role_name) }}" system_service_script_dir: "{{ [ DIR_SCRIPTS_SYSTEMCTL, system_service_id ] | path_join }}" @@ -25,7 +31,12 @@ system_service_script_inter: "{{ '/bin/bash' if system_service_script_type == 's system_service_script_exec: "{{ system_service_script_inter }} {{ system_service_id | get_service_script_path( system_service_script_type ) }}" system_service_tpl_on_failure: "{{ SYS_SERVICE_ON_FAILURE_COMPOSE }}" +system_service_tpl_after: "" +system_service_tpl_before: "" +system_service_tpl_wants: "" system_service_tpl_type: "oneshot" +system_service_tpl_remain_after_exit: "" +system_service_tpl_wanted_by: "" # Empty installs no [Install] section, which leaves the unit static system_service_tpl_environment: [] # Environment variables system_service_tpl_runtime: "{{ '' if system_service_tpl_type == 'oneshot' else SYS_SERVICE_DEFAULT_RUNTIME }}" system_service_tpl_exec_start_pre: "" diff --git a/roles/sys-stk-backend/tasks/main.yml b/roles/sys-stk-backend/tasks/main.yml index 7f0cdcfab9..4b7ad305d7 100644 --- a/roles/sys-stk-backend/tasks/main.yml +++ b/roles/sys-stk-backend/tasks/main.yml @@ -59,6 +59,19 @@ include_tasks: "{{ lookup('path_absolute', 'roles/web-app-keycloak/tasks/sso_proxy.yml') }}" when: lookup('sso', application_id, 'is_proxy_gated') | bool +- name: "๐Ÿ“‚ For '{{ application_id }}': re-own the compose handler topics before the flush" + ansible.builtin.include_role: + name: sys-svc-compose + tasks_from: none.yml + handlers_from: main + - name: "๐Ÿšฟ flush compose and SSO proxy" meta: flush_handlers when: compose_handlers_flush | bool + +- name: "๐Ÿ”‘ For '{{ application_id }}': realign a dedicated postgres" + include_tasks: + file: "{{ lookup('path_absolute', 'roles/sys-svc-rdbms/tasks/utils/realign_dedicated_db.yml') }}" + apply: + delegate_to: "{{ STACK_HOST }}" + run_once: true diff --git a/roles/sys-stk-front-base/tasks/01_cloudflare.yml b/roles/sys-stk-front-base/tasks/01_cloudflare.yml index a2b3c04b48..bcf2805402 100644 --- a/roles/sys-stk-front-base/tasks/01_cloudflare.yml +++ b/roles/sys-stk-front-base/tasks/01_cloudflare.yml @@ -42,7 +42,10 @@ - cf_zone_lookup_dev.json.result | length == 0 - name: ๐ŸŸข activate cloudflare cache development mode - include_tasks: "cloudflare/01_enable_cf_dev_mode.yml" + include_tasks: + file: "cloudflare/01_enable_cf_dev_mode.yml" + apply: + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" when: (ENVIRONMENT | lower) == 'development' - name: ๐Ÿงน purge cloudflare domain cache diff --git a/roles/sys-stk-front-base/tasks/cloudflare/02_cleanup.yml b/roles/sys-stk-front-base/tasks/cloudflare/02_cleanup.yml index 07e24cd8d8..a37e1049c0 100644 --- a/roles/sys-stk-front-base/tasks/cloudflare/02_cleanup.yml +++ b/roles/sys-stk-front-base/tasks/cloudflare/02_cleanup.yml @@ -1,5 +1,6 @@ --- - name: "๐Ÿงน Purge everything from Cloudflare cache for domain {{ domain }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" uri_retry: url: "https://api.cloudflare.com/client/v4/zones/{{ cf_zone_id }}/purge_cache" method: POST diff --git a/roles/sys-stk-front-proxy/defaults/main.yml b/roles/sys-stk-front-proxy/defaults/main.yml index 925ef14284..34d6e60c50 100644 --- a/roles/sys-stk-front-proxy/defaults/main.yml +++ b/roles/sys-stk-front-proxy/defaults/main.yml @@ -1,3 +1,4 @@ --- # default vhost flavour webserver_vhost_flavour: "basic" # valid: basic, ws_generic +front_proxy_stale_config_status_codes: [-1, 404] diff --git a/roles/sys-stk-front-proxy/tasks/main.yml b/roles/sys-stk-front-proxy/tasks/main.yml index 2cb4d2bb1e..2ee080d001 100644 --- a/roles/sys-stk-front-proxy/tasks/main.yml +++ b/roles/sys-stk-front-proxy/tasks/main.yml @@ -45,6 +45,12 @@ }} changed_when: false +- name: ๐ŸงŠ Freeze the probe target for this vhost + ansible.builtin.set_fact: + front_proxy_probe_url: "{{ lookup('tls', front_proxy_domain, 'url.base') }}" + front_proxy_status_codes: "{{ lookup('applications') | accepted_status_codes(front_proxy_application_id, lookup('tls', front_proxy_domain, 'domain')) }}" + changed_when: false + - name: ๐Ÿ“‚ Include dependencies include_role: name: "sys-svc-nss" @@ -103,24 +109,21 @@ notify: reload-openresty - block: - - name: "๐Ÿ” Check if {{ lookup('domain', front_proxy_application_id) }} is reachable" + - name: "๐Ÿ” Check if '{{ front_proxy_domain }}' is reachable" uri_probe: - url: "{{ lookup('tls', front_proxy_application_id, 'url.base') }}" - status_code: - - 200 - - 301 - - 302 + url: "{{ front_proxy_probe_url }}" + status_code: "{{ front_proxy_status_codes }}" register: site_check failed_when: false changed_when: false - - name: ๐Ÿ”„ Restart NGINX if site is down + - name: "๐Ÿ”„ Redeploy: site answered {{ site_check.status | default('none') }}" ansible.builtin.command: cmd: "true" notify: restart-openresty when: - - site_check.status is defined - - site_check.status not in [200, 301, 302] + - site_check.status | default(-1) not in front_proxy_status_codes + - site_check.status | default(-1) in front_proxy_stale_config_status_codes when: not nginx_conf.changed - name: "๐Ÿ”„ Restart Webserver for '{{ front_proxy_domain_conf_dst_resolved }}'" @@ -128,24 +131,23 @@ - name: "๐Ÿ” Verify '{{ front_proxy_domain }}' is served after the reload" uri_probe: - url: "{{ lookup('tls', front_proxy_application_id, 'url.base') }}" - status_code: - - 200 - - 301 - - 302 + url: "{{ front_proxy_probe_url }}" + status_code: "{{ front_proxy_status_codes }}" register: front_proxy_reload_check failed_when: false changed_when: false when: nginx_conf.changed -- name: ๐Ÿ”„ Fall back to a full redeploy when the reload did not take +- name: "๐Ÿ”„ Redeploy: reload left {{ front_proxy_reload_check.status | default('none') }}" ansible.builtin.command: cmd: "true" notify: restart-openresty when: - nginx_conf.changed - - front_proxy_reload_check.status is defined - - front_proxy_reload_check.status not in [200, 301, 302] + - front_proxy_reload_check.status | default(-1) not in front_proxy_status_codes + - >- + not openresty_reload.changed + or front_proxy_reload_check.status | default(-1) in front_proxy_stale_config_status_codes - name: "๐Ÿ”„ Flush the fallback redeploy for '{{ front_proxy_domain }}'" ansible.builtin.meta: flush_handlers diff --git a/roles/sys-svc-certbot/tasks/01_no_webroot.yml b/roles/sys-svc-certbot/tasks/01_no_webroot.yml index 05c0b050a1..41d4e73540 100644 --- a/roles/sys-svc-certbot/tasks/01_no_webroot.yml +++ b/roles/sys-svc-certbot/tasks/01_no_webroot.yml @@ -13,6 +13,7 @@ mode: "0755" - name: ๐Ÿ“ฆ Install plugin credentials file + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" copy: dest: "{{ CERTBOT_CREDENTIALS_FILE }}" content: | diff --git a/roles/sys-svc-compose-ca/files/python/compose_ca.py b/roles/sys-svc-compose-ca/files/python/compose_ca.py index 7a0ec19938..e406bf1dc8 100755 --- a/roles/sys-svc-compose-ca/files/python/compose_ca.py +++ b/roles/sys-svc-compose-ca/files/python/compose_ca.py @@ -534,6 +534,21 @@ def _cache_frontend_ca_host() -> str: return "" +def _trust_bundle_host(ca_host: str) -> str: + """Host path of the CA bundle sys-ca-selfsigned builds beside the root CA, or ''. + + SSL_CERT_FILE, CURL_CA_BUNDLE and REQUESTS_CA_BUNDLE replace the trust + store rather than extend it, so a container pointed at the root CA alone + cannot verify a public certificate. Returning '' when the bundle is absent + keeps a host that has not built one yet on the previous behaviour instead + of binding a missing path, which Docker would materialise as a directory. + """ + bundle = Path(ca_host).parent / "ca-bundle.crt" + if bundle.is_file() and bundle.stat().st_size > 0: + return str(bundle) + return "" + + def render_override( services: dict[str, Any], service_to_compose_cmd: dict[str, list[str]], @@ -570,6 +585,7 @@ def render_override( """ out_services: dict[str, Any] = {} extra_ca_host = _cache_frontend_ca_host() + bundle_host = _trust_bundle_host(ca_host) image_meta = gather_image_meta( sorted( @@ -612,6 +628,12 @@ def render_override( "CURL_CA_BUNDLE": ca_container, "NODE_EXTRA_CA_CERTS": ca_container, } + if bundle_host: + bundle_container = str(Path(ca_container).parent / Path(bundle_host).name) + volumes.append(f"{bundle_host}:{bundle_container}:ro") + environment["SSL_CERT_FILE"] = bundle_container + environment["REQUESTS_CA_BUNDLE"] = bundle_container + environment["CURL_CA_BUNDLE"] = bundle_container if extra_ca_host: extra_ca_container = str(Path(ca_container).parent / "ca-trust-extra.crt") volumes.append(f"{extra_ca_host}:{extra_ca_container}:ro") diff --git a/roles/sys-svc-compose/files/shell/swarm/service_converged.sh b/roles/sys-svc-compose/files/shell/swarm/service_converged.sh index a4d8a973c7..33f1739fbb 100644 --- a/roles/sys-svc-compose/files/shell/swarm/service_converged.sh +++ b/roles/sys-svc-compose/files/shell/swarm/service_converged.sh @@ -3,17 +3,50 @@ set -euo pipefail : "${SERVICE:?SERVICE env var is required}" +fail() { + echo "${SERVICE}: $1" >&2 + exit 1 +} + +report_tasks() { + local ps rows + if ! ps=$(timeout 15 container service ps "$SERVICE" --no-trunc \ + --format '{{.Name}} {{.Node}} {{.DesiredState}} {{.CurrentState}} error={{.Error}}' 2>&1); then + printf '%s: service ps failed: %s\n' "${SERVICE}" "${ps}" >&2 + return 0 + fi + rows="$(printf '%s\n' "${ps}" | awk '!/error=$/ && n++ < 10')" + [ -n "${rows}" ] || return 0 + printf '%s\n' "${rows}" >&2 +} + +give_up() { + echo "${SERVICE}: $1" >&2 + report_tasks + exit 2 +} + +report_failed_tasks() { + echo "${SERVICE}: $1" >&2 + report_tasks + exit 1 +} + state=$(timeout 15 container service inspect "$SERVICE" \ --format '{{.UpdateStatus.State}}' 2>/dev/null) || state="" case "$state" in -"" | "" | completed | rollback_completed) ;; -*) exit 1 ;; +"" | "" | completed) ;; +rollback_started | rollback_completed) give_up "update was rolled back (UpdateStatus.State=${state}); the running spec is the previous one, not the desired one" ;; +paused | rollback_paused) give_up "update latched (UpdateStatus.State=${state}); it cannot leave this state on its own" ;; +*) fail "update in progress (UpdateStatus.State=${state})" ;; esac states=$(timeout 15 container service ps "$SERVICE" \ --filter desired-state=running \ - --format '{{.CurrentState}}') -[ -n "$states" ] || exit 1 -if printf '%s\n' "$states" | grep -qvE '^Running'; then - exit 1 + --format '{{.CurrentState}}') || fail "service ps failed or timed out" +if [ -z "$states" ]; then + fail "no task carries desired-state=running" +fi +if grep -qvE '^Running' <<<"$states"; then + report_failed_tasks "tasks not running yet" fi diff --git a/roles/sys-svc-compose/files/shell/swarm/stack_ready.sh b/roles/sys-svc-compose/files/shell/swarm/stack_ready.sh index 72caf11cb3..d6878638a1 100755 --- a/roles/sys-svc-compose/files/shell/swarm/stack_ready.sh +++ b/roles/sys-svc-compose/files/shell/swarm/stack_ready.sh @@ -3,6 +3,8 @@ set -euo pipefail : "${STACK:?STACK env var is required}" : "${FATAL_GRACE:?FATAL_GRACE env var is required}" +: "${DEPLOY_SINCE:=}" +: "${DEPLOYED_SERVICES:=}" is_completed_oneshot() { local ps @@ -32,8 +34,6 @@ report_tasks() { report_task_states "$1" } -# Exception: `docker service ps` renders CurrentState as prose ("Preparing 3 minutes ago"), which -# cannot distinguish an image still extracting from a task idling on something else. report_task_states() { local ids inspect if ! ids=$(timeout 15 docker service ps --no-trunc --format '{{.ID}}' "$1" 2>/dev/null); then @@ -80,16 +80,105 @@ has_fatal_task() { ' <<<"$ps" } +inspect_update_states() { + timeout 15 docker service inspect \ + --format '{{.Spec.Name}} {{if .UpdateStatus}}{{.UpdateStatus.State}}{{else}}none{{end}} {{with .UpdateStatus}}{{with .StartedAt}}{{.Unix}}{{else}}-{{end}}{{else}}-{{end}}' \ + "$@" 2>/dev/null && return 0 + timeout 15 docker service inspect \ + --format '{{.Spec.Name}} {{if .UpdateStatus}}{{.UpdateStatus.State}}{{else}}none{{end}} -' \ + "$@" 2>/dev/null +} + +started_before_deploy() { + case "${DEPLOY_SINCE}${1}" in + '' | *[!0-9]*) return 1 ;; + esac + [ "$1" -lt "$DEPLOY_SINCE" ] +} + +deploy_touched() { + case " ${DEPLOYED_SERVICES} " in + *" $1 "*) return 0 ;; + *) return 1 ;; + esac +} + +running_current_spec() { + local states + states=$(timeout 15 docker service ps "$1" \ + --filter desired-state=running \ + --format '{{.CurrentState}}' 2>/dev/null) || return 1 + printf '%s\n' "$states" | awk '/^Running/ { n++ } END { print n + 0 }' +} + if ! services=$(timeout 15 docker stack services --format '{{.Name}} {{.Replicas}}' "$STACK"); then echo "not converged: docker stack services failed or timed out for ${STACK}" >&2 exit 1 fi +mapfile -t service_names < <(printf '%s\n' "$services" | awk 'NF {print $1}') +latched="" +updating="" +unknown="" +if [ ${#service_names[@]} -gt 0 ]; then + if ! update_states=$(inspect_update_states "${service_names[@]}"); then + sleep 2 + if ! update_states=$(inspect_update_states "${service_names[@]}"); then + echo "not converged: docker service inspect failed or timed out twice for ${STACK}" >&2 + exit 1 + fi + fi + while read -r name state started; do + [ -n "$name" ] || continue + if [ "$state" = "completed" ] && started_before_deploy "$started" && + deploy_touched "$name"; then + updating="${updating} ${name}(pending)" + continue + fi + case "$state" in + none | completed) ;; + paused | rollback_paused | rollback_started | rollback_completed) + latched="${latched} ${name}(${state})" + ;; + updating) + updating="${updating} ${name}(${state})" + ;; + *) + unknown="${unknown} ${name}(${state})" + ;; + esac + done <<<"$update_states" +fi + +if [ -n "$latched" ]; then + echo "update latched:${latched}; it cannot leave this state without another stack deploy" >&2 + printf '%s\n' "$latched" | tr ' ' '\n' | sed 's/(.*//' | while read -r svc; do + [ -n "$svc" ] || continue + report_tasks "$svc" + done + exit 2 +fi + +if [ -n "$unknown" ]; then + echo "not converged: unrecognised update state, treated as in flight:${unknown}" >&2 + updating="${updating}${unknown}" +fi + +if [ -n "$updating" ]; then + echo "not converged: rolling update still in flight:${updating}" >&2 + printf '%s\n' "$updating" | tr ' ' '\n' | sed 's/(.*//' | while read -r svc; do + [ -n "$svc" ] || continue + report_tasks "$svc" + done + exit 1 +fi + not_running="" while read -r name reps; do [ -n "$name" ] || continue if awk -v r="$reps" 'BEGIN { split(r, a, "/"); exit (a[1] == a[2]) ? 0 : 1 }'; then - continue + desired=$(awk -v r="$reps" 'BEGIN { split(r, a, "/"); print a[2] }') + [ "$(running_current_spec "$name")" = "$desired" ] && continue fi is_completed_oneshot "$name" && continue not_running="$not_running $name" @@ -110,3 +199,10 @@ if [ -n "$not_running" ]; then fi exit 1 fi + +printf '%s\n' "$services" | sed 's/^/ converged: /' >&2 +if [ ${#service_names[@]} -gt 0 ]; then + for svc in "${service_names[@]}"; do + report_task_states "$svc" + done +fi diff --git a/roles/sys-svc-compose/handlers/compose.yml b/roles/sys-svc-compose/handlers/compose.yml index 9b6a4fe3e7..416639c3e8 100644 --- a/roles/sys-svc-compose/handlers/compose.yml +++ b/roles/sys-svc-compose/handlers/compose.yml @@ -86,6 +86,16 @@ listen: - compose-build +- name: "๐ŸŒ compose: pre-create external provider networks for the stack" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/network/create.yml') }}" + vars: + network_role_id: "{{ external_network_role }}" + loop: "{{ lookup('compose_external_networks') }}" + loop_control: + loop_var: external_network_role + listen: + - compose-up + - name: ๐Ÿณ compose up ansible.builtin.shell: | set -euo pipefail diff --git a/roles/sys-svc-compose/handlers/swarm.yml b/roles/sys-svc-compose/handlers/swarm.yml index 620e498a3d..facdcd8727 100644 --- a/roles/sys-svc-compose/handlers/swarm.yml +++ b/roles/sys-svc-compose/handlers/swarm.yml @@ -143,7 +143,8 @@ - name: "๐Ÿš€ swarm: docker stack deploy" ansible.builtin.shell: | set -euo pipefail - docker stack deploy \ + date -u +%s + timeout {{ lookup('timeout', swarm_stack_converge_retries | int) | int }} docker stack deploy \ {{ lookup('compose_file_args', application_id, flag='--compose-file') }} \ --resolve-image never \ --prune \ @@ -165,11 +166,14 @@ environment: STACK: "{{ application_id | get_entity_name }}" FATAL_GRACE: "{{ swarm_stack_fatal_grace }}" + DEPLOY_SINCE: "{{ swarm_deploy_result.stdout_lines | default([]) | first | default('') }}" + DEPLOYED_SERVICES: "{{ swarm_deploy_result | swarm_deployed_services | join(' ') }}" register: _swarm_stack_ready_handler retries: "{{ swarm_stack_converge_retries }}" delay: 2 changed_when: false until: _swarm_stack_ready_handler.rc in [0, 2] + failed_when: _swarm_stack_ready_handler.rc != 0 listen: - compose-up - swarm-deploy @@ -180,7 +184,7 @@ ansible.builtin.shell: | set -euo pipefail docker stack services --format '{{ "{{.Name}}" }}' {{ application_id | get_entity_name | quote }} \ - | xargs -r -n1 docker service update --detach=false --force + | xargs -r -n1 timeout {{ lookup('timeout', 900) | int }} docker service update --detach=false --force args: executable: /bin/bash register: _swarm_force_recreate diff --git a/roles/sys-svc-compose/tasks/00_core.yml b/roles/sys-svc-compose/tasks/00_core.yml index c0d631675f..9e53702465 100644 --- a/roles/sys-svc-compose/tasks/00_core.yml +++ b/roles/sys-svc-compose/tasks/00_core.yml @@ -44,3 +44,11 @@ mode: "0755" owner: root group: root + +- name: "๐Ÿ›ก๏ธ Assert the NFS client mount is active on this swarm node" + ansible.builtin.command: "mountpoint -q {{ DIR_VAR_LIB }}" + changed_when: false + when: + - DEPLOYMENT_MODE == 'swarm' + - (storage.backend | default('local')) == 'nfs' + - (groups['svc-storage-nfs-server'] | default([])) | length > 0 diff --git a/roles/sys-svc-compose/tasks/utils/nfs_prep.yml b/roles/sys-svc-compose/tasks/utils/nfs_prep.yml index f22615d86d..f7f528da7b 100644 --- a/roles/sys-svc-compose/tasks/utils/nfs_prep.yml +++ b/roles/sys-svc-compose/tasks/utils/nfs_prep.yml @@ -19,19 +19,6 @@ - item.value.driver_opts is defined - application_id not in lookup('roles_with_placement', 'manager') -- name: "๐Ÿ›ก๏ธ Assert the NFS client mount is active on every swarm node" - ansible.builtin.command: "mountpoint -q {{ DIR_VAR_LIB }}" - changed_when: false - delegate_to: "{{ item }}" - run_once: true - loop: "{{ groups['svc-swarm-node'] | default([]) }}" - when: - - DEPLOYMENT_MODE == 'swarm' - - (storage.backend | default('local')) == 'nfs' - - (groups['svc-storage-nfs-server'] | default([])) | length > 0 - - (lookup('compose_volumes') | from_yaml).volumes | default({}) | length > 0 - - application_id not in lookup('roles_with_placement', 'manager') - - name: "๐Ÿ” Materialize NFS subdirs for '{{ application_id }}' on every swarm node" ansible.builtin.file: path: "{{ DIR_VAR_LIB }}/{{ item.0.value.name | default(item.0.key) }}" diff --git a/roles/sys-svc-compose/tasks/utils/post_deploy.yml b/roles/sys-svc-compose/tasks/utils/post_deploy.yml index 4359fe3863..b1974fbe00 100644 --- a/roles/sys-svc-compose/tasks/utils/post_deploy.yml +++ b/roles/sys-svc-compose/tasks/utils/post_deploy.yml @@ -13,6 +13,9 @@ - (compose_mode_force | default('') or DEPLOYMENT_MODE) == 'compose' - lookup('database', application_id, 'enabled') | bool +- name: "๐Ÿ”‘ For '{{ application_id }}': realign a dedicated postgres" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-rdbms/tasks/utils/realign_dedicated_db.yml') }}" + - name: "โณ Wait until swarm tasks of '{{ application_id | get_entity_name }}' are running" ansible.builtin.script: "{{ lookup('path_absolute', 'roles/sys-svc-compose/files/shell/swarm/stack_ready.sh') }}" environment: diff --git a/roles/sys-svc-compose/tasks/utils/swarm/wait_converged.yml b/roles/sys-svc-compose/tasks/utils/swarm/wait_converged.yml index 275bb63723..16e659009e 100644 --- a/roles/sys-svc-compose/tasks/utils/swarm/wait_converged.yml +++ b/roles/sys-svc-compose/tasks/utils/swarm/wait_converged.yml @@ -18,5 +18,6 @@ changed_when: false retries: "{{ wait_retries | default(600) }}" delay: "{{ wait_delay | default(2) }}" - until: _swarm_converged is succeeded + until: _swarm_converged.rc != 1 + failed_when: _swarm_converged.rc != 0 delegate_to: "{{ STACK_HOST }}" diff --git a/roles/sys-svc-container/files/shell/test-dns.sh b/roles/sys-svc-container/files/shell/test-dns.sh index 040e34c7e0..94deee3145 100644 --- a/roles/sys-svc-container/files/shell/test-dns.sh +++ b/roles/sys-svc-container/files/shell/test-dns.sh @@ -7,7 +7,6 @@ set -euo pipefail : "${BUSYBOX_IMAGE:?Missing Busybox image}" : "${NODE_IMAGE?Missing Node image; pass it empty to skip the getaddrinfo check}" -: "${DNS_IP:?Missing env DNS_IP}" : "${DOMAIN:?Missing env DOMAIN}" SUBDOMAIN="foo.${DOMAIN}" @@ -38,7 +37,7 @@ container info >/dev/null 2>&1 || fail "container info still failing after waiti section "Docker-in-Docker DNS (busybox: A + no SERVFAIL)" -container run --rm --dns "${DNS_IP}" "${BUSYBOX_IMAGE}" sh -lc " +container run --rm "${BUSYBOX_IMAGE}" sh -lc " set -e test_lookup_a() { @@ -76,7 +75,7 @@ if [ -z "${NODE_IMAGE}" ]; then else section "Docker-in-Docker DNS (node/getaddrinfo)" - container run --rm --dns "${DNS_IP}" "${NODE_IMAGE}" sh -lc " + container run --rm "${NODE_IMAGE}" sh -lc " set -e node -e \" const dns = require('dns'); diff --git a/roles/sys-svc-container/handlers/main.yml b/roles/sys-svc-container/handlers/main.yml index 8000f0e235..c3449ad67a 100644 --- a/roles/sys-svc-container/handlers/main.yml +++ b/roles/sys-svc-container/handlers/main.yml @@ -20,5 +20,4 @@ BUSYBOX_IMAGE: "{{ lookup('config', 'sys-svc-container', 'services.busybox.image') }}:{{ lookup('config', 'sys-svc-container', 'services.busybox.version') }}" NODE_IMAGE: "{{ '' if DEPLOYMENT_MODE == 'swarm' else lookup('config', 'sys-svc-container', 'services.node.image') ~ ':' ~ lookup('config', 'sys-svc-container', 'services.node.version') }}" - DNS_IP: "{{ networks.internet.dns }}" DOMAIN: "{{ DOMAIN_PRIMARY }}" diff --git a/roles/sys-svc-container/tasks/00_core.yml b/roles/sys-svc-container/tasks/00_core.yml index 8419562ec2..949f6f2999 100644 --- a/roles/sys-svc-container/tasks/00_core.yml +++ b/roles/sys-svc-container/tasks/00_core.yml @@ -43,6 +43,12 @@ include_tasks: "02_docker_in_docker.yml" when: DOCKER_IN_CONTAINER | bool +- name: ๐Ÿ”ง Configure docker daemon on a bare host that needs sandbox runtimes + include_tasks: "daemon_config.yml" + when: + - not (DOCKER_IN_CONTAINER | bool) + - "'svc-virt-kata' in group_names" + - name: ๐Ÿ”„ Restart and enable docker service meta: flush_handlers diff --git a/roles/sys-svc-container/tasks/02_docker_in_docker.yml b/roles/sys-svc-container/tasks/02_docker_in_docker.yml index 1eae0c6298..f75ea31050 100644 --- a/roles/sys-svc-container/tasks/02_docker_in_docker.yml +++ b/roles/sys-svc-container/tasks/02_docker_in_docker.yml @@ -31,11 +31,7 @@ changed_when: false - name: ๐Ÿ”ง Configure docker daemon storage driver (container) - ansible.builtin.template: # nocheck: stack-host-template (per-host docker daemon config, runs on every container-host) - src: daemon.json.j2 - dest: "{{ SYS_SVC_DOCKER_DAEMON }}" - mode: "0644" - notify: container-manager-restart + include_tasks: "daemon_config.yml" - name: ๐Ÿ”Ž Check if TCP MSS clamp to PMTU is already present (container) ansible.builtin.command: diff --git a/roles/sys-svc-container/tasks/_mtu.yml b/roles/sys-svc-container/tasks/_mtu.yml index df6e550fab..f7972ff789 100644 --- a/roles/sys-svc-container/tasks/_mtu.yml +++ b/roles/sys-svc-container/tasks/_mtu.yml @@ -3,7 +3,7 @@ include_role: name: sys-pip-install vars: - package_name: automtu + package_name: "automtu==1.1.1" global_install: true - name: โœ… Ensure 'ip' and 'ping' commands are available for automtu diff --git a/roles/sys-svc-container/tasks/daemon_config.yml b/roles/sys-svc-container/tasks/daemon_config.yml new file mode 100644 index 0000000000..070bab90b4 --- /dev/null +++ b/roles/sys-svc-container/tasks/daemon_config.yml @@ -0,0 +1,43 @@ +--- +- name: "๐Ÿ” Probe hardware virtualization" + ansible.builtin.stat: + path: /dev/kvm + register: sys_svc_container_kvm + +- name: "๐Ÿ” Probe the Kata shim" + ansible.builtin.stat: + path: "{{ KATA_SHIM_BINARY }}" + register: sys_svc_container_kata_shim + +- name: "๐Ÿ” Probe the gVisor shim" + ansible.builtin.stat: + path: "{{ RUNSC_SHIM_BINARY }}" + register: sys_svc_container_runsc_shim + +- name: "๐Ÿงฉ Publish the isolating runtime this host can carry" + ansible.builtin.set_fact: + SANDBOX_RUNTIME: >- + {{ + 'kata' + if ( + sys_svc_container_kvm.stat.exists + and sys_svc_container_kata_shim.stat.exists + and not (DOCKER_IN_CONTAINER | bool) + ) + else 'runsc' + }} + +- name: "๐Ÿ“ฃ Report the isolation tier" + ansible.builtin.debug: + msg: >- + /dev/kvm {{ 'present' if sys_svc_container_kvm.stat.exists else 'absent' }}, + kata shim {{ 'present' if sys_svc_container_kata_shim.stat.exists else 'absent' }}, + gVisor shim {{ 'present' if sys_svc_container_runsc_shim.stat.exists else 'absent' }}, + docker-in-docker {{ DOCKER_IN_CONTAINER | bool }} -> {{ SANDBOX_RUNTIME }} + +- name: "๐Ÿ”ง Configure the container daemon" + ansible.builtin.template: # nocheck: stack-host-template (per-host docker daemon config, runs on every container-host) + src: daemon.json.j2 + dest: "{{ SYS_SVC_DOCKER_DAEMON }}" + mode: "0644" + notify: container-manager-restart diff --git a/roles/sys-svc-container/templates/daemon.json.j2 b/roles/sys-svc-container/templates/daemon.json.j2 index 5753844515..5fcda85fe7 100644 --- a/roles/sys-svc-container/templates/daemon.json.j2 +++ b/roles/sys-svc-container/templates/daemon.json.j2 @@ -18,9 +18,12 @@ {% endif %} "dns-search": ["{{ DOMAIN_PRIMARY }}"], "dns-opts": ["ndots:0"], + "default-address-pools": {{ NETWORK_DOCKER_ADDRESS_POOLS | tojson }}, "log-driver": "json-file", - "log-opts": {"max-size": "10m", "max-file": "2"}, + "log-opts": {"max-size": "10m", "max-file": "2"} +{% if DOCKER_IN_CONTAINER | bool %}, "storage-driver": "fuse-overlayfs" +{% endif %} {% if SYS_DOCKER_DAEMONM_MTU is defined and SYS_DOCKER_DAEMONM_MTU | int > 0 %}, "mtu": {{ SYS_DOCKER_DAEMONM_MTU | int }} {% endif %} @@ -34,4 +37,19 @@ {% if _cache_hosts | length > 0 %}, "registry-mirrors": ["http://{{ _cache_hosts[0] }}:{{ _cache_port }}"] {% endif %} +{% set _shim_paths = {'kata': KATA_SHIM_BINARY, 'runsc': RUNSC_SHIM_BINARY} %} +{% set _present = [] %} +{% if sys_svc_container_kata_shim.stat.exists %}{% set _ = _present.append('kata') %}{% endif %} +{% if sys_svc_container_runsc_shim.stat.exists %}{% set _ = _present.append('runsc') %}{% endif %} +{% if _present | length > 0 %}, + "runtimes": { +{% for _name in _present %} + "{{ _name }}": {"path": "{{ _shim_paths[_name] }}"{% if _name == 'runsc' and DOCKER_IN_CONTAINER | bool %}, "runtimeArgs": ["--network=host"]{% endif %}}{% if not loop.last %},{% endif %} + +{% endfor %} + } +{% if DEPLOYMENT_MODE == 'swarm' and not (IS_STACK_HOST | bool) and (SANDBOX_RUNTIME | trim) in _present %}, + "default-runtime": "{{ SANDBOX_RUNTIME | trim }}" +{% endif %} +{% endif %} } diff --git a/roles/sys-svc-container/templates/deploy.yml.j2 b/roles/sys-svc-container/templates/deploy.yml.j2 index b37d19113a..6d6e6586ce 100644 --- a/roles/sys-svc-container/templates/deploy.yml.j2 +++ b/roles/sys-svc-container/templates/deploy.yml.j2 @@ -1,10 +1,38 @@ {% if compose_mode == 'swarm' %} {{ "\n" }} +{% if service_replicas_forced is defined %} +{% set _replicas = service_replicas_forced %} +{% else %} {% set _replicas = lookup('applications') | resource_filter(application_id, 'replicas', service_name | default(''), '') %} - {{ lookup('container_deploy', replicas=_replicas) | indent(4) }} +{% endif %} + deploy: + {{ lookup('compose_replicas', _replicas) if _replicas != '' else lookup('compose_replicas') }} +{% set _constraints = [] %} +{% if application_id in lookup('roles_with_placement', 'manager') %} +{% set _ = _constraints.append('node.role == manager') %} +{% endif %} +{% set _arch = lookup('applications') | resource_filter(application_id, 'platform_arch', service_name | default(''), '') %} +{% if _arch != '' %} +{% set _ = _constraints.append('node.platform.arch == ' ~ _arch) %} +{% endif %} +{% if groups['svc-virt-kata'] is defined %} +{% if lookup('config', application_id, 'services.kata.enabled', false) | bool %} +{% set _ = _constraints.append('node.labels.' ~ SANDBOX_NODE_LABEL ~ ' == true') %} +{% else %} +{% set _ = _constraints.append('node.labels.' ~ SANDBOX_NODE_LABEL ~ ' != true') %} +{% endif %} +{% endif %} +{% if _constraints | length > 0 %} + placement: + constraints: +{% for _constraint in _constraints %} + - {{ _constraint }} +{% endfor %} +{% endif %} update_config: parallelism: {{ service_update_parallelism | default(1) }} delay: {{ service_update_delay | default('10s') }} + failure_action: continue {% if service_update_order is defined %} order: {{ service_update_order }} {% endif %} diff --git a/roles/sys-svc-engine/README.md b/roles/sys-svc-engine/README.md index 58fefdac8c..aa00e191f6 100644 --- a/roles/sys-svc-engine/README.md +++ b/roles/sys-svc-engine/README.md @@ -27,6 +27,6 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( ## Credits -Implemented by **Kevin Veen-Birkenbach**. +Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/sys-svc-mail-msmtp/templates/msmtprc.conf.j2 b/roles/sys-svc-mail-msmtp/templates/msmtprc.conf.j2 index 98c22ba93c..f703f5447d 100644 --- a/roles/sys-svc-mail-msmtp/templates/msmtprc.conf.j2 +++ b/roles/sys-svc-mail-msmtp/templates/msmtprc.conf.j2 @@ -10,7 +10,7 @@ auth {{ email.auth_mechanism }} tls_starttls {{ email.start_tls | on_off }} tls {{ email.tls | on_off }} {% if ca_injected %} -tls_trust_file {{ CA_TRUST.inject_cert_container }} +tls_trust_file {{ CA_TRUST.inject_bundle_container }} {% endif %} tls_host_override {{ email.host }} {% if smtp_target.endswith('.onion') %} diff --git a/roles/sys-svc-mail-smtp/tasks/enable.yml b/roles/sys-svc-mail-smtp/tasks/enable.yml index 2ac245a6ce..05f7bb5ef5 100644 --- a/roles/sys-svc-mail-smtp/tasks/enable.yml +++ b/roles/sys-svc-mail-smtp/tasks/enable.yml @@ -33,3 +33,9 @@ ansible.builtin.command: newaliases changed_when: false notify: restart-postfix + +- name: "๐Ÿš€ Ensure the local relay is listening" + ansible.builtin.systemd: + name: postfix + enabled: true + state: started diff --git a/roles/sys-svc-mcp-reconcile/README.md b/roles/sys-svc-mcp-reconcile/README.md new file mode 100644 index 0000000000..c927956d1e --- /dev/null +++ b/roles/sys-svc-mcp-reconcile/README.md @@ -0,0 +1,57 @@ +# sys-svc-mcp-reconcile + +## Description + +Post-application MCP convergence for every deployed client, run at the **end of the server stage** once all providers have provisioned and before anything reads the converged state. + +## Overview + +This role re-invokes each deployed MCP client's own reconciliation from the complete provider set. + +## Cosmos + +The diagram places sys-svc-mcp-reconcile in the Infinito.Nexus cosmos: the components it deploys (capabilities), the central services it consumes (dependencies), and its outward reach (federation and bridged external networks). + +```mermaid +flowchart LR + subgraph role [sys-svc-mcp-reconcile ๐Ÿ’ป] + svc_svc_mcp_reconcile["svc-mcp-reconcile"] + end +``` + +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (๐Ÿ’ป host, ๐Ÿณ compose, ๐Ÿ swarm); โŒ marks a service that is explicitly turned off, and โš™๏ธ an Ansible role dependency declared in `meta/main.yml`. + +## Features + +- Converges every deployed MCP client from one complete provider set. +- Enumerates the clients from their own declarations, so a new client role joins by declaring one. +- Skips any client that is not deployed on this host, or whose `mcp` block is disabled or unshared. + +## How it works + +A provider writes its credential to the token store during its own role run, and each client resolves the providers it +may reach from that store. This role runs at the end of the server stage, after every provider has written and before +the end-to-end tests read the converged state. + +The client list comes from [`roles_with_service`](../../plugins/lookup/roles_with_service.py) with `topic='mcp'` and +`direction='client'`, which returns the roles on this host whose `meta/mcp.yml` declares a client side and is both +enabled and shared. Each is then included through the entrypoint every client role carries: + +```yaml +tasks_from: utils/mcp.yml +``` + +`tasks/utils/` is the repository's home for unnumbered, includable task files, so the entrypoint carries no step number. + +That file brings the client to its desired MCP state from scratch, so the same file serves the role's own run and this +one. `tests/lint/ansible/services/test_mcp_client_entrypoint.py` fails when a client role lacks it. + +## Further Resources + +- [Model Context Protocol](https://modelcontextprotocol.io/) + +## Credits + +Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. +Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). +Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/sys-svc-mcp-reconcile/meta/main.yml b/roles/sys-svc-mcp-reconcile/meta/main.yml new file mode 100644 index 0000000000..6c171aec4c --- /dev/null +++ b/roles/sys-svc-mcp-reconcile/meta/main.yml @@ -0,0 +1,30 @@ +--- +galaxy_info: + author: Kevin Veen-Birkenbach + description: End-of-play convergence of every deployed MCP client against the complete provider set + license: Infinito.Nexus Community License (Non-Commercial) + company: | + Kevin Veen-Birkenbach + https://www.veen.world + min_ansible_version: "2.9" + platforms: + - name: ArchLinux + versions: + - all + - name: Debian + versions: + - all + - name: EL + versions: + - all + - name: Fedora + versions: + - all + - name: Ubuntu + versions: + - all + galaxy_tags: + - mcp + - ai + - infinito +dependencies: [] diff --git a/roles/sys-svc-mcp-reconcile/meta/services.yml b/roles/sys-svc-mcp-reconcile/meta/services.yml new file mode 100644 index 0000000000..3c262ff847 --- /dev/null +++ b/roles/sys-svc-mcp-reconcile/meta/services.yml @@ -0,0 +1,4 @@ +--- +# nocheck: required-by-coverage invoked directly from the server stage, not consumed as a service +svc-mcp-reconcile: + lifecycle: beta diff --git a/roles/sys-svc-mcp-reconcile/tasks/main.yml b/roles/sys-svc-mcp-reconcile/tasks/main.yml new file mode 100644 index 0000000000..10857f9829 --- /dev/null +++ b/roles/sys-svc-mcp-reconcile/tasks/main.yml @@ -0,0 +1,32 @@ +--- +- name: "๐Ÿ”’ Stop excusing a provider whose credential never resolved" + ansible.builtin.set_fact: + MCP_RECONCILE_STRICT: true + +- name: "๐Ÿ” Find which MCP clients this deployment actually carries" + ansible.builtin.stat: + path: "{{ lookup('container', mcp_client.id, 'directories.instance') }}" + register: mcp_client_instances + loop: "{{ lookup('roles_with_service', 'mcp', topic='mcp', direction='client') }}" + loop_control: + loop_var: mcp_client + label: "{{ mcp_client.id }}" + changed_when: false + delegate_to: "{{ STACK_HOST }}" + +- name: "๐Ÿ”Œ Reconcile every MCP client against the complete provider set" + ansible.builtin.include_tasks: "utils/reconcile_one.yml" + vars: + application_id: "{{ mcp_client.id }}" + domain: "{{ lookup('domain', mcp_client.id) }}" + loop: "{{ mcp_client_instances.results | selectattr('stat.exists') | map(attribute='mcp_client') | list }}" + loop_control: + loop_var: mcp_client + label: "{{ mcp_client.id }}" + +- name: "๐Ÿšฟ Flush what the clients notified while they were still bound" + ansible.builtin.meta: flush_handlers + +- name: "๐Ÿ”“ Stop being strict once the reconciliation is over" + ansible.builtin.set_fact: + MCP_RECONCILE_STRICT: false diff --git a/roles/sys-svc-mcp-reconcile/tasks/utils/reconcile_one.yml b/roles/sys-svc-mcp-reconcile/tasks/utils/reconcile_one.yml new file mode 100644 index 0000000000..adc5fa42aa --- /dev/null +++ b/roles/sys-svc-mcp-reconcile/tasks/utils/reconcile_one.yml @@ -0,0 +1,14 @@ +--- +- name: "โ™ป๏ธ Bind the compose handlers to '{{ application_id }}' before it notifies" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'tasks/utils/load/handlers.yml') }}" + vars: + handler_role_name: "sys-svc-compose" + +- name: "๐Ÿ”Œ Reconcile '{{ application_id }}'" + ansible.builtin.include_role: + name: "{{ application_id }}" + tasks_from: utils/mcp.yml + public: false + +- name: "๐Ÿšฟ Flush what '{{ application_id }}' notified while it is still bound" + ansible.builtin.meta: flush_handlers diff --git a/roles/sys-svc-nss/README.md b/roles/sys-svc-nss/README.md index 671af07d49..6a12b47760 100644 --- a/roles/sys-svc-nss/README.md +++ b/roles/sys-svc-nss/README.md @@ -33,6 +33,6 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( ## Credits -Implemented by **Kevin Veen-Birkenbach**. +Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/sys-svc-objstore/README.md b/roles/sys-svc-objstore/README.md index 1f5d45a24d..8af2c6fb29 100644 --- a/roles/sys-svc-objstore/README.md +++ b/roles/sys-svc-objstore/README.md @@ -27,6 +27,6 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( ## Credits -Implemented by **Kevin Veen-Birkenbach**. +Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 b/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 index 8b9684a919..80d3b05a73 100644 --- a/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 +++ b/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 @@ -25,6 +25,12 @@ header_filter_by_lua_block { ngx.header.content_length = nil else ngx.ctx.is_html = false +{% if (lookup('config', application_id, 'services.tor.enabled', False) | bool) and (lookup('applications') | external_asset_origins(application_id, DOMAIN_PRIMARY)) %} + if lct:find("^text/css") and (ngx.var.http_host or ""):sub(-6) == ".onion" then + ngx.ctx.is_css = true + ngx.header.content_length = nil + end +{% endif %} end } diff --git a/roles/sys-svc-proxy/templates/location/html.conf.j2 b/roles/sys-svc-proxy/templates/location/html.conf.j2 index 91867318ae..b910730594 100644 --- a/roles/sys-svc-proxy/templates/location/html.conf.j2 +++ b/roles/sys-svc-proxy/templates/location/html.conf.j2 @@ -35,9 +35,9 @@ location {{location}} proxy_set_header Connection $connection_upgrade; proxy_connect_timeout 5s; - proxy_send_timeout 900s; - proxy_read_timeout 900s; - send_timeout 900s; + proxy_send_timeout {{ webserver_proxy_send_timeout | default('900s') }}; + proxy_read_timeout {{ webserver_proxy_read_timeout | default('900s') }}; + send_timeout {{ webserver_send_timeout | default('900s') }}; {% set proxy_lua_enabled = proxy_lua_enabled | default(true) | bool %} proxy_buffering {{ 'on' if proxy_lua_enabled else 'off' }}; diff --git a/roles/sys-svc-proxy/templates/location/media.conf.j2 b/roles/sys-svc-proxy/templates/location/media.conf.j2 index cae44dce04..3b359b5d93 100644 --- a/roles/sys-svc-proxy/templates/location/media.conf.j2 +++ b/roles/sys-svc-proxy/templates/location/media.conf.j2 @@ -8,5 +8,7 @@ location ~* \.(jpg|jpeg|png|gif|webp|ico|svg)$ { proxy_cache_valid 404 1m; add_header X-Proxy-Cache $upstream_cache_status; + {% include 'roles/sys-svc-proxy/templates/headers/identity_request_strips.conf.j2' %} + {% include 'roles/sys-svc-proxy/templates/headers/upstream_strips.conf.j2' %} } \ No newline at end of file diff --git a/roles/sys-svc-proxy/templates/location/upload.conf.j2 b/roles/sys-svc-proxy/templates/location/upload.conf.j2 index 41e28777af..8e0560b2f9 100644 --- a/roles/sys-svc-proxy/templates/location/upload.conf.j2 +++ b/roles/sys-svc-proxy/templates/location/upload.conf.j2 @@ -1,6 +1,8 @@ location {{ location_upload }} { {{ lookup('proxy_pass', application_id, proxy_service_key | default(application_id | get_entity_name), 'http', tail='plain', local_port=http_port, internal_port=proxy_internal_port | default('')) }} + {% include 'roles/sys-svc-proxy/templates/headers/identity_request_strips.conf.j2' %} + proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; diff --git a/roles/sys-svc-proxy/templates/location/ws.conf.j2 b/roles/sys-svc-proxy/templates/location/ws.conf.j2 index 36cc0a216c..316610d1af 100644 --- a/roles/sys-svc-proxy/templates/location/ws.conf.j2 +++ b/roles/sys-svc-proxy/templates/location/ws.conf.j2 @@ -1,4 +1,6 @@ location {{ webserver_websocket_location }} { + {% include 'roles/sys-svc-proxy/templates/headers/identity_request_strips.conf.j2' %} + proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; diff --git a/roles/sys-svc-proxy/templates/mcp/directives.conf.j2 b/roles/sys-svc-proxy/templates/mcp/directives.conf.j2 new file mode 100644 index 0000000000..27b53bef02 --- /dev/null +++ b/roles/sys-svc-proxy/templates/mcp/directives.conf.j2 @@ -0,0 +1,4 @@ + limit_req zone={{ mcp_zone }}_req burst={{ mcp_limits.concurrent_requests }} nodelay; + limit_conn {{ mcp_zone }}_conn {{ mcp_limits.concurrent_requests }}; + limit_req_status 429; + limit_conn_status 429; diff --git a/roles/sys-svc-proxy/templates/mcp/vhost.conf.j2 b/roles/sys-svc-proxy/templates/mcp/vhost.conf.j2 new file mode 100644 index 0000000000..5b4385afe2 --- /dev/null +++ b/roles/sys-svc-proxy/templates/mcp/vhost.conf.j2 @@ -0,0 +1,35 @@ +{% set mcp_endpoint_path = lookup('config', application_id, 'mcp.endpoint.path', '') %} +{% set mcp_upstream_path = lookup('config', application_id, 'mcp.adapter.upstream_path', '') %} +{% if mcp_endpoint_path or mcp_upstream_path %} +{% set mcp_public = lookup('config', application_id, 'mcp.exposure', '') == 'public' + and lookup('config', application_id, 'mcp.enabled', false) | bool %} +{% set mcp_acl_gated = lookup('sso', application_id, 'is_proxy_gated') + and (lookup('sso', application_id, 'oauth2_acl') | length) %} +{% set mcp_served = (mcp_endpoint_path | regex_replace('/+$', '')) if (mcp_public and not mcp_acl_gated) else '' %} +{% if mcp_served %} +{% set mcp_limits = lookup('config', application_id, 'mcp.limits') %} +{% set mcp_zone = 'mcp_' ~ (application_id | replace('-', '_')) %} +{% set sso_proxy_enabled = lookup('sso', application_id, 'is_proxy_gated') %} +{% set location = mcp_served %} +{% set webserver_client_max_body_size = mcp_limits.request_bytes %} +{% set webserver_proxy_send_timeout = mcp_limits.timeout_seconds ~ 's' %} +{% set webserver_proxy_read_timeout = mcp_limits.stream_seconds ~ 's' %} +{% set webserver_send_timeout = mcp_limits.stream_seconds ~ 's' %} +{% set webserver_location_extra_configuration %}{% include 'roles/sys-svc-proxy/templates/mcp/directives.conf.j2' %}{% endset %} +{% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} +{% endif %} +{% for hidden in [mcp_upstream_path, mcp_endpoint_path] | map('regex_replace', '/+$', '') | unique | select | list %} +{% if hidden != mcp_served %} +{% set routed = hidden | regex_replace('^/index\\.php', '') %} +{% if routed != hidden %} + location ~ ^(?:/index\.php)?{{ routed | regex_escape }}(?:$|/) { + return 404; + } +{% else %} + location {{ hidden }} { + return 404; + } +{% endif %} +{% endif %} +{% endfor %} +{% endif %} diff --git a/roles/sys-svc-proxy/templates/mcp/zones.conf.j2 b/roles/sys-svc-proxy/templates/mcp/zones.conf.j2 new file mode 100644 index 0000000000..dc7db2d812 --- /dev/null +++ b/roles/sys-svc-proxy/templates/mcp/zones.conf.j2 @@ -0,0 +1,4 @@ +{% set mcp_limits = lookup('config', application_id, 'mcp.limits') %} +{% set mcp_zone = 'mcp_' ~ (application_id | replace('-', '_')) %} +limit_req_zone $binary_remote_addr zone={{ mcp_zone }}_req:10m rate={{ mcp_limits.concurrent_requests }}r/s; +limit_conn_zone $binary_remote_addr zone={{ mcp_zone }}_conn:10m; diff --git a/roles/sys-svc-proxy/templates/vhost/basic.conf.j2 b/roles/sys-svc-proxy/templates/vhost/basic.conf.j2 index 16d0fe6257..17ec5d2ae9 100644 --- a/roles/sys-svc-proxy/templates/vhost/basic.conf.j2 +++ b/roles/sys-svc-proxy/templates/vhost/basic.conf.j2 @@ -56,4 +56,6 @@ server {% include 'roles/web-app-prometheus/templates/nginx/locations.conf.j2' %} + {% include 'roles/sys-svc-proxy/templates/mcp/vhost.conf.j2' %} + } diff --git a/roles/sys-svc-proxy/templates/vhost/ws_generic.conf.j2 b/roles/sys-svc-proxy/templates/vhost/ws_generic.conf.j2 index 19c88aac96..0d8e2bbd64 100644 --- a/roles/sys-svc-proxy/templates/vhost/ws_generic.conf.j2 +++ b/roles/sys-svc-proxy/templates/vhost/ws_generic.conf.j2 @@ -25,4 +25,6 @@ server { error_page 500 501 502 503 504 /500.html; {% include 'roles/web-app-prometheus/templates/nginx/locations.conf.j2' %} + + {% include 'roles/sys-svc-proxy/templates/mcp/vhost.conf.j2' %} } diff --git a/roles/sys-svc-rdbms/files/shell/patch_persisted_password.sh b/roles/sys-svc-rdbms/files/shell/patch_persisted_password.sh new file mode 100755 index 0000000000..0192dc7946 --- /dev/null +++ b/roles/sys-svc-rdbms/files/shell/patch_persisted_password.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Rewrite the database password an application persists inside its own config, +# on whichever node holds the volume. Every swarm node runs this; the ones +# without the volume, or without the config on it, leave without printing the +# marker, which is what the calling task reads as "changed". +# +# The password is injected here rather than left to the shell: the expression +# arrives as an environment variable, and a ${...} inside a variable's value is +# not expanded a second time. +# +# Param: PATCH_VOLUME - docker volume the app persists its config in +# Param: PATCH_CONFIG_REL - config path relative to that volume's mountpoint +# Param: PATCH_EXPRESSION - extended-regex sed expression (sed -E), with +# @PASSWORD@ where the value goes +# Param: PATCH_PASSWORD - the value, already escaped for the sed delimiter +# Param: PATCH_DATA_DIR - inventory-known backing directory, tried when the +# volume object does not name its own +set -euo pipefail + +: "${PATCH_VOLUME:?}" +: "${PATCH_CONFIG_REL:?}" +: "${PATCH_EXPRESSION:?}" +: "${PATCH_PASSWORD:?}" + +container volume ls -q -f "name=^${PATCH_VOLUME}$" | grep -q . || exit 0 + +opts="$(container volume inspect --format '{{if .Options}}{{.Options.o}}{{end}}' "$PATCH_VOLUME")" +case "$opts" in +*bind*) data_dir="$(container volume inspect --format '{{.Options.device}}' "$PATCH_VOLUME")" ;; +*) data_dir="$(container volume inspect --format '{{.Mountpoint}}' "$PATCH_VOLUME")" ;; +esac + +config="${data_dir}/${PATCH_CONFIG_REL}" +test -f "$config" || config="${PATCH_DATA_DIR:-}/${PATCH_CONFIG_REL}" +if [ ! -f "$config" ]; then + echo "SKIPPED: ${PATCH_CONFIG_REL} is under neither ${data_dir} nor ${PATCH_DATA_DIR:-};" \ + "a node holding ${PATCH_VOLUME} without its driver options reports the empty node-local path" + exit 0 +fi + +expression="${PATCH_EXPRESSION//@PASSWORD@/$PATCH_PASSWORD}" + +if [ -z "$(sed -E -n "${expression}p" "$config" | head -n1)" ]; then + echo "FAILED: no line in ${PATCH_CONFIG_REL} matches the patch expression" >&2 + exit 1 +fi + +sed -E -i "$expression" "$config" +echo PATCHED diff --git a/roles/sys-svc-rdbms/tasks/dedicated.yml b/roles/sys-svc-rdbms/tasks/dedicated.yml index 4c91b600be..c3039c0f29 100644 --- a/roles/sys-svc-rdbms/tasks/dedicated.yml +++ b/roles/sys-svc-rdbms/tasks/dedicated.yml @@ -1,4 +1,16 @@ --- +- name: "๐Ÿ“‚ For '{{ application_id }}': own the compose handler topic" + ansible.builtin.include_role: + name: sys-svc-compose + tasks_from: none.yml + handlers_from: main + +- name: "๐Ÿฅพ For '{{ application_id }}': bootstrap the compose host once" + ansible.builtin.include_role: + name: sys-svc-compose + tasks_from: 00_core.yml + when: run_once_sys_svc_compose is not defined + - name: "โœ… Ensure env dir exists: {{ _container_env_dir }}" ansible.builtin.file: path: "{{ _container_env_dir }}" @@ -11,6 +23,13 @@ dest: "{{ _database_env }}" notify: compose-up +- name: "๐Ÿ“„ Render the credential realignment for '{{ _database_consumer_id }}'" + stack_host_template: + src: "sql/mariadb-realign.sql.j2" + dest: "{{ lookup('database', _database_consumer_id, 'realign_sql') }}" + when: _database_type == 'mariadb' + notify: compose-up + - name: "๐Ÿ”ง For '{{ application_id }}/{{ _database_consumer_id }}': Apply postgres setup" include_tasks: dedicated_postgres.yml when: _database_type == 'postgres' diff --git a/roles/sys-svc-rdbms/tasks/main.yml b/roles/sys-svc-rdbms/tasks/main.yml index 05368e8d71..44a4a48027 100644 --- a/roles/sys-svc-rdbms/tasks/main.yml +++ b/roles/sys-svc-rdbms/tasks/main.yml @@ -26,6 +26,12 @@ - _sys_svc_rdbms_consumer_local | bool - _sys_svc_rdbms_compose_template.stat.exists +- name: "๐Ÿ”‘ Realign '{{ application_id }}' persisted password before the health gate" + ansible.builtin.include_tasks: "{{ _app_persisted_credentials }}" + vars: + _app_persisted_credentials: "{{ lookup('path_absolute', 'roles/' ~ application_id ~ '/tasks/utils/patch/db_credentials.yml') }}" + when: _app_persisted_credentials is exists + - name: ๐Ÿ—„๏ธ Central Database Logic block: - name: "โœ… For '{{ application_id }}': Assert shared database provider was preloaded" diff --git a/roles/sys-svc-rdbms/tasks/utils/patch_persisted_password.yml b/roles/sys-svc-rdbms/tasks/utils/patch_persisted_password.yml new file mode 100644 index 0000000000..0c42e1026f --- /dev/null +++ b/roles/sys-svc-rdbms/tasks/utils/patch_persisted_password.yml @@ -0,0 +1,17 @@ +--- +# Param: patch_volume - docker volume the app persists its config in +# Param: patch_config_rel - config path relative to that volume's mountpoint +# Param: patch_expression - sed expression, with @PASSWORD@ where the value goes +- name: "๐Ÿ”‘ Realign the persisted database password wherever {{ patch_volume }} lives" + ansible.builtin.script: "{{ lookup('path_absolute', 'roles/sys-svc-rdbms/files/shell/patch_persisted_password.sh') }}" + environment: + PATCH_VOLUME: "{{ patch_volume }}" + PATCH_CONFIG_REL: "{{ patch_config_rel }}" + PATCH_EXPRESSION: "{{ patch_expression }}" + PATCH_PASSWORD: "{{ lookup('database', application_id, 'password') | sed_escape('|') }}" + PATCH_DATA_DIR: "{{ [DIR_VAR_LIB, patch_volume] | path_join }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: patch_persisted + changed_when: "'PATCHED' in patch_persisted.stdout" + delegate_to: "{{ item }}" + loop: "{{ (groups['svc-swarm-node'] | default([])) or [inventory_hostname] }}" diff --git a/roles/sys-svc-rdbms/tasks/utils/realign_dedicated_db.yml b/roles/sys-svc-rdbms/tasks/utils/realign_dedicated_db.yml new file mode 100644 index 0000000000..256e53ae3e --- /dev/null +++ b/roles/sys-svc-rdbms/tasks/utils/realign_dedicated_db.yml @@ -0,0 +1,36 @@ +--- +- name: "๐Ÿ” Find the compose file rendering '{{ application_id }}'s own engine" + ansible.builtin.stat: + path: "{{ lookup('path_absolute', 'roles', application_id, 'templates/compose.yml.j2') }}" + register: _app_db_compose_template + delegate_to: localhost + run_once: true # nocheck: run-once the path is host-independent, one stat answers for the play + changed_when: false + when: (compose_mode_force | default('') or DEPLOYMENT_MODE) == 'compose' + +- name: "๐Ÿ”‘ Realign a dedicated postgres for '{{ application_id }}'" + when: + - (compose_mode_force | default('') or DEPLOYMENT_MODE) == 'compose' + - lookup('database', application_id, 'local') | bool + - lookup('database', application_id, 'type') == 'postgres' + - _app_db_compose_template.stat.exists | default(false) + block: + - name: "๐Ÿ” Find the running engine of '{{ application_id }}'" + ansible.builtin.command: >- + container ps -q + --filter name=^{{ lookup('database', application_id, 'container') }}$ + --filter status=running + register: _app_db_engine + changed_when: false + + - name: "๐Ÿ”‘ Realign the password a dedicated postgres kept from its initdb" + ansible.builtin.script: > # nocheck: container-address-quote script evals the fragment itself + {{ lookup('path_absolute', 'roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh') }} + {{ lookup('database', application_id, 'container') | quote }} + {{ lookup('database', application_id, 'password') | quote }} + {{ lookup('database', application_id, 'username') | quote }} + register: _app_db_realign + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + changed_when: _app_db_realign.stdout is search('\\[CHANGED\\]') + failed_when: _app_db_realign.rc != 0 or _app_db_realign.stdout is search('\\[FAIL\\]') + when: (_app_db_engine.stdout | trim) != '' diff --git a/roles/sys-svc-rdbms/templates/services/mariadb.yml.j2 b/roles/sys-svc-rdbms/templates/services/mariadb.yml.j2 index 517f14556d..0978769b1e 100644 --- a/roles/sys-svc-rdbms/templates/services/mariadb.yml.j2 +++ b/roles/sys-svc-rdbms/templates/services/mariadb.yml.j2 @@ -10,14 +10,20 @@ {{ lookup('compose_restart') }} env_file: - {{ lookup('database', application_id, 'env') }} - command: "--transaction-isolation=READ-COMMITTED --binlog-format=ROW" + command: "--transaction-isolation=READ-COMMITTED --binlog-format=ROW --init-file={{ lookup('database', application_id, 'realign_target') }}" + configs: + - source: {{ lookup('database', application_id, 'realign_config') }} + target: {{ lookup('database', application_id, 'realign_target') }} volumes: - database:/var/lib/mysql + # nocheck: container-healthcheck-literal shared partial rendered for the consuming role's application_id, so the declaration has no single meta/services.yml to live in healthcheck: test: [ "CMD", "sh", "-c", "/usr/bin/mariadb --user=$$MYSQL_USER --password=$$MYSQL_PASSWORD --execute 'SHOW DATABASES;'" ] - interval: 10s + interval: 2m timeout: 5s retries: 18 + start_period: 10m + start_interval: 5s networks: # nocheck: networks-literal local sidecar inside consumer stack, default-only attachment - default {% endif %} diff --git a/roles/sys-svc-rdbms/templates/services/postgres.yml.j2 b/roles/sys-svc-rdbms/templates/services/postgres.yml.j2 index 40e4bda426..caf5b6c390 100644 --- a/roles/sys-svc-rdbms/templates/services/postgres.yml.j2 +++ b/roles/sys-svc-rdbms/templates/services/postgres.yml.j2 @@ -20,10 +20,11 @@ {{ lookup('compose_restart') }} healthcheck: test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U {{ lookup('database', application_id, 'username') }}"] - interval: 10s + interval: 2m timeout: 5s retries: 6 - start_period: 60s + start_period: 10m + start_interval: 5s volumes: - type: volume source: database diff --git a/roles/sys-svc-rdbms/templates/sql/mariadb-realign.sql.j2 b/roles/sys-svc-rdbms/templates/sql/mariadb-realign.sql.j2 new file mode 100644 index 0000000000..571afad2de --- /dev/null +++ b/roles/sys-svc-rdbms/templates/sql/mariadb-realign.sql.j2 @@ -0,0 +1,2 @@ +ALTER USER IF EXISTS '{{ lookup('database', application_id, 'username') }}'@'%' + IDENTIFIED BY '{{ lookup('database', application_id, 'password') }}'; diff --git a/roles/sys-svc-webserver-core/tasks/00_core/manager_setup.yml b/roles/sys-svc-webserver-core/tasks/00_core/manager_setup.yml index 8cb3c83769..20f1c99fd7 100644 --- a/roles/sys-svc-webserver-core/tasks/00_core/manager_setup.yml +++ b/roles/sys-svc-webserver-core/tasks/00_core/manager_setup.yml @@ -16,6 +16,7 @@ include_tasks: "utils/load/app.yml" vars: load_app_id: svc-prx-openresty + compose_mode_force: "" - name: ๐Ÿš€ Deploy OpenResty NGINX Base Configuration stack_host_template: diff --git a/roles/sys-svc-webserver-core/tasks/utils/mcp_edge_limits.yml b/roles/sys-svc-webserver-core/tasks/utils/mcp_edge_limits.yml new file mode 100644 index 0000000000..1d5efaa56c --- /dev/null +++ b/roles/sys-svc-webserver-core/tasks/utils/mcp_edge_limits.yml @@ -0,0 +1,6 @@ +--- +- name: "๐Ÿšฆ Declare the MCP rate and connection zones of {{ application_id }}" + stack_host_template: + src: "roles/sys-svc-proxy/templates/mcp/zones.conf.j2" + dest: "{{ [lookup('nginx', 'directories.configuration.global'), 'mcp-' ~ application_id ~ '.conf'] | path_join }}" + notify: restart-openresty diff --git a/roles/sys-svc-webserver-core/templates/nginx.conf.j2 b/roles/sys-svc-webserver-core/templates/nginx.conf.j2 index 8fa6877d6a..7ee2aaa105 100644 --- a/roles/sys-svc-webserver-core/templates/nginx.conf.j2 +++ b/roles/sys-svc-webserver-core/templates/nginx.conf.j2 @@ -24,6 +24,7 @@ http proxy_cache_path {{ lookup('nginx','directories.cache.image') }} levels=1:2 keys_zone=imgcache:10m inactive=60m use_temp_path=off; server_names_hash_bucket_size 128; # size of each bucket for server_name lookups (in bytes) server_names_hash_max_size 512; # maximum total buckets for the server_name hash table +{% include 'roles/sys-svc-proxy/templates/headers/buffers.conf.j2' %} {% if MODE_DEBUG | bool %} log_format debug '$host - $remote_addr [$time_local] ' '"$request" $status $body_bytes_sent ' diff --git a/roles/sys-token-store/tasks/write.yml b/roles/sys-token-store/tasks/write.yml index 38b99108c4..51c6f5190f 100644 --- a/roles/sys-token-store/tasks/write.yml +++ b/roles/sys-token-store/tasks/write.yml @@ -51,3 +51,15 @@ run_once: true no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" become: true + +- name: "๐Ÿชž Mirror the store onto the controller, where every users lookup reads" + ansible.builtin.copy: + dest: "{{ FILE_TOKENS }}" + mode: "{{ SYS_TOKEN_STORE_FILE_MODE }}" + content: "{{ {'users': sys_token_store_users_merged} | to_nice_yaml(indent=2, width=9999) }}" + when: + - sys_token_store_users_merged != sys_token_store_users + - DEPLOYMENT_MODE == 'swarm' + delegate_to: localhost + run_once: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/test-e2e-cli/README.md b/roles/test-e2e-cli/README.md index f646eb08f1..1d05b63eb6 100644 --- a/roles/test-e2e-cli/README.md +++ b/roles/test-e2e-cli/README.md @@ -27,6 +27,6 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( ## Credits -Implemented by **Alejandro Roman Ibanez**. +Implemented by **[Alejandro Roman Ibanez](https://github.com/AlejandroRomanIbanez)**. Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/test-e2e-cli/files/shared/.nocheck b/roles/test-e2e-cli/files/shared/.nocheck new file mode 100644 index 0000000000..2db32cc447 --- /dev/null +++ b/roles/test-e2e-cli/files/shared/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Shared CLI harness staged as one tree by run_one.yml; contract.sh feeds contract.py from the same directory, so the two languages cannot be split apart. diff --git a/roles/test-e2e-cli/files/shared/mcp/contract.py b/roles/test-e2e-cli/files/shared/mcp/contract.py new file mode 100644 index 0000000000..4af0b34781 --- /dev/null +++ b/roles/test-e2e-cli/files/shared/mcp/contract.py @@ -0,0 +1,496 @@ +"""Prove one MCP provider actually honours its declared contract. + +Runs at deploy time, not in Playwright: the check needs the provider's real +credential, and a Playwright run would capture it in the trace. + +Over ``streamable_http`` it asserts, in order, that the endpoint + +1. refuses a caller presenting no credential, +2. refuses a caller presenting a wrong one, +3. completes an authenticated ``initialize`` handshake, +4. advertises exactly the tools the checked-in contract names, and +5. answers one deterministic read call without an error. + +Steps 1 and 2 are what separate a guarded endpoint from one that merely +happens to be unreachable today. Step 4 is what turns "the metadata says three +tools" into "the server serves three tools": an upstream that grew a fourth +fails here rather than in front of a client. + +For a provider with no adapter in front of it, step 4 is also the only runtime +evidence behind ``mutating_tools_enabled: false``, which nothing else enforces +there: relaxing it to a subset would let an upstream release add a mutating +tool while the metadata still promises none. + +Over ``sse`` the same five assertions hold, driven through a real session: +the stream is the response channel and the endpoint it announces is the +request channel. + +A provider whose credential is a path segment rather than a header is refused +by presenting a wrong segment, so the negative probes attack whatever actually +guards the endpoint. + +Environment: + MCP_URL: endpoint to probe. + MCP_TRANSPORT: ``streamable_http`` or ``sse``. + MCP_PATH_KEY: credential carried in the URL path, or "" for none. + MCP_AUTH_HEADER: Authorization header value the provider expects. + MCP_EXPECTED_TOOLS: JSON list of the exact tool names the platform permits. + MCP_UPSTREAM_SERVES: JSON list of what the upstream offers at the pinned + version, when that differs from the permitted set; "[]" when it does + not, so drift and policy are reported to different readers. + MCP_READ_TOOL: tool to invoke for the deterministic read. + MCP_READ_ARGUMENTS: JSON object of arguments for that tool. + MCP_HOST_HEADER: vhost to address a host-routed provider by, or "". +""" + +from __future__ import annotations + +import json +import os +import queue +import sys +import threading +import time +import urllib.error +import urllib.parse +import urllib.request + +URL = os.environ["MCP_URL"] +TRANSPORT = os.environ["MCP_TRANSPORT"] +PATH_KEY = os.environ.get("MCP_PATH_KEY", "") +AUTH = os.environ["MCP_AUTH_HEADER"] +EXPECTED = sorted(json.loads(os.environ.get("MCP_EXPECTED_TOOLS", "[]"))) +UPSTREAM_SERVES = sorted(json.loads(os.environ.get("MCP_UPSTREAM_SERVES", "[]"))) +READ_TOOL = os.environ.get("MCP_READ_TOOL", "") +READ_ARGUMENTS = json.loads(os.environ.get("MCP_READ_ARGUMENTS", "{}")) +HOST_HEADER = os.environ.get("MCP_HOST_HEADER", "") + +PROTOCOL_VERSION = "2025-06-18" +INITIALIZE = { + "protocolVersion": PROTOCOL_VERSION, + "capabilities": {}, + "clientInfo": {"name": "infinito-contract-probe", "version": "1"}, +} +TIMEOUT = 30 +SESSION_TIMEOUT = 20 +WRONG_CREDENTIAL = "Bearer " + "0" * 40 +SESSION_HEADER = "Mcp-Session-Id" + +SESSION = {"id": ""} + + +def unguarded_url(): + """Return the URL with its path credential replaced by a wrong one. + + A server that carries its credential in the path ignores the Authorization + header entirely, so varying the header would probe nothing and the negative + cases would answer exactly like the positive one. + """ + if not PATH_KEY: + return URL + head, separator, tail = URL.rpartition(PATH_KEY) + if not separator: + reject("the declared path credential is absent from the probed URL") + return head + "0" * len(PATH_KEY) + tail + + +def rpc(method, params=None, authorization=None, url=None, notification=False): + """Return ``(status, body)`` of one JSON-RPC call. + + Args: + method: MCP method name. + params: method params, or None. + authorization: header value to present, or None to present none. + url: endpoint to call, defaulting to the probed one. + notification: omit the id, so the server answers without a result. + """ + payload = {"jsonrpc": "2.0", "method": method} + if not notification: + payload["id"] = 1 + if params is not None: + payload["params"] = params + request = urllib.request.Request( # noqa: S310 fixed internal http origin + url or URL, data=json.dumps(payload).encode(), method="POST" + ) + request.add_header("Content-Type", "application/json") + request.add_header("Accept", "application/json, text/event-stream") + if HOST_HEADER: + request.add_header("Host", HOST_HEADER) + if authorization: + request.add_header("Authorization", authorization) + if SESSION["id"]: + request.add_header(SESSION_HEADER, SESSION["id"]) + try: + with urllib.request.urlopen(request, timeout=TIMEOUT) as response: # noqa: S310 fixed internal http origin + session = response.headers.get(SESSION_HEADER) + if session: + SESSION["id"] = session + return response.status, json_body( + response.headers.get("Content-Type", ""), + response.read().decode(errors="replace"), + ) + except urllib.error.HTTPError as error: + return error.code, json_body( + error.headers.get("Content-Type", ""), + error.read().decode(errors="replace"), + ) + except OSError as error: + return 0, f"unreachable: {error}" + + +def json_body(content_type, body): + """Return the JSON-RPC payload of one response, whatever framing it used. + + Args: + content_type: the response's Content-Type header. + body: its decoded body. + + Streamable HTTP lets a server answer a POST with an event stream instead of + a plain body, carrying the same JSON-RPC object in a ``data:`` line. Feeding + that framing straight to a JSON parser raises, which reads as a broken + server rather than as a different, permitted encoding. + """ + if "text/event-stream" not in content_type: + return body + for line in body.splitlines(): + if line.startswith("data:"): + return line.split(":", 1)[1].strip() + return body + + +def reject(message): + sys.stderr.write(f"REJECTED {message}\n") + sys.exit(1) + + +def reject_error(label, error): + if error: + reject(f"{label} returned {str(error)[:200]}") + + +def unreachable(message): + """Fail without the REJECTED marker, so the caller keeps retrying. + + A sidecar that has not finished starting is indistinguishable here from one + that will never answer. Marking the run REJECTED would settle the caller's + retry condition on the first attempt and turn a slow start into a failure. + """ + sys.stderr.write(f"UNREACHABLE {message}\n") + sys.exit(1) + + +def assert_read_call(status, body): + """Fail the read call, retrying while the provider itself is still starting. + + Args: + status: HTTP status the adapter answered with. + body: its response body. + + An adapter that answers 502 has reached the provider's port and been + refused, or has not reached it at all. Only the second case, and a provider + answering 5xx, are worth waiting for: a 4xx means the adapter's credential + or its contracted path is wrong and no amount of retrying fixes it. + """ + if status == 200: + return + upstream = 0 + try: + upstream = int( + ((json.loads(body).get("error") or {}).get("data") or {}).get( + "upstream_status", 0 + ) + ) + except (ValueError, AttributeError): + upstream = 0 + if (status == 502 and upstream >= 500) or (status == 502 and upstream == 0): + unreachable( + f"read call {READ_TOOL}: the provider answered {upstream or 'nothing'}" + ) + reject(f"read call {READ_TOOL} answered {status}: {body[:200]}") + + +def speaks_json_rpc(body): + """Return whether a body is the JSON object an MCP server would answer with. + + A server-side error page proves the endpoint is not serving yet, not that it + serves the unauthenticated. Treating a PHP fatal rendered as HTTP 200 as a + refusal verdict settles the caller's retry condition on the first attempt. + """ + try: + return isinstance(json.loads(body or "null"), dict) + except ValueError: + return False + + +def rpc_error(body): + """Return the JSON-RPC ``error`` object a response body carries, or None.""" + try: + payload = json.loads(body or "null") + except ValueError: + return None + return payload.get("error") if isinstance(payload, dict) else None + + +def refused(status, body): + """Return whether a response refused the caller rather than serving it. + + Args: + status: HTTP status of the response. + body: its JSON-RPC payload. + + JSON-RPC carries its own error channel, so a server may refuse a caller + with a transport-level 200 and an ``error`` object. Moodle does exactly + that. Demanding a 4xx would read a correct refusal as a served request. + """ + return status >= 400 or bool(rpc_error(body)) + + +def assert_refused(label, authorization, url=None): + """Prove one credential is refused, retrying while the endpoint is unserved. + + Args: + label: which credential is being presented, for the failure message. + authorization: the header value to present, or None. + url: endpoint to probe, defaulting to the module's URL. + """ + session_before = SESSION["id"] + try: + status, body = rpc( + "initialize", INITIALIZE, authorization=authorization, url=url + ) + finally: + SESSION["id"] = session_before + if status == 0: + unreachable(f"{label} probe could not reach {url or URL}: {body}") + if not 400 <= status < 500 and not speaks_json_rpc(body): + unreachable( + f"{label} probe answered {status} with no JSON-RPC body: {body[:200]}" + ) + if not refused(status, body): + reject(f"{label} probe answered {status}: {body[:200]}") + if '"tools"' in body: + reject(f"{label} probe disclosed the tool inventory") + + +class SseSession: + """One open SSE stream plus the message endpoint it announced. + + The stream is the response channel and the announced endpoint is the + request channel, so a call means: post to the endpoint, then read the + matching id off the stream that is already open. A reader thread is what + keeps the two from deadlocking, since the response to a POST can arrive on + the stream before the POST itself returns. + """ + + def __init__(self, url, authorization): + self.url = url + self.authorization = authorization + self.endpoint = None + self.status = 0 + self.content_type = "" + self.error = None + self._messages = queue.Queue() + self._announced = threading.Event() + self._response = None + self._reader = threading.Thread(target=self._read, daemon=True) + + def open(self): + """Start the stream and wait for its endpoint announcement.""" + self._reader.start() + self._announced.wait(SESSION_TIMEOUT) + return self + + def _read(self): + request = urllib.request.Request(self.url, method="GET") # noqa: S310 fixed internal http origin + request.add_header("Accept", "text/event-stream") + if self.authorization: + request.add_header("Authorization", self.authorization) + try: + self._response = urllib.request.urlopen(request, timeout=SESSION_TIMEOUT) # noqa: S310 fixed internal http origin + except urllib.error.HTTPError as error: + self.status, self.error = error.code, error + self._announced.set() + return + except OSError as error: + self.error = error + self._announced.set() + return + + self.status = self._response.status + self.content_type = self._response.headers.get("Content-Type", "") + event = None + try: + for raw in self._response: + line = raw.decode(errors="replace").rstrip("\r\n") + if line.startswith("event:"): + event = line.split(":", 1)[1].strip() + elif line.startswith("data:"): + data = line.split(":", 1)[1].strip() + if event == "endpoint": + self.endpoint = urllib.parse.urljoin(self.url, data) + self._announced.set() + else: + self._messages.put(data) + elif not line: + event = None + except (OSError, ValueError): + pass + finally: + self._announced.set() + + def call(self, method, params=None, request_id=1): + """Post one JSON-RPC request and return the matching stream response. + + Args: + method: MCP method name. + params: method params, or None. + request_id: JSON-RPC id to match the streamed response against. + """ + payload = {"jsonrpc": "2.0", "id": request_id, "method": method} + if params is not None: + payload["params"] = params + request = urllib.request.Request( # noqa: S310 fixed internal http origin + self.endpoint, data=json.dumps(payload).encode(), method="POST" + ) + request.add_header("Content-Type", "application/json") + if self.authorization: + request.add_header("Authorization", self.authorization) + with urllib.request.urlopen(request, timeout=SESSION_TIMEOUT): # noqa: S310 fixed internal http origin + pass + + deadline = time.monotonic() + SESSION_TIMEOUT + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + reject(f"{method} got no response on the stream") + try: + parsed = json.loads(self._messages.get(timeout=remaining)) + except queue.Empty: + reject(f"{method} got no response on the stream") + if parsed.get("id") == request_id: + return parsed + + +def probe_sse(): + """Prove an SSE provider is guarded, then drive a real session through it.""" + guarded = unguarded_url() + for label, authorization in ( + ("unauthenticated", None), + ("wrong-credential", WRONG_CREDENTIAL), + ): + session = SseSession(guarded, authorization).open() + status, content_type, endpoint = ( + session.status, + session.content_type, + session.endpoint, + ) + if status == 0: + unreachable(f"{label} probe could not reach {guarded}: {session.error}") + if status < 400: + reject(f"{label} probe answered {status} {content_type}") + if endpoint: + reject(f"{label} probe was served a session at {endpoint}") + + session = SseSession(URL, AUTH).open() + if session.status == 0: + unreachable(f"authenticated probe could not reach {URL}: {session.error}") + if session.status != 200 or "text/event-stream" not in session.content_type: + reject(f"authenticated stream answered {session.status}") + if not session.endpoint: + reject("authenticated stream announced no message endpoint") + + answer = session.call("initialize", INITIALIZE) + reject_error("authenticated initialize", answer.get("error")) + + answer = session.call("tools/list", request_id=2) + reject_error("authenticated tools/list", answer.get("error")) + served = sorted( + str(tool.get("name")) + for tool in (answer.get("result") or {}).get("tools") or [] + if tool.get("name") + ) + assert_surface(served) + + if READ_TOOL: + answer = session.call( + "tools/call", + {"name": READ_TOOL, "arguments": READ_ARGUMENTS}, + request_id=3, + ) + reject_error(f"read call {READ_TOOL}", answer.get("error")) + if (answer.get("result") or {}).get("isError"): + reject(f"read call {READ_TOOL} returned an error result") + print("OK") + + +def assert_surface(served): + """Refuse a served tool set that does not match what the role recorded. + + Args: + served: the tool names the upstream answered ``tools/list`` with. + + Two comparisons with different addressees. Drift against ``upstream_serves`` + means the vendor changed the surface, so the checked-in record is stale and + a human has to re-read the contract. A mismatch against the allowlist means + the platform's own policy is not what is being served. Reporting both as one + failure sent every upstream version bump to the wrong reader. + """ + if UPSTREAM_SERVES and served != UPSTREAM_SERVES: + grew = sorted(set(served) - set(UPSTREAM_SERVES)) + gone = sorted(set(UPSTREAM_SERVES) - set(served)) + reject( + f"upstream drift: the recorded surface is stale " + f"(added {grew}, removed {gone}); re-read the contract at this " + f"version before deploying" + ) + if EXPECTED and served != EXPECTED: + reject(f"server serves {served} but the contract declares {EXPECTED}") + + +def main(): + + if TRANSPORT == "sse": + probe_sse() + return + + guarded = unguarded_url() + assert_refused("unauthenticated", None, guarded) + assert_refused("wrong-credential", WRONG_CREDENTIAL, guarded) + + status, body = rpc("initialize", INITIALIZE, authorization=AUTH) + if status == 0: + unreachable(f"authenticated probe could not reach {URL}: {body}") + if status != 200: + reject(f"authenticated initialize answered {status}: {body[:200]}") + reject_error("authenticated initialize", rpc_error(body)) + + rpc("notifications/initialized", authorization=AUTH, notification=True) + + status, body = rpc("tools/list", authorization=AUTH) + if status != 200: + reject(f"authenticated tools/list answered {status}: {body[:200]}") + reject_error("authenticated tools/list", rpc_error(body)) + + served = sorted( + str(tool.get("name")) + for tool in (json.loads(body).get("result") or {}).get("tools") or [] + if tool.get("name") + ) + assert_surface(served) + + if READ_TOOL: + status, body = rpc( + "tools/call", + {"name": READ_TOOL, "arguments": READ_ARGUMENTS}, + authorization=AUTH, + ) + assert_read_call(status, body) + reject_error(f"read call {READ_TOOL}", rpc_error(body)) + if (json.loads(body).get("result") or {}).get("isError"): + reject(f"read call {READ_TOOL} returned an error result") + + print("OK") + + +if __name__ == "__main__": + main() diff --git a/roles/test-e2e-cli/files/shared/mcp/contract.sh b/roles/test-e2e-cli/files/shared/mcp/contract.sh new file mode 100644 index 0000000000..218838051b --- /dev/null +++ b/roles/test-e2e-cli/files/shared/mcp/contract.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# Drive the MCP contract checker for one role's endpoint. +# +# It runs in the provider's own network because the endpoint is `expose:`-only: +# the service name resolves there and nowhere else. Running it on the stack +# host would reach nothing. +# +# Variables sourced from test.env.j2 by test-e2e-cli. +set -euo pipefail + +: "${MCP_TEST_NETWORK:?}" +: "${MCP_TEST_IMAGE:?}" +: "${MCP_URL:?}" +: "${MCP_TRANSPORT:?}" +: "${MCP_AUTH_HEADER:?}" +: "${MCP_EXPECTED_TOOLS:?}" +: "${MCP_UPSTREAM_SERVES:?}" +: "${MCP_READ_ARGUMENTS:?}" + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +container run --rm -i \ + --network "${MCP_TEST_NETWORK}" \ + -e "MCP_URL=${MCP_URL}" \ + -e "MCP_TRANSPORT=${MCP_TRANSPORT}" \ + -e "MCP_PATH_KEY=${MCP_PATH_KEY}" \ + -e "MCP_AUTH_HEADER=${MCP_AUTH_HEADER}" \ + -e "MCP_EXPECTED_TOOLS=${MCP_EXPECTED_TOOLS}" \ + -e "MCP_UPSTREAM_SERVES=${MCP_UPSTREAM_SERVES}" \ + -e "MCP_READ_TOOL=${MCP_READ_TOOL}" \ + -e "MCP_READ_ARGUMENTS=${MCP_READ_ARGUMENTS}" \ + -e "MCP_HOST_HEADER=${MCP_HOST_HEADER}" \ + "${MCP_TEST_IMAGE}" \ + python3 - <"${here}/contract.py" diff --git a/roles/test-e2e-cli/files/shared/mcp/isolation.sh b/roles/test-e2e-cli/files/shared/mcp/isolation.sh new file mode 100644 index 0000000000..7b176a7666 --- /dev/null +++ b/roles/test-e2e-cli/files/shared/mcp/isolation.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Prove one role's MCP adapter sidecar is attached to exactly the networks it may. +# +# The attachment set is read from the engine, never by probing a peer's name: an +# unknown name does not fail to resolve in this environment, it falls through to +# a wildcard resolver that answers every name with one reachable address, so a +# name-based probe reports isolation broken for every provider. +# +# Swarm service introspection needs a manager. On a worker this reports that it +# cannot measure and returns success, because the manager in the same round does +# measure; a silent skip here would be indistinguishable from a pass. +# +# Env (rendered into test.env from test-e2e-cli/templates/mcp/test.env.j2): +# MCP_SIDECAR_SERVICE swarm service name, or compose container name +# MCP_EXPECTED_NETWORKS comma-separated networks the sidecar may hold +# MCP_DEPLOYMENT_MODE compose | swarm +set -euo pipefail + +: "${MCP_SIDECAR_SERVICE:?}" +: "${MCP_EXPECTED_NETWORKS:?}" +: "${MCP_DEPLOYMENT_MODE:?}" + +attached_swarm() { + local id + for id in $(container service inspect "${MCP_SIDECAR_SERVICE}" \ + --format '{{range .Endpoint.VirtualIPs}}{{.NetworkID}} {{end}}'); do + container network inspect "${id}" --format '{{.Name}}' + done +} + +attached_compose() { + container inspect --type container "${MCP_SIDECAR_SERVICE}" --format '{{json .NetworkSettings.Networks}}' | + python3 -c 'import json,sys; print("\n".join(json.load(sys.stdin)))' +} + +if [[ "${MCP_DEPLOYMENT_MODE}" == "swarm" ]]; then + if ! container node ls >/dev/null 2>&1; then + echo "SKIP: not a swarm manager, the manager of this round measures instead" + exit 0 + fi + attached="$(attached_swarm)" +else + attached="$(attached_compose)" +fi + +attached="$(printf '%s\n' "${attached}" | sed '/^$/d' | sort -u)" +expected="$(printf '%s' "${MCP_EXPECTED_NETWORKS}" | tr ',' '\n' | sed '/^$/d' | sort -u)" + +echo "attached: $(printf '%s' "${attached}" | tr '\n' ' ')" + +unexpected="$(comm -23 <(printf '%s\n' "${attached}") <(printf '%s\n' "${expected}"))" +absent="$(comm -13 <(printf '%s\n' "${attached}") <(printf '%s\n' "${expected}"))" + +if [[ -n "${unexpected}" ]]; then + echo "REJECTED the adapter is attached beyond its declared networks ($(printf '%s' "${unexpected}" | tr '\n' ' ')); a sidecar holding its provider's credential reaches that provider and its admitted clients only" >&2 +fi + +if [[ -n "${absent}" ]]; then + echo "REJECTED the adapter is missing a declared attachment ($(printf '%s' "${absent}" | tr '\n' ' ')); an admitted client cannot reach it" >&2 +fi + +[[ -z "${unexpected}${absent}" ]] || exit 1 diff --git a/roles/test-e2e-cli/files/shared/mcp/run.sh b/roles/test-e2e-cli/files/shared/mcp/run.sh new file mode 100644 index 0000000000..27d36c9522 --- /dev/null +++ b/roles/test-e2e-cli/files/shared/mcp/run.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Run the MCP test suite of whichever role staged this harness. +# +# A connection error is retried and a REJECTED verdict is not: the endpoint may +# still be warming up when the round reaches its tests, but a served surface +# that disagrees with the declared contract will disagree just as much in five +# minutes. +# +# Retrying is bounded by wall clock rather than by a count, because the budget +# it has to stay under is one: meta/tests.yml states the timeout the harness +# kills the run at, and both scale through the same lookup('timeout'). A +# retry count would keep its own budget and drift out from under that one. +# +# Env (rendered into test.env from test-e2e-cli/templates/mcp/test.env.j2): +# MCP_TEST_ENABLED whether this round serves MCP for the role at all +# MCP_SIDECAR_SERVICE the sidecar, empty for non-adapter providers +# MCP_DEADLINE_SECONDS when to stop retrying, below the harness timeout +set -euo pipefail + +: "${MCP_TEST_ENABLED:?}" +: "${MCP_SIDECAR_SERVICE?}" +: "${MCP_DEADLINE_SECONDS:?}" + +SLEEP_SECONDS=10 + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +case "${MCP_TEST_ENABLED}" in + true) ;; + false) + echo "SKIP: MCP is switched off in this round" + exit 0 + ;; + *) + echo "[FATAL] MCP_TEST_ENABLED is '${MCP_TEST_ENABLED}', neither true nor false" >&2 + exit 1 + ;; +esac + +while :; do + if out="$(bash "${here}/contract.sh" 2>&1)"; then + echo "${out}" + break + fi + if [[ "${out}" == *REJECTED* || ${SECONDS} -ge ${MCP_DEADLINE_SECONDS} ]]; then + echo "${out}" >&2 + exit 1 + fi + sleep "${SLEEP_SECONDS}" +done + +if [[ -n "${MCP_SIDECAR_SERVICE}" ]]; then + bash "${here}/isolation.sh" +fi + +echo "ALL CHECKS PASSED" diff --git a/roles/test-e2e-cli/tasks/main.yml b/roles/test-e2e-cli/tasks/main.yml index 78e2190aea..cfb3092bf3 100644 --- a/roles/test-e2e-cli/tasks/main.yml +++ b/roles/test-e2e-cli/tasks/main.yml @@ -44,7 +44,7 @@ ansible.builtin.include_tasks: run_one.yml loop: "{{ _cli_apps }}" loop_control: - loop_var: application_id + loop_var: application_id # nocheck: loop-var-shadow the item IS the role id, so run_one reads the same value the tested role declares label: "{{ application_id }}" - name: โœ… Fail if there were CLI test failures diff --git a/roles/test-e2e-cli/tasks/run_one.yml b/roles/test-e2e-cli/tasks/run_one.yml index 281d1c7a65..9e0f9dbdea 100644 --- a/roles/test-e2e-cli/tasks/run_one.yml +++ b/roles/test-e2e-cli/tasks/run_one.yml @@ -4,6 +4,7 @@ _cli_env_template: "{{ lookup('path_absolute', 'roles', application_id, 'templates/test.env.j2') }}" _cli_stage_dir: "{{ TEST_E2E_CLI_STAGE_BASE_DIR }}/{{ application_id }}" _cli_test_script: "{{ TEST_E2E_CLI_STAGE_BASE_DIR }}/{{ application_id }}/test.sh" + _cli_service_key: "{{ lookup('role_tests', application_id, 'cli.container_service_key', default='') | trim }}" - name: "โœ… Assert CLI test assets exist for {{ application_id }}" ansible.builtin.stat: @@ -23,17 +24,41 @@ loop_control: label: "{{ item.item }}" +- name: ๐Ÿงญ Default the CLI host to the loop host for {{ application_id }} + ansible.builtin.set_fact: + CLI_HOST_NODE: "{{ inventory_hostname }}" + CLI_LOCAL_CID: "" + +- name: "๐Ÿ” Resolve the node that holds {{ application_id }}'s test container" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ _cli_service_key }}" + resolve_output_prefix: CLI + resolve_compose_cid: "{{ lookup('container_address', application_id, _cli_service_key) }}" + resolve_converge_retries: 30 + resolve_converge_delay: 2 + when: _cli_service_key | length > 0 + - name: ๐Ÿ“ Create stage directory for {{ application_id }} ansible.builtin.file: path: "{{ _cli_stage_dir }}" state: directory mode: "0700" + delegate_to: "{{ CLI_HOST_NODE }}" - name: ๐Ÿ“ฆ Stage CLI test assets for {{ application_id }} ansible.builtin.copy: src: "{{ lookup('path_absolute', 'roles', application_id, 'files/test') }}/" dest: "{{ _cli_stage_dir }}/" mode: "0755" + delegate_to: "{{ CLI_HOST_NODE }}" + +- name: ๐Ÿ“ฆ Stage the shared CLI harness for {{ application_id }} + ansible.builtin.copy: + src: "{{ lookup('path_absolute', 'roles/test-e2e-cli/files/shared') }}/" + dest: "{{ _cli_stage_dir }}/shared/" + mode: "0755" + delegate_to: "{{ CLI_HOST_NODE }}" - name: ๐Ÿงญ Reset the per-role deployment-mode override ansible.builtin.include_vars: @@ -68,6 +93,7 @@ dest: "{{ _cli_stage_dir }}/test.env" mode: "0600" content: "{{ lookup('template', _cli_env_template) }}" + delegate_to: "{{ CLI_HOST_NODE }}" - name: ๐Ÿš€ Run CLI test script for {{ application_id }} ansible.builtin.shell: @@ -82,6 +108,8 @@ register: _cli_run changed_when: false failed_when: false + delegate_to: "{{ CLI_HOST_NODE }}" + throttle: 1 - name: ๐Ÿ“„ Print CLI test output on failure for {{ application_id }} ansible.builtin.debug: @@ -97,3 +125,10 @@ ansible.builtin.set_fact: _cli_failures: "{{ (_cli_failures | default([])) + [application_id] }}" when: _cli_run.rc != 0 + +- name: ๐Ÿงน Remove the delegated stage dir of {{ application_id }} + ansible.builtin.file: + path: "{{ _cli_stage_dir }}" + state: absent + delegate_to: "{{ CLI_HOST_NODE }}" + when: CLI_HOST_NODE != inventory_hostname diff --git a/roles/test-e2e-cli/templates/mcp/test.env.j2 b/roles/test-e2e-cli/templates/mcp/test.env.j2 new file mode 100644 index 0000000000..f76a3133c0 --- /dev/null +++ b/roles/test-e2e-cli/templates/mcp/test.env.j2 @@ -0,0 +1,20 @@ +{% set endpoint = lookup('config', application_id, 'mcp.endpoint') -%} +{% set upstream_key = lookup('config', application_id, 'mcp.adapter.upstream_network', '') -%} +{% set implementation = lookup('config', application_id, 'mcp.implementation') -%} +{% set entity = application_id | get_entity_name -%} +MCP_AUTH_HEADER='{{ {'id': application_id, 'auth': lookup('config', application_id, 'mcp.auth'), 'token': lookup('mcp_client_bearer', application_id), 'owner': lookup('config', application_id, 'mcp.credential.owner')} | mcp_authorization }}' +MCP_DEADLINE_SECONDS={{ lookup('timeout', 420) | int }} +MCP_DEPLOYMENT_MODE={{ compose_mode }} +MCP_EXPECTED_NETWORKS={{ ([entity] + ([entity ~ '_' ~ upstream_key] if upstream_key else [])) | join(',') }} +MCP_EXPECTED_TOOLS='{{ lookup('config', application_id, 'mcp.tools.allowlist', []) | to_json }}' +MCP_HOST_HEADER={{ lookup('domain', application_id) if endpoint.get('host_header', false) else '' }} +MCP_PATH_KEY= +MCP_READ_ARGUMENTS='{{ lookup('config', application_id, 'mcp.tools.read_probe.arguments', {}) | to_json }}' +MCP_READ_TOOL={{ lookup('config', application_id, 'mcp.tools.read_probe.tool', '') }} +MCP_SIDECAR_SERVICE={{ ((entity ~ '_' ~ endpoint.service_key) if compose_mode == 'swarm' else lookup('config', application_id, 'services.' ~ endpoint.service_key ~ '.name')) if implementation == 'adapter' else '' }} +MCP_TEST_ENABLED={{ lookup('config', application_id, 'mcp.enabled') | string | lower }} +MCP_TEST_IMAGE={{ lookup('config', 'svc-ai-mcp-adapter', 'services.mcp-adapter.image') }}:{{ lookup('config', 'svc-ai-mcp-adapter', 'services.mcp-adapter.version') }} +MCP_TEST_NETWORK={{ entity }} +MCP_TRANSPORT={{ lookup('config', application_id, 'mcp.transport') }} +MCP_UPSTREAM_SERVES='{{ ([] if implementation == 'adapter' else lookup('config', application_id, 'mcp.tools.upstream_serves', [])) | to_json }}' +MCP_URL=http://{{ endpoint.service_key }}:{{ lookup('config', application_id, 'services.' ~ endpoint.service_key ~ '.ports.internal.' ~ endpoint.port_key) }}{{ endpoint.path }} diff --git a/roles/test-e2e-playwright/README.md b/roles/test-e2e-playwright/README.md index c0153a1c25..d42483a4a4 100644 --- a/roles/test-e2e-playwright/README.md +++ b/roles/test-e2e-playwright/README.md @@ -101,7 +101,7 @@ Both are used as central defaults for every app role. ### Discovery filters -- `test_e2e_playwright_only_roles` (default: `allowed_applications`) +- `test_e2e_playwright_only_roles` (default: `lookup('deployment').running`, every role the round deploys, dependencies included) - `test_e2e_playwright_skip_roles` (default: `[]`) ## Design notes @@ -118,7 +118,7 @@ Both are used as central defaults for every app role. - `roles//templates/playwright.env.j2` - `roles//files/playwright/playwright.spec.js` Follow [Contributing `playwright.env.j2`](../../docs/agents/files/role/playwright.env.j2.md) and [Contributing `playwright.spec.js`](../../docs/contributing/artefact/files/role/playwright.specs.js.md) while creating them. -2. Run deployment and include your app in `allowed_applications` (or leave it empty to run all discovered apps). +2. Deploy a round that includes your app (e.g. `make compose-deploy apps=`); its specs run with those of every other role the round deploys. 3. Keep `package.json` and `playwright.config.js` centralized in `roles/test-e2e-playwright/` (`templates/package.json.j2` and `files/playwright.config.js`). Example override for running only one spec: diff --git a/roles/test-e2e-playwright/defaults/main.yml b/roles/test-e2e-playwright/defaults/main.yml index 324bf08595..eabbcd85f9 100644 --- a/roles/test-e2e-playwright/defaults/main.yml +++ b/roles/test-e2e-playwright/defaults/main.yml @@ -1,9 +1,33 @@ --- -# Hard cap per role; Ansible kills the sidecar if exceeded. Sized for -# addon-heavy roles that run many per-addon specs, e.g. nextcloud (~50 addons). +# Defaults for the Playwright end-to-end sidecar. +# +# Param test_e2e_playwright_run_timeout: hard cap per role in seconds; Ansible +# kills the sidecar when it is exceeded. Sized for addon-heavy roles that run +# many per-addon specs, e.g. nextcloud (~50 addons). +# Param test_e2e_playwright_test_timeout: per-test timeout in ms +# (config.timeout); caps a single spec. +# Param test_e2e_playwright_workers: parallel Playwright workers. Spec FILES run +# concurrently; tests within a file stay serial while +# TEST_E2E_PLAYWRIGHT_FULLY_PARALLEL is false. Computed conservatively from +# host CPU/RAM, capped for the app-under-test's concurrency limits, reduced +# on CI. +# Param TEST_E2E_PLAYWRIGHT_GLOBAL_TIMEOUT_BUFFER: seconds subtracted from +# run_timeout to form globalTimeout, leaving room for Ansible to collect +# artifacts before it kills the sidecar. +# Param test_e2e_playwright_only_roles: roles whose specs run. `.running` is the +# whitelist when a targeted deploy sets one and the inventory groups +# otherwise. `.groups` would run every spec in the round even when `apps=` +# deployed three roles, so specs for untouched roles fail on stale state and +# mask the result of the deploy that actually ran. +# Param test_e2e_playwright_skip_roles: roles excluded from the run. +# Param test_e2e_playwright_keep: keep the sidecar and cluster after the run. +# Param VARIANT_INDEX: 0-based matrix-deploy round id, pushed as an extra var by +# `cli/administration/deploy/development/deploy.py` when the matrix +# orchestrator runs. Defaults to 0 for dev / non-matrix invocations so +# per-(variant, pass) artifact archiving still produces a valid +# `variant-0//` slot. test_e2e_playwright_run_timeout: 3600 -# Per-test timeout (ms) inside Playwright (config.timeout); caps a single spec. test_e2e_playwright_test_timeout: 300000 test_e2e_playwright_workers: "{{ lookup('playwright_workers') }}" @@ -12,8 +36,8 @@ TEST_E2E_PLAYWRIGHT_GLOBAL_TIMEOUT_BUFFER: 60 TEST_E2E_PLAYWRIGHT_GLOBAL_TIMEOUT_MS: "{{ (((TEST_E2E_PLAYWRIGHT_RUN_TIMEOUT_EFFECTIVE | int) - (TEST_E2E_PLAYWRIGHT_GLOBAL_TIMEOUT_BUFFER | int)) * 1000) | string }}" -# Run only a subset (optional) -test_e2e_playwright_only_roles: "{{ lookup('deployment').groups }}" +test_e2e_playwright_only_roles: "{{ lookup('deployment').running }}" test_e2e_playwright_skip_roles: [] test_e2e_playwright_keep: false + VARIANT_INDEX: 0 diff --git a/roles/test-e2e-playwright/files/mcp-endpoint.js b/roles/test-e2e-playwright/files/mcp-endpoint.js new file mode 100644 index 0000000000..7f3c88acfe --- /dev/null +++ b/roles/test-e2e-playwright/files/mcp-endpoint.js @@ -0,0 +1,119 @@ +/** + * Shared disabled-state assertion for MCP endpoints. + * + * Every role-local MCP spec gates itself on `MCP_SERVICE_ENABLED` and skips + * when the surface is off, so nothing ever checked that switching it off + * actually removes it. A surface still serving after the flag went false is + * indistinguishable from one that was never deployed, which is the failure + * this registers a test for. + * + * The check is deliberately transport-agnostic. Roles serve over classic SSE, + * Streamable HTTP or plain JSON-RPC and their enabled-state specs differ + * accordingly, but an endpoint that is gone answers none of them, so both a + * GET and a POST have to come back unserved. + * + * Contract: + * mcpEndpointUrl(path?, baseUrl?) -> the endpoint under baseUrl, defaulting + * to `/mcp` under APP_BASE_URL. Roles that export their own base variable + * pass it rather than declaring APP_BASE_URL: the shared guest persona + * collapses itself on `!APP_BASE_URL`, so adding one to a role that has + * none turns its never-executed public journey live. + * registerMcpDisabledState(() => endpointUrl) -> registers one Playwright test + * registerMcpGuestRejection(() => endpointUrl) -> registers one Playwright test + * + * The URL is passed as a thunk because the roles build it differently and some + * of them resolve it from fixtures that only exist once a test is running. + */ + +const { test, expect } = require("@playwright/test"); +const { normalizeBaseUrl } = require("./personas/utils/dotenv"); +const { + skipUnlessServiceDisabled, + skipUnlessServiceEnabled, +} = require("./service-gating"); + +const SERVED = new Set([200, 201, 202, 401, 403, 405, 406, 415, 429]); +const ABSOLUTE_URL = /^https?:\/\/[^/]+/; + +function mcpEndpointUrl(path = "/mcp", baseUrl = process.env.APP_BASE_URL) { + return `${normalizeBaseUrl(baseUrl)}${path}`; +} + +function registerMcpDisabledState(resolveEndpointUrl) { + test("guest: the MCP endpoint is gone while the service is switched off", async ({ + page, + }) => { + skipUnlessServiceDisabled("mcp"); + + const endpointUrl = resolveEndpointUrl(); + expect(endpointUrl, "the MCP endpoint URL must resolve to an absolute URL even while disabled").toMatch(ABSOLUTE_URL); + + const attempts = [ + await page.request.get(endpointUrl, { + failOnStatusCode: false, + maxRedirects: 0, + headers: { accept: "text/event-stream" }, + }), + await page.request.post(endpointUrl, { + failOnStatusCode: false, + maxRedirects: 0, + headers: { Accept: "application/json", "Content-Type": "application/json" }, + data: { jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }, + }), + ]; + + for (const response of attempts) { + const status = response.status(); + const excerpt = (await response.text()).slice(0, 200); + expect( + SERVED.has(status), + `${endpointUrl} answered ${status} with ${excerpt} while MCP is disabled; ` + + `a refused credential still means the surface is listening`, + ).toBe(false); + expect( + response.headers()["content-type"] || "", + "a disabled endpoint must not open the SSE channel", + ).not.toContain("text/event-stream"); + } + }); +} + +function registerMcpGuestRejection(resolveEndpointUrl, label = "") { + const title = label + ? `mcp: an unauthenticated probe of ${label} is rejected` + : "mcp: an unauthenticated probe of the MCP endpoint is rejected"; + test(title, async ({ page }) => { + skipUnlessServiceEnabled("mcp"); + + const endpointUrl = resolveEndpointUrl(); + expect(endpointUrl, "the MCP endpoint URL must resolve to an absolute URL").toMatch(ABSOLUTE_URL); + + // maxRedirects: 0 because a vhost may answer the bearerless probe with an + // SSO redirect; following it would land on a 200 login page and hide that + // no MCP response was ever served. + const response = await page.request.post(endpointUrl, { + failOnStatusCode: false, + maxRedirects: 0, + headers: { "Content-Type": "application/json" }, + data: { jsonrpc: "2.0", id: 1, method: "initialize", params: {} }, + }); + + expect( + response.status(), + `POST ${endpointUrl} answered ${response.status()} โ€” the MCP server is ` + + "internal-only, so the public vhost must redirect or refuse a bearerless " + + "initialize, never answer it.", + ).toBeGreaterThanOrEqual(300); + + expect( + await response.text(), + "the public vhost must not return an MCP protocol response to a bearerless probe", + ).not.toContain('"jsonrpc"'); + }); +} + +module.exports = { + mcpEndpointUrl, + registerMcpDisabledState, + registerMcpGuestRejection, +}; diff --git a/roles/test-e2e-playwright/files/personas/admin.js b/roles/test-e2e-playwright/files/personas/admin.js index a3126a0272..2844942de6 100644 --- a/roles/test-e2e-playwright/files/personas/admin.js +++ b/roles/test-e2e-playwright/files/personas/admin.js @@ -11,9 +11,22 @@ const { assertUnauthenticatedLanding, assertCspInjections, runRoleInteraction, + hostnameOf, LOGIN_CONTROL_NAME, } = require("./utils"); +async function readCredentialRejection(page) { + const text = await page + .locator( + "[role='alert']:visible, .alert:visible, .error:visible, .v-alert:visible, [class*='error']:visible", + ) + .first() + .innerText({ timeout: resolveTimeout(2_000) }) + .catch(() => ""); + const line = text.trim().split("\n")[0].slice(0, 200); + return /invalid|incorrect|wrong|failed|denied|do(es)? not match/i.test(line) ? line : ""; +} + async function runAdminFlow(page, opts = {}) { if ((process.env.PERSONA_ADMINISTRATOR_BLOCKED || "").toLowerCase() === "true") { test.skip( @@ -163,7 +176,7 @@ async function runAdminFlow(page, opts = {}) { const fUrl = frame.url(); if (!fUrl || fUrl === "about:blank") continue; if (/openid-connect\/auth|\/oauth2\/(?:start|sign_in|callback)/.test(fUrl)) continue; - if (canonicalDomain && fUrl.includes(canonicalDomain)) { + if (canonicalDomain && hostnameOf(fUrl) === canonicalDomain) { adminReachedAuthenticated = true; break; } @@ -195,13 +208,16 @@ async function runAdminFlow(page, opts = {}) { } } if (!adminReachedAuthenticated) { - expect( - false, + const rejection = await readCredentialRejection(page); + const rejected = + `administrator's credential was rejected by the app on ${canonicalDomain}: "${rejection}". ` + + `The password typed here does not match what the app stores, so the role seeds it at install ` + + `and never re-applies it: a rotation between the sync and async pass leaves the app behind. `; + const unreached = `administrator did NOT reach an authenticated surface on ${canonicalDomain}. ` + - `Either the role's auth chain is broken or administrator legitimately has no OIDC-driven admin path here, ` + - `in which case the role MUST declare \`PERSONA_ADMINISTRATOR_BLOCKED=true\` in templates/playwright.env.j2. ` + - `Current URL: ${page.url()}.`, - ).toBe(true); + `Either the role's auth chain is broken or administrator legitimately has no OIDC-driven admin path here, ` + + `in which case the role MUST declare \`PERSONA_ADMINISTRATOR_BLOCKED=true\` in templates/playwright.env.j2. `; + expect(false, `${rejection ? rejected : unreached}Current URL: ${page.url()}.`).toBe(true); return; } diff --git a/roles/test-e2e-playwright/files/personas/biber.js b/roles/test-e2e-playwright/files/personas/biber.js index d5a3b3f241..9a8d5d57df 100644 --- a/roles/test-e2e-playwright/files/personas/biber.js +++ b/roles/test-e2e-playwright/files/personas/biber.js @@ -33,6 +33,7 @@ const { assertUnauthenticatedLanding, assertCspInjections, runRoleInteraction, + hostnameOf, LOGIN_CONTROL_NAME, } = require("./utils"); @@ -128,7 +129,7 @@ async function runBiberFlow(page, opts = {}) { const fUrl = frame.url(); if (!fUrl || fUrl === "about:blank") continue; if (/openid-connect\/auth|\/oauth2\/(?:start|sign_in|callback)/.test(fUrl)) continue; - if (canonicalDomain && fUrl.includes(canonicalDomain)) { + if (canonicalDomain && hostnameOf(fUrl) === canonicalDomain) { reachedAuthenticated = true; break; } diff --git a/roles/test-e2e-playwright/files/personas/utils/dom.js b/roles/test-e2e-playwright/files/personas/utils/dom.js index 0318113e3f..4d9c0b6f74 100644 --- a/roles/test-e2e-playwright/files/personas/utils/dom.js +++ b/roles/test-e2e-playwright/files/personas/utils/dom.js @@ -24,6 +24,9 @@ * regular-expression source string. Suitable for embedding a raw * string into a `new RegExp(...)` or `getByRole({ name: new RegExp(`^${escapeRegex(s)}$`) })`. * + * `hostnameOf(url)` + * Hostname of `url`, or "" when it does not parse. + * * `LOGIN_CONTROL_NAME` * Accessible-name pattern for a sign-in control, used by the * post-login gates to assert no login affordance survived the @@ -68,12 +71,21 @@ function escapeRegex(value) { return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } -const LOGIN_CONTROL_NAME = /^\s*(log\s*in|sign\s*in|sso)(\s+with\s+\S.*)?\s*$/i; +function hostnameOf(url) { + try { + return new URL(url).hostname; + } catch { + return ""; + } +} + +const LOGIN_CONTROL_NAME = /^[\s\p{Co}]*(log\s*in|sign\s*in|sso)(\s+with\s+\S.*)?\s*$/iu; module.exports = { isVisible, waitForFrameUrl, findFirstVisibleCandidate, escapeRegex, + hostnameOf, LOGIN_CONTROL_NAME, }; diff --git a/roles/test-e2e-playwright/files/personas/utils/env.js b/roles/test-e2e-playwright/files/personas/utils/env.js index 0eea54eb46..5e1c319d35 100644 --- a/roles/test-e2e-playwright/files/personas/utils/env.js +++ b/roles/test-e2e-playwright/files/personas/utils/env.js @@ -75,16 +75,22 @@ async function gotoOnion(page, url, opts = {}) { } /** - * Tor-resilient `request.get` for the standalone APIRequestContext fixture. - * Its SOCKS CONNECT goes through the bundled `socks` client whose 30s connect - * cap is not configurable, so a cold onion circuit fails the request no matter - * how large the request timeout is. Retries only transient proxy/socket - * errors; clearnet URLs get a single attempt and real HTTP failures re-throw. + * Tor-resilient `request.fetch` for any APIRequestContext (the standalone + * fixture or `context.request`); `opts.method` picks the verb. Its SOCKS + * CONNECT goes through the bundled `socks` client whose 30s connect cap is not + * configurable, so a cold onion circuit fails the request no matter how large + * the request timeout is. Retries only transient proxy/socket errors; clearnet + * URLs get a single attempt and real HTTP failures re-throw. `apiGetOnion` is + * the GET shorthand. */ const _API_TRANSIENT_RE = - /Proxy connection timed out|Socket closed|socket hang up|ECONNRESET|ETIMEDOUT|ECONNREFUSED|ENOTFOUND/i; + /Proxy connection timed out|Socks5 proxy rejected connection|Socket closed|socket hang up|ECONNRESET|ETIMEDOUT|ECONNREFUSED|ENOTFOUND/i; -async function apiGetOnion(request, url, opts = {}) { +function apiGetOnion(request, url, opts = {}) { + return apiFetchOnion(request, url, { ...opts, method: "GET" }); +} + +async function apiFetchOnion(request, url, opts = {}) { const isRelative = /^\/(?!\/)/.test(url); const isOnion = /\.onion(?::\d+)?(?:\/|$|\?)/i.test(url) || (isRelative && isOnionCanonical()); @@ -92,7 +98,7 @@ async function apiGetOnion(request, url, opts = {}) { let lastErr; for (let attempt = 1; attempt <= attempts; attempt += 1) { try { - return await request.get(url, opts); + return await request.fetch(url, opts); } catch (err) { lastErr = err; if (attempt >= attempts || !_API_TRANSIENT_RE.test(String(err && err.message))) { @@ -162,6 +168,7 @@ module.exports = { isOnionCanonical, gotoOnion, apiGetOnion, + apiFetchOnion, safeSkipUnlessEnabled, safeIsEnabled, recordVideoOptions, diff --git a/roles/test-e2e-playwright/files/personas/utils/keycloak.js b/roles/test-e2e-playwright/files/personas/utils/keycloak.js index ea2526b964..ff499b5a67 100644 --- a/roles/test-e2e-playwright/files/personas/utils/keycloak.js +++ b/roles/test-e2e-playwright/files/personas/utils/keycloak.js @@ -12,7 +12,7 @@ * * `performKeycloakLogin(page, username, password, canonicalDomain)` * Calls `performKeycloakLoginForm` and additionally polls the - * page URL until it contains `canonicalDomain`, asserting the + * page URL until its hostname is `canonicalDomain`, asserting the * OAuth2-Proxy / app callback completes. * * `performKeycloakLoginExpectingDenial(page, username, password, canonicalDomain)` @@ -27,16 +27,30 @@ const { expect } = require("@playwright/test"); const { resolveTimeout } = require("../../timeouts"); +const { hostnameOf } = require("./dom"); // SPOT for the role-side OIDC adapter readiness contract. A role whose // `templates/javascript/oidc.js.j2` wraps its Login link in a JS click // handler (e.g. `keycloak.login()` with PKCE) MUST set this flag on -// `window` after the click interceptor is wired, so persona helpers can -// click the link without racing the adapter. +// `window` to `false` before the Login link renders and to `true` after +// the click interceptor is wired, so persona helpers can click the link +// without racing the adapter. const OIDC_LOGIN_READY_FLAG = "__oidcLoginReady"; const OIDC_TRIGGER_NAME = /sso|openid|single[\s-]?sign/i; +// Keycloak's end-session URL also contains `openid-connect`; a page that +// renders a hidden Logout item before its Login link would otherwise pin +// `.first()` to the hidden Logout item until the probe times out. +const OIDC_ENTRY_SELECTOR = [ + "a[href*='openid_connect' i]:not([href*='logout' i])", + "a[href*='openid-connect' i]:not([href*='logout' i])", + "a[href*='/auth/auth/' i]:not([href*='logout' i])", + "form[action*='openid' i] button", + "a[data-testid*='oidc' i]", + "button[data-testid*='oidc' i]", +].join(", "); + async function performKeycloakLoginForm(target, username, password) { const usernameField = target .getByRole("textbox", { name: /username|email/i }) @@ -62,19 +76,19 @@ async function performKeycloakLogin(page, username, password, canonicalDomain) { await performKeycloakLoginForm(page, username, password); await expect - .poll(() => page.url(), { + .poll(() => hostnameOf(page.url()), { timeout: resolveTimeout(60_000), message: `Expected redirect back to ${canonicalDomain} after Keycloak login`, }) - .toContain(canonicalDomain); + .toBe(canonicalDomain); } // Click a role's in-app Login link to start the OIDC chain. Waits for // the role's adapter to signal readiness (OIDC_LOGIN_READY_FLAG) before // clicking, so the click hits the JS-wrapped handler (which stores // PKCE state) and not the raw `href` (which would skip PKCE and break -// the post-login token exchange on PKCE-enforced clients). The 15s -// fallback covers roles whose Login link is purely static. Returns the +// the post-login token exchange on PKCE-enforced clients). Roles that +// never declare the flag only wait for the page's load event. Returns the // Page that reached `openid-connect/auth` โ€” the opener, or the popup for // roles that hand the IdP off via `window.open` โ€” else null. // @@ -88,11 +102,7 @@ async function performKeycloakLogin(page, username, password, canonicalDomain) { // flow instead of the role's own auth chain. async function clickOidcLoginLink(page, strictLink, looseLink) { for (let attempt = 0; attempt < 2; attempt += 1) { - let oidcLink = page - .locator( - "a[href*='openid_connect' i], a[href*='openid-connect' i], a[href*='/auth/auth/' i], form[action*='openid' i] button, a[data-testid*='oidc' i], button[data-testid*='oidc' i]", - ) - .first(); + let oidcLink = page.locator(OIDC_ENTRY_SELECTOR).first(); if (attempt > 0) { oidcLink = oidcLink .or(page.getByRole("button", { name: OIDC_TRIGGER_NAME })) @@ -120,9 +130,10 @@ async function clickOidcLoginLink(page, strictLink, looseLink) { } } + await page.waitForLoadState("load", { timeout: resolveTimeout(15_000) }).catch(() => {}); await page .waitForFunction( - (flag) => window[flag] === true, + (flag) => window[flag] !== false, OIDC_LOGIN_READY_FLAG, { timeout: resolveTimeout(15_000) }, ) @@ -157,7 +168,7 @@ async function performKeycloakLoginExpectingDenial(page, username, password, can await page.content().catch(() => ""), ) || /openid-connect\/auth/.test(finalUrl) || - !finalUrl.includes(canonicalDomain); + hostnameOf(finalUrl) !== canonicalDomain; expect( denied, diff --git a/roles/test-e2e-playwright/files/personas/utils/logout.js b/roles/test-e2e-playwright/files/personas/utils/logout.js index e8d4eaef82..292a49b2ba 100644 --- a/roles/test-e2e-playwright/files/personas/utils/logout.js +++ b/roles/test-e2e-playwright/files/personas/utils/logout.js @@ -37,6 +37,7 @@ const { expect } = require("@playwright/test"); const { resolveTimeout } = require("../../timeouts"); const LOGOUT_NAME_RE = /log\s*out|sign\s*out|sign-out|abmelden/i; +const KEYCLOAK_LOGOUT_URL_RE = /\/protocol\/openid-connect\/logout/i; const ACCOUNT_MENU_NAME_RE = /(account|\bprofile\b|user.?menu|^menu$|signed\s*in)/i; async function clickFirstVisible(loc) { @@ -86,14 +87,31 @@ function menuTriggerCandidatesOn(scope) { ]; } -async function waitForAnyLogoutCandidate(page, timeoutMs = resolveTimeout(30_000)) { - // Returns true on the first visible logout-shaped element OR menu trigger - // (Account/Profile). Async-rendered post-login UIs (e.g. dashboard's - // CDN-loaded keycloak-js + token exchange) routinely exceed 10s before - // the Account dropdown is even visible โ€” bumped from 10s to 30s. +const POLL_INTERVAL_MS = 250; + +async function waitForLogoutControl(page, timeoutMs) { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { - for (const loc of [...logoutCandidatesOn(page), ...menuTriggerCandidatesOn(page)]) { + for (const loc of logoutCandidatesOn(page)) { + const count = await loc.count().catch(() => 0); + for (let i = 0; i < count; i++) { + if (await loc.nth(i).isVisible().catch(() => false)) return true; + } + } + await page.waitForTimeout(POLL_INTERVAL_MS); + } + return false; +} + +async function waitForAnyLogoutCandidate(page, timeoutMs = resolveTimeout(30_000), extraCandidates = []) { + // Returns true on the first visible logout-shaped element, menu trigger + // (Account/Profile) or extra candidate. Async-rendered post-login UIs + // (e.g. dashboard's CDN-loaded keycloak-js + token exchange) routinely + // exceed 10s before the Account dropdown is even visible; bumped from + // 10s to 30s. + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + for (const loc of [...logoutCandidatesOn(page), ...menuTriggerCandidatesOn(page), ...extraCandidates]) { const count = await loc.count().catch(() => 0); for (let i = 0; i < count; i++) { const cand = loc.nth(i); @@ -102,7 +120,7 @@ async function waitForAnyLogoutCandidate(page, timeoutMs = resolveTimeout(30_000 } } } - await page.waitForTimeout(resolveTimeout(250)); + await page.waitForTimeout(POLL_INTERVAL_MS); } return false; } @@ -122,7 +140,7 @@ async function tryLogoutViaMenus(page) { tried.add(key); await trigger.click({ timeout: resolveTimeout(5_000) }).catch(() => {}); // Give the dropdown / popover time to render its items. - await page.waitForTimeout(resolveTimeout(1_500)); + await waitForLogoutControl(page, resolveTimeout(1_500)); if (await tryLogoutFrom(page)) { await page.waitForLoadState("domcontentloaded", { timeout: resolveTimeout(30_000) }).catch(() => {}); return true; @@ -135,10 +153,14 @@ async function tryLogoutViaMenus(page) { return false; } -async function openAccountSettings(page) { - const links = page.locator( +function settingsLinksOn(scope) { + return scope.locator( "a[href^='/'][href*='setting' i], a[href^='/'][href*='preference' i], a[href^='/'][href*='einstellung' i]", ); +} + +async function openAccountSettings(page) { + const links = settingsLinksOn(page); const count = await links.count().catch(() => 0); for (let i = 0; i < count; i++) { const link = links.nth(i); @@ -157,11 +179,20 @@ async function openAccountSettings(page) { * without it the Keycloak SSO session โ€” and every app session โ€” survives. */ async function confirmKeycloakLogoutIfPrompted(page) { - if (!/\/protocol\/openid-connect\/logout/i.test(page.url())) return; + if (!KEYCLOAK_LOGOUT_URL_RE.test(page.url())) return; const confirmBtn = page .locator("#kc-logout, form[action*='logout-confirm'] input[type='submit'], form[action*='logout-confirm'] button") .first(); - if (await confirmBtn.waitFor({ state: "visible", timeout: resolveTimeout(2_000) }).then(() => true).catch(() => false)) { + const prompted = await Promise.race([ + confirmBtn.waitFor({ state: "visible", timeout: resolveTimeout(2_000) }).then(() => true), + page + .waitForURL((url) => !KEYCLOAK_LOGOUT_URL_RE.test(url.href), { + waitUntil: "commit", + timeout: resolveTimeout(2_000), + }) + .then(() => false), + ]).catch(() => false); + if (prompted) { await confirmBtn.click({ timeout: resolveTimeout(10_000) }).catch(() => {}); await page.waitForLoadState("domcontentloaded", { timeout: resolveTimeout(30_000) }).catch(() => {}); } @@ -170,9 +201,8 @@ async function confirmKeycloakLogoutIfPrompted(page) { async function inAppLogout(page) { await page.waitForLoadState("domcontentloaded", { timeout: resolveTimeout(30_000) }).catch(() => {}); - await waitForAnyLogoutCandidate(page); - await page.waitForTimeout(resolveTimeout(3_000)); - await waitForAnyLogoutCandidate(page); + await waitForLogoutControl(page, resolveTimeout(3_000)); + await waitForAnyLogoutCandidate(page, resolveTimeout(30_000), [settingsLinksOn(page)]); if (await tryLogoutFrom(page)) { await page.waitForLoadState("domcontentloaded", { timeout: resolveTimeout(30_000) }).catch(() => {}); @@ -222,4 +252,4 @@ async function inAppLogout(page) { expect.soft(false, "no in-app logout control reachable on the current authenticated surface").toBe(true); } -module.exports = { inAppLogout, confirmKeycloakLogoutIfPrompted }; +module.exports = { inAppLogout, confirmKeycloakLogoutIfPrompted, waitForLogoutControl }; diff --git a/roles/test-e2e-playwright/files/playwright.config.js b/roles/test-e2e-playwright/files/playwright.config.js index 6b2bc56949..0587e22fcb 100644 --- a/roles/test-e2e-playwright/files/playwright.config.js +++ b/roles/test-e2e-playwright/files/playwright.config.js @@ -1,5 +1,6 @@ const { defineConfig } = require("@playwright/test"); +// nocheck: env-default a role may export its own base variable and no APP_BASE_URL const baseURL = process.env.APP_BASE_URL || "http://127.0.0.1"; const keepAll = (process.env.INFINITO_PLAYWRIGHT_KEEP || "").toLowerCase() === "true"; @@ -21,12 +22,30 @@ function onionSecureOrigins() { const onionSecure = onionSecureOrigins(); -const globalTimeout = parseInt(process.env.INFINITO_PLAYWRIGHT_GLOBAL_TIMEOUT_MS || "0", 10); +/** + * The timeout the harness renders into the staged .env under this name. + * + * Args: + * name: the PLAYWRIGHT_*_TIMEOUT variable to read. + */ +function requiredTimeout(name) { + const value = Number(process.env[name]); + if (!Number.isFinite(value) || value <= 0) { + throw new Error( + `${name} is missing from the environment. The harness writes every ` + + "timeout into the staged .env, so this run was started outside it." + ); + } + return value; +} + +const globalTimeout = parseInt(process.env.INFINITO_PLAYWRIGHT_GLOBAL_TIMEOUT_MS || 0, 10); module.exports = defineConfig({ testDir: "./tests", testMatch: "**/*.@(spec|test).js", - timeout: Number(process.env.PLAYWRIGHT_TEST_TIMEOUT) || 300_000, + timeout: requiredTimeout("PLAYWRIGHT_TEST_TIMEOUT"), + expect: { timeout: requiredTimeout("PLAYWRIGHT_EXPECT_TIMEOUT") }, ...(globalTimeout > 0 ? { globalTimeout } : {}), retries: 2, workers: Number(process.env.PLAYWRIGHT_WORKERS) || 1, @@ -52,8 +71,8 @@ module.exports = defineConfig({ : undefined, // Fail fast instead of hanging until the per-test timeout when a target is // unreachable (e.g. an onion service that is not yet published). - navigationTimeout: Number(process.env.PLAYWRIGHT_NAVIGATION_TIMEOUT) || 60_000, - actionTimeout: Number(process.env.PLAYWRIGHT_ACTION_TIMEOUT) || 30_000, + navigationTimeout: requiredTimeout("PLAYWRIGHT_NAVIGATION_TIMEOUT"), + actionTimeout: requiredTimeout("PLAYWRIGHT_ACTION_TIMEOUT"), trace: keepAll ? "on" : "retain-on-failure", screenshot: keepAll ? "on" : "only-on-failure", video: keepAll ? "on" : "retain-on-failure" diff --git a/roles/test-e2e-playwright/files/service-gating.js b/roles/test-e2e-playwright/files/service-gating.js index 201165c047..3e03319193 100644 --- a/roles/test-e2e-playwright/files/service-gating.js +++ b/roles/test-e2e-playwright/files/service-gating.js @@ -121,6 +121,25 @@ function skipUnlessServiceEnabled(name) { } } +/** + * Skip the current test unless the named service is disabled, so a spec can + * assert what a switched-off service must NOT do: + * + * test("the endpoint is gone while mcp is off", async ({ page }) => { + * skipUnlessServiceDisabled("mcp"); + * // assert absence below + * }); + * + * Without this the disabled state is never asserted at all: every gated spec + * skips itself when the flag is false, so a surface that kept serving after + * being switched off looks exactly like one that was never deployed. + */ +function skipUnlessServiceDisabled(name) { + if (isServiceEnabled(name)) { + test.skip(true, `${envKey(name)}=true`); + } +} + /** * Legacy wrapper kept for compatibility with callers that were written * against the wrap-style API. New code SHOULD use @@ -142,5 +161,6 @@ module.exports = { isServiceEnabled, isServiceDisabledReason, requireService, + skipUnlessServiceDisabled, skipUnlessServiceEnabled, }; diff --git a/roles/test-e2e-playwright/tasks/01_setup/orchestrate.yml b/roles/test-e2e-playwright/tasks/01_setup/orchestrate.yml index 0a0db3cd4b..9580f19f34 100644 --- a/roles/test-e2e-playwright/tasks/01_setup/orchestrate.yml +++ b/roles/test-e2e-playwright/tasks/01_setup/orchestrate.yml @@ -18,7 +18,7 @@ ansible.builtin.include_tasks: 02_run_one.yml loop: "{{ TEST_E2E_PLAYWRIGHT_APPS }}" loop_control: - loop_var: application_id + loop_var: application_id # nocheck: loop-var-shadow the item IS the role id, so 02_run_one reads the same value the tested role's own vars declare label: "{{ application_id }}" - name: ๐Ÿ” Stash first-pass failures for one flake retry @@ -31,7 +31,7 @@ ansible.builtin.include_tasks: 02_run_one.yml loop: "{{ _playwright_retry_roles | default([]) }}" loop_control: - loop_var: application_id + loop_var: application_id # nocheck: loop-var-shadow same loop body, same identity between item and role id label: "{{ application_id }} (retry)" - name: ๐Ÿ›‘ Fail if there were Playwright failures diff --git a/roles/test-e2e-playwright/tasks/02_run_one.yml b/roles/test-e2e-playwright/tasks/02_run_one.yml index f2c8133186..0fa0ac0e36 100644 --- a/roles/test-e2e-playwright/tasks/02_run_one.yml +++ b/roles/test-e2e-playwright/tasks/02_run_one.yml @@ -144,30 +144,14 @@ mode: "0644" directory_mode: "0755" -- name: ๐Ÿ“ Create staging fixtures directory - ansible.builtin.file: - path: "{{ _playwright_stage_tests_dir }}/fixtures" - state: directory - mode: "0755" - -- name: ๐Ÿ“‹ Copy role Playwright binary fixtures into staging fixtures directory - ansible.builtin.copy: - src: "{{ item }}" - dest: "{{ _playwright_stage_tests_dir }}/fixtures/{{ item | basename }}" - mode: "0644" - with_fileglob: - - "{{ _playwright_files_dir }}/fixtures/*" - - name: ๐Ÿ“‹ Copy shared Playwright helpers into staging tests directory ansible.builtin.copy: - src: "{{ lookup('path_absolute', 'roles/test-e2e-playwright/files', item) }}" - dest: "{{ _playwright_stage_tests_dir }}/{{ item }}" + src: "{{ item }}" + dest: "{{ _playwright_stage_tests_dir }}/{{ item | basename }}" mode: "0644" - loop: - - service-gating.js - - onion-test.js - - addon-gating.js - - timeouts.js + when: (item | basename) != 'playwright.config.js' + with_fileglob: + - "{{ lookup('path_absolute', 'roles/test-e2e-playwright/files') }}/*.js" - name: โœ… Ensure staging volume directory exists ansible.builtin.file: @@ -179,7 +163,11 @@ ansible.builtin.copy: dest: "{{ _playwright_stage_dir }}/.env" mode: "0644" - content: "{{ lookup('template', _playwright_env_template) }}" + content: | + {{ lookup('template', _playwright_env_template) }} + {% for name, value in TEST_E2E_PLAYWRIGHT_CONFIG_TIMEOUTS.items() %} + {{ name }}={{ value }} + {% endfor %} vars: application_id: "{{ application_id }}" domains: "{{ lookup('domains') }}" @@ -248,9 +236,8 @@ + ['-e', 'PLAYWRIGHT_PROXY=' ~ TEST_E2E_PLAYWRIGHT_PROXY] + ['-e', 'PLAYWRIGHT_WORKERS=' ~ test_e2e_playwright_workers] + ['-e', 'PLAYWRIGHT_FULLY_PARALLEL=' ~ TEST_E2E_PLAYWRIGHT_FULLY_PARALLEL] - + ['-e', 'PLAYWRIGHT_TEST_TIMEOUT=' ~ (TEST_E2E_PLAYWRIGHT_ONION_TEST_TIMEOUT if (TEST_E2E_PLAYWRIGHT_IS_ONION | bool) else test_e2e_playwright_test_timeout)] + ['-e', 'PLAYWRIGHT_TIMEOUT_FACTOR=' ~ TIMEOUT_FACTOR] - + ['-e', 'PLAYWRIGHT_NAVIGATION_TIMEOUT=' ~ (TEST_E2E_PLAYWRIGHT_ONION_NAVIGATION_TIMEOUT if (TEST_E2E_PLAYWRIGHT_IS_ONION | bool) else TEST_E2E_PLAYWRIGHT_NAVIGATION_TIMEOUT)] + + (['-e', 'PLAYWRIGHT_ONION_TIMEOUT_MULTIPLIER=' ~ TEST_E2E_PLAYWRIGHT_ONION_TIMEOUT_MULTIPLIER] if (TEST_E2E_PLAYWRIGHT_IS_ONION | bool) else []) + ['-v', _playwright_stage_dir ~ ':/e2e'] + ['-v', _playwright_stage_dir ~ '/volume:/volume'] + ['-v', _playwright_reports_dir ~ ':/reports'] diff --git a/roles/test-e2e-playwright/vars/main.yml b/roles/test-e2e-playwright/vars/main.yml index df49130ac8..64acaaded7 100644 --- a/roles/test-e2e-playwright/vars/main.yml +++ b/roles/test-e2e-playwright/vars/main.yml @@ -34,6 +34,8 @@ TEST_E2E_PLAYWRIGHT_ONION_RUN_TIMEOUT: 5400 TEST_E2E_PLAYWRIGHT_RUN_TIMEOUT_EFFECTIVE: "{{ TEST_E2E_PLAYWRIGHT_ONION_RUN_TIMEOUT if (TEST_E2E_PLAYWRIGHT_IS_ONION | bool) else test_e2e_playwright_run_timeout }}" TEST_E2E_PLAYWRIGHT_ONION_TEST_TIMEOUT: 900000 +TEST_E2E_PLAYWRIGHT_ONION_TIMEOUT_MULTIPLIER: "{{ lookup('config', 'svc-net-tor', 'services.tor.timeout_multipliers')[lookup('config', 'svc-net-tor', 'services.tor.flavor')] + }}" TEST_E2E_PLAYWRIGHT_WAIT_ENABLED: true TEST_E2E_PLAYWRIGHT_WAIT_RETRIES: 30 TEST_E2E_PLAYWRIGHT_WAIT_DELAY: 5 @@ -41,3 +43,14 @@ TEST_E2E_PLAYWRIGHT_ONION_PROBE_RETRIES: 40 TEST_E2E_PLAYWRIGHT_ONION_PROBE_DELAY: 15 TEST_E2E_PLAYWRIGHT_NAVIGATION_TIMEOUT: 60000 TEST_E2E_PLAYWRIGHT_ONION_NAVIGATION_TIMEOUT: 180000 +TEST_E2E_PLAYWRIGHT_EXPECT_TIMEOUT: 10000 +TEST_E2E_PLAYWRIGHT_ONION_EXPECT_TIMEOUT: 30000 +TEST_E2E_PLAYWRIGHT_ACTION_TIMEOUT: 30000 +TEST_E2E_PLAYWRIGHT_ONION_ACTION_TIMEOUT: 90000 + +TEST_E2E_PLAYWRIGHT_CONFIG_TIMEOUTS: + PLAYWRIGHT_TEST_TIMEOUT: "{{ TEST_E2E_PLAYWRIGHT_ONION_TEST_TIMEOUT if (TEST_E2E_PLAYWRIGHT_IS_ONION | bool) else test_e2e_playwright_test_timeout }}" + PLAYWRIGHT_EXPECT_TIMEOUT: "{{ TEST_E2E_PLAYWRIGHT_ONION_EXPECT_TIMEOUT if (TEST_E2E_PLAYWRIGHT_IS_ONION | bool) else TEST_E2E_PLAYWRIGHT_EXPECT_TIMEOUT }}" + PLAYWRIGHT_NAVIGATION_TIMEOUT: "{{ TEST_E2E_PLAYWRIGHT_ONION_NAVIGATION_TIMEOUT if (TEST_E2E_PLAYWRIGHT_IS_ONION | bool) else TEST_E2E_PLAYWRIGHT_NAVIGATION_TIMEOUT + }}" + PLAYWRIGHT_ACTION_TIMEOUT: "{{ TEST_E2E_PLAYWRIGHT_ONION_ACTION_TIMEOUT if (TEST_E2E_PLAYWRIGHT_IS_ONION | bool) else TEST_E2E_PLAYWRIGHT_ACTION_TIMEOUT }}" diff --git a/roles/update/README.md b/roles/update/README.md index 8704fa200f..fbdb3e21fd 100644 --- a/roles/update/README.md +++ b/roles/update/README.md @@ -66,7 +66,7 @@ make compose-deploy mode=reinstall apps=update full_cycle=false ### Production -Install Package update directly onto the target machine โ€” clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): +Install Package update directly onto the target machine: clone the repository, install the OS prerequisites and the repository toolchain, then deploy against localhost over a local connection (no SSH, no container): ```bash git clone https://github.com/infinito-nexus/core.git @@ -76,6 +76,7 @@ make install source scripts/meta/env/load.sh APP=update +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" INVENTORY=inventories/production @@ -83,7 +84,7 @@ infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host localhost \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv diff --git a/roles/update/meta/info.yml b/roles/update/meta/info.yml new file mode 100644 index 0000000000..938c031874 --- /dev/null +++ b/roles/update/meta/info.yml @@ -0,0 +1,2 @@ +--- +# nocheck: info-media Self-written system-maintenance glue role that refreshes the package index and upgrades installed packages by dispatching to native OS package managers (apt/pacman/dnf); no single upstream product website. diff --git a/roles/update/meta/main.yml b/roles/update/meta/main.yml index 0208072e1b..43945d304b 100644 --- a/roles/update/meta/main.yml +++ b/roles/update/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written system-maintenance glue role that refreshes the package index and upgrades installed packages by dispatching to native OS package managers (apt/pacman/dnf); no single upstream product website. galaxy_info: author: Kevin Veen-Birkenbach description: System-maintenance role for refreshing the package index and upgrading installed packages via the OS package manager diff --git a/roles/user-backup/templates/ssh-wrapper.sh.j2 b/roles/user-backup/templates/ssh-wrapper.sh.j2 index fdffae7363..86e03d9763 100644 --- a/roles/user-backup/templates/ssh-wrapper.sh.j2 +++ b/roles/user-backup/templates/ssh-wrapper.sh.j2 @@ -1,9 +1,10 @@ #!/bin/sh +{# nocheck: shell-template grandfathered, values only: the backup directory and the repository list #} # log command if [ -n "$SSH_ORIGINAL_COMMAND" ] then - echo "`/bin/date`: $SSH_ORIGINAL_COMMAND" | systemd-cat -t "ssh-wrapper.sh" + echo "$(/bin/date): $SSH_ORIGINAL_COMMAND" | systemd-cat -t "ssh-wrapper.sh" fi get_hashed_machine_id="sha256sum /etc/machine-id"; diff --git a/roles/web-app-akaunting/README.md b/roles/web-app-akaunting/README.md index 3d948b1f28..3fa2744a38 100644 --- a/roles/web-app-akaunting/README.md +++ b/roles/web-app-akaunting/README.md @@ -96,19 +96,20 @@ Run the published image to provision the inventory and deploy Akaunting to a man ```bash APP=web-app-akaunting HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-akaunting/files/php/realign_admin_password.php b/roles/web-app-akaunting/files/php/realign_admin_password.php new file mode 100644 index 0000000000..561edd1c4c --- /dev/null +++ b/roles/web-app-akaunting/files/php/realign_admin_password.php @@ -0,0 +1,20 @@ +// Tinker snippet, not a standalone script: it is passed to `artisan tinker --execute`, +// which evaluates PHP without an opening tag. +// +// Reads ADMIN_EMAIL and ADMIN_PASSWORD from the environment so neither reaches a +// command line. Prints CHANGED, UNCHANGED or FAILED. +// +// The password is assigned in clear text on purpose. User::setPasswordAttribute +// bcrypts it on save, so hashing here would store a hash of a hash. +$email = getenv('ADMIN_EMAIL'); +$password = getenv('ADMIN_PASSWORD'); +$user = $email ? \App\Models\Auth\User::where('email', $email)->first() : null; +if (!$user) { + echo "FAILED: no user with email " . var_export($email, true) . "\n"; +} elseif (\Illuminate\Support\Facades\Hash::check($password, (string) $user->password)) { + echo "UNCHANGED\n"; +} else { + $user->password = $password; + $user->save(); + echo "CHANGED\n"; +} diff --git a/roles/web-app-akaunting/meta/info.yml b/roles/web-app-akaunting/meta/info.yml index afe0c2c669..ca648cc9e5 100644 --- a/roles/web-app-akaunting/meta/info.yml +++ b/roles/web-app-akaunting/meta/info.yml @@ -2,4 +2,4 @@ logo: class: fa-solid fa-file-invoice-dollar homepage: https://akaunting.com/ -video: https://www.youtube.com/akaunting +video: https://www.youtube.com/watch?v=UTVe_Zob_k0 diff --git a/roles/web-app-akaunting/meta/services.yml b/roles/web-app-akaunting/meta/services.yml index 4433e8e5cf..caa489020f 100644 --- a/roles/web-app-akaunting/meta/services.yml +++ b/roles/web-app-akaunting/meta/services.yml @@ -38,7 +38,6 @@ ldap: akaunting: healthcheck: flavor: tcp - start_period: 10m modes: compose: enabled: true diff --git a/roles/web-app-akaunting/tasks/01_setup.yml b/roles/web-app-akaunting/tasks/01_setup.yml index 86845d9828..b5340e7ee5 100644 --- a/roles/web-app-akaunting/tasks/01_setup.yml +++ b/roles/web-app-akaunting/tasks/01_setup.yml @@ -24,3 +24,26 @@ path: "{{ AKAUNTING_SETUP_MARKER }}" state: touch mode: "0644" + +- name: "๐Ÿ” Akaunting | Resolve the 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: "akaunting" + resolve_output_prefix: AKAUNTING + resolve_compose_cid: "{{ AKAUNTING_CONTAINER }}" + +- name: "๐Ÿ”‘ Akaunting | Realign the administrator password with the declared one" + ansible.builtin.shell: > # nocheck: container-exec-resolver AKAUNTING_LOCAL_CID resolved at delegate_to runtime + container exec + -e ADMIN_EMAIL={{ AKAUNTING_ADMIN_EMAIL | quote }} + -e ADMIN_PASSWORD={{ AKAUNTING_ADMIN_PASSWORD | quote }} + {{ AKAUNTING_LOCAL_CID | quote }} + php artisan tinker --execute={{ lookup('file', 'php/realign_admin_password.php') | quote }} + register: akaunting_admin_password + changed_when: "'CHANGED' in akaunting_admin_password.stdout" + failed_when: >- + akaunting_admin_password.rc != 0 + or 'FAILED' in akaunting_admin_password.stdout + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ AKAUNTING_HOST_NODE }}" + run_once: true diff --git a/roles/web-app-akaunting/vars/main.yml b/roles/web-app-akaunting/vars/main.yml index f41b227a13..b08964bc27 100644 --- a/roles/web-app-akaunting/vars/main.yml +++ b/roles/web-app-akaunting/vars/main.yml @@ -6,8 +6,8 @@ database_password: "{{ lookup('config', application_id, 'secrets.credentials.dat AKAUNTING_URL: "{{ lookup('tls', application_id, 'url.base') }}" AKAUNTING_IMAGE: "{{ lookup('config', application_id, 'services.akaunting.image') }}" AKAUNTING_VERSION: "{{ lookup('config', application_id, 'services.akaunting.version') }}" -AKAUNTING_REPOSITORY: "{{ lookup('config', application_id, 'services.akaunting.repository') }}" -AKAUNTING_REF: "{{ lookup('config', application_id, 'services.akaunting.ref') }}" +AKAUNTING_REPOSITORY: "{{ lookup('config', 'web-app-akaunting', 'services.akaunting.repository') }}" +AKAUNTING_REF: "{{ lookup('config', 'web-app-akaunting', 'services.akaunting.ref') }}" AKAUNTING_CONTAINER: "{{ lookup('config', application_id, 'services.akaunting.name') }}" AKAUNTING_VOLUME: "{{ lookup('volume', application_id, 'data').name }}" AKAUNTING_COMPANY_NAME: "{{ lookup('config', application_id, 'services.akaunting.company.name') }}" diff --git a/roles/web-app-baserow/README.md b/roles/web-app-baserow/README.md index e77eb56c8f..fdeeb930df 100644 --- a/roles/web-app-baserow/README.md +++ b/roles/web-app-baserow/README.md @@ -20,9 +20,12 @@ flowchart LR dep_svc_db_redis["svc-db-redis ๐Ÿณ๐Ÿ"] dep_svc_net_tor["svc-net-tor ๐Ÿณ๐Ÿ"] dep_web_app_dashboard["web-app-dashboard ๐Ÿณ๐Ÿ"] + dep_web_app_hermes["web-app-hermes ๐Ÿณ๐Ÿ"] dep_web_app_keycloak["web-app-keycloak ๐Ÿณ๐Ÿ"] dep_web_app_mailu["web-app-mailu ๐Ÿณ๐Ÿ"] dep_web_app_matomo["web-app-matomo ๐Ÿณ๐Ÿ"] + dep_web_app_openclaw["web-app-openclaw ๐Ÿณ๐Ÿ"] + dep_web_app_openwebui["web-app-openwebui ๐Ÿณ๐Ÿ"] dep_web_app_prometheus["web-app-prometheus ๐Ÿณ๐Ÿ"] dep_web_app_seaweedfs["web-app-seaweedfs ๐Ÿณ๐Ÿ"] dep_web_svc_css["web-svc-css ๐Ÿ’ป"] @@ -39,20 +42,28 @@ flowchart LR svc_minio["minio โŒ"] svc_seaweedfs["seaweedfs"] svc_baserow["baserow"] + svc_baserowmcp["baserowmcp"] svc_css["css"] svc_javascript["javascript"] svc_prometheus["prometheus"] svc_tor["tor"] svc_container_backup["container_backup"] + svc_openwebui["openwebui"] + svc_hermes["hermes"] + svc_openclaw["openclaw"] + svc_flowise["flowise โŒ"] end dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup dep_svc_db_postgres -. "0..1" .-> svc_postgres dep_svc_db_redis -. "0..1" .-> svc_redis dep_svc_net_tor -. "0..1" .-> svc_tor dep_web_app_dashboard -. "0..1" .-> svc_dashboard + dep_web_app_hermes -. "0..1" .-> svc_hermes dep_web_app_keycloak -. "0..1" .-> svc_sso dep_web_app_mailu -. "0..1" .-> svc_email dep_web_app_matomo -. "0..1" .-> svc_matomo + dep_web_app_openclaw -. "0..1" .-> svc_openclaw + dep_web_app_openwebui -. "0..1" .-> svc_openwebui dep_web_app_prometheus -. "0..1" .-> svc_prometheus dep_web_app_seaweedfs -. "0..1" .-> svc_seaweedfs dep_web_svc_css -. "0..1" .-> svc_css @@ -68,6 +79,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - **Dynamic Customization:** Adapt workflows and database structures to suit your specific needs. - **Scalable Architecture:** Efficiently handle increasing workloads while maintaining high performance. - **Robust API Integration:** Leverage a comprehensive API to extend functionalities and integrate with other systems. +- **MCP Server:** Serve four read-only Baserow tools to AI clients through a bearer-guarded adapter sidecar that fronts the native SSE endpoint. ## Quick Setup @@ -89,19 +101,20 @@ Run the published image to provision the inventory and deploy Baserow to a manag ```bash APP=web-app-baserow HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' @@ -138,6 +151,90 @@ Configuration is controlled via `applications..bootstrap_admin.*`: - `email` - `password` (should come from vault/credentials) +## MCP Server + +Baserow ships a native MCP server in the OSS backend, mounted on the ASGI root +ahead of Django. Clients do not reach it. The role runs it as the *upstream* of +a [`svc-ai-mcp-adapter`](../svc-ai-mcp-adapter/README.md) sidecar +(`classification: adapter_server`), and the sidecar is the only MCP surface a +consumer is given. + +The reason is the endpoint's own shape: Baserow's `MCPEndpoint` carries no +scope column, so the endpoint key grants every tool the backend implements โ€” +including the three write tools โ€” with no way to narrow it. The adapter is what +narrows it, by serving four read tools and refusing every other name. + +### Topology + +``` +consumer โ”€โ”€Bearerโ”€โ”€> baserowmcp (adapter) โ”€โ”€endpoint-key in URLโ”€โ”€> baserow:80/mcp +``` + +| Property | Value | +| --- | --- | +| Client transport | `streamable_http` at `http://baserowmcp:/mcp` | +| Client auth | `Authorization: Bearer ` | +| Upstream transport | HTTP+SSE (`adapter.upstream_transport: sse`) | +| Upstream stream | `GET http://baserow:80/mcp//sse` | +| Upstream messages | `POST http://baserow:80/mcp/messages/?session_id=` | + +The SSE session travels through the shared Redis channel layer, so the stream +and the message POST may land on different replicas. + +### Auth + +Two credentials, in two directions. + +Client to adapter: `credentials.mcp_bearer`, owned by `mcp-web-app-baserow`. +The adapter refuses any request that does not present it, so a caller on the +container network is no longer implicitly trusted. + +Adapter to Baserow: the endpoint key, which Baserow reads from the URL *path*, +not from a header. It reaches the sidecar as `ADAPTER_UPSTREAM_PATH_KEY` and is +spliced in by `policy.upstream_url()`, so it never enters the rendered contract +the sidecar advertises. The key is generated as `credentials.mcp_endpoint_key` +(32 hex characters, matching the `varchar(32)` column). An unknown key answers +`401 Endpoint not found.`. + +[`tasks/utils/mcp.yml`](./tasks/utils/mcp.yml) creates a dedicated non-superuser +owner (`mcp@`, unusable password) plus its own workspace, and +binds the endpoint to that pair. + +### Tools + +Served: `get_table_schema`, `list_databases`, `list_table_rows`, `list_tables`. + +Refused: the ten remaining tools Baserow 2.3.3 implements, listed under +`tools.upstream_serves`. Three of them (`create_rows`, `update_rows`, +`delete_rows`) are live upstream โ€” the image carries no env var, setting or UI +toggle that removes them, so `mutating_tools_enabled: false` is enforced by the +adapter and by nothing in Baserow. The other seven are shipped disabled +upstream and are listed so a version bump that enables one shows up as contract +drift rather than as a silently widened surface. + +The four served schemas are pinned in +[`files/mcp/tools.json`](./files/mcp/tools.json) and hashed into +`tools.schema_sha256`; the adapter refuses to start when the two disagree. + +### Authorization subject + +`auth_subject: service_account`. A call arrives at Baserow as the endpoint owner +regardless of who asked the client, and reaches only the one workspace that +account owns. That is the second bound under the adapter's allowlist, not a +substitute for it. + +### Default state + +Off. `mcp.enabled` is true only while an MCP client role is part of the +deployment. + +### How to disable + +Remove the MCP client role, or pin `mcp.enabled: false` for this role in the +inventory. The endpoint is then not provisioned, the sidecar is not deployed, +and `BASEROW_EXTRA_PUBLIC_URLS` drops the MCP origin, so the image's Caddy layer +stops routing `/mcp/*`. + ## Security: SECRET_KEY Baserow requires Django `SECRET_KEY` for correct backend operation (e.g., JWT, sessions). diff --git a/roles/web-app-baserow/files/mcp/tools.json b/roles/web-app-baserow/files/mcp/tools.json new file mode 100644 index 0000000000..12e548eba5 --- /dev/null +++ b/roles/web-app-baserow/files/mcp/tools.json @@ -0,0 +1,70 @@ +{ + "get_table_schema": { + "description": "Get the field schema for one or more tables.", + "input_schema": { + "properties": { + "table_ids": { + "description": "List of table IDs to get the schema for.", + "items": { + "type": "integer" + }, + "type": "array" + } + }, + "required": [ + "table_ids" + ], + "type": "object" + }, + "mutating": false + }, + "list_databases": { + "description": "List all databases in the workspace. Use this to discover database IDs before listing tables.", + "input_schema": { + "properties": {}, + "type": "object" + }, + "mutating": false + }, + "list_table_rows": { + "description": "List rows from a table with optional search and pagination. Returns rows with user-facing field names as keys.", + "input_schema": { + "properties": { + "page": { + "description": "Page number (1-based).", + "type": "integer" + }, + "search": { + "description": "Optional search term to filter rows.", + "type": "string" + }, + "size": { + "description": "Maximum number of rows to return.", + "type": "integer" + }, + "table_id": { + "description": "The ID of the table to list rows from.", + "type": "integer" + } + }, + "required": [ + "table_id" + ], + "type": "object" + }, + "mutating": false + }, + "list_tables": { + "description": "List all tables in the workspace, optionally filtered by database.", + "input_schema": { + "properties": { + "database_id": { + "description": "If provided, only return tables from this database.", + "type": "integer" + } + }, + "type": "object" + }, + "mutating": false + } +} diff --git a/roles/web-app-baserow/files/playwright/playwright.spec.js b/roles/web-app-baserow/files/playwright/playwright.spec.js index 3b672c40d3..30e7747afc 100644 --- a/roles/web-app-baserow/files/playwright/playwright.spec.js +++ b/roles/web-app-baserow/files/playwright/playwright.spec.js @@ -5,3 +5,4 @@ require("./test-guest-persona"); require("./test-biber-persona"); require("./test-administrator-persona"); require("./test-seaweedfs"); +require("./test-mcp"); diff --git a/roles/web-app-baserow/files/playwright/test-mcp.js b/roles/web-app-baserow/files/playwright/test-mcp.js new file mode 100644 index 0000000000..0d78c9d818 --- /dev/null +++ b/roles/web-app-baserow/files/playwright/test-mcp.js @@ -0,0 +1,33 @@ +const { test, expect } = require("@playwright/test"); +const { skipUnlessServiceEnabled } = require("./service-gating"); +const { normalizeBaseUrl } = require("./personas"); +const { registerMcpDisabledState } = require("./mcp-endpoint"); + +const UNKNOWN_ENDPOINT_KEY = "0".repeat(32); + +test.use({ ignoreHTTPSErrors: true }); + +test("mcp: an unauthenticated probe of the MCP endpoint is rejected", async ({ page }) => { + skipUnlessServiceEnabled("mcp"); + + const baseUrl = normalizeBaseUrl(process.env.BASEROW_BASE_URL || ""); + expect(baseUrl, "BASEROW_BASE_URL must be set").toBeTruthy(); + + const response = await page.request.get(`${baseUrl}/mcp/${UNKNOWN_ENDPOINT_KEY}/sse`, { + failOnStatusCode: false, + }); + + expect( + response.headers()["content-type"] || "", + "a probe carrying no valid endpoint key must never be upgraded to the MCP stream", + ).not.toContain("text/event-stream"); + expect( + await response.text(), + "a probe carrying no valid endpoint key must never receive an MCP session endpoint", + ).not.toContain("event: endpoint"); +}); + +registerMcpDisabledState( + () => + `${normalizeBaseUrl(process.env.BASEROW_BASE_URL || "")}/mcp/${UNKNOWN_ENDPOINT_KEY}/sse`, +); diff --git a/roles/web-app-baserow/files/playwright/test-seaweedfs.js b/roles/web-app-baserow/files/playwright/test-seaweedfs.js index 7fd4c30085..f2054ca091 100644 --- a/roles/web-app-baserow/files/playwright/test-seaweedfs.js +++ b/roles/web-app-baserow/files/playwright/test-seaweedfs.js @@ -24,6 +24,21 @@ async function readJson(response, label) { return body ? JSON.parse(body) : null; } +async function postWhileTableLocked(appPage, url, options, label) { + const deadline = Date.now() + 60_000; + for (;;) { + const response = await appPage.request.post(url, options); + if (response.status() !== 409) { + return readJson(response, label); + } + const body = await response.text(); + if (!body.includes("ERROR_FAILED_TO_LOCK_TABLE_DUE_TO_CONFLICT") || Date.now() > deadline) { + expect(false, `${label} failed with 409: ${body}`).toBe(true); + } + await appPage.waitForTimeout(resolveTimeout(500)); + } +} + async function getBaserowSession(appPage, baseUrl, adminUsername, adminPassword) { await appPage.context().clearCookies(); await appPage.goto(`${baseUrl}/`, { waitUntil: "domcontentloaded" }); @@ -75,11 +90,10 @@ async function createBaserowFileRow(appPage, baseUrl, accessToken) { "table creation", ); - const fileField = await readJson( - await appPage.request.post(`${baseUrl}/api/database/fields/table/${table.id}/`, { - headers: jsonHeaders, - data: { name: "Attachment", type: "file" }, - }), + const fileField = await postWhileTableLocked( + appPage, + `${baseUrl}/api/database/fields/table/${table.id}/`, + { headers: jsonHeaders, data: { name: "Attachment", type: "file" } }, "file field creation", ); diff --git a/roles/web-app-baserow/files/python/probe_mcp_endpoint.py b/roles/web-app-baserow/files/python/probe_mcp_endpoint.py new file mode 100644 index 0000000000..42eda67bf4 --- /dev/null +++ b/roles/web-app-baserow/files/python/probe_mcp_endpoint.py @@ -0,0 +1,54 @@ +# nocheck: mirrored-unit-test - reads MCP_BASE_URL and the endpoint key from the +# container environment at import and then drives a live SSE handshake; the module +# cannot be loaded outside the running Baserow container +import os +import sys +import urllib.error +import urllib.request + +base_url = os.environ["MCP_BASE_URL"].rstrip("/") +endpoint_path = os.environ["MCP_ENDPOINT_PATH"] +key = os.environ["MCP_ENDPOINT_KEY"] + +TIMEOUT = 15 +STREAM_LINES = 4 + +TRANSIENT_STATUS = frozenset({0, 429, 502, 503, 504}) + + +def refuse(message, status): + marker = "PENDING" if status in TRANSIENT_STATUS else "REJECTED" + sys.stderr.write(f"{marker} {message}\n") + sys.exit(1) + + +def probe(candidate): + """Return (status, content_type, first stream lines) of an SSE GET. + + Args: + candidate: endpoint key placed in the URL path. + """ + url = f"{base_url}{endpoint_path}/{candidate}/sse" + try: + with urllib.request.urlopen(url, timeout=TIMEOUT) as response: # noqa: S310 fixed internal http origin + lines = [response.readline() for _ in range(STREAM_LINES)] + return response.status, response.headers.get("Content-Type", ""), lines + except urllib.error.HTTPError as error: + return error.code, error.headers.get("Content-Type", ""), [] + except OSError: + return 0, "", [] + + +status, content_type, _ = probe("0" * len(key)) +if status != 401: + refuse(f"unauthenticated probe answered {status} {content_type}", status) + +status, content_type, lines = probe(key) +if status != 200 or "text/event-stream" not in content_type: + refuse(f"authenticated probe answered {status} {content_type}", status) + +stream = b"".join(lines) +if b"event: endpoint" not in stream: + refuse(f"authenticated probe streamed {stream!r}", None) + +print("OK") diff --git a/roles/web-app-baserow/files/python/provision_mcp.py b/roles/web-app-baserow/files/python/provision_mcp.py new file mode 100644 index 0000000000..fba5dfc2c4 --- /dev/null +++ b/roles/web-app-baserow/files/python/provision_mcp.py @@ -0,0 +1,54 @@ +# nocheck: mirrored-unit-test - imports baserow.core and django at module level and +# writes through the ORM inside `baserow-cli`; neither the framework nor a database is +# available outside the Baserow image +import os + +from baserow.core.handler import CoreHandler +from baserow.core.mcp.models import MCPEndpoint +from baserow.core.models import UserProfile, WorkspaceUser +from django.contrib.auth import get_user_model + +email = os.environ["MCP_OWNER_EMAIL"] +workspace_name = os.environ["MCP_WORKSPACE_NAME"] +endpoint_name = os.environ["MCP_ENDPOINT_NAME"] +key = os.environ["MCP_ENDPOINT_KEY"] + +User = get_user_model() + +owner, owner_created = User.objects.get_or_create( + username=email, + defaults={"email": email, "first_name": endpoint_name}, +) + +if owner_created: + owner.set_unusable_password() + owner.save() + +UserProfile.objects.get_or_create( + user=owner, + defaults={"email_verified": True, "completed_onboarding": True}, +) + +membership = WorkspaceUser.objects.filter( + user=owner, workspace__name=workspace_name +).first() + +if membership is None: + membership = CoreHandler().create_workspace(owner, name=workspace_name) + +previous_key = ( + MCPEndpoint.objects.filter( + user=owner, workspace=membership.workspace, name=endpoint_name + ) + .values_list("key", flat=True) + .first() +) + +MCPEndpoint.objects.update_or_create( + user=owner, + workspace=membership.workspace, + name=endpoint_name, + defaults={"key": key}, +) + +print("CHANGED" if owner_created or previous_key != key else "UNCHANGED") diff --git a/roles/web-app-baserow/files/test/.nocheck b/roles/web-app-baserow/files/test/.nocheck new file mode 100644 index 0000000000..2b9d82d840 --- /dev/null +++ b/roles/web-app-baserow/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; test-e2e-cli stages files/test/ by that fixed path. diff --git a/roles/web-app-baserow/files/test/test.sh b/roles/web-app-baserow/files/test/test.sh new file mode 100644 index 0000000000..18d8a31dd5 --- /dev/null +++ b/roles/web-app-baserow/files/test/test.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# CLI test for web-app-baserow: the MCP endpoint honours its declared contract. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +bash "${here}/shared/mcp/run.sh" diff --git a/roles/web-app-baserow/meta/mcp.yml b/roles/web-app-baserow/meta/mcp.yml new file mode 100644 index 0000000000..17f82c7bc3 --- /dev/null +++ b/roles/web-app-baserow/meta/mcp.yml @@ -0,0 +1,58 @@ +--- +classification: adapter_server +direction: server +source_url: https://baserow.io/user-docs/mcp-server # nocheck: url โ€” page is live (HEAD+GET 200); baserow.io edge intermittently 404s CI runner IPs +transport: streamable_http +exposure: internal +auth: bearer_token +auth_subject: service_account +implementation: adapter +credential: + owner: mcp-web-app-baserow + source: credentials + key: mcp_bearer +adapter: + type: mcp_passthrough + upstream_transport: sse + specification_path: roles/web-app-baserow/files/mcp/tools.json + specification_sha256: sha256:716effccfedbb6e83cacd489bf0c2cf8f318853f9b20bf8fd733db4e637ec144 + upstream_path: /mcp +endpoint: + service_key: baserowmcp + path: /mcp + port_key: http +limits: + request_bytes: 65536 + response_bytes: 1048576 + timeout_seconds: 15 + concurrent_requests: 4 + page_size: 100 + result_items: 100 + stream_seconds: 300 +tools: + read_probe: + tool: list_databases + arguments: {} + allowlist: + - get_table_schema + - list_databases + - list_table_rows + - list_tables + upstream_serves: + - create_database + - create_fields + - create_rows + - create_table + - delete_fields + - delete_rows + - delete_table + - get_table_schema + - list_databases + - list_table_rows + - list_tables + - update_fields + - update_rows + - update_table + schema_sha256: sha256:f38460244b77a14edc1933fd29dd34b063256496a3bb5cc0506d0833d7d20be7 + read_only_default: true + mutating_tools_enabled: false diff --git a/roles/web-app-baserow/meta/networks.yml b/roles/web-app-baserow/meta/networks.yml index a01b8348fd..e833be7012 100644 --- a/roles/web-app-baserow/meta/networks.yml +++ b/roles/web-app-baserow/meta/networks.yml @@ -1,3 +1,8 @@ --- local: subnet: 192.168.1.0/24 +overlay: + modes: [compose, swarm] + topology: shared_net + consumer: + kind: mcp_client diff --git a/roles/web-app-baserow/meta/rbac.yml b/roles/web-app-baserow/meta/rbac.yml index 0c37d62134..084e6fbeca 100644 --- a/roles/web-app-baserow/meta/rbac.yml +++ b/roles/web-app-baserow/meta/rbac.yml @@ -1,2 +1,4 @@ --- -roles: {} +roles: + mcp: + description: Can drive this application through an MCP client, which acts with the credentials the deployment issued rather than the caller's own diff --git a/roles/web-app-baserow/meta/secrets.yml b/roles/web-app-baserow/meta/secrets.yml index ba14e6612f..9a9ba9616f 100644 --- a/roles/web-app-baserow/meta/secrets.yml +++ b/roles/web-app-baserow/meta/secrets.yml @@ -5,3 +5,13 @@ credentials: algorithm: alphanumeric validation: min_length: 50 + mcp_bearer: + description: Bearer an MCP client presents to the Baserow adapter sidecar. Distinct from the endpoint key the sidecar presents upstream, because reaching + Baserow says nothing about who called the adapter. + algorithm: alphanumeric + validation: "^[A-Za-z0-9]{32,}$" + length: 48 + mcp_endpoint_key: + description: URL-path secret of the MCP endpoint, stored in MCPEndpoint.key (varchar 32) + algorithm: random_hex_16 + validation: "^[a-f0-9]{32}$" diff --git a/roles/web-app-baserow/meta/services.yml b/roles/web-app-baserow/meta/services.yml index 75be60d778..8bcdde0165 100644 --- a/roles/web-app-baserow/meta/services.yml +++ b/roles/web-app-baserow/meta/services.yml @@ -53,12 +53,16 @@ seaweedfs: enabled: "{{ 'web-app-seaweedfs' in group_names }}" shared: "{{ 'web-app-seaweedfs' in group_names }}" public: true +# nocheck: playwright-service-flag baserow: modes: compose: enabled: true swarm: enabled: true + bond: 1 + enabled: true + shared: true backup: no_stop_required: true image: baserow/baserow @@ -85,6 +89,27 @@ baserow: - web-app-mailu - web-app-seaweedfs lifecycle: beta +# nocheck: playwright-service-flag internal adapter sidecar, covered by the role's MCP spec +# nocheck: dockerfile-custom the Dockerfile is owned by svc-ai-mcp-adapter and staged into this role's instance directory +# nocheck: dynamic-flag the sidecar tracks this role's own mcp flag, not another role's presence; a group_names expression would decide its exposure from an unrelated deployment +baserowmcp: + enabled: "{{ lookup('config', 'web-app-baserow', 'mcp.enabled') | bool }}" + shared: false + image: python + # nocheck: docker-version base of the self-built stdlib adapter, not the served application + version: "3.13.15-slim" + custom: true + name: baserowmcp + cpus: "0.25" + mem_reservation: 16m + mem_limit: 24m + pids_limit: 64 + healthcheck: + flavor: http_status + path: health + ports: + internal: + http: 8080 # nocheck: playwright-service-flag โ€” css consumer, no Playwright surface (provider: web-svc-css) css: bond: 1 @@ -113,3 +138,24 @@ container_backup: # nocheck: bond-baseline backup host joins outside the variant bond: 1 enabled: "{{ 'svc-bkp-volume-2-local' in group_names }}" shared: true +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openwebui: + bond: 0.5 + enabled: "{{ 'web-app-openwebui' in group_names }}" + shared: "{{ 'web-app-openwebui' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +hermes: + bond: 0.5 + enabled: "{{ 'web-app-hermes' in group_names }}" + shared: "{{ 'web-app-hermes' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openclaw: + bond: 0.5 + enabled: "{{ 'web-app-openclaw' in group_names }}" + shared: "{{ 'web-app-openclaw' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +# nocheck: dynamic-flag the entry refuses this client, so the link is off on every host and no group_names gate can decide it +flowise: + enabled: false + shared: false + mcp_consumer: false diff --git a/roles/web-app-baserow/meta/tests.yml b/roles/web-app-baserow/meta/tests.yml new file mode 100644 index 0000000000..28bea0efe2 --- /dev/null +++ b/roles/web-app-baserow/meta/tests.yml @@ -0,0 +1,3 @@ +--- +cli: + timeout: 900 diff --git a/roles/web-app-baserow/meta/variants.yml b/roles/web-app-baserow/meta/variants.yml index b00bc810af..e98a9564c5 100644 --- a/roles/web-app-baserow/meta/variants.yml +++ b/roles/web-app-baserow/meta/variants.yml @@ -37,6 +37,15 @@ shared: true tor: enabled: true + openwebui: + enabled: true + shared: true + hermes: + enabled: true + shared: true + openclaw: + enabled: true + shared: true - services: container_backup: enabled: false @@ -71,3 +80,12 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + openwebui: + enabled: false + shared: false + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false diff --git a/roles/web-app-baserow/tasks/00_core.yml b/roles/web-app-baserow/tasks/00_core.yml new file mode 100644 index 0000000000..3f3d7f788e --- /dev/null +++ b/roles/web-app-baserow/tasks/00_core.yml @@ -0,0 +1,35 @@ +--- +- include_tasks: utils/once/flag.yml + +- name: "๐ŸŽฌ Stage the MCP adapter build context for {{ application_id }}" + include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/instance.yml') }}" + vars: + mcp_adapter_instance_dir: "{{ BASEROW_MCP_INSTANCE_DIR }}" + when: BASEROW_MCP_ENABLED | bool + +- name: "๐Ÿงฉ For '{{ application_id }}': load docker, db and proxy" + include_role: + name: sys-stk-full + vars: + compose_handlers_flush: false + +- name: "๐ŸŽฌ Stage trusted-header SSO build-context files for {{ application_id }}" + stack_host_copy: + src: "{{ item.src }}" + dest: "{{ [ lookup('container', application_id, 'directories.instance'), item.dest ] | path_join }}" + mode: "0644" + loop: + - { src: "Dockerfile", dest: "Dockerfile" } + - { src: "sso/infinito_sso.py", dest: "infinito_sso.py" } + - { src: "sso/settings_patch.py", dest: "settings_patch.py" } + +- name: "๐Ÿšฟ Flush compose handlers for {{ application_id }}" + ansible.builtin.meta: flush_handlers + +- name: "๐Ÿ‘” Baserow manager-side operations (file deploys + container exec)" + include_tasks: 01_manager_ops.yml + when: IS_STACK_HOST | bool + +- name: "๐Ÿ”Œ Provision the MCP server surface" + include_tasks: utils/mcp.yml + when: BASEROW_MCP_ENABLED | bool diff --git a/roles/web-app-baserow/tasks/01_manager_ops.yml b/roles/web-app-baserow/tasks/01_manager_ops.yml index a06bf9c6c4..695a9b2dcb 100644 --- a/roles/web-app-baserow/tasks/01_manager_ops.yml +++ b/roles/web-app-baserow/tasks/01_manager_ops.yml @@ -1,4 +1,11 @@ --- +- name: "๐Ÿ” Resolve {{ application_id }} hosting node + container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ BASEROW_SERVICE_NAME }}" + resolve_output_prefix: BASEROW + resolve_compose_cid: "{{ BASEROW_CONTAINER }}" + - name: "โ–ถ๏ธ Run Baserow Django migrations before bootstrapping users" ansible.builtin.shell: cmd: >- @@ -6,7 +13,7 @@ -e DJANGO_SETTINGS_MODULE={{ BASEROW_DJANGO_SETTINGS_MODULE | quote }} -e SECRET_KEY={{ BASEROW_SECRET_KEY | quote }} -e BASEROW_SECRET_KEY={{ BASEROW_SECRET_KEY | quote }} - {{ BASEROW_APP_CONTAINER_ADDRESS }} + {{ BASEROW_LOCAL_CID | quote }} {{ BASEROW_PYTHON }} {{ BASEROW_MANAGE_PY }} locked_migrate --noinput register: baserow_migrate_result no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" @@ -18,9 +25,11 @@ retries: 60 delay: 5 until: baserow_migrate_result.rc == 0 + delegate_to: "{{ BASEROW_HOST_NODE }}" + run_once: true - name: "๐Ÿ”„ Restart Baserow application after applying migrations (compose mode)" - ansible.builtin.command: "container restart {{ BASEROW_APP_CONTAINER_ADDRESS | quote }}" # nocheck: container-address-quote compose-gated task + ansible.builtin.command: "container restart {{ BASEROW_LOCAL_CID | quote }}" # nocheck: container-exec-resolver runtime-resolved CID register: baserow_restart_after_migrate changed_when: baserow_restart_after_migrate.rc == 0 when: @@ -36,6 +45,14 @@ - baserow_migrate_result.changed - DEPLOYMENT_MODE == 'swarm' +- name: "๐Ÿ” Re-resolve the container the restart replaced" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ BASEROW_SERVICE_NAME }}" + resolve_output_prefix: BASEROW + resolve_compose_cid: "{{ BASEROW_CONTAINER }}" + when: baserow_migrate_result.changed + - name: "๐ŸŽฌ Bootstrap Baserow superuser '{{ BASEROW_BOOTSTRAP_ADMIN_USERNAME }}'" ansible.builtin.shell: cmd: >- @@ -46,7 +63,7 @@ -e BOOTSTRAP_ADMIN_USERNAME={{ BASEROW_BOOTSTRAP_ADMIN_USERNAME | quote }} -e BOOTSTRAP_ADMIN_EMAIL={{ BASEROW_BOOTSTRAP_ADMIN_EMAIL | quote }} -e BOOTSTRAP_ADMIN_PASSWORD={{ BASEROW_BOOTSTRAP_ADMIN_PASSWORD | quote }} - {{ BASEROW_APP_CONTAINER_ADDRESS }} + {{ BASEROW_LOCAL_CID | quote }} {{ BASEROW_PYTHON }} {{ BASEROW_MANAGE_PY }} shell -c {{ lookup('file', role_path ~ '/files/python/bootstrap_admin.py') | quote }} register: baserow_bootstrap_admin_result no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" @@ -56,3 +73,5 @@ retries: 60 delay: 5 until: baserow_bootstrap_admin_result.rc == 0 + delegate_to: "{{ BASEROW_HOST_NODE }}" + run_once: true diff --git a/roles/web-app-baserow/tasks/main.yml b/roles/web-app-baserow/tasks/main.yml index 413a74d5f9..e1e8b720f0 100644 --- a/roles/web-app-baserow/tasks/main.yml +++ b/roles/web-app-baserow/tasks/main.yml @@ -1,23 +1,5 @@ --- -- name: "๐Ÿงฉ For '{{ application_id }}': load docker, db and proxy" - include_role: - name: sys-stk-full +- include_tasks: 00_core.yml + when: run_once_web_app_baserow is not defined vars: - compose_handlers_flush: false - -- name: "๐ŸŽฌ Stage trusted-header SSO build-context files for {{ application_id }}" - stack_host_copy: - src: "{{ item.src }}" - dest: "{{ [ lookup('container', application_id, 'directories.instance'), item.dest ] | path_join }}" - mode: "0644" - loop: - - { src: "Dockerfile", dest: "Dockerfile" } - - { src: "sso/infinito_sso.py", dest: "infinito_sso.py" } - - { src: "sso/settings_patch.py", dest: "settings_patch.py" } - -- name: "๐Ÿšฟ Flush compose handlers for {{ application_id }}" - ansible.builtin.meta: flush_handlers - -- name: "๐Ÿ‘” Baserow manager-side operations (file deploys + container exec)" - include_tasks: 01_manager_ops.yml - when: IS_STACK_HOST | bool + application_id: web-app-baserow diff --git a/roles/web-app-baserow/tasks/utils/mcp.yml b/roles/web-app-baserow/tasks/utils/mcp.yml new file mode 100644 index 0000000000..c36e23042a --- /dev/null +++ b/roles/web-app-baserow/tasks/utils/mcp.yml @@ -0,0 +1,83 @@ +--- +- name: "๐Ÿ” Resolve {{ application_id }} hosting node + container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ BASEROW_SERVICE_NAME }}" + resolve_output_prefix: BASEROW + resolve_compose_cid: "{{ BASEROW_CONTAINER }}" + +- name: "๐Ÿ”‘ Create the MCP endpoint, its owner and its workspace" + ansible.builtin.command: + argv: + - container + - exec + - -i + - -e + - "DJANGO_SETTINGS_MODULE={{ BASEROW_DJANGO_SETTINGS_MODULE }}" + - -e + - "SECRET_KEY={{ BASEROW_SECRET_KEY }}" + - -e + - "BASEROW_SECRET_KEY={{ BASEROW_SECRET_KEY }}" + - -e + - "MCP_OWNER_EMAIL={{ BASEROW_MCP_OWNER_EMAIL }}" + - -e + - "MCP_WORKSPACE_NAME={{ BASEROW_MCP_WORKSPACE_NAME }}" + - -e + - "MCP_ENDPOINT_NAME={{ BASEROW_MCP_ENDPOINT_NAME }}" + - -e + - "MCP_ENDPOINT_KEY={{ BASEROW_MCP_ENDPOINT_KEY }}" + - "{{ BASEROW_LOCAL_CID }}" # nocheck: container-exec-resolver + - "{{ BASEROW_PYTHON }}" + - "{{ BASEROW_MANAGE_PY }}" + - shell + - -c + - "{{ lookup('file', 'python/provision_mcp.py') }}" + register: baserow_mcp_provision + retries: 30 + delay: 10 + until: baserow_mcp_provision.rc == 0 + changed_when: "'CHANGED' in baserow_mcp_provision.stdout" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ BASEROW_HOST_NODE }}" + run_once: true + +- name: "๐Ÿฉบ Probe the MCP endpoint on the internal origin" + ansible.builtin.command: + argv: + - container + - exec + - -i + - -e + - "MCP_BASE_URL={{ BASEROW_INTERNAL_URL }}" + - -e + - "MCP_ENDPOINT_PATH={{ BASEROW_MCP_ENDPOINT_PATH }}" + - -e + - "MCP_ENDPOINT_KEY={{ BASEROW_MCP_ENDPOINT_KEY }}" + - "{{ BASEROW_LOCAL_CID }}" # nocheck: container-exec-resolver + - "{{ BASEROW_PYTHON }}" + - "-" + stdin: "{{ lookup('file', 'python/probe_mcp_endpoint.py') }}" + register: baserow_mcp_probe + retries: 30 + delay: 10 + until: baserow_mcp_probe.rc == 0 or 'REJECTED' in baserow_mcp_probe.stderr + failed_when: false + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ BASEROW_HOST_NODE }}" + run_once: true + +- name: "๐Ÿ›‘ Refuse an endpoint that never serves the MCP stream" + ansible.builtin.assert: + that: + - baserow_mcp_probe.rc == 0 + fail_msg: >- + {{ BASEROW_INTERNAL_URL }}{{ BASEROW_MCP_ENDPOINT_PATH }} did not answer 401 + for an unknown key and text/event-stream for the provisioned one, so every + MCP client would be pointed at a dead or unguarded endpoint. + +- name: "๐Ÿ” Rebuild the adapter sidecar against the current contract" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/rebuild.yml') }}" + +- name: "๐Ÿ”„ Start the sidecar before probing it" + ansible.builtin.meta: flush_handlers diff --git a/roles/web-app-baserow/templates/compose.yml.j2 b/roles/web-app-baserow/templates/compose.yml.j2 index c87db4757a..b41a7c46cc 100644 --- a/roles/web-app-baserow/templates/compose.yml.j2 +++ b/roles/web-app-baserow/templates/compose.yml.j2 @@ -15,5 +15,35 @@ {{ lookup('container_networks') | indent(4) }} {{ lookup('container_depends_on', application_id) | indent(4) }} + {% if BASEROW_MCP_ENABLED | bool %} + {% set service_name = 'baserowmcp' %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, 'baserowmcp') }} + build: + context: {{ BASEROW_MCP_INSTANCE_DIR }} + dockerfile: Dockerfile + args: + MCP_ADAPTER_BASE_IMAGE: {{ lookup('config', application_id, 'services.baserowmcp.image') }} + MCP_ADAPTER_BASE_VERSION: "{{ lookup('config', application_id, 'services.baserowmcp.version') }}" + {{ lookup('compose_only', 'container_name', BASEROW_MCP_CONTAINER) }} + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + environment: + ADAPTER_CONTRACT: {{ BASEROW_MCP_CONTRACT | to_json | to_json | replace('$', '$$') }} + ADAPTER_BEARER: {{ BASEROW_MCP_BEARER | to_json }} + ADAPTER_PORT: "{{ BASEROW_MCP_PORT }}" + ADAPTER_UPSTREAM_PATH_KEY: {{ BASEROW_MCP_ENDPOINT_KEY | to_json }} + ADAPTER_UPSTREAM_PATH_SUFFIX: "sse" + expose: + - "{{ BASEROW_MCP_PORT }}" + {{ lookup('container_healthcheck', 'baserowmcp') | indent(4) }} + {{ lookup('container_networks', own_network_only=True, provider_self_alias=False) | indent(4) }} + {{ lookup('depends_on', {'baserow': 'service_healthy'}) }} + {% endif %} + {{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/web-app-baserow/templates/env.j2 b/roles/web-app-baserow/templates/env.j2 index 8472dc1f8d..917ea72c85 100644 --- a/roles/web-app-baserow/templates/env.j2 +++ b/roles/web-app-baserow/templates/env.j2 @@ -1,6 +1,9 @@ {% include 'roles/sys-svc-container/templates/env.j2' %} BASEROW_PUBLIC_URL={{ BASEROW_PUBLIC_URL }} +{% if BASEROW_MCP_ENABLED | bool %} +BASEROW_EXTRA_PUBLIC_URLS={{ BASEROW_INTERNAL_URL }} +{% endif %} SECRET_KEY={{ BASEROW_SECRET_KEY | dotenv_quote }} BASEROW_SECRET_KEY={{ BASEROW_SECRET_KEY | dotenv_quote }} diff --git a/roles/web-app-baserow/templates/javascript.js.j2 b/roles/web-app-baserow/templates/javascript.js.j2 index 3d0b0324cb..8f947dae32 100644 --- a/roles/web-app-baserow/templates/javascript.js.j2 +++ b/roles/web-app-baserow/templates/javascript.js.j2 @@ -1,5 +1,5 @@ (function () { - const LOGOUT_URL = "{{ OIDC.CLIENT.LOGOUT_URL }}"; + const LOGOUT_URL = {{ lookup('sso', application_id, 'logout_url') | to_json }}; const INJECTED_ATTR = "data-injected-logout"; const LOGOUT_SVG = 'LittleJS Repository - + {{ LITTLEJS_HEADLINE }} Code diff --git a/roles/web-app-littlejs/vars/main.yml b/roles/web-app-littlejs/vars/main.yml index 65d9981b14..0c423d981c 100644 --- a/roles/web-app-littlejs/vars/main.yml +++ b/roles/web-app-littlejs/vars/main.yml @@ -9,8 +9,8 @@ LITTLEJS_HEADLINE: "LittleJS Playground" LITTLEJS_TITLE: "{{ LITTLEJS_HEADLINE }} โ€“ {{ DOMAIN_PRIMARY | upper }}" # Clone coordinates โ€” SPOT in meta/services.yml -LITTLEJS_REPOSITORY: "{{ lookup('config', application_id, 'services.littlejs.repository') }}" -LITTLEJS_REF: "{{ lookup('config', application_id, 'services.littlejs.ref') }}" +LITTLEJS_REPOSITORY: "{{ lookup('config', 'web-app-littlejs', 'services.littlejs.repository') }}" +LITTLEJS_REF: "{{ lookup('config', 'web-app-littlejs', 'services.littlejs.ref') }}" # Human-readable upstream link for nav_bottom.html (strip .git suffix) LITTLEJS_REPOSITORY_BASE: "{{ LITTLEJS_REPOSITORY | regex_replace('\\.git$', '') }}" diff --git a/roles/web-app-magento/README.md b/roles/web-app-magento/README.md index 69c9a9ce94..77c2b7236d 100644 --- a/roles/web-app-magento/README.md +++ b/roles/web-app-magento/README.md @@ -95,19 +95,20 @@ Run the published image to provision the inventory and deploy Magento to a manag ```bash APP=web-app-magento HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-magento/meta/info.yml b/roles/web-app-magento/meta/info.yml index 8ec419d9e7..5768f42183 100644 --- a/roles/web-app-magento/meta/info.yml +++ b/roles/web-app-magento/meta/info.yml @@ -2,4 +2,4 @@ logo: class: fa-solid fa-cart-shopping homepage: https://business.adobe.com/products/commerce/magento/open-source.html -video: https://www.youtube.com/user/magentocommerce +video: https://www.youtube.com/watch?v=nFdz9DZrdFc diff --git a/roles/web-app-magento/tasks/01_setup.yml b/roles/web-app-magento/tasks/01_setup.yml index 0264b81310..ffa05cedc6 100644 --- a/roles/web-app-magento/tasks/01_setup.yml +++ b/roles/web-app-magento/tasks/01_setup.yml @@ -77,6 +77,13 @@ ('Magento installation complete' in magento_install.stdout or 'successfully installed' in magento_install.stdout)) +- name: "๐Ÿ”‘ Realign the DB password Magento persisted in app/etc/env.php" + shell: > + container exec --user {{ MAGENTO_USER }} {{ MAGENTO_PHP_CONTAINER_ADDRESS }} bash -lc " + cd {{ MAGENTO_ROOT }} && bin/magento setup:config:set --no-interaction --db-password=\"\$MYSQL_PASSWORD\"" + register: magento_db_password_realign + changed_when: "'You saved the new configuration' in magento_db_password_realign.stdout" + - name: "๐Ÿ“ค Stage Magento's remote-storage configurator into the volume" ansible.builtin.copy: src: php/remote-storage.php diff --git a/roles/web-app-magento/templates/compose.yml.j2 b/roles/web-app-magento/templates/compose.yml.j2 index 33a26e1845..8ab9ce649d 100644 --- a/roles/web-app-magento/templates/compose.yml.j2 +++ b/roles/web-app-magento/templates/compose.yml.j2 @@ -11,9 +11,11 @@ {{ lookup('container_ports', ['magento', 'http', DOCKER_BIND_HOST]) | indent(4) }} healthcheck: test: ["CMD-SHELL", "nginx -t >/dev/null 2>&1 && nc -z {{ MAGENTO_PHP_HOST }} {{ MAGENTO_PHP_PORT }}"] - interval: 10s + interval: 2m timeout: 5s retries: 5 + start_period: 10m + start_interval: 5s {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} diff --git a/roles/web-app-mailu/README.md b/roles/web-app-mailu/README.md index 59d8cb68eb..3116e307c7 100644 --- a/roles/web-app-mailu/README.md +++ b/roles/web-app-mailu/README.md @@ -132,19 +132,20 @@ Run the published image to provision the inventory and deploy Mailu to a managed ```bash APP=web-app-mailu HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-mailu/files/playwright/playwright.spec.js b/roles/web-app-mailu/files/playwright/playwright.spec.js index 9c679a32bc..e8d48e7e58 100644 --- a/roles/web-app-mailu/files/playwright/playwright.spec.js +++ b/roles/web-app-mailu/files/playwright/playwright.spec.js @@ -16,6 +16,8 @@ const adminEmail = decodeDotenvQuotedValue(process.env.ADMIN_EMAIL); const biberUsername = decodeDotenvQuotedValue(process.env.BIBER_USERNAME); const biberPassword = decodeDotenvQuotedValue(process.env.BIBER_PASSWORD); const biberEmail = decodeDotenvQuotedValue(process.env.BIBER_EMAIL); +const POLL_INTERVAL_MS = 500; +const INBOX_REFRESH_INTERVAL_MS = 3_000; async function waitForFirstVisible(page, locators, timeout = resolveTimeout(60_000)) { const deadline = Date.now() + timeout; @@ -27,7 +29,7 @@ async function waitForFirstVisible(page, locators, timeout = resolveTimeout(60_0 } } - await page.waitForTimeout(resolveTimeout(500)); + await page.waitForTimeout(POLL_INTERVAL_MS); } throw new Error("Timed out waiting for one of the expected selectors to become visible"); @@ -73,7 +75,7 @@ async function waitForEmailInInbox(page, subjectText, timeout = resolveTimeout(6 // Refresh inbox by clicking the inbox folder await page.getByRole("link", { name: "Inbox" }).first().click().catch(() => {}); - await page.waitForTimeout(resolveTimeout(3_000)); + await page.waitForTimeout(INBOX_REFRESH_INTERVAL_MS); } throw new Error(`Timed out waiting for email with subject "${subjectText}" to arrive`); diff --git a/roles/web-app-mailu/lookup_plugins/mailu_users.py b/roles/web-app-mailu/lookup_plugins/mailu_users.py new file mode 100644 index 0000000000..833ca40d14 --- /dev/null +++ b/roles/web-app-mailu/lookup_plugins/mailu_users.py @@ -0,0 +1,88 @@ +"""Lookup ``mailu_users``: the subset of the user catalogue Mailu provisions. + +``lookup('users')`` yields every user any role declares -- 291 of them in a full +CI round -- while Mailu acts on seven. Looping the whole catalogue and letting +each task's ``when:`` discard the rest still pays a task execution per user per +task, which measured 259.5s of a single job. + +A user is Mailu's when it carries a mailbox account, or when it is a bot, whose +API token Mailu issues. Both halves are needed: the token task is gated on the +role, not on the account, so filtering by mailbox alone would silently stop +issuing tokens to a bot that has no mailbox of its own. + +The per-task ``when:`` conditions stay in place. This set is a superset of what +each of them selects, so it decides how often they are evaluated, never their +outcome. + +Returns the same dict shape ``lookup('users')`` yields, so call sites keep +``| dict2items`` and ``user_item.value.*`` unchanged. + +Usage, through the constant in ``vars/main.yml``: + + MAILU_USERS: "{{ lookup('mailu_users') }}" +""" + +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +MAILBOX_ACCOUNT = "mailbox" +BOT_ROLE = "bot" + + +def _string_list(user: dict[str, Any], key: str) -> list[str]: + """Read one list-valued user attribute, defaulting to empty. + + Args: + user: one entry of the merged user catalogue. + key: attribute name, ``accounts`` or ``roles``. + + Raises: + AnsibleError: the attribute is present but is not a list. + """ + value = user.get(key, []) + if value is None: + return [] + if not isinstance(value, (list, tuple)): + raise AnsibleError( + f"mailu_users: user '{user.get('username', '?')}' declares " + f"{key}={value!r}; a list is required." + ) + return [str(entry) for entry in value] + + +def provisioned_by_mailu(user: dict[str, Any]) -> bool: + """Return whether Mailu acts on this user at all.""" + return MAILBOX_ACCOUNT in _string_list( + user, "accounts" + ) or BOT_ROLE in _string_list(user, "roles") + + +class LookupModule(LookupBase): + def run( + self, + terms: list[Any] | None, + variables: dict[str, Any] | None = None, + **kwargs: Any, + ) -> list[dict[str, Any]]: + if terms: + raise AnsibleError("mailu_users lookup takes no positional terms") + + variables = variables or getattr(self._templar, "available_variables", {}) or {} + users = lookup_loader.get( + "users", + loader=getattr(self, "_loader", None), + templar=getattr(self, "_templar", None), + ).run([], variables=variables, **kwargs)[0] + + return [ + { + key: user + for key, user in users.items() + if isinstance(user, dict) and provisioned_by_mailu(user) + } + ] diff --git a/roles/web-app-mailu/meta/info.yml b/roles/web-app-mailu/meta/info.yml index ca0fa64d92..7c9ee3954b 100644 --- a/roles/web-app-mailu/meta/info.yml +++ b/roles/web-app-mailu/meta/info.yml @@ -1,4 +1,5 @@ --- +# nocheck: info-media no official demo video logo: class: fa-solid fa-envelope homepage: https://mailu.io/ diff --git a/roles/web-app-mailu/meta/main.yml b/roles/web-app-mailu/meta/main.yml index 5e555ea0e0..58c938260e 100644 --- a/roles/web-app-mailu/meta/main.yml +++ b/roles/web-app-mailu/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Self-hosted mail server suite with SMTP/IMAP/POP3, webmail, spam filtering, antivirus, DKIM signing, and TLS diff --git a/roles/web-app-mailu/meta/services.yml b/roles/web-app-mailu/meta/services.yml index e5ecaf8f48..8705b6d3d9 100644 --- a/roles/web-app-mailu/meta/services.yml +++ b/roles/web-app-mailu/meta/services.yml @@ -67,6 +67,13 @@ mailu: imap: 143 imaps: 993 sieve: 4190 + onion: + smtp: true + submission: true + imap: true + pop3: true + # nocheck: onion-flag ManageSieve edits server-side filters, which is administration rather than the sending and receiving the onion transport is for + sieve: false proxy: service_key: front run_after: diff --git a/roles/web-app-mailu/tasks/02_manager_ops/post_bootstrap_ops.yml b/roles/web-app-mailu/tasks/02_manager_ops/post_bootstrap_ops.yml index 3f486ee109..e29ee062de 100644 --- a/roles/web-app-mailu/tasks/02_manager_ops/post_bootstrap_ops.yml +++ b/roles/web-app-mailu/tasks/02_manager_ops/post_bootstrap_ops.yml @@ -18,7 +18,7 @@ mailu_token_name: "{{ SOFTWARE_NAME ~ ' Token for ' ~ user_item.value.username }}" mailu_user_roles: "{{ user_item.value.roles | default([]) }}" mailu_user_accounts: "{{ user_item.value.accounts | default([]) }}" - loop: "{{ lookup('users') | dict2items }}" + loop: "{{ MAILU_USERS | dict2items }}" loop_control: loop_var: user_item no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-mailu/templates/env.j2 b/roles/web-app-mailu/templates/env.j2 index e86ca8bc92..469b70fa0d 100644 --- a/roles/web-app-mailu/templates/env.j2 +++ b/roles/web-app-mailu/templates/env.j2 @@ -9,6 +9,7 @@ POSTMASTER=admin TLS_FLAVOR={{ MAILU_TLS_FLAVOR }} PORTS={{ MAILU_PORTS.values() | map('int') | unique | sort | join(',') }} AUTH_RATELIMIT=10/minute;1000/hour +MESSAGE_RATELIMIT_EXEMPTION={{ lookup('users', 'no-reply').email | lower }} DISABLE_STATISTICS=True ADMIN=true WEBMAIL=roundcube diff --git a/roles/web-app-mailu/vars/main.yml b/roles/web-app-mailu/vars/main.yml index 85653f16dd..67132cbd2e 100644 --- a/roles/web-app-mailu/vars/main.yml +++ b/roles/web-app-mailu/vars/main.yml @@ -45,6 +45,7 @@ MAILU_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') MAILU_OIDC_EMAIL_BY_USERNAME_ENABLED: "{{ lookup('config', application_id, 'services.sso.oidc.email_by_username') }}" MAILU_OIDC_ENABLE_USER_CREATION: "{{ lookup('config', application_id, 'services.sso.oidc.enable_user_creation') | string | capitalize }}" MAILU_EXTRA_HOSTS: "{{ query('mailu_extra_hosts') }}" +MAILU_USERS: "{{ lookup('mailu_users') }}" MAILU_DOCKER_FLAVOR: "{{ 'ghcr.io/heviat' if MAILU_OIDC_ENABLED | bool else 'ghcr.io/mailu' }}" MAILU_DMARC_RUF: "{{ lookup('config', application_id, 'users.administrator.email') }}" MAILU_DKIM_KEY_FILE: "{{ MAILU_DOMAIN }}.dkim.key" diff --git a/roles/web-app-mastodon/README.md b/roles/web-app-mastodon/README.md index 018205ac7c..5997b93ae6 100644 --- a/roles/web-app-mastodon/README.md +++ b/roles/web-app-mastodon/README.md @@ -98,19 +98,20 @@ Run the published image to provision the inventory and deploy Mastodon to a mana ```bash APP=web-app-mastodon HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-mastodon/meta/info.yml b/roles/web-app-mastodon/meta/info.yml index 0e433a5a51..99a1ca69b5 100644 --- a/roles/web-app-mastodon/meta/info.yml +++ b/roles/web-app-mastodon/meta/info.yml @@ -1,4 +1,5 @@ --- +# nocheck: info-media no official demo video logo: class: fa-solid fa-bullhorn homepage: https://joinmastodon.org/ diff --git a/roles/web-app-mastodon/meta/main.yml b/roles/web-app-mastodon/meta/main.yml index 2b36fcaf39..d5ce9f411a 100644 --- a/roles/web-app-mastodon/meta/main.yml +++ b/roles/web-app-mastodon/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Self-hosted federated social network for microblogging, real-time timelines, and community moderation diff --git a/roles/web-app-mastodon/meta/services.yml b/roles/web-app-mastodon/meta/services.yml index b0a0b7e0eb..9b25d00fd7 100644 --- a/roles/web-app-mastodon/meta/services.yml +++ b/roles/web-app-mastodon/meta/services.yml @@ -93,7 +93,9 @@ sidekiq: name: mastodon-sidekiq healthcheck: test: ["CMD-SHELL", "pgrep -f sidekiq || exit 1"] + # nocheck: healthcheck-timing-override a worker with no endpoint, so its liveness is checked rarely interval: 1m + # nocheck: healthcheck-timing-override carried over and never measured; pgrep fits the 5s default timeout: 10s cpus: "0.8" mem_reservation: 1g diff --git a/roles/web-app-mastodon/tasks/00_core.yml b/roles/web-app-mastodon/tasks/00_core.yml index 53b877980b..4e60f56b9b 100644 --- a/roles/web-app-mastodon/tasks/00_core.yml +++ b/roles/web-app-mastodon/tasks/00_core.yml @@ -6,7 +6,7 @@ name: sys-stk-front-proxy loop: "{{ lookup('domains', 'web-app-mastodon') }}" loop_control: - loop_var: domain + loop_var: domain # nocheck: loop-var-shadow sys-stk-front-proxy takes the vhost through this name, see its tasks/main.yml front_proxy_domain vars: http_port: "{{ lookup('config', application_id, 'services.mastodon.ports.local.http') }}" webserver_websocket_location: "/api/v1/streaming" diff --git a/roles/web-app-mastodon/tasks/01_overrides.yml b/roles/web-app-mastodon/tasks/01_overrides.yml index 9c080ae1f8..cbfcd51304 100644 --- a/roles/web-app-mastodon/tasks/01_overrides.yml +++ b/roles/web-app-mastodon/tasks/01_overrides.yml @@ -18,6 +18,11 @@ Rails.application.config.force_ssl = false Rails.application.config.middleware.delete ActionDispatch::SSL if defined?(ActionDispatch::SSL) Rails.application.routes.default_url_options[:protocol] = "http" + Rails.application.config.x.use_https = false + Rails.application.config.x.streaming_api_base_url = "ws://#{Rails.application.config.x.web_domain}" + ActiveSupport.on_load(:action_mailer) do + self.default_url_options = default_url_options.merge(protocol: "http://") + end notify: compose-up - name: "๐Ÿ“ฆ MASTODON | Install OIDC http-discovery override initializer (HTTP-only)" diff --git a/roles/web-app-mastodon/tasks/05_administrator.yml b/roles/web-app-mastodon/tasks/05_administrator.yml index b5aae2efca..339849ba71 100644 --- a/roles/web-app-mastodon/tasks/05_administrator.yml +++ b/roles/web-app-mastodon/tasks/05_administrator.yml @@ -17,11 +17,15 @@ --confirmed --role Owner" register: tootctl_create changed_when: tootctl_create.rc == 0 - failed_when: > - tootctl_create.rc != 0 - and - ("taken" not in tootctl_create.stderr | lower) + failed_when: false no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" +- name: ๐Ÿ›‘ Refuse a tootctl error other than the account already existing + ansible.builtin.assert: + that: + - tootctl_create.rc == 0 or 'taken' in tootctl_create.stdout | lower or 'taken' in tootctl_create.stderr | lower + fail_msg: >- + bin/tootctl accounts create exited {{ tootctl_create.rc }} for the administrator + account without reporting the name as taken: {{ tootctl_create.stderr }} - name: ๐Ÿ‘ Approve the administrator account in Mastodon ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec -u root {{ MASTODON_LOCAL_CID | quote }} bash -c "bin/tootctl accounts modify {{ lookup('users', 'administrator').username }} --approve" diff --git a/roles/web-app-matomo/README.md b/roles/web-app-matomo/README.md index 27e05386f9..49294f717c 100644 --- a/roles/web-app-matomo/README.md +++ b/roles/web-app-matomo/README.md @@ -108,19 +108,20 @@ Run the published image to provision the inventory and deploy Matomo to a manage ```bash APP=web-app-matomo HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-matomo/files/playwright/_shared.js b/roles/web-app-matomo/files/playwright/_shared.js index 3be96a9d2a..14f96da694 100644 --- a/roles/web-app-matomo/files/playwright/_shared.js +++ b/roles/web-app-matomo/files/playwright/_shared.js @@ -15,7 +15,7 @@ const biberUsername = decodeDotenvQuotedValue(process.env.BIBER_USERNAME); const biberPassword = decodeDotenvQuotedValue(process.env.BIBER_PASSWORD); const canonicalDomain = decodeDotenvQuotedValue(process.env.CANONICAL_DOMAIN); const matomoApiToken = decodeDotenvQuotedValue(process.env.MATOMO_API_TOKEN); -const matomoTrackingScope = (process.env.MATOMO_TRACKING_SCOPE || "sub").trim().toLowerCase(); +const matomoTrackingScope = (process.env.MATOMO_TRACKING_SCOPE || "").trim().toLowerCase(); const matomoCanonicalDomain = (() => { try { diff --git a/roles/web-app-matomo/meta/services.yml b/roles/web-app-matomo/meta/services.yml index 983b4cb94b..c1e3a80ea6 100644 --- a/roles/web-app-matomo/meta/services.yml +++ b/roles/web-app-matomo/meta/services.yml @@ -16,6 +16,13 @@ dashboard: shared: "{{ 'web-app-dashboard' in group_names }}" # nocheck: playwright-service-flag โ€” self-provider matomo: + healthcheck: + test: + - "CMD-SHELL" + - "code=\"$$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1/index.php || echo 000)\"; [ \"$$code\" -ge 200 ] && [ \"$$code\" -lt 400 ]" + retries: 12 + # nocheck: healthcheck-timing-override boots slower than the ten minute window; the value predates this default and has not been measured against it + start_period: 900s modes: compose: enabled: true diff --git a/roles/web-app-matomo/tasks/utils/patch/db_credentials.yml b/roles/web-app-matomo/tasks/utils/patch/db_credentials.yml new file mode 100644 index 0000000000..3e35087d80 --- /dev/null +++ b/roles/web-app-matomo/tasks/utils/patch/db_credentials.yml @@ -0,0 +1,7 @@ +--- +- name: "๐Ÿ”‘ Realign the password matomo persisted in its config" + include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-rdbms/tasks/utils/patch_persisted_password.yml') }}" + vars: + patch_volume: "matomo_data" + patch_config_rel: "config/config.ini.php" + patch_expression: "s|^password *=.*|password = @PASSWORD@|" diff --git a/roles/web-app-matomo/templates/compose.yml.j2 b/roles/web-app-matomo/templates/compose.yml.j2 index b03417bad3..e7b8ef95c7 100644 --- a/roles/web-app-matomo/templates/compose.yml.j2 +++ b/roles/web-app-matomo/templates/compose.yml.j2 @@ -10,15 +10,7 @@ MATOMO_VERSION: "{{ lookup('config', application_id, 'services.' ~ MATOMO_SERVICE ~ '.version') }}" {{ lookup('container_ports', ['matomo', 'http', DOCKER_BIND_HOST]) | indent(4) }} {{ lookup('container_volumes', service_name) | indent(4) }} - healthcheck: - test: - - CMD-SHELL - - | - code="$$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1/index.php || echo 000)"; [ "$$code" -ge 200 ] && [ "$$code" -lt 400 ] - interval: 10s - timeout: 5s - retries: 12 - start_period: 180s + {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_depends_on', application_id) | indent(4) }} {{ lookup('container_networks') | indent(4) }} diff --git a/roles/web-app-matrix/README.md b/roles/web-app-matrix/README.md index 9f1cea5c6a..a350c60ad4 100644 --- a/roles/web-app-matrix/README.md +++ b/roles/web-app-matrix/README.md @@ -20,6 +20,7 @@ The diagram places Matrix in the Infinito.Nexus cosmos: the components it deploy ```mermaid flowchart LR subgraph deps [Dependencies] + dep_svc_ai_litellm["svc-ai-litellm ๐Ÿณ๐Ÿ"] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local ๐Ÿ’ป"] dep_svc_db_openldap["svc-db-openldap ๐Ÿณ๐Ÿ"] dep_svc_db_postgres["svc-db-postgres ๐Ÿณ๐Ÿ"] @@ -35,6 +36,7 @@ flowchart LR dep_web_svc_logout["web-svc-logout ๐Ÿณ๐Ÿ"] end subgraph role [web-app-matrix ๐Ÿณ๐Ÿ] + svc_litellm["litellm"] svc_sso["sso"] svc_ldap["ldap"] svc_logout["logout"] @@ -56,6 +58,7 @@ flowchart LR subgraph dependents [Dependents] dpt_web_app_nextcloud["web-app-nextcloud ๐Ÿณ๐Ÿ"] end + dep_svc_ai_litellm -. "0..1" .-> svc_litellm dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup dep_svc_db_openldap -. "0..1" .-> svc_ldap dep_svc_db_postgres -. "0..1" .-> svc_postgres @@ -69,7 +72,7 @@ flowchart LR dep_web_svc_coturn -. "0..1" .-> svc_coturn dep_web_svc_css -. "0..1" .-> svc_css dep_web_svc_logout -. "0..1" .-> svc_logout - svc_sso -. "0..1" .-> dpt_web_app_nextcloud + svc_litellm -. "0..1" .-> dpt_web_app_nextcloud ``` Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (๐Ÿ’ป host, ๐Ÿณ compose, ๐Ÿ swarm); โŒ marks a service that is explicitly turned off, and โš™๏ธ an Ansible role dependency declared in `meta/main.yml`. @@ -102,19 +105,20 @@ Run the published image to provision the inventory and deploy Matrix to a manage ```bash APP=web-app-matrix HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' @@ -163,10 +167,8 @@ flowchart TD end kc["keycloak_keycloak
+ one-shot realm import job"] - role["web-app-matrix tasks"] -- "renders compose.yml,
notify: swarm deploy" --> flush["meta: flush_handlers
(before registration wait)"] - flush -- "docker stack deploy" --> stack - stack -- "writes mautrix/*/registration.yaml" --> role - role -- "waits for registration files" --> stack + role["web-app-matrix tasks"] -- "renders config/mautrix/*/{config,registration}.yaml
and compose.yml, notify: swarm deploy" --> flush["meta: flush_handlers
(before the Synapse wait)"] + flush -- "docker stack deploy
(both files as secrets)" --> stack syn -- "OIDC discovery via
--add-host issuer โ†’ subnet .1" --> prx prx -- "vhost auth.*" --> kc @@ -186,8 +188,9 @@ The ansible flavor maps each true flag to the matching `matrix__enabled` The mautrix network bridges are declared in [`meta/addons/`](./meta/addons/) as `mechanism: bridge` addons (requirement 026, Decision 13). Each is `required: false` and **disabled by default**; its -per-network DB password is referenced from -[`meta/secrets.yml`](./meta/secrets.yml) `credentials:`, never inlined. +per-network DB password and its appservice `as_token`/`hs_token` pair are referenced from +[`meta/secrets.yml`](./meta/secrets.yml) `credentials:`, never inlined. The role renders each +bridge's `config.yaml` and the matching Synapse `registration.yaml` from the same tokens. | Addon | Mechanism | Default state | Bridges | |-------|-----------|---------------|---------| diff --git a/roles/web-app-matrix/files/flavor/ansible/reconfigure.sh b/roles/web-app-matrix/files/flavor/ansible/reconfigure.sh new file mode 100755 index 0000000000..b5729f9426 --- /dev/null +++ b/roles/web-app-matrix/files/flavor/ansible/reconfigure.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Param: MATRIX_MDAD_VOLUME - docker volume holding the bootstrap marker +# Param: MATRIX_MDAD_CONTAINER - the DiD runner container +set -euo pipefail + +: "${MATRIX_MDAD_VOLUME:?}" +: "${MATRIX_MDAD_CONTAINER:?}" + +if _mp="$(container volume inspect -f '{{ .Mountpoint }}' "$MATRIX_MDAD_VOLUME" 2>/dev/null)"; then + rm -f "${_mp}/bootstrap.done" +fi + +if container ps -q -f "name=^${MATRIX_MDAD_CONTAINER}$" | grep -q .; then + container restart "$MATRIX_MDAD_CONTAINER" +fi diff --git a/roles/web-app-matrix/files/playwright/_shared.js b/roles/web-app-matrix/files/playwright/_shared.js index 616729c793..19c41d2978 100644 --- a/roles/web-app-matrix/files/playwright/_shared.js +++ b/roles/web-app-matrix/files/playwright/_shared.js @@ -22,6 +22,8 @@ const biberUsername = decodeDotenvQuotedValue(process.env.BIBER_USERNAME); const biberPassword = decodeDotenvQuotedValue(process.env.BIBER_PASSWORD); const canonicalDomain = decodeDotenvQuotedValue(process.env.CANONICAL_DOMAIN); const oidcServiceEnabled = isServiceEnabled("sso"); +// Synapse refills rc_login on its own clock, so the onion multiplier must not stretch this wait. +const RC_LOGIN_COOLDOWN_MS = 45_000; function attachDiagnostics(page) { const consoleErrors = []; @@ -240,7 +242,7 @@ async function signInViaElementOidc(page, username, password, personaLabel) { // requires a few seconds per slot. Wait 45s to leave margin โ€” clicking // "Try again" sooner just re-triggers M_LIMIT_EXCEEDED and burns the // next burst slot, extending the outage. - await page.waitForTimeout(resolveTimeout(45_000)); + await page.waitForTimeout(RC_LOGIN_COOLDOWN_MS); const tryAgain = rateLimitDialog.getByRole("button", { name: /^try again$/i }).first(); await tryAgain.click({ timeout: resolveTimeout(5_000) }).catch(() => {}); return true; diff --git a/roles/web-app-matrix/files/playwright/playwright.spec.js b/roles/web-app-matrix/files/playwright/playwright.spec.js index 8b6b4a934b..9f797873fa 100644 --- a/roles/web-app-matrix/files/playwright/playwright.spec.js +++ b/roles/web-app-matrix/files/playwright/playwright.spec.js @@ -27,4 +27,5 @@ require("./test-dm-admin-biber").register(shared); require("./test-guest-persona").register(shared); require("./test-element-call").register(shared); require("./test-bridge-roster").register(shared); +require("./test-litellm-chatgpt").register(shared); require("./test-seaweedfs"); diff --git a/roles/web-app-matrix/files/playwright/test-bridge-roster.js b/roles/web-app-matrix/files/playwright/test-bridge-roster.js index 42e272c9a4..e64dbf67d7 100644 --- a/roles/web-app-matrix/files/playwright/test-bridge-roster.js +++ b/roles/web-app-matrix/files/playwright/test-bridge-roster.js @@ -1,5 +1,6 @@ const { test, expect } = require("./onion-test"); const { resolveTimeout } = require("./timeouts"); +const { decodeDotenvQuotedValue } = require("./personas"); const BRIDGE_TO_BOT_LOCALPART = { appservice_irc: "ircbot", @@ -38,7 +39,7 @@ exports.register = function (shared) { shared.skipUnlessServiceEnabled("bridges"); const { matrixBaseUrl, matrixServerName } = shared.env; - const rawPlugins = process.env.MATRIX_PLUGINS_JSON || "{}"; + const rawPlugins = decodeDotenvQuotedValue(process.env.MATRIX_PLUGINS_JSON || "") || "{}"; let plugins; try { plugins = JSON.parse(rawPlugins); diff --git a/roles/web-app-matrix/files/playwright/test-dm-admin-biber.js b/roles/web-app-matrix/files/playwright/test-dm-admin-biber.js index 9bf055aea4..d60069523d 100644 --- a/roles/web-app-matrix/files/playwright/test-dm-admin-biber.js +++ b/roles/web-app-matrix/files/playwright/test-dm-admin-biber.js @@ -1,6 +1,10 @@ const { test, expect } = require("./onion-test"); const { resolveTimeout } = require("./timeouts"); +// Synapse refills rc_login on its own clock, so the onion multiplier must not stretch these waits. +const RC_LOGIN_DRAIN_MS = 120_000; +const RC_LOGIN_REFILL_MS = 30_000; + exports.register = function (shared) { test.describe("matrix DM", () => { test("administrator and biber can exchange a direct message in element", async ({ browser }) => { @@ -30,11 +34,11 @@ exports.register = function (shared) { // test's state machine isn't forced to spend most of its deadline // cycling through consentโ†”M_LIMIT_EXCEEDED retries. Running the DM // test in isolation doesn't need this, but the extra wait is cheap. - await adminPage.waitForTimeout(resolveTimeout(120_000)); + await adminPage.waitForTimeout(RC_LOGIN_DRAIN_MS); await shared.signInViaElement(adminPage, adminUsername, adminPassword, "administrator"); // Same reasoning between admin and biber: two back-to-back SSO // logins easily exhaust rc_login. 30s lets the burst refill. - await adminPage.waitForTimeout(resolveTimeout(30_000)); + await adminPage.waitForTimeout(RC_LOGIN_REFILL_MS); await shared.signInViaElement(biberPage, biberUsername, biberPassword, "biber"); const marker = `hello-from-admin-${Date.now()}`; @@ -93,28 +97,31 @@ exports.register = function (shared) { await adminPage.keyboard.type(bootstrap); await adminPage.keyboard.press("Enter"); - // Biber: wait for admin's invite to propagate, then accept. The flow - // mirrors Element's invite UX: (1) click the sidebar tile for admin's - // invite (the tile renders with admin's display name but no standalone - // Accept button), then (2) click the primary accept action in the invite - // view (modern Element labels this "Start chatting" for DMs; older - // builds / non-DM invites use "Accept" / "Join"). MUST NOT match - // "Decline" / "Decline and block". await expect .poll(async () => { return await biberPage.evaluate(() => { - // Step 1: open the invite. + const sections = document.querySelectorAll( + 'button[aria-expanded="false"][aria-label^="Toggle "]', + ); + for (const section of sections) { + section.click(); + } + + // Not scoped to a row wrapper: the list is virtualised and 1.12.27 + // renders no role=row, aria-level or aria-expanded at all. const roomTiles = document.querySelectorAll( - "[role='treeitem'], [role='option'], .mx_RoomTile, [data-testid^='room-tile']", + 'button[aria-label^="Open room"]', ); for (const tile of roomTiles) { - const text = (tile.textContent || "").trim(); - if (/administrator/i.test(text)) { + const name = `${tile.getAttribute("aria-label") || ""} ${tile.textContent || ""}`; + if (/administrator/i.test(name)) { tile.click(); break; } } - // Step 2: click accept. + + // Anchored: "Decline and block" contains an accept-looking word and + // clicking it destroys the invite. const acceptCandidates = document.querySelectorAll( "button, a, [role='button']", ); @@ -124,9 +131,6 @@ exports.register = function (shared) { b.click(); } } - // Success: invite accepted when the room timeline renders a - // message composer for biber (only appears once membership is - // `join`). Use the same composer signature as admin's side. return !!document.querySelector( "div[role='textbox'][contenteditable='true'], textarea[aria-label*='message' i]", ); diff --git a/roles/web-app-matrix/files/playwright/test-litellm-chatgpt.js b/roles/web-app-matrix/files/playwright/test-litellm-chatgpt.js new file mode 100644 index 0000000000..07359c03be --- /dev/null +++ b/roles/web-app-matrix/files/playwright/test-litellm-chatgpt.js @@ -0,0 +1,271 @@ +// LiteLLM gateway scenario for the Matrix ChatGPT bridge (compose flavor). +// +// The bridge container reads CHATGPT_REVERSE_PROXY / CHATGPT_API_MODEL / +// OPENAI_API_KEY from MATRIX_CHATGPT_BRIDGE_* (roles/web-app-matrix/vars/main.yml), +// which resolve to the in-cluster svc-ai-litellm endpoint whenever +// services.litellm.enabled is true. Nothing on the Matrix HTTP surface exposes +// that container env, so the endpoint is asserted from the same Ansible values +// the compose template renders, and the round trip against @chatgptbot proves +// the bridge actually reaches an inference backend through it. +// +// Required env (rendered by templates/playwright.env.j2): +// ADMIN_USERNAME, ADMIN_PASSWORD, MATRIX_BASE_URL, MATRIX_SERVER_NAME, +// MATRIX_FLAVOR, MATRIX_PLUGINS_JSON, LITELLM_SERVICE_ENABLED, +// MATRIX_CHATGPT_BRIDGE_ENDPOINT, MATRIX_CHATGPT_BRIDGE_MODEL. + +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); +const { decodeDotenvQuotedValue } = require("./personas"); + +const BOT_LOCALPART = "chatgptbot"; +const PROMPT = "!chatgpt Reply with the single digit that is the result of 2+2."; +const BOT_FAILURE_PATTERN = /^\s*(something went wrong|there was an error|an error occurred|error:|failed to)/i; + +const bridgeEndpoint = decodeDotenvQuotedValue(process.env.MATRIX_CHATGPT_BRIDGE_ENDPOINT || ""); +const bridgeModel = decodeDotenvQuotedValue(process.env.MATRIX_CHATGPT_BRIDGE_MODEL || ""); + +function isTruthy(value) { + if (value === true) return true; + if (typeof value === "string") return value.toLowerCase() === "true"; + return false; +} + +function authHeaders(accessToken) { + return { Authorization: `Bearer ${accessToken}` }; +} + +function sleep(ms) { + return new Promise((resolve) => { + setTimeout(resolve, ms); + }); +} + +/** + * Args: + * request: Playwright APIRequestContext + * matrixBaseUrl: Synapse client-server base URL, no trailing slash + * username: localpart of the account registered by the deploy + * password: that account's password + * Returns: the access token string, or null when every attempt was rejected. + * Sets `diagnostic.last` to the final HTTP status/body for the caller's message. + */ +async function loginWithPassword(request, matrixBaseUrl, username, password, diagnostic) { + const payload = { + type: "m.login.password", + identifier: { type: "m.id.user", user: username }, + password, + initial_device_display_name: "infinito-litellm-gateway-probe", + }; + for (let attempt = 0; attempt < 8; attempt += 1) { + const response = await request.post(`${matrixBaseUrl}/_matrix/client/v3/login`, { + data: payload, + failOnStatusCode: false, + timeout: resolveTimeout(30_000), + }); + const raw = await response.text().catch(() => ""); + if (response.ok()) { + try { + const token = JSON.parse(raw).access_token; + if (token) return token; + } catch { + diagnostic.last = `HTTP 200 with unparseable body: ${raw.slice(0, 400)}`; + return null; + } + } + diagnostic.last = `HTTP ${response.status()}: ${raw.slice(0, 400)}`; + if (response.status() !== 429) return null; + let retryAfterMs; + try { + retryAfterMs = Number(JSON.parse(raw).retry_after_ms) || 5_000; + } catch { + retryAfterMs = 5_000; + } + await sleep(Math.min(Math.max(retryAfterMs, 1_000), 30_000)); + } + return null; +} + +async function joinedMembers(request, matrixBaseUrl, roomId, accessToken) { + const response = await request.get( + `${matrixBaseUrl}/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/joined_members`, + { headers: authHeaders(accessToken), failOnStatusCode: false, timeout: resolveTimeout(30_000) }, + ); + if (!response.ok()) return []; + const body = await response.json().catch(() => ({})); + return Object.keys(body.joined || {}); +} + +async function botReplies(request, matrixBaseUrl, roomId, accessToken, botUserId) { + const response = await request.get( + `${matrixBaseUrl}/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/messages`, + { + headers: authHeaders(accessToken), + params: { dir: "b", limit: "100" }, + failOnStatusCode: false, + timeout: resolveTimeout(30_000), + }, + ); + if (!response.ok()) return []; + const body = await response.json().catch(() => ({})); + return (body.chunk || []) + .filter((event) => event && event.type === "m.room.message" && event.sender === botUserId) + .map((event) => String((event.content || {}).body || "").trim()); +} + +exports.register = function (shared) { + test("litellm: the matrix chatgpt bridge answers a prompt through the in-cluster gateway", async ({ request }) => { + shared.skipUnlessServiceEnabled("litellm"); + test.skip( + !(process.env.MATRIX_FLAVOR || "").toLowerCase().includes("compose"), + "The matrix-chatgpt-bot bridge is only rendered by the compose flavor; the ansible flavor deploys matrix-docker-ansible-deploy, which owns its own bridge wiring.", + ); + + const { matrixBaseUrl, matrixServerName, adminUsername, adminPassword } = shared.env; + const botUserId = `@${BOT_LOCALPART}:${matrixServerName}`; + + const plugins = JSON.parse(decodeDotenvQuotedValue(process.env.MATRIX_PLUGINS_JSON || "") || "{}"); + expect( + isTruthy(plugins.chatgpt), + `services.matrix.plugins.chatgpt must be on wherever svc-ai-litellm is deployed, otherwise the bridge container is never rendered and no Matrix surface reaches the gateway (MATRIX_PLUGINS_JSON: ${JSON.stringify(plugins)})`, + ).toBe(true); + + expect( + bridgeEndpoint, + "MATRIX_CHATGPT_BRIDGE_ENDPOINT must be set; it is the value the compose template writes into the bridge's CHATGPT_REVERSE_PROXY", + ).toBeTruthy(); + expect( + bridgeEndpoint, + "the bridge endpoint must be an absolute http(s) URL, otherwise the bridge cannot address any inference backend at all", + ).toMatch(/^https?:\/\/.+/i); + + const endpointUrl = new URL(bridgeEndpoint); + expect( + endpointUrl.protocol, + "the bridge endpoint must be plain http on the container network; https means the prompt leaves the cluster through the public ingress instead of reaching the gateway directly", + ).toBe("http:"); + expect( + endpointUrl.hostname.includes("."), + `the bridge endpoint host must be an undotted container name (got "${endpointUrl.hostname}"); a dotted host is completed by the container dns-search suffix and resolves through the public ingress, which is the leak the requirement forbids`, + ).toBe(false); + expect( + endpointUrl.pathname, + "the bridge endpoint must be the gateway's OpenAI-compatible chat-completions path, so CHATGPT_REVERSE_PROXY is a drop-in replacement for the vendor URL", + ).toBe("/v1/chat/completions"); + expect( + bridgeEndpoint.toLowerCase(), + `the bridge endpoint must not contain the public server name "${matrixServerName}"; a public hostname routes the prompt back out through the ingress rather than over the container network`, + ).not.toContain(String(matrixServerName).toLowerCase()); + expect( + bridgeModel, + "MATRIX_CHATGPT_BRIDGE_MODEL must be set to the model the gateway serves; an empty CHATGPT_API_MODEL makes the bridge fall back to a vendor model name the gateway does not route", + ).toBeTruthy(); + + const loginDiagnostic = { last: "no attempt was made" }; + const accessToken = await loginWithPassword( + request, + matrixBaseUrl, + adminUsername, + adminPassword, + loginDiagnostic, + ); + expect( + accessToken, + `the administrator must be able to obtain a client-server access token by password (the deploy registers the account with register_new_matrix_user); last response: ${loginDiagnostic.last}`, + ).toBeTruthy(); + + let roomId = null; + try { + // Deliberately unencrypted: Element creates DMs with E2EE on, and an + // encrypted timeline is opaque to this API-only client, so the bot's + // answer would be unreadable. matrix-chatgpt-bot answers in plaintext + // rooms too, which is what makes the completion observable here. + const createResponse = await request.post(`${matrixBaseUrl}/_matrix/client/v3/createRoom`, { + headers: authHeaders(accessToken), + data: { + preset: "private_chat", + is_direct: true, + invite: [botUserId], + name: `litellm-gateway-probe-${Date.now()}`, + }, + failOnStatusCode: false, + timeout: resolveTimeout(30_000), + }); + const createBody = await createResponse.text().catch(() => ""); + expect( + createResponse.status(), + `creating the probe room and inviting ${botUserId} must succeed; a 403/404 here means the deploy never registered the bridge's Matrix account: ${createBody.slice(0, 400)}`, + ).toBe(200); + roomId = JSON.parse(createBody).room_id; + + await expect + .poll(async () => (await joinedMembers(request, matrixBaseUrl, roomId, accessToken)).includes(botUserId), { + timeout: resolveTimeout(180_000), + intervals: [5_000], + message: `${botUserId} must accept the invite (MATRIX_AUTOJOIN=true); if it never joins, the bridge container is not running or failed to authenticate against Synapse, so no prompt can reach the gateway`, + }) + .toBe(true); + + const sendResponse = await request.put( + `${matrixBaseUrl}/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/send/m.room.message/${encodeURIComponent(`litellm-probe-${Date.now()}`)}`, + { + headers: authHeaders(accessToken), + data: { msgtype: "m.text", body: PROMPT }, + failOnStatusCode: false, + timeout: resolveTimeout(30_000), + }, + ); + expect( + sendResponse.status(), + `sending the probe prompt into the room must succeed: ${(await sendResponse.text().catch(() => "")).slice(0, 400)}`, + ).toBe(200); + + let replies = []; + await expect + .poll( + async () => { + replies = await botReplies(request, matrixBaseUrl, roomId, accessToken, botUserId); + return replies.length > 0; + }, + { + timeout: resolveTimeout(300_000), + intervals: [5_000], + message: `${botUserId} must post an answer to the prompt; the bridge only posts once its chat-completions call returned, so silence means the request to ${bridgeEndpoint} never completed`, + }, + ) + .toBe(true); + + const reply = replies[0]; + expect( + reply.length, + `the bridge's answer must be non-empty, proving the gateway returned a real completion rather than an empty choice (replies seen: ${JSON.stringify(replies)})`, + ).toBeGreaterThan(0); + expect( + reply, + `the bridge must answer with a completion, not with its own failure notice; this text is what matrix-chatgpt-bot posts when the call to ${bridgeEndpoint} raised: ${JSON.stringify(reply)}`, + ).not.toMatch(BOT_FAILURE_PATTERN); + expect( + reply, + `the bridge must answer the prompt rather than echo it back (got: ${JSON.stringify(reply)})`, + ).not.toBe(PROMPT); + } finally { + if (roomId) { + await request + .post(`${matrixBaseUrl}/_matrix/client/v3/rooms/${encodeURIComponent(roomId)}/leave`, { + headers: authHeaders(accessToken), + data: {}, + failOnStatusCode: false, + timeout: resolveTimeout(30_000), + }) + .catch(() => {}); + } + await request + .post(`${matrixBaseUrl}/_matrix/client/v3/logout`, { + headers: authHeaders(accessToken), + data: {}, + failOnStatusCode: false, + timeout: resolveTimeout(30_000), + }) + .catch(() => {}); + } + }); +}; diff --git a/roles/web-app-matrix/files/playwright/test-seaweedfs.js b/roles/web-app-matrix/files/playwright/test-seaweedfs.js index 6e19f324db..563cc8f63f 100644 --- a/roles/web-app-matrix/files/playwright/test-seaweedfs.js +++ b/roles/web-app-matrix/files/playwright/test-seaweedfs.js @@ -62,6 +62,13 @@ test("seaweedfs: an uploaded Matrix avatar is stored in the SeaweedFS bucket", a ).toBeAttached({ timeout: resolveTimeout(60_000) }); const marker = `infinito-storage-check-${Date.now()}.png`; + const upload = appPage.waitForResponse( + (response) => + /\/_matrix\/media\/(v3|r0)\/upload/.test(response.url()) && + response.request().method() === "POST", + { timeout: resolveTimeout(120_000) }, + ); + await fileInput.setInputFiles({ name: marker, mimeType: "image/png", @@ -71,9 +78,20 @@ test("seaweedfs: an uploaded Matrix avatar is stored in the SeaweedFS bucket", a const saveButton = appPage .getByRole("button", { name: /^(save|apply|upload|confirm)$/i }) .first(); - if (await saveButton.waitFor({ state: "visible", timeout: resolveTimeout(2_000) }).then(() => true).catch(() => false)) { + if (await saveButton.waitFor({ state: "visible", timeout: resolveTimeout(30_000) }).then(() => true).catch(() => false)) { await saveButton.click().catch(() => {}); } + + const response = await upload.catch(() => null); + expect( + response, + "Element never POSTed the avatar to /_matrix/media/*/upload, so nothing could reach the bucket; " + + "the settings flow did not complete rather than the object store failing", + ).not.toBeNull(); + expect( + response.status(), + `Synapse rejected the avatar upload with HTTP ${response.status()}`, + ).toBeLessThan(300); }, }); }); diff --git a/roles/web-app-matrix/files/sql/realign_user_password.sql b/roles/web-app-matrix/files/sql/realign_user_password.sql new file mode 100644 index 0000000000..e25b24325b --- /dev/null +++ b/roles/web-app-matrix/files/sql/realign_user_password.sql @@ -0,0 +1 @@ +UPDATE users SET password_hash = :'hash' WHERE name = :'name'; diff --git a/roles/web-app-matrix/lookup_plugins/matrix_bridge_mounts.py b/roles/web-app-matrix/lookup_plugins/matrix_bridge_mounts.py index 2111efd119..a3c2f53a1b 100644 --- a/roles/web-app-matrix/lookup_plugins/matrix_bridge_mounts.py +++ b/roles/web-app-matrix/lookup_plugins/matrix_bridge_mounts.py @@ -1,25 +1,42 @@ -"""Lookup ``matrix_bridge_mounts``: the synapse registration-file mounts, -one ``/mautrix/:/mautrix-:ro`` -short-form entry per enabled bridge. +"""Lookup ``matrix_bridge_mounts``: the secrets that carry each enabled +bridge's config and registration. -Usage (compose template): +Usage (compose templates): - extra_volumes=lookup('matrix_bridge_mounts') + lookup('compose_volumes', extra_secrets=lookup('matrix_bridge_mounts', 'stack')) + lookup('container_volumes', 'synapse', extra_secrets=lookup('matrix_bridge_mounts', 'synapse')) + lookup('container_volumes', service_name, extra_secrets=lookup('matrix_bridge_mounts', 'bridge', item.bridge_name)) + +Terms: + stack -- top-level secret definitions, named by compose_volumes + synapse -- one registration mount per bridge + bridge -- the config mount of that bridge Reads from the templating context: - application_id -- the consuming role MATRIX_BRIDGES -- enabled bridge configs (set_fact) + MATRIX_BRIDGE_SOURCE_DIR -- host directory holding /*.yaml + MATRIX_BRIDGE_CONFIG_TARGET -- config path inside each bridge MATRIX_REGISTRATION_FILE_FOLDER -- registration folder inside synapse """ from __future__ import annotations +from pathlib import Path from typing import Any from ansible.errors import AnsibleError -from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase +SECRET_MODE = 0o444 + + +def _config_key(bridge: str) -> str: + return f"mautrix_{bridge}_config" + + +def _registration_key(bridge: str) -> str: + return f"mautrix_{bridge}_registration" + class LookupModule(LookupBase): def run( @@ -27,9 +44,13 @@ class LookupModule(LookupBase): terms: list[Any] | None, variables: dict[str, Any] | None = None, **kwargs: Any, - ) -> list[list[str]]: - if terms: - raise AnsibleError("matrix_bridge_mounts lookup expects no terms.") + ) -> list[Any]: + view = str(terms[0]) if terms else "" + if view not in ("stack", "synapse", "bridge"): + raise AnsibleError( + "matrix_bridge_mounts lookup expects 'stack', 'synapse' or " + f"'bridge ', got {terms!r}" + ) vars_ = variables or getattr(self._templar, "available_variables", {}) or {} templar = getattr(self, "_templar", None) @@ -45,23 +66,49 @@ class LookupModule(LookupBase): value = templar.template(value) return value - application_id = str(ctx("application_id")).strip() bridges = ctx("MATRIX_BRIDGES") - reg_folder = str(ctx("MATRIX_REGISTRATION_FILE_FOLDER")) if not isinstance(bridges, list): raise AnsibleError( "matrix_bridge_mounts lookup: MATRIX_BRIDGES must be a list, " f"got {type(bridges).__name__}" ) + names = [str(bridge["bridge_name"]) for bridge in bridges] - instance_dir = str( - lookup_loader.get("container", loader=self._loader, templar=templar).run( - [application_id, "directories.instance"], variables=vars_ - )[0] - ) + if view == "bridge": + if len(terms) != 2 or str(terms[1]) not in names: + raise AnsibleError( + f"matrix_bridge_mounts lookup: 'bridge' needs one enabled bridge name, got {terms[1:]!r}" + ) + return [ + [ + { + "source": _config_key(str(terms[1])), + "target": str(ctx("MATRIX_BRIDGE_CONFIG_TARGET")), + "mode": SECRET_MODE, + } + ] + ] - mounts = [] - for bridge in bridges: - name = str(bridge["bridge_name"]) - mounts.append(f"{instance_dir}mautrix/{name}:{reg_folder}mautrix-{name}:ro") - return [mounts] + if view == "synapse": + folder = str(ctx("MATRIX_REGISTRATION_FILE_FOLDER")) + return [ + [ + { + "source": _registration_key(name), + "target": f"{folder}mautrix-{name}/registration.yaml", + "mode": SECRET_MODE, + } + for name in names + ] + ] + + source_dir = Path(str(ctx("MATRIX_BRIDGE_SOURCE_DIR"))) + secrets: dict[str, dict[str, str]] = {} + for name in names: + secrets[_config_key(name)] = { + "file": str(source_dir / name / "config.yaml") + } + secrets[_registration_key(name)] = { + "file": str(source_dir / name / "registration.yaml") + } + return [secrets] diff --git a/roles/web-app-matrix/meta/addons/mautrix-meta.yml b/roles/web-app-matrix/meta/addons/mautrix-meta.yml index 9b0d918d54..e32d910035 100644 --- a/roles/web-app-matrix/meta/addons/mautrix-meta.yml +++ b/roles/web-app-matrix/meta/addons/mautrix-meta.yml @@ -9,6 +9,7 @@ update: upstream_id: mautrix-meta config: bridge_name: "meta" + appservice_port: 29319 database_username: "mautrix_meta_bridge" database_name: "mautrix_meta_bridge" database_password: "{{ lookup('config', 'web-app-matrix', 'secrets.credentials.mautrix_meta_bridge_database_password', '') }}" diff --git a/roles/web-app-matrix/meta/addons/mautrix-signal.yml b/roles/web-app-matrix/meta/addons/mautrix-signal.yml index 2673b7c54e..ece3fbd7ef 100644 --- a/roles/web-app-matrix/meta/addons/mautrix-signal.yml +++ b/roles/web-app-matrix/meta/addons/mautrix-signal.yml @@ -9,6 +9,7 @@ update: upstream_id: mautrix-signal config: bridge_name: "signal" + appservice_port: 29328 database_username: "mautrix_signal_bridge" database_name: "mautrix_signal_bridge" database_password: "{{ lookup('config', 'web-app-matrix', 'secrets.credentials.mautrix_signal_bridge_database_password', '') }}" diff --git a/roles/web-app-matrix/meta/addons/mautrix-slack.yml b/roles/web-app-matrix/meta/addons/mautrix-slack.yml index f597e98bf0..1908b3d217 100644 --- a/roles/web-app-matrix/meta/addons/mautrix-slack.yml +++ b/roles/web-app-matrix/meta/addons/mautrix-slack.yml @@ -9,6 +9,7 @@ update: upstream_id: mautrix-slack config: bridge_name: "slack" + appservice_port: 29335 database_username: "mautrix_slack_bridge" database_name: "mautrix_slack_bridge" database_password: "{{ lookup('config', 'web-app-matrix', 'secrets.credentials.mautrix_slack_bridge_database_password', '') }}" diff --git a/roles/web-app-matrix/meta/addons/mautrix-telegram.yml b/roles/web-app-matrix/meta/addons/mautrix-telegram.yml index f7da0ac88e..c5f4a0c610 100644 --- a/roles/web-app-matrix/meta/addons/mautrix-telegram.yml +++ b/roles/web-app-matrix/meta/addons/mautrix-telegram.yml @@ -9,6 +9,7 @@ update: upstream_id: mautrix-telegram config: bridge_name: "telegram" + appservice_port: 29317 database_username: "mautrix_telegram_bridge" database_name: "mautrix_telegram_bridge" database_password: "{{ lookup('config', 'web-app-matrix', 'secrets.credentials.mautrix_telegram_bridge_database_password', '') }}" diff --git a/roles/web-app-matrix/meta/addons/mautrix-whatsapp.yml b/roles/web-app-matrix/meta/addons/mautrix-whatsapp.yml index 094e3fc675..df8da1c89c 100644 --- a/roles/web-app-matrix/meta/addons/mautrix-whatsapp.yml +++ b/roles/web-app-matrix/meta/addons/mautrix-whatsapp.yml @@ -9,6 +9,7 @@ update: upstream_id: mautrix-whatsapp config: bridge_name: "whatsapp" + appservice_port: 29318 database_username: "mautrix_whatsapp_bridge" database_name: "mautrix_whatsapp_bridge" database_password: "{{ lookup('config', 'web-app-matrix', 'secrets.credentials.mautrix_whatsapp_bridge_database_password', '') }}" diff --git a/roles/web-app-matrix/meta/secrets.yml b/roles/web-app-matrix/meta/secrets.yml index 8a3d7eb59f..7025aa312d 100644 --- a/roles/web-app-matrix/meta/secrets.yml +++ b/roles/web-app-matrix/meta/secrets.yml @@ -1,5 +1,10 @@ --- credentials: + litellm_api_key: + description: Per-consumer virtual key for the shared svc-ai-litellm gateway + algorithm: sk_prefixed + validation: + min_length: 50 administrator_password: description: Initial administrator password for the Matrix homeserver algorithm: sha256 @@ -25,9 +30,10 @@ credentials: algorithm: sha256 validation: ^[a-f0-9]{64}$ chatgpt_bridge_openai_api_key: - description: API key for accessing OpenAI via the Matrix ChatGPT bridge - algorithm: plain - validation: ^sk-[a-zA-Z0-9]{40,}$ + description: Key the Matrix ChatGPT bridge presents to its inference endpoint, the shared gateway when svc-ai-litellm is deployed + algorithm: sk_prefixed + validation: + min_length: 50 chatgpt_bridge_access_token: description: Access token used by the ChatGPT bridge for authentication algorithm: plain @@ -40,6 +46,46 @@ credentials: description: Database password for the mautrix-meta bridge (Facebook Messenger + Instagram) algorithm: bcrypt validation: ^\$2[aby]\$.{56}$ + mautrix_meta_bridge_as_token: + description: Appservice token the mautrix-meta bridge presents to Synapse + algorithm: alphanumeric + validation: ^[A-Za-z0-9]{64}$ + mautrix_meta_bridge_hs_token: + description: Token Synapse presents to the mautrix-meta bridge + algorithm: alphanumeric + validation: ^[A-Za-z0-9]{64}$ + mautrix_signal_bridge_as_token: + description: Appservice token the mautrix-signal bridge presents to Synapse + algorithm: alphanumeric + validation: ^[A-Za-z0-9]{64}$ + mautrix_signal_bridge_hs_token: + description: Token Synapse presents to the mautrix-signal bridge + algorithm: alphanumeric + validation: ^[A-Za-z0-9]{64}$ + mautrix_slack_bridge_as_token: + description: Appservice token the mautrix-slack bridge presents to Synapse + algorithm: alphanumeric + validation: ^[A-Za-z0-9]{64}$ + mautrix_slack_bridge_hs_token: + description: Token Synapse presents to the mautrix-slack bridge + algorithm: alphanumeric + validation: ^[A-Za-z0-9]{64}$ + mautrix_telegram_bridge_as_token: + description: Appservice token the mautrix-telegram bridge presents to Synapse + algorithm: alphanumeric + validation: ^[A-Za-z0-9]{64}$ + mautrix_telegram_bridge_hs_token: + description: Token Synapse presents to the mautrix-telegram bridge + algorithm: alphanumeric + validation: ^[A-Za-z0-9]{64}$ + mautrix_whatsapp_bridge_as_token: + description: Appservice token the mautrix-whatsapp bridge presents to Synapse + algorithm: alphanumeric + validation: ^[A-Za-z0-9]{64}$ + mautrix_whatsapp_bridge_hs_token: + description: Token Synapse presents to the mautrix-whatsapp bridge + algorithm: alphanumeric + validation: ^[A-Za-z0-9]{64}$ mautrix_signal_bridge_database_password: description: Database password for the mautrix-signal bridge algorithm: bcrypt diff --git a/roles/web-app-matrix/meta/services.yml b/roles/web-app-matrix/meta/services.yml index dd04f12398..a78f526cad 100644 --- a/roles/web-app-matrix/meta/services.yml +++ b/roles/web-app-matrix/meta/services.yml @@ -1,4 +1,9 @@ --- +# nocheck: dynamic-flag - the gateway is a single shared instance, never deployed per consumer +litellm: + bond: 0.5 + enabled: "{{ LITELLM_USABLE }}" + shared: true # nocheck: dockerfile-custom sso: bond: 1 @@ -50,6 +55,9 @@ synapse: http: 8021 public: federation: 8448 + onion: + # nocheck: onion-flag federation is dialled by clearnet homeservers resolving this server_name; serving it on the onion needs an onion server_name, which is a different deployment + federation: false min_storage: 311MB cpus: "1.5" mem_reservation: "1g" @@ -58,7 +66,7 @@ synapse: element: healthcheck: flavor: wget - version: v1.12.27 + version: v1.12.28 image: vectorim/element-web name: matrix-element ports: @@ -105,7 +113,6 @@ matrix: healthcheck: flavor: http_status path: _matrix/client/versions - start_period: 10m retries: 10 ports: internal: @@ -124,7 +131,7 @@ matrix: flavor: ansible upstream: repo: https://github.com/spantaleev/matrix-docker-ansible-deploy - ref: master + ref: 40179e6d4a36513eb77c4ef2eff067716ebb1821 migration_validated_version: v2026.05.18.0 runner: image: infinito/web-app-matrix-mdad-runner:1 @@ -136,7 +143,7 @@ matrix: server_name: "{{ DOMAIN_PRIMARY }}" plugins: appservice_irc: false - chatgpt: false + chatgpt: "{{ 'svc-ai-litellm' in group_names }}" discord: false gitter: false heisenbridge: true diff --git a/roles/web-app-matrix/meta/variants.yml b/roles/web-app-matrix/meta/variants.yml index 038f802f78..59965eb1f1 100644 --- a/roles/web-app-matrix/meta/variants.yml +++ b/roles/web-app-matrix/meta/variants.yml @@ -27,6 +27,8 @@ shared: true postgres: shared: true + litellm: + enabled: false sso: enabled: true shared: true @@ -68,6 +70,8 @@ shared: false # nocheck: variants-static-override backup shared stays literally true postgres: shared: false # nocheck: variants-static-override backup shared stays literally true + litellm: + enabled: false sso: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -112,6 +116,8 @@ shared: true postgres: shared: true + litellm: + enabled: true sso: enabled: true shared: true diff --git a/roles/web-app-matrix/meta/volumes.yml b/roles/web-app-matrix/meta/volumes.yml index cd2c0908f4..7bd7033b12 100644 --- a/roles/web-app-matrix/meta/volumes.yml +++ b/roles/web-app-matrix/meta/volumes.yml @@ -4,7 +4,7 @@ synapse_data: name: matrix_synapse_data mounts: - service: synapse - target: /data + target: &data_target /data when: "{{ lookup('config', 'web-app-matrix', 'services.matrix.flavor', 'ansible') == 'compose' }}" chatgpt_data: @@ -14,6 +14,25 @@ chatgpt_data: - service: matrix-chatgpt-bot target: /storage +mautrix_workdir: + type: tmpfs + mounts: + - service: mautrix-whatsapp + target: *data_target + size: 16m + - service: mautrix-meta + target: *data_target + size: 16m + - service: mautrix-signal + target: *data_target + size: 16m + - service: mautrix-slack + target: *data_target + size: 16m + - service: mautrix-telegram + target: *data_target + size: 16m + synapse_config: type: config source: "{{ [ lookup('container', 'web-app-matrix', 'directories.config'), 'homeserver.yaml' ] | path_join }}" diff --git a/roles/web-app-matrix/tasks/00_core.yml b/roles/web-app-matrix/tasks/00_core.yml index 2e9783dc49..6db1052df6 100644 --- a/roles/web-app-matrix/tasks/00_core.yml +++ b/roles/web-app-matrix/tasks/00_core.yml @@ -12,6 +12,10 @@ - matrix_flavor in ['ansible', 'compose'] fail_msg: "services.matrix.flavor must be 'ansible' or 'compose' (got '{{ matrix_flavor }}')" +- name: "๐Ÿ” Verify the gateway contract for {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-litellm/tasks/utils/consumer_contract.yml') }}" + when: MATRIX_LITELLM_ENABLED | bool + - name: "๐Ÿ“ค dispatch to ansible flavor (matrix-docker-ansible-deploy upstream)" include_tasks: flavor/ansible/main.yml when: matrix_flavor == 'ansible' diff --git a/roles/web-app-matrix/tasks/flavor/ansible/02_render_inventory.yml b/roles/web-app-matrix/tasks/flavor/ansible/02_render_inventory.yml index 3ac767fb45..8007cd0f72 100644 --- a/roles/web-app-matrix/tasks/flavor/ansible/02_render_inventory.yml +++ b/roles/web-app-matrix/tasks/flavor/ansible/02_render_inventory.yml @@ -17,17 +17,13 @@ dest: "{{ MATRIX_MDAD_DIR }}/inventory/host_vars/{{ MATRIX_SYNAPSE_DOMAIN }}/vars.yml" mode: "0644" register: _matrix_mdad_vars + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - name: "๐Ÿ”„ reconfigure matrix-mdad on inventory change" - ansible.builtin.shell: | - set -euo pipefail - if _mp="$(container volume inspect -f '{% raw %}{{ .Mountpoint }}{% endraw %}' matrix_matrix_mdad_state 2>/dev/null)"; then - rm -f "${_mp}/bootstrap.done" - fi - if container ps -q -f name=^matrix-mdad$ | grep -q .; then - container restart matrix-mdad - fi - args: - executable: /bin/bash + ansible.builtin.script: + cmd: "{{ role_path }}/files/flavor/ansible/reconfigure.sh" + environment: + MATRIX_MDAD_VOLUME: "{{ lookup('volume', application_id, 'matrix_mdad_state').name }}" + MATRIX_MDAD_CONTAINER: "{{ MATRIX_MDAD_CONTAINER }}" become: true when: _matrix_mdad_vars is changed diff --git a/roles/web-app-matrix/tasks/flavor/compose/01_docker.yml b/roles/web-app-matrix/tasks/flavor/compose/01_docker.yml index d5105f44ef..3b3cbf7d17 100644 --- a/roles/web-app-matrix/tasks/flavor/compose/01_docker.yml +++ b/roles/web-app-matrix/tasks/flavor/compose/01_docker.yml @@ -13,12 +13,9 @@ database_username: "{{ item.database_username }}" database_name: "{{ item.database_name }}" loop: "{{ MATRIX_BRIDGES }}" - -- name: ๐Ÿณ shut down compose project - command: - cmd: "{{ BIN_COMPOSE }} down" - chdir: "{{ lookup('container', application_id, 'directories.instance') }}" - when: DEPLOYMENT_MODE == 'compose' + loop_control: + label: "{{ item.bridge_name }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - name: "๐Ÿงน cleanup project folder" file: @@ -27,16 +24,32 @@ - name: "๐Ÿ“ create bridge folders" file: - path: "{{ lookup('container', application_id, 'directories.instance') }}mautrix/{{ item.bridge_name }}" + path: "{{ [ MATRIX_BRIDGE_SOURCE_DIR, item.bridge_name ] | path_join }}" state: directory mode: "0755" loop: "{{ MATRIX_BRIDGES }}" + loop_control: + label: "{{ item.bridge_name }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - name: โž• add multiple mautrix bridge configuration stack_host_template: src: "flavor/compose/mautrix/{{ item.bridge_name }}.config.yml.j2" - dest: "{{ lookup('container', application_id, 'directories.instance') }}mautrix/{{ item.bridge_name }}/config.yaml" + dest: "{{ [ MATRIX_BRIDGE_SOURCE_DIR, item.bridge_name, 'config.yaml' ] | path_join }}" loop: "{{ MATRIX_BRIDGES }}" + loop_control: + label: "{{ item.bridge_name }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + notify: compose-up + +- name: "โž• add the registration each bridge config implies" + stack_host_template: + src: "flavor/compose/mautrix/registration.yaml.j2" + dest: "{{ [ MATRIX_BRIDGE_SOURCE_DIR, item.bridge_name, 'registration.yaml' ] | path_join }}" + loop: "{{ MATRIX_BRIDGES }}" + loop_control: + label: "{{ item.bridge_name }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" notify: compose-up - name: โž• add element configuration @@ -72,47 +85,9 @@ include_tasks: 03_compose_pull_and_up.yml when: DEPLOYMENT_MODE == 'compose' -- name: "๐Ÿšฟ Flush handlers so the swarm stack deploys before the registration wait" +- name: "๐Ÿšฟ Flush handlers so the stack deploys before the Synapse wait" meta: flush_handlers -- name: โณ wait for registration files - wait_for: - path: "{{ lookup('container', application_id, 'directories.instance') }}mautrix/{{ item.bridge_name }}/registration.yaml" - state: present - timeout: "{{ lookup('timeout', 120) | int }}" - loop: "{{ MATRIX_BRIDGES }}" - -- name: "๐Ÿ” Make each bridge directory traversable for synapse" - file: - path: "{{ lookup('container', application_id, 'directories.instance') }}mautrix/{{ item.bridge_name }}" - state: directory - mode: "0755" - loop: "{{ MATRIX_BRIDGES }}" - -- name: "๐Ÿ” change file permissions" - file: - path: "{{ lookup('container', application_id, 'directories.instance') }}mautrix/{{ item.bridge_name }}/registration.yaml" - mode: "0755" - loop: "{{ MATRIX_BRIDGES }}" - -- name: "๐Ÿ”„ Restart synapse to load bridge registrations (compose mode)" - command: - cmd: "{{ BIN_COMPOSE }} restart synapse" - chdir: "{{ lookup('container', application_id, 'directories.instance') }}" - changed_when: true - when: - - MATRIX_BRIDGES | length > 0 - - DEPLOYMENT_MODE == 'compose' - -- name: "๐Ÿ”„ Restart synapse to load bridge registrations (swarm mode)" - ansible.builtin.command: "container service update --force {{ lookup('container_service', application_id, 'synapse') }}" - changed_when: true - timeout: "{{ lookup('timeout', 600) | int }}" - when: - - MATRIX_BRIDGES | length > 0 - - DEPLOYMENT_MODE == 'swarm' - - IS_STACK_HOST | bool - - name: โณ wait for Synapse client/versions endpoint uri_retry: url: "http://127.0.0.1:{{ lookup('config', application_id, 'services.synapse.ports.local.http') }}/_matrix/client/versions" @@ -123,36 +98,26 @@ delay: 2 until: matrix_synapse_health.status == 200 -- name: ๐Ÿ“ create admin account - shell: >- - container exec -i {{ MATRIX_SYNAPSE_CONTAINER_ADDRESS }} - register_new_matrix_user - -u {{ MATRIX_ADMINISTRATOR_USERNAME | quote }} - -p {{ MATRIX_ADMINISTRATOR_PASSWORD | quote }} - -a -c {{ MATRIX_SYNAPSE_CONFIG_PATH_CONTAINER | quote }} - http://localhost:{{ MATRIX_SYNAPSE_CONTAINER_PORT }} - register: matrix_create_admin - changed_when: matrix_create_admin.rc == 0 - failed_when: > - matrix_create_admin.rc != 0 and - 'User ID already taken' not in (matrix_create_admin.stdout + matrix_create_admin.stderr) +- name: "โœ… Wait until Synapse reaches every bridge as ready" + ansible.builtin.shell: + cmd: >- + container exec {{ MATRIX_SYNAPSE_CONTAINER_ADDRESS }} + {{ 10 | curl(retries=0) }} --noproxy '*' -fS + http://mautrix-{{ item.bridge_name }}:{{ item.appservice_port }}/_matrix/mau/ready + executable: /bin/bash + loop: "{{ MATRIX_BRIDGES }}" + loop_control: + label: "{{ item.bridge_name }}" + register: matrix_bridge_ready no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + retries: 60 + delay: 10 + until: matrix_bridge_ready.rc == 0 + changed_when: false when: IS_STACK_HOST | bool -- name: ๐Ÿ“ create chatgpt bot - shell: >- - container exec -i {{ MATRIX_SYNAPSE_CONTAINER_ADDRESS }} - register_new_matrix_user - -u chatgptbot - -p {{ lookup('config', application_id, 'secrets.credentials.chatgpt_bridge_user_password') | quote }} - -a -c {{ MATRIX_SYNAPSE_CONFIG_PATH_CONTAINER | quote }} - http://localhost:{{ MATRIX_SYNAPSE_CONTAINER_PORT }} - register: matrix_create_chatgptbot - changed_when: matrix_create_chatgptbot.rc == 0 - failed_when: > - matrix_create_chatgptbot.rc != 0 and - 'User ID already taken' not in (matrix_create_chatgptbot.stdout + matrix_create_chatgptbot.stderr) - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" +- name: "๐Ÿ‘ค Provision what only the stack host owns (accounts, bridge token, compose)" + ansible.builtin.include_tasks: utils/stack_host_provisioning.yml when: IS_STACK_HOST | bool - name: "๐Ÿ”„ Flush all handlers after docker setup so they don't intervine with openresty" diff --git a/roles/web-app-matrix/tasks/flavor/compose/utils/chatgpt_bridge_token.yml b/roles/web-app-matrix/tasks/flavor/compose/utils/chatgpt_bridge_token.yml new file mode 100644 index 0000000000..a7d82c412c --- /dev/null +++ b/roles/web-app-matrix/tasks/flavor/compose/utils/chatgpt_bridge_token.yml @@ -0,0 +1,22 @@ +--- +- name: "๐Ÿ”‘ Log the ChatGPT bridge bot in against Synapse" + uri_retry: + url: "http://127.0.0.1:{{ lookup('config', application_id, 'services.synapse.ports.local.http') }}/_matrix/client/v3/login" + method: POST + body_format: json + body: + type: m.login.password + identifier: + type: m.id.user + user: chatgptbot + password: "{{ lookup('config', application_id, 'secrets.credentials.chatgpt_bridge_user_password') }}" + initial_device_display_name: infinito-chatgpt-bridge + status_code: 200 + register: matrix_chatgptbot_login + retries: 10 + delay: 6 + until: matrix_chatgptbot_login.status | default(0) == 200 + +- name: "๐Ÿ”ง Publish the issued token to the bridge container env" + ansible.builtin.set_fact: + MATRIX_CHATGPT_ACCESS_TOKEN: "{{ matrix_chatgptbot_login.json.access_token }}" diff --git a/roles/web-app-matrix/tasks/flavor/compose/utils/realign_synapse_password.yml b/roles/web-app-matrix/tasks/flavor/compose/utils/realign_synapse_password.yml new file mode 100644 index 0000000000..1150cf6d2b --- /dev/null +++ b/roles/web-app-matrix/tasks/flavor/compose/utils/realign_synapse_password.yml @@ -0,0 +1,28 @@ +--- +# Param: realign_localpart - the account's localpart, e.g. "chatgptbot" +# Param: realign_password - the password the deployment declares for it +- name: "๐Ÿ”‘ Hash the declared password for {{ realign_localpart }}" + ansible.builtin.shell: + cmd: >- + container exec -i {{ MATRIX_SYNAPSE_CONTAINER_ADDRESS }} + hash_password -c {{ MATRIX_SYNAPSE_CONFIG_PATH_CONTAINER | quote }} + -p {{ realign_password | quote }} + executable: /bin/bash + register: matrix_password_hash + changed_when: false + +- name: "๐Ÿ”‘ Point {{ realign_localpart }} at the declared password" + ansible.builtin.shell: + cmd: >- + container exec -i -e PGPASSWORD={{ MATRIX_POSTGRES_PASSWORD | quote }} + {{ lookup('database', application_id, 'address') }} + psql -v ON_ERROR_STOP=1 -U {{ MATRIX_POSTGRES_USER | quote }} + -d {{ MATRIX_POSTGRES_DATABASE | quote }} + -v hash={{ (matrix_password_hash.stdout | trim) | quote }} + -v name={{ ('@' ~ realign_localpart ~ ':' ~ MATRIX_SERVER_NAME) | quote }} + -f - + stdin: >- + {{ lookup('file', 'sql/realign_user_password.sql') }} + executable: /bin/bash + register: matrix_password_update + changed_when: "'UPDATE 1' in matrix_password_update.stdout" diff --git a/roles/web-app-matrix/tasks/flavor/compose/utils/stack_host_provisioning.yml b/roles/web-app-matrix/tasks/flavor/compose/utils/stack_host_provisioning.yml new file mode 100644 index 0000000000..f2ead609a3 --- /dev/null +++ b/roles/web-app-matrix/tasks/flavor/compose/utils/stack_host_provisioning.yml @@ -0,0 +1,62 @@ +--- +- name: ๐Ÿ“ create admin account + shell: >- + container exec -i {{ MATRIX_SYNAPSE_CONTAINER_ADDRESS }} + register_new_matrix_user + -u {{ MATRIX_ADMINISTRATOR_USERNAME | quote }} + -p {{ MATRIX_ADMINISTRATOR_PASSWORD | quote }} + -a -c {{ MATRIX_SYNAPSE_CONFIG_PATH_CONTAINER | quote }} + http://localhost:{{ MATRIX_SYNAPSE_CONTAINER_PORT }} + register: matrix_create_admin + changed_when: matrix_create_admin.rc == 0 + failed_when: > + matrix_create_admin.rc != 0 and + 'User ID already taken' not in (matrix_create_admin.stdout + matrix_create_admin.stderr) + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐Ÿ”‘ Realign the admin password Synapse already stored" + ansible.builtin.include_tasks: + file: realign_synapse_password.yml + apply: + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + vars: + realign_localpart: "{{ MATRIX_ADMINISTRATOR_USERNAME }}" + realign_password: "{{ MATRIX_ADMINISTRATOR_PASSWORD }}" + when: not matrix_create_admin.changed + +- name: ๐Ÿ“ create chatgpt bot + shell: >- + container exec -i {{ MATRIX_SYNAPSE_CONTAINER_ADDRESS }} + register_new_matrix_user + -u chatgptbot + -p {{ lookup('config', application_id, 'secrets.credentials.chatgpt_bridge_user_password') | quote }} + -a -c {{ MATRIX_SYNAPSE_CONFIG_PATH_CONTAINER | quote }} + http://localhost:{{ MATRIX_SYNAPSE_CONTAINER_PORT }} + register: matrix_create_chatgptbot + changed_when: matrix_create_chatgptbot.rc == 0 + failed_when: > + matrix_create_chatgptbot.rc != 0 and + 'User ID already taken' not in (matrix_create_chatgptbot.stdout + matrix_create_chatgptbot.stderr) + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐Ÿ”‘ Realign the bridge bot password Synapse already stored" + ansible.builtin.include_tasks: + file: realign_synapse_password.yml + apply: + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + vars: + realign_localpart: chatgptbot + realign_password: "{{ lookup('config', application_id, 'secrets.credentials.chatgpt_bridge_user_password') }}" + when: not matrix_create_chatgptbot.changed + +- name: "๐Ÿ”‘ Give the ChatGPT bridge a token Synapse actually issued" + ansible.builtin.include_tasks: + file: chatgpt_bridge_token.yml + apply: + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "โž• re-add compose.yml now that the bridge token exists" + stack_host_template: + src: "compose.yml.j2" + dest: "{{ [ lookup('container', application_id, 'directories.instance'),'compose.yml' ] | path_join }}" + notify: compose-up diff --git a/roles/web-app-matrix/templates/compose.yml.j2 b/roles/web-app-matrix/templates/compose.yml.j2 index 71b57cc273..ab2b469675 100644 --- a/roles/web-app-matrix/templates/compose.yml.j2 +++ b/roles/web-app-matrix/templates/compose.yml.j2 @@ -5,6 +5,6 @@ {% include 'flavor/compose/services.yml.j2' %} {% endif %} -{{ lookup('compose_volumes') }} +{{ lookup('compose_volumes', extra_secrets=(lookup('matrix_bridge_mounts', 'stack') if matrix_flavor == 'compose' else {})) }} {{ lookup('compose_networks') }} diff --git a/roles/web-app-matrix/templates/flavor/ansible/services.yml.j2 b/roles/web-app-matrix/templates/flavor/ansible/services.yml.j2 index 42542a19cf..3746b3eb25 100644 --- a/roles/web-app-matrix/templates/flavor/ansible/services.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/ansible/services.yml.j2 @@ -1,5 +1,5 @@ -{% set service_name = MATRIX_MDAD_SERVICE %} - {{ MATRIX_MDAD_SERVICE }}: +{% set service_name = MATRIX_MDAD_SERVICE_KEY %} + {{ MATRIX_MDAD_SERVICE_KEY }}: {% include 'roles/sys-svc-container/templates/deploy.yml.j2' %} {{ lookup('compose_only', 'container_name', MATRIX_MDAD_CONTAINER) }} build: @@ -26,15 +26,17 @@ - {{ lookup('volume', application_id, 'matrix_mdad_docker').name }}:{{ lookup('volume', 'web-app-matrix', 'matrix_mdad_docker').target }} - {{ lookup('volume', application_id, 'matrix_mdad_state').name }}:{{ lookup('volume', 'web-app-matrix', 'matrix_mdad_state').target }} - {{ lookup('volume', application_id, 'matrix_mdad_matrix').name }}:{{ lookup('volume', 'web-app-matrix', 'matrix_mdad_matrix').target }} -{% if (TLS_MODE | lower) == 'self_signed' %} +{% if MATRIX_CA_INJECTED | bool %} - {{ CA_TRUST.cert_host }}:{{ CA_TRUST.cert_host }}:ro + - {{ CA_TRUST.bundle_host }}:{{ CA_TRUST.bundle_host }}:ro {% endif %} - /sys/fs/cgroup:/sys/fs/cgroup:rw tmpfs: - /run - /run/lock - /tmp - ports: - - "{{ DOCKER_BIND_HOST }}:{{ MATRIX_SYNAPSE_PORT }}:8008" + {{ lookup('container_ports', ['synapse', 'http', DOCKER_BIND_HOST]) | indent(4) }} + # nocheck: compose-ports-must-use-container-ports matrix-docker-ansible-deploy fixes element on 8080 while this repo declares element.ports.internal.http 80; the two disagree and the playbook owns the container - "{{ DOCKER_BIND_HOST }}:{{ MATRIX_ELEMENT_PORT }}:8080" + # nocheck: compose-ports-must-use-container-ports the upstream playbook serves federation on 8048 and no ports.internal.federation is declared for it - "{{ DOCKER_BIND_HOST }}:{{ MATRIX_FEDERATION_PORT }}:8048" diff --git a/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 b/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 index 9bf6d713f3..8185cfdfd2 100644 --- a/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/ansible/vars.yml.j2 @@ -60,9 +60,9 @@ jitsi_jicofo_container_network: host matrix_livekit_jwt_service_container_port: 8030 {% set _synapse_extra_args = [] %} -{% if (TLS_MODE | lower) == 'self_signed' %} +{% if MATRIX_CA_INJECTED | bool %} {% set _ = _synapse_extra_args.extend([ - '--mount type=bind,src=' ~ CA_TRUST.cert_host ~ ',dst=' ~ MATRIX_CA_MOUNT_PATH ~ ',ro', + '--mount type=bind,src=' ~ CA_TRUST.bundle_host ~ ',dst=' ~ MATRIX_CA_MOUNT_PATH ~ ',ro', '-e SSL_CERT_FILE=' ~ MATRIX_CA_MOUNT_PATH, '-e REQUESTS_CA_BUNDLE=' ~ MATRIX_CA_MOUNT_PATH, ]) %} diff --git a/roles/web-app-matrix/templates/flavor/compose/mautrix/meta.config.yml.j2 b/roles/web-app-matrix/templates/flavor/compose/mautrix/meta.config.yml.j2 index a369dda056..b584e7ba6b 100644 --- a/roles/web-app-matrix/templates/flavor/compose/mautrix/meta.config.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/compose/mautrix/meta.config.yml.j2 @@ -115,10 +115,10 @@ homeserver: retry_limit: 4 appservice: - address: http://mautrix-meta:29319 + address: http://mautrix-meta:{{ item.appservice_port }} hostname: 0.0.0.0 - port: 29319 + port: {{ item.appservice_port }} id: meta bot: @@ -129,8 +129,8 @@ appservice: ephemeral_events: true async_transactions: false - as_token: "This value is generated when generating the registration" - hs_token: "This value is generated when generating the registration" + as_token: "{{ lookup('config', application_id, 'secrets.credentials.mautrix_meta_bridge_as_token') }}" + hs_token: "{{ lookup('config', application_id, 'secrets.credentials.mautrix_meta_bridge_hs_token') }}" {% raw %} username_template: meta_{{.}} diff --git a/roles/web-app-matrix/templates/flavor/compose/mautrix/registration.yaml.j2 b/roles/web-app-matrix/templates/flavor/compose/mautrix/registration.yaml.j2 new file mode 100644 index 0000000000..2b207259a7 --- /dev/null +++ b/roles/web-app-matrix/templates/flavor/compose/mautrix/registration.yaml.j2 @@ -0,0 +1,20 @@ +{% set bridge = lookup('template', lookup('path_absolute', 'roles/web-app-matrix/templates/flavor/compose/mautrix/' ~ item.bridge_name ~ '.config.yml.j2')) | from_yaml %} +{% set appservice = bridge.appservice %} +{% set domain = bridge.homeserver.domain | string | regex_escape %} +{% set ghost = appservice.username_template.split('{{.}}') %} +{{ { + 'id': appservice.id, + 'url': appservice.address, + 'as_token': appservice.as_token, + 'hs_token': appservice.hs_token, + 'sender_localpart': '_bot_' ~ appservice.bot.username, + 'rate_limited': false, + 'namespaces': { + 'users': [ + {'regex': '^@' ~ (appservice.bot.username | regex_escape) ~ ':' ~ domain ~ '$', 'exclusive': true}, + {'regex': '^@' ~ (ghost[0] | regex_escape) ~ '.*' ~ (ghost[1] | regex_escape) ~ ':' ~ domain ~ '$', 'exclusive': true}, + ], + }, + 'de.sorunome.msc2409.push_ephemeral': appservice.ephemeral_events, + 'receive_ephemeral': appservice.ephemeral_events, +} | to_nice_yaml(indent=2) }} diff --git a/roles/web-app-matrix/templates/flavor/compose/mautrix/signal.config.yml.j2 b/roles/web-app-matrix/templates/flavor/compose/mautrix/signal.config.yml.j2 index 8d738306e1..9ee88b43cf 100644 --- a/roles/web-app-matrix/templates/flavor/compose/mautrix/signal.config.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/compose/mautrix/signal.config.yml.j2 @@ -47,10 +47,10 @@ homeserver: retry_limit: 4 appservice: - address: http://mautrix-signal:29328 + address: http://mautrix-signal:{{ item.appservice_port }} hostname: 0.0.0.0 - port: 29328 + port: {{ item.appservice_port }} id: signal bot: @@ -61,8 +61,8 @@ appservice: ephemeral_events: true async_transactions: false - as_token: "This value is generated when generating the registration" - hs_token: "This value is generated when generating the registration" + as_token: "{{ lookup('config', application_id, 'secrets.credentials.mautrix_signal_bridge_as_token') }}" + hs_token: "{{ lookup('config', application_id, 'secrets.credentials.mautrix_signal_bridge_hs_token') }}" {% raw %} username_template: signal_{{.}} @@ -125,9 +125,3 @@ logging: writers: - type: stdout format: pretty-colored - - type: file - format: json - filename: ./logs/mautrix-signal.log - max_size: 100 - max_backups: 10 - compress: true diff --git a/roles/web-app-matrix/templates/flavor/compose/mautrix/slack.config.yml.j2 b/roles/web-app-matrix/templates/flavor/compose/mautrix/slack.config.yml.j2 index 33f37562d7..a89d2b6c20 100644 --- a/roles/web-app-matrix/templates/flavor/compose/mautrix/slack.config.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/compose/mautrix/slack.config.yml.j2 @@ -21,10 +21,10 @@ homeserver: retry_limit: 4 appservice: - address: http://mautrix-slack:29335 + address: http://mautrix-slack:{{ item.appservice_port }} hostname: 0.0.0.0 - port: 29335 + port: {{ item.appservice_port }} id: slack bot: @@ -35,8 +35,8 @@ appservice: ephemeral_events: true async_transactions: false - as_token: "This value is generated when generating the registration" - hs_token: "This value is generated when generating the registration" + as_token: "{{ lookup('config', application_id, 'secrets.credentials.mautrix_slack_bridge_as_token') }}" + hs_token: "{{ lookup('config', application_id, 'secrets.credentials.mautrix_slack_bridge_hs_token') }}" {% raw %} username_template: slack_{{.}} @@ -128,9 +128,3 @@ logging: writers: - type: stdout format: pretty-colored - - type: file - format: json - filename: ./logs/mautrix-slack.log - max_size: 100 - max_backups: 10 - compress: true diff --git a/roles/web-app-matrix/templates/flavor/compose/mautrix/telegram.config.yml.j2 b/roles/web-app-matrix/templates/flavor/compose/mautrix/telegram.config.yml.j2 index a11300ea82..e3ad679693 100644 --- a/roles/web-app-matrix/templates/flavor/compose/mautrix/telegram.config.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/compose/mautrix/telegram.config.yml.j2 @@ -63,9 +63,9 @@ homeserver: retry_limit: 4 appservice: - address: http://mautrix-telegram:29317 + address: http://mautrix-telegram:{{ item.appservice_port }} hostname: 0.0.0.0 - port: 29317 + port: {{ item.appservice_port }} id: telegram bot: @@ -75,8 +75,8 @@ appservice: ephemeral_events: true - as_token: "This value is generated when generating the registration" - hs_token: "This value is generated when generating the registration" + as_token: "{{ lookup('config', application_id, 'secrets.credentials.mautrix_telegram_bridge_as_token') }}" + hs_token: "{{ lookup('config', application_id, 'secrets.credentials.mautrix_telegram_bridge_hs_token') }}" username_template: {% raw %}telegram_{{.}}{% endraw %} @@ -189,9 +189,3 @@ logging: writers: - type: stdout format: pretty-colored - - type: file - format: json - filename: ./logs/bridge.log - max_size: 100 - max_backups: 10 - compress: false diff --git a/roles/web-app-matrix/templates/flavor/compose/mautrix/whatsapp.config.yml.j2 b/roles/web-app-matrix/templates/flavor/compose/mautrix/whatsapp.config.yml.j2 index 623309ad15..13a910b171 100644 --- a/roles/web-app-matrix/templates/flavor/compose/mautrix/whatsapp.config.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/compose/mautrix/whatsapp.config.yml.j2 @@ -138,10 +138,10 @@ homeserver: retry_limit: 4 appservice: - address: http://mautrix-whatsapp:29318 + address: http://mautrix-whatsapp:{{ item.appservice_port }} hostname: 0.0.0.0 - port: 29318 + port: {{ item.appservice_port }} id: whatsapp bot: @@ -152,8 +152,8 @@ appservice: ephemeral_events: true async_transactions: false - as_token: "This value is generated when generating the registration" - hs_token: "This value is generated when generating the registration" + as_token: "{{ lookup('config', application_id, 'secrets.credentials.mautrix_whatsapp_bridge_as_token') }}" + hs_token: "{{ lookup('config', application_id, 'secrets.credentials.mautrix_whatsapp_bridge_hs_token') }}" {% raw %} username_template: whatsapp_{{.}} diff --git a/roles/web-app-matrix/templates/flavor/compose/services.yml.j2 b/roles/web-app-matrix/templates/flavor/compose/services.yml.j2 index d04bbfe093..e24e06d6f3 100644 --- a/roles/web-app-matrix/templates/flavor/compose/services.yml.j2 +++ b/roles/web-app-matrix/templates/flavor/compose/services.yml.j2 @@ -1,36 +1,28 @@ {% set service_name = 'synapse' %} {{ service_name }}: {% include 'roles/sys-svc-container/templates/deploy.yml.j2' %} -{% set container_port = MATRIX_SYNAPSE_CONTAINER_PORT %} {{ lookup('container_image', application_id, 'synapse') }} {{ lookup('compose_only', 'container_name', MATRIX_SYNAPSE_NAME) }} {{ lookup('compose_restart') }} logging: driver: journald - {{ lookup('container_volumes', service_name, extra_volumes=lookup('matrix_bridge_mounts')) | indent(4) }} + {{ lookup('container_volumes', service_name, extra_secrets=lookup('matrix_bridge_mounts', 'synapse')) | indent(4) }} environment: - SYNAPSE_SERVER_NAME={{ MATRIX_SYNAPSE_DOMAIN }} - SYNAPSE_REPORT_STATS=no - ports: - - "{{ DOCKER_BIND_HOST }}:{{lookup('config', 'web-app-matrix', 'services.synapse.ports.local.http')}}:{{ container_port }}" + {{ lookup('container_ports', ['synapse', 'http', DOCKER_BIND_HOST]) | indent(4) }} {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_healthcheck', service_name) | indent(4) }} -{% set _synapse_bridge_deps = {} %} -{% for item in MATRIX_BRIDGES %} -{% set _ = _synapse_bridge_deps.__setitem__('mautrix-' ~ item.bridge_name, {'condition': 'service_healthy'}) %} -{% endfor %} - {{ lookup('container_depends_on', application_id, extra=_synapse_bridge_deps) | indent(4) }} + {{ lookup('container_depends_on', application_id) | indent(4) }} {{ lookup('container_networks') | indent(4) }} {% set service_name = 'element' %} {{ service_name }}: {% include 'roles/sys-svc-container/templates/deploy.yml.j2' %} -{% set container_port = lookup('config', application_id, 'services.' ~ service_name ~ '.ports.internal.http') %} {{ lookup('container_image', application_id, 'element') }} {{ lookup('compose_only', 'container_name', MATRIX_ELEMENT_NAME) }} {{ lookup('compose_restart') }} {{ lookup('container_volumes', service_name) | indent(4) }} - ports: - - "{{ DOCKER_BIND_HOST }}:{{ MATRIX_ELEMENT_PORT }}:{{ container_port }}" + {{ lookup('container_ports', ['element', 'http', DOCKER_BIND_HOST]) | indent(4) }} {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} @@ -41,20 +33,20 @@ {{ lookup('compose_only', 'container_name', 'matrix-' ~ item.bridge_name) }} image: "dock.mau.dev/mautrix/{{ item.bridge_name }}:latest" # nocheck: container-image-lookup {{ lookup('compose_restart') }} - environment: - UID: "{{ MATRIX_SYNAPSE_UID }}" - GID: "{{ MATRIX_SYNAPSE_GID }}" - volumes: # nocheck: compose-inline-mount-section - - ./mautrix/{{ item.bridge_name }}:/data + user: "{{ MATRIX_SYNAPSE_UID }}:{{ MATRIX_SYNAPSE_GID }}" + command: ["/usr/bin/mautrix-{{ item.bridge_name }}", "--config", "{{ MATRIX_BRIDGE_CONFIG_TARGET }}", "--no-update"] + {{ lookup('container_volumes', service_name, extra_secrets=lookup('matrix_bridge_mounts', 'bridge', item.bridge_name)) | indent(4) }} healthcheck: - test: ["CMD-SHELL", "test -f {{ MATRIX_REGISTRATION_FILE_FOLDER }}registration.yaml || exit 1"] - interval: 15s - timeout: 10s - retries: 5 - start_period: 5m + test: ["CMD", "curl", "--noproxy", "*", "-fsS", "http://127.0.0.1:{{ item.appservice_port }}/_matrix/mau/live"] + interval: 2m + timeout: 5s + retries: 3 + start_period: 10m + start_interval: 5s + {{ lookup('container_depends_on', application_id, extra={'synapse': {'condition': 'service_healthy'}}) | indent(4) }} {{ lookup('container_networks') | indent(4) }} {% endfor %} -{% if lookup('config', application_id, 'services.matrix.plugins.chatgpt') | bool %} +{% if (lookup('config', application_id, 'services.matrix.plugins.chatgpt') | bool) and (MATRIX_CHATGPT_ACCESS_TOKEN | length > 0) %} {% set service_name = 'matrix-chatgpt-bot' %} {{ service_name }}: {% include 'roles/sys-svc-container/templates/deploy.yml.j2' %} @@ -62,25 +54,26 @@ {{ lookup('compose_only', 'container_name', "matrix-chatgpt") }} {{ lookup('container_image', application_id, 'matrix-chatgpt-bot') }} {{ lookup('container_volumes', service_name) | indent(4) }} + {{ lookup('container_depends_on', application_id, extra={'synapse': {'condition': 'service_healthy'}}) | indent(4) }} environment: - OPENAI_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.chatgpt_bridge_openai_api_key')}}" + OPENAI_API_KEY: "{{ MATRIX_CHATGPT_BRIDGE_API_KEY }}" CHATGPT_CONTEXT: 'thread' - CHATGPT_API_MODEL: 'gpt-3.5-turbo' - CHATGPT_REVERSE_PROXY: 'https://api.openai.com/v1/chat/completions' + CHATGPT_API_MODEL: "{{ MATRIX_CHATGPT_BRIDGE_MODEL }}" + CHATGPT_REVERSE_PROXY: "{{ MATRIX_CHATGPT_BRIDGE_ENDPOINT }}" CHATGPT_MAX_PROMPT_TOKENS: '3000' KEYV_BACKEND: 'file' KEYV_URL: '' KEYV_BOT_ENCRYPTION: 'false' KEYV_BOT_STORAGE: 'true' - MATRIX_HOMESERVER_URL: '{{ MATRIX_SYNAPSE_URL }}' + MATRIX_HOMESERVER_URL: '{{ MATRIX_SYNAPSE_LOCAL_URL }}' MATRIX_BOT_USERNAME: '@chatgptbot:{{ MATRIX_SERVER_NAME }}' - MATRIX_ACCESS_TOKEN: "{{ lookup('config', application_id, 'secrets.credentials.chatgpt_bridge_access_token', '') }}" + MATRIX_ACCESS_TOKEN: "{{ MATRIX_CHATGPT_ACCESS_TOKEN }}" MATRIX_BOT_PASSWORD: "{{ lookup('config', application_id, 'secrets.credentials.chatgpt_bridge_user_password') }}" MATRIX_DEFAULT_PREFIX: '!chatgpt' MATRIX_DEFAULT_PREFIX_REPLY: 'false' MATRIX_WHITELIST: ':{{ MATRIX_SERVER_NAME }}' MATRIX_AUTOJOIN: 'true' - MATRIX_ENCRYPTION: 'true' + MATRIX_ENCRYPTION: '{{ MATRIX_CHATGPT_ENCRYPTION | lower }}' MATRIX_THREADS: 'true' MATRIX_PREFIX_DM: 'false' MATRIX_RICH_TEXT: 'true' diff --git a/roles/web-app-matrix/templates/flavor/compose/synapse/homeserver.yaml.j2 b/roles/web-app-matrix/templates/flavor/compose/synapse/homeserver.yaml.j2 index d7891d4e02..2a96e6a26d 100644 --- a/roles/web-app-matrix/templates/flavor/compose/synapse/homeserver.yaml.j2 +++ b/roles/web-app-matrix/templates/flavor/compose/synapse/homeserver.yaml.j2 @@ -37,6 +37,25 @@ trusted_key_servers: - server_name: "matrix.org" admin_contact: 'mailto:{{ lookup('users', 'administrator').email }}' +rc_joins: + local: + per_second: 0.1 + burst_count: {{ MATRIX_SYNAPSE_LOGIN_BURST }} + remote: + per_second: 0.01 + burst_count: {{ MATRIX_SYNAPSE_LOGIN_BURST }} + +rc_login: + address: + per_second: 0.17 + burst_count: {{ MATRIX_SYNAPSE_LOGIN_BURST }} + account: + per_second: 0.17 + burst_count: {{ MATRIX_SYNAPSE_LOGIN_BURST }} + failed_attempts: + per_second: 0.17 + burst_count: {{ MATRIX_SYNAPSE_LOGIN_BURST }} + {% set email = lookup('email', application_id) %} {% if email.enabled | bool %} email: diff --git a/roles/web-app-matrix/templates/playwright.env.j2 b/roles/web-app-matrix/templates/playwright.env.j2 index 2f881167df..5438b6172c 100644 --- a/roles/web-app-matrix/templates/playwright.env.j2 +++ b/roles/web-app-matrix/templates/playwright.env.j2 @@ -22,6 +22,8 @@ EMAIL_SERVICE_ENABLED={{ lookup('config', application_id, 'services.email.enable # nocheck: playwright-service-gate โ€” persona drives OIDC path; LDAP federation exercised in LDAP-only matrix variant LDAP_SERVICE_ENABLED={{ lookup('config', application_id, 'services.ldap.enabled') | string | lower }} +LITELLM_SERVICE_ENABLED={{ lookup('config', application_id, 'services.litellm.enabled') | string | lower }} + # nocheck: playwright-service-gate โ€” consumed via shared persona helpers (roles/test-e2e-playwright/files/personas/) LOGOUT_SERVICE_ENABLED={{ lookup('config', application_id, 'services.logout.enabled') | string | lower }} @@ -32,6 +34,10 @@ MATOMO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.matomo.enab MATRIX_BASE_URL={{ lookup('canonical_url', application_id, 'synapse') | dotenv_quote }} +MATRIX_CHATGPT_BRIDGE_ENDPOINT={{ MATRIX_CHATGPT_BRIDGE_ENDPOINT | dotenv_quote }} + +MATRIX_CHATGPT_BRIDGE_MODEL={{ MATRIX_CHATGPT_BRIDGE_MODEL | dotenv_quote }} + MATRIX_FLAVOR={{ lookup('config', application_id, 'services.matrix.flavor') | dotenv_quote }} MATRIX_PLUGINS_JSON={{ MATRIX_BRIDGE | to_json | dotenv_quote }} diff --git a/roles/web-app-matrix/vars/main.yml b/roles/web-app-matrix/vars/main.yml index 491677d404..deea5c3e51 100644 --- a/roles/web-app-matrix/vars/main.yml +++ b/roles/web-app-matrix/vars/main.yml @@ -12,7 +12,9 @@ MATRIX_ADMINISTRATOR_USERNAME: "{{ lookup('users', 'administrator').username }}" MATRIX_ADMINISTRATOR_PASSWORD: "{{ lookup('users', 'administrator').password }}" MATRIX_WELL_KNOWN_DIRECTORY: "{{ [ lookup('nginx','directories.data.well_known'), 'matrix' ] | path_join }}" MATRIX_WELL_KNOWN_FILE: "{{ MATRIX_WELL_KNOWN_DIRECTORY }}server" -MATRIX_REGISTRATION_FILE_FOLDER: "/data/" +MATRIX_REGISTRATION_FILE_FOLDER: "/registrations/" +MATRIX_BRIDGE_SOURCE_DIR: "{{ [ lookup('container', application_id, 'directories.config'), 'mautrix' ] | path_join }}" +MATRIX_BRIDGE_CONFIG_TARGET: "/config/config.yaml" MATRIX_REGISTRATION_SHARED_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.registration_shared_secret') }}" MATRIX_FEDERATION_PORT: "{{ lookup('config', 'web-app-matrix', 'services.synapse.ports.public.federation') }}" MATRIX_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') }}" @@ -20,14 +22,22 @@ MATRIX_OIDC_HOST: "{{ lookup('tls', 'web-app-keycloak', 'domain') }}" MATRIX_OIDC_HOST_IS_ONION: "{{ MATRIX_OIDC_HOST is search('\\.onion$') }}" MATRIX_BASE_URL: "{{ lookup('tls', application_id, 'protocols.web') }}://{{ DOMAIN_PRIMARY }}" +MATRIX_LITELLM_ENABLED: "{{ lookup('config', application_id, 'services.litellm.enabled') | bool }}" +MATRIX_CHATGPT_BRIDGE_ENDPOINT: "{{ (LITELLM_OPENAI_BASE_LOCAL_URL ~ '/chat/completions') if (MATRIX_LITELLM_ENABLED | bool) else 'https://api.openai.com/v1/chat/completions' + }}" +MATRIX_CHATGPT_BRIDGE_MODEL: "{{ LITELLM_CHAT_MODEL if (MATRIX_LITELLM_ENABLED | bool) else 'gpt-3.5-turbo' }}" +MATRIX_CHATGPT_BRIDGE_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.litellm_api_key') if (MATRIX_LITELLM_ENABLED | bool) else lookup('config', + application_id, 'secrets.credentials.chatgpt_bridge_openai_api_key') }}" + MATRIX_SYNAPSE_NAME: "{{ lookup('config', application_id, 'services.synapse.name') }}" +MATRIX_SYNAPSE_SERVICE: "{{ lookup('container_service', application_id, 'synapse') }}" MATRIX_SYNAPSE_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, 'synapse') }}" MATRIX_SYNAPSE_VOLUME: "{{ lookup('volume', application_id, 'synapse_data').name }}" MATRIX_SYNAPSE_UID: 991 MATRIX_SYNAPSE_GID: 991 -MATRIX_MDAD_SERVICE: "matrix" +MATRIX_MDAD_SERVICE_KEY: "matrix" MATRIX_MDAD_CONTAINER: "{{ application_id | get_entity_name }}" -MATRIX_MDAD_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, MATRIX_MDAD_SERVICE) }}" +MATRIX_MDAD_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, MATRIX_MDAD_SERVICE_KEY) }}" MATRIX_SYNAPSE_DOMAIN: "{{ lookup('domains', application_id).synapse }}" MATRIX_SYNAPSE_PORT: "{{ lookup('config', 'web-app-matrix', 'services.synapse.ports.local.http') }}" MATRIX_SYNAPSE_CONTAINER_PORT: "{{ lookup('config', application_id, 'services.synapse.ports.internal.http') }}" @@ -37,6 +47,10 @@ MATRIX_SYNAPSE_LOG_PATH_HOST: "{{ [ lookup('container', application_id, 'directo MATRIX_SYNAPSE_LOG_PATH_CONTAINER: "/data/{{ MATRIX_SYNAPSE_DOMAIN }}.log.config" # nocheck: container-var-name-lookup in-container path, not a container name MATRIX_SYNAPSE_BIND_MOUNT_MODE: "0644" MATRIX_SYNAPSE_URL: "{{ lookup('canonical_url', application_id, 'synapse') }}" +MATRIX_SYNAPSE_LOCAL_URL: "http://{{ MATRIX_SYNAPSE_SERVICE }}:{{ MATRIX_SYNAPSE_CONTAINER_PORT }}" +MATRIX_SYNAPSE_LOGIN_BURST: 30 +MATRIX_CHATGPT_ACCESS_TOKEN: "{{ lookup('config', application_id, 'secrets.credentials.chatgpt_bridge_access_token', '') }}" +MATRIX_CHATGPT_ENCRYPTION: "false" MATRIX_SYNAPSE_LISTEN_FLAGS: "{{ MATRIX_FEDERATION_PORT }} {{ 'ssl ' if (lookup('tls', application_id, 'enabled') | bool) else '' }} default_server" MATRIX_ELEMENT_NAME: "{{ lookup('config', application_id, 'services.element.name') }}" @@ -71,6 +85,7 @@ MATRIX_CONFERENCING_ELEMENT_CALL: "{{ lookup('config', application_id, 'services MATRIX_LDAP_ENABLED: "{{ lookup('config', application_id, 'services.ldap.enabled') | bool }}" +MATRIX_CA_INJECTED: "{{ lookup('ca_injected', application_id) | bool }}" MATRIX_CA_MOUNT_PATH: "{{ CA_TRUST.cert_container }}" MATRIX_POSTGRES_HOST: "{{ lookup('database', application_id, 'host') }}" diff --git a/roles/web-app-mattermost/README.md b/roles/web-app-mattermost/README.md index 3b15bc9f5f..1a7c01b98f 100644 --- a/roles/web-app-mattermost/README.md +++ b/roles/web-app-mattermost/README.md @@ -15,15 +15,19 @@ The diagram places Mattermost in the Infinito.Nexus cosmos: the components it de ```mermaid flowchart LR subgraph deps [Dependencies] + dep_svc_ai_litellm["svc-ai-litellm ๐Ÿณ๐Ÿ"] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local ๐Ÿ’ป"] dep_svc_db_openldap["svc-db-openldap ๐Ÿณ๐Ÿ"] dep_svc_db_postgres["svc-db-postgres ๐Ÿณ๐Ÿ"] dep_svc_db_redis["svc-db-redis ๐Ÿณ๐Ÿ"] dep_svc_net_tor["svc-net-tor ๐Ÿณ๐Ÿ"] dep_web_app_dashboard["web-app-dashboard ๐Ÿณ๐Ÿ"] + dep_web_app_hermes["web-app-hermes ๐Ÿณ๐Ÿ"] dep_web_app_keycloak["web-app-keycloak ๐Ÿณ๐Ÿ"] dep_web_app_mailu["web-app-mailu ๐Ÿณ๐Ÿ"] dep_web_app_matomo["web-app-matomo ๐Ÿณ๐Ÿ"] + dep_web_app_openclaw["web-app-openclaw ๐Ÿณ๐Ÿ"] + dep_web_app_openwebui["web-app-openwebui ๐Ÿณ๐Ÿ"] dep_web_app_prometheus["web-app-prometheus ๐Ÿณ๐Ÿ"] dep_web_app_seaweedfs["web-app-seaweedfs ๐Ÿณ๐Ÿ"] dep_web_svc_css["web-svc-css ๐Ÿ’ป"] @@ -46,19 +50,29 @@ flowchart LR svc_prometheus["prometheus"] svc_tor["tor"] svc_container_backup["container_backup"] + svc_litellm["litellm"] + svc_mattermostmcp["mattermostmcp"] + svc_openwebui["openwebui"] + svc_hermes["hermes"] + svc_openclaw["openclaw"] + svc_flowise["flowise โŒ"] end subgraph dependents [Dependents] dpt_web_app_nextcloud["web-app-nextcloud ๐Ÿณ๐Ÿ"] end + dep_svc_ai_litellm -. "0..1" .-> svc_litellm dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup dep_svc_db_openldap -- "1:1" --> svc_ldap dep_svc_db_postgres -. "0..1" .-> svc_postgres dep_svc_db_redis -. "0..1" .-> svc_redis dep_svc_net_tor -. "0..1" .-> svc_tor dep_web_app_dashboard -. "0..1" .-> svc_dashboard + dep_web_app_hermes -. "0..1" .-> svc_hermes dep_web_app_keycloak -. "0..1" .-> svc_sso dep_web_app_mailu -. "0..1" .-> svc_email dep_web_app_matomo -. "0..1" .-> svc_matomo + dep_web_app_openclaw -. "0..1" .-> svc_openclaw + dep_web_app_openwebui -. "0..1" .-> svc_openwebui dep_web_app_prometheus -. "0..1" .-> svc_prometheus dep_web_app_seaweedfs -. "0..1" .-> svc_seaweedfs dep_web_svc_css -. "0..1" .-> svc_css @@ -97,19 +111,20 @@ Run the published image to provision the inventory and deploy Mattermost to a ma ```bash APP=web-app-mattermost HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' @@ -125,6 +140,58 @@ The login button in the UI will read "SSO with Infinito.Nexus" (renamed via inje To enable SSO, set `services.sso.enabled: true` (the default) in your inventory and ensure `OIDC.CLIENT.SECRET` is configured. +## MCP Server + +Mattermost exposes a Model Context Protocol server through the prepackaged Agents plugin (`mattermost-ai`), which ships inside the pinned `mattermost/mattermost-team-edition` image. + +| Property | Value | +|----------|-------| +| Endpoint | `/mcp` on the `mattermostmcp` sidecar; the adapter reaches `/plugins/mattermost-ai/mcp-server/mcp` on the `mattermost` service upstream | +| Health path | `/plugins/mattermost-ai/mcp-server/.well-known/oauth-protected-resource` | +| Transport | `streamable_http` (stateless); SSE is not served | +| Auth | `Authorization: Bearer ` | +| Subject | The token owner; tool calls run with that account's Mattermost permissions | +| Exposure | `internal` | + +### Default state + +`mcp.enabled` resolves to `true` only when `web-app-hermes`, `web-app-openclaw` or `web-app-openwebui` is part of the same deployment, and is `false` otherwise. While it is `true` the deploy: + +- sets `MM_SERVICESETTINGS_ENABLEUSERACCESSTOKENS=true`, +- enables the `mattermost-ai` plugin through `mmctl --local`, +- sets `mcp.enablePluginServer` in the plugin's active `agents_confighistory` row and reloads the plugin, +- mints a personal access token for the administrator account and persists it with `sys-token-store` under `users.administrator.tokens['web-app-mattermost']`. + +While it is `false` the route is not registered and the endpoint answers `404`. Unauthenticated requests to the enabled endpoint answer `401` with a `WWW-Authenticate: Bearer resource_metadata=""` header. + +### Authorization subject + +`auth_subject: administrator`: Mattermost bounds a call by the account the token +belongs to. This deployment mints that personal access token for the +administrator account, so calls arrive with that account's rights whoever asked. +Reaching the tool server is gated on the role's `mcp` RBAC group. + +### Tool categories + +The endpoint serves the Agents plugin's native Mattermost tool catalog: + +- channels: list, read, create, update, archive, +- posts: search, read, create, update, delete, +- direct messages: read and send, +- users and teams: look up, add members, update profiles, +- files: list, read, upload. + +The catalog includes mutating entries (`create`, `update`, `archive`, `delete`, +`send`, `upload`). The Agents plugin exposes no filter, scope or permission flag +that removes them, so `mcp.tools.mutating_tools_enabled: false` records +the deployment's intent rather than an enforced state. Every call is bounded by +the permissions of the account the bearer token belongs to, which here is the +administrator. + +### How to disable + +Remove the MCP client roles, or pin `mcp.enabled: false` for this role. The Agents plugin's MCP server is then left switched off and no personal access token is issued. + ## Configuration Key settings in `meta/services.yml` and `meta/server.yml`: @@ -138,13 +205,13 @@ Key settings in `meta/services.yml` and `meta/server.yml`: ## Addons -This role declares no addons (it ships no `meta/addons/` directory). Mattermost **Team Edition** manages plugin install and enablement at runtime; there is no declarative per-plugin install path in this role. Plugins are operator-managed and persisted through the named plugin volumes (`plugins`, `client-plugins`) declared in `meta/volumes.yml`. No addon bridges any in-repo service. +This role declares no addons (it ships no `meta/addons/` directory). Mattermost **Team Edition** manages plugin install and enablement at runtime; there is no declarative per-plugin install path in this role. Plugins are operator-managed. The named volumes `plugins` and `client-plugins` declared in `meta/volumes.yml` are node-local derived copies that every replica extracts for itself from the image's prepackaged bundles; an uploaded bundle persists in the file store, not in them. No addon bridges any in-repo service. ## References -- [Mattermost Docker Install](https://docs.mattermost.com/install/install-docker.html) -- [Mattermost Configuration Settings](https://docs.mattermost.com/configure/configuration-settings.html) -- [GitLab SSO in Mattermost](https://docs.mattermost.com/deployment/sso-gitlab.html) +- [Mattermost Docker Install](https://docs.mattermost.com/deployment-guide/server/deploy-containers.html) +- [Mattermost Configuration Settings](https://docs.mattermost.com/administration-guide/configure/configuration-settings.html) +- [GitLab SSO in Mattermost](https://docs.mattermost.com/administration-guide/onboard/sso-gitlab.html) ## Persona contract opt-outs diff --git a/roles/web-app-mattermost/files/mcp/tools.json b/roles/web-app-mattermost/files/mcp/tools.json new file mode 100644 index 0000000000..12a98f2df1 --- /dev/null +++ b/roles/web-app-mattermost/files/mcp/tools.json @@ -0,0 +1,300 @@ +{ + "get_channel_info": { + "description": "Get channel info.", + "input_schema": { + "additionalProperties": false, + "properties": { + "channel_id": { + "description": "The exact channel ID (fastest, most reliable method),maxLength=26", + "type": "string" + }, + "channel_name": { + "description": "Channel name to search for \u2014 matches against both display name and URL name (case-insensitive, supports partial matches),maxLength=64", + "type": "string" + }, + "team_id": { + "description": "Team ID (optional - if provided, searches within specific team; if omitted, searches across all teams),maxLength=26", + "type": "string" + } + }, + "type": "object" + }, + "mutating": false + }, + "get_channel_members": { + "description": "Get channel members.", + "input_schema": { + "additionalProperties": false, + "properties": { + "channel_id": { + "description": "ID of the channel to get members for,minLength=26,maxLength=26", + "type": "string" + }, + "exclude_bots": { + "description": "Exclude bot accounts from results (default: true)", + "type": [ + "null", + "boolean" + ] + }, + "limit": { + "description": "Number of members to return (default: 50, max: 200),minimum=1,maximum=200", + "type": "integer" + }, + "page": { + "description": "Page number for pagination (default: 0),minimum=0", + "type": "integer" + } + }, + "required": [ + "channel_id" + ], + "type": "object" + }, + "mutating": false + }, + "get_team_info": { + "description": "Get team info.", + "input_schema": { + "additionalProperties": false, + "properties": { + "team_id": { + "description": "The exact team ID (fastest, most reliable method),maxLength=26", + "type": "string" + }, + "team_name": { + "description": "Team name to search for \u2014 matches against both display name and URL name (case-insensitive, supports partial matches)", + "type": "string" + } + }, + "type": "object" + }, + "mutating": false + }, + "get_team_members": { + "description": "Get team members.", + "input_schema": { + "additionalProperties": false, + "properties": { + "exclude_bots": { + "description": "Exclude bot accounts from results (default: true)", + "type": [ + "null", + "boolean" + ] + }, + "limit": { + "description": "Number of members to return (default: 50, max: 200),minimum=1,maximum=200", + "type": "integer" + }, + "page": { + "description": "Page number for pagination (default: 0),minimum=0", + "type": "integer" + }, + "team_id": { + "description": "ID of the team to get members for,minLength=26,maxLength=26", + "type": "string" + } + }, + "required": [ + "team_id" + ], + "type": "object" + }, + "mutating": false + }, + "get_user_channels": { + "description": "Get user channels.", + "input_schema": { + "additionalProperties": false, + "properties": { + "page": { + "description": "Page number for pagination (default: 0),minimum=0", + "type": "integer" + }, + "per_page": { + "description": "Number of channels per page (default: 60, max: 200),minimum=1,maximum=200", + "type": "integer" + }, + "team_id": { + "description": "Optional team ID to filter channels by team,maxLength=26", + "type": "string" + } + }, + "type": "object" + }, + "mutating": false + }, + "list_agents": { + "description": "List agents.", + "input_schema": { + "additionalProperties": false, + "type": "object" + }, + "mutating": false + }, + "read_channel": { + "description": "Read channel.", + "input_schema": { + "additionalProperties": false, + "properties": { + "after": { + "description": "Return the page of posts immediately after this post ID (history pagination). Mutually exclusive with before/since.,maxLength=26", + "type": "string" + }, + "before": { + "description": "Return the page of posts immediately before this post ID (history pagination). Mutually exclusive with after/since.,maxLength=26", + "type": "string" + }, + "channel_id": { + "description": "The ID of the channel to read from,minLength=26,maxLength=26", + "type": "string" + }, + "limit": { + "description": "Number of posts to retrieve (default: 20, max: 100),minimum=1,maximum=100", + "type": "integer" + }, + "page": { + "description": "Page number for pagination (default: 0),minimum=0", + "type": "integer" + }, + "since": { + "description": "Only get posts since this timestamp (ISO 8601 format),format=date-time", + "type": "string" + } + }, + "required": [ + "channel_id" + ], + "type": "object" + }, + "mutating": false + }, + "read_file": { + "description": "Read file.", + "input_schema": { + "additionalProperties": false, + "properties": { + "file_id": { + "description": "The ID of the file to read; use the File ID shown in the attached-file metadata,minLength=26,maxLength=26", + "type": "string" + }, + "limit": { + "description": "Maximum number of characters to return (default 6000, capped at 20000).", + "type": "integer" + }, + "offset": { + "description": "Character offset to start reading from (default 0). Pass the next offset reported by a previous call to page through a large file.", + "type": "integer" + } + }, + "required": [ + "file_id" + ], + "type": "object" + }, + "mutating": false + }, + "read_post": { + "description": "Read post.", + "input_schema": { + "additionalProperties": false, + "properties": { + "include_thread": { + "description": "Whether to include the entire thread (default: true). Set false to fetch only the single post.", + "type": [ + "null", + "boolean" + ] + }, + "post_id": { + "description": "The ID of the post to read,minLength=26,maxLength=26", + "type": "string" + } + }, + "required": [ + "post_id" + ], + "type": "object" + }, + "mutating": false + }, + "search_posts": { + "description": "Search posts.", + "input_schema": { + "additionalProperties": false, + "properties": { + "after": { + "description": "Optional date YYYY-MM-DD \u2014 only posts after this date (keyword search only)", + "type": "string" + }, + "before": { + "description": "Optional date YYYY-MM-DD \u2014 only posts before this date (keyword search only)", + "type": "string" + }, + "channel_id": { + "description": "Optional channel ID to limit search to a specific channel,minLength=26,maxLength=26", + "type": "string" + }, + "from": { + "description": "Optional username \u2014 only posts from this user (keyword search only),maxLength=64", + "type": "string" + }, + "in": { + "description": "Optional channel name or ID \u2014 only posts in this channel (keyword search only),maxLength=64", + "type": "string" + }, + "keyword_limit": { + "description": "Max results from keyword search (default 10; max 100),minimum=1,maximum=100", + "type": "integer" + }, + "keyword_offset": { + "description": "Offset for keyword search pagination,minimum=0", + "type": "integer" + }, + "query": { + "description": "The search query,minLength=1,maxLength=4000", + "type": "string" + }, + "semantic_limit": { + "description": "Max results from semantic search (default 10; max 50),minimum=1,maximum=50", + "type": "integer" + }, + "semantic_offset": { + "description": "Offset for semantic search pagination,minimum=0", + "type": "integer" + }, + "team_id": { + "description": "Optional team ID to limit search scope,minLength=26,maxLength=26", + "type": "string" + } + }, + "required": [ + "query" + ], + "type": "object" + }, + "mutating": false + }, + "search_users": { + "description": "Search users.", + "input_schema": { + "additionalProperties": false, + "properties": { + "limit": { + "description": "Maximum number of results to return (default: 20, max: 100),minimum=1,maximum=100", + "type": "integer" + }, + "term": { + "description": "Search term (username, email, first name, or last name),minLength=1,maxLength=64", + "type": "string" + } + }, + "required": [ + "term" + ], + "type": "object" + }, + "mutating": false + } +} diff --git a/roles/web-app-mattermost/files/playwright/_shared.js b/roles/web-app-mattermost/files/playwright/_shared.js index 871b0a0f21..6d787f0ca4 100644 --- a/roles/web-app-mattermost/files/playwright/_shared.js +++ b/roles/web-app-mattermost/files/playwright/_shared.js @@ -100,7 +100,21 @@ async function waitForMattermostChannelView(frame, timeout = resolveTimeout(60_0 // `waitUntil: "commit"` avoids net::ERR_ABORTED from the multi-domain // redirect chain the universal-logout service triggers. async function mattermostLogout(page, baseUrl) { - await gotoOnion(page, `${baseUrl.replace(/\/$/, "")}/logout`, { waitUntil: "commit" }).catch(() => {}); + const root = baseUrl.replace(/\/$/, ""); + const session = await page.context().cookies(root).catch(() => []); + const csrf = session.find((cookie) => cookie.name === "MMCSRF"); + await page.request + .post(`${root}/api/v4/users/logout`, { + headers: csrf ? { "X-CSRF-Token": csrf.value } : {}, + failOnStatusCode: false, + }) + .catch(() => {}); + await gotoOnion(page, `${root}/logout`, { waitUntil: "commit" }).catch(() => {}); + for (let attempt = 0; attempt < 40; attempt += 1) { + const cookies = await page.context().cookies(root).catch(() => []); + if (!cookies.some((cookie) => cookie.name === "MMAUTHTOKEN" && cookie.value)) return; + await page.waitForTimeout(resolveTimeout(500)); + } } function beforeEach() { diff --git a/roles/web-app-mattermost/files/playwright/playwright.spec.js b/roles/web-app-mattermost/files/playwright/playwright.spec.js index 1b430444d8..a73e657651 100644 --- a/roles/web-app-mattermost/files/playwright/playwright.spec.js +++ b/roles/web-app-mattermost/files/playwright/playwright.spec.js @@ -9,6 +9,8 @@ test.beforeEach(shared.beforeEach); require("./test-sso-login").register(shared); require("./test-biber-dm-administrator").register(shared); require("./test-guest-persona").register(shared); +require("./test-mcp-guest").register(shared); +require("./test-litellm-agent").register(shared); require("./test-biber-persona").register(shared); require("./test-administrator-persona").register(shared); require("./test-seaweedfs"); diff --git a/roles/web-app-mattermost/files/playwright/test-biber-dm-administrator.js b/roles/web-app-mattermost/files/playwright/test-biber-dm-administrator.js index 179cdab09b..0e6ca28c76 100644 --- a/roles/web-app-mattermost/files/playwright/test-biber-dm-administrator.js +++ b/roles/web-app-mattermost/files/playwright/test-biber-dm-administrator.js @@ -36,10 +36,10 @@ exports.register = function (shared) { await shared.dismissMattermostPopups(biberPage); - // /{team}/messages/@{username} auto-joins the open team and opens the DM - // in one step, dodging /select_team on first login. await biberPage.goto(`${baseUrl}/main/messages/@${shared.env.adminUsername}`); + await shared.dismissMattermostPopups(biberPage); + await biberPage.reload(); await shared.dismissMattermostPopups(biberPage); const messageInput = biberPage diff --git a/roles/web-app-mattermost/files/playwright/test-litellm-agent.js b/roles/web-app-mattermost/files/playwright/test-litellm-agent.js new file mode 100644 index 0000000000..17a24373b6 --- /dev/null +++ b/roles/web-app-mattermost/files/playwright/test-litellm-agent.js @@ -0,0 +1,171 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); + +const { + apiFetchOnion, + apiGetOnion, + decodeDotenvQuotedValue, + performKeycloakLoginForm, +} = require("./personas"); +const { skipUnlessServiceEnabled } = require("./service-gating"); + +const LITELLM_API_URL = decodeDotenvQuotedValue(process.env.LITELLM_API_URL); +const LITELLM_BOT_NAME = decodeDotenvQuotedValue(process.env.LITELLM_BOT_NAME); + +const PLUGIN_FAILURE_NOTICE = /sorry!?\s*an error|an error occurred|accessing the llm/i; + +// The role rewrites the administrator to gitlab auth only when SSO is on, so the +// password grant exists exactly in the deployments that run without OIDC. +async function acquireAdminToken(context, shared, baseUrl) { + if (!shared.oidcEnabled) { + const login = await apiFetchOnion(context.request, `${baseUrl}/api/v4/users/login`, { + method: "POST", + failOnStatusCode: false, + headers: { "Content-Type": "application/json" }, + data: { login_id: shared.env.adminUsername, password: shared.env.adminPassword }, + }); + expect( + login.status(), + `the administrator must be able to open a Mattermost session; without one the Agents bot cannot be prompted at all (HTTP ${login.status()})`, + ).toBe(200); + + const token = login.headers().token; + expect( + token, + "Mattermost must return the session token in the Token response header of /api/v4/users/login", + ).toBeTruthy(); + return token; + } + + const page = await context.newPage(); + await shared.startMattermostSsoFlow(page, baseUrl); + await performKeycloakLoginForm(page, shared.env.adminUsername, shared.env.adminPassword); + await expect + .poll(() => page.url(), { + timeout: resolveTimeout(60_000), + message: "Expected redirect back to Mattermost after the administrator OIDC login", + }) + .toContain(baseUrl); + + const session = (await context.cookies(baseUrl)).find((cookie) => cookie.name === "MMAUTHTOKEN"); + expect( + session && session.value, + "the OIDC login must leave an MMAUTHTOKEN session cookie; without it no Agents prompt can be authenticated", + ).toBeTruthy(); + await page.close().catch(() => {}); + return session.value; +} + +async function firstBotReply(context, baseUrl, headers, channelId, botId, afterPostId) { + const response = await context.request.get( + `${baseUrl}/api/v4/channels/${channelId}/posts?after=${afterPostId}&per_page=50`, + { headers, failOnStatusCode: false }, + ); + if (!response.ok()) return ""; + + const body = await response.json(); + const replies = Object.values((body && body.posts) || {}) + .filter((post) => post.user_id === botId && String(post.message || "").trim().length > 0) + .sort((a, b) => a.create_at - b.create_at); + return replies.length > 0 ? String(replies[0].message).trim() : ""; +} + +exports.register = function (shared) { + test("litellm: the Agents bot answers a prompt through the in-cluster gateway", async ({ browser }) => { + skipUnlessServiceEnabled("litellm"); + test.setTimeout(resolveTimeout(300_000)); + + expect( + LITELLM_API_URL, + "LITELLM_API_URL must render MATTERMOST_LITELLM_BASE_URL into the Playwright env; without it the endpoint the Agents plugin was pointed at cannot be checked", + ).toMatch(/^https?:\/\/.+/i); + + const gatewayHost = new URL(LITELLM_API_URL).hostname; + expect( + gatewayHost, + `the Agents service endpoint must address the gateway by its bare in-cluster service name; "${gatewayHost}" carries a dot, so the container dns-search suffix completes it and the prompt leaves the deployment through the public ingress`, + ).not.toContain("."); + + const baseUrl = shared.expectedMattermostBaseUrl(); + const context = await browser.newContext({ ignoreHTTPSErrors: true }); + + try { + const token = await acquireAdminToken(context, shared, baseUrl); + await context.clearCookies(); + const headers = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }; + + const meResponse = await apiGetOnion(context.request, `${baseUrl}/api/v4/users/me`, { + headers, + failOnStatusCode: false, + }); + expect( + meResponse.status(), + `the session token must authenticate against the Mattermost API (HTTP ${meResponse.status()})`, + ).toBe(200); + const me = await meResponse.json(); + + const botResponse = await apiGetOnion( + context.request, + `${baseUrl}/api/v4/users/username/${LITELLM_BOT_NAME}`, + { headers, failOnStatusCode: false }, + ); + expect( + botResponse.status(), + `the Agents plugin must have provisioned the bot user "${LITELLM_BOT_NAME}"; its absence means the bot row the deploy merged into agents_confighistory was never picked up (HTTP ${botResponse.status()})`, + ).toBe(200); + const bot = await botResponse.json(); + expect( + bot.id, + `the "${LITELLM_BOT_NAME}" account must carry a user id so a direct message channel can be opened with it`, + ).toBeTruthy(); + + const dmResponse = await apiFetchOnion(context.request, `${baseUrl}/api/v4/channels/direct`, { + method: "POST", + headers, + failOnStatusCode: false, + data: [me.id, bot.id], + }); + expect( + dmResponse.ok(), + `a direct message channel between the administrator and the Agents bot must open; the plugin answers prompts only inside a channel it participates in (HTTP ${dmResponse.status()})`, + ).toBeTruthy(); + const dm = await dmResponse.json(); + + const prompt = `Reply with exactly the word: pong (${Date.now()})`; + const promptResponse = await context.request.post(`${baseUrl}/api/v4/posts`, { + headers, + failOnStatusCode: false, + data: { channel_id: dm.id, message: prompt }, + }); + expect( + promptResponse.ok(), + `the prompt must be posted into the Agents direct message channel (HTTP ${promptResponse.status()})`, + ).toBeTruthy(); + const prompted = await promptResponse.json(); + + let reply = ""; + await expect + .poll( + async () => { + reply = await firstBotReply(context, baseUrl, headers, dm.id, bot.id, prompted.id).catch( + () => "", + ); + return reply.length; + }, + { + timeout: resolveTimeout(180_000), + intervals: [2_000], + message: `the Agents bot "${LITELLM_BOT_NAME}" must answer the direct message with a real completion; silence means the plugin never reached ${LITELLM_API_URL}, the gateway rejected the virtual key, or no model is served behind it`, + }, + ) + .toBeGreaterThan(0); + + expect( + reply, + `the Agents bot returned the plugin's LLM failure notice instead of a completion, so the prompt never got an answer out of ${LITELLM_API_URL}: ${JSON.stringify(reply).slice(0, 300)}`, + ).not.toMatch(PLUGIN_FAILURE_NOTICE); + } finally { + await context.close().catch(() => {}); + } + }); +}; diff --git a/roles/web-app-mattermost/files/playwright/test-mcp-guest.js b/roles/web-app-mattermost/files/playwright/test-mcp-guest.js new file mode 100644 index 0000000000..3807aab58e --- /dev/null +++ b/roles/web-app-mattermost/files/playwright/test-mcp-guest.js @@ -0,0 +1,41 @@ +const { test, expect } = require("@playwright/test"); + +const { decodeDotenvQuotedValue } = require("./personas"); +const { skipUnlessServiceEnabled } = require("./service-gating"); +const { registerMcpDisabledState } = require("./mcp-endpoint"); + +const MCP_ENDPOINT_PATH = decodeDotenvQuotedValue(process.env.MCP_ENDPOINT_PATH); + +exports.register = function (shared) { + test("guest: the MCP endpoint rejects unauthenticated access", async ({ page }) => { + skipUnlessServiceEnabled("mcp"); + + const baseUrl = shared.expectedMattermostBaseUrl(); + const response = await page.request.post(`${baseUrl}${MCP_ENDPOINT_PATH}`, { + failOnStatusCode: false, + headers: { + "Content-Type": "application/json", + Accept: "application/json, text/event-stream", + }, + data: { + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "infinito-guest-probe", version: "0" }, + }, + }, + }); + + expect( + response.status(), + "an unauthenticated MCP initialize must not be served a 2xx; the endpoint is bearer-guarded", + ).toBeGreaterThanOrEqual(400); + }); + + registerMcpDisabledState(() => + new URL(MCP_ENDPOINT_PATH, shared.expectedMattermostBaseUrl()).toString(), + ); +}; diff --git a/roles/web-app-mattermost/files/sql/select/ai/bot-user.sql b/roles/web-app-mattermost/files/sql/select/ai/bot-user.sql new file mode 100644 index 0000000000..03bb60b85e --- /dev/null +++ b/roles/web-app-mattermost/files/sql/select/ai/bot-user.sql @@ -0,0 +1,4 @@ +SELECT count(*) + FROM bots b + JOIN users u ON u.id = b.userid + WHERE u.username = %(bot_name)s; diff --git a/roles/web-app-mattermost/files/sql/select/ai/service.sql b/roles/web-app-mattermost/files/sql/select/ai/service.sql new file mode 100644 index 0000000000..ff3a360d14 --- /dev/null +++ b/roles/web-app-mattermost/files/sql/select/ai/service.sql @@ -0,0 +1,32 @@ +SELECT CASE + WHEN EXISTS (SELECT 1 + FROM jsonb_array_elements( + CASE WHEN jsonb_typeof(a.config::jsonb -> 'services') = 'array' + THEN a.config::jsonb -> 'services' + ELSE '[]'::jsonb END + ) AS s + WHERE s ->> 'id' = d.service ->> 'id' + AND s @> d.service) + AND EXISTS (SELECT 1 + FROM agents_useragents u + WHERE u.username = d.bot ->> 'name' + AND u.serviceid = d.bot ->> 'serviceID' + AND u.model = d.bot ->> 'model' + AND u.deleteat = 0 + AND u.botuserid <> '') + AND NOT EXISTS (SELECT 1 + FROM jsonb_array_elements( + CASE WHEN jsonb_typeof(a.config::jsonb -> 'bots') = 'array' + THEN a.config::jsonb -> 'bots' + ELSE '[]'::jsonb END + ) AS legacy + JOIN agents_useragents u2 + ON u2.username = legacy ->> 'name' + AND u2.deleteat = 0) + THEN 'converged' + ELSE 'stale' + END + FROM agents_confighistory a, + (SELECT %(service)s::jsonb AS service, + %(bot)s::jsonb AS bot) AS d + WHERE a.active = true; diff --git a/roles/web-app-mattermost/files/sql/select/mcp-plugin-server.sql b/roles/web-app-mattermost/files/sql/select/mcp-plugin-server.sql new file mode 100644 index 0000000000..c34f912d6c --- /dev/null +++ b/roles/web-app-mattermost/files/sql/select/mcp-plugin-server.sql @@ -0,0 +1,3 @@ +SELECT coalesce(config::jsonb #>> '{mcp,enablePluginServer}', 'false') + FROM agents_confighistory + WHERE active = true; diff --git a/roles/web-app-mattermost/files/sql/select/user/access-token.sql b/roles/web-app-mattermost/files/sql/select/user/access-token.sql new file mode 100644 index 0000000000..22506ed5b3 --- /dev/null +++ b/roles/web-app-mattermost/files/sql/select/user/access-token.sql @@ -0,0 +1 @@ +SELECT count(*) FROM useraccesstokens WHERE token = %(token)s AND isactive = true; diff --git a/roles/web-app-mattermost/files/sql/select-user-authservice.sql b/roles/web-app-mattermost/files/sql/select/user/authservice.sql similarity index 100% rename from roles/web-app-mattermost/files/sql/select-user-authservice.sql rename to roles/web-app-mattermost/files/sql/select/user/authservice.sql diff --git a/roles/web-app-mattermost/files/sql/update/ai/agent.sql b/roles/web-app-mattermost/files/sql/update/ai/agent.sql new file mode 100644 index 0000000000..cbf3f13d20 --- /dev/null +++ b/roles/web-app-mattermost/files/sql/update/ai/agent.sql @@ -0,0 +1,9 @@ +UPDATE agents_useragents u + SET serviceid = d.bot ->> 'serviceID', + model = d.bot ->> 'model', + updateat = (extract(epoch from now()) * 1000)::bigint + FROM (SELECT %(bot)s::jsonb AS bot) AS d + WHERE u.username = d.bot ->> 'name' + AND u.deleteat = 0 + AND (u.serviceid IS DISTINCT FROM d.bot ->> 'serviceID' + OR u.model IS DISTINCT FROM d.bot ->> 'model'); diff --git a/roles/web-app-mattermost/files/sql/update/ai/service.sql b/roles/web-app-mattermost/files/sql/update/ai/service.sql new file mode 100644 index 0000000000..48c1d3f9de --- /dev/null +++ b/roles/web-app-mattermost/files/sql/update/ai/service.sql @@ -0,0 +1,37 @@ +UPDATE agents_confighistory a + SET config = ( + a.config::jsonb + || jsonb_build_object( + 'services', + coalesce(( + SELECT jsonb_agg(s) + FROM jsonb_array_elements( + CASE WHEN jsonb_typeof(a.config::jsonb -> 'services') = 'array' + THEN a.config::jsonb -> 'services' + ELSE '[]'::jsonb END + ) AS s + WHERE s ->> 'id' <> d.service ->> 'id' + ), '[]'::jsonb) || jsonb_build_array(d.service) + ) + || jsonb_build_object( + 'bots', + coalesce(( + SELECT jsonb_agg(b) + FROM jsonb_array_elements( + CASE WHEN jsonb_typeof(a.config::jsonb -> 'bots') = 'array' + THEN a.config::jsonb -> 'bots' + ELSE '[]'::jsonb END + ) AS b + WHERE b ->> 'id' <> d.bot ->> 'id' + ), '[]'::jsonb) || CASE WHEN EXISTS (SELECT 1 + FROM agents_useragents u + WHERE u.username = d.bot ->> 'name' + AND u.deleteat = 0) + THEN '[]'::jsonb + ELSE jsonb_build_array(d.bot) END + ) + || jsonb_build_object('defaultBotName', d.bot ->> 'name') + )::text + FROM (SELECT %(service)s::jsonb AS service, + %(bot)s::jsonb AS bot) AS d + WHERE a.active = true; diff --git a/roles/web-app-mattermost/files/sql/update/enable-mcp-plugin-server.sql b/roles/web-app-mattermost/files/sql/update/enable-mcp-plugin-server.sql new file mode 100644 index 0000000000..520cb1dbf1 --- /dev/null +++ b/roles/web-app-mattermost/files/sql/update/enable-mcp-plugin-server.sql @@ -0,0 +1,8 @@ +UPDATE agents_confighistory + SET config = jsonb_set( + config::jsonb, + '{mcp}', + coalesce(config::jsonb -> 'mcp', '{}'::jsonb) || '{"enablePluginServer": true}'::jsonb, + true + )::text + WHERE active = true; diff --git a/roles/web-app-mattermost/files/test/.nocheck b/roles/web-app-mattermost/files/test/.nocheck new file mode 100644 index 0000000000..2b9d82d840 --- /dev/null +++ b/roles/web-app-mattermost/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; test-e2e-cli stages files/test/ by that fixed path. diff --git a/roles/web-app-mattermost/files/test/test.sh b/roles/web-app-mattermost/files/test/test.sh new file mode 100644 index 0000000000..7bd951b445 --- /dev/null +++ b/roles/web-app-mattermost/files/test/test.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# CLI test for web-app-mattermost: the MCP endpoint honours its declared contract. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +bash "${here}/shared/mcp/run.sh" diff --git a/roles/web-app-mattermost/meta/mcp.yml b/roles/web-app-mattermost/meta/mcp.yml new file mode 100644 index 0000000000..e13969fcc7 --- /dev/null +++ b/roles/web-app-mattermost/meta/mcp.yml @@ -0,0 +1,186 @@ +--- +classification: adapter_server +direction: server +source_url: https://github.com/mattermost/mattermost-plugin-agents/blob/master/mcpserver/README.md +transport: streamable_http +exposure: internal +auth: bearer_token +auth_subject: service_account +implementation: adapter +credential: + owner: mcp-web-app-mattermost + source: credentials + key: mcp_bearer +adapter: + type: mcp_passthrough + specification_path: roles/web-app-mattermost/files/mcp/tools.json + specification_sha256: sha256:b06c02b100fa8d959d3e4d9fca42682df943967f6bf2de2c66f7031d5a6b823f + upstream_path: /plugins/mattermost-ai/mcp-server/mcp +endpoint: + service_key: mattermostmcp + path: /mcp + port_key: http +limits: + request_bytes: 65536 + response_bytes: 1048576 + timeout_seconds: 15 + concurrent_requests: 4 + page_size: 100 + result_items: 100 + stream_seconds: 300 +tools: + read_probe: + tool: get_user_channels + arguments: {} + schema_sha256: sha256:24872026324af9402aca15cad57d058a408582fbea677af02ce474fd5d7edb28 + allowlist: + - get_channel_info + - get_channel_members + - get_team_info + - get_team_members + - get_user_channels + - list_agents + - read_channel + - read_file + - read_post + - search_posts + - search_users + writer_allowlist: + - add_channel_member + - create_channel + - create_post + - dm + - get_channel_info + - get_channel_members + - get_team_info + - get_team_members + - get_user_channels + - group_message + - list_agents + - read_channel + - read_file + - read_post + - search_posts + - search_users + upstream_serves: + - acknowledge_post + - add_channel_member + - add_channel_members + - add_reaction + - add_team_member + - add_team_members + - archive_channel + - convert_channel_privacy + - create_channel + - create_channel_bookmark + - create_post + - create_scheduled_post + - delete_channel_bookmark + - delete_post + - delete_scheduled_post + - dm + - get_bot + - get_bulk_reactions + - get_channel_groups + - get_channel_info + - get_channel_member + - get_channel_member_counts + - get_channel_members + - get_channel_members_by_ids + - get_channel_members_by_status + - get_channel_moderations + - get_channel_stats + - get_channel_unread + - get_dm_common_teams + - get_file_info + - get_file_link + - get_group_info + - get_me + - get_mentions + - get_new_users_in_team + - get_post_files + - get_post_info + - get_post_reactions + - get_posts_around_unread + - get_role + - get_team_groups + - get_team_info + - get_team_member + - get_team_members + - get_team_stats + - get_threads + - get_unread_counts + - get_user + - get_user_by_email + - get_user_by_username + - get_user_channel_memberships + - get_user_channels + - get_user_cpa_values + - get_user_custom_status + - get_user_groups + - get_user_stats + - get_user_status + - get_user_teams + - get_users_by_ids + - get_users_by_usernames + - get_users_in_group_channels + - get_users_in_team + - get_users_not_in_channel + - get_users_not_in_team + - get_users_statuses + - group_message + - invite_users_to_team + - invite_users_to_team_and_channels + - list_agents + - list_archived_channels + - list_bots + - list_channel_bookmarks + - list_cpa_fields + - list_custom_emoji + - list_groups + - list_incoming_webhooks + - list_outgoing_webhooks + - list_pinned_posts + - list_saved_posts + - list_scheduled_posts + - list_sidebar_categories + - list_team_channels + - mark_channel_read + - mark_channels_viewed + - mark_post_unread + - pin_post + - read_channel + - read_file + - read_post + - remove_channel_member + - remove_reaction + - remove_team_member + - restore_channel + - save_post + - search_channels + - search_custom_emoji + - search_files + - search_posts + - search_teams + - search_users + - search_users_in_channel + - search_users_in_team + - set_channel_favorite + - set_channel_mute + - set_dnd + - set_post_reminder + - set_status + - set_thread_follow + - unpin_post + - update_channel + - update_channel_bookmark + - update_channel_member_roles + - update_channel_notify_props + - update_post + - update_scheduled_post + - update_team + - update_team_member_roles + - update_user + - upload_file + read_only_default: true + mutating_tools_enabled: false diff --git a/roles/web-app-mattermost/meta/networks.yml b/roles/web-app-mattermost/meta/networks.yml index f7613c8c09..2cad14c791 100644 --- a/roles/web-app-mattermost/meta/networks.yml +++ b/roles/web-app-mattermost/meta/networks.yml @@ -1,3 +1,8 @@ --- local: subnet: 192.168.33.0/24 +overlay: + modes: [compose, swarm] + topology: shared_net + consumer: + kind: mcp_client diff --git a/roles/web-app-mattermost/meta/rbac.yml b/roles/web-app-mattermost/meta/rbac.yml new file mode 100644 index 0000000000..084e6fbeca --- /dev/null +++ b/roles/web-app-mattermost/meta/rbac.yml @@ -0,0 +1,4 @@ +--- +roles: + mcp: + description: Can drive this application through an MCP client, which acts with the credentials the deployment issued rather than the caller's own diff --git a/roles/web-app-mattermost/meta/secrets.yml b/roles/web-app-mattermost/meta/secrets.yml new file mode 100644 index 0000000000..e6dff9cab1 --- /dev/null +++ b/roles/web-app-mattermost/meta/secrets.yml @@ -0,0 +1,13 @@ +--- +credentials: + litellm_api_key: + description: Per-consumer virtual key for the shared svc-ai-litellm gateway + algorithm: sk_prefixed + validation: + min_length: 50 + mcp_bearer: + description: "Bearer an MCP client must present to this role's adapter instance. Distinct from the credential the adapter presents upstream: holding a token the + application accepts says nothing about who called the adapter." + algorithm: alphanumeric + validation: "^[A-Za-z0-9]{32,}$" + length: 48 diff --git a/roles/web-app-mattermost/meta/services.yml b/roles/web-app-mattermost/meta/services.yml index 7e9bc40f2f..28de9174c8 100644 --- a/roles/web-app-mattermost/meta/services.yml +++ b/roles/web-app-mattermost/meta/services.yml @@ -30,6 +30,12 @@ postgres: shared: "{{ 'svc-db-postgres' in group_names }}" # nocheck: playwright-service-flag: shared provider entity; the app itself is covered by this role's own Playwright spec mattermost: + healthcheck: + test: ["CMD", "/mattermost/bin/mmctl", "--local", "system", "status"] + # nocheck: healthcheck-timing-override mmctl spawns a binary and talks to the local socket, so it does not belong on a 30s steady-state loop + interval: 1m + # nocheck: healthcheck-timing-override spawning that binary does not finish inside the 5s default + timeout: 10s modes: compose: enabled: true @@ -108,3 +114,50 @@ container_backup: # nocheck: bond-baseline backup host joins outside the variant bond: 1 enabled: "{{ 'svc-bkp-volume-2-local' in group_names }}" shared: true +# nocheck: dynamic-flag - the gateway is a single shared instance, never deployed per consumer +litellm: + bond: 0.5 + enabled: "{{ LITELLM_USABLE }}" + shared: true +# nocheck: playwright-service-flag internal adapter sidecar, covered by the role's MCP spec +# nocheck: dockerfile-custom the Dockerfile is owned by svc-ai-mcp-adapter and staged per instance, so every adapter-backed provider shares one audited build +# nocheck: dynamic-flag the sidecar tracks this role's own mcp flag, not another role's presence; a group_names expression would decide its exposure from an unrelated deployment +mattermostmcp: + enabled: "{{ lookup('config', 'web-app-mattermost', 'mcp.enabled') | bool }}" + shared: false + image: python + # nocheck: docker-version base of the self-built stdlib adapter, not the served application + version: "3.13.15-slim" + custom: true + name: mattermostmcp + cpus: "0.25" + mem_reservation: 16m + mem_limit: 24m + pids_limit: 64 + healthcheck: + flavor: http_status + path: health + ports: + internal: + http: 8080 +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openwebui: + bond: 0.5 + enabled: "{{ 'web-app-openwebui' in group_names }}" + shared: "{{ 'web-app-openwebui' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +hermes: + bond: 0.5 + enabled: "{{ 'web-app-hermes' in group_names }}" + shared: "{{ 'web-app-hermes' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openclaw: + bond: 0.5 + enabled: "{{ 'web-app-openclaw' in group_names }}" + shared: "{{ 'web-app-openclaw' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +# nocheck: dynamic-flag the entry refuses this client, so the link is off on every host and no group_names gate can decide it +flowise: + enabled: false + shared: false + mcp_consumer: false diff --git a/roles/web-app-mattermost/meta/tests.yml b/roles/web-app-mattermost/meta/tests.yml new file mode 100644 index 0000000000..28bea0efe2 --- /dev/null +++ b/roles/web-app-mattermost/meta/tests.yml @@ -0,0 +1,3 @@ +--- +cli: + timeout: 900 diff --git a/roles/web-app-mattermost/meta/users.yml b/roles/web-app-mattermost/meta/users.yml new file mode 100644 index 0000000000..48f4a7254d --- /dev/null +++ b/roles/web-app-mattermost/meta/users.yml @@ -0,0 +1,4 @@ +--- +administrator: + tokens: + web-app-mattermost: "" diff --git a/roles/web-app-mattermost/meta/variants.yml b/roles/web-app-mattermost/meta/variants.yml index 9c2cc39809..6f53b2a005 100644 --- a/roles/web-app-mattermost/meta/variants.yml +++ b/roles/web-app-mattermost/meta/variants.yml @@ -35,8 +35,65 @@ css: enabled: true shared: true + litellm: + enabled: false tor: enabled: true + openwebui: + enabled: false + shared: false + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false +- services: + container_backup: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + dashboard: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + email: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + logout: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + matomo: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + sso: + enabled: true + shared: true + postgres: + shared: true + redis: + shared: true + prometheus: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + seaweedfs: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + css: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + litellm: + enabled: false + tor: + enabled: true + openwebui: + enabled: true + shared: true + hermes: + enabled: true + shared: true + openclaw: + enabled: true + shared: true + - services: container_backup: enabled: false @@ -69,5 +126,16 @@ css: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true + litellm: + enabled: true tor: enabled: true + openwebui: + enabled: false + shared: false + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false diff --git a/roles/web-app-mattermost/meta/volumes.yml b/roles/web-app-mattermost/meta/volumes.yml index 7f7960dc0b..d7d9173830 100644 --- a/roles/web-app-mattermost/meta/volumes.yml +++ b/roles/web-app-mattermost/meta/volumes.yml @@ -23,6 +23,8 @@ logs: plugins: type: volume name: mattermost_plugins + # nocheck: nfs-false-data-loss Reason: extracted per node from the image's prepackaged bundles, the file store holds none; shared over NFS a redeploy unlinks the tree while the outgoing task still holds the plugin binary open, silly-rename leaves it non-empty, and the reinstall then fails destination-already-exists and the node serves 404 + nfs: false mounts: - service: mattermost target: /mattermost/plugins @@ -30,6 +32,8 @@ plugins: client-plugins: type: volume name: mattermost_client_plugins + # nocheck: nfs-false-data-loss Reason: unpacked from the server-side plugin bundle at every activation; shared, replicas starting at once copy into one directory and the loser then serves 404 on the plugin routes + nfs: false mounts: - service: mattermost target: /mattermost/client/plugins diff --git a/roles/web-app-mattermost/tasks/00_core.yml b/roles/web-app-mattermost/tasks/00_core.yml index 8378add86a..75d50002c7 100644 --- a/roles/web-app-mattermost/tasks/00_core.yml +++ b/roles/web-app-mattermost/tasks/00_core.yml @@ -1,6 +1,13 @@ --- - include_tasks: utils/once/flag.yml +- name: "๐Ÿ”Œ Stage the MCP adapter instance for {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/instance.yml') }}" + vars: + mcp_adapter_instance_dir: "{{ MATTERMOST_MCP_INSTANCE_DIR }}" + mcp_adapter_upstream_key: true + when: MATTERMOST_MCP_ENABLED | bool + - name: "๐Ÿ—‘๏ธ Remove stale nginx config for renamed domain chat.{{ DOMAIN_PRIMARY }}" # nocheck: domain-spot ansible.builtin.file: path: "{{ [lookup('nginx', 'directories.configuration.servers'), 'https', 'chat.' ~ DOMAIN_PRIMARY ~ '.conf'] | path_join }}" @@ -22,3 +29,11 @@ - name: "๐Ÿ”ง Configure Keycloak OIDC mappers for Mattermost" include_tasks: 02_keycloak.yml when: MATTERMOST_OIDC_ENABLED | bool + +- name: "๐Ÿค– Bind the native AI surface to the platform gateway" + include_tasks: utils/ai_gateway.yml + when: MATTERMOST_LITELLM_ENABLED | bool + +- name: "๐Ÿ”Œ Provision the MCP server surface" + include_tasks: utils/mcp.yml + when: MATTERMOST_MCP_ENABLED | bool diff --git a/roles/web-app-mattermost/tasks/01_setup.yml b/roles/web-app-mattermost/tasks/01_setup.yml index 4bea426836..09af300d38 100644 --- a/roles/web-app-mattermost/tasks/01_setup.yml +++ b/roles/web-app-mattermost/tasks/01_setup.yml @@ -21,6 +21,7 @@ delegate_to: "{{ MATTERMOST_HOST_NODE }}" - name: "๐Ÿ“ Mattermost | Create system administrator user" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" ansible.builtin.shell: | # nocheck: container-exec-resolver MATTERMOST_LOCAL_CID resolved at delegate_to runtime; container_address would return a manager-only subshell container exec -i {{ MATTERMOST_LOCAL_CID | quote }} \ /mattermost/bin/mmctl --local user create \ diff --git a/roles/web-app-mattermost/tasks/02_keycloak.yml b/roles/web-app-mattermost/tasks/02_keycloak.yml index 1bcccc885f..46e9f5c8d7 100644 --- a/roles/web-app-mattermost/tasks/02_keycloak.yml +++ b/roles/web-app-mattermost/tasks/02_keycloak.yml @@ -1,5 +1,5 @@ --- -# @see https://docs.mattermost.com/deployment/sso-gitlab.html +# @see https://docs.mattermost.com/administration-guide/onboard/sso-gitlab.html - name: "๐Ÿ” Resolve keycloak hosting node + container id" ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" diff --git a/roles/web-app-mattermost/tasks/03_oidc_admin.yml b/roles/web-app-mattermost/tasks/03_oidc_admin.yml index 8cf008c76d..01f0ee615f 100644 --- a/roles/web-app-mattermost/tasks/03_oidc_admin.yml +++ b/roles/web-app-mattermost/tasks/03_oidc_admin.yml @@ -3,7 +3,7 @@ - name: "๐Ÿ”Ž Mattermost | Check administrator auth service" database_query: config: "{{ lookup('database', application_id) }}" - query_file: "{{ role_path }}/files/sql/select-user-authservice.sql" + query_file: "{{ role_path }}/files/sql/select/user/authservice.sql" named_args: email: "{{ lookup('users', 'administrator').email }}" expect_rows: true @@ -13,33 +13,11 @@ - when: (mm_admin_authservice.rows[0][0] | default('') | trim) != 'gitlab' block: - - name: "๐Ÿ” Resolve openldap hosting node + container id" - ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" - vars: - resolve_service_key: openldap - resolve_service_name: "{{ lookup('container_service', 'svc-db-openldap', 'openldap') }}" - resolve_output_prefix: MATTERMOST_LDAP - resolve_compose_cid: "{{ MATTERMOST_LDAP_CONTAINER_ADDRESS }}" - - - name: "๐Ÿ—‚๏ธ Mattermost | Get administrator uidNumber from LDAP" - ansible.builtin.shell: | # nocheck: container-exec-resolver MATTERMOST_LDAP_LOCAL_CID resolved at delegate_to runtime; container_address would return a manager-only subshell - container exec -i {{ MATTERMOST_LDAP_LOCAL_CID | quote }} \ - ldapsearch -x -H ldap://localhost:389 \ - -D {{ LDAP.DN.ADMINISTRATOR.DATA | quote }} \ - -w {{ LDAP.BIND_CREDENTIAL | quote }} \ - -b {{ LDAP.DN.OU.USERS | quote }} \ - "(uid={{ lookup('users', 'administrator').username }})" uidNumber \ - | grep '^uidNumber:' | awk '{print $2}' - register: mm_admin_uidnumber - changed_when: false - failed_when: mm_admin_uidnumber.rc != 0 or mm_admin_uidnumber.stdout | trim == '' - delegate_to: "{{ MATTERMOST_LDAP_HOST_NODE | default(omit) }}" - - name: "๐Ÿ”„ Mattermost | Convert administrator to gitlab SSO auth" database_query: config: "{{ lookup('database', application_id) }}" query_file: "{{ role_path }}/files/sql/update/user-to-gitlab-auth.sql" named_args: - authdata: "{{ mm_admin_uidnumber.stdout | trim }}" + authdata: "{{ lookup('users', 'administrator').uid }}" email: "{{ lookup('users', 'administrator').email }}" mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-mattermost/tasks/utils/agents/enable.yml b/roles/web-app-mattermost/tasks/utils/agents/enable.yml new file mode 100644 index 0000000000..620a406bb6 --- /dev/null +++ b/roles/web-app-mattermost/tasks/utils/agents/enable.yml @@ -0,0 +1,20 @@ +--- +- name: "๐Ÿงฉ Mattermost | Activate the prepackaged Agents plugin" + ansible.builtin.command: + argv: + - container + - exec + - -i + - "{{ mattermost_agents_cid }}" # nocheck: container-exec-resolver + - /mattermost/bin/mmctl + - --local + - plugin + - enable + - "{{ MATTERMOST_MCP_PLUGIN_ID }}" + register: mattermost_agents_plugin_enable + retries: 60 + delay: 5 + until: mattermost_agents_plugin_enable.rc == 0 + changed_when: false + delegate_to: "{{ mattermost_agents_node }}" + run_once: true diff --git a/roles/web-app-mattermost/tasks/utils/agents/reload.yml b/roles/web-app-mattermost/tasks/utils/agents/reload.yml new file mode 100644 index 0000000000..9fcea0e943 --- /dev/null +++ b/roles/web-app-mattermost/tasks/utils/agents/reload.yml @@ -0,0 +1,19 @@ +--- +- name: "๐Ÿงฉ Mattermost | Deactivate the Agents plugin so it drops its cached config" + ansible.builtin.command: + argv: + - container + - exec + - -i + - "{{ mattermost_agents_cid }}" # nocheck: container-exec-resolver + - /mattermost/bin/mmctl + - --local + - plugin + - disable + - "{{ MATTERMOST_MCP_PLUGIN_ID }}" + changed_when: true + delegate_to: "{{ mattermost_agents_node }}" + run_once: true + +- name: "๐Ÿงฉ Mattermost | Reactivate the Agents plugin to ensure its bots" + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/agents/enable.yml" diff --git a/roles/web-app-mattermost/tasks/utils/ai_gateway.yml b/roles/web-app-mattermost/tasks/utils/ai_gateway.yml new file mode 100644 index 0000000000..12cf167c38 --- /dev/null +++ b/roles/web-app-mattermost/tasks/utils/ai_gateway.yml @@ -0,0 +1,135 @@ +--- +- name: "๐Ÿ” Verify the gateway contract for {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-litellm/tasks/utils/consumer_contract.yml') }}" + +- name: "๐Ÿ” Resolve {{ application_id }} hosting node + container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ entity_name }}" + resolve_output_prefix: MATTERMOST_AI + resolve_compose_cid: "{{ MATTERMOST_CONTAINER_ADDRESS }}" + resolve_converge_retries: 120 + resolve_converge_delay: 5 + +- name: "๐Ÿงฉ Mattermost | Activate the prepackaged Agents plugin" + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/agents/enable.yml" + vars: + mattermost_agents_cid: "{{ MATTERMOST_AI_LOCAL_CID }}" + mattermost_agents_node: "{{ MATTERMOST_AI_HOST_NODE }}" + +- name: "๐Ÿ”Ž Mattermost | Compare the stored Agents config to the contract" + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/select/ai/service.sql" + named_args: + service: "{{ MATTERMOST_LITELLM_SERVICE | to_json }}" + bot: "{{ MATTERMOST_LITELLM_BOT | to_json }}" + expect_rows: true + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: mattermost_ai_state + retries: 60 + delay: 5 + until: mattermost_ai_state.rows | default([]) | length > 0 + changed_when: false + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "๐Ÿค– Mattermost | Point the Agents bot at the platform gateway" + when: (mattermost_ai_state.rows[0][0] | trim) != 'converged' + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/update/ai/service.sql" + named_args: + service: "{{ MATTERMOST_LITELLM_SERVICE | to_json }}" + bot: "{{ MATTERMOST_LITELLM_BOT | to_json }}" + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + changed_when: true + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "๐Ÿค– Mattermost | Retarget the migrated agent row at the gateway" + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/update/ai/agent.sql" + named_args: + bot: "{{ MATTERMOST_LITELLM_BOT | to_json }}" + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + changed_when: true + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "๐Ÿ” Mattermost | Cycle the Agents plugin so it adopts the merged config" + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/agents/reload.yml" + vars: + mattermost_agents_cid: "{{ MATTERMOST_AI_LOCAL_CID }}" + mattermost_agents_node: "{{ MATTERMOST_AI_HOST_NODE }}" + +- name: "๐Ÿ”„ Mattermost | Carry the merged Agents config to every replica" + ansible.builtin.command: >- + container service update --force + {{ lookup('container_service', application_id, entity_name) }} + register: mattermost_agents_swarm_update + changed_when: mattermost_agents_swarm_update.rc == 0 + become: true + delegate_to: "{{ STACK_HOST }}" + run_once: true + when: + - DEPLOYMENT_MODE == 'swarm' + - IS_STACK_HOST | bool + +- name: "โณ Mattermost | Wait until every replica is back on the merged config" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/wait_converged.yml') }}" + vars: + wait_service_key: "{{ entity_name }}" + +- name: "๐Ÿ”Ž Mattermost | Re-read the stored Agents service and bot" + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/select/ai/service.sql" + named_args: + service: "{{ MATTERMOST_LITELLM_SERVICE | to_json }}" + bot: "{{ MATTERMOST_LITELLM_BOT | to_json }}" + expect_rows: true + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: mattermost_ai_state_final + changed_when: false + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "๐Ÿ›‘ Refuse an Agents configuration that does not match the gateway contract" + ansible.builtin.assert: + that: + - (mattermost_ai_state_final.rows[0][0] | trim) == 'converged' + - (LITELLM_CHAT_MODEL | trim) | length > 0 + fail_msg: >- + The Agents plugin still stores a service or bot that differs from the + deployed gateway contract ({{ MATTERMOST_LITELLM_BASE_URL }}, + model {{ LITELLM_CHAT_MODEL }}), so prompts would leave the deployment, + use a model the gateway does not serve, or carry a stale virtual key. + An empty model means the gateway serves none: neither svc-ai-ollama nor + svc-ai-lmstudio is in this deployment and no remote provider key is set. + +- name: "๐Ÿ”Ž Mattermost | Wait for the Agents plugin to provision its bot account" + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/select/ai/bot-user.sql" + named_args: + bot_name: "{{ MATTERMOST_LITELLM_BOT_NAME }}" + expect_rows: true + register: mattermost_ai_bot_final + retries: 60 + delay: 5 + until: (mattermost_ai_bot_final.rows[0][0] | int) > 0 + changed_when: false + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "๐Ÿ›‘ Refuse an Agents integration whose bot account was never created" + ansible.builtin.assert: + that: + - (mattermost_ai_bot_final.rows[0][0] | int) > 0 + fail_msg: >- + The Agents plugin never created the '{{ MATTERMOST_LITELLM_BOT_NAME }}' + bot account, so no Mattermost surface can address the gateway. The merged + config row alone does not provision the account; only the plugin's + EnsureBots run on activation does. diff --git a/roles/web-app-mattermost/tasks/utils/mcp.yml b/roles/web-app-mattermost/tasks/utils/mcp.yml new file mode 100644 index 0000000000..6893dac7d7 --- /dev/null +++ b/roles/web-app-mattermost/tasks/utils/mcp.yml @@ -0,0 +1,32 @@ +--- +- name: "๐Ÿ” Read the MCP token this server already issued" + ansible.builtin.set_fact: + mattermost_mcp_token: "{{ lookup('mcp_credential', application_id) }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐Ÿ” Resolve {{ application_id }} hosting node + container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ entity_name }}" + resolve_output_prefix: MATTERMOST_MCP + resolve_compose_cid: "{{ MATTERMOST_CONTAINER_ADDRESS }}" + resolve_converge_retries: 120 + resolve_converge_delay: 5 + +- name: "๐Ÿงฉ Switch the Agents plugin MCP server on" + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/mcp/server.yml" + +- name: "๐Ÿ”‘ Hand MCP clients a bearer token" + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/mcp/token.yml" + +- name: "๐Ÿ”‘ Hand the minted upstream token to the adapter" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/upstream_key.yml') }}" + vars: + mcp_upstream_key_path: "{{ [MATTERMOST_MCP_INSTANCE_DIR, 'upstream.env'] | path_join }}" + mcp_upstream_key: "{{ lookup('mcp_credential', application_id) }}" + +- name: "๐Ÿงฑ Rebuild the MCP adapter of {{ application_id }} now the bearer exists" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/rebuild.yml') }}" + +- name: "๐Ÿšฟ Flush compose handlers for {{ application_id }}" + ansible.builtin.meta: flush_handlers diff --git a/roles/web-app-mattermost/tasks/utils/mcp/server.yml b/roles/web-app-mattermost/tasks/utils/mcp/server.yml new file mode 100644 index 0000000000..79f83b6fde --- /dev/null +++ b/roles/web-app-mattermost/tasks/utils/mcp/server.yml @@ -0,0 +1,53 @@ +--- +- name: "๐Ÿงฉ Mattermost | Activate the prepackaged Agents plugin" + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/agents/enable.yml" + vars: + mattermost_agents_cid: "{{ MATTERMOST_MCP_LOCAL_CID }}" + mattermost_agents_node: "{{ MATTERMOST_MCP_HOST_NODE }}" + +- name: "๐Ÿ”Ž Mattermost | Read the Agents MCP server toggle" + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/select/mcp-plugin-server.sql" + expect_rows: true + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: mattermost_mcp_toggle + retries: 60 + delay: 5 + until: mattermost_mcp_toggle.rows | default([]) | length > 0 + changed_when: false + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "๐ŸŸข Mattermost | Expose the MCP server in the Agents config" + when: (mattermost_mcp_toggle.rows[0][0] | trim) != 'true' + block: + - name: "๐ŸŸข Mattermost | Patch the active Agents config row" + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/update/enable-mcp-plugin-server.sql" + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + changed_when: true + delegate_to: "{{ STACK_HOST }}" + run_once: true + notify: container-recreate + +- name: "๐Ÿ”Ž Mattermost | Re-read the Agents MCP server toggle" + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/select/mcp-plugin-server.sql" + expect_rows: true + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: mattermost_mcp_toggle_final + changed_when: false + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "๐Ÿ›‘ Refuse a server that routes no MCP endpoint" + ansible.builtin.assert: + that: + - (mattermost_mcp_toggle_final.rows[0][0] | trim) == 'true' + fail_msg: >- + The Agents plugin still reports mcp.enablePluginServer=false, so + {{ lookup('config', application_id, 'mcp.endpoint.path') }} + answers 404 and every MCP client would be pointed at a dead endpoint. diff --git a/roles/web-app-mattermost/tasks/utils/mcp/token.yml b/roles/web-app-mattermost/tasks/utils/mcp/token.yml new file mode 100644 index 0000000000..ae2ccd6dfb --- /dev/null +++ b/roles/web-app-mattermost/tasks/utils/mcp/token.yml @@ -0,0 +1,66 @@ +--- +- name: "๐Ÿฉบ Mattermost | Check whether the stored token is still active" + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/select/user/access-token.sql" + named_args: + token: "{{ mattermost_mcp_token }}" + expect_rows: true + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: mattermost_mcp_token_state + when: mattermost_mcp_token | length > 0 + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "๐Ÿ”‘ Mattermost | Mint a personal access token for MCP clients" + when: mattermost_mcp_token | length == 0 or (mattermost_mcp_token_state.rows[0][0] | default('0') | trim) != '1' + block: + - name: "๐Ÿ”‘ Mattermost | Ask the server for a personal access token" + ansible.builtin.command: + argv: + - container + - exec + - -i + - "{{ MATTERMOST_MCP_LOCAL_CID }}" # nocheck: container-exec-resolver + - /mattermost/bin/mmctl + - --local + - --json + - --suppress-warnings + - token + - generate + - "{{ lookup('users', 'administrator').username }}" + - "{{ MATTERMOST_MCP_TOKEN_DESCRIPTION }}" + register: mattermost_mcp_token_mint + retries: 30 + delay: 10 + until: mattermost_mcp_token_mint.rc == 0 + changed_when: mattermost_mcp_token_mint.rc == 0 + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ MATTERMOST_MCP_HOST_NODE }}" + run_once: true + + - name: "๐Ÿ”ง Mattermost | Take the minted token from the mmctl payload" + ansible.builtin.set_fact: + mattermost_mcp_token: "{{ (mattermost_mcp_token_mint.stdout | from_json | first).token | trim }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + run_once: true + +- name: "๐Ÿ›‘ Refuse a server that issued no usable token" + ansible.builtin.assert: + that: + - mattermost_mcp_token | length >= 26 + fail_msg: >- + Mattermost returned no personal access token, so every MCP client would + be configured with an empty bearer and be rejected at first use. + +- name: "๐Ÿ’พ Persist the token so MCP clients can read it" + ansible.builtin.include_role: + name: sys-token-store + tasks_from: write.yml + vars: + sys_token_store_user_key: "{{ lookup('config', application_id, 'mcp.credential.owner') }}" + sys_token_store_app: "{{ application_id }}" + sys_token_store_token: "{{ mattermost_mcp_token }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-mattermost/templates/compose.yml.j2 b/roles/web-app-mattermost/templates/compose.yml.j2 index 3d939a52ff..9e9cb7ab5e 100644 --- a/roles/web-app-mattermost/templates/compose.yml.j2 +++ b/roles/web-app-mattermost/templates/compose.yml.j2 @@ -7,16 +7,40 @@ {{ lookup('compose_only', 'container_name', MATTERMOST_CONTAINER) }} {{ lookup('container_ports', ['mattermost', 'http', DOCKER_BIND_HOST]) | indent(4) }} {{ lookup('container_volumes', service_name) | indent(4) }} - healthcheck: - test: ["CMD", "/mattermost/bin/mmctl", "--local", "system", "status"] - interval: 1m - timeout: 10s - retries: 3 - start_period: 30s + command: ["/mattermost/bin/mattermost", "server"] + {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} {{ lookup('container_depends_on', application_id) | indent(4) }} + {% if MATTERMOST_MCP_ENABLED | bool %} + {% set service_name = 'mattermostmcp' %} + {% set docker_compose_env = [MATTERMOST_MCP_INSTANCE_DIR, 'upstream.env'] | path_join %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, 'mattermostmcp') }} + build: + context: {{ MATTERMOST_MCP_INSTANCE_DIR }} + dockerfile: Dockerfile + args: + MCP_ADAPTER_BASE_IMAGE: {{ lookup('config', application_id, 'services.mattermostmcp.image') }} + MCP_ADAPTER_BASE_VERSION: "{{ lookup('config', application_id, 'services.mattermostmcp.version') }}" + {{ lookup('compose_only', 'container_name', MATTERMOST_MCP_CONTAINER) }} + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + environment: + ADAPTER_CONTRACT: {{ MATTERMOST_MCP_CONTRACT | to_json | to_json | replace('$', '$$') }} + ADAPTER_BEARER: {{ MATTERMOST_MCP_BEARER | to_json }} + ADAPTER_PORT: "{{ MATTERMOST_MCP_PORT }}" + expose: + - "{{ MATTERMOST_MCP_PORT }}" + {{ lookup('container_healthcheck', 'mattermostmcp') | indent(4) }} + {{ lookup('container_networks', own_network_only=True, provider_self_alias=False) | indent(4) }} + {% endif %} + {{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/web-app-mattermost/templates/env.j2 b/roles/web-app-mattermost/templates/env.j2 index 36a697b14b..2f4911fa4c 100644 --- a/roles/web-app-mattermost/templates/env.j2 +++ b/roles/web-app-mattermost/templates/env.j2 @@ -4,7 +4,7 @@ MM_SERVICESETTINGS_SITEURL={{ lookup('tls', application_id, 'url.base') }} MM_SERVICESETTINGS_LISTENADDRESS=:{{ container_port }} MM_SERVICESETTINGS_ALLOWCORSFROM={{ lookup('tls', application_id, 'url.base') }} MM_SERVICESETTINGS_ENABLELOCALMODE=true -MM_SERVICESETTINGS_ENABLEUSERACCESSTOKENS={{ lookup('config', application_id, 'services.mattermost.user_access_token_enabled') }} +MM_SERVICESETTINGS_ENABLEUSERACCESSTOKENS={{ (lookup('config', application_id, 'services.mattermost.user_access_token_enabled') | bool) or (MATTERMOST_MCP_ENABLED | bool) }} MM_EXPERIMENTALSETTINGS_DISABLELANDINGPAGE=true MM_LOGSETTINGS_CONSOLELEVEL={% if MODE_DEBUG | bool %}DEBUG{% else %}INFO{% endif %} @@ -12,10 +12,12 @@ MM_LOGSETTINGS_CONSOLELEVEL={% if MODE_DEBUG | bool %}DEBUG{% else %}INFO{% endi MM_LOGSETTINGS_ENABLEFILE=false MM_SQLSETTINGS_DRIVERNAME=postgres -MM_SQLSETTINGS_DATASOURCE=postgres://{{ lookup('database', application_id, 'username') }}:{{ lookup('database', application_id, 'password') }}@{{ lookup('database', application_id, 'host') }}:{{ lookup('database', application_id, 'port') }}/{{ lookup('database', application_id, 'name') }}?sslmode=disable&connect_timeout=10 +MM_SQLSETTINGS_DATASOURCE={{ MATTERMOST_DATABASE_DSN }} MM_SQLSETTINGS_MAXOPENCONNS=20 MM_SQLSETTINGS_MAXIDLECONNS=10 +MM_CONFIG={{ MATTERMOST_DATABASE_DSN }} + {% if lookup('objstore', application_id, 'enabled') | bool %} MM_FILESETTINGS_DRIVERNAME=amazons3 MM_FILESETTINGS_AMAZONS3BUCKET={{ lookup('objstore', application_id, 'bucket') }} @@ -49,6 +51,7 @@ MM_GITLABSETTINGS_SECRET={{ OIDC.CLIENT.SECRET }} MM_GITLABSETTINGS_AUTHENDPOINT={{ OIDC.CLIENT.AUTHORIZE_URL }} MM_GITLABSETTINGS_TOKENENDPOINT={{ OIDC.CLIENT.TOKEN_URL }} MM_GITLABSETTINGS_USERAPIENDPOINT={{ OIDC.CLIENT.USER_INFO_URL }} +MM_SERVICESETTINGS_ALLOWEDUNTRUSTEDINTERNALCONNECTIONS={{ [OIDC.CLIENT.TOKEN_URL | urlsplit('hostname'), OIDC.CLIENT.USER_INFO_URL | urlsplit('hostname')] | unique | join(',') }} {% endif %} {% if lookup('config', application_id, 'services.prometheus.native_metrics.enabled', False) | bool %} diff --git a/roles/web-app-mattermost/templates/javascript.js.j2 b/roles/web-app-mattermost/templates/javascript.js.j2 index b96dc1378e..4dec5e539a 100644 --- a/roles/web-app-mattermost/templates/javascript.js.j2 +++ b/roles/web-app-mattermost/templates/javascript.js.j2 @@ -5,7 +5,7 @@ window.addEventListener("DOMContentLoaded", function () { // Rename if Mattermost ever renders the GitLab button natively document.querySelectorAll("a[href*='/oauth/gitlab/']").forEach(function (el) { if (el.textContent.trim() === "GitLab") { - el.textContent = "SSO with Infinito.Nexus"; + el.textContent = "SSO with {{ SOFTWARE_NAME }}"; } }); @@ -19,7 +19,7 @@ window.addEventListener("DOMContentLoaded", function () { var a = document.createElement("a"); a.href = "/oauth/gitlab/login"; - a.textContent = "SSO with Infinito.Nexus"; + a.textContent = "SSO with {{ SOFTWARE_NAME }}"; a.className = "btn btn-primary login-body-card-form-button-submit large"; a.style.cssText = "display:flex;align-items:center;justify-content:center;width:100%;box-sizing:border-box;margin:20px 0 0 0;"; btn.parentNode.insertBefore(a, btn.nextSibling); diff --git a/roles/web-app-mattermost/templates/playwright.env.j2 b/roles/web-app-mattermost/templates/playwright.env.j2 index b315558fc9..4f807ed924 100644 --- a/roles/web-app-mattermost/templates/playwright.env.j2 +++ b/roles/web-app-mattermost/templates/playwright.env.j2 @@ -16,6 +16,12 @@ EMAIL_SERVICE_ENABLED={{ lookup('config', application_id, 'services.email.enable # nocheck: playwright-service-gate โ€” persona drives the OIDC path; LDAP federation is exercised in the LDAP-only matrix variant LDAP_SERVICE_ENABLED={{ lookup('config', application_id, 'services.ldap.enabled') | string | lower }} +LITELLM_API_URL={{ MATTERMOST_LITELLM_BASE_URL | dotenv_quote }} + +LITELLM_BOT_NAME={{ MATTERMOST_LITELLM_BOT_NAME | dotenv_quote }} + +LITELLM_SERVICE_ENABLED={{ lookup('config', application_id, 'services.litellm.enabled') | string | lower }} + LOGOUT_SERVICE_ENABLED={{ lookup('config', application_id, 'services.logout.enabled') | string | lower }} MATOMO_BASE_URL={{ lookup('tls', 'web-app-matomo', 'url.base') | dotenv_quote }} @@ -24,10 +30,13 @@ MATOMO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.matomo.enab MATTERMOST_BASE_URL={{ lookup('tls', 'web-app-mattermost', 'url.base') | dotenv_quote }} +MCP_ENDPOINT_PATH={{ MATTERMOST_MCP_UPSTREAM_PATH | dotenv_quote }} +MCP_SERVICE_ENABLED={{ lookup('config', application_id, 'mcp.enabled') | string | lower }} + OIDC_ISSUER_URL={{ OIDC.CLIENT.ISSUER_URL | dotenv_quote }} -# nocheck: persona-block-rationale โ€” Mattermost Team Edition has no native OIDC provider, so this role piggybacks Keycloak onto the GitLab OAuth slot (vars/main.yml, MM_GITLABSETTINGS_* in templates/env.j2); the entry point is a[href='/oauth/gitlab/login'] relabelled "SSO with Infinito.Nexus" by templates/javascript.js.j2, which the shared helper's name-based login matcher does not match, and Mattermost v11+ first serves a /landing interstitial that only clears once localStorage.__landingPageSeen__ is seeded before navigation โ€” the shared helper has no init-script hook (see README "Persona contract opt-outs"). +# nocheck: persona-block-rationale โ€” Mattermost Team Edition has no native OIDC provider, so this role piggybacks Keycloak onto the GitLab OAuth slot (vars/main.yml, MM_GITLABSETTINGS_* in templates/env.j2); the entry point is a[href='/oauth/gitlab/login'] relabelled "SSO with {{ SOFTWARE_NAME }}" by templates/javascript.js.j2, which the shared helper's name-based login matcher does not match, and Mattermost v11+ first serves a /landing interstitial that only clears once localStorage.__landingPageSeen__ is seeded before navigation โ€” the shared helper has no init-script hook (see README "Persona contract opt-outs"). PERSONA_ADMINISTRATOR_BLOCKED=true # nocheck: persona-block-rationale โ€” see PERSONA_ADMINISTRATOR_BLOCKED above. @@ -44,4 +53,3 @@ SEAWEEDFS_FILER_URL={{ lookup('canonical_url', 'web-app-seaweedfs', 'filer', con SEAWEEDFS_SERVICE_ENABLED={{ lookup('config', application_id, 'services.seaweedfs.enabled') | string | lower }} SSO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.sso.enabled') | string | lower }} - diff --git a/roles/web-app-mattermost/templates/test.env.j2 b/roles/web-app-mattermost/templates/test.env.j2 new file mode 100644 index 0000000000..3c7bacad44 --- /dev/null +++ b/roles/web-app-mattermost/templates/test.env.j2 @@ -0,0 +1 @@ +{{ lookup('template', lookup('path_absolute', 'roles/test-e2e-cli/templates/mcp/test.env.j2')) }} diff --git a/roles/web-app-mattermost/vars/main.yml b/roles/web-app-mattermost/vars/main.yml index edc6348e3b..de4abe3f63 100644 --- a/roles/web-app-mattermost/vars/main.yml +++ b/roles/web-app-mattermost/vars/main.yml @@ -4,14 +4,67 @@ entity_name: "{{ application_id | get_entity_name }}" container_port: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.ports.internal.http') }}" +MATTERMOST_DATABASE_DSN: "{{ lookup('database', application_id, 'url_full') }}?sslmode=disable&connect_timeout=10" + MATTERMOST_CONTAINER: "{{ lookup('config', application_id, 'services.mattermost.name') }}" MATTERMOST_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, entity_name) }}" -# Exception: OIDC piggybacks on MM_GITLABSETTINGS_* -- Team Edition has no native OIDC provider for Keycloak MATTERMOST_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') }}" +MATTERMOST_LITELLM_ENABLED: "{{ lookup('config', application_id, 'services.litellm.enabled') | bool }}" +MATTERMOST_LITELLM_BASE_URL: "{{ LITELLM_OPENAI_BASE_LOCAL_URL }}" +MATTERMOST_LITELLM_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.litellm_api_key') }}" +MATTERMOST_LITELLM_SERVICE_ID: infinito-litellm +MATTERMOST_LITELLM_BOT_ID: infinito-litellm-agent +MATTERMOST_LITELLM_BOT_NAME: agent + +MATTERMOST_LITELLM_SERVICE: + id: "{{ MATTERMOST_LITELLM_SERVICE_ID }}" + name: Infinito LiteLLM + type: openaicompatible + apiKey: "{{ MATTERMOST_LITELLM_API_KEY }}" + apiURL: "{{ MATTERMOST_LITELLM_BASE_URL }}" + defaultModel: "{{ LITELLM_CHAT_MODEL }}" + orgId: "" + tokenLimit: 0 + streamingTimeoutSeconds: 0 + +MATTERMOST_LITELLM_BOT: + id: "{{ MATTERMOST_LITELLM_BOT_ID }}" + name: "{{ MATTERMOST_LITELLM_BOT_NAME }}" + displayName: Agent + customInstructions: "" + serviceID: "{{ MATTERMOST_LITELLM_SERVICE_ID }}" + model: "{{ LITELLM_CHAT_MODEL }}" + enableVision: false + disableTools: false + channelAccessLevel: 0 + channelIDs: [] + userAccessLevel: 0 + userIDs: [] + teamIDs: [] + maxFileSize: 0 + +MATTERMOST_MCP_ENABLED: "{{ lookup('config', application_id, 'services.mattermostmcp.enabled') | bool }}" +MATTERMOST_MCP_PLUGIN_ID: mattermost-ai +MATTERMOST_MCP_TOKEN_DESCRIPTION: mcp + MATTERMOST_KEYCLOAK_CONTAINER_ADDRESS: "{{ lookup('container_address', 'web-app-keycloak', 'keycloak') }}" MATTERMOST_KEYCLOAK_ADMIN_USER: "{{ lookup('config', 'web-app-keycloak', 'services.keycloak.accounts.system.username') }}" MATTERMOST_KEYCLOAK_ADMIN_PASS: "{{ lookup('users', 'administrator').password }}" -MATTERMOST_LDAP_CONTAINER_ADDRESS: "{{ lookup('container_address', 'svc-db-openldap', 'openldap') }}" +MATTERMOST_MCP_CONTAINER: "{{ lookup('config', application_id, 'services.mattermostmcp.name') }}" +MATTERMOST_MCP_PORT: "{{ lookup('config', application_id, 'services.mattermostmcp.ports.internal.http') }}" +MATTERMOST_MCP_INSTANCE_DIR: "{{ [lookup('container', application_id, 'directories.instance'), 'mcp'] | path_join }}" +MATTERMOST_MCP_UPSTREAM_PATH: "{{ lookup('config', application_id, 'mcp.adapter.upstream_path') }}" +MATTERMOST_MCP_UPSTREAM_URL: "http://{{ MATTERMOST_CONTAINER }}:{{ container_port }}{{ MATTERMOST_MCP_UPSTREAM_PATH }}" +MATTERMOST_MCP_BEARER: "{{ lookup('config', application_id, 'secrets.credentials.mcp_bearer') }}" +MATTERMOST_MCP_CONTRACT: + upstream_kind: mcp + provider: "{{ application_id }}" + upstream_url: "{{ MATTERMOST_MCP_UPSTREAM_URL }}" + auth_subject: "{{ lookup('config', application_id, 'mcp.auth_subject') }}" + mutating_tools_enabled: "{{ lookup('config', application_id, 'mcp.tools.mutating_tools_enabled') | bool }}" + tools: "{{ lookup('file', 'mcp/tools.json') | from_json }}" + limits: "{{ lookup('config', application_id, 'mcp.limits') }}" + schema_sha256: "{{ lookup('config', application_id, 'mcp.tools.schema_sha256') }}" diff --git a/roles/web-app-mediawiki/README.md b/roles/web-app-mediawiki/README.md index 5e13e21d5e..4681affb8c 100644 --- a/roles/web-app-mediawiki/README.md +++ b/roles/web-app-mediawiki/README.md @@ -15,6 +15,7 @@ The diagram places MediaWiki in the Infinito.Nexus cosmos: the components it dep ```mermaid flowchart LR subgraph deps [Dependencies] + dep_svc_ai_litellm["svc-ai-litellm ๐Ÿณ๐Ÿ"] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local ๐Ÿ’ป"] dep_svc_db_mariadb["svc-db-mariadb ๐Ÿณ๐Ÿ"] dep_svc_net_tor["svc-net-tor ๐Ÿณ๐Ÿ"] @@ -27,6 +28,7 @@ flowchart LR dep_web_svc_logout["web-svc-logout ๐Ÿณ๐Ÿ"] end subgraph role [web-app-mediawiki ๐Ÿณ๐Ÿ] + svc_litellm["litellm"] svc_sso["sso"] svc_logout["logout"] svc_dashboard["dashboard"] @@ -39,6 +41,7 @@ flowchart LR svc_tor["tor"] svc_container_backup["container_backup"] end + dep_svc_ai_litellm -. "0..1" .-> svc_litellm dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup dep_svc_db_mariadb -. "0..1" .-> svc_mariadb dep_svc_net_tor -. "0..1" .-> svc_tor @@ -81,19 +84,20 @@ Run the published image to provision the inventory and deploy MediaWiki to a man ```bash APP=web-app-mediawiki HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' @@ -101,12 +105,28 @@ docker run --rm -it \ ## Addons -This role ships its OIDC login stack as unified addons declared in [`meta/addons/`](meta/addons/). Both are MediaWiki extensions installed from upstream and gated on the `sso` service flag (`web-app-keycloak` co-deployed). The OIDC client secret is rendered through `templates/oidc.php.j2` and never inlined into the addon declaration. +This role ships its OIDC login stack and its AI editing stack as unified addons declared in [`meta/addons/`](meta/addons/). All four are MediaWiki extensions installed from upstream at the `REL_` branch matching the pinned image, and each is gated on a service flag. Secrets are rendered through the role's templates and never inlined into an addon declaration. | Addon | Mechanism | Default state | Bridges | |---|---|---|---| | PluggableAuth | extension | enabled when `services.sso.enabled` | none | | OpenIDConnect | extension | enabled when `services.sso.enabled` | `sso` | +| VisualEditorPlus | extension | enabled when `services.litellm.enabled` | `litellm` | +| AIEditingAssistant | extension | enabled when `services.litellm.enabled` | `litellm` | + +`meta/addons/` is also the download list: `MEDIAWIKI_EXT_NAMES` keeps only the addons whose `enabled` resolves true, so a deployment without the matching service never pulls that tarball or runs composer for it. + +## AI editing assistant + +With `services.litellm.enabled`, `templates/LocalSettings.php.j2` loads `VisualEditor` (bundled in the image), `VisualEditorPlus` and `AIEditingAssistant`, then points the extension's `open-ai` provider at the in-cluster gateway: + +- `$wgAIEditingAssistantActiveProvider` is `open-ai`. +- `$wgAIEditingAssistantActiveProviderConnection` is the JSON object `{url, endpoint, model, secret}` built from `MEDIAWIKI_LITELLM_CONNECTION`; `url` is `LITELLM_OPENAI_BASE_LOCAL_URL` and `secret` is this role's own `credentials.litellm_api_key`. The braces are mandatory: a brace-free value is re-wrapped as `{"legacy": ...}` upstream and the provider falls back to the vendor endpoint at `api.openai.com`. +- `$wgHTTPTimeout` is raised inside the same block because core's 25s is below a cold local model's first token. + +The wiring block sits behind a `file_exists` guard on `extensions/VisualEditorPlus/vendor/autoload.php`, because `LocalSettings.php` is rendered before the extensions are installed and `VisualEditorPlus` fatals until its composer step has run. + +[`tasks/utils/ai_gateway.yml`](tasks/utils/ai_gateway.yml) runs after `update.php`. It includes the shared gateway consumer contract, then reads both globals back out of the running container with `maintenance/run.php getConfiguration --format=json` and asserts the provider, the base URL and the model, so an unconfigured surface cannot reach a green deploy. ## Further Resources diff --git a/roles/web-app-mediawiki/files/playwright/addons/AIEditingAssistant.spec.js b/roles/web-app-mediawiki/files/playwright/addons/AIEditingAssistant.spec.js new file mode 100644 index 0000000000..2634ec33c9 --- /dev/null +++ b/roles/web-app-mediawiki/files/playwright/addons/AIEditingAssistant.spec.js @@ -0,0 +1,86 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("../timeouts"); + +const { skipUnlessAddonEnabled } = require("../addon-gating"); +const { normalizeBaseUrl } = require("../personas"); + +test.use({ ignoreHTTPSErrors: true }); + +const appBaseUrl = normalizeBaseUrl(process.env.APP_BASE_URL || ""); +const aiGatewayBaseUrl = normalizeBaseUrl(process.env.AI_GATEWAY_BASE_URL || ""); + +const PROMPT_ROUTE = "/rest.php/aieditingassistant/v1/prompt"; + +test("AIEditingAssistant: the wiki answers a prompt through the in-cluster gateway", async ({ + request, +}) => { + skipUnlessAddonEnabled("AIEditingAssistant"); + test.setTimeout(resolveTimeout(240_000)); + + expect(appBaseUrl, "APP_BASE_URL must be set").toBeTruthy(); + expect(aiGatewayBaseUrl, "AI_GATEWAY_BASE_URL must be set").toBeTruthy(); + + const gateway = new URL(aiGatewayBaseUrl); + const wikiHost = new URL(appBaseUrl).host; + + expect( + gateway.protocol, + `the AI base URL must stay on the container network (plain http), got ${aiGatewayBaseUrl}`, + ).toBe("http:"); + expect( + gateway.hostname.includes("."), + "the AI base URL host must be an undotted compose/swarm service name; a dotted host is " + + `resolved through the dns-search suffix and leaves via the public ingress (got ${aiGatewayBaseUrl})`, + ).toBe(false); + expect( + gateway.host, + "the AI base URL must point at the gateway, not back at the wiki itself", + ).not.toBe(wikiHost); + + const siteinfo = await request.get( + `${appBaseUrl}/api.php?action=query&meta=siteinfo&siprop=extensions&format=json&formatversion=2`, + { timeout: resolveTimeout(60_000) }, + ); + expect( + siteinfo.status(), + "the MediaWiki action API must answer so the loaded extension list can be read", + ).toBe(200); + const installed = ((await siteinfo.json()).query?.extensions || []).map( + (extension) => extension.name, + ); + expect( + installed, + "AIEditingAssistant is not in the loaded extension list, so LocalSettings.php never " + + "reached its wfLoadExtension block (extension missing, or VisualEditor/VisualEditorPlus " + + "not loaded ahead of it)", + ).toContain("AIEditingAssistant"); + + const response = await request.post(`${appBaseUrl}${PROMPT_ROUTE}`, { + data: { + command: "Fix grammar and punctuation in this text", + text: "this sentence have a error", + isContinuation: false, + }, + timeout: resolveTimeout(210_000), + }); + + const bodyText = await response.text(); + expect( + response.status(), + `POST ${PROMPT_ROUTE} returned ${response.status()}: ${bodyText.slice(0, 500)}. ` + + "400 means $wgAIEditingAssistantActiveProvider is unset or unknown; 500 means the " + + "provider reached no working gateway leg (wrong base URL, rejected virtual key, or a " + + `model the gateway does not serve). Configured gateway: ${aiGatewayBaseUrl}.`, + ).toBe(200); + + const body = JSON.parse(bodyText); + expect( + body.success, + "the prompt handler must report success, proving the provider completed the round-trip", + ).toBe(true); + expect( + String(body.result || "").trim().length, + "the gateway must return a real, non-empty completion; an empty result means the model " + + "answered nothing and the surface is wired but useless", + ).toBeGreaterThan(0); +}); diff --git a/roles/web-app-mediawiki/files/playwright/addons/VisualEditorPlus.spec.js b/roles/web-app-mediawiki/files/playwright/addons/VisualEditorPlus.spec.js new file mode 100644 index 0000000000..ac3cf9d6c9 --- /dev/null +++ b/roles/web-app-mediawiki/files/playwright/addons/VisualEditorPlus.spec.js @@ -0,0 +1,61 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("../timeouts"); + +const { skipUnlessAddonEnabled } = require("../addon-gating"); +const { normalizeBaseUrl } = require("../personas"); + +test.use({ ignoreHTTPSErrors: true }); + +const appBaseUrl = normalizeBaseUrl(process.env.APP_BASE_URL || ""); + +const INSPECTOR_MODULE = "ext.visualEditorPlus.inlineTextInspector"; + +test("VisualEditorPlus: the extension is loaded and serves the inspector module AIEditingAssistant depends on", async ({ + request, +}) => { + skipUnlessAddonEnabled("VisualEditorPlus"); + test.setTimeout(resolveTimeout(120_000)); + + expect(appBaseUrl, "APP_BASE_URL must be set").toBeTruthy(); + + const siteinfo = await request.get( + `${appBaseUrl}/api.php?action=query&meta=siteinfo&siprop=extensions&format=json&formatversion=2`, + { timeout: resolveTimeout(60_000) }, + ); + expect( + siteinfo.status(), + "the MediaWiki action API must answer so the loaded extension list can be read", + ).toBe(200); + + const installed = ((await siteinfo.json()).query?.extensions || []).map( + (extension) => extension.name, + ); + expect( + installed, + "VisualEditor must be loaded: AIEditingAssistant's extension.json hard-requires it and " + + "ExtensionRegistry raises a fatal ExtensionDependencyError when it is absent", + ).toContain("VisualEditor"); + expect( + installed, + "VisualEditorPlus is not loaded; it is not bundled in the mediawiki image, so a missing " + + "tarball or an unfinished composer install left LocalSettings.php's file_exists guard closed", + ).toContain("VisualEditorPlus"); + + const module = await request.get( + `${appBaseUrl}/load.php?modules=${INSPECTOR_MODULE}&only=scripts&raw=1&debug=1`, + { timeout: resolveTimeout(60_000) }, + ); + expect(module.status(), `load.php must serve ${INSPECTOR_MODULE}`).toBe(200); + + const script = await module.text(); + expect( + script.length, + `${INSPECTOR_MODULE} rendered an empty payload; AIEditingAssistant's inspector module ` + + "depends on it and would never load in VisualEditor", + ).toBeGreaterThan(0); + expect( + /"missing"|no such module/i.test(script), + `ResourceLoader reports ${INSPECTOR_MODULE} as missing, so VisualEditorPlus registered no ` + + `modules: ${script.slice(0, 300)}`, + ).toBe(false); +}); diff --git a/roles/web-app-mediawiki/meta/addons/AIEditingAssistant.yml b/roles/web-app-mediawiki/meta/addons/AIEditingAssistant.yml new file mode 100644 index 0000000000..4dc6773d5c --- /dev/null +++ b/roles/web-app-mediawiki/meta/addons/AIEditingAssistant.yml @@ -0,0 +1,11 @@ +--- +enabled: "{{ lookup('config', 'web-app-mediawiki', 'services.litellm.enabled') | bool }}" +required: true +mechanism: extension +source: upstream +bridges: + - litellm +update: + monitored: true + catalog: mediawiki-extension + upstream_id: AIEditingAssistant diff --git a/roles/web-app-mediawiki/meta/addons/VisualEditorPlus.yml b/roles/web-app-mediawiki/meta/addons/VisualEditorPlus.yml new file mode 100644 index 0000000000..5cac56dbfb --- /dev/null +++ b/roles/web-app-mediawiki/meta/addons/VisualEditorPlus.yml @@ -0,0 +1,11 @@ +--- +enabled: "{{ lookup('config', 'web-app-mediawiki', 'services.litellm.enabled') | bool }}" +required: true +mechanism: extension +source: upstream +bridges: + - litellm +update: + monitored: true + catalog: mediawiki-extension + upstream_id: VisualEditorPlus diff --git a/roles/web-app-mediawiki/meta/secrets.yml b/roles/web-app-mediawiki/meta/secrets.yml index b4730c62c1..190cb1ba1e 100644 --- a/roles/web-app-mediawiki/meta/secrets.yml +++ b/roles/web-app-mediawiki/meta/secrets.yml @@ -1,5 +1,10 @@ --- credentials: + litellm_api_key: + description: Per-consumer virtual key for the shared svc-ai-litellm gateway + algorithm: sk_prefixed + validation: + min_length: 50 secret_key: description: MediaWiki $wgSecretKey (hex-encoded 32 random bytes) algorithm: random_hex_32 diff --git a/roles/web-app-mediawiki/meta/services.yml b/roles/web-app-mediawiki/meta/services.yml index 94a8b95812..59ab1fea9b 100644 --- a/roles/web-app-mediawiki/meta/services.yml +++ b/roles/web-app-mediawiki/meta/services.yml @@ -1,4 +1,9 @@ --- +# nocheck: playwright-service-flag, dynamic-flag - shared gateway consumer; inference wiring is covered by the gateway role, and the gateway is a single shared instance +litellm: + bond: 0.5 + enabled: "{{ LITELLM_USABLE }}" + shared: true # nocheck: seaweedfs-required โ€” object storage not implemented for this role sso: bond: 1 @@ -29,7 +34,6 @@ mariadb: mediawiki: healthcheck: flavor: tcp - start_period: 5m modes: compose: enabled: true diff --git a/roles/web-app-mediawiki/meta/variants.yml b/roles/web-app-mediawiki/meta/variants.yml index b0b39f9c1f..bd762b7a90 100644 --- a/roles/web-app-mediawiki/meta/variants.yml +++ b/roles/web-app-mediawiki/meta/variants.yml @@ -24,6 +24,8 @@ matomo: enabled: true shared: true + litellm: + enabled: true sso: enabled: true shared: true @@ -53,6 +55,40 @@ matomo: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true + litellm: + enabled: false + sso: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + prometheus: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + tor: + enabled: true + +- services: + container_backup: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + css: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + dashboard: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + email: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + logout: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + mariadb: + shared: true + matomo: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + litellm: + enabled: true sso: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true diff --git a/roles/web-app-mediawiki/tasks/02_extensions.yml b/roles/web-app-mediawiki/tasks/02_extensions.yml index 36206933f8..1fe8ca69dd 100644 --- a/roles/web-app-mediawiki/tasks/02_extensions.yml +++ b/roles/web-app-mediawiki/tasks/02_extensions.yml @@ -55,3 +55,4 @@ register: _oidc_class changed_when: false failed_when: _oidc_class.rc != 0 + when: MEDIAWIKI_OIDC_ENABLED | bool diff --git a/roles/web-app-mediawiki/tasks/addons/AIEditingAssistant.yml b/roles/web-app-mediawiki/tasks/addons/AIEditingAssistant.yml new file mode 100644 index 0000000000..ed97d539c0 --- /dev/null +++ b/roles/web-app-mediawiki/tasks/addons/AIEditingAssistant.yml @@ -0,0 +1 @@ +--- diff --git a/roles/web-app-mediawiki/tasks/addons/VisualEditorPlus.yml b/roles/web-app-mediawiki/tasks/addons/VisualEditorPlus.yml new file mode 100644 index 0000000000..ed97d539c0 --- /dev/null +++ b/roles/web-app-mediawiki/tasks/addons/VisualEditorPlus.yml @@ -0,0 +1 @@ +--- diff --git a/roles/web-app-mediawiki/tasks/main.yml b/roles/web-app-mediawiki/tasks/main.yml index 24f2993068..aa2875bffc 100644 --- a/roles/web-app-mediawiki/tasks/main.yml +++ b/roles/web-app-mediawiki/tasks/main.yml @@ -25,7 +25,7 @@ apply: delegate_to: "{{ MEDIAWIKI_HOST_NODE }}" when: - - MEDIAWIKI_OIDC_ENABLED | bool + - (MEDIAWIKI_OIDC_ENABLED | bool) or (MEDIAWIKI_LITELLM_ENABLED | bool) - IS_STACK_HOST | bool - name: "๐Ÿ“‚ Load update procedures for '{{ application_id }}'" @@ -38,5 +38,11 @@ (_ext_composer.changed | default(false)) or (_vendor.changed | default(false)) +- name: "๐Ÿค– Bind the native AI surface to the platform gateway" + include_tasks: utils/ai_gateway.yml + when: + - MEDIAWIKI_LITELLM_ENABLED | bool + - IS_STACK_HOST | bool + - name: "๐Ÿ“‚ Load admin setup procedures for '{{ application_id }}'" include_tasks: 04_admin.yml diff --git a/roles/web-app-mediawiki/tasks/utils/ai_gateway.yml b/roles/web-app-mediawiki/tasks/utils/ai_gateway.yml new file mode 100644 index 0000000000..5a85190b1c --- /dev/null +++ b/roles/web-app-mediawiki/tasks/utils/ai_gateway.yml @@ -0,0 +1,36 @@ +--- +- name: "๐Ÿ” Verify the gateway contract for {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-litellm/tasks/utils/consumer_contract.yml') }}" + +- name: "๐Ÿ”Ž MEDIAWIKI | Read back the configured AI provider and connection" + ansible.builtin.command: + argv: + - container + - exec + - --user + - "{{ MEDIAWIKI_USER }}" + - "{{ MEDIAWIKI_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + - "{{ [MEDIAWIKI_HTML_DIR, 'maintenance', 'run.php'] | path_join }}" + - getConfiguration + - --format=json + - --settings=wgAIEditingAssistantActiveProvider wgAIEditingAssistantActiveProviderConnection + register: mediawiki_ai_configuration + changed_when: false + run_once: true + delegate_to: "{{ MEDIAWIKI_HOST_NODE }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐Ÿ›‘ Refuse a MediaWiki AI provider that does not answer through the gateway" + ansible.builtin.assert: + that: + - (mediawiki_ai_configuration.stdout | from_json).wgAIEditingAssistantActiveProvider == MEDIAWIKI_LITELLM_PROVIDER + - ((mediawiki_ai_configuration.stdout | from_json).wgAIEditingAssistantActiveProviderConnection | from_json).url == LITELLM_OPENAI_BASE_LOCAL_URL + - ((mediawiki_ai_configuration.stdout | from_json).wgAIEditingAssistantActiveProviderConnection | from_json).model == LITELLM_CHAT_MODEL + fail_msg: >- + AIEditingAssistant still resolves provider + '{{ (mediawiki_ai_configuration.stdout | from_json).wgAIEditingAssistantActiveProvider }}' + to '{{ ((mediawiki_ai_configuration.stdout | from_json).wgAIEditingAssistantActiveProviderConnection | from_json).url }}' + with model '{{ ((mediawiki_ai_configuration.stdout | from_json).wgAIEditingAssistantActiveProviderConnection | from_json).model }}' + instead of {{ MEDIAWIKI_LITELLM_PROVIDER }} on {{ LITELLM_OPENAI_BASE_LOCAL_URL }} + with {{ LITELLM_CHAT_MODEL }}, so prompts would leave the deployment. diff --git a/roles/web-app-mediawiki/templates/LocalSettings.php.j2 b/roles/web-app-mediawiki/templates/LocalSettings.php.j2 index ff69101897..f0f5e7ab0b 100644 --- a/roles/web-app-mediawiki/templates/LocalSettings.php.j2 +++ b/roles/web-app-mediawiki/templates/LocalSettings.php.j2 @@ -2,6 +2,7 @@ # nocheck: comments-valid upstream MediaWiki LocalSettings layout, its inline setting docs are upstream's # Managed by Ansible ({{ SOFTWARE_NAME }}). # Do not edit manually; change the role/template instead. +# nocheck: comments-valid upstream MediaWiki LocalSettings.php reference documentation # # See includes/MainConfigSchema.php for all configurable settings # and their default values, but don't forget to make changes in _this_ @@ -133,6 +134,18 @@ wfLoadSkin( 'Vector' ); require_once '{{ MEDIAWIKI_LOCAL_PATH }}/oidc.php'; {% endif %} +{% if MEDIAWIKI_LITELLM_ENABLED | bool %} +if ( file_exists( "$IP/extensions/VisualEditorPlus/vendor/autoload.php" ) + && file_exists( "$IP/extensions/AIEditingAssistant/extension.json" ) ) { + wfLoadExtension( 'VisualEditor' ); + wfLoadExtension( 'VisualEditorPlus' ); + wfLoadExtension( 'AIEditingAssistant' ); + $wgAIEditingAssistantActiveProvider = '{{ MEDIAWIKI_LITELLM_PROVIDER }}'; + $wgAIEditingAssistantActiveProviderConnection = '{{ MEDIAWIKI_LITELLM_CONNECTION | to_json }}'; + $wgHTTPTimeout = {{ MEDIAWIKI_LITELLM_HTTP_TIMEOUT | int }}; +} +{% endif %} + {% if MODE_DEBUG | bool %} require_once '{{ MEDIAWIKI_LOCAL_PATH }}/debug.php'; {% endif %} diff --git a/roles/web-app-mediawiki/templates/playwright.env.j2 b/roles/web-app-mediawiki/templates/playwright.env.j2 index 1765d27035..4566bd05f5 100644 --- a/roles/web-app-mediawiki/templates/playwright.env.j2 +++ b/roles/web-app-mediawiki/templates/playwright.env.j2 @@ -2,6 +2,8 @@ ADMIN_PASSWORD={{ lookup('users', 'administrator').password | dotenv_quote }} ADMIN_USERNAME={{ lookup('users', 'administrator').username | dotenv_quote }} +AI_GATEWAY_BASE_URL={{ LITELLM_OPENAI_BASE_LOCAL_URL | dotenv_quote }} + APP_BASE_URL={{ lookup('tls', application_id, 'url.base') }} BIBER_PASSWORD={{ lookup('users', 'biber').password | dotenv_quote }} diff --git a/roles/web-app-mediawiki/templates/style.css.j2 b/roles/web-app-mediawiki/templates/style.css.j2 index b5b5fcfb1d..68379bc125 100644 --- a/roles/web-app-mediawiki/templates/style.css.j2 +++ b/roles/web-app-mediawiki/templates/style.css.j2 @@ -1,4 +1,4 @@ -/* MediaWiki (Vector 2022 + OOUI) color remap via Infinito.Nexus palette +/* MediaWiki (Vector 2022 + OOUI) color remap via {{ SOFTWARE_NAME }} palette - Keep changes scoped and variable-driven - Prefer variables over hard values - Avoid !important unless an inline style or strong OOUI rule requires it diff --git a/roles/web-app-mediawiki/vars/main.yml b/roles/web-app-mediawiki/vars/main.yml index 946744c15d..0cea35810f 100644 --- a/roles/web-app-mediawiki/vars/main.yml +++ b/roles/web-app-mediawiki/vars/main.yml @@ -38,10 +38,19 @@ MEDIAWIKI_OIDC_BUTTON_TEXT: "{{ OIDC.BUTTON_TEXT }}" MEDIAWIKI_OIDC_AUTOLOGIN: true MEDIAWIKI_OIDC_LOCALLOGIN: false +MEDIAWIKI_LITELLM_ENABLED: "{{ lookup('config', application_id, 'services.litellm.enabled') | bool }}" +MEDIAWIKI_LITELLM_PROVIDER: "open-ai" +MEDIAWIKI_LITELLM_CONNECTION: + url: "{{ LITELLM_OPENAI_BASE_LOCAL_URL }}" + endpoint: "chat/completions" + model: "{{ LITELLM_CHAT_MODEL }}" + secret: "{{ lookup('config', application_id, 'secrets.credentials.litellm_api_key') }}" +MEDIAWIKI_LITELLM_HTTP_TIMEOUT: 120 + MEDIAWIKI_EXT_BRANCH: "REL{{ (MEDIAWIKI_VERSION | string).split('.')[:2] | join('_') }}" MEDIAWIKI_EXT_CFG_BASE: "{{ [ MEDIAWIKI_CONFIG_DIR, 'mwext', MEDIAWIKI_EXT_BRANCH ] | path_join }}" MEDIAWIKI_EXT_HELPER_DIR: "{{ [ MEDIAWIKI_EXT_CFG_BASE, 'helpers' ] | path_join }}" -MEDIAWIKI_EXT_NAMES: "{{ lookup('config', application_id, 'addons').keys() | list }}" +MEDIAWIKI_EXT_NAMES: "{{ lookup('config', application_id, 'addons') | dict2items | selectattr('value.enabled') | map(attribute='key') | list }}" # nocheck: url MEDIAWIKI_EXT_URL_PREFIX: "https://codeload.github.com/wikimedia/mediawiki-extensions-" MEDIAWIKI_EXT_URL_SUFFIX: "/tar.gz/refs/heads/{{ MEDIAWIKI_EXT_BRANCH }}" diff --git a/roles/web-app-mig/README.md b/roles/web-app-mig/README.md index 8cc0112509..6554c4c575 100644 --- a/roles/web-app-mig/README.md +++ b/roles/web-app-mig/README.md @@ -74,19 +74,20 @@ Run the published image to provision the inventory and deploy MIG to a managed s ```bash APP=web-app-mig HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-mig/meta/info.yml b/roles/web-app-mig/meta/info.yml index 41e35060e2..015fcbd944 100644 --- a/roles/web-app-mig/meta/info.yml +++ b/roles/web-app-mig/meta/info.yml @@ -1,3 +1,4 @@ --- +# nocheck: info-media In-house Infinito.Nexus tool (Meta Infinite Graph) written by the same author; only a GitHub repo exists, no third-party vendor product homepage or official demo video. logo: class: fa-solid fa-brain diff --git a/roles/web-app-mig/meta/main.yml b/roles/web-app-mig/meta/main.yml index 0cb45c9585..5e10e18131 100644 --- a/roles/web-app-mig/meta/main.yml +++ b/roles/web-app-mig/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media In-house Infinito.Nexus tool (Meta Infinite Graph) written by the same author; only a GitHub repo exists, no third-party vendor product homepage or official demo video. galaxy_info: author: Kevin Veen-Birkenbach description: Interactive graph visualization of all Infinito.Nexus roles and their dependencies for architecture transparency diff --git a/roles/web-app-mig/meta/services.yml b/roles/web-app-mig/meta/services.yml index a21a0d5290..feb3a06616 100644 --- a/roles/web-app-mig/meta/services.yml +++ b/roles/web-app-mig/meta/services.yml @@ -34,6 +34,7 @@ mig: swarm: enabled: true image: ghcr.io/kevinveenbirkenbach/infinito-mig + # nocheck: docker-version -- this registry carries exactly 1 tag; the image is built from this project and has no release line yet version: latest name: mig min_storage: 1224MB diff --git a/roles/web-app-mini-qr/README.md b/roles/web-app-mini-qr/README.md index bbc72034d7..e7eda16ea4 100644 --- a/roles/web-app-mini-qr/README.md +++ b/roles/web-app-mini-qr/README.md @@ -77,19 +77,20 @@ Run the published image to provision the inventory and deploy Mini-QR to a manag ```bash APP=web-app-mini-qr HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-mini-qr/meta/info.yml b/roles/web-app-mini-qr/meta/info.yml index 99902de766..57d7d68247 100644 --- a/roles/web-app-mini-qr/meta/info.yml +++ b/roles/web-app-mini-qr/meta/info.yml @@ -1,4 +1,5 @@ --- +# nocheck: info-media no official demo video logo: class: fa-solid fa-qrcode homepage: https://github.com/lyqht/mini-qr diff --git a/roles/web-app-mini-qr/meta/main.yml b/roles/web-app-mini-qr/meta/main.yml index 0358ab1177..1d20eb6b2d 100644 --- a/roles/web-app-mini-qr/meta/main.yml +++ b/roles/web-app-mini-qr/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Self-hosted browser tool for generating QR codes from text or URLs with privacy-friendly local rendering diff --git a/roles/web-app-minio/README.md b/roles/web-app-minio/README.md index 95eb6c76a5..2c4ebe6615 100644 --- a/roles/web-app-minio/README.md +++ b/roles/web-app-minio/README.md @@ -86,19 +86,20 @@ Run the published image to provision the inventory and deploy MinIO to a managed ```bash APP=web-app-minio HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-mobilizon/README.md b/roles/web-app-mobilizon/README.md index b147fce2ad..949fcd1bc4 100644 --- a/roles/web-app-mobilizon/README.md +++ b/roles/web-app-mobilizon/README.md @@ -82,19 +82,20 @@ Run the published image to provision the inventory and deploy Mobilizon to a man ```bash APP=web-app-mobilizon HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-mobilizon/meta/info.yml b/roles/web-app-mobilizon/meta/info.yml index 2cfaed37cd..f6b20c201a 100644 --- a/roles/web-app-mobilizon/meta/info.yml +++ b/roles/web-app-mobilizon/meta/info.yml @@ -2,4 +2,4 @@ logo: class: fa-solid fa-calendar-days homepage: https://joinmobilizon.org/ -video: https://framatube.org/c/mobilizon/videos +video: https://framatube.org/w/2mtugeJXaihsQnTHVWHf2E diff --git a/roles/web-app-mobilizon/meta/volumes.yml b/roles/web-app-mobilizon/meta/volumes.yml index 61ffc005c4..46dd09c772 100644 --- a/roles/web-app-mobilizon/meta/volumes.yml +++ b/roles/web-app-mobilizon/meta/volumes.yml @@ -1,4 +1,5 @@ --- +# nocheck: config-volume-secret Mobilizon evaluates one Elixir config file at boot, so the OIDC client secret is an expression inside the same document as every other setting; there is no separate secret file the release reads. uploads: type: volume name: mobilizon_uploads diff --git a/roles/web-app-moodle/README.md b/roles/web-app-moodle/README.md index 9631b2b9a3..5627a61d51 100644 --- a/roles/web-app-moodle/README.md +++ b/roles/web-app-moodle/README.md @@ -15,19 +15,24 @@ The diagram places Moodle in the Infinito.Nexus cosmos: the components it deploy ```mermaid flowchart LR subgraph deps [Dependencies] + dep_svc_ai_litellm["svc-ai-litellm ๐Ÿณ๐Ÿ"] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local ๐Ÿ’ป"] dep_svc_db_mariadb["svc-db-mariadb ๐Ÿณ๐Ÿ"] dep_svc_db_openldap["svc-db-openldap ๐Ÿณ๐Ÿ"] dep_svc_net_tor["svc-net-tor ๐Ÿณ๐Ÿ"] dep_web_app_dashboard["web-app-dashboard ๐Ÿณ๐Ÿ"] + dep_web_app_hermes["web-app-hermes ๐Ÿณ๐Ÿ"] dep_web_app_keycloak["web-app-keycloak ๐Ÿณ๐Ÿ"] dep_web_app_mailu["web-app-mailu ๐Ÿณ๐Ÿ"] dep_web_app_matomo["web-app-matomo ๐Ÿณ๐Ÿ"] + dep_web_app_openclaw["web-app-openclaw ๐Ÿณ๐Ÿ"] + dep_web_app_openwebui["web-app-openwebui ๐Ÿณ๐Ÿ"] dep_web_app_prometheus["web-app-prometheus ๐Ÿณ๐Ÿ"] dep_web_svc_css["web-svc-css ๐Ÿ’ป"] dep_web_svc_logout["web-svc-logout ๐Ÿณ๐Ÿ"] end subgraph role [web-app-moodle ๐Ÿณ๐Ÿ] + svc_litellm["litellm"] svc_sso["sso"] svc_logout["logout"] svc_dashboard["dashboard"] @@ -42,15 +47,23 @@ flowchart LR svc_prometheus["prometheus"] svc_tor["tor"] svc_container_backup["container_backup"] + svc_openwebui["openwebui"] + svc_hermes["hermes"] + svc_openclaw["openclaw"] + svc_flowise["flowise โŒ"] end + dep_svc_ai_litellm -. "0..1" .-> svc_litellm dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup dep_svc_db_mariadb -. "0..1" .-> svc_mariadb dep_svc_db_openldap -. "0..1" .-> svc_ldap dep_svc_net_tor -. "0..1" .-> svc_tor dep_web_app_dashboard -. "0..1" .-> svc_dashboard + dep_web_app_hermes -. "0..1" .-> svc_hermes dep_web_app_keycloak -. "0..1" .-> svc_sso dep_web_app_mailu -. "0..1" .-> svc_email dep_web_app_matomo -. "0..1" .-> svc_matomo + dep_web_app_openclaw -. "0..1" .-> svc_openclaw + dep_web_app_openwebui -. "0..1" .-> svc_openwebui dep_web_app_prometheus -. "0..1" .-> svc_prometheus dep_web_svc_css -. "0..1" .-> svc_css dep_web_svc_logout -. "0..1" .-> svc_logout @@ -87,24 +100,77 @@ Run the published image to provision the inventory and deploy Moodle to a manage ```bash APP=web-app-moodle HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' ``` +## MCP server + +The role exposes a Model Context Protocol surface through the `webservice_mcp` protocol plugin, baked into the image at `webservice/mcp` and served by the NGINX sidecar. + +| Property | Value | +| --- | --- | +| Endpoint | `/webservice/mcp/server.php` on the canonical domain | +| Container URL | `http://nginx:80/webservice/mcp/server.php` on the shared MCP overlay | +| Transport | Streamable HTTP (JSON-RPC 2.0 over `POST`) | +| Auth | `Authorization: Bearer `, a Moodle web-service token | +| Subject | the `administrator` account | +| Default state | off; `mcp.enabled` turns true when `web-app-hermes`, `web-app-openclaw` or `web-app-openwebui` is in the inventory | + +Provisioning runs in `tasks/utils/mcp.yml`: it copies the plugin into the code volume, runs `admin/cli/upgrade.php`, enables `enablewebservices`, appends `mcp` to `webserviceprotocols`, creates the `infinito_mcp` external service, attaches the read-only functions, mints the permanent token and stores it under `users.administrator.tokens['web-app-moodle']`. + +Tool categories exposed by the external service: + +- site metadata (`core_webservice_get_site_info`) +- course catalogue (`core_course_get_courses`, `core_enrol_get_users_courses`) +- user lookup (`core_user_get_users_by_field`) +- calendar events (`core_calendar_get_calendar_events`) + +All of them are read-only; `mcp.tools.mutating_tools_enabled` is `false` and no write function is attached. + +### Default state + +Off. `mcp.enabled` is true only while `web-app-hermes`, `web-app-openclaw` or `web-app-openwebui` is part of the deployment. + +### Authorization subject + +`auth_subject: administrator`: the web-service token is issued against the +administrator account, so a call carries that account's rights regardless of who +asked the client. The attached functions are read-only, which bounds what those +rights can do here. Reaching the tool server is gated on the role's `mcp` RBAC +group. + +### Canonical origin + +Moodle compares every request against `$CFG->wwwroot`. A probe that reaches the endpoint over the internal HTTP origin is answered with a redirect to the canonical HTTPS URL rather than with JSON, so callers must send the canonical `Host` header and `X-Forwarded-Proto: https`. + +### How to disable + +Remove the MCP client roles, or pin `mcp.enabled: false` for this role. The web-service token is then not issued and the protocol plugin stays unconfigured. + +## Outbound HTTP policy + +Moodle ships a cURL blocklist that rejects every request to `10.0.0.0/8`, `172.16.0.0/12` and `192.168.0.0/16`, and only permits ports 80 and 443. Both settings gate `\core\files\curl_security_helper`, which `auth_oidc` consults for the Keycloak token exchange and `\core\http_client` consults for the AI provider request. The gateway answers on `192.168.80.0/24`, and on an onion node `container_extra_hosts` pins the Keycloak authority to the Docker bridge gateway, which `NETWORK_DOCKER_ADDRESS_POOLS` draws from `10.208.0.0/12`. With the upstream defaults the OIDC login obtains no token and the AI provider cannot reach the gateway. + +`tasks/01_manager_ops.yml` therefore rewrites `curlsecurityblockedhosts` to `MOODLE_EGRESS_BLOCKED_HOSTS` and extends `curlsecurityallowedport` with the port of `MOODLE_LITELLM_CHAT_ENDPOINT` when the `litellm` service is enabled. Loopback, `0.0.0.0` and the cloud metadata address stay blocked; the RFC1918 ranges are opened. The Docker address pool and the bridge gateway that serves the pinned Keycloak authority both live inside them. + +This is an accepted trade-off, not an oversight. Moodle offers no allowlist, so a single internal host cannot be permitted without unblocking the range it sits in. The cost is that any account holding a URL-fetching capability, such as `block/rss_client:myaddinstance` or a `repository/url` instance, can make the server issue requests to sibling containers. Grant those capabilities only to roles you trust with that reach, or keep the upstream blocklist and accept that SSO login and the AI surface do not work. + ## Image source This role builds its own Moodle image from upstream Moodle source on top of the official `php:8.3-fpm` base. @@ -117,7 +183,7 @@ This role builds its own Moodle image from upstream Moodle source on top of the ## Persona contract opt-outs -This role declares `PERSONA_ADMINISTRATOR_BLOCKED` in `templates/playwright.env.j2`. Moodle's site administrator is created by `install_database.php` in `tasks/01_manager_ops.yml` with `credentials.user_password`, a role-local secret the Playwright env never renders โ€” `ADMIN_PASSWORD` carries the Keycloak secret instead. In the SSO variant `tasks/04_oidc.yml` sets `alternateloginurl` so `/login/index.php` bounces to the OIDC plugin and rewrites every `mdl_user` row to `auth='oidc'`, so no form accepts either secret; the SSO-off variants in `meta/variants.yml` have no OIDC chain to substitute. One env file is rendered per role, not per variant, so the flag has to hold for the worst case. +This role declares `PERSONA_ADMINISTRATOR_BLOCKED` in `templates/playwright.env.j2`. Moodle's site administrator is created by `install_database.php` in `tasks/01_manager_ops.yml` and realigned on every pass, both from the `administrator` user, so the native form and the identity provider carry one secret. In the SSO variant `tasks/04_oidc.yml` sets `alternateloginurl` so `/login/index.php` bounces to the OIDC plugin and rewrites every `mdl_user` row to `auth='oidc'`, so no form accepts either secret; the SSO-off variants in `meta/variants.yml` have no OIDC chain to substitute. One env file is rendered per role, not per variant, so the flag has to hold for the worst case. Biber keeps a runnable journey: `files/playwright/test-ldap-variant.js` drives the native LDAP-bind login and `files/playwright/test-profile-readonly.js` asserts the locked profile fields. The path back to the administrator persona is a deploy step that hands the site administrator a credential the persona env already carries. diff --git a/roles/web-app-moodle/files/Dockerfile b/roles/web-app-moodle/files/Dockerfile index ba07f38002..dc36c5be3a 100644 --- a/roles/web-app-moodle/files/Dockerfile +++ b/roles/web-app-moodle/files/Dockerfile @@ -20,26 +20,35 @@ FROM ${MOODLE_BASE_IMAGE}:${MOODLE_BASE_TAG} ARG MOODLE_CODE_DIR ARG MOODLE_DATA_DIR +ARG MOODLE_LOCAL_CACHE_DIR ARG MOODLE_SOURCE_DIR ARG MOODLE_RUNTIME_USER ARG MOODLE_OIDC_ENABLED ARG MOODLE_OIDC_PLUGIN_RELPATH +ARG MOODLE_MCP_ENABLED +ARG MOODLE_MCP_PLUGIN_RELPATH +ARG MOODLE_MCP_PLUGIN_ARCHIVE_URL +ARG MOODLE_OIDC_PLUGIN_ARCHIVE_URL ARG MOODLE_RELEASE ARG MOODLE_TARBALL_URL -ARG MOODLE_TARBALL_FILENAME ARG MOODLE_VERSION_FILE ARG MOODLE_AUTH_SUBDIR +ARG MOODLE_WEBSERVICE_SUBDIR ENV MOODLE_CODE_DIR=${MOODLE_CODE_DIR} \ MOODLE_DATA_DIR=${MOODLE_DATA_DIR} \ + MOODLE_LOCAL_CACHE_DIR=${MOODLE_LOCAL_CACHE_DIR} \ MOODLE_SOURCE_DIR=${MOODLE_SOURCE_DIR} \ MOODLE_RUNTIME_USER=${MOODLE_RUNTIME_USER} \ MOODLE_OIDC_PLUGIN_RELPATH=${MOODLE_OIDC_PLUGIN_RELPATH} \ + MOODLE_MCP_PLUGIN_RELPATH=${MOODLE_MCP_PLUGIN_RELPATH} \ + MOODLE_MCP_PLUGIN_ARCHIVE_URL=${MOODLE_MCP_PLUGIN_ARCHIVE_URL} \ + MOODLE_OIDC_PLUGIN_ARCHIVE_URL=${MOODLE_OIDC_PLUGIN_ARCHIVE_URL} \ MOODLE_RELEASE=${MOODLE_RELEASE} \ MOODLE_TARBALL_URL=${MOODLE_TARBALL_URL} \ - MOODLE_TARBALL_FILENAME=${MOODLE_TARBALL_FILENAME} \ MOODLE_VERSION_FILE=${MOODLE_VERSION_FILE} \ - MOODLE_AUTH_SUBDIR=${MOODLE_AUTH_SUBDIR} + MOODLE_AUTH_SUBDIR=${MOODLE_AUTH_SUBDIR} \ + MOODLE_WEBSERVICE_SUBDIR=${MOODLE_WEBSERVICE_SUBDIR} # hadolint ignore=DL3008 RUN rm -rf /var/lib/apt/lists/* \ @@ -96,6 +105,12 @@ RUN if [ "${MOODLE_OIDC_ENABLED}" = "1" ] || [ "${MOODLE_OIDC_ENABLED}" = "true" fi \ && rm /tmp/install-auth-oidc.sh +COPY build/install/webservice-mcp.sh /tmp/install-webservice-mcp.sh +RUN if [ "${MOODLE_MCP_ENABLED}" = "1" ] || [ "${MOODLE_MCP_ENABLED}" = "true" ]; then \ + bash /tmp/install-webservice-mcp.sh; \ + fi \ + && rm /tmp/install-webservice-mcp.sh + COPY build/config.php ${MOODLE_SOURCE_DIR}/config.php RUN chown ${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER} ${MOODLE_SOURCE_DIR}/config.php \ && chmod 0640 ${MOODLE_SOURCE_DIR}/config.php diff --git a/roles/web-app-moodle/files/build/config.php b/roles/web-app-moodle/files/build/config.php index 42d4bde9f7..5434affc26 100644 --- a/roles/web-app-moodle/files/build/config.php +++ b/roles/web-app-moodle/files/build/config.php @@ -37,12 +37,19 @@ $CFG->dboptions = array( $CFG->wwwroot = moodle_env('MOODLE_WWWROOT'); $CFG->dataroot = moodle_env('MOODLE_DATAROOT'); +$CFG->localcachedir = moodle_env('MOODLE_LOCALCACHEDIR'); $CFG->admin = 'admin'; $CFG->directorypermissions = 02770; $CFG->reverseproxy = moodle_env_bool('MOODLE_REVERSEPROXY'); $CFG->sslproxy = moodle_env_bool('MOODLE_SSLPROXY'); +$_moodle_internal_host = moodle_env('MOODLE_INTERNAL_HOST'); +if (explode(':', $_SERVER['HTTP_HOST'] ?? '', 2)[0] === $_moodle_internal_host) { + $_SERVER['HTTP_HOST'] = parse_url($CFG->wwwroot, PHP_URL_HOST); + $_SERVER['SERVER_NAME'] = $_SERVER['HTTP_HOST']; +} + $_moodle_debug = moodle_env_bool('MOODLE_DEBUG'); $CFG->debug = $_moodle_debug ? 32767 : 0; $CFG->debugdisplay = $_moodle_debug; diff --git a/roles/web-app-moodle/files/build/install/auth-oidc.sh b/roles/web-app-moodle/files/build/install/auth-oidc.sh index f0f6b63202..8b9628b22c 100644 --- a/roles/web-app-moodle/files/build/install/auth-oidc.sh +++ b/roles/web-app-moodle/files/build/install/auth-oidc.sh @@ -1,34 +1,22 @@ #!/bin/bash -# Install Microsoft auth_oidc plugin pinned to the highest tag matching -# the Moodle major.minor we are building. All values come from env -# vars exported by the Dockerfile (single source of truth: +# Install the Microsoft auth_oidc plugin. All values come from env vars +# exported by the Dockerfile (single source of truth: # roles/web-app-moodle/vars/main.yml). set -euxo pipefail : "${MOODLE_SOURCE_DIR:?required}" : "${MOODLE_OIDC_PLUGIN_RELPATH:?required}" -: "${MOODLE_RELEASE:?required}" +: "${MOODLE_OIDC_PLUGIN_ARCHIVE_URL:?required}" : "${MOODLE_AUTH_SUBDIR:?required}" -MOODLE_VER="$(printf '%s' "${MOODLE_RELEASE}" | sed -E 's/^([0-9]+\.[0-9]+).*/\1/')" - PLUGIN_DIR="${MOODLE_SOURCE_DIR}/${MOODLE_OIDC_PLUGIN_RELPATH}" ZIP_PATH="$(mktemp -t auth-oidc.XXXXXX.zip)" EXTRACT_DIR="$(mktemp -d -t auth-oidc-extract.XXXXXX)" trap 'rm -rf "${ZIP_PATH}" "${EXTRACT_DIR}"' EXIT -VERSION="$(curl --connect-timeout 5 --max-time 60 -sfSL https://api.github.com/repos/microsoft/moodle-auth_oidc/tags \ - | jq -r '.[].name' \ - | grep -E "^v${MOODLE_VER}\." \ - | sort -Vr \ - | head -n1)" - -[ -n "${VERSION}" ] || { echo "no auth_oidc tag found for Moodle ${MOODLE_VER}" >&2; exit 1; } - -echo "Installing auth_oidc ${VERSION} (Moodle ${MOODLE_VER})" test -d "${MOODLE_SOURCE_DIR}/${MOODLE_AUTH_SUBDIR}" -curl --connect-timeout 5 --max-time 300 --retry 3 --retry-all-errors --retry-delay 2 -fSL -o "${ZIP_PATH}" "https://github.com/microsoft/moodle-auth_oidc/archive/refs/tags/${VERSION}.zip" +curl --connect-timeout 5 --max-time 300 --retry 3 --retry-all-errors --retry-delay 2 -fSL -o "${ZIP_PATH}" "${MOODLE_OIDC_PLUGIN_ARCHIVE_URL}" unzip -q "${ZIP_PATH}" -d "${EXTRACT_DIR}" rm -rf "${PLUGIN_DIR}" diff --git a/roles/web-app-moodle/files/build/install/moodle-source.sh b/roles/web-app-moodle/files/build/install/moodle-source.sh index 73fc66278d..8674cbc69f 100644 --- a/roles/web-app-moodle/files/build/install/moodle-source.sh +++ b/roles/web-app-moodle/files/build/install/moodle-source.sh @@ -10,21 +10,18 @@ set -euxo pipefail : "${MOODLE_SOURCE_DIR:?required}" : "${MOODLE_RUNTIME_USER:?required}" : "${MOODLE_TARBALL_URL:?required}" -: "${MOODLE_TARBALL_FILENAME:?required}" : "${MOODLE_VERSION_FILE:?required}" : "${MOODLE_AUTH_SUBDIR:?required}" -EXTRACT_DIR="$(mktemp -d -t moodle-extract.XXXXXX)" TARBALL_PATH="$(mktemp -t moodle-tarball.XXXXXX)" -trap 'rm -rf "${EXTRACT_DIR}" "${TARBALL_PATH}"' EXIT +trap 'rm -rf "${TARBALL_PATH}"' EXIT curl --connect-timeout 5 --max-time 600 --retry 3 --retry-all-errors --retry-delay 2 -fSL -o "${TARBALL_PATH}" "${MOODLE_TARBALL_URL}" file "${TARBALL_PATH}" rm -rf "${MOODLE_SOURCE_DIR}" mkdir -p "${MOODLE_SOURCE_DIR}" -tar -xzf "${TARBALL_PATH}" -C "${EXTRACT_DIR}" -cp -a "${EXTRACT_DIR}/moodle/." "${MOODLE_SOURCE_DIR}/" +tar -xzf "${TARBALL_PATH}" --strip-components=1 -C "${MOODLE_SOURCE_DIR}" test -d "${MOODLE_SOURCE_DIR}/${MOODLE_AUTH_SUBDIR}" test -f "${MOODLE_SOURCE_DIR}/${MOODLE_VERSION_FILE}" diff --git a/roles/web-app-moodle/files/build/install/webservice-mcp.sh b/roles/web-app-moodle/files/build/install/webservice-mcp.sh new file mode 100644 index 0000000000..7c305d5a98 --- /dev/null +++ b/roles/web-app-moodle/files/build/install/webservice-mcp.sh @@ -0,0 +1,23 @@ +#!/bin/bash +set -euxo pipefail + +: "${MOODLE_SOURCE_DIR:?required}" +: "${MOODLE_WEBSERVICE_SUBDIR:?required}" +: "${MOODLE_MCP_PLUGIN_RELPATH:?required}" +: "${MOODLE_MCP_PLUGIN_ARCHIVE_URL:?required}" + +PLUGIN_DIR="${MOODLE_SOURCE_DIR}/${MOODLE_MCP_PLUGIN_RELPATH}" +ZIP_PATH="$(mktemp -t webservice-mcp.XXXXXX.zip)" +EXTRACT_DIR="$(mktemp -d -t webservice-mcp-extract.XXXXXX)" +trap 'rm -rf "${ZIP_PATH}" "${EXTRACT_DIR}"' EXIT + +test -d "${MOODLE_SOURCE_DIR}/${MOODLE_WEBSERVICE_SUBDIR}" + +curl --connect-timeout 5 --max-time 300 --retry 3 --retry-all-errors --retry-delay 2 -fSL -o "${ZIP_PATH}" "${MOODLE_MCP_PLUGIN_ARCHIVE_URL}" +unzip -q "${ZIP_PATH}" -d "${EXTRACT_DIR}" +rm -rf "${PLUGIN_DIR}" + +SRC="$(find "${EXTRACT_DIR}" -maxdepth 1 -type d -name 'moodle-webservice_mcp-*' | sort | head -n1)" +[ -n "${SRC}" ] || { echo "webservice_mcp unpack produced no directory" >&2; exit 1; } + +mv "${SRC}" "${PLUGIN_DIR}" diff --git a/roles/web-app-moodle/files/build/moodle-entrypoint.sh b/roles/web-app-moodle/files/build/moodle-entrypoint.sh index b7279fc4af..8474a21407 100644 --- a/roles/web-app-moodle/files/build/moodle-entrypoint.sh +++ b/roles/web-app-moodle/files/build/moodle-entrypoint.sh @@ -10,6 +10,7 @@ set -euo pipefail : "${MOODLE_CODE_DIR:?required}" : "${MOODLE_DATA_DIR:?required}" +: "${MOODLE_LOCAL_CACHE_DIR:?required}" : "${MOODLE_SOURCE_DIR:?required}" : "${MOODLE_RUNTIME_USER:?required}" : "${MOODLE_VERSION_FILE:?required}" @@ -20,6 +21,11 @@ MOODLE_BOOTSTRAP_LOCK="${MOODLE_CODE_DIR}/.bootstrap.lock" mkdir -p "${MOODLE_DATA_DIR}" chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_DATA_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error +mkdir -p "${MOODLE_LOCAL_CACHE_DIR}" +if [ "$(id -u)" -eq 0 ]; then + chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_LOCAL_CACHE_DIR}" +fi + moodle_bootstrap_code_dir() { if [ -f "${MOODLE_BOOTSTRAP_SENTINEL}" ]; then return 0 @@ -33,6 +39,17 @@ moodle_bootstrap_code_dir() { touch "${MOODLE_BOOTSTRAP_SENTINEL}" } +moodle_refresh_config() { + if [ ! -f "${MOODLE_SOURCE_DIR}/config.php" ]; then + return 0 + fi + cp -f "${MOODLE_SOURCE_DIR}/config.php" "${MOODLE_CODE_DIR}/config.php" + if [ "$(id -u)" -eq 0 ]; then + chown "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_CODE_DIR}/config.php" + chmod 0640 "${MOODLE_CODE_DIR}/config.php" + fi +} + mkdir -p "${MOODLE_CODE_DIR}" while [ ! -f "${MOODLE_BOOTSTRAP_SENTINEL}" ]; do exec 9>>"${MOODLE_BOOTSTRAP_LOCK}" @@ -44,6 +61,8 @@ while [ ! -f "${MOODLE_BOOTSTRAP_SENTINEL}" ]; do exec 9>&- done +moodle_refresh_config + if [ "$(id -u)" -eq 0 ] && [ "${1:-}" != "php-fpm" ]; then exec gosu "${MOODLE_RUNTIME_USER}" "$@" fi diff --git a/roles/web-app-moodle/files/php/provision_mcp.php b/roles/web-app-moodle/files/php/provision_mcp.php new file mode 100644 index 0000000000..37c7d34773 --- /dev/null +++ b/roles/web-app-moodle/files/php/provision_mcp.php @@ -0,0 +1,96 @@ +libdir . '/externallib.php'); +require_once($CFG->dirroot . '/webservice/lib.php'); + +$shortname = (string) getenv('MCP_SERVICE_SHORTNAME'); +$servicename = (string) getenv('MCP_SERVICE_NAME'); +$functions = array_filter(array_map('trim', explode(',', (string) getenv('MCP_SERVICE_FUNCTIONS')))); + +set_config('enablewebservices', 1); + +$protocols = array_filter(array_map('trim', explode(',', (string) get_config('core', 'webserviceprotocols')))); +if (!in_array('mcp', $protocols, true)) { + $protocols[] = 'mcp'; + set_config('webserviceprotocols', implode(',', $protocols)); +} + +$webservice = new webservice(); +$service = $webservice->get_external_service_by_shortname($shortname); +if (!$service) { + $webservice->add_external_service((object) [ + 'name' => $servicename, + 'shortname' => $shortname, + 'enabled' => 1, + 'restrictedusers' => 0, + 'downloadfiles' => 0, + 'uploadfiles' => 0, + ]); + $service = $webservice->get_external_service_by_shortname($shortname, MUST_EXIST); +} + +foreach ($functions as $function) { + if (!$DB->record_exists('external_functions', ['name' => $function])) { + continue; + } + if (!$webservice->service_function_exists($function, $service->id)) { + $webservice->add_external_function_to_service($function, $service->id); + } +} + +require_once($CFG->dirroot . '/user/lib.php'); + +$username = (string) getenv('MCP_ACCOUNT_USERNAME'); +$capabilities = array_filter(array_map('trim', explode(',', (string) getenv('MCP_ROLE_CAPABILITIES')))); +$systemcontext = context_system::instance(); + +$account = $DB->get_record('user', [ + 'username' => $username, + 'mnethostid' => $CFG->mnet_localhost_id, +]); +if (!$account) { + $new = new stdClass(); + $new->username = $username; + $new->email = (string) getenv('MCP_ACCOUNT_EMAIL'); + $new->password = (string) getenv('MCP_ACCOUNT_PASSWORD'); + $new->firstname = 'Infinito'; + $new->lastname = 'MCP'; + $new->auth = 'manual'; + $new->confirmed = 1; + $new->mnethostid = $CFG->mnet_localhost_id; + $accountid = user_create_user($new, true, false); + $account = $DB->get_record('user', ['id' => $accountid], '*', MUST_EXIST); +} + +$roleshortname = (string) getenv('MCP_ROLE_SHORTNAME'); +$roleid = $DB->get_field('role', 'id', ['shortname' => $roleshortname]); +if (!$roleid) { + $roleid = create_role((string) getenv('MCP_ROLE_NAME'), $roleshortname, '', 'user'); + set_role_contextlevels($roleid, [CONTEXT_SYSTEM]); +} +foreach ($capabilities as $capability) { + assign_capability($capability, CAP_ALLOW, $roleid, $systemcontext->id, true); +} +role_assign($roleid, $account->id, $systemcontext->id); + +$token = $DB->get_field('external_tokens', 'token', [ + 'externalserviceid' => $service->id, + 'userid' => $account->id, + 'tokentype' => EXTERNAL_TOKEN_PERMANENT, +], IGNORE_MULTIPLE); + +if (!$token) { + $token = external_generate_token( + EXTERNAL_TOKEN_PERMANENT, + $service->id, + $account->id, + $systemcontext + ); +} + +echo $token . PHP_EOL; diff --git a/roles/web-app-moodle/files/playwright/addons/auth_oidc.spec.js b/roles/web-app-moodle/files/playwright/addons/auth_oidc.spec.js new file mode 100644 index 0000000000..161d4fdde8 --- /dev/null +++ b/roles/web-app-moodle/files/playwright/addons/auth_oidc.spec.js @@ -0,0 +1,37 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("../timeouts"); +const { skipUnlessAddonEnabled } = require("../addon-gating"); +const { skipUnlessServiceEnabled } = require("../service-gating"); +const { gotoOnion } = require("../personas"); + +test.use({ ignoreHTTPSErrors: true }); + +test("addon auth_oidc: the login page bounces to the Keycloak authorization endpoint with the OAuth client", async ({ page }) => { + skipUnlessAddonEnabled("auth_oidc"); + skipUnlessServiceEnabled("sso"); + + const appBaseUrl = (process.env.APP_BASE_URL || "").replace(/\/$/, ""); + test.skip(!appBaseUrl, "APP_BASE_URL not set for this role"); + + await page.context().clearCookies(); + await gotoOnion(page, `${appBaseUrl}/login/index.php`, { waitUntil: "domcontentloaded" }).catch(() => {}); + await page.waitForURL(/openid-connect\/auth/i, { timeout: resolveTimeout(30_000) }).catch(() => {}); + + const target = page.url(); + expect( + target, + "Moodle /login/index.php must land on the Keycloak openid-connect authorization endpoint: auth_oidc installed under auth/oidc and alternateloginurl pointed at it", + ).toMatch(/openid-connect\/auth/i); + + const authUrl = new URL(target); + expect( + (authUrl.searchParams.get("client_id") || "").length, + "Keycloak authorization request from Moodle must carry the configured OAuth client_id", + ).toBeGreaterThan(0); + + const redirectUri = authUrl.searchParams.get("redirect_uri") || ""; + expect( + /auth\/oidc/i.test(redirectUri), + `Authorization request redirect_uri must point back at the Moodle auth_oidc callback (got: ${redirectUri || ""})`, + ).toBe(true); +}); diff --git a/roles/web-app-moodle/files/playwright/playwright.spec.js b/roles/web-app-moodle/files/playwright/playwright.spec.js index 6930b62958..7c357e85f4 100644 --- a/roles/web-app-moodle/files/playwright/playwright.spec.js +++ b/roles/web-app-moodle/files/playwright/playwright.spec.js @@ -13,3 +13,5 @@ require("./test-keycloak-scope").register(shared); require("./test-lam-writethrough").register(shared); require("./test-administrator-persona").register(shared); require("./test-guest-persona").register(shared); +require("./test-mcp-guest").register(shared); +require("./test-litellm-gateway").register(shared); diff --git a/roles/web-app-moodle/files/playwright/test-keycloak-scope.js b/roles/web-app-moodle/files/playwright/test-keycloak-scope.js index c0282d078d..7a4588ad34 100644 --- a/roles/web-app-moodle/files/playwright/test-keycloak-scope.js +++ b/roles/web-app-moodle/files/playwright/test-keycloak-scope.js @@ -2,7 +2,7 @@ const { test, expect } = require("@playwright/test"); const { resolveTimeout } = require("./timeouts"); const { decodeDotenvQuotedValue, gotoOnion } = require("./personas"); -const moodleScopeName = decodeDotenvQuotedValue(process.env.MOODLE_OIDC_SCOPE_NAME || "moodle"); +const moodleScopeName = decodeDotenvQuotedValue(process.env.MOODLE_OIDC_SCOPE_NAME); exports.register = function (shared) { test.describe("moodle keycloak scope wiring (variant 0)", () => { diff --git a/roles/web-app-moodle/files/playwright/test-litellm-gateway.js b/roles/web-app-moodle/files/playwright/test-litellm-gateway.js new file mode 100644 index 0000000000..038d3c3c70 --- /dev/null +++ b/roles/web-app-moodle/files/playwright/test-litellm-gateway.js @@ -0,0 +1,165 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); +const { decodeDotenvQuotedValue, performKeycloakLogin, readEnv, gotoOnion } = require("./personas"); +const { skipUnlessServiceEnabled } = require("./service-gating"); + +const adminNativePassword = decodeDotenvQuotedValue(process.env.ADMIN_NATIVE_PASSWORD || ""); + +const ENDPOINT_FIELD = "#id_s_aiprovider_openai_action_generate_text_endpoint"; +const USER_MENU = ".usermenu, [data-region='user-menu-toggle'], a[href*='profile.php']"; +const GATEWAY_PROMPT = "Reply with the single word: pong"; + +/** + * Open an authenticated site-administrator session. + * + * `tasks/04_oidc.yml` rewrites `mdl_user.auth` to `oidc` for every account but + * `guest`, and `auth_oidc` grants a login only when the request carries an + * authorization code, so with the sso service enabled no password reaches the + * account through the native form. Without sso that task never runs, the + * accounts stay on `auth_manual` and the password `install_database.php` + * provisioned is the only way in. + * + * @param {import('@playwright/test').Page} page browser page to authenticate + * @param {object} shared role-shared env and persona helpers + */ +async function loginAsSiteAdmin(page, shared) { + if (shared.env.ssoEnabled) { + await gotoOnion(page, `${shared.env.moodleBaseUrl}/auth/oidc/?source=loginpage`, { + waitUntil: "domcontentloaded", + timeout: resolveTimeout(60_000), + }); + await performKeycloakLogin( + page, + shared.env.adminUsername, + shared.env.adminPassword, + readEnv("CANONICAL_DOMAIN"), + ); + } else { + expect( + adminNativePassword, + "ADMIN_NATIVE_PASSWORD must be rendered from the administrator user; with the sso service off it is the only secret that authenticates the Moodle site administrator", + ).toBeTruthy(); + + await gotoOnion(page, `${shared.env.moodleBaseUrl}/login/index.php`, { + waitUntil: "domcontentloaded", + timeout: resolveTimeout(60_000), + }); + await page + .locator("input[name='username'], input#username") + .first() + .fill(shared.env.adminUsername); + + const passwordInput = page + .locator( + ".toggle-sensitive-wrapper input[name='password'], .toggle-sensitive-wrapper input#password, input[name='password']", + ) + .first(); + await expect( + passwordInput, + "the native Moodle login form must expose a password field; its absence means the login page no longer serves the manual auth form", + ).toBeAttached({ timeout: resolveTimeout(30_000) }); + await expect(async () => { + await passwordInput.fill(adminNativePassword); + await expect(passwordInput).toHaveValue(adminNativePassword); + }).toPass({ timeout: resolveTimeout(30_000) }); + + await page.locator("#loginbtn, button[type='submit'], input[type='submit']").first().click(); + await page.waitForLoadState("load"); + } + + await expect( + page.locator(USER_MENU).first(), + "the site administrator must reach an authenticated session; a failure here means the auth chain the deploy configured does not admit the administrator account", + ).toBeVisible({ timeout: resolveTimeout(60_000) }); +} + +exports.register = function (shared) { + test("litellm: Moodle answers a prompt through the in-cluster gateway", async ({ page }) => { + skipUnlessServiceEnabled("litellm"); + test.setTimeout(resolveTimeout(240_000)); + + await loginAsSiteAdmin(page, shared); + + await gotoOnion( + page, + `${shared.env.moodleBaseUrl}/admin/settings.php?section=aiprovider_openai_generate_text`, + { waitUntil: "domcontentloaded", timeout: resolveTimeout(60_000) }, + ); + + const endpointField = page.locator(ENDPOINT_FIELD); + await expect( + endpointField, + "the aiprovider_openai generate_text settings page must render its API endpoint field; its absence means the provider was never configured or the session lacks moodle/site:config", + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + + const configuredEndpoint = ((await endpointField.inputValue()) || "").trim(); + expect( + configuredEndpoint, + "aiprovider_openai/action_generate_text_endpoint must be an http(s) URL written by the deploy, not the upstream api.openai.com default", + ).toMatch(/^https?:\/\/.+/i); + + const endpointHost = new URL(configuredEndpoint).hostname; + expect( + endpointHost, + `the generate_text endpoint host must be a bare in-cluster service name; the dotted host "${endpointHost}" gets completed by the container dns-search suffix and resolves through the public ingress, so the prompt would leave the deployment`, + ).not.toContain("."); + expect( + endpointHost, + "the generate_text endpoint must address the svc-ai-litellm gateway, not point back at Moodle itself", + ).not.toBe(new URL(shared.env.moodleBaseUrl).hostname); + + const bootstrap = await page.evaluate(() => ({ + sesskey: (window.M && window.M.cfg && window.M.cfg.sesskey) || "", + contextid: (window.M && window.M.cfg && window.M.cfg.contextid) || 0, + })); + expect( + bootstrap.sesskey, + "M.cfg.sesskey must be exposed on the admin page; without it Moodle rejects every /lib/ajax/service.php call", + ).toBeTruthy(); + expect( + bootstrap.contextid, + "M.cfg.contextid must be exposed so the AI placement runs in the context the admin page already validated", + ).toBeGreaterThan(0); + + const ajaxUrl = + `${shared.env.moodleBaseUrl}/lib/ajax/service.php` + + `?sesskey=${encodeURIComponent(bootstrap.sesskey)}&info=aiplacement_editor_generate_text`; + const response = await page.request.post(ajaxUrl, { + headers: { "Content-Type": "application/json" }, + data: [ + { + index: 0, + methodname: "aiplacement_editor_generate_text", + args: { contextid: bootstrap.contextid, prompttext: GATEWAY_PROMPT }, + }, + ], + timeout: resolveTimeout(180_000), + }); + + expect( + response.status(), + `the aiplacement_editor web service must answer 200; a non-200 means the placement is disabled or unavailable, so no AI surface reaches the provider (got ${response.status()})`, + ).toBe(200); + + const payload = await response.json(); + const entry = Array.isArray(payload) ? payload[0] : null; + expect( + entry, + `aiplacement_editor_generate_text must return exactly one result entry, got ${JSON.stringify(payload).slice(0, 400)}`, + ).toBeTruthy(); + expect( + entry.error, + `the placement call must not raise a Moodle exception, got ${JSON.stringify(entry.exception || entry).slice(0, 400)}`, + ).toBe(false); + + const result = entry.data; + expect( + result.success, + `the generate_text action must succeed; errorcode carries the gateway HTTP status, so 401 means the virtual key is wrong and 404 or 0 means the endpoint is unreachable (got ${JSON.stringify(result).slice(0, 400)})`, + ).toBe(true); + expect( + String(result.generatedcontent || "").trim().length, + "the gateway must return a non-empty completion, proving Moodle's AI placement had the prompt answered inside the deployment", + ).toBeGreaterThan(0); + }); +}; diff --git a/roles/web-app-moodle/files/playwright/test-mcp-guest.js b/roles/web-app-moodle/files/playwright/test-mcp-guest.js new file mode 100644 index 0000000000..f2e4a1aea6 --- /dev/null +++ b/roles/web-app-moodle/files/playwright/test-mcp-guest.js @@ -0,0 +1,42 @@ +const { test, expect } = require("@playwright/test"); +const { decodeDotenvQuotedValue } = require("./personas"); +const { skipUnlessServiceEnabled } = require("./service-gating"); +const { registerMcpDisabledState } = require("./mcp-endpoint"); + +const mcpEndpointPath = decodeDotenvQuotedValue(process.env.MCP_ENDPOINT_PATH || ""); + +exports.register = function (shared) { + test("guest: the MCP endpoint rejects unauthenticated access", async ({ page }) => { + skipUnlessServiceEnabled("mcp"); + + expect(mcpEndpointPath, "MCP_ENDPOINT_PATH must be set in the Playwright env file").toBeTruthy(); + + const endpointUrl = new URL(mcpEndpointPath, shared.env.moodleBaseUrl).toString(); + const response = await page.request.post(endpointUrl, { + failOnStatusCode: false, + headers: { + Accept: "application/json", + "Content-Type": "application/json", + }, + data: { jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }, + }); + + const status = response.status(); + const body = await response.text(); + const excerpt = body.slice(0, 200); + + expect(status, `${endpointUrl} must be served while the MCP service is enabled`).not.toBe(404); + expect( + body.includes('"result"'), + `an unauthenticated MCP probe must not be served a JSON-RPC result, got ${excerpt}`, + ).toBe(false); + expect( + status >= 400 || body.includes('"error"'), + `an unauthenticated MCP probe must be rejected, got ${status} with ${excerpt}`, + ).toBe(true); + }); + + registerMcpDisabledState(() => + new URL(mcpEndpointPath, shared.env.moodleBaseUrl).toString(), + ); +}; diff --git a/roles/web-app-moodle/files/test/.nocheck b/roles/web-app-moodle/files/test/.nocheck new file mode 100644 index 0000000000..2b9d82d840 --- /dev/null +++ b/roles/web-app-moodle/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; test-e2e-cli stages files/test/ by that fixed path. diff --git a/roles/web-app-moodle/files/test/test.sh b/roles/web-app-moodle/files/test/test.sh new file mode 100644 index 0000000000..7219bcca72 --- /dev/null +++ b/roles/web-app-moodle/files/test/test.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# CLI test for web-app-moodle: the MCP endpoint honours its declared contract. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +bash "${here}/shared/mcp/run.sh" diff --git a/roles/web-app-moodle/meta/addons/auth_oidc.yml b/roles/web-app-moodle/meta/addons/auth_oidc.yml new file mode 100644 index 0000000000..7315cb50f4 --- /dev/null +++ b/roles/web-app-moodle/meta/addons/auth_oidc.yml @@ -0,0 +1,12 @@ +--- +enabled: "{{ lookup('config', 'web-app-moodle', 'services.sso.enabled') | bool }}" +required: false +mechanism: plugin +source: upstream +version: "v4.5.8" +bridges: + - sso +update: + monitored: true + catalog: github-releases + upstream_id: microsoft/moodle-auth_oidc diff --git a/roles/web-app-moodle/meta/mcp.yml b/roles/web-app-moodle/meta/mcp.yml new file mode 100644 index 0000000000..34ac05769f --- /dev/null +++ b/roles/web-app-moodle/meta/mcp.yml @@ -0,0 +1,37 @@ +--- +classification: plugin_server +direction: server +source_url: https://moodle.org/plugins/webservice_mcp +transport: streamable_http +exposure: public +auth: bearer_token +auth_subject: service_account +implementation: plugin +credential: + owner: mcp-web-app-moodle + source: token_store + key: web-app-moodle +endpoint: + service_key: nginx + path: /webservice/mcp/server.php + port_key: http +limits: + request_bytes: 65536 + response_bytes: 1048576 + timeout_seconds: 15 + concurrent_requests: 4 + page_size: 100 + result_items: 500 + stream_seconds: 300 +tools: + read_probe: + tool: core_course_get_courses + arguments: {} + allowlist: + - core_calendar_get_calendar_events + - core_course_get_courses + - core_enrol_get_users_courses + - core_user_get_users_by_field + - core_webservice_get_site_info + read_only_default: true + mutating_tools_enabled: false diff --git a/roles/web-app-moodle/meta/networks.yml b/roles/web-app-moodle/meta/networks.yml index 1c20393d02..bf3863ce00 100644 --- a/roles/web-app-moodle/meta/networks.yml +++ b/roles/web-app-moodle/meta/networks.yml @@ -1,3 +1,9 @@ --- local: subnet: 192.168.39.0/24 +overlay: + modes: [compose, swarm] + topology: shared_net + aliases: ["nginx"] + consumer: + kind: mcp_client diff --git a/roles/web-app-moodle/meta/rbac.yml b/roles/web-app-moodle/meta/rbac.yml new file mode 100644 index 0000000000..084e6fbeca --- /dev/null +++ b/roles/web-app-moodle/meta/rbac.yml @@ -0,0 +1,4 @@ +--- +roles: + mcp: + description: Can drive this application through an MCP client, which acts with the credentials the deployment issued rather than the caller's own diff --git a/roles/web-app-moodle/meta/secrets.yml b/roles/web-app-moodle/meta/secrets.yml index 0abacf3ad8..3e849cac41 100644 --- a/roles/web-app-moodle/meta/secrets.yml +++ b/roles/web-app-moodle/meta/secrets.yml @@ -1,6 +1,7 @@ --- credentials: - user_password: - description: Initial password for the Moodle admin user - algorithm: sha256 - validation: ^[a-f0-9]{64}$ + litellm_api_key: + description: Per-consumer virtual key for the shared svc-ai-litellm gateway + algorithm: sk_prefixed + validation: + min_length: 50 diff --git a/roles/web-app-moodle/meta/services.yml b/roles/web-app-moodle/meta/services.yml index 4a2bd646fd..8d8a476113 100644 --- a/roles/web-app-moodle/meta/services.yml +++ b/roles/web-app-moodle/meta/services.yml @@ -1,4 +1,9 @@ --- +# nocheck: dynamic-flag - the gateway is a single shared instance, never deployed per consumer +litellm: + bond: 0.5 + enabled: "{{ LITELLM_USABLE }}" + shared: true # nocheck: seaweedfs-required โ€” object storage not implemented for this role sso: bond: 1 @@ -40,7 +45,6 @@ moodle: bond: 1 enabled: true # nocheck: dynamic-flag shared: true - branch: stable405 release: 4.5.11 image: php # nocheck: docker-version @@ -83,6 +87,9 @@ nginx: mem_reservation: 128m mem_limit: 256m pids_limit: 256 + ports: + internal: + http: 80 cron: name: moodle-cron custom: true @@ -114,3 +121,24 @@ container_backup: # nocheck: bond-baseline backup host joins outside the variant bond: 1 enabled: "{{ 'svc-bkp-volume-2-local' in group_names }}" shared: true +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openwebui: + bond: 0.5 + enabled: "{{ 'web-app-openwebui' in group_names }}" + shared: "{{ 'web-app-openwebui' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +hermes: + bond: 0.5 + enabled: "{{ 'web-app-hermes' in group_names }}" + shared: "{{ 'web-app-hermes' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openclaw: + bond: 0.5 + enabled: "{{ 'web-app-openclaw' in group_names }}" + shared: "{{ 'web-app-openclaw' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +# nocheck: dynamic-flag the entry refuses this client, so the link is off on every host and no group_names gate can decide it +flowise: + enabled: false + shared: false + mcp_consumer: false diff --git a/roles/web-app-moodle/meta/tests.yml b/roles/web-app-moodle/meta/tests.yml new file mode 100644 index 0000000000..28bea0efe2 --- /dev/null +++ b/roles/web-app-moodle/meta/tests.yml @@ -0,0 +1,3 @@ +--- +cli: + timeout: 900 diff --git a/roles/web-app-moodle/meta/users.yml b/roles/web-app-moodle/meta/users.yml index 6c31213ebc..c041216a59 100644 --- a/roles/web-app-moodle/meta/users.yml +++ b/roles/web-app-moodle/meta/users.yml @@ -1,2 +1,10 @@ --- administrator: {} +mcp-web-app-moodle: + firstname: Infinito + lastname: MCP + accounts: [] + password: + algorithm: strong_password + validation: "[^A-Za-z0-9]" + description: Account the Moodle web-service token is issued for; a token on the site administrator would bypass every capability check diff --git a/roles/web-app-moodle/meta/variants.yml b/roles/web-app-moodle/meta/variants.yml index fc0d35876c..37f229dd12 100644 --- a/roles/web-app-moodle/meta/variants.yml +++ b/roles/web-app-moodle/meta/variants.yml @@ -36,9 +36,63 @@ prometheus: enabled: true shared: true + litellm: + enabled: false tor: enabled: true + openwebui: + enabled: false + shared: false + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false +- services: + container_backup: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + css: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + dashboard: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + email: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + ldap: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + logout: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + mariadb: + shared: false # nocheck: variants-static-override backup shared stays literally true + matomo: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + sso: + enabled: true + shared: true + prometheus: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + litellm: + enabled: false + tor: + enabled: true + openwebui: + enabled: true + shared: true + hermes: + enabled: true + shared: true + openclaw: + enabled: true + shared: true - services: container_backup: enabled: false @@ -70,37 +124,16 @@ prometheus: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true + litellm: + enabled: true tor: enabled: true -- services: - container_backup: + openwebui: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true - css: + shared: false + hermes: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true - dashboard: + shared: false + openclaw: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true - email: - enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true - ldap: - enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true - logout: - enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true - mariadb: - shared: false # nocheck: variants-static-override backup shared stays literally true - matomo: - enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true - sso: - enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true - prometheus: - enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true - tor: - enabled: true + shared: false diff --git a/roles/web-app-moodle/meta/volumes.yml b/roles/web-app-moodle/meta/volumes.yml index 9b47498ff6..6019189890 100644 --- a/roles/web-app-moodle/meta/volumes.yml +++ b/roles/web-app-moodle/meta/volumes.yml @@ -11,6 +11,17 @@ data: target: &var_www_moodledata_target /var/www/moodledata - service: cron target: *var_www_moodledata_target +localcache: + type: volume + name: moodle_localcache + # nocheck: nfs-false-data-loss Reason: Moodle documents localcachedir as node-local and safe to delete, unlike cachedir and tempdir which stay on the shared dataroot + nfs: false + mounts: + - service: moodle + target: &moodle_localcache /var/www/moodlelocalcache + - service: cron + target: *moodle_localcache + code: type: volume name: moodle_code diff --git a/roles/web-app-moodle/tasks/00_core.yml b/roles/web-app-moodle/tasks/00_core.yml index 34bff24b08..2f50423a24 100644 --- a/roles/web-app-moodle/tasks/00_core.yml +++ b/roles/web-app-moodle/tasks/00_core.yml @@ -1,6 +1,10 @@ --- - include_tasks: utils/once/flag.yml +- name: "๐Ÿšฆ Declare the MCP edge limits before the vhost references them" + include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-webserver-core/tasks/utils/mcp_edge_limits.yml') }}" + when: MOODLE_MCP_ENABLED | bool + - name: "๐Ÿงฉ load docker, db and proxy for {{ application_id }}" include_role: name: sys-stk-full diff --git a/roles/web-app-moodle/tasks/01_manager_ops.yml b/roles/web-app-moodle/tasks/01_manager_ops.yml index 8b22b3e9ae..078f32c1ca 100644 --- a/roles/web-app-moodle/tasks/01_manager_ops.yml +++ b/roles/web-app-moodle/tasks/01_manager_ops.yml @@ -31,12 +31,15 @@ container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} php {{ MOODLE_CLI_DIR }}/install_database.php --agree-license - --adminuser={{ lookup('config', application_id, 'users.administrator.username') }} - --adminpass={{ lookup('config', application_id, 'secrets.credentials.user_password') | quote }} - --adminemail={{ lookup('config', application_id, 'users.administrator.email') }} + --adminuser={{ MOODLE_ADMIN_USERNAME | quote }} + --adminpass={{ MOODLE_ADMIN_PASSWORD | quote }} + --adminemail={{ MOODLE_ADMIN_EMAIL | quote }} --fullname="{{ MOODLE_SITE_TITLE }}" --shortname=Academy register: moodle_install + retries: 20 + delay: 15 + until: moodle_install.rc != 137 changed_when: "'Moodle has been installed' in moodle_install.stdout" failed_when: - moodle_install.rc != 0 @@ -45,6 +48,30 @@ - "'Database tables already present' not in moodle_install.stderr" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" +- name: "๐Ÿ”‘ Realign the administrator password Moodle persisted at install" + when: not (MOODLE_OIDC_ENABLED | bool) + # nocheck: password-quote the token is upstream's CLI filename, not a credential + shell: > + container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} + php {{ [MOODLE_CLI_DIR, 'reset_password.php'] | path_join }} + --username={{ MOODLE_ADMIN_USERNAME | quote }} + --password={{ MOODLE_ADMIN_PASSWORD | quote }} + --ignore-password-policy + register: moodle_admin_password + changed_when: moodle_admin_password.rc == 0 + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐ŸŒ Open Moodle's cURL egress policy for the deployment's own networks" + ansible.builtin.shell: > + container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} + php {{ [MOODLE_CLI_DIR, 'cfg.php'] | path_join }} + --name={{ item.name | quote }} + --set={{ item.value | quote }} + loop: "{{ MOODLE_EGRESS_SETTINGS }}" + loop_control: + label: "{{ item.name }}" + changed_when: false + - name: "๐Ÿ“‚ Include ownership settings tasks for moodle" include_tasks: 03_ownership.yml @@ -56,6 +83,14 @@ include_tasks: 05_ldap_sync.yml when: MOODLE_LDAP_ENABLED | bool +- name: "๐Ÿค– Bind the native AI surface to the platform gateway" + include_tasks: utils/ai_gateway.yml + when: MOODLE_LITELLM_ENABLED | bool + +- name: "๐Ÿ”Œ Provision the MCP server surface" + include_tasks: utils/mcp.yml + when: MOODLE_MCP_ENABLED | bool + - name: "๐Ÿ“ง Verify the relay accepts Moodle's mail" when: lookup('config', application_id, 'services.email.enabled', false) | bool block: diff --git a/roles/web-app-moodle/tasks/02_build_context.yml b/roles/web-app-moodle/tasks/02_build_context.yml index fd345300b6..a6b56a4edb 100644 --- a/roles/web-app-moodle/tasks/02_build_context.yml +++ b/roles/web-app-moodle/tasks/02_build_context.yml @@ -36,6 +36,7 @@ - { path: "{{ MOODLE_BUILD_FILES.fpm_pool }}", mode: "0644" } - { path: "{{ MOODLE_BUILD_FILES.install_source }}", mode: "0755" } - { path: "{{ MOODLE_BUILD_FILES.install_oidc }}", mode: "0755" } + - { path: "{{ MOODLE_BUILD_FILES.install_mcp }}", mode: "0755" } loop_control: label: "{{ item.path }}" notify: diff --git a/roles/web-app-moodle/tasks/04_oidc.yml b/roles/web-app-moodle/tasks/04_oidc.yml index ac620ff606..e150b4d5ed 100644 --- a/roles/web-app-moodle/tasks/04_oidc.yml +++ b/roles/web-app-moodle/tasks/04_oidc.yml @@ -22,6 +22,7 @@ failed_when: false - name: "๐Ÿ”ง Set Moodle OIDC configuration via CLI" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" loop: - { name: "idptype", value: 3 } - { name: "clientauthmethod", value: 1 } diff --git a/roles/web-app-moodle/tasks/addons/auth_oidc.yml b/roles/web-app-moodle/tasks/addons/auth_oidc.yml new file mode 100644 index 0000000000..c6b9be9c8c --- /dev/null +++ b/roles/web-app-moodle/tasks/addons/auth_oidc.yml @@ -0,0 +1,2 @@ +--- +# No hook logic required: files/build/install/auth-oidc.sh installs the plugin into the image and tasks/04_oidc.yml configures it, included by tasks/01_manager_ops.yml on MOODLE_OIDC_ENABLED, the same services.sso.enabled flag this addon's enabled expression reads. Coupling is verified by files/playwright/addons/auth_oidc.spec.js. diff --git a/roles/web-app-moodle/tasks/utils/ai_gateway.yml b/roles/web-app-moodle/tasks/utils/ai_gateway.yml new file mode 100644 index 0000000000..ef74562a9b --- /dev/null +++ b/roles/web-app-moodle/tasks/utils/ai_gateway.yml @@ -0,0 +1,40 @@ +--- +- name: "๐Ÿ” Verify the gateway contract for {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-litellm/tasks/utils/consumer_contract.yml') }}" + +- name: "๐Ÿค– Point the Moodle AI subsystem at the platform gateway" + ansible.builtin.shell: > + container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} + php {{ [MOODLE_CLI_DIR, 'cfg.php'] | path_join }} + --component={{ item.component | quote }} + --name={{ item.name | quote }} + --set={{ item.value | quote }} + loop: "{{ MOODLE_LITELLM_SETTINGS }}" + loop_control: + label: "{{ item.component }}/{{ item.name }}" + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐Ÿงน Purge Moodle caches so the provider picks up its endpoint" + ansible.builtin.shell: > + container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} + php {{ [MOODLE_CLI_DIR, 'purge_caches.php'] | path_join }} + changed_when: false + +- name: "๐Ÿ”Ž Read back the configured chat endpoint" + ansible.builtin.shell: > + container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} + php {{ [MOODLE_CLI_DIR, 'cfg.php'] | path_join }} + --component=aiprovider_openai + --name=action_generate_text_endpoint + register: moodle_ai_endpoint + changed_when: false + +- name: "๐Ÿ›‘ Refuse a Moodle AI provider that does not answer through the gateway" + ansible.builtin.assert: + that: + - (moodle_ai_endpoint.stdout | trim) == MOODLE_LITELLM_CHAT_ENDPOINT + fail_msg: >- + aiprovider_openai still resolves generate_text to + '{{ moodle_ai_endpoint.stdout | trim }}' instead of + {{ MOODLE_LITELLM_CHAT_ENDPOINT }}, so prompts would leave the deployment. diff --git a/roles/web-app-moodle/tasks/utils/mcp.yml b/roles/web-app-moodle/tasks/utils/mcp.yml new file mode 100644 index 0000000000..883a688d26 --- /dev/null +++ b/roles/web-app-moodle/tasks/utils/mcp.yml @@ -0,0 +1,16 @@ +--- +- name: "๐Ÿ” Resolve {{ application_id }} hosting node + container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ entity_name }}" + resolve_output_prefix: MOODLE_MCP + resolve_compose_cid: "{{ MOODLE_CONTAINER_ADDRESS }}" + +- name: "๐Ÿงฉ Publish the MCP protocol plugin into the code volume" + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/mcp/plugin.yml" + +- name: "๐Ÿ”‘ Enable web services and mint the MCP bearer" + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/mcp/provision.yml" + +- name: "๐Ÿฉบ Verify the MCP endpoint answers that bearer" + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/mcp/verify.yml" diff --git a/roles/web-app-moodle/tasks/utils/mcp/plugin.yml b/roles/web-app-moodle/tasks/utils/mcp/plugin.yml new file mode 100644 index 0000000000..88c04c7dcd --- /dev/null +++ b/roles/web-app-moodle/tasks/utils/mcp/plugin.yml @@ -0,0 +1,34 @@ +--- +- name: "๐Ÿ”Ž Check the MCP plugin is baked into the image" + ansible.builtin.shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec --user root {{ MOODLE_MCP_LOCAL_CID | quote }} \ + test -d {{ MOODLE_MCP_PLUGIN_SOURCE_DIR | quote }} + register: moodle_mcp_plugin_source + changed_when: false + failed_when: false + delegate_to: "{{ MOODLE_MCP_HOST_NODE }}" + run_once: true + +- name: "๐Ÿ›‘ Refuse a Moodle image built without the MCP plugin" + ansible.builtin.assert: + that: + - moodle_mcp_plugin_source.rc == 0 + fail_msg: >- + {{ MOODLE_MCP_PLUGIN_SOURCE_DIR }} is missing, so the image carries no + webservice_mcp plugin and the MCP endpoint cannot exist. + +- name: "๐Ÿ“‹ Sync the MCP plugin into the bootstrapped code volume" + ansible.builtin.shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_MCP_LOCAL_CID | quote }} \ + cp -aT {{ MOODLE_MCP_PLUGIN_SOURCE_DIR | quote }} {{ MOODLE_MCP_PLUGIN_DIR | quote }} + changed_when: false + delegate_to: "{{ MOODLE_MCP_HOST_NODE }}" + run_once: true + +- name: "โ–ถ๏ธ Install the MCP plugin database records" + ansible.builtin.shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_MCP_LOCAL_CID | quote }} \ + php {{ MOODLE_CLI_DIR }}/upgrade.php --non-interactive + changed_when: false + delegate_to: "{{ MOODLE_MCP_HOST_NODE }}" + run_once: true diff --git a/roles/web-app-moodle/tasks/utils/mcp/provision.yml b/roles/web-app-moodle/tasks/utils/mcp/provision.yml new file mode 100644 index 0000000000..20ff563c06 --- /dev/null +++ b/roles/web-app-moodle/tasks/utils/mcp/provision.yml @@ -0,0 +1,55 @@ +--- +- name: "๐Ÿ”‘ Register the MCP web service and mint its permanent token" + ansible.builtin.shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec -i --user {{ MOODLE_RUNTIME_USER }} \ + -e MOODLE_CONFIG={{ MOODLE_CONFIG | quote }} \ + -e MCP_SERVICE_NAME={{ MOODLE_MCP_EXTERNAL_SERVICE_NAME | quote }} \ + -e MCP_SERVICE_SHORTNAME={{ MOODLE_MCP_EXTERNAL_SERVICE_SHORTNAME | quote }} \ + -e MCP_SERVICE_FUNCTIONS={{ MOODLE_MCP_EXTERNAL_FUNCTIONS | join(',') | quote }} \ + -e MCP_ACCOUNT_USERNAME={{ MOODLE_MCP_ACCOUNT_USERNAME | quote }} \ + -e MCP_ACCOUNT_EMAIL={{ MOODLE_MCP_ACCOUNT_EMAIL | quote }} \ + -e MCP_ACCOUNT_PASSWORD={{ MOODLE_MCP_ACCOUNT_PASSWORD | quote }} \ + -e MCP_ROLE_SHORTNAME={{ MOODLE_MCP_ROLE_SHORTNAME | quote }} \ + -e MCP_ROLE_NAME={{ MOODLE_MCP_ROLE_NAME | quote }} \ + -e MCP_ROLE_CAPABILITIES={{ MOODLE_MCP_ROLE_CAPABILITIES | join(',') | quote }} \ + {{ MOODLE_MCP_LOCAL_CID | quote }} php + args: + stdin: "{{ lookup('file', 'php/provision_mcp.php') }}" + register: moodle_mcp_provision + changed_when: false + delegate_to: "{{ MOODLE_MCP_HOST_NODE }}" + run_once: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐Ÿ”ง Take the minted token from the provisioning output" + ansible.builtin.set_fact: + moodle_mcp_token: "{{ moodle_mcp_provision.stdout_lines | last | trim }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + run_once: true + +- name: "๐Ÿ›‘ Refuse a Moodle that issued no usable web-service token" + ansible.builtin.assert: + that: + - moodle_mcp_token is match('^[a-f0-9]{32}$') + fail_msg: >- + Moodle returned no web-service token, so every MCP client would be + configured with an empty bearer and fail at first use. + +- name: "๐Ÿงน Purge the Moodle caches so the MCP protocol takes effect" + ansible.builtin.shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_MCP_LOCAL_CID | quote }} \ + php {{ MOODLE_CLI_DIR }}/purge_caches.php + changed_when: true + delegate_to: "{{ MOODLE_MCP_HOST_NODE }}" + run_once: true + notify: container-recreate + +- name: "๐Ÿ’พ Persist the token so MCP clients can read it" + ansible.builtin.include_role: + name: sys-token-store + tasks_from: write.yml + vars: + sys_token_store_user_key: "{{ lookup('config', application_id, 'mcp.credential.owner') }}" + sys_token_store_app: "{{ application_id }}" + sys_token_store_token: "{{ moodle_mcp_token }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-moodle/tasks/utils/mcp/verify.yml b/roles/web-app-moodle/tasks/utils/mcp/verify.yml new file mode 100644 index 0000000000..29ad45fe35 --- /dev/null +++ b/roles/web-app-moodle/tasks/utils/mcp/verify.yml @@ -0,0 +1,27 @@ +--- +- name: "๐Ÿฉบ List the MCP tools with the minted bearer" + ansible.builtin.shell: | # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec -i {{ MOODLE_MCP_LOCAL_CID | quote }} \ + {{ lookup('timeout', 30) | curl(5, 0) }} -f \ + -X POST \ + -H 'Content-Type: application/json' \ + -H 'Accept: application/json' \ + -H {{ ('Authorization: Bearer ' ~ moodle_mcp_token) | quote }} \ + --data-binary {{ MOODLE_MCP_TOOLS_LIST_PAYLOAD | to_json | quote }} \ + {{ MOODLE_MCP_URL | quote }} + register: moodle_mcp_tools_probe + changed_when: false + retries: 30 + delay: 2 + until: moodle_mcp_tools_probe.rc == 0 and '"tools"' in moodle_mcp_tools_probe.stdout + delegate_to: "{{ MOODLE_MCP_HOST_NODE }}" + run_once: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐Ÿ›‘ Refuse an MCP surface that exposes no tool" + ansible.builtin.assert: + that: + - (moodle_mcp_tools_probe.stdout | from_json).result.tools | length > 0 + fail_msg: >- + {{ MOODLE_MCP_URL }} answered the bearer but listed no tool, so every MCP + client would connect to an empty surface. diff --git a/roles/web-app-moodle/tasks/utils/patch/db_credentials.yml b/roles/web-app-moodle/tasks/utils/patch/db_credentials.yml new file mode 100644 index 0000000000..b2347f3e97 --- /dev/null +++ b/roles/web-app-moodle/tasks/utils/patch/db_credentials.yml @@ -0,0 +1,7 @@ +--- +- name: "๐Ÿ”‘ Realign the password moodle persisted in its config" + include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-rdbms/tasks/utils/patch_persisted_password.yml') }}" + vars: + patch_volume: "moodle_code" + patch_config_rel: "config.php" + patch_expression: "s|^\\$CFG->dbpass *=.*|\\$CFG->dbpass = '@PASSWORD@';|" diff --git a/roles/web-app-moodle/templates/compose.yml.j2 b/roles/web-app-moodle/templates/compose.yml.j2 index 9248f01cdd..0bb8966b57 100644 --- a/roles/web-app-moodle/templates/compose.yml.j2 +++ b/roles/web-app-moodle/templates/compose.yml.j2 @@ -12,22 +12,27 @@ MOODLE_BASE_TAG: "{{ MOODLE_VERSION }}" MOODLE_CODE_DIR: "{{ MOODLE_CODE_DIR }}" MOODLE_DATA_DIR: "{{ MOODLE_DATA_DIR }}" + MOODLE_LOCAL_CACHE_DIR: "{{ MOODLE_LOCAL_CACHE_DIR }}" MOODLE_SOURCE_DIR: "{{ MOODLE_SOURCE_DIR }}" MOODLE_RUNTIME_USER: "{{ MOODLE_RUNTIME_USER }}" MOODLE_OIDC_ENABLED: "{{ MOODLE_OIDC_ENABLED | bool | ternary('1','0') }}" MOODLE_OIDC_PLUGIN_RELPATH: "{{ MOODLE_OIDC_PLUGIN_RELPATH }}" + MOODLE_MCP_ENABLED: "{{ MOODLE_MCP_ENABLED | bool | ternary('1','0') }}" + MOODLE_MCP_PLUGIN_RELPATH: "{{ MOODLE_MCP_PLUGIN_RELPATH }}" + MOODLE_MCP_PLUGIN_ARCHIVE_URL: "{{ MOODLE_MCP_PLUGIN_ARCHIVE_URL }}" + MOODLE_OIDC_PLUGIN_ARCHIVE_URL: "{{ MOODLE_OIDC_PLUGIN_ARCHIVE_URL }}" MOODLE_RELEASE: "{{ MOODLE_RELEASE }}" MOODLE_TARBALL_URL: "{{ MOODLE_TARBALL_URL }}" - MOODLE_TARBALL_FILENAME: "{{ MOODLE_TARBALL_FILENAME }}" MOODLE_VERSION_FILE: "{{ MOODLE_VERSION_FILE }}" MOODLE_AUTH_SUBDIR: "{{ MOODLE_AUTH_SUBDIR }}" + MOODLE_WEBSERVICE_SUBDIR: "{{ MOODLE_WEBSERVICE_SUBDIR }}" {{ lookup('container_image', application_id, 'moodle') }} {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_depends_on', application_id) | indent(4) }} {{ lookup('container_extra_hosts', host_alias=true) | indent(4) }} - {{ lookup('container_networks') | indent(4) }} + {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} {% set service_name = 'nginx' %} {{ service_name }}: @@ -35,8 +40,7 @@ {{ lookup('compose_only', 'container_name', MOODLE_NGINX_CONTAINER) }} {{ lookup('container_image', application_id, 'nginx') }} {{ lookup('depends_on', {'moodle': 'service_healthy'}) }} - ports: - - {{ DOCKER_BIND_HOST }}:{{ lookup('config', application_id, 'services.moodle.ports.local.http') }}:{{ MOODLE_NGINX_PORT }} + {{ lookup('container_ports', ['moodle', 'http', DOCKER_BIND_HOST]) | indent(4) }} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('compose_restart') }} {{ lookup('container_networks') | indent(4) }} @@ -62,7 +66,7 @@ done {{ lookup('compose_restart') }} {{ lookup('container_extra_hosts', host_alias=true) | indent(4) }} - {{ lookup('container_networks') | indent(4) }} + {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} {{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/web-app-moodle/templates/env.j2 b/roles/web-app-moodle/templates/env.j2 index ee8d861d78..460894e166 100644 --- a/roles/web-app-moodle/templates/env.j2 +++ b/roles/web-app-moodle/templates/env.j2 @@ -1,7 +1,9 @@ {% include 'roles/sys-svc-container/templates/env.j2' %} MOODLE_WWWROOT={{ lookup('tls', application_id, 'url.base') | regex_replace('/$', '') }} +MOODLE_INTERNAL_HOST={{ MOODLE_MCP_SERVICE_KEY }} MOODLE_DATAROOT={{ MOODLE_DATA_DIR }} +MOODLE_LOCALCACHEDIR={{ MOODLE_LOCAL_CACHE_DIR }} MOODLE_DB_TYPE=mariadb MOODLE_DB_HOST={{ lookup('database', application_id, 'host') }} diff --git a/roles/web-app-moodle/templates/playwright.env.j2 b/roles/web-app-moodle/templates/playwright.env.j2 index 6bef85c5d6..02eb6ebd3c 100644 --- a/roles/web-app-moodle/templates/playwright.env.j2 +++ b/roles/web-app-moodle/templates/playwright.env.j2 @@ -10,15 +10,17 @@ LDAP_ADMIN_PASSWORD={{ LDAP.BIND_CREDENTIAL | dotenv_quote }} {% endif %} ADMIN_USERNAME={{ lookup('users', 'administrator').username | dotenv_quote }} ADMIN_PASSWORD={{ lookup('users', 'administrator').password | dotenv_quote }} +ADMIN_NATIVE_PASSWORD={{ MOODLE_ADMIN_PASSWORD | dotenv_quote }} BIBER_USERNAME={{ lookup('users', 'biber').username | dotenv_quote }} BIBER_PASSWORD={{ lookup('users', 'biber').password | dotenv_quote }} CANONICAL_DOMAIN={{ lookup('domain', application_id) | dotenv_quote }} -# nocheck: persona-block-rationale โ€” Moodle's site administrator is created by install_database.php with secrets.credentials.user_password (tasks/01_manager_ops.yml), a role-local secret this env never renders; ADMIN_PASSWORD above is the Keycloak secret. In the SSO variant tasks/04_oidc.yml replaces the login page with an alternateloginurl bounce and flips every mdl_user row to auth='oidc', so no form accepts either secret, and the sso-off variants in meta/variants.yml have no OIDC chain to substitute โ€” one env file is rendered per role, not per variant (see README "Persona contract opt-outs"). +# nocheck: persona-block-rationale โ€” in the SSO variant tasks/04_oidc.yml replaces the login page with an alternateloginurl bounce and flips every mdl_user row to auth='oidc', so no form accepts the administrator secret, and the sso-off variants in meta/variants.yml have no OIDC chain to substitute โ€” one env file is rendered per role, not per variant (see README "Persona contract opt-outs"). PERSONA_ADMINISTRATOR_BLOCKED=true MATOMO_BASE_URL={{ lookup('tls', 'web-app-matomo', 'url.base') | dotenv_quote }} +LITELLM_SERVICE_ENABLED={{ lookup('config', application_id, 'services.litellm.enabled') | string | lower }} SSO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.sso.enabled') | string | lower }} LOGOUT_SERVICE_ENABLED={{ lookup('config', application_id, 'services.logout.enabled') | string | lower }} MATOMO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.matomo.enabled') | string | lower }} @@ -26,3 +28,7 @@ MATOMO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.matomo.enab EMAIL_SERVICE_ENABLED={{ lookup('config', application_id, 'services.email.enabled') | string | lower }} LDAP_SERVICE_ENABLED={{ lookup('config', application_id, 'services.ldap.enabled') | string | lower }} LAM_SERVICE_ENABLED={{ lookup('config', application_id, 'services.lam.enabled', false) | string | lower }} +MCP_SERVICE_ENABLED={{ lookup('config', application_id, 'mcp.enabled') | string | lower }} +MCP_ENDPOINT_PATH={{ lookup('config', application_id, 'mcp.endpoint.path') | dotenv_quote }} + +{{ lookup('addon_env_flags', application_id) }} diff --git a/roles/web-app-moodle/templates/test.env.j2 b/roles/web-app-moodle/templates/test.env.j2 new file mode 100644 index 0000000000..3c7bacad44 --- /dev/null +++ b/roles/web-app-moodle/templates/test.env.j2 @@ -0,0 +1 @@ +{{ lookup('template', lookup('path_absolute', 'roles/test-e2e-cli/templates/mcp/test.env.j2')) }} diff --git a/roles/web-app-moodle/vars/main.yml b/roles/web-app-moodle/vars/main.yml index 45616b6d8c..7ddc796bbc 100644 --- a/roles/web-app-moodle/vars/main.yml +++ b/roles/web-app-moodle/vars/main.yml @@ -5,6 +5,7 @@ swarm_stack_converge_retries: 600 MOODLE_CODE_DIR: "{{ lookup('volume', 'web-app-moodle', 'code').target }}" MOODLE_DATA_DIR: "{{ lookup('volume', 'web-app-moodle', 'data').target }}" +MOODLE_LOCAL_CACHE_DIR: "{{ lookup('volume', application_id, 'localcache').mounts[0].target }}" MOODLE_SOURCE_DIR: "/opt/moodle-source" MOODLE_ENTRYPOINT_PATH: "/usr/local/bin/moodle-entrypoint.sh" @@ -14,13 +15,18 @@ MOODLE_BUILD_FILES: config_php: "config.php" install_source: "install/moodle-source.sh" install_oidc: "install/auth-oidc.sh" + install_mcp: "install/webservice-mcp.sh" opcache_ini: "php-conf/opcache-recommended.ini" runtime_ini: "php-conf/moodle-runtime.ini" fpm_pool: "php-conf/zz-moodle-pool.conf" MOODLE_VERSION_FILE: "version.php" # bootstrap-detection sentinel MOODLE_AUTH_SUBDIR: "auth" # top-level auth/ tree +MOODLE_WEBSERVICE_SUBDIR: "webservice" MOODLE_CLI_RELPATH: "admin/cli" # admin CLI script dir +MOODLE_OIDC_PLUGIN_VERSION: "{{ lookup('config', application_id, 'addons.auth_oidc.version') }}" +MOODLE_OIDC_PLUGIN_UPSTREAM: "{{ lookup('config', application_id, 'addons.auth_oidc.update.upstream_id') }}" +MOODLE_OIDC_PLUGIN_ARCHIVE_URL: "https://github.com/{{ MOODLE_OIDC_PLUGIN_UPSTREAM }}/archive/refs/tags/{{ MOODLE_OIDC_PLUGIN_VERSION }}.zip" MOODLE_OIDC_PLUGIN_RELPATH: "{{ [MOODLE_AUTH_SUBDIR, 'oidc'] | path_join }}" MOODLE_OIDC_PLUGIN_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_OIDC_PLUGIN_RELPATH] | path_join }}" MOODLE_CLI_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_CLI_RELPATH] | path_join }}" @@ -29,10 +35,12 @@ MOODLE_CONFIG: "{{ [MOODLE_CODE_DIR, 'config.php'] | path_join }}" MOODLE_RUNTIME_USER: "www-data" MOODLE_RUNTIME_USER_GROUP: "{{ MOODLE_RUNTIME_USER }}:{{ MOODLE_RUNTIME_USER }}" -MOODLE_BRANCH: "{{ lookup('config', application_id, 'services.moodle.branch') }}" +MOODLE_ADMIN_USERNAME: "{{ lookup('users', 'administrator').username }}" +MOODLE_ADMIN_PASSWORD: "{{ lookup('users', 'administrator').password }}" +MOODLE_ADMIN_EMAIL: "{{ lookup('users', 'administrator').email }}" + MOODLE_RELEASE: "{{ lookup('config', application_id, 'services.moodle.release') }}" -MOODLE_TARBALL_FILENAME: "moodle-{{ MOODLE_RELEASE }}.tgz" -MOODLE_TARBALL_URL: "https://download.moodle.org/download.php/direct/{{ MOODLE_BRANCH }}/{{ MOODLE_TARBALL_FILENAME }}" +MOODLE_TARBALL_URL: "https://github.com/moodle/moodle/archive/refs/tags/v{{ MOODLE_RELEASE }}.tar.gz" MOODLE_MSMTP_SRC: "{{ lookup('path_absolute', 'roles/sys-svc-mail-msmtp/templates/msmtprc.conf.j2') }}" MOODLE_MSMTP_ABS: "{{ [ lookup('container', application_id, 'directories.config'), 'msmtprc.conf'] | path_join }}" @@ -41,13 +49,79 @@ MOODLE_IMAGE: "{{ lookup('config', application_id, 'services.moodle.image') }}" MOODLE_VERSION: "{{ lookup('config', application_id, 'services.moodle.version') }}" MOODLE_CONTAINER: "{{ lookup('config', application_id, 'services.moodle.name') }}" MOODLE_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, entity_name) }}" -MOODLE_DB_CONTAINER_ADDRESS: "{{ lookup('container_address', 'svc-db-mariadb', 'mariadb') }}" +MOODLE_DB_CONTAINER_ADDRESS: "{{ lookup('database', application_id, 'address') }}" MOODLE_NGINX_CONTAINER: "{{ lookup('config', application_id, 'services.nginx.name') }}" MOODLE_CRON_CONTAINER: "{{ lookup('config', application_id, 'services.cron.name') }}" MOODLE_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') }}" MOODLE_LDAP_ENABLED: "{{ lookup('config', application_id, 'services.ldap.enabled') }}" +MOODLE_LITELLM_ENABLED: "{{ lookup('config', application_id, 'services.litellm.enabled') | bool }}" +MOODLE_LITELLM_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.litellm_api_key') }}" +MOODLE_LITELLM_CHAT_ENDPOINT: "{{ LITELLM_OPENAI_BASE_LOCAL_URL }}/chat/completions" +MOODLE_LITELLM_IMAGE_ENDPOINT: "{{ LITELLM_OPENAI_BASE_LOCAL_URL }}/images/generations" +MOODLE_LITELLM_SETTINGS: + - { component: aiprovider_openai, name: enabled, value: "1" } + - { component: aiprovider_openai, name: apikey, value: "{{ MOODLE_LITELLM_API_KEY }}" } + - { component: aiprovider_openai, name: action_generate_text_endpoint, value: "{{ MOODLE_LITELLM_CHAT_ENDPOINT }}" } + - { component: aiprovider_openai, name: action_generate_text_model, value: "{{ LITELLM_CHAT_MODEL }}" } + - { component: aiprovider_openai, name: action_summarise_text_endpoint, value: "{{ MOODLE_LITELLM_CHAT_ENDPOINT }}" } + - { component: aiprovider_openai, name: action_summarise_text_model, value: "{{ LITELLM_CHAT_MODEL }}" } + - { component: aiprovider_openai, name: action_generate_image_endpoint, value: "{{ MOODLE_LITELLM_IMAGE_ENDPOINT }}" } + - { component: aiprovider_openai, name: generate_image, value: "0" } + - { component: aiplacement_courseassist, name: enabled, value: "1" } + - { component: aiplacement_editor, name: enabled, value: "1" } + +MOODLE_EGRESS_BLOCKED_HOSTS: + - "0.0.0.0" + - "127.0.0.0/8" + - "localhost" + - "169.254.169.254" + - "0000::1" +MOODLE_EGRESS_ALLOWED_PORTS: + - "80" + - "443" +MOODLE_EGRESS_NEWLINE: "\n" +MOODLE_EGRESS_SETTINGS: + - name: curlsecurityblockedhosts + value: "{{ MOODLE_EGRESS_BLOCKED_HOSTS | join(MOODLE_EGRESS_NEWLINE) }}" + - name: curlsecurityallowedport + value: "{{ (MOODLE_EGRESS_ALLOWED_PORTS + ([MOODLE_LITELLM_CHAT_ENDPOINT | urlsplit('port') | string] if MOODLE_LITELLM_ENABLED | bool else [])) | join(MOODLE_EGRESS_NEWLINE) + }}" + +MOODLE_MCP_ENABLED: "{{ lookup('config', application_id, 'mcp.enabled') }}" +MOODLE_MCP_PLUGIN_VERSION: "v0.6.0" +MOODLE_MCP_PLUGIN_ARCHIVE_URL: "https://github.com/onbirdev/moodle-webservice_mcp/archive/refs/tags/{{ MOODLE_MCP_PLUGIN_VERSION }}.zip" +MOODLE_MCP_PLUGIN_RELPATH: "{{ [MOODLE_WEBSERVICE_SUBDIR, 'mcp'] | path_join }}" +MOODLE_MCP_PLUGIN_SOURCE_DIR: "{{ [MOODLE_SOURCE_DIR, MOODLE_MCP_PLUGIN_RELPATH] | path_join }}" +MOODLE_MCP_PLUGIN_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_MCP_PLUGIN_RELPATH] | path_join }}" +MOODLE_MCP_SERVICE_KEY: "{{ lookup('config', application_id, 'mcp.endpoint.service_key') }}" +MOODLE_MCP_PORT: "{{ lookup('config', application_id, 'services.nginx.ports.internal.http') }}" +MOODLE_MCP_URL: "http://{{ MOODLE_MCP_SERVICE_KEY }}:{{ MOODLE_MCP_PORT }}{{ lookup('config', application_id, 'mcp.endpoint.path') }}" +MOODLE_MCP_EXTERNAL_SERVICE_NAME: "Model Context Protocol" +MOODLE_MCP_EXTERNAL_SERVICE_SHORTNAME: "infinito_mcp" +MOODLE_MCP_EXTERNAL_FUNCTIONS: + - core_webservice_get_site_info + - core_course_get_courses + - core_enrol_get_users_courses + - core_user_get_users_by_field + - core_calendar_get_calendar_events +MOODLE_MCP_ACCOUNT: "{{ lookup('users', 'mcp-web-app-moodle') }}" +MOODLE_MCP_ACCOUNT_USERNAME: "{{ MOODLE_MCP_ACCOUNT.username }}" +MOODLE_MCP_ACCOUNT_EMAIL: "{{ MOODLE_MCP_ACCOUNT.email }}" +MOODLE_MCP_ACCOUNT_PASSWORD: "{{ MOODLE_MCP_ACCOUNT.password }}" +MOODLE_MCP_ROLE_SHORTNAME: "infinito_mcp" +MOODLE_MCP_ROLE_NAME: "Infinito MCP service" +MOODLE_MCP_ROLE_CAPABILITIES: + - webservice/mcp:use + - webservice/rest:use + - moodle/course:view + - moodle/user:viewdetails +MOODLE_MCP_TOOLS_LIST_PAYLOAD: + jsonrpc: "2.0" + id: 1 + method: tools/list + params: {} MOODLE_OIDC_CUSTOM_SCOPE: "{{ lookup('config', 'web-app-keycloak', 'services.keycloak.scopes.moodle') }}" MOODLE_OIDC_SCOPES: "openid profile email phone address {{ MOODLE_OIDC_CUSTOM_SCOPE }}" diff --git a/roles/web-app-n8n/README.md b/roles/web-app-n8n/README.md index 3efbc4045b..03ab8e5096 100644 --- a/roles/web-app-n8n/README.md +++ b/roles/web-app-n8n/README.md @@ -15,13 +15,17 @@ The diagram places n8n in the Infinito.Nexus cosmos: the components it deploys ( ```mermaid flowchart LR subgraph deps [Dependencies] + dep_svc_ai_litellm["svc-ai-litellm ๐Ÿณ๐Ÿ"] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local ๐Ÿ’ป"] dep_svc_db_postgres["svc-db-postgres ๐Ÿณ๐Ÿ"] dep_svc_net_tor["svc-net-tor ๐Ÿณ๐Ÿ"] dep_web_app_dashboard["web-app-dashboard ๐Ÿณ๐Ÿ"] + dep_web_app_hermes["web-app-hermes ๐Ÿณ๐Ÿ"] dep_web_app_keycloak["web-app-keycloak ๐Ÿณ๐Ÿ"] dep_web_app_mailu["web-app-mailu ๐Ÿณ๐Ÿ"] dep_web_app_matomo["web-app-matomo ๐Ÿณ๐Ÿ"] + dep_web_app_openclaw["web-app-openclaw ๐Ÿณ๐Ÿ"] + dep_web_app_openwebui["web-app-openwebui ๐Ÿณ๐Ÿ"] dep_web_app_prometheus["web-app-prometheus ๐Ÿณ๐Ÿ"] dep_web_svc_css["web-svc-css ๐Ÿ’ป"] dep_web_svc_logout["web-svc-logout ๐Ÿณ๐Ÿ"] @@ -38,14 +42,23 @@ flowchart LR svc_tor["tor"] svc_n8n["n8n"] svc_container_backup["container_backup"] + svc_litellm["litellm"] + svc_openwebui["openwebui"] + svc_hermes["hermes"] + svc_openclaw["openclaw"] + svc_flowise["flowise โŒ"] end + dep_svc_ai_litellm -. "0..1" .-> svc_litellm dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup dep_svc_db_postgres -. "0..1" .-> svc_postgres dep_svc_net_tor -. "0..1" .-> svc_tor dep_web_app_dashboard -. "0..1" .-> svc_dashboard + dep_web_app_hermes -. "0..1" .-> svc_hermes dep_web_app_keycloak -. "0..1" .-> svc_sso dep_web_app_mailu -. "0..1" .-> svc_email dep_web_app_matomo -. "0..1" .-> svc_matomo + dep_web_app_openclaw -. "0..1" .-> svc_openclaw + dep_web_app_openwebui -. "0..1" .-> svc_openwebui dep_web_app_prometheus -. "0..1" .-> svc_prometheus dep_web_svc_css -. "0..1" .-> svc_css dep_web_svc_logout -. "0..1" .-> svc_logout @@ -81,19 +94,20 @@ Run the published image to provision the inventory and deploy n8n to a managed s ```bash APP=web-app-n8n HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-n8n/files/javascript/reconcile/owner_password.js b/roles/web-app-n8n/files/javascript/reconcile/owner_password.js new file mode 100644 index 0000000000..db036e4306 --- /dev/null +++ b/roles/web-app-n8n/files/javascript/reconcile/owner_password.js @@ -0,0 +1,62 @@ +/** + * Prints CHANGED when it rewrote the owner's hash, OK when it already matched or + * the owner does not exist yet. + * + * Environment: + * N8N_OWNER_EMAIL: the owner account's email. + * N8N_OWNER_PASSWORD: the password the deployment wants it to have. + * DB_TYPE, DB_POSTGRESDB_HOST, DB_POSTGRESDB_PORT, DB_POSTGRESDB_DATABASE, + * DB_POSTGRESDB_USER, DB_POSTGRESDB_PASSWORD: n8n's own connection settings. + */ + +// nocheck: mirrored-unit-test - resolves bcryptjs and pg from the n8n container's +// own node_modules and writes the hash straight into the live user row; outside that +// container the requires do not resolve + +const bcrypt = require('bcryptjs') +const { Client } = require('pg') + +const email = process.env.N8N_OWNER_EMAIL +const password = process.env.N8N_OWNER_PASSWORD + +function fail(message) { + process.stderr.write(`FAILED ${message}\n`) + process.exit(1) +} + +async function main() { + if (!email || !password) { + fail('N8N_OWNER_EMAIL and N8N_OWNER_PASSWORD are required') + } + if (process.env.DB_TYPE !== 'postgresdb') { + fail(`unsupported DB_TYPE ${process.env.DB_TYPE}`) + } + + const client = new Client({ + host: process.env.DB_POSTGRESDB_HOST, + port: parseInt(process.env.DB_POSTGRESDB_PORT, 10), + database: process.env.DB_POSTGRESDB_DATABASE, + user: process.env.DB_POSTGRESDB_USER, + password: process.env.DB_POSTGRESDB_PASSWORD + }) + await client.connect() + try { + const found = await client.query('SELECT password FROM "user" WHERE email = lower($1)', [email]) + if (found.rowCount === 0) { + console.log('OK') + return + } + const stored = found.rows[0].password + if (stored && bcrypt.compareSync(password, stored)) { + console.log('OK') + return + } + const hash = bcrypt.hashSync(password, 10) + await client.query('UPDATE "user" SET password = $1 WHERE email = lower($2)', [hash, email]) + console.log('CHANGED') + } finally { + await client.end() + } +} + +main().catch((error) => fail(error.message)) diff --git a/roles/web-app-n8n/files/playwright/playwright.spec.js b/roles/web-app-n8n/files/playwright/playwright.spec.js index 1b203f659b..49af1e5141 100644 --- a/roles/web-app-n8n/files/playwright/playwright.spec.js +++ b/roles/web-app-n8n/files/playwright/playwright.spec.js @@ -13,3 +13,5 @@ require("./test-csp-headers").register(shared); require("./test-login-administrator").register(shared); require("./test-login-biber").register(shared); require("./test-guest-persona").register(shared); +require("./test-litellm-gateway").register(shared); +require("./test-mcp-guest").register(shared); diff --git a/roles/web-app-n8n/files/playwright/test-litellm-gateway.js b/roles/web-app-n8n/files/playwright/test-litellm-gateway.js new file mode 100644 index 0000000000..97d55b4d57 --- /dev/null +++ b/roles/web-app-n8n/files/playwright/test-litellm-gateway.js @@ -0,0 +1,334 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); +const { decodeDotenvQuotedValue, gotoOnion } = require("./personas"); + +const credentialName = decodeDotenvQuotedValue(process.env.N8N_LITELLM_CREDENTIAL_NAME); +const gatewayBaseUrl = decodeDotenvQuotedValue(process.env.N8N_LITELLM_BASE_URL); +const gatewayModel = decodeDotenvQuotedValue(process.env.N8N_LITELLM_MODEL); + +const CREDENTIAL_TYPE = "openAiApi"; +const PROBE_WORKFLOW = "infinito:litellm-probe"; +const REQUEST_NODE = "Gateway"; +const PROMPT = "Reply with exactly the word: pong"; +const FINAL_STATUSES = new Set(["success", "error", "crashed", "canceled"]); +const COMPLETION_TIMEOUT_MS = 240_000; + +/** + * Return a caller for n8n's internal `/rest` API bound to the page's session. + * + * n8n binds the `n8n-auth` JWT to the `browser-id` the frontend generated at + * login time, so a request that omits the header is rejected with 401 while + * the very same cookie works in the tab. The SSO path (files/hooks.js) issues + * a cookie without one, hence the empty-value tolerance. + * + * Args: + * page: the signed-in Playwright page. + * baseUrl: origin of the n8n vhost. + */ +async function restClient(page, baseUrl) { + const browserId = await page.evaluate(() => { + try { + const stored = window.localStorage.getItem("n8n-browserId"); + if (stored) { + return stored; + } + const key = Object.keys(window.localStorage).find((name) => /browser.?id/i.test(name)); + return key ? window.localStorage.getItem(key) || "" : ""; + } catch { + return ""; + } + }); + + return async function rest(method, path, payload) { + const headers = { accept: "application/json" }; + if (browserId) { + headers["browser-id"] = browserId; + } + const options = { method, headers, failOnStatusCode: false, timeout: resolveTimeout(120_000) }; + if (payload !== undefined) { + options.data = payload; + } + const response = await page.request.fetch(`${baseUrl}${path}`, options); + const text = await response.text(); + let body; + try { + body = text ? JSON.parse(text) : null; + } catch { + body = null; + } + return { status: response.status(), body, text: text.slice(0, 400) }; + }; +} + +/** + * Sign in as the n8n instance owner, the account that owns the managed + * credential, over whichever login surface the deploy exposes. + * + * Args: + * page: a page with cleared cookies. + * shared: the role's `_shared` module. + */ +async function signInAsOwner(page, shared) { + if (shared.env.oidcEnabled) { + expect(shared.env.adminUsername, "ADMIN_USERNAME must be set").toBeTruthy(); + expect(shared.env.adminPassword, "ADMIN_PASSWORD must be set").toBeTruthy(); + await shared.signInViaN8nOidc( + page, + shared.env.adminUsername, + shared.env.adminPassword, + "administrator" + ); + return; + } + + expect(shared.env.adminEmail, "ADMIN_EMAIL must be set").toBeTruthy(); + expect(shared.env.n8nOwnerPassword, "N8N_OWNER_PASSWORD must be set").toBeTruthy(); + await gotoOnion(page, `${shared.env.n8nBaseUrl}/`); + await shared.performN8nLoginForm(page, shared.env.adminEmail, shared.env.n8nOwnerPassword); +} + +/** + * Revive the `data` field of an execution read over `/rest`. + * + * n8n 1.95.3 hands the field back exactly as it stores it: a `flatted` string, + * a JSON array whose object and string members are numeric indices back into + * that same array. Reading `.resultData` off that string yields `undefined`, + * which is indistinguishable from a node that never ran. + * + * Args: + * payload: the execution's `data` field, flatted string or plain object. + */ +function reviveExecutionData(payload) { + if (typeof payload !== "string") { + return payload; + } + const nodes = JSON.parse(payload); + if (!Array.isArray(nodes)) { + return nodes; + } + const revived = new Map(); + const revive = (index) => { + const value = nodes[index]; + if (value === null || typeof value !== "object") { + return value; + } + if (revived.has(index)) { + return revived.get(index); + } + const output = Array.isArray(value) ? [] : {}; + revived.set(index, output); + for (const [key, reference] of Object.entries(value)) { + output[key] = typeof reference === "string" ? revive(Number(reference)) : reference; + } + return output; + }; + return revive(0); +} + +/** + * Poll one manual execution until it reaches a final state. + * + * Args: + * page: the signed-in Playwright page. + * rest: the `/rest` caller. + * executionId: id returned by the manual run. + * timeoutMs: budget for the whole completion. + */ +async function pollExecution(page, rest, executionId, timeoutMs) { + const deadline = Date.now() + timeoutMs; + for (;;) { + const latest = await rest("GET", `/rest/executions/${executionId}`); + const execution = latest.body?.data; + const status = String(execution?.status || ""); + if (execution && (execution.finished === true || FINAL_STATUSES.has(status))) { + return { execution, latest }; + } + if (Date.now() >= deadline) { + return { execution: null, latest }; + } + await page.waitForTimeout(resolveTimeout(2_000)); + } +} + +function probeWorkflow(credentialId, endpoint) { + return { + name: PROBE_WORKFLOW, + active: false, + settings: { executionOrder: "v1" }, + nodes: [ + { + id: "infinito-litellm-start", + name: "Start", + type: "n8n-nodes-base.manualTrigger", + typeVersion: 1, + position: [0, 0], + parameters: {}, + }, + { + id: "infinito-litellm-request", + name: REQUEST_NODE, + type: "n8n-nodes-base.httpRequest", + typeVersion: 4.2, + position: [220, 0], + parameters: { + method: "POST", + url: `${endpoint}/chat/completions`, + authentication: "predefinedCredentialType", + nodeCredentialType: CREDENTIAL_TYPE, + sendBody: true, + contentType: "json", + specifyBody: "json", + jsonBody: JSON.stringify({ + model: gatewayModel, + messages: [{ role: "user", content: PROMPT }], + stream: false, + }), + options: { timeout: COMPLETION_TIMEOUT_MS }, // nocheck: raw-timeout an n8n node parameter, not a Playwright wait: n8n reaches LiteLLM inside the deployment and never crosses a Tor circuit + }, + credentials: { [CREDENTIAL_TYPE]: { id: credentialId, name: credentialName } }, + }, + ], + connections: { Start: { main: [[{ node: REQUEST_NODE, type: "main", index: 0 }]] } }, + }; +} + +exports.register = function (shared) { + test("administrator: the managed openAiApi credential answers a prompt through the in-cluster gateway", async ({ page }) => { + shared.skipUnlessServiceEnabled("litellm"); + test.setTimeout(resolveTimeout(360_000)); + + expect(credentialName, "N8N_LITELLM_CREDENTIAL_NAME must be set").toBeTruthy(); + expect(gatewayBaseUrl, "N8N_LITELLM_BASE_URL must be set").toBeTruthy(); + expect(gatewayModel, "N8N_LITELLM_MODEL must be set").toBeTruthy(); + + await signInAsOwner(page, shared); + + const rest = await restClient(page, shared.env.n8nBaseUrl); + + const list = await rest("GET", "/rest/credentials"); + expect( + list.status, + `the owner session must be able to list credentials over /rest (HTTP ${list.status}: ${list.text})` + ).toBe(200); + + const managed = (Array.isArray(list.body?.data) ? list.body.data : []).filter( + (entry) => entry?.name === credentialName + ); + expect( + managed, + `exactly one credential named "${credentialName}" must exist; tasks/utils/ai_gateway.yml upserts it, so 0 means the gateway wiring never ran and every AI Agent node stays unconfigured` + ).toHaveLength(1); + expect( + String(managed[0]?.type), + `the managed credential must be of type ${CREDENTIAL_TYPE}; that is the only type an AI Agent node reads its endpoint and key from` + ).toBe(CREDENTIAL_TYPE); + + const credentialId = String(managed[0].id); + const detail = await rest("GET", `/rest/credentials/${credentialId}?includeData=true`); + expect( + detail.status, + `the owner must be able to read the managed credential with its data (HTTP ${detail.status})` + ).toBe(200); + + const storedUrl = String(detail.body?.data?.data?.url || ""); + expect( + storedUrl.length, + "the managed credential must carry a base URL; an empty one falls back to the openAiApi vendor default at api.openai.com and sends every prompt off the deployment" + ).toBeGreaterThan(0); + expect( + storedUrl, + "the stored base URL must be the in-cluster gateway address the deploy configured (N8N_LITELLM_BASE_URL)" + ).toBe(gatewayBaseUrl); + + const endpoint = new URL(storedUrl); + expect( + endpoint.protocol, + "the gateway endpoint must be plain http on the container network; https would mean the prompt leaves through the public ingress" + ).toBe("http:"); + expect( + endpoint.hostname.includes("."), + `the gateway host must be an undotted container name (got "${endpoint.hostname}"); a dotted host is completed by the container dns-search suffix and resolves through the public ingress, which is the leak the platform forbids` + ).toBe(false); + expect( + endpoint.host.toLowerCase(), + "the gateway must be a distinct in-cluster service, not n8n pointing at itself" + ).not.toBe(new URL(shared.env.n8nBaseUrl).host.toLowerCase()); + + const probe = await rest("POST", "/rest/credentials/test", { + credentials: { + id: credentialId, + name: credentialName, + type: CREDENTIAL_TYPE, + data: detail.body.data.data, + }, + }); + expect( + probe.status, + `n8n must accept a credential test for the managed credential (HTTP ${probe.status})` + ).toBe(200); + expect( + String(probe.body?.data?.status), + `n8n tests an ${CREDENTIAL_TYPE} credential with GET ${storedUrl}/models, so anything but "OK" means n8n cannot reach the gateway or the gateway rejects this role's virtual key: ${String(probe.body?.data?.message || probe.status)}` + ).toBe("OK"); + + const workflow = probeWorkflow(credentialId, storedUrl.replace(/\/+$/, "")); + const created = await rest("POST", "/rest/workflows", workflow); + expect( + created.status, + `n8n must accept the probe workflow that sends one prompt through the managed credential (HTTP ${created.status}: ${created.text})` + ).toBeLessThan(300); + + const workflowId = String(created.body?.data?.id || ""); + expect( + workflowId.length, + `the created probe workflow must carry an id to run it with (HTTP ${created.status}: ${created.text})` + ).toBeGreaterThan(0); + + try { + const run = await rest("POST", `/rest/workflows/${workflowId}/run`, { + workflowData: { ...workflow, id: workflowId }, + }); + expect( + run.status, + `n8n must accept the manual run of the probe workflow (HTTP ${run.status}: ${run.text})` + ).toBeLessThan(300); + + const executionId = String(run.body?.data?.executionId || ""); + expect( + executionId.length, + `the manual run must report an execution id to read the answer from (HTTP ${run.status}: ${run.text})` + ).toBeGreaterThan(0); + + const { execution, latest } = await pollExecution( + page, + rest, + executionId, + COMPLETION_TIMEOUT_MS + ); + expect( + execution, + `execution ${executionId} must reach a final state within ${COMPLETION_TIMEOUT_MS} ms (last HTTP ${latest.status}: ${latest.text})` + ).toBeTruthy(); + const result = reviveExecutionData(execution.data); + expect( + String(execution.status), + `the prompt must be answered through the gateway; a failed execution is n8n reaching ${storedUrl} and being refused or timed out: ${JSON.stringify(result?.resultData?.error || {}).slice(0, 400)}` + ).toBe("success"); + + const item = result?.resultData?.runData?.[REQUEST_NODE]?.[0]?.data?.main?.[0]?.[0]; + expect( + item?.json, + `the ${REQUEST_NODE} node must have produced a response item; empty runData means the node never ran and nothing was asked of the gateway` + ).toBeTruthy(); + + const answer = String(item.json?.choices?.[0]?.message?.content || "").trim(); + expect( + answer.length, + `the gateway must return non-empty assistant text over n8n -> ${storedUrl} -> ${gatewayModel} (got ${JSON.stringify(item.json).slice(0, 300)})` + ).toBeGreaterThan(0); + } finally { + await rest("DELETE", `/rest/workflows/${workflowId}`).catch(() => {}); + await shared.n8nLogout(page).catch(() => {}); + } + }); +}; diff --git a/roles/web-app-n8n/files/playwright/test-login-biber.js b/roles/web-app-n8n/files/playwright/test-login-biber.js index 470cd1b1d1..465d39d6e0 100644 --- a/roles/web-app-n8n/files/playwright/test-login-biber.js +++ b/roles/web-app-n8n/files/playwright/test-login-biber.js @@ -2,13 +2,7 @@ const { test, expect } = require("@playwright/test"); const { resolveTimeout } = require("./timeouts"); exports.register = function (shared) { - // hooks.js (EXTERNAL_HOOK_FILES) auto-provisions ANY Keycloak identity - // forwarded via the trusted Remote-Email header as a `global:member` n8n - // user โ€” not just the owner account tasks/02_bootstrap.yml creates. So - // biber, a non-admin persona with no pre-existing n8n-local account, now - // reaches n8n's authenticated workflow surface too, exactly like the - // administrator. - test("biber: Keycloak SSO auto-provisions and lands on the workflow editor", async ({ page }) => { + test("biber: the proxy refuses a persona holding none of the admitted groups", async ({ page }) => { shared.skipUnlessServiceEnabled("sso"); expect(shared.env.biberUsername, "BIBER_USERNAME must be set").toBeTruthy(); expect(shared.env.biberPassword, "BIBER_PASSWORD must be set").toBeTruthy(); @@ -16,11 +10,16 @@ exports.register = function (shared) { await shared.signInViaN8nOidc(page, shared.env.biberUsername, shared.env.biberPassword, "biber"); - await expect(page.locator("body")).toContainText( - /workflow|execution|credential|canvas|overview/i, - { timeout: resolveTimeout(60_000) } - ); + await expect(page.locator("body"), { + message: + "biber reached n8n's authenticated surface; meta/services.yml admits only the administrator and mcp groups and biber holds neither, so the gate is open to a persona that carries no role", + }).not.toContainText(/workflow|execution|credential|canvas|overview/i, { + timeout: resolveTimeout(60_000), + }); - await shared.n8nLogout(page); + await expect(page.locator("body"), { + message: + "the page is neither n8n's surface nor a recognisable denial; the proxy may have changed its rejection wording", + }).toContainText(/403|forbidden|permission|unauthorized|access denied/i); }); }; diff --git a/roles/web-app-n8n/files/playwright/test-mcp-guest.js b/roles/web-app-n8n/files/playwright/test-mcp-guest.js new file mode 100644 index 0000000000..0b96d05fdf --- /dev/null +++ b/roles/web-app-n8n/files/playwright/test-mcp-guest.js @@ -0,0 +1,27 @@ +const { test, expect } = require("@playwright/test"); +const { skipUnlessServiceEnabled } = require("./service-gating"); +const { mcpEndpointUrl, registerMcpDisabledState } = require("./mcp-endpoint"); +const { decodeDotenvQuotedValue } = require("./personas"); + +const mcpEndpointPath = decodeDotenvQuotedValue(process.env.MCP_ENDPOINT_PATH || ""); +const resolveEndpointUrl = () => mcpEndpointUrl(mcpEndpointPath, process.env.N8N_BASE_URL); + +exports.register = function () { + test("guest: the public vhost refuses the internal MCP trigger to every unauthenticated caller", async ({ page }) => { + skipUnlessServiceEnabled("mcp"); + expect(mcpEndpointPath, "MCP_ENDPOINT_PATH must be set").toBeTruthy(); + + const response = await page.request.get(resolveEndpointUrl(), { + failOnStatusCode: false, + maxRedirects: 0, + headers: { accept: "text/event-stream" }, + }); + + expect( + response.status(), + "n8n's MCP trigger is exposure: internal, so the public vhost must answer 404; the bearer guard itself is proven in-cluster by the CLI MCP contract", + ).toBe(404); + }); + + registerMcpDisabledState(resolveEndpointUrl); +}; diff --git a/roles/web-app-n8n/files/python/provision/ai.py b/roles/web-app-n8n/files/python/provision/ai.py new file mode 100644 index 0000000000..74bcdc9226 --- /dev/null +++ b/roles/web-app-n8n/files/python/provision/ai.py @@ -0,0 +1,114 @@ +# nocheck: mirrored-unit-test - the contract is the shape n8n 1.95.3 accepts on +# /rest/credentials behind a session cookie; every helper is one call against the live +# instance and a stubbed opener would assert this file's own payload back at it +"""Provision the deployment-managed OpenAI credential of n8n 1.95.3. + +Prints ``CHANGED``/``OK``. + +Environment: + N8N_BASE: origin of the n8n API. + N8N_OWNER_EMAIL: owner account email. + N8N_OWNER_PASSWORD: owner account password. + N8N_AI_CREDENTIAL: deterministic name of the managed credential. + N8N_AI_BASE_URL: OpenAI-compatible base URL of the gateway. + N8N_AI_API_KEY: gateway virtual key of this role. +""" + +from __future__ import annotations + +import json +import os +import sys +import urllib.error +import urllib.request + +BASE = os.environ.get("N8N_BASE", "").rstrip("/") +EMAIL = os.environ.get("N8N_OWNER_EMAIL", "") +PASSWORD = os.environ.get("N8N_OWNER_PASSWORD", "") +CREDENTIAL_NAME = os.environ.get("N8N_AI_CREDENTIAL", "") +AI_BASE_URL = os.environ.get("N8N_AI_BASE_URL", "") +AI_API_KEY = os.environ.get("N8N_AI_API_KEY", "") + +REST = "/rest" +CREDENTIAL_TYPE = "openAiApi" + +SESSION = {"cookie": ""} + + +def call(path, method="GET", payload=None): + """Return ``(status, body)`` of one n8n internal API call. + + Args: + path: API path below the n8n origin. + method: HTTP method. + payload: JSON-serialisable request body, or None. + """ + data = json.dumps(payload).encode() if payload is not None else None + request = urllib.request.Request( # noqa: S310 - fixed http:// base from N8N_BASE, no user-supplied scheme + f"{BASE}{path}", data=data, method=method + ) + request.add_header("Content-Type", "application/json") + if SESSION["cookie"]: + request.add_header("Cookie", SESSION["cookie"]) + try: + with urllib.request.urlopen(request, timeout=60) as response: # noqa: S310 - fixed http:// base from N8N_BASE + for header in response.headers.get_all("Set-Cookie") or []: + if header.startswith("n8n-auth="): + SESSION["cookie"] = header.split(";", 1)[0] + return response.status, json.loads(response.read() or b"null") + except urllib.error.HTTPError as error: + return error.code, error.read().decode(errors="replace") + + +def login(): + status, body = call( + f"{REST}/login", + method="POST", + payload={"emailOrLdapLoginId": EMAIL, "password": PASSWORD}, + ) + if status != 200: + sys.exit(f"FAILED logging in as {EMAIL}: {status} {body}") + + +def payload(): + return { + "name": CREDENTIAL_NAME, + "type": CREDENTIAL_TYPE, + "data": {"apiKey": AI_API_KEY, "url": AI_BASE_URL}, + } + + +def upsert(): + """Create or overwrite the managed gateway credential.""" + status, body = call(f"{REST}/credentials") + if status != 200: + sys.exit(f"FAILED listing credentials: {status} {body}") + + existing = (body or {}).get("data") if isinstance(body, dict) else body + matches = [item for item in existing or [] if item.get("name") == CREDENTIAL_NAME] + if len(matches) > 1: + sys.exit(f"FAILED: {len(matches)} credentials named {CREDENTIAL_NAME}") + + if not matches: + status, body = call(f"{REST}/credentials", method="POST", payload=payload()) + if status not in (200, 201): + sys.exit(f"FAILED creating {CREDENTIAL_NAME}: {status} {body}") + return True + + status, body = call( + f"{REST}/credentials/{matches[0]['id']}", method="PATCH", payload=payload() + ) + if status != 200: + sys.exit(f"FAILED updating {CREDENTIAL_NAME}: {status} {body}") + return False + + +def main(): + if not AI_API_KEY: + sys.exit("FAILED: no gateway virtual key configured") + login() + print("CHANGED" if upsert() else "OK") + + +if __name__ == "__main__": + main() diff --git a/roles/web-app-n8n/files/python/provision/client.py b/roles/web-app-n8n/files/python/provision/client.py new file mode 100644 index 0000000000..e1c6241d3d --- /dev/null +++ b/roles/web-app-n8n/files/python/provision/client.py @@ -0,0 +1,386 @@ +"""Provision the deployment-managed MCP client surface of n8n 1.95.3. + +Renders one agent workflow whose connected MCP Client Tool nodes are exactly +the providers this deployment discovered, each pinned to that provider's +declared tool allowlist. + +Prints ``CHANGED`` or ``OK``. + +Environment: + N8N_BASE: origin of the n8n API. + N8N_OWNER_EMAIL: owner account email. + N8N_OWNER_PASSWORD: owner account password. + N8N_API_KEY_NAME: deterministic name of the managed API key. + N8N_CLIENT_WORKFLOW: deterministic name of the managed agent workflow. + N8N_AI_CREDENTIAL: name of the managed gateway credential. + N8N_CHAT_MODEL: model the agent asks the gateway for. + N8N_MCP_PROVIDERS: JSON array of discovered providers, each carrying + ``id``, ``url``, ``token`` and ``tools``. +""" + +from __future__ import annotations + +import json +import os +import re +import sys +import urllib.error +import urllib.request + +BASE = os.environ.get("N8N_BASE", "").rstrip("/") +EMAIL = os.environ.get("N8N_OWNER_EMAIL", "") +PASSWORD = os.environ.get("N8N_OWNER_PASSWORD", "") +KEY_NAME = os.environ.get("N8N_API_KEY_NAME", "") +WORKFLOW_NAME = os.environ.get("N8N_CLIENT_WORKFLOW", "") +AI_CREDENTIAL = os.environ.get("N8N_AI_CREDENTIAL", "") +CHAT_MODEL = os.environ.get("N8N_CHAT_MODEL", "") +PROVIDERS = json.loads(os.environ.get("N8N_MCP_PROVIDERS", "[]")) + +REST = "/rest" +PUBLIC = "/api/v1" +CREDENTIAL_TYPE = "httpBearerAuth" +BEARER_AUTH = "bearerAuth" +CLIENT_PREFIX = "infinito:mcp-client:" + +TRIGGER_TYPE = "n8n-nodes-base.executeWorkflowTrigger" +TRIGGER_VERSION = 1.1 +TRIGGER_NAME = "Infinito Client Trigger" +AGENT_TYPE = "@n8n/n8n-nodes-langchain.agent" +AGENT_VERSION = 2 +AGENT_NAME = "Infinito Agent" +MODEL_TYPE = "@n8n/n8n-nodes-langchain.lmChatOpenAi" +MODEL_VERSION = 1.2 +MODEL_NAME = "Infinito Model" +CLIENT_TYPE = "@n8n/n8n-nodes-langchain.mcpClientTool" +CLIENT_VERSION = 1 + +MAIN = "main" +AI_TOOL = "ai_tool" +AI_LANGUAGE_MODEL = "ai_languageModel" +INCLUDE_SELECTED = "selected" + +SESSION = {"cookie": ""} + + +def call(path, method="GET", payload=None, api_key=None): + """Return ``(status, body)`` of one n8n API call. + + Args: + path: API path below the n8n origin. + method: HTTP method. + payload: JSON-serialisable request body, or None. + api_key: public-API key; omitted calls ride the owner cookie instead. + """ + data = json.dumps(payload).encode() if payload is not None else None + request = urllib.request.Request( # noqa: S310 - fixed http:// base from N8N_BASE, no user-supplied scheme + f"{BASE}{path}", data=data, method=method + ) + request.add_header("Content-Type", "application/json") + if api_key: + request.add_header("X-N8N-API-KEY", api_key) + elif SESSION["cookie"]: + request.add_header("Cookie", SESSION["cookie"]) + try: + with urllib.request.urlopen(request, timeout=60) as response: # noqa: S310 - fixed http:// base from N8N_BASE + for header in response.headers.get_all("Set-Cookie") or []: + if header.startswith("n8n-auth="): + SESSION["cookie"] = header.split(";", 1)[0] + return response.status, json.loads(response.read() or b"null") + except urllib.error.HTTPError as error: + return error.code, error.read().decode(errors="replace") + + +def login(): + status, body = call( + f"{REST}/login", + method="POST", + payload={"emailOrLdapLoginId": EMAIL, "password": PASSWORD}, + ) + if status != 200: + sys.exit(f"FAILED logging in as {EMAIL}: {status} {body}") + + +def api_key(): + """Return ``(secret, id)`` of a public-API key minted for this run alone. + + n8n returns the usable secret only once, as ``rawApiKey``, and a listed key + is redacted, so the key cannot be carried between runs. It is minted here + and revoked before the run ends; an entry left behind under the managed name + belongs to a run that died and is deleted rather than guessed at. + """ + status, body = call(f"{REST}/api-keys") + if status != 200: + sys.exit(f"FAILED listing api keys: {status} {body}") + + existing = (body or {}).get("data") if isinstance(body, dict) else body + matches = [key for key in existing or [] if key.get("label") == KEY_NAME] + if len(matches) > 1: + sys.exit(f"FAILED: {len(matches)} api keys named {KEY_NAME}") + for key in matches: + call(f"{REST}/api-keys/{key['id']}", method="DELETE") + + status, body = call( + f"{REST}/api-keys", + method="POST", + payload={ + "label": KEY_NAME, + "scopes": [ + "workflow:create", + "workflow:read", + "workflow:update", + "workflow:list", + "workflow:delete", + ], + "expiresAt": None, + }, + ) + if status not in (200, 201): + sys.exit(f"FAILED creating api key {KEY_NAME}: {status} {body}") + created = (body or {}).get("data") if isinstance(body, dict) else body + return str(created["rawApiKey"]), str(created["id"]) + + +def revoke_key(key_id): + """Delete the public-API key this run minted. + + Args: + key_id: id of the key to delete. + """ + status, body = call(f"{REST}/api-keys/{key_id}", method="DELETE") + if status != 200: + sys.exit(f"FAILED revoking api key {KEY_NAME}: {status} {body}") + + +def node_name(provider_id): + """Return the stable node name of one provider's client tool. + + Args: + provider_id: the provider's application_id. + """ + return "mcp_" + re.sub(r"[^a-zA-Z0-9]+", "_", provider_id).strip("_") + + +def credential_name(provider_id): + """Return the deterministic name of one provider's bearer credential. + + Args: + provider_id: the provider's application_id. + """ + return f"{CLIENT_PREFIX}{provider_id}" + + +def listed_credentials(): + """Return the credentials n8n currently holds.""" + status, body = call(f"{REST}/credentials") + if status != 200: + sys.exit(f"FAILED listing credentials: {status} {body}") + existing = (body or {}).get("data") if isinstance(body, dict) else body + return list(existing or []) + + +def credential(provider): + """Return ``({"id", "name"}, created)`` of one provider's bearer credential. + + Args: + provider: a discovered provider carrying ``id`` and ``token``. + """ + name = credential_name(provider["id"]) + matches = [item for item in listed_credentials() if item.get("name") == name] + if len(matches) > 1: + sys.exit(f"FAILED: {len(matches)} credentials named {name}") + + payload = { + "name": name, + "type": CREDENTIAL_TYPE, + "data": {"token": provider["token"]}, + } + if not matches: + status, body = call(f"{REST}/credentials", method="POST", payload=payload) + if status not in (200, 201): + sys.exit(f"FAILED creating {name}: {status} {body}") + created = (body or {}).get("data") if isinstance(body, dict) else body + return {"id": str(created["id"]), "name": name}, True + + status, body = call( + f"{REST}/credentials/{matches[0]['id']}", method="PATCH", payload=payload + ) + if status != 200: + sys.exit(f"FAILED updating {name}: {status} {body}") + return {"id": str(matches[0]["id"]), "name": name}, False + + +def drop_stale_credentials(keep): + """Delete managed client credentials no discovered provider claims. + + Args: + keep: credential names the current provider set still needs. + + A name outside ``CLIENT_PREFIX`` belongs to a human and is never touched. + """ + dropped = False + for item in listed_credentials(): + name = str(item.get("name") or "") + if name.startswith(CLIENT_PREFIX) and name not in keep: + status, body = call(f"{REST}/credentials/{item['id']}", method="DELETE") + if status != 200: + sys.exit(f"FAILED deleting {name}: {status} {body}") + dropped = True + return dropped + + +def client_node(provider, reference, index): + """Return one MCP Client Tool node pinned to a provider's allowlist. + + Args: + provider: a discovered provider carrying ``id``, ``url`` and ``tools``. + reference: ``{"id", "name"}`` reference to its bearer credential. + index: position of the node, so the rendering stays stable. + """ + name = node_name(provider["id"]) + mutating = set(provider.get("mutating") or []) + return { + "id": name, + "name": name, + "type": CLIENT_TYPE, + "typeVersion": CLIENT_VERSION, + "position": [220 * index, 220], + "parameters": { + "sseEndpoint": provider["url"], + "authentication": BEARER_AUTH, + "include": INCLUDE_SELECTED, + "includeTools": sorted(set(provider.get("tools") or []) - mutating), + }, + "credentials": {CREDENTIAL_TYPE: reference}, + } + + +def workflow_body(references): + """Return the managed agent workflow as the public API accepts it. + + Args: + references: ``{provider_id: {"id", "name"}}`` bearer references. + """ + nodes = [ + { + "id": "infinito-client-trigger", + "name": TRIGGER_NAME, + "type": TRIGGER_TYPE, + "typeVersion": TRIGGER_VERSION, + "position": [0, 0], + "parameters": {}, + }, + { + "id": "infinito-agent", + "name": AGENT_NAME, + "type": AGENT_TYPE, + "typeVersion": AGENT_VERSION, + "position": [220, 0], + "parameters": {}, + }, + { + "id": "infinito-model", + "name": MODEL_NAME, + "type": MODEL_TYPE, + "typeVersion": MODEL_VERSION, + "position": [220, 220], + "parameters": {"model": CHAT_MODEL}, + "credentials": {"openAiApi": {"name": AI_CREDENTIAL}}, + }, + ] + connections = { + TRIGGER_NAME: {MAIN: [[{"node": AGENT_NAME, "type": MAIN, "index": 0}]]}, + MODEL_NAME: { + AI_LANGUAGE_MODEL: [ + [{"node": AGENT_NAME, "type": AI_LANGUAGE_MODEL, "index": 0}] + ] + }, + } + for index, provider in enumerate(PROVIDERS): + nodes.append(client_node(provider, references[provider["id"]], index + 2)) + connections[node_name(provider["id"])] = { + AI_TOOL: [[{"node": AGENT_NAME, "type": AI_TOOL, "index": 0}]] + } + return { + "name": WORKFLOW_NAME, + "settings": {"executionOrder": "v1"}, + "nodes": nodes, + "connections": connections, + } + + +def managed_workflow(key): + """Return the managed agent workflow, or None, refusing to guess between two. + + Args: + key: the public-API key. + """ + status, body = call(f"{PUBLIC}/workflows", api_key=key) + if status != 200: + sys.exit(f"FAILED listing workflows: {status} {body}") + existing = (body or {}).get("data") if isinstance(body, dict) else body + matches = [flow for flow in existing or [] if flow.get("name") == WORKFLOW_NAME] + if len(matches) > 1: + sys.exit(f"FAILED: {len(matches)} workflows named {WORKFLOW_NAME}") + return matches[0] if matches else None + + +def reconcile(key): + """Render the agent workflow over exactly the providers this run discovered. + + Args: + key: the public-API key. + + The workflow is never activated: it answers a sub-workflow call, so it runs + only once an operator wires something to it. + """ + flow = managed_workflow(key) + if not PROVIDERS: + dropped = drop_stale_credentials(set()) + if flow is not None: + status, body = call( + f"{PUBLIC}/workflows/{flow['id']}", method="DELETE", api_key=key + ) + if status != 200: + sys.exit(f"FAILED deleting {WORKFLOW_NAME}: {status} {body}") + return dropped or flow is not None + + references = {} + minted = False + for provider in PROVIDERS: + references[provider["id"]], created = credential(provider) + minted = minted or created + dropped = drop_stale_credentials( + {credential_name(provider["id"]) for provider in PROVIDERS} + ) + + payload = workflow_body(references) + if flow is None: + status, body = call( + f"{PUBLIC}/workflows", method="POST", payload=payload, api_key=key + ) + if status not in (200, 201): + sys.exit(f"FAILED creating {WORKFLOW_NAME}: {status} {body}") + return True + + changed = flow.get("nodes") != payload["nodes"] + status, body = call( + f"{PUBLIC}/workflows/{flow['id']}", + method="PUT", + payload=payload, + api_key=key, + ) + if status != 200: + sys.exit(f"FAILED updating {WORKFLOW_NAME}: {status} {body}") + return changed or minted or dropped + + +def main(): + login() + key, key_id = api_key() + changed = reconcile(key) + revoke_key(key_id) + print("CHANGED" if changed else "OK") + + +if __name__ == "__main__": + main() diff --git a/roles/web-app-n8n/files/python/provision/mcp.py b/roles/web-app-n8n/files/python/provision/mcp.py new file mode 100644 index 0000000000..e54f5f5d39 --- /dev/null +++ b/roles/web-app-n8n/files/python/provision/mcp.py @@ -0,0 +1,314 @@ +"""Provision the deployment-managed MCP surfaces of n8n 1.100.1. + +Prints ``CHANGED`` or ``OK``. + +Environment: + N8N_BASE: origin of the n8n API. + N8N_OWNER_EMAIL: owner account email. + N8N_OWNER_PASSWORD: owner account password. + N8N_API_KEY_NAME: deterministic name of the managed API key. + N8N_MCP_PATH: webhook path segment of the managed trigger. + N8N_MCP_TOKEN: bearer the trigger requires from clients. + N8N_MCP_WORKFLOW: deterministic name of the managed workflow. + N8N_MCP_CREDENTIAL: deterministic name of the managed bearer credential. +""" + +from __future__ import annotations + +import json +import os +import sys +import urllib.error +import urllib.request + +BASE = os.environ.get("N8N_BASE", "").rstrip("/") +EMAIL = os.environ.get("N8N_OWNER_EMAIL", "") +PASSWORD = os.environ.get("N8N_OWNER_PASSWORD", "") +KEY_NAME = os.environ.get("N8N_API_KEY_NAME", "") +MCP_PATH = os.environ.get("N8N_MCP_PATH", "") +MCP_TOKEN = os.environ.get("N8N_MCP_TOKEN", "") +WORKFLOW_NAME = os.environ.get("N8N_MCP_WORKFLOW", "") +CREDENTIAL_NAME = os.environ.get("N8N_MCP_CREDENTIAL", "") + +REST = "/rest" +PUBLIC = "/api/v1" +TRIGGER_TYPE = "@n8n/n8n-nodes-langchain.mcpTrigger" +TRIGGER_VERSION = 2 +TRIGGER_NAME = "Infinito MCP Trigger" +BEARER_AUTH = "bearerAuth" +CREDENTIAL_TYPE = "httpBearerAuth" + +TOOL_TYPE = "@n8n/n8n-nodes-langchain.toolCode" +TOOL_VERSION = 1.2 +TOOL_NAME = "infinito_health" +TOOL_CONNECTION = "ai_tool" +TOOL_DESCRIPTION = ( + "Report that the managed MCP server is reachable and echo the caller's text " + "back. Reads nothing: it reaches no application, database, or network." +) +TOOL_CODE = ( + 'return JSON.stringify({status: "ok", echo: query.echo, ' + "checked_at: new Date().toISOString()});" +) +TOOL_SCHEMA = json.dumps( + { + "type": "object", + "properties": { + "echo": { + "type": "string", + "description": "Text returned unchanged, to prove the round trip.", + } + }, + "required": ["echo"], + "additionalProperties": False, + } +) + +SESSION = {"cookie": ""} + + +def call(path, method="GET", payload=None, api_key=None): + """Return ``(status, body)`` of one n8n API call. + + Args: + path: API path below the n8n origin. + method: HTTP method. + payload: JSON-serialisable request body, or None. + api_key: public-API key; omitted calls ride the owner cookie instead. + """ + data = json.dumps(payload).encode() if payload is not None else None + request = urllib.request.Request( # noqa: S310 - fixed http:// base from N8N_BASE, no user-supplied scheme + f"{BASE}{path}", data=data, method=method + ) + request.add_header("Content-Type", "application/json") + if api_key: + request.add_header("X-N8N-API-KEY", api_key) + elif SESSION["cookie"]: + request.add_header("Cookie", SESSION["cookie"]) + try: + with urllib.request.urlopen(request, timeout=60) as response: # noqa: S310 - fixed http:// base from N8N_BASE + for header in response.headers.get_all("Set-Cookie") or []: + if header.startswith("n8n-auth="): + SESSION["cookie"] = header.split(";", 1)[0] + return response.status, json.loads(response.read() or b"null") + except urllib.error.HTTPError as error: + return error.code, error.read().decode(errors="replace") + + +def login(): + status, body = call( + f"{REST}/login", + method="POST", + payload={"emailOrLdapLoginId": EMAIL, "password": PASSWORD}, + ) + if status != 200: + sys.exit(f"FAILED logging in as {EMAIL}: {status} {body}") + + +def api_key(): + """Return ``(secret, id)`` of a public-API key minted for this run alone. + + n8n returns the usable secret only once, as ``rawApiKey``, and a listed key + is redacted, so the key cannot be carried between runs. It is minted here + and revoked before the run ends; an entry left behind under the managed name + belongs to a run that died and is deleted rather than guessed at. + """ + status, body = call(f"{REST}/api-keys") + if status != 200: + sys.exit(f"FAILED listing api keys: {status} {body}") + + existing = (body or {}).get("data") if isinstance(body, dict) else body + matches = [key for key in existing or [] if key.get("label") == KEY_NAME] + if len(matches) > 1: + sys.exit(f"FAILED: {len(matches)} api keys named {KEY_NAME}") + for key in matches: + call(f"{REST}/api-keys/{key['id']}", method="DELETE") + + status, body = call( + f"{REST}/api-keys", + method="POST", + payload={ + "label": KEY_NAME, + "scopes": [ + "workflow:create", + "workflow:read", + "workflow:update", + "workflow:list", + ], + "expiresAt": None, + }, + ) + if status not in (200, 201): + sys.exit(f"FAILED creating api key {KEY_NAME}: {status} {body}") + created = (body or {}).get("data") if isinstance(body, dict) else body + return str(created["rawApiKey"]), str(created["id"]) + + +def revoke_key(key_id): + """Delete the public-API key this run minted. + + Args: + key_id: id of the key to delete. + """ + status, body = call(f"{REST}/api-keys/{key_id}", method="DELETE") + if status != 200: + sys.exit(f"FAILED revoking api key {KEY_NAME}: {status} {body}") + + +def bearer_credential(): + """Return ``(reference, created)`` of the managed ``httpBearerAuth`` credential. + + The reference is the ``{"id", "name"}`` shape a node's ``credentials`` map + expects. n8n encrypts credential data at rest and never hands it back, so an + existing managed credential is overwritten rather than compared. + """ + status, body = call(f"{REST}/credentials") + if status != 200: + sys.exit(f"FAILED listing credentials: {status} {body}") + + existing = (body or {}).get("data") if isinstance(body, dict) else body + matches = [item for item in existing or [] if item.get("name") == CREDENTIAL_NAME] + if len(matches) > 1: + sys.exit(f"FAILED: {len(matches)} credentials named {CREDENTIAL_NAME}") + + payload = { + "name": CREDENTIAL_NAME, + "type": CREDENTIAL_TYPE, + "data": {"token": MCP_TOKEN}, + } + if not matches: + status, body = call(f"{REST}/credentials", method="POST", payload=payload) + if status not in (200, 201): + sys.exit(f"FAILED creating {CREDENTIAL_NAME}: {status} {body}") + created = (body or {}).get("data") if isinstance(body, dict) else body + return {"id": str(created["id"]), "name": CREDENTIAL_NAME}, True + + status, body = call( + f"{REST}/credentials/{matches[0]['id']}", method="PATCH", payload=payload + ) + if status != 200: + sys.exit(f"FAILED updating {CREDENTIAL_NAME}: {status} {body}") + return {"id": str(matches[0]["id"]), "name": CREDENTIAL_NAME}, False + + +def workflow_body(credential): + """Return the managed MCP server workflow as the public API accepts it. + + The trigger serves exactly the tools reaching it over an ``ai_tool`` + connection, so the connection map is the tool allowlist. + + Args: + credential: ``{"id", "name"}`` reference to the managed bearer credential. + """ + return { + "name": WORKFLOW_NAME, + "settings": {"executionOrder": "v1"}, + "nodes": [ + { + "id": "infinito-mcp-trigger", + "name": TRIGGER_NAME, + "type": TRIGGER_TYPE, + "typeVersion": TRIGGER_VERSION, + "position": [0, 0], + "webhookId": "infinito-mcp", + "parameters": { + "path": MCP_PATH, + "authentication": BEARER_AUTH, + }, + "credentials": {CREDENTIAL_TYPE: credential}, + }, + { + "id": "infinito-mcp-health", + "name": TOOL_NAME, + "type": TOOL_TYPE, + "typeVersion": TOOL_VERSION, + "position": [0, 220], + "parameters": { + "description": TOOL_DESCRIPTION, + "language": "javaScript", + "jsCode": TOOL_CODE, + "specifyInputSchema": True, + "schemaType": "manual", + "inputSchema": TOOL_SCHEMA, + }, + }, + ], + "connections": { + TOOL_NAME: { + TOOL_CONNECTION: [ + [{"node": TRIGGER_NAME, "type": TOOL_CONNECTION, "index": 0}] + ] + } + }, + } + + +def activate_workflow(key, workflow_id): + """Activate the managed workflow, failing loudly when n8n refuses. + + Args: + key: the public-API key. + workflow_id: id of the managed workflow. + """ + status, body = call( + f"{PUBLIC}/workflows/{workflow_id}/activate", method="POST", api_key=key + ) + if status != 200: + sys.exit(f"FAILED activating {WORKFLOW_NAME}: {status} {body}") + + +def upsert_workflow(key, credential): + """Create or reconcile the managed MCP server workflow, then activate it. + + Args: + key: the public-API key. + credential: ``{"id", "name"}`` reference to the managed bearer credential. + """ + status, body = call(f"{PUBLIC}/workflows", api_key=key) + if status != 200: + sys.exit(f"FAILED listing workflows: {status} {body}") + + existing = (body or {}).get("data") if isinstance(body, dict) else body + matches = [flow for flow in existing or [] if flow.get("name") == WORKFLOW_NAME] + if len(matches) > 1: + sys.exit(f"FAILED: {len(matches)} workflows named {WORKFLOW_NAME}") + + payload = workflow_body(credential) + if not matches: + status, body = call( + f"{PUBLIC}/workflows", method="POST", payload=payload, api_key=key + ) + if status not in (200, 201): + sys.exit(f"FAILED creating {WORKFLOW_NAME}: {status} {body}") + if not isinstance(body, dict) or "id" not in body: + sys.exit(f"FAILED creating {WORKFLOW_NAME}: no id in {body}") + activate_workflow(key, body["id"]) + return True + + flow = matches[0] + changed = flow.get("nodes") != payload["nodes"] or not flow.get("active") + status, body = call( + f"{PUBLIC}/workflows/{flow['id']}", + method="PUT", + payload=payload, + api_key=key, + ) + if status != 200: + sys.exit(f"FAILED updating {WORKFLOW_NAME}: {status} {body}") + activate_workflow(key, flow["id"]) + return changed + + +def main(): + if not MCP_TOKEN: + sys.exit("FAILED: no bearer configured; the trigger would be unauthenticated") + login() + key, key_id = api_key() + credential, minted = bearer_credential() + changed = upsert_workflow(key, credential) + revoke_key(key_id) + print(f"{'CHANGED' if changed or minted else 'OK'}") + + +if __name__ == "__main__": + main() diff --git a/roles/web-app-n8n/files/test/.nocheck b/roles/web-app-n8n/files/test/.nocheck new file mode 100644 index 0000000000..2b9d82d840 --- /dev/null +++ b/roles/web-app-n8n/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; test-e2e-cli stages files/test/ by that fixed path. diff --git a/roles/web-app-n8n/files/test/test.sh b/roles/web-app-n8n/files/test/test.sh new file mode 100644 index 0000000000..cf546a99a4 --- /dev/null +++ b/roles/web-app-n8n/files/test/test.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# CLI test for web-app-n8n: the MCP endpoint honours its declared contract. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +bash "${here}/shared/mcp/run.sh" diff --git a/roles/web-app-n8n/meta/mcp.yml b/roles/web-app-n8n/meta/mcp.yml new file mode 100644 index 0000000000..4af670689c --- /dev/null +++ b/roles/web-app-n8n/meta/mcp.yml @@ -0,0 +1,32 @@ +--- +classification: native_both +direction: both +source_url: https://github.com/n8n-io/n8n/tree/n8n%401.100.1/packages/%40n8n/nodes-langchain/nodes/mcp +transport: streamable_http +exposure: internal +auth: bearer_token +auth_subject: service_account +implementation: native +credential: + owner: mcp-web-app-n8n + source: token_store + key: web-app-n8n +supported_transports: + - sse +supported_auths: + - bearer_token + - app_password + - upstream_session +endpoint: + service_key: n8n + path: /mcp/infinito-mcp + port_key: http +tools: + read_probe: + tool: infinito_health + arguments: + echo: infinito + allowlist: + - infinito_health + read_only_default: true + mutating_tools_enabled: false diff --git a/roles/web-app-n8n/meta/networks.yml b/roles/web-app-n8n/meta/networks.yml index 78e949896b..e8ef61382f 100644 --- a/roles/web-app-n8n/meta/networks.yml +++ b/roles/web-app-n8n/meta/networks.yml @@ -1,3 +1,8 @@ --- local: subnet: 192.168.218.0/24 +overlay: + modes: [compose, swarm] + topology: shared_net + consumer: + kind: mcp_client diff --git a/roles/web-app-n8n/meta/rbac.yml b/roles/web-app-n8n/meta/rbac.yml new file mode 100644 index 0000000000..084e6fbeca --- /dev/null +++ b/roles/web-app-n8n/meta/rbac.yml @@ -0,0 +1,4 @@ +--- +roles: + mcp: + description: Can drive this application through an MCP client, which acts with the credentials the deployment issued rather than the caller's own diff --git a/roles/web-app-n8n/meta/secrets.yml b/roles/web-app-n8n/meta/secrets.yml index 9524a29d9d..c96567b150 100644 --- a/roles/web-app-n8n/meta/secrets.yml +++ b/roles/web-app-n8n/meta/secrets.yml @@ -1,10 +1,18 @@ --- credentials: + litellm_api_key: + description: Per-consumer virtual key for the shared svc-ai-litellm gateway + algorithm: sk_prefixed + validation: + min_length: 50 encryption_key: - description: "AES encryption key n8n uses to encrypt stored credentials at rest. Must remain stable across deploys โ€” changing it invalidates all saved credentials." + description: "AES encryption key n8n uses to encrypt stored credentials at rest. Must remain stable across deploys โ€” changing it invalidates all saved credentials. + A mismatch between the settings file and the env var makes oclif's findCommand throw for every command, so `n8n export:credentials` is unreachable in exactly + the state that would need it and a re-key is one-way." algorithm: alphanumeric validation: "^[A-Za-z0-9]{32,}$" length: 48 + rotatable: false owner_password: description: "Break-glass local password for the n8n owner account created during bootstrap. Alphanumeric on purpose โ€” the system admin password carries special characters (e.g. Unicode, single quotes) that fail n8n's xssCheck on the /rest/owner/setup endpoint. Normal users authenticate via SSO/Keycloak; this password @@ -12,3 +20,8 @@ credentials: algorithm: alphanumeric validation: "^[A-Za-z0-9]{32,}$" length: 48 + mcp_token: + description: "Bearer an MCP client must present to the managed MCP Server Trigger. Alphanumeric so it survives n8n's xssCheck on the workflow payload." + algorithm: alphanumeric + validation: "^[A-Za-z0-9]{32,}$" + length: 48 diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index 448052c2ba..46a71c10d2 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -6,9 +6,13 @@ sso: shared: "{{ 'web-app-keycloak' in group_names }}" flavor: oauth2 oauth2: + pass_access_token: true origin: host: n8n port: 5678 + allowed_groups: + - "{{ lookup('rbac_group_path', application_id='web-app-n8n', role='administrator') }}" + - "{{ lookup('rbac_group_path', application_id='web-app-n8n', role='mcp') }}" email: bond: 1 enabled: "{{ MAIL_PROVIDER in group_names }}" @@ -47,11 +51,14 @@ tor: bond: 0.5 enabled: "{{ 'svc-net-tor' in group_names }}" shared: true # nocheck: dynamic-flag +# nocheck: playwright-service-flag self-provider n8n: + enabled: true + shared: true + bond: 1 healthcheck: flavor: wget - path: healthz - start_period: 5m + path: healthz/readiness modes: compose: enabled: true @@ -60,7 +67,7 @@ n8n: backup: no_stop_required: false image: docker.n8n.io/n8nio/n8n - version: "1.95.3" + version: "1.100.1" name: n8n min_storage: 422MB cpus: "1.0" @@ -87,3 +94,29 @@ container_backup: # nocheck: bond-baseline backup host joins outside the variant bond: 1 enabled: "{{ 'svc-bkp-volume-2-local' in group_names }}" shared: true +# nocheck: dynamic-flag - the gateway is a single shared instance, never deployed per consumer +litellm: + bond: 0.5 + enabled: "{{ LITELLM_USABLE }}" + shared: true +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openwebui: + bond: 0.5 + enabled: "{{ 'web-app-openwebui' in group_names }}" + shared: "{{ 'web-app-openwebui' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +hermes: + bond: 0.5 + enabled: "{{ 'web-app-hermes' in group_names }}" + shared: "{{ 'web-app-hermes' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openclaw: + bond: 0.5 + enabled: "{{ 'web-app-openclaw' in group_names }}" + shared: "{{ 'web-app-openclaw' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +# nocheck: dynamic-flag the entry refuses this client, so the link is off on every host and no group_names gate can decide it +flowise: + enabled: false + shared: false + mcp_consumer: false diff --git a/roles/web-app-n8n/meta/tests.yml b/roles/web-app-n8n/meta/tests.yml new file mode 100644 index 0000000000..28bea0efe2 --- /dev/null +++ b/roles/web-app-n8n/meta/tests.yml @@ -0,0 +1,3 @@ +--- +cli: + timeout: 900 diff --git a/roles/web-app-n8n/meta/variants.yml b/roles/web-app-n8n/meta/variants.yml index 07533a4e97..a4de279d1d 100644 --- a/roles/web-app-n8n/meta/variants.yml +++ b/roles/web-app-n8n/meta/variants.yml @@ -25,9 +25,20 @@ prometheus: enabled: true shared: true + litellm: + enabled: true tor: enabled: true + openwebui: + enabled: true + shared: true + hermes: + enabled: true + shared: true + openclaw: + enabled: true + shared: true - services: container_backup: enabled: false @@ -55,5 +66,16 @@ prometheus: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true + litellm: + enabled: false tor: enabled: true + openwebui: + enabled: false + shared: false + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false diff --git a/roles/web-app-n8n/tasks/00_core.yml b/roles/web-app-n8n/tasks/00_core.yml index de7327d0da..e81fb776d4 100644 --- a/roles/web-app-n8n/tasks/00_core.yml +++ b/roles/web-app-n8n/tasks/00_core.yml @@ -43,5 +43,16 @@ include_tasks: file: 01_bootstrap.yml apply: - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" run_once: true + +- name: "๐Ÿค– Bind the native AI surface to the platform gateway" + include_tasks: + file: utils/ai_gateway.yml + when: N8N_LITELLM_ENABLED | bool + +- name: "๐Ÿ”Œ Provision the MCP surface" + include_tasks: + file: utils/mcp.yml + apply: + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + when: N8N_MCP_ENABLED | bool diff --git a/roles/web-app-n8n/tasks/01_bootstrap.yml b/roles/web-app-n8n/tasks/01_bootstrap.yml index 46e4527223..8b48b86b26 100644 --- a/roles/web-app-n8n/tasks/01_bootstrap.yml +++ b/roles/web-app-n8n/tasks/01_bootstrap.yml @@ -29,6 +29,7 @@ until: "'json' in (n8n_owner_probe.content_type | default(''))" retries: 4 delay: 30 + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - name: "๐Ÿ”ง Initialise n8n owner account (first-time only)" uri_retry: @@ -44,6 +45,7 @@ return_content: true register: n8n_owner_setup when: n8n_owner_probe.status != 200 + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - name: "โœ… Assert n8n owner setup succeeded or was already done" ansible.builtin.assert: @@ -53,3 +55,52 @@ or (n8n_owner_setup.status in [200, 201]) or ('already setup' in (n8n_owner_setup.content | default(''))) fail_msg: "n8n owner setup returned {{ n8n_owner_setup.status | default('n/a') }}: {{ n8n_owner_setup.content | default('') }}" + +- name: "๐Ÿ” Resolve {{ application_id }} hosting node + container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ entity_name }}" + resolve_output_prefix: N8N + resolve_compose_cid: "{{ N8N_CONTAINER }}" + +- name: "๐Ÿ” Converge a rotated owner password n8n still rejects" + when: + - n8n_owner_probe.status in [401, 403] + - "'already setup' in (n8n_owner_setup.content | default(''))" + block: + - name: "๐Ÿ” Write the deployed owner password into n8n's user row" + ansible.builtin.command: + argv: + - container + - exec + - -i + - -e + - "NODE_PATH={{ N8N_NODE_MODULES }}" + - -e + - "N8N_OWNER_EMAIL={{ N8N_OWNER_EMAIL }}" + - -e + - "N8N_OWNER_PASSWORD={{ N8N_OWNER_PASSWORD }}" + - "{{ N8N_LOCAL_CID }}" # nocheck: container-exec-resolver + - node + - "-" + stdin: "{{ lookup('file', 'javascript/reconcile/owner_password.js') }}" + register: n8n_owner_password + retries: 30 + delay: 10 + until: n8n_owner_password.rc == 0 + changed_when: n8n_owner_password.stdout.startswith('CHANGED') + delegate_to: "{{ N8N_HOST_NODE }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + + - name: "๐Ÿ”Ž Confirm the owner signs in with the deployed password" + uri_retry: + url: "{{ N8N_INTERNAL_API_URL }}/rest/login" + method: POST + body_format: json + body: + emailOrLdapLoginId: "{{ lookup('users', 'administrator').email }}" + password: "{{ N8N_OWNER_PASSWORD }}" + status_code: [200] + return_content: false + retries: 0 + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-n8n/tasks/utils/ai_gateway.yml b/roles/web-app-n8n/tasks/utils/ai_gateway.yml new file mode 100644 index 0000000000..1a43b5d77b --- /dev/null +++ b/roles/web-app-n8n/tasks/utils/ai_gateway.yml @@ -0,0 +1,25 @@ +--- +- name: "๐Ÿ” Verify the gateway contract for {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-litellm/tasks/utils/consumer_contract.yml') }}" + +- name: "๐Ÿค– Provision the managed OpenAI credential against the gateway" + ansible.builtin.command: + argv: + - python3 + - "-" + stdin: "{{ lookup('file', 'python/provision/ai.py') }}" + environment: + N8N_BASE: "{{ N8N_INTERNAL_API_URL }}" + N8N_OWNER_EMAIL: "{{ N8N_OWNER_EMAIL }}" + N8N_OWNER_PASSWORD: "{{ N8N_OWNER_PASSWORD }}" + N8N_AI_CREDENTIAL: "{{ N8N_LITELLM_CREDENTIAL_NAME }}" + N8N_AI_BASE_URL: "{{ N8N_LITELLM_BASE_URL }}" + N8N_AI_API_KEY: "{{ N8N_LITELLM_API_KEY }}" + register: n8n_ai_provision + retries: 30 + delay: 10 + until: n8n_ai_provision.rc == 0 + changed_when: n8n_ai_provision.stdout.startswith('CHANGED') + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ STACK_HOST }}" + run_once: true diff --git a/roles/web-app-n8n/tasks/utils/mcp.yml b/roles/web-app-n8n/tasks/utils/mcp.yml new file mode 100644 index 0000000000..8967a3eaf0 --- /dev/null +++ b/roles/web-app-n8n/tasks/utils/mcp.yml @@ -0,0 +1,55 @@ +--- +- name: "๐Ÿ”Œ Provision the managed MCP trigger workflow" + ansible.builtin.command: + argv: + - python3 + - "-" + stdin: "{{ lookup('file', 'python/provision/mcp.py') }}" + environment: + N8N_BASE: "{{ N8N_INTERNAL_API_URL }}" + N8N_OWNER_EMAIL: "{{ N8N_OWNER_EMAIL }}" + N8N_OWNER_PASSWORD: "{{ N8N_OWNER_PASSWORD }}" + N8N_API_KEY_NAME: "{{ N8N_MCP_API_KEY_NAME }}" + N8N_MCP_PATH: "{{ N8N_MCP_WEBHOOK_PATH }}" + N8N_MCP_TOKEN: "{{ N8N_MCP_TOKEN }}" + N8N_MCP_WORKFLOW: "{{ N8N_MCP_WORKFLOW_NAME }}" + N8N_MCP_CREDENTIAL: "{{ N8N_MCP_CREDENTIAL_NAME }}" + register: n8n_mcp_provision + retries: 30 + delay: 10 + until: n8n_mcp_provision.rc == 0 + changed_when: n8n_mcp_provision.stdout.startswith('CHANGED') + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ STACK_HOST }}" + run_once: true + +- name: "๐Ÿ’พ Persist the MCP bearer so clients can read it" + ansible.builtin.include_role: + name: sys-token-store + tasks_from: write.yml + vars: + sys_token_store_user_key: "{{ lookup('config', application_id, 'mcp.credential.owner') }}" + sys_token_store_app: "{{ application_id }}" + sys_token_store_token: "{{ N8N_MCP_TOKEN }}" + +- name: "๐Ÿ”Œ Reconcile the managed agent over every discovered MCP provider" + ansible.builtin.command: + argv: + - python3 + - "-" + stdin: "{{ lookup('file', 'python/provision/client.py') }}" + environment: + N8N_AI_CREDENTIAL: "{{ N8N_LITELLM_CREDENTIAL_NAME }}" + N8N_API_KEY_NAME: "{{ N8N_MCP_API_KEY_NAME }}" + N8N_BASE: "{{ N8N_INTERNAL_API_URL }}" + N8N_CHAT_MODEL: "{{ LITELLM_CHAT_MODEL }}" + N8N_CLIENT_WORKFLOW: "{{ N8N_MCP_CLIENT_WORKFLOW_NAME }}" + N8N_MCP_PROVIDERS: "{{ N8N_MCP_PROVIDERS | to_json }}" + N8N_OWNER_EMAIL: "{{ N8N_OWNER_EMAIL }}" + N8N_OWNER_PASSWORD: "{{ N8N_OWNER_PASSWORD }}" + register: n8n_client_provision + changed_when: n8n_client_provision.stdout.startswith('CHANGED') + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ STACK_HOST }}" + run_once: true + when: N8N_LITELLM_ENABLED | bool diff --git a/roles/web-app-n8n/templates/env.j2 b/roles/web-app-n8n/templates/env.j2 index 874160d750..b9743c2010 100644 --- a/roles/web-app-n8n/templates/env.j2 +++ b/roles/web-app-n8n/templates/env.j2 @@ -21,6 +21,10 @@ EXTERNAL_HOOK_FILES={{ N8N_HOOKS_FILE_CONTAINER }} N8N_FORWARD_AUTH_HEADER=Remote-Email {% endif %} +{% if N8N_LITELLM_ENABLED | bool %} +N8N_AI_ENABLED=true +{% endif %} + {% set email = lookup('email', application_id) %} {% if email.enabled | bool %} N8N_EMAIL_MODE=smtp diff --git a/roles/web-app-n8n/templates/playwright.env.j2 b/roles/web-app-n8n/templates/playwright.env.j2 index 9f028c0ba0..42754bde3c 100644 --- a/roles/web-app-n8n/templates/playwright.env.j2 +++ b/roles/web-app-n8n/templates/playwright.env.j2 @@ -15,14 +15,26 @@ CANONICAL_DOMAIN={{ lookup('domain', application_id) | dotenv_quote }} # nocheck: playwright-service-gate โ€” covered by sys-svc-mail integration tests, not the persona surface EMAIL_SERVICE_ENABLED={{ lookup('config', application_id, 'services.email.enabled') | string | lower }} +LITELLM_SERVICE_ENABLED={{ N8N_LITELLM_ENABLED | string | lower }} + LOGOUT_SERVICE_ENABLED={{ lookup('config', application_id, 'services.logout.enabled') | string | lower }} MATOMO_BASE_URL={{ lookup('tls', 'web-app-matomo', 'url.base') | dotenv_quote }} MATOMO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.matomo.enabled') | string | lower }} +MCP_ENDPOINT_PATH={{ lookup('config', application_id, 'mcp.endpoint.path') | dotenv_quote }} + +MCP_SERVICE_ENABLED={{ N8N_MCP_ENABLED | string | lower }} + N8N_BASE_URL={{ lookup('tls', application_id, 'url.base') | dotenv_quote }} +N8N_LITELLM_BASE_URL={{ N8N_LITELLM_BASE_URL | dotenv_quote }} + +N8N_LITELLM_CREDENTIAL_NAME={{ N8N_LITELLM_CREDENTIAL_NAME | dotenv_quote }} + +N8N_LITELLM_MODEL={{ LITELLM_CHAT_MODEL | dotenv_quote }} + N8N_OWNER_PASSWORD={{ N8N_OWNER_PASSWORD | dotenv_quote }} OIDC_ISSUER_URL={{ OIDC.CLIENT.ISSUER_URL | dotenv_quote }} diff --git a/roles/web-app-n8n/templates/proxy.conf.j2 b/roles/web-app-n8n/templates/proxy.conf.j2 index f73ec9b0f0..7f88f8b30f 100644 --- a/roles/web-app-n8n/templates/proxy.conf.j2 +++ b/roles/web-app-n8n/templates/proxy.conf.j2 @@ -29,4 +29,6 @@ server {% endif %} {% include 'roles/web-app-prometheus/templates/nginx/locations.conf.j2' %} + + {% include 'roles/sys-svc-proxy/templates/mcp/vhost.conf.j2' %} } diff --git a/roles/web-app-n8n/templates/test.env.j2 b/roles/web-app-n8n/templates/test.env.j2 new file mode 100644 index 0000000000..3c7bacad44 --- /dev/null +++ b/roles/web-app-n8n/templates/test.env.j2 @@ -0,0 +1 @@ +{{ lookup('template', lookup('path_absolute', 'roles/test-e2e-cli/templates/mcp/test.env.j2')) }} diff --git a/roles/web-app-n8n/vars/main.yml b/roles/web-app-n8n/vars/main.yml index a15ab08183..d196121c95 100644 --- a/roles/web-app-n8n/vars/main.yml +++ b/roles/web-app-n8n/vars/main.yml @@ -10,10 +10,26 @@ N8N_HOSTNAME: "{{ lookup('domain', application_id) }}" N8N_WEB_PROTOCOL: "{{ lookup('tls', application_id, 'protocols.web') }}" N8N_ENCRYPTION_KEY: "{{ lookup('config', application_id, 'secrets.credentials.encryption_key') }}" N8N_OWNER_PASSWORD: "{{ lookup('config', application_id, 'secrets.credentials.owner_password') }}" +N8N_NODE_MODULES: /usr/local/lib/node_modules/n8n/node_modules N8N_INTERNAL_API_URL: "http://{{ DOCKER_REACH_HOST }}:{{ N8N_HTTP_PORT }}" N8N_SSO_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') | bool }}" +N8N_MCP_ENABLED: "{{ lookup('config', application_id, 'mcp.enabled') | bool }}" +N8N_OWNER_EMAIL: "{{ lookup('users', 'administrator').email }}" +N8N_MCP_TOKEN: "{{ lookup('config', application_id, 'secrets.credentials.mcp_token') }}" +N8N_MCP_API_KEY_NAME: "infinito:mcp" +N8N_MCP_WORKFLOW_NAME: "infinito:mcp-server" +N8N_MCP_CREDENTIAL_NAME: "infinito:mcp-bearer" +N8N_MCP_WEBHOOK_PATH: "infinito-mcp" +N8N_MCP_CLIENT_WORKFLOW_NAME: "infinito:mcp-agent" +N8N_MCP_PROVIDERS: "{{ MCP_DISCOVERED_SERVERS if N8N_MCP_ENABLED else [] }}" + +N8N_LITELLM_ENABLED: "{{ lookup('config', application_id, 'services.litellm.enabled') | bool }}" +N8N_LITELLM_BASE_URL: "{{ LITELLM_OPENAI_BASE_LOCAL_URL }}" +N8N_LITELLM_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.litellm_api_key') }}" +N8N_LITELLM_CREDENTIAL_NAME: "infinito:litellm" + N8N_HOOKS_FILE_HOST: "{{ [ lookup('container', application_id, 'directories.instance'), 'hooks.js' ] | path_join }}" N8N_HOOKS_FILE_CONTAINER: "{{ lookup('volume', 'web-app-n8n', 'hooks').target }}" # nocheck: container-var-name-lookup diff --git a/roles/web-app-navigator/README.md b/roles/web-app-navigator/README.md index d54ac86ff4..0e05dba9de 100644 --- a/roles/web-app-navigator/README.md +++ b/roles/web-app-navigator/README.md @@ -72,19 +72,20 @@ Run the published image to provision the inventory and deploy Presentation to a ```bash APP=web-app-navigator HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-navigator/meta/info.yml b/roles/web-app-navigator/meta/info.yml index 0029896cff..859c342f69 100644 --- a/roles/web-app-navigator/meta/info.yml +++ b/roles/web-app-navigator/meta/info.yml @@ -1,3 +1,4 @@ --- +# nocheck: info-media Self-written role that builds and serves Infinito.Nexus's own project presentation (Reveal.js slides pulled from their own source repo). No third-party consumer-facing upstream product; Reveal.js is only the rendering library, not the deployed product. logo: class: fas fa-map diff --git a/roles/web-app-navigator/meta/main.yml b/roles/web-app-navigator/meta/main.yml index b3f58769e6..a17ed3eb5c 100644 --- a/roles/web-app-navigator/meta/main.yml +++ b/roles/web-app-navigator/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media Self-written role that builds and serves Infinito.Nexus's own project presentation (Reveal.js slides pulled from their own source repo). No third-party consumer-facing upstream product; Reveal.js is only the rendering library, not the deployed product. galaxy_info: author: Kevin Veen-Birkenbach description: Containerized Reveal.js slide deck for presenting the platform to admins, developers, users, and investors diff --git a/roles/web-app-nextcloud/README.md b/roles/web-app-nextcloud/README.md index 0f269ad57e..e3a3df494f 100644 --- a/roles/web-app-nextcloud/README.md +++ b/roles/web-app-nextcloud/README.md @@ -15,6 +15,7 @@ The diagram places Nextcloud in the Infinito.Nexus cosmos: the components it dep ```mermaid flowchart LR subgraph deps [Dependencies] + dep_svc_ai_litellm["svc-ai-litellm ๐Ÿณ๐Ÿ"] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local ๐Ÿ’ป"] dep_svc_db_mariadb["svc-db-mariadb ๐Ÿณ๐Ÿ"] dep_svc_db_openldap["svc-db-openldap ๐Ÿณ๐Ÿ"] @@ -23,14 +24,15 @@ flowchart LR dep_web_app_bigbluebutton["web-app-bigbluebutton ๐Ÿณ๐Ÿ"] dep_web_app_dashboard["web-app-dashboard ๐Ÿณ๐Ÿ"] dep_web_app_discourse["web-app-discourse ๐Ÿณ๐Ÿ"] - dep_web_app_flowise["web-app-flowise ๐Ÿณ๐Ÿ"] dep_web_app_gitlab["web-app-gitlab ๐Ÿณ๐Ÿ"] + dep_web_app_hermes["web-app-hermes ๐Ÿณ๐Ÿ"] dep_web_app_keycloak["web-app-keycloak ๐Ÿณ๐Ÿ"] dep_web_app_mailu["web-app-mailu ๐Ÿณ๐Ÿ"] dep_web_app_mastodon["web-app-mastodon ๐Ÿณ๐Ÿ"] dep_web_app_matomo["web-app-matomo ๐Ÿณ๐Ÿ"] dep_web_app_matrix["web-app-matrix ๐Ÿณ๐Ÿ"] dep_web_app_mattermost["web-app-mattermost ๐Ÿณ๐Ÿ"] + dep_web_app_openclaw["web-app-openclaw ๐Ÿณ๐Ÿ"] dep_web_app_openproject["web-app-openproject ๐Ÿณ๐Ÿ"] dep_web_app_openwebui["web-app-openwebui ๐Ÿณ๐Ÿ"] dep_web_app_peertube["web-app-peertube ๐Ÿณ๐Ÿ"] @@ -56,6 +58,8 @@ flowchart LR svc_mariadb["mariadb"] svc_nextcloud["nextcloud"] svc_proxy["proxy"] + svc_context_agent["context_agent"] + svc_contextagentmcp["contextagentmcp"] svc_cron["cron"] svc_talk["talk"] svc_whiteboard["whiteboard"] @@ -77,13 +81,17 @@ flowchart LR svc_matrix["matrix"] svc_zammad["zammad"] svc_openwebui["openwebui"] - svc_flowise["flowise"] + svc_litellm["litellm"] svc_mastodon["mastodon"] svc_peertube["peertube"] svc_moodle["moodle โŒ"] svc_suitecrm["suitecrm โŒ"] svc_container_backup["container_backup"] + svc_hermes["hermes"] + svc_openclaw["openclaw"] + svc_flowise["flowise โŒ"] end + dep_svc_ai_litellm -. "0..1" .-> svc_litellm dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup dep_svc_db_mariadb -. "0..1" .-> svc_mariadb dep_svc_db_openldap -. "0..1" .-> svc_ldap @@ -92,14 +100,15 @@ flowchart LR dep_web_app_bigbluebutton -. "0..1" .-> svc_bigbluebutton dep_web_app_dashboard -. "0..1" .-> svc_dashboard dep_web_app_discourse -. "0..1" .-> svc_discourse - dep_web_app_flowise -. "0..1" .-> svc_flowise dep_web_app_gitlab -. "0..1" .-> svc_gitlab + dep_web_app_hermes -. "0..1" .-> svc_hermes dep_web_app_keycloak -. "0..1" .-> svc_sso dep_web_app_mailu -. "0..1" .-> svc_email dep_web_app_mastodon -. "0..1" .-> svc_mastodon dep_web_app_matomo -. "0..1" .-> svc_matomo dep_web_app_matrix -. "0..1" .-> svc_matrix dep_web_app_mattermost -. "0..1" .-> svc_mattermost + dep_web_app_openclaw -. "0..1" .-> svc_openclaw dep_web_app_openproject -. "0..1" .-> svc_openproject dep_web_app_openwebui -. "0..1" .-> svc_openwebui dep_web_app_peertube -. "0..1" .-> svc_peertube @@ -146,19 +155,20 @@ Run the published image to provision the inventory and deploy Nextcloud to a man ```bash APP=web-app-nextcloud HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' @@ -183,6 +193,73 @@ The enable-only appstore apps stay under `nextcloud.plugins` in [`meta/services. The SSO (`sociallogin`) and LDAP (`user_ldap`) login surfaces are covered by the OIDC/LDAP Playwright specs (requirements 017/018). +## MCP Server + +Nextcloud serves a Model Context Protocol endpoint through the AppAPI proxy of the `context_agent` ExApp. + +| Property | Value | +|----------|-------| +| Endpoint | `/mcp` on the `contextagentmcp` adapter sidecar | +| Container-network URL | `http://contextagentmcp:8080/mcp` | +| Transport | Streamable HTTP | +| Exposure | internal (the sidecar is reachable on the container network only; the hub's own MCP route is not published to clients) | +| Auth | `credentials.mcp_bearer`, sent as `Authorization: Bearer ` | +| Identity | the Nextcloud account the app password belongs to; every tool call the adapter forwards runs with that account's permissions | +| Implementation | adapter (`svc-ai-mcp-adapter` in `mcp_passthrough` mode, fronting the `context_agent` ExApp) | +| Default state | off; `mcp.enabled` turns on when `web-app-hermes`, `web-app-openclaw` or `web-app-openwebui` is deployed | + +### Deployment + +The `context_agent` and `contextagentmcp` services in [`meta/services.yml`](./meta/services.yml) render only while `mcp.enabled` is true. The first runs `ghcr.io/nextcloud/context_agent`, listens on its internal port for AppAPI only, and shares `credentials.context_agent_app_secret` with the ExApp registration as `APP_SECRET`. The second is the adapter sidecar, built from the staged `svc-ai-mcp-adapter` context, read-only with every capability dropped, and it is the only MCP endpoint clients are given. + +The sidecar reads its upstream credential from an `upstream.env` file rather than from the compose environment, because the app password does not exist when the stack is first rendered. [`tasks/utils/mcp.yml`](./tasks/utils/mcp.yml) writes that file after the mint and recreates the sidecar through `svc-ai-mcp-adapter`'s `rebuild.yml`: `compose up` resolves `env_file` while creating the container, which a restart would not. + +[`tasks/utils/mcp.yml`](./tasks/utils/mcp.yml) waits for the ExApp heartbeat, registers the deploy daemon and the ExApp (route `^/mcp`, verbs `POST,GET,DELETE`, access level `1`), enables the ExApp, mints an app password for the dedicated MCP account via `occ user:auth-tokens:add`, persists it through `sys-token-store` under `users['mcp-web-app-nextcloud'].tokens['web-app-nextcloud']`, and asserts that an authenticated `initialize` call answers `200`. + +### Authorization subject + +`auth_subject: service_account`: [`tasks/utils/mcp/token.yml`](./tasks/utils/mcp/token.yml) creates the account `NEXTCLOUD_MCP_USERNAME` with `occ user:add` if it is missing, mints the app password against that account, and stores it under `mcp.credential.owner`. Every call carries that account's rights, not the administrator's, no matter who asked the client. Reaching the tool server is gated on the role's `mcp` RBAC group, which is a separate grant from holding a Nextcloud account. + +### Tool categories + +The 2.7.0 image ships 23 tool categories, which are application names (`calendar`, `files`, `mail`, `talk`, โ€ฆ) rather than operations: each bundles its read and its write tools, and the hub offers no setting that removes only the mutating ones. Enabling the ExApp writes `true` for every category absent from `tool_status`, so the hub itself serves all of them, write tools included. + +The adapter is what bounds that. [`files/mcp/tools.json`](./files/mcp/tools.json) names the nine read tools of `calendar`, `contacts` and `files` โ€” the three categories whose upstream `is_available` is unconditional, so the set does not vary with which optional apps a deployment installs. `svc-ai-mcp-adapter` refuses any tool outside that list and any tool marked `mutating` while `mutating_tools_enabled` is false, and it refuses to start at all if the contract's `schema_sha256` does not match the file. The refusal happens in the sidecar, so it holds for every client regardless of what each renders locally. + +The hub keeps all its categories. Nextcloud's own Assistant is unaffected by the bound: it reads the same `tool_status`, and nothing here narrows it. + +The app password never reaches a client. Clients present `credentials.mcp_bearer` to the sidecar; the sidecar presents the app password upstream. Revoking one does not revoke the other. + +```bash +occ app_api:app:config:get context_agent tool_status +occ app_api:app:config:set context_agent tool_status --value '' +``` + +Widening the exposed set means adding the tool to `files/mcp/tools.json`, recomputing both `adapter.specification_sha256` and `tools.schema_sha256`, and listing it in `mcp.tools.allowlist`. + +### Verification + +The sidecar is reachable on the container network only, so a client probes it from inside the stack: + +```bash +curl -i -X POST \ + -H 'Authorization: Bearer ' \ + -H 'Accept: application/json, text/event-stream' \ + -H 'Content-Type: application/json' \ + --data '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"cli","version":"1"}}}' \ + http://contextagentmcp:8080/mcp +``` + +From outside, every MCP path answers `404`. The hub serves its route under two spellings โ€” with and without the `/index.php` front controller โ€” and `roles/sys-svc-proxy/templates/mcp/vhost.conf.j2` withdraws both, so neither reaches the Context Agent. [`files/playwright/test-mcp-guest.js`](./files/playwright/test-mcp-guest.js) probes all three public paths and asserts each answers `>= 300` without an MCP protocol body. + +### Default state + +Off. `mcp.enabled` is true only while `web-app-hermes`, `web-app-openclaw` or `web-app-openwebui` is part of the deployment. + +### How to disable + +Remove the MCP client roles, or pin `mcp.enabled: false` for this role. The `context_agent` service is then not rendered, the ExApp is not registered with AppAPI, and no app password is minted. + ## Documentation A detailed documentation for the use and administration of Nextcloud on Infinito.Nexus you will find [here](docs/README.md). diff --git a/roles/web-app-nextcloud/files/mcp/tools.json b/roles/web-app-nextcloud/files/mcp/tools.json new file mode 100644 index 0000000000..af1ec30bbc --- /dev/null +++ b/roles/web-app-nextcloud/files/mcp/tools.json @@ -0,0 +1,146 @@ +{ + "find_details_of_current_user": { + "description": "Find the current user's personal information.", + "input_schema": { + "properties": {}, + "type": "object" + }, + "mutating": false + }, + "find_free_time_slot_in_calendar": { + "description": "Find a time slot in which every participant is free.", + "input_schema": { + "properties": { + "end_time": { + "description": "End of the range to search, as YYYY-MM-DD. Defaults to seven days after start_time.", + "type": "string" + }, + "participants": { + "description": "Email addresses of the participants to find a common slot for.", + "items": { + "type": "string" + }, + "type": "array" + }, + "slot_duration": { + "description": "Length of the slot in hours. Defaults to one hour.", + "type": "number" + }, + "start_time": { + "description": "Start of the range to search, as YYYY-MM-DD. Defaults to now.", + "type": "string" + } + }, + "required": [ + "participants" + ], + "type": "object" + }, + "mutating": false + }, + "find_person_in_contacts": { + "description": "Find a person's contact details by name, returning email, phone and address.", + "input_schema": { + "properties": { + "name": { + "description": "The name to search the address book for.", + "type": "string" + } + }, + "required": [ + "name" + ], + "type": "object" + }, + "mutating": false + }, + "find_person_in_users": { + "description": "Search the instance's users and return their user IDs.", + "input_schema": { + "properties": { + "search_term": { + "description": "The term to find the user by.", + "type": "string" + } + }, + "required": [ + "search_term" + ], + "type": "object" + }, + "mutating": false + }, + "get_file_content": { + "description": "Return the content of one file.", + "input_schema": { + "properties": { + "file_path": { + "description": "Path of the file inside the user's Files.", + "type": "string" + } + }, + "required": [ + "file_path" + ], + "type": "object" + }, + "mutating": false + }, + "get_file_content_by_file_link": { + "description": "Return the content of one file addressed by an internal Nextcloud link.", + "input_schema": { + "properties": { + "file_url": { + "description": "Internal file URL, for example https://host/index.php/f/12345.", + "type": "string" + } + }, + "required": [ + "file_url" + ], + "type": "object" + }, + "mutating": false + }, + "get_folder_tree": { + "description": "List the files the user holds in Nextcloud Files as a folder tree.", + "input_schema": { + "properties": { + "depth": { + "description": "Depth of the returned tree.", + "type": "integer" + } + }, + "required": [ + "depth" + ], + "type": "object" + }, + "mutating": false + }, + "list_calendars": { + "description": "List every existing calendar by name.", + "input_schema": { + "properties": {}, + "type": "object" + }, + "mutating": false + }, + "list_tasks": { + "description": "List tasks from the calendars, optionally narrowed by calendar and status.", + "input_schema": { + "properties": { + "calendar_name": { + "description": "Name of the calendar to list from, as returned by list_calendars. Omit to list from all.", + "type": "string" + }, + "filter_status": { + "description": "One of NEEDS-ACTION, COMPLETED, IN-PROCESS or CANCELLED.", + "type": "string" + } + }, + "type": "object" + }, + "mutating": false + } +} diff --git a/roles/web-app-nextcloud/files/playwright/_page.js b/roles/web-app-nextcloud/files/playwright/_page.js new file mode 100644 index 0000000000..941611a561 --- /dev/null +++ b/roles/web-app-nextcloud/files/playwright/_page.js @@ -0,0 +1,164 @@ +const { resolveTimeout } = require("./timeouts"); +const { findFirstVisibleCandidate } = require("./personas"); + +function getNextcloudShellCandidates(target) { + return [ + { + kind: "shell", + locator: target.locator("#app-content-vue, #app-navigation-vue, #app-dashboard") + }, + { + kind: "shell", + locator: target.locator("nav.app-menu, #user-menu") + } + ]; +} + +async function waitForFirstVisible(page, locators, timeout = resolveTimeout(60_000)) { + const deadline = Date.now() + timeout; + + while (Date.now() < deadline) { + for (const locator of locators) { + if (await locator.first().isVisible().catch(() => false)) { + return locator.first(); + } + } + + await page.waitForTimeout(resolveTimeout(500)); + } + + throw new Error("Timed out waiting for one of the expected Nextcloud selectors to become visible"); +} + +const serverErrorByPage = new WeakMap(); +const LOGIN_CALLBACK = /\/apps\/(?:sociallogin|oidc_login)\//; + +function trackServerErrors(page) { + if (serverErrorByPage.has(page)) { + return; + } + + serverErrorByPage.set(page, null); + page.on("response", (response) => { + const request = response.request(); + + if (request.resourceType() !== "document") { + return; + } + + if (request.frame() !== page.mainFrame()) { + return; + } + + const status = response.status(); + const url = response.url().split("?")[0]; + const failed = status >= 500 || (status >= 400 && LOGIN_CALLBACK.test(url)); + serverErrorByPage.set(page, failed ? { status, url } : null); + }); +} + +async function waitForVisibleCandidate( + page, + candidates, + timeout = resolveTimeout(60_000), + errorMessage = "Timed out waiting for one of the expected Nextcloud selectors to become visible" +) { + const deadline = Date.now() + timeout; + + trackServerErrors(page); + + while (Date.now() < deadline) { + const visibleCandidate = await findFirstVisibleCandidate(candidates); + + if (visibleCandidate) { + return visibleCandidate; + } + + const serverError = serverErrorByPage.get(page); + + if (serverError) { + throw new Error( + `${errorMessage} โ€” the page itself failed: HTTP ${serverError.status} for ${serverError.url}` + ); + } + + await page.waitForTimeout(resolveTimeout(500)); + } + + throw new Error(errorMessage); +} + +async function dismissBlockingNextcloudModals(page, nextcloudFrame, maxDismissals = 4) { + const modalOverlay = nextcloudFrame.locator( + "#firstrunwizard.modal-mask, #firstrunwizard[role='dialog'], .modal-mask[role='dialog'], [role='dialog'][aria-modal='true']" + ); + const dismissButtonCandidates = [ + nextcloudFrame.getByRole("button", { name: /^close$/i }), + nextcloudFrame.getByRole("button", { name: /^schlie(?:ss|รŸ)en$/i }), + nextcloudFrame.locator( + ".modal-mask .modal-container__close, .modal-mask .header-close, [role='dialog'] .modal-container__close, [role='dialog'] .header-close" + ), + nextcloudFrame.locator( + ".modal-mask .next, .modal-mask button[aria-label='Next'], [role='dialog'] .next, [role='dialog'] button[aria-label='Next']" + ), + nextcloudFrame.getByRole("button", { name: /skip|not now|later|dismiss|done|got it/i }) + ]; + let stableChecksWithoutModal = 0; + + for (let i = 0; i < maxDismissals; i += 1) { + if (!(await modalOverlay.first().isVisible().catch(() => false))) { + stableChecksWithoutModal += 1; + if (stableChecksWithoutModal >= 2) { + return; + } + await page.waitForTimeout(resolveTimeout(600)); + continue; + } + + stableChecksWithoutModal = 0; + let dismissed = false; + + for (const candidate of dismissButtonCandidates) { + const button = candidate.first(); + if (await button.isVisible().catch(() => false)) { + await button.click({ timeout: resolveTimeout(2_000) }).catch(() => {}); + dismissed = true; + break; + } + } + + if (!dismissed) { + await page.keyboard.press("Escape").catch(() => {}); + } + + await page.waitForTimeout(resolveTimeout(300)); + } +} + +async function clickWithModalRetry(page, nextcloudFrame, target, attempts = 5) { + for (let attempt = 1; attempt <= attempts; attempt += 1) { + await dismissBlockingNextcloudModals(page, nextcloudFrame, 6); + + try { + await target.click({ timeout: resolveTimeout(4_000) }); + return; + } catch (error) { + const message = String(error && error.message ? error.message : error); + const retriable = /intercepts pointer events|timed out|timeout/i.test(message); + + if (!retriable || attempt === attempts) { + throw error; + } + await page.waitForTimeout(resolveTimeout(500)); + } + } +} + +module.exports = { + getNextcloudShellCandidates, + waitForFirstVisible, + trackServerErrors, + waitForVisibleCandidate, + dismissBlockingNextcloudModals, + clickWithModalRetry, +}; diff --git a/roles/web-app-nextcloud/files/playwright/_shared.js b/roles/web-app-nextcloud/files/playwright/_shared.js index 7de3647021..06dd40577f 100644 --- a/roles/web-app-nextcloud/files/playwright/_shared.js +++ b/roles/web-app-nextcloud/files/playwright/_shared.js @@ -2,6 +2,14 @@ const { expect } = require("@playwright/test"); const { resolveTimeout } = require("./timeouts"); const { decodeDotenvQuotedValue, findFirstVisibleCandidate, runAdminFlow, runBiberFlow, runGuestFlow } = require("./personas"); const { isServiceEnabled } = require("./service-gating"); +const { + getNextcloudShellCandidates, + waitForFirstVisible, + trackServerErrors, + waitForVisibleCandidate, + dismissBlockingNextcloudModals, + clickWithModalRetry, +} = require("./_page"); const loginUsername = decodeDotenvQuotedValue(process.env.LOGIN_USERNAME); const loginPassword = decodeDotenvQuotedValue(process.env.LOGIN_PASSWORD); @@ -25,160 +33,6 @@ const nextcloudLoginFlavor = !nextcloudOidcEnabled ? "oidc_login" : "sociallogin"; -function getNextcloudShellCandidates(target) { - return [ - { - kind: "shell", - locator: target.locator("#app-content-vue, #app-navigation-vue, #app-dashboard") - }, - { - kind: "shell", - locator: target.locator("nav.app-menu, #user-menu") - } - ]; -} - -async function waitForFirstVisible(page, locators, timeout = resolveTimeout(60_000)) { - const deadline = Date.now() + timeout; - - while (Date.now() < deadline) { - for (const locator of locators) { - if (await locator.first().isVisible().catch(() => false)) { - return locator.first(); - } - } - - await page.waitForTimeout(resolveTimeout(500)); - } - - throw new Error("Timed out waiting for one of the expected Nextcloud selectors to become visible"); -} - -const serverErrorByPage = new WeakMap(); - -function trackServerErrors(page) { - if (serverErrorByPage.has(page)) { - return; - } - - serverErrorByPage.set(page, null); - page.on("response", (response) => { - const request = response.request(); - - if (request.resourceType() !== "document") { - return; - } - - if (request.frame() !== page.mainFrame()) { - return; - } - - serverErrorByPage.set( - page, - response.status() >= 500 - ? { status: response.status(), url: response.url() } - : null - ); - }); -} - -async function waitForVisibleCandidate( - page, - candidates, - timeout = resolveTimeout(60_000), - errorMessage = "Timed out waiting for one of the expected Nextcloud selectors to become visible" -) { - const deadline = Date.now() + timeout; - - trackServerErrors(page); - - while (Date.now() < deadline) { - const visibleCandidate = await findFirstVisibleCandidate(candidates); - - if (visibleCandidate) { - return visibleCandidate; - } - - const serverError = serverErrorByPage.get(page); - - if (serverError) { - throw new Error( - `${errorMessage} โ€” the page itself failed: HTTP ${serverError.status} for ${serverError.url}` - ); - } - - await page.waitForTimeout(resolveTimeout(500)); - } - - throw new Error(errorMessage); -} - -async function dismissBlockingNextcloudModals(page, nextcloudFrame, maxDismissals = 4) { - const modalOverlay = nextcloudFrame.locator( - "#firstrunwizard.modal-mask, #firstrunwizard[role='dialog'], .modal-mask[role='dialog'], [role='dialog'][aria-modal='true']" - ); - const dismissButtonCandidates = [ - nextcloudFrame.getByRole("button", { name: /^close$/i }), - nextcloudFrame.getByRole("button", { name: /^schlie(?:ss|รŸ)en$/i }), - nextcloudFrame.locator( - ".modal-mask .modal-container__close, .modal-mask .header-close, [role='dialog'] .modal-container__close, [role='dialog'] .header-close" - ), - nextcloudFrame.locator( - ".modal-mask .next, .modal-mask button[aria-label='Next'], [role='dialog'] .next, [role='dialog'] button[aria-label='Next']" - ), - nextcloudFrame.getByRole("button", { name: /skip|not now|later|dismiss|done|got it/i }) - ]; - let stableChecksWithoutModal = 0; - - for (let i = 0; i < maxDismissals; i += 1) { - if (!(await modalOverlay.first().isVisible().catch(() => false))) { - stableChecksWithoutModal += 1; - if (stableChecksWithoutModal >= 2) { - return; - } - await page.waitForTimeout(resolveTimeout(600)); - continue; - } - - stableChecksWithoutModal = 0; - let dismissed = false; - - for (const candidate of dismissButtonCandidates) { - const button = candidate.first(); - if (await button.isVisible().catch(() => false)) { - await button.click({ timeout: resolveTimeout(2_000) }).catch(() => {}); - dismissed = true; - break; - } - } - - if (!dismissed) { - await page.keyboard.press("Escape").catch(() => {}); - } - - await page.waitForTimeout(resolveTimeout(300)); - } -} - -async function clickUserMenuWithModalRetry(page, nextcloudFrame, userMenuLocator, attempts = 5) { - for (let attempt = 1; attempt <= attempts; attempt += 1) { - await dismissBlockingNextcloudModals(page, nextcloudFrame, 6); - - try { - await userMenuLocator.click({ timeout: resolveTimeout(4_000) }); - return; - } catch (error) { - const message = String(error && error.message ? error.message : error); - const retriable = /intercepts pointer events|timed out|timeout/i.test(message); - - if (!retriable || attempt === attempts) { - throw error; - } - await page.waitForTimeout(resolveTimeout(500)); - } - } -} - function getNextcloudSocialLoginCandidates(target) { return [ { @@ -198,7 +52,7 @@ function getNextcloudSocialLoginCandidates(target) { ]; } -async function loginToStandaloneNextcloud(adminPage, username = loginUsername, password = loginPassword) { +async function attemptStandaloneNextcloudLogin(adminPage, username, password) { const loginUrl = new URL("login", nextcloudBaseUrl).toString(); const usernameField = adminPage.getByRole("textbox", { name: nextcloudUsernameFieldPattern }); const passwordField = adminPage.locator('input[name="password"], input[type="password"]').first(); @@ -304,7 +158,7 @@ async function logoutStandaloneNextcloud(adminPage) { const logoutConfirmButton = adminPage.getByRole("button", { name: "Logout" }); await dismissBlockingNextcloudModals(adminPage, adminPage); - await clickUserMenuWithModalRetry(adminPage, adminPage, userMenuTrigger); + await clickWithModalRetry(adminPage, adminPage, userMenuTrigger); const logoutLink = await waitForFirstVisible( adminPage, @@ -326,13 +180,18 @@ async function logoutStandaloneNextcloud(adminPage) { await adminPage.waitForLoadState("networkidle", { timeout: resolveTimeout(45_000) }).catch(() => {}); } -async function loginToStandaloneNextcloudWithRetry(adminPage, username, password) { +async function loginToStandaloneNextcloud(adminPage, username = loginUsername, password = loginPassword) { try { - await loginToStandaloneNextcloud(adminPage, username, password); + await attemptStandaloneNextcloudLogin(adminPage, username, password); return; - } catch { + } catch (first) { await adminPage.waitForTimeout(resolveTimeout(5_000)); - await loginToStandaloneNextcloud(adminPage, username, password); + try { + await attemptStandaloneNextcloudLogin(adminPage, username, password); + } catch (second) { + second.message += `\n\nThe first attempt failed with: ${first.message}`; + throw second; + } } } @@ -366,10 +225,9 @@ module.exports = { waitForFirstVisible, waitForVisibleCandidate, dismissBlockingNextcloudModals, - clickUserMenuWithModalRetry, + clickWithModalRetry, loginToStandaloneNextcloud, logoutStandaloneNextcloud, - loginToStandaloneNextcloudWithRetry, findFirstVisibleCandidate, runAdminFlow, runBiberFlow, diff --git a/roles/web-app-nextcloud/files/playwright/addons/drawio.spec.js b/roles/web-app-nextcloud/files/playwright/addons/drawio.spec.js index 97b659f5f5..37d54a9c48 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/drawio.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/drawio.spec.js @@ -12,7 +12,7 @@ test("addon drawio: app installed + enabled (registered in OC.appswebroots)", as const page = await context.newPage(); try { - await shared.loginToStandaloneNextcloudWithRetry(page); + await shared.loginToStandaloneNextcloud(page); await gotoOnion(page, new URL("apps/files/", shared.env.nextcloudBaseUrl).toString(), { waitUntil: "domcontentloaded", diff --git a/roles/web-app-nextcloud/files/playwright/addons/epubviewer.spec.js b/roles/web-app-nextcloud/files/playwright/addons/epubviewer.spec.js index 9748a6a808..752069313f 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/epubviewer.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/epubviewer.spec.js @@ -14,7 +14,7 @@ test("addon epubviewer: EPUB reader personal settings panel renders and reflects const page = await context.newPage(); try { - await shared.loginToStandaloneNextcloudWithRetry(page); + await shared.loginToStandaloneNextcloud(page); const settingsUrl = new URL("settings/user/epubviewer", shared.env.nextcloudBaseUrl).toString(); const response = await gotoOnion(page, settingsUrl, { waitUntil: "domcontentloaded", timeout: resolveTimeout(60_000) }); diff --git a/roles/web-app-nextcloud/files/playwright/addons/integration_mastodon.spec.js b/roles/web-app-nextcloud/files/playwright/addons/integration_mastodon.spec.js index 5c9d47aafa..c0df7ba9e4 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/integration_mastodon.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/integration_mastodon.spec.js @@ -117,7 +117,7 @@ test("integration integration_mastodon: connects Nextcloud to the partner Mastod const popupPromise = page.waitForEvent("popup", { timeout: resolveTimeout(15_000) }).catch(() => null); await Promise.all([ page.waitForEvent("framenavigated", { timeout: resolveTimeout(60_000) }).catch(() => {}), - connect.click({ timeout: resolveTimeout(30_000) }), + shared.clickWithModalRetry(page, page, connect), ]); const popup = await popupPromise; diff --git a/roles/web-app-nextcloud/files/playwright/addons/integration_openai.spec.js b/roles/web-app-nextcloud/files/playwright/addons/integration_openai.spec.js index b568278769..0d5dcb2f6c 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/integration_openai.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/integration_openai.spec.js @@ -9,7 +9,7 @@ test.use({ ignoreHTTPSErrors: true }); const expectApiKey = String(process.env.INTEGRATION_OPENAI_EXPECT_API_KEY || "").toLowerCase() === "true"; -test("integration integration_openai: Nextcloud is configured and coupled to the openwebui/flowise backend", async ({ browser }) => { +test("integration integration_openai: Nextcloud is configured and coupled to the openwebui/litellm backend", async ({ browser }) => { skipUnlessAddonEnabled("integration_openai"); test.setTimeout(resolveTimeout(120_000)); @@ -43,19 +43,19 @@ test("integration integration_openai: Nextcloud is configured and coupled to the const configuredUrl = ((await serviceUrlField.inputValue().catch(() => "")) || "").trim(); expect( configuredUrl.length, - "the Service URL must be populated from config:app:set so the openwebui/flowise partner endpoint is wired" + "the Service URL must be populated from config:app:set so the openwebui/litellm partner endpoint is wired" ).toBeGreaterThan(0); expect( configuredUrl, - "the Service URL must be a valid http(s) URL pointing at the OpenAI-compatible AI backend (web-app-openwebui / web-app-flowise base URL)" + "the Service URL must be a valid http(s) URL pointing at the OpenAI-compatible AI backend (web-app-openwebui base URL or the svc-ai-litellm in-cluster endpoint)" ).toMatch(/^https?:\/\/.+/i); const configuredHost = new URL(configuredUrl).host; expect( configuredHost, - "the Service URL host must be the AI backend partner (openwebui chat.ai.* or flowise flow.ai.*), proving the config:app:set actually wired the partner endpoint rather than a placeholder" - ).toMatch(/^(chat|flow)\.ai\./i); + "the Service URL host must be the AI backend partner (openwebui chat.ai.* or the in-cluster litellm gateway), proving the config:app:set actually wired the partner endpoint rather than a placeholder" + ).toMatch(/^(chat\.ai\.|litellm(:\d+)?$)/i); expect( configuredHost, "the Service URL must point at the partner backend, distinct from the Nextcloud host โ€” proving real cross-host coupling, not a self-pointing/unconfigured value" @@ -74,7 +74,7 @@ test("integration integration_openai: Nextcloud is configured and coupled to the const configuredApiKey = ((await apiKeyField.inputValue().catch(() => "")) || "").trim(); expect( configuredApiKey.length, - "the API key must be provisioned (config:app:set integration_openai api_key) so the Flowise/LiteLLM master-key-protected /v1 endpoint authenticates instead of returning 401" + "the API key must be provisioned (config:app:set integration_openai api_key) so the virtual-key-protected svc-ai-litellm /v1 endpoint authenticates instead of returning 401" ).toBeGreaterThan(0); } } finally { diff --git a/roles/web-app-nextcloud/files/playwright/addons/onlyoffice.spec.js b/roles/web-app-nextcloud/files/playwright/addons/onlyoffice.spec.js index 045bfd4793..56333e0a42 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/onlyoffice.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/onlyoffice.spec.js @@ -52,29 +52,55 @@ test("onlyoffice addon: opening a document loads the partner document-server edi await shared.dismissBlockingNextcloudModals(page, page); await uploadedRow.click(); - const editorIframeElement = page.locator( - "iframe#iframeEditor, iframe[name='frameEditor'], iframe[src*='/web-apps/'], iframe[src*='OfficeWeb']", - ).first(); + const connectorIframe = page.locator("iframe#onlyofficeFrame").first(); await expect( - editorIframeElement, - "opening the .docx must mount the ONLYOFFICE editor iframe (the onlyoffice connector view), proving the partner document server was reached", + connectorIframe, + "opening the .docx must mount the onlyoffice connector iframe (#onlyofficeFrame) into the Files view", ).toBeVisible({ timeout: resolveTimeout(90_000) }); - const editorSrc = (await editorIframeElement.getAttribute("src").catch(() => "")) || ""; - let editorSrcHost = ""; - try { - editorSrcHost = new URL(editorSrc, shared.env.nextcloudBaseUrl).host; - } catch { - editorSrcHost = ""; - } - expect( - editorSrcHost, - `the ONLYOFFICE editor iframe must be served by the web-svc-onlyoffice partner host '${documentServerHost}' (the DocumentServerUrl coupling), not by Nextcloud ('${nextcloudHost}'); got src '${editorSrc}'`, - ).toBe(documentServerHost); + const frameUrlMatching = (predicate) => { + const frame = page.frames().find((candidate) => { + try { + return predicate(new URL(candidate.url())); + } catch { + return false; + } + }); + return frame ? frame.url() : ""; + }; - const editorFrame = page.frameLocator( - "iframe#iframeEditor, iframe[name='frameEditor'], iframe[src*='/web-apps/'], iframe[src*='OfficeWeb']", - ); + await expect + .poll( + () => + frameUrlMatching( + (url) => + url.host === nextcloudHost && + /^\/apps\/onlyoffice\/\d+$/.test(url.pathname) && + url.searchParams.get("inframe") === "true", + ), + { + message: `the connector iframe must load the onlyoffice editor view '/apps/onlyoffice/?inframe=true' from Nextcloud ('${nextcloudHost}'), which is what hands the document over to the document server`, + timeout: resolveTimeout(90_000), + }, + ) + .toBeTruthy(); + + await expect + .poll( + () => + frameUrlMatching( + (url) => url.host === documentServerHost && url.pathname.includes("/web-apps/apps/documenteditor/"), + ), + { + message: `the connector view must embed the document editor served by the web-svc-onlyoffice partner host '${documentServerHost}' (the DocumentServerUrl coupling), not by Nextcloud ('${nextcloudHost}')`, + timeout: resolveTimeout(120_000), + }, + ) + .toBeTruthy(); + + const editorFrame = page + .frameLocator("iframe#onlyofficeFrame") + .frameLocator("iframe[name='frameEditor']"); const jwtError = editorFrame.getByText( /security token is not correctly formed|token is not valid|invalid token|error while downloading|download failed/i, diff --git a/roles/web-app-nextcloud/files/playwright/addons/richdocuments.spec.js b/roles/web-app-nextcloud/files/playwright/addons/richdocuments.spec.js index c9d538a9d3..516ee5f251 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/richdocuments.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/richdocuments.spec.js @@ -30,9 +30,7 @@ test("richdocuments addon: Collabora connector wired to the partner WOPI server" "the Collabora Online (richdocuments) admin settings section must render, proving the app is enabled" ).toBeVisible({ timeout: resolveTimeout(60_000) }); - const wopiField = page - .locator("#wopi_url, input[name='wopi_url'], input[id*='wopi' i]") - .first(); + const wopiField = page.locator("input#wopi_url, input[name='wopi_url']").first(); await expect( wopiField, "the Collabora server URL (WOPI) field must render in the admin panel" diff --git a/roles/web-app-nextcloud/files/playwright/addons/user_ldap.spec.js b/roles/web-app-nextcloud/files/playwright/addons/user_ldap.spec.js index 28cbec387e..8842ef8a83 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/user_ldap.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/user_ldap.spec.js @@ -25,7 +25,7 @@ test("addon user_ldap: biber authenticates via LDAP-backed native login", async const page = await context.newPage(); try { - await shared.loginToStandaloneNextcloudWithRetry( + await shared.loginToStandaloneNextcloud( page, shared.env.biberUsername, shared.env.biberPassword, diff --git a/roles/web-app-nextcloud/files/playwright/playwright.spec.js b/roles/web-app-nextcloud/files/playwright/playwright.spec.js index 076cc0088b..7b62b8a83e 100644 --- a/roles/web-app-nextcloud/files/playwright/playwright.spec.js +++ b/roles/web-app-nextcloud/files/playwright/playwright.spec.js @@ -24,6 +24,7 @@ require("./test-login-admin-native").register(shared); require("./test-login-biber-oidc").register(shared); require("./test-login-biber-ldap").register(shared); require("./test-guest-persona").register(shared); +require("./test-mcp-guest").register(shared); require("./test-biber-persona").register(shared); require("./test-administrator-persona").register(shared); require("./test-seaweedfs"); diff --git a/roles/web-app-nextcloud/files/playwright/test-login-biber-ldap.js b/roles/web-app-nextcloud/files/playwright/test-login-biber-ldap.js index 1b1e373e92..1d70b1ecd6 100644 --- a/roles/web-app-nextcloud/files/playwright/test-login-biber-ldap.js +++ b/roles/web-app-nextcloud/files/playwright/test-login-biber-ldap.js @@ -17,12 +17,7 @@ exports.register = function (shared) { const biberPage = await biberContext.newPage(); try { - // `loginToStandaloneNextcloudWithRetry` retries once after a - // 5 s pause โ€” the LDAP-first-login caveat (see - // roles/web-app-nextcloud/docs/LDAP.md) means biber's NC account - // is materialised lazily on first successful login, so the very - // first attempt for a non-admin persona can stall. - await shared.loginToStandaloneNextcloudWithRetry( + await shared.loginToStandaloneNextcloud( biberPage, shared.env.biberUsername, shared.env.biberPassword, diff --git a/roles/web-app-nextcloud/files/playwright/test-login-biber-oidc.js b/roles/web-app-nextcloud/files/playwright/test-login-biber-oidc.js index b8928b5528..f27855ebc6 100644 --- a/roles/web-app-nextcloud/files/playwright/test-login-biber-oidc.js +++ b/roles/web-app-nextcloud/files/playwright/test-login-biber-oidc.js @@ -12,7 +12,7 @@ exports.register = function (shared) { const biberPage = await biberContext.newPage(); try { - await shared.loginToStandaloneNextcloudWithRetry(biberPage, shared.env.biberUsername, shared.env.biberPassword); + await shared.loginToStandaloneNextcloud(biberPage, shared.env.biberUsername, shared.env.biberPassword); const shellState = await shared.waitForVisibleCandidate( biberPage, diff --git a/roles/web-app-nextcloud/files/playwright/test-mcp-guest.js b/roles/web-app-nextcloud/files/playwright/test-mcp-guest.js new file mode 100644 index 0000000000..45e459e144 --- /dev/null +++ b/roles/web-app-nextcloud/files/playwright/test-mcp-guest.js @@ -0,0 +1,20 @@ +const { decodeDotenvQuotedValue } = require("./personas"); +const { registerMcpDisabledState, registerMcpGuestRejection } = require("./mcp-endpoint"); + +const mcpEndpointPath = decodeDotenvQuotedValue(process.env.NEXTCLOUD_MCP_ENDPOINT_PATH); +const mcpUpstreamPath = decodeDotenvQuotedValue(process.env.NEXTCLOUD_MCP_UPSTREAM_PATH); + +const withoutFrontController = (path) => path.replace(/^\/index\.php/, ""); + +exports.register = function (shared) { + const url = (path) => new URL(path, shared.env.nextcloudBaseUrl).toString(); + + registerMcpGuestRejection(() => url(mcpEndpointPath), "the adapter endpoint"); + registerMcpGuestRejection(() => url(mcpUpstreamPath), "the hub route"); + registerMcpGuestRejection( + () => url(withoutFrontController(mcpUpstreamPath)), + "the hub route without its front controller", + ); + + registerMcpDisabledState(() => url(mcpEndpointPath)); +}; diff --git a/roles/web-app-nextcloud/files/shell/realign_admin_password.sh b/roles/web-app-nextcloud/files/shell/realign_admin_password.sh new file mode 100644 index 0000000000..a929300ef8 --- /dev/null +++ b/roles/web-app-nextcloud/files/shell/realign_admin_password.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Usage: +# realign_admin_password.sh +# OC_PASS: the declared password, read from the environment only. +# +# Exit: 0 with [CHANGED] or [UNCHANGED] on stdout, 1 with [FAIL] on stderr. + +container="${1:-}" +run_as="${2:-}" +admin_user="${3:-}" +occ="${4:-}" + +if [[ -z "$container" || -z "$run_as" || -z "$admin_user" || -z "$occ" ]]; then + echo "Usage: $0 " >&2 + exit 2 +fi + +if [[ -z "${OC_PASS:-}" ]]; then + echo "[FAIL] OC_PASS is empty; refusing to set an empty administrator password." >&2 + exit 1 +fi + +marker="/var/www/html/config/.admin_password_sha256" +declared_sha="$(printf '%s' "$OC_PASS" | sha256sum | cut -d' ' -f1)" + +current_sha="$(container exec -u "$run_as" "$container" \ + sh -c "cat '$marker' 2>/dev/null || true")" + +if [[ "$current_sha" == "$declared_sha" ]]; then + echo "[UNCHANGED] Administrator password already matches the declared one." + exit 0 +fi + +if ! container exec -u "$run_as" -e "OC_PASS=$OC_PASS" "$container" \ + php "$occ" user:resetpassword --password-from-env "$admin_user" >/dev/null; then + echo "[FAIL] occ user:resetpassword failed for '$admin_user'." >&2 + exit 1 +fi + +if ! container exec -u "$run_as" -e "SHA=$declared_sha" "$container" \ + sh -c "printf '%s' \"\$SHA\" > '$marker'"; then + echo "[FAIL] Password was reset but the marker could not be written." >&2 + exit 1 +fi + +echo "[CHANGED] Administrator password did not match the declared one, and does now." diff --git a/roles/web-app-nextcloud/files/test/.nocheck b/roles/web-app-nextcloud/files/test/.nocheck new file mode 100644 index 0000000000..2b9d82d840 --- /dev/null +++ b/roles/web-app-nextcloud/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; test-e2e-cli stages files/test/ by that fixed path. diff --git a/roles/web-app-nextcloud/files/test/test.sh b/roles/web-app-nextcloud/files/test/test.sh new file mode 100644 index 0000000000..0be1abb318 --- /dev/null +++ b/roles/web-app-nextcloud/files/test/test.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# CLI test for web-app-nextcloud: the MCP endpoint honours its declared contract. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +bash "${here}/shared/mcp/run.sh" diff --git a/roles/web-app-nextcloud/meta/addons/integration_github.yml b/roles/web-app-nextcloud/meta/addons/integration_github.yml index 5e3f59fab0..b409c441a0 100644 --- a/roles/web-app-nextcloud/meta/addons/integration_github.yml +++ b/roles/web-app-nextcloud/meta/addons/integration_github.yml @@ -1,5 +1,5 @@ --- -enabled: "{{ (lookup('api', 'github.client_id') | length > 0) and (lookup('api', 'github.client_secret') | length > 0) }}" +enabled: "{{ lookup('api_enabled', 'github') }}" required: true mechanism: plugin source: upstream diff --git a/roles/web-app-nextcloud/meta/addons/integration_google.yml b/roles/web-app-nextcloud/meta/addons/integration_google.yml index 98e6def4dd..c96349ab13 100644 --- a/roles/web-app-nextcloud/meta/addons/integration_google.yml +++ b/roles/web-app-nextcloud/meta/addons/integration_google.yml @@ -1,5 +1,5 @@ --- -enabled: "{{ (lookup('api', 'google.client_id') | length > 0) and (lookup('api', 'google.client_secret') | length > 0) }}" +enabled: "{{ lookup('api_enabled', 'google') }}" required: true mechanism: plugin source: upstream diff --git a/roles/web-app-nextcloud/meta/addons/integration_jira.yml b/roles/web-app-nextcloud/meta/addons/integration_jira.yml index 0b08bd9d25..94c1f2a096 100644 --- a/roles/web-app-nextcloud/meta/addons/integration_jira.yml +++ b/roles/web-app-nextcloud/meta/addons/integration_jira.yml @@ -1,5 +1,5 @@ --- -enabled: "{{ (lookup('api', 'jira.client_id') | length > 0) and (lookup('api', 'jira.client_secret') | length > 0) }}" +enabled: "{{ lookup('api_enabled', 'jira') }}" required: true mechanism: plugin source: upstream diff --git a/roles/web-app-nextcloud/meta/addons/integration_openai.yml b/roles/web-app-nextcloud/meta/addons/integration_openai.yml index 806f546bc3..7b4c23de84 100644 --- a/roles/web-app-nextcloud/meta/addons/integration_openai.yml +++ b/roles/web-app-nextcloud/meta/addons/integration_openai.yml @@ -1,15 +1,15 @@ --- -enabled: "{{ (lookup('config', 'web-app-nextcloud', 'services.openwebui.enabled') | bool) or (lookup('config', 'web-app-nextcloud', 'services.flowise.enabled') | +enabled: "{{ (lookup('config', 'web-app-nextcloud', 'services.openwebui.enabled') | bool) or (lookup('config', 'web-app-nextcloud', 'services.litellm.enabled') | bool) }}" required: true mechanism: plugin source: upstream bridges: - openwebui - - flowise + - litellm config: plugin_configuration: - appid: "integration_openai" configkey: "url" - configvalue: "{{ (lookup('tls', 'web-app-openwebui', 'url.base') | regex_replace('/+$', '') ~ '/api') if ('web-app-openwebui' in group_names) else lookup('tls', - 'web-app-flowise', 'url.base') }}" + configvalue: "{{ (lookup('tls', 'web-app-openwebui', 'url.base') | regex_replace('/+$', '') ~ '/api') if ('web-app-openwebui' in group_names) else (LITELLM_BASE_LOCAL_URL + ~ '/v1') }}" diff --git a/roles/web-app-nextcloud/meta/addons/onlyoffice.yml b/roles/web-app-nextcloud/meta/addons/onlyoffice.yml index fcb245ad91..00a09a6158 100644 --- a/roles/web-app-nextcloud/meta/addons/onlyoffice.yml +++ b/roles/web-app-nextcloud/meta/addons/onlyoffice.yml @@ -10,19 +10,20 @@ update: catalog: nextcloud-appstore upstream_id: onlyoffice config: + archive: "https://github.com/ONLYOFFICE/onlyoffice-nextcloud/releases/download/v10.1.2/onlyoffice.tar.gz" incompatible_plugins: - richdocuments - fileslibreofficeedit plugin_configuration: - appid: "onlyoffice" configkey: "DocumentServerUrl" - configvalue: "{{ NEXTCLOUD_ONLYOFFICE_URL }}/" + configvalue: "{{ NEXTCLOUD_ONLYOFFICE_URL }}" - appid: "onlyoffice" configkey: "DocumentServerInternalUrl" - configvalue: "{{ NEXTCLOUD_ONLYOFFICE_URL }}/" + configvalue: "{{ NEXTCLOUD_ONLYOFFICE_URL }}" - appid: "onlyoffice" configkey: "StorageUrl" - configvalue: "{{ NEXTCLOUD_URL }}/" + configvalue: "{{ NEXTCLOUD_URL }}" - appid: "onlyoffice" configkey: "jwt_secret" configvalue: "{{ lookup('config','web-svc-onlyoffice', 'secrets.credentials.onlyoffice_jwt_secret', '') }}" diff --git a/roles/web-app-nextcloud/meta/addons/sociallogin.yml b/roles/web-app-nextcloud/meta/addons/sociallogin.yml index 88af238e87..bd9b4a0682 100644 --- a/roles/web-app-nextcloud/meta/addons/sociallogin.yml +++ b/roles/web-app-nextcloud/meta/addons/sociallogin.yml @@ -31,7 +31,7 @@ config: configkey: "custom_providers" configvalue: custom_oidc: - - name: "{{ lookup('domain','web-app-keycloak') }}" + - name: "{{ lookup('bounded_name', 'web-app-keycloak', 64 - 1 - 36) }}" title: "keycloak" style: "keycloak" authorizeUrl: "{{ OIDC.CLIENT.AUTHORIZE_URL }}" @@ -41,8 +41,10 @@ config: logoutUrl: "{{ OIDC.CLIENT.LOGOUT_URL }}" clientId: "{{ OIDC.CLIENT.ID }}" clientSecret: "{{ OIDC.CLIENT.SECRET }}" - scope: "openid" - groupsClaim: "" + scope: "openid {{ RBAC.GROUP.CLAIM }}" + groupsClaim: "{{ RBAC.GROUP.CLAIM }}" + groupMapping: >- + {{ { '/' ~ lookup('rbac_group_path', application_id=application_id, role='administrator'): 'admin' } }} defaultGroup: "" - appid: "sociallogin" configkey: "disable_notify_admins" diff --git a/roles/web-app-nextcloud/meta/mcp.yml b/roles/web-app-nextcloud/meta/mcp.yml new file mode 100644 index 0000000000..d4c4f6cbaa --- /dev/null +++ b/roles/web-app-nextcloud/meta/mcp.yml @@ -0,0 +1,52 @@ +--- +classification: adapter_server +direction: server +source_url: https://docs.nextcloud.com/server/latest/admin_manual/ai/app_context_agent.html +transport: streamable_http +exposure: internal +auth: bearer_token +auth_subject: service_account +implementation: adapter +credential: + owner: mcp-web-app-nextcloud + source: credentials + key: mcp_bearer +adapter: + type: mcp_passthrough + upstream_transport: streamable_http + specification_path: roles/web-app-nextcloud/files/mcp/tools.json + specification_sha256: sha256:1b9a603d452bf350bdc36fdc0f64b5fda82e01bb6a0cbbdf3dc9e400831474ab + upstream_path: /index.php/apps/app_api/proxy/context_agent/mcp/ +endpoint: + service_key: contextagentmcp + path: /mcp + port_key: http +limits: + request_bytes: 65536 + response_bytes: 1048576 + timeout_seconds: 15 + concurrent_requests: 4 + page_size: 100 + result_items: 500 + stream_seconds: 300 +tools: + read_probe: + tool: find_details_of_current_user + arguments: {} + allowlist: + - find_details_of_current_user + - find_free_time_slot_in_calendar + - find_person_in_contacts + - find_person_in_users + - get_file_content + - get_file_content_by_file_link + - get_folder_tree + - list_calendars + - list_tasks + categories: + - calendar + - contacts + - files + schema_sha256: sha256:3c1ad73136e3985d4884a83582bb39da051ef323eb4a9f8109558e17b6ccbdab + read_only_default: true + mutating_tools_enabled: false diff --git a/roles/web-app-nextcloud/meta/networks.yml b/roles/web-app-nextcloud/meta/networks.yml index 9070c4282b..2f01a1f4c6 100644 --- a/roles/web-app-nextcloud/meta/networks.yml +++ b/roles/web-app-nextcloud/meta/networks.yml @@ -2,6 +2,10 @@ local: subnet: 192.168.41.0/24 overlay: - modes: [swarm] + modes: [compose, swarm] + topology: shared_net + aliases: ["proxy"] + consumer: + kind: mcp_client proxy_resolvable: true - aliases: ["{{ lookup('domain', 'web-app-nextcloud') }}"] + proxy_aliases: ["{{ lookup('domain', 'web-app-nextcloud') }}"] diff --git a/roles/web-app-nextcloud/meta/rbac.yml b/roles/web-app-nextcloud/meta/rbac.yml new file mode 100644 index 0000000000..084e6fbeca --- /dev/null +++ b/roles/web-app-nextcloud/meta/rbac.yml @@ -0,0 +1,4 @@ +--- +roles: + mcp: + description: Can drive this application through an MCP client, which acts with the credentials the deployment issued rather than the caller's own diff --git a/roles/web-app-nextcloud/meta/secrets.yml b/roles/web-app-nextcloud/meta/secrets.yml index c36c2d9da0..3d9e46fd81 100644 --- a/roles/web-app-nextcloud/meta/secrets.yml +++ b/roles/web-app-nextcloud/meta/secrets.yml @@ -1,5 +1,10 @@ --- credentials: + litellm_api_key: + description: Per-consumer virtual key for the shared svc-ai-litellm gateway + algorithm: sk_prefixed + validation: + min_length: 50 talk_recording_secret: description: Shared secret between Nextcloud Talk and the recording backend algorithm: random_hex_32 @@ -24,3 +29,14 @@ credentials: description: Internal secret for AIO Talk algorithm: base64_prefixed_32 validation: ^base64:[A-Za-z0-9+/]{43}=$ + context_agent_app_secret: + description: Shared secret between the Nextcloud AppAPI proxy and the Context Agent ExApp serving the MCP endpoint + algorithm: alphanumeric + validation: + min_length: 64 + mcp_bearer: + description: Bearer an MCP client presents to the Context Agent adapter sidecar. Distinct from the app password the sidecar presents upstream, because + reaching the hub says nothing about who called the adapter. + algorithm: alphanumeric + validation: "^[A-Za-z0-9]{32,}$" + length: 48 diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index 235c75fc48..13f7f4b47e 100644 --- a/roles/web-app-nextcloud/meta/services.yml +++ b/roles/web-app-nextcloud/meta/services.yml @@ -54,7 +54,11 @@ mariadb: mem_reservation: 512m mem_limit: 1.5g pids_limit: 512 +# nocheck: playwright-service-flag self-provider nextcloud: + enabled: true + shared: true + bond: 1 modes: compose: enabled: true @@ -83,6 +87,12 @@ nextcloud: memory_limit: "{{ ((ansible_facts['memtotal_mb'] | int) / 30) | int }}M" upload_limit: 5G opcache_memory_consumption: "{{ ((ansible_facts['memtotal_mb'] | int) / 30) | int }}M" + fpm: + max_children: 16 + start_servers: 4 + min_spare_servers: 4 + max_spare_servers: 8 + request_terminate_timeout: 900s plugins_enabled: true proxy: service_key: proxy @@ -101,11 +111,16 @@ nextcloud: run_after: - web-app-keycloak - web-app-matomo + - web-app-gitlab + - web-app-mattermost + - web-app-openproject + - web-app-zammad lifecycle: beta proxy: name: nextcloud-proxy healthcheck: flavor: curl + # nocheck: healthcheck-timing-override a sidecar of a stack whose main service alone takes minutes; the value predates this default and has not been measured against it start_period: 20m image: nginx version: 1.31.5-alpine @@ -116,6 +131,55 @@ proxy: mem_limit: 256m pids_limit: 512 min_storage: 226MB + ports: + internal: + http: 80 +# nocheck: playwright-service-flag +# nocheck: dynamic-flag the container serves this role's MCP surface, so it tracks the role's own mcp flag rather than one client's presence +context_agent: + bond: 1 + enabled: "{{ lookup('config', 'web-app-nextcloud', 'mcp.enabled') | bool }}" + shared: "{{ lookup('config', 'web-app-nextcloud', 'mcp.enabled') | bool }}" + name: nextcloud-context-agent + image: ghcr.io/nextcloud/context_agent + version: 2.8.0 + backup: + no_stop_required: true + # nocheck: single-replica + replicas: 1 + cpus: "1.0" + mem_reservation: 512m + mem_limit: 1g + pids_limit: 512 + min_storage: 512MB + ports: + internal: + http: 23000 + healthcheck: + flavor: curl + path: heartbeat + # nocheck: healthcheck-timing-override a sidecar of a stack whose main service alone takes minutes; the value predates this default and has not been measured against it + start_period: 20m +# nocheck: playwright-service-flag MCP sidecar, no browser surface +# nocheck: dynamic-flag the sidecar fronts this role's MCP surface, so it tracks the role's own mcp flag rather than one client's presence +contextagentmcp: + enabled: "{{ lookup('config', 'web-app-nextcloud', 'mcp.enabled') | bool }}" + shared: false + image: python + # nocheck: docker-version base of the self-built stdlib adapter, not the served application + version: "3.13.15-slim" + custom: true + name: contextagentmcp + cpus: "0.25" + mem_reservation: 16m + mem_limit: 24m + pids_limit: 64 + healthcheck: + flavor: http_status + path: health + ports: + internal: + http: 8080 cron: # nocheck: single-replica singleton cron.sh; replicas double-run background jobs on the shared data volume replicas: 1 @@ -133,6 +197,7 @@ talk: shared: "{{ 'web-svc-coturn' in group_names }}" name: nextcloud-talk image: nextcloud/aio-talk + # nocheck: docker-version -- all 174 tags upstream publishes are AIO build stamps, none is a version version: latest backup: no_stop_required: false @@ -151,6 +216,7 @@ talk: healthcheck: flavor: tcp port_key: signaling + # nocheck: healthcheck-timing-override a sidecar of a stack whose main service alone takes minutes; the value predates this default and has not been measured against it start_period: 20m whiteboard: name: nextcloud-whiteboard @@ -169,6 +235,7 @@ whiteboard: http: 3002 healthcheck: flavor: nc + # nocheck: healthcheck-timing-override a sidecar of a stack whose main service alone takes minutes; the value predates this default and has not been measured against it start_period: 20m # nocheck: playwright-service-flag: infrastructural sub-component (collaborative editing) onlyoffice: @@ -198,9 +265,14 @@ seaweedfs: bond: 1 enabled: "{{ 'web-app-seaweedfs' in group_names }}" shared: "{{ 'web-app-seaweedfs' in group_names }}" +# nocheck: playwright-service-flag internal recording server, reachable only from the Talk signaling backend +# nocheck: dynamic-flag the recording server is part of the Talk deployment, so it follows the talk entry rather than a role's presence talk_recording: + enabled: "{{ lookup('config', 'web-app-nextcloud', 'services.talk.enabled') | bool }}" + shared: false name: nextcloud-talk-recording image: nextcloud/aio-talk-recording + # nocheck: docker-version -- all 104 tags upstream publishes are AIO build stamps, none is a version version: latest backup: no_stop_required: true @@ -265,11 +337,11 @@ openwebui: bond: 0.5 enabled: "{{ 'web-app-openwebui' in group_names }}" shared: "{{ 'web-app-openwebui' in group_names }}" -# nocheck: playwright-service-flag: bridged flowise partner, covered by partner role spec -flowise: +# nocheck: playwright-service-flag, dynamic-flag - bridged litellm gateway partner, covered by partner role spec, and a single shared instance +litellm: bond: 0.5 - enabled: "{{ 'web-app-flowise' in group_names }}" - shared: "{{ 'web-app-flowise' in group_names }}" + enabled: "{{ LITELLM_USABLE }}" + shared: true # nocheck: playwright-service-flag: bridged mastodon partner, covered by partner role spec mastodon: bond: 0.5 @@ -284,14 +356,12 @@ peertube: # Re-enable enabled/shared (back to the "web-app-moodle in group_names" form) once a plugin ships. # nocheck: playwright-service-flag: bridged moodle partner, covered by partner role spec moodle: - bond: 0.5 enabled: false # nocheck: dynamic-flag shared: false # nocheck: dynamic-flag # TODO(bridge): integration_suitecrm requires nc <= 24 (see meta/addons/integration_suitecrm.yml). # Re-enable enabled/shared (back to the "web-app-suitecrm in group_names" form) once a plugin ships. # nocheck: playwright-service-flag: bridged suitecrm partner, covered by partner role spec suitecrm: - bond: 0.5 enabled: false # nocheck: dynamic-flag shared: false # nocheck: dynamic-flag # nocheck: dynamic-flag @@ -300,3 +370,19 @@ container_backup: # nocheck: bond-baseline backup host joins outside the variant bond: 1 enabled: "{{ 'svc-bkp-volume-2-local' in group_names }}" shared: true +# nocheck: playwright-service-flag: MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +hermes: + bond: 0.5 + enabled: "{{ 'web-app-hermes' in group_names }}" + shared: "{{ 'web-app-hermes' in group_names }}" +# nocheck: playwright-service-flag: MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openclaw: + bond: 0.5 + enabled: "{{ 'web-app-openclaw' in group_names }}" + shared: "{{ 'web-app-openclaw' in group_names }}" +# nocheck: playwright-service-flag: MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +# nocheck: dynamic-flag the entry refuses this client, so the link is off on every host and no group_names gate can decide it +flowise: + enabled: false + shared: false + mcp_consumer: false diff --git a/roles/web-app-nextcloud/meta/tests.yml b/roles/web-app-nextcloud/meta/tests.yml new file mode 100644 index 0000000000..28bea0efe2 --- /dev/null +++ b/roles/web-app-nextcloud/meta/tests.yml @@ -0,0 +1,3 @@ +--- +cli: + timeout: 900 diff --git a/roles/web-app-nextcloud/meta/users.yml b/roles/web-app-nextcloud/meta/users.yml index 008e65e465..5308c446a3 100644 --- a/roles/web-app-nextcloud/meta/users.yml +++ b/roles/web-app-nextcloud/meta/users.yml @@ -8,3 +8,8 @@ no-reply: limits: rate: 60 / 1min burst: 3600 +mcp-web-app-nextcloud: + firstname: Infinito + lastname: MCP + accounts: [] + description: Account the Nextcloud MCP app password is issued for; an app password carries the full rights of its account diff --git a/roles/web-app-nextcloud/meta/variants.yml b/roles/web-app-nextcloud/meta/variants.yml index 58e033767e..5dad822253 100644 --- a/roles/web-app-nextcloud/meta/variants.yml +++ b/roles/web-app-nextcloud/meta/variants.yml @@ -36,6 +36,9 @@ dashboard: enabled: true shared: true + context_agent: + enabled: true + shared: true matomo: enabled: true shared: true @@ -91,9 +94,8 @@ openwebui: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true - flowise: + litellm: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true mastodon: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -102,14 +104,20 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false # Variant 1: minimal - SSO off, no partners - services: container_backup: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true sso: - enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true + enabled: true + shared: true coturn: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -122,6 +130,9 @@ dashboard: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true + context_agent: + enabled: true + shared: true matomo: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -177,11 +188,10 @@ enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true openwebui: + enabled: true + shared: true + litellm: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true - flowise: - enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true mastodon: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -190,6 +200,12 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + hermes: + enabled: true + shared: true + openclaw: + enabled: true + shared: true addons: &addons_static_off appointments: enabled: false @@ -312,9 +328,8 @@ openwebui: enabled: true shared: true - flowise: + litellm: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true mastodon: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -323,6 +338,12 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false addons: *addons_static_off # Variant 3: openproject - services: @@ -401,9 +422,8 @@ openwebui: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true - flowise: + litellm: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true mastodon: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -412,6 +432,12 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false addons: *addons_static_off # Variant 4: onlyoffice + mastodon - services: @@ -490,9 +516,8 @@ openwebui: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true - flowise: + litellm: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true mastodon: enabled: true shared: true @@ -501,6 +526,12 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false addons: *addons_static_off # Variant 5: zammad - services: @@ -579,9 +610,8 @@ openwebui: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true - flowise: + litellm: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true mastodon: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -590,6 +620,12 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false addons: *addons_static_off # Variant 6: gitlab - services: @@ -668,9 +704,8 @@ openwebui: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true - flowise: + litellm: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true mastodon: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -679,6 +714,12 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false addons: *addons_static_off # Variant 7: discourse - services: @@ -757,9 +798,8 @@ openwebui: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true - flowise: - enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true + litellm: + enabled: true mastodon: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -768,6 +808,12 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false addons: *addons_static_off # Variant 8: peertube - clearnet, because the OIDC plugin rejects a plaintext onion issuer - services: @@ -846,9 +892,8 @@ openwebui: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true - flowise: + litellm: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true mastodon: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -857,6 +902,12 @@ shared: true tor: enabled: false + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false addons: *addons_static_off # Variant 9: xwiki - services: @@ -935,9 +986,8 @@ openwebui: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true - flowise: + litellm: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true mastodon: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -946,6 +996,12 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false addons: *addons_static_off # Variant 10: mattermost - services: @@ -1024,9 +1080,8 @@ openwebui: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true - flowise: + litellm: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true mastodon: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -1035,6 +1090,12 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false addons: *addons_static_off # Variant 11: bigbluebutton - services: @@ -1113,9 +1174,8 @@ openwebui: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true - flowise: + litellm: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true mastodon: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -1124,6 +1184,12 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false addons: *addons_static_off # Variant 12: matrix - services: @@ -1202,9 +1268,8 @@ openwebui: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true - flowise: + litellm: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true mastodon: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -1213,8 +1278,14 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false addons: *addons_static_off -# Variant 13: flowise +# Variant 13: litellm - services: container_backup: enabled: false @@ -1291,9 +1362,8 @@ openwebui: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true - flowise: + litellm: enabled: true - shared: true mastodon: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -1302,4 +1372,10 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false addons: *addons_static_off diff --git a/roles/web-app-nextcloud/meta/volumes.yml b/roles/web-app-nextcloud/meta/volumes.yml index 7ff2c879ec..ad65b6b229 100644 --- a/roles/web-app-nextcloud/meta/volumes.yml +++ b/roles/web-app-nextcloud/meta/volumes.yml @@ -43,6 +43,14 @@ nginx_conf: - service: proxy target: /etc/nginx/nginx.conf +fpm_pool_conf: + type: config + source: "{{ [ lookup('container', 'web-app-nextcloud', 'directories.volumes'), 'fpm-pool.conf' ] | path_join }}" + mode: "0444" + mounts: + - service: nextcloud + target: /usr/local/etc/php-fpm.d/zzz-infinito.conf + infinito_conf: type: bind source: "{{ [ lookup('container', 'web-app-nextcloud', 'directories.volumes'), 'infinito' ] | path_join }}" diff --git a/roles/web-app-nextcloud/tasks/00_core.yml b/roles/web-app-nextcloud/tasks/00_core.yml new file mode 100644 index 0000000000..b5a3b2362d --- /dev/null +++ b/roles/web-app-nextcloud/tasks/00_core.yml @@ -0,0 +1,23 @@ +--- +- include_tasks: utils/once/flag.yml + +- name: "๐Ÿšฆ Declare the MCP edge limits before the vhost references them" + include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-webserver-core/tasks/utils/mcp_edge_limits.yml') }}" + when: NEXTCLOUD_MCP_ENABLED | bool + +- name: "๐ŸŽฌ Stage the MCP adapter build context for {{ application_id }}" + include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/instance.yml') }}" + vars: + mcp_adapter_instance_dir: "{{ NEXTCLOUD_MCP_ADAPTER_INSTANCE_DIR }}" + mcp_adapter_upstream_key: true + when: NEXTCLOUD_MCP_ENABLED | bool + +- name: ๐Ÿ”ง Setup the full docker stack + include_tasks: 01_fullstack.yml + vars: + domain: "{{ NEXTCLOUD_DOMAIN }}" + http_port: "{{ NEXTCLOUD_PORT }}" + +- name: "๐Ÿ–ฅ๏ธ Nextcloud stack-host post-deploy (config, occ, plugins, admin)" + include_tasks: 02_manager_ops.yml + when: IS_STACK_HOST | bool diff --git a/roles/web-app-nextcloud/tasks/01_fullstack.yml b/roles/web-app-nextcloud/tasks/01_fullstack.yml index f969155a12..694b81ac91 100644 --- a/roles/web-app-nextcloud/tasks/01_fullstack.yml +++ b/roles/web-app-nextcloud/tasks/01_fullstack.yml @@ -68,3 +68,11 @@ role_templates: - src: "docker.conf.j2" dest: "{{ NEXTCLOUD_HOST_NGINX_PATH }}" + +- name: "๐Ÿ“„ Render the php-fpm pool sizing (local + swarm peers)" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" + vars: + role_templates: + - src: "fpm-pool.conf.j2" + dest: "{{ NEXTCLOUD_HOST_FPM_POOL_PATH }}" diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops.yml b/roles/web-app-nextcloud/tasks/02_manager_ops.yml index b51fa1cc57..e6cc801ff2 100644 --- a/roles/web-app-nextcloud/tasks/02_manager_ops.yml +++ b/roles/web-app-nextcloud/tasks/02_manager_ops.yml @@ -51,6 +51,8 @@ loop: "{{ NEXTCLOUD_PLUGIN_ITEMS }}" loop_control: loop_var: plugin_item + label: "{{ plugin_item.key }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" vars: plugin_key: "{{ plugin_item.key }}" plugin_value: "{{ plugin_item.value }}" @@ -61,3 +63,7 @@ file: 02_manager_ops/07_admin_identities.yml apply: delegate_to: "{{ NEXTCLOUD_HOST_NODE }}" + +- name: "๐Ÿ”Œ Provision the MCP server surface" + include_tasks: utils/mcp.yml + when: NEXTCLOUD_MCP_ENABLED | bool diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/03_upgrade.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/03_upgrade.yml index 9b7abf8f3b..c4960649e0 100644 --- a/roles/web-app-nextcloud/tasks/02_manager_ops/03_upgrade.yml +++ b/roles/web-app-nextcloud/tasks/02_manager_ops/03_upgrade.yml @@ -22,6 +22,30 @@ retries: 2 delay: 3 until: occ_app_update.rc == 0 + when: NEXTCLOUD_PINNED_PLUGINS | length == 0 + +- name: ๐Ÿ” Nextcloud | List the apps the appstore offers an update for + shell: "{{ NEXTCLOUD_DOCKER_EXEC_OCC }} app:update --all --showonly" + register: occ_app_updatable + changed_when: false + retries: 2 + delay: 3 + until: occ_app_updatable.rc == 0 + when: NEXTCLOUD_PINNED_PLUGINS | length > 0 + +- name: ๐Ÿ”„ Nextcloud | App update, leaving the pinned releases alone + shell: "{{ NEXTCLOUD_DOCKER_EXEC_OCC }} app:update {{ item | quote }}" + register: occ_app_update_unpinned + changed_when: "'No apps found for update' not in occ_app_update_unpinned.stdout" + retries: 2 + delay: 3 + until: occ_app_update_unpinned.rc == 0 + when: NEXTCLOUD_PINNED_PLUGINS | length > 0 + loop: >- + {{ occ_app_updatable.stdout_lines | default([]) + | select('search', ' new version available') + | map('regex_replace', ' new version available.*$', '') + | difference(NEXTCLOUD_PINNED_PLUGINS) }} - name: โž• Nextcloud | Add missing columns shell: "{{ NEXTCLOUD_DOCKER_EXEC_OCC }} db:add-missing-columns" diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/04_admin.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/04_admin.yml index 8a5b875d7e..4be968fbb5 100644 --- a/roles/web-app-nextcloud/tasks/02_manager_ops/04_admin.yml +++ b/roles/web-app-nextcloud/tasks/02_manager_ops/04_admin.yml @@ -1,4 +1,20 @@ --- +- name: "๐Ÿ”‘ Realign the administrator password with the declared one" + ansible.builtin.script: > # nocheck: container-exec-resolver NEXTCLOUD_LOCAL_CID resolved at delegate_to runtime + {{ lookup('path_absolute', 'roles/web-app-nextcloud/files/shell/realign_admin_password.sh') }} + {{ NEXTCLOUD_LOCAL_CID | quote }} + {{ NEXTCLOUD_DOCKER_USER | quote }} + {{ NEXTCLOUD_ADMINISTRATOR_USERNAME | quote }} + {{ NEXTCLOUD_INTERNAL_OCC_COMMAND | quote }} + environment: + OC_PASS: "{{ NEXTCLOUD_ADMINISTRATOR_PASSWORD }}" + register: _nextcloud_admin_password + changed_when: _nextcloud_admin_password.stdout is search('\[CHANGED\]') + failed_when: >- + _nextcloud_admin_password.rc != 0 + or _nextcloud_admin_password.stdout is search('\[FAIL\]') + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + - name: โœ… Ensure Nextcloud administrator is in the 'admin' group shell: > {{ NEXTCLOUD_DOCKER_EXEC }} diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/01_install.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/01_install.yml index c92cb89644..a9810511df 100644 --- a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/01_install.yml +++ b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/01_install.yml @@ -4,6 +4,24 @@ ansible.builtin.set_fact: plugin_incompatible: "{{ plugin_value.config.incompatible_plugins | default(plugin_value.incompatible_plugins | default([])) }}" plugin_mandatory: "{{ plugin_value.config.mandatory | default(plugin_value.mandatory | default(false)) }}" + plugin_archive: "{{ plugin_value.config.archive | default(plugin_value.archive | default('')) }}" + changed_when: false + +- name: "โฌ‡๏ธ Stage the pinned {{ plugin_key }} release on the node" + get_url_retry: + url: "{{ plugin_archive }}" + dest: "/tmp/nextcloud-plugin-{{ plugin_key }}.tar.gz" + mode: "0644" + when: plugin_archive | length > 0 + +- name: "๐Ÿ“ฆ Unpack the pinned {{ plugin_key }} release so occ finds it installed" + ansible.builtin.shell: >- + cat /tmp/nextcloud-plugin-{{ plugin_key }}.tar.gz + | {{ NEXTCLOUD_DOCKER_EXEC_INTERACTIVE }} + tar -xzf - -C {{ NEXTCLOUD_APPS_DIRECTORY | quote }} + args: + executable: /bin/bash + when: plugin_archive | length > 0 changed_when: false - name: "๐Ÿ”ด Disable incompatible plugins for {{ plugin_key }} (batched shell, no async)" diff --git a/roles/web-app-nextcloud/tasks/addons/integration_openai.yml b/roles/web-app-nextcloud/tasks/addons/integration_openai.yml index f5d794139d..c514ad3dc8 100644 --- a/roles/web-app-nextcloud/tasks/addons/integration_openai.yml +++ b/roles/web-app-nextcloud/tasks/addons/integration_openai.yml @@ -1,29 +1,29 @@ --- # Exception logic only: the generic loader writes the Service URL (config SPOT), -# but the Flowise backend exposes its OpenAI-compatible API through LiteLLM, -# whose /v1 endpoint is protected by the deployer-owned master key -# (web-app-flowise credentials.llm_master_key). That partner-side credential -# must be fetched and written into integration_openai api_key here; the loader -# cannot derive it. -- name: ๐Ÿ” Resolve Flowise/LiteLLM backend selection for integration_openai +# but the LiteLLM gateway's /v1 endpoint is guarded by a per-consumer virtual +# key (this role's credentials.litellm_api_key). That credential must be +# written into integration_openai api_key here; the loader cannot derive it. +- name: ๐Ÿ” Resolve LiteLLM backend selection for integration_openai set_fact: - nextcloud_openai_use_flowise: "{{ ('web-app-flowise' in group_names) and ('web-app-openwebui' not in group_names) }}" + nextcloud_openai_use_litellm: "{{ ('svc-ai-litellm' in group_names) and ('web-app-openwebui' not in group_names) }}" changed_when: false -- name: ๐Ÿ” Resolve Flowise LiteLLM master key for integration_openai api_key - set_fact: - nextcloud_openai_flowise_api_key: "{{ lookup('config', 'web-app-flowise', 'secrets.credentials.llm_master_key', '') }}" - changed_when: false - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - when: nextcloud_openai_use_flowise | bool +- name: ๐Ÿ”‘ Bind integration_openai to the LiteLLM gateway + when: nextcloud_openai_use_litellm | bool + block: + - name: "๐Ÿ” Verify the gateway contract for {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-litellm/tasks/utils/consumer_contract.yml') }}" -- name: ๐Ÿ”ง Provision integration_openai api_key for the Flowise/LiteLLM backend - shell: > - {{ NEXTCLOUD_DOCKER_EXEC_OCC }} config:app:set integration_openai api_key - --value={{ nextcloud_openai_flowise_api_key | quote }} - register: nextcloud_openai_set_api_key - changed_when: nextcloud_openai_set_api_key.stdout is search(' set to ') - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - when: - - nextcloud_openai_use_flowise | bool - - (nextcloud_openai_flowise_api_key | default('')) | length > 0 + - name: ๐Ÿ” Resolve LiteLLM virtual key for integration_openai api_key + set_fact: + nextcloud_openai_litellm_api_key: "{{ lookup('config', 'web-app-nextcloud', 'secrets.credentials.litellm_api_key') }}" + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + + - name: ๐Ÿ”ง Provision integration_openai api_key for the LiteLLM gateway backend + shell: > + {{ NEXTCLOUD_DOCKER_EXEC_OCC }} config:app:set integration_openai api_key + --value '{{ nextcloud_openai_litellm_api_key }}' + register: nextcloud_openai_set_api_key + changed_when: nextcloud_openai_set_api_key.stdout is search(' set to ') + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-nextcloud/tasks/main.yml b/roles/web-app-nextcloud/tasks/main.yml index 52f562df3c..894562490d 100644 --- a/roles/web-app-nextcloud/tasks/main.yml +++ b/roles/web-app-nextcloud/tasks/main.yml @@ -1,10 +1,3 @@ --- -- name: ๐Ÿ”ง Setup the full docker stack - include_tasks: 01_fullstack.yml - vars: - domain: "{{ NEXTCLOUD_DOMAIN }}" - http_port: "{{ NEXTCLOUD_PORT }}" - -- name: "๐Ÿ–ฅ๏ธ Nextcloud stack-host post-deploy (config, occ, plugins, admin)" - include_tasks: 02_manager_ops.yml - when: IS_STACK_HOST | bool +- include_tasks: 00_core.yml + when: run_once_web_app_nextcloud is not defined diff --git a/roles/web-app-nextcloud/tasks/utils/mcp.yml b/roles/web-app-nextcloud/tasks/utils/mcp.yml new file mode 100644 index 0000000000..228323186c --- /dev/null +++ b/roles/web-app-nextcloud/tasks/utils/mcp.yml @@ -0,0 +1,100 @@ +--- +- name: "๐Ÿ” Resolve the Nextcloud hosting node + container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ NEXTCLOUD_SERVICE }}" + resolve_output_prefix: NEXTCLOUD + resolve_compose_cid: "{{ NEXTCLOUD_CONTAINER }}" + +- name: "๐Ÿ” Resolve the proxy hosting node + container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ NEXTCLOUD_PROXY_SERVICE }}" + resolve_output_prefix: NEXTCLOUD_PROXY + resolve_compose_cid: "{{ NEXTCLOUD_PROXY_CONTAINER }}" + +- name: "๐Ÿ” Resolve the Context Agent hosting node + container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ NEXTCLOUD_CONTEXT_AGENT_SERVICE }}" + resolve_output_prefix: NEXTCLOUD_CONTEXT_AGENT + resolve_compose_cid: "{{ NEXTCLOUD_CONTEXT_AGENT_CONTAINER }}" + +- name: "โณ Wait until the Context Agent answers its heartbeat" + ansible.builtin.command: + argv: + - container + - exec + - "{{ NEXTCLOUD_CONTEXT_AGENT_LOCAL_CID }}" # nocheck: container-exec-resolver + - python3 + - -c + - "import urllib.request; urllib.request.urlopen('http://127.0.0.1:{{ NEXTCLOUD_CONTEXT_AGENT_PORT }}/heartbeat', timeout=5)" + register: nextcloud_context_agent_heartbeat + retries: 60 + delay: 5 + until: nextcloud_context_agent_heartbeat.rc == 0 + changed_when: false + delegate_to: "{{ NEXTCLOUD_CONTEXT_AGENT_HOST_NODE }}" + run_once: true + +- name: "๐Ÿš€ Register the Context Agent as an AppAPI ExApp" + ansible.builtin.include_tasks: + file: "{{ role_path }}/tasks/utils/mcp/register.yml" + apply: + delegate_to: "{{ NEXTCLOUD_HOST_NODE }}" + run_once: true + vars: + nextcloud_exapp_renew: false + +- name: "๐Ÿ” Read the MCP app password this deployment already issued" + ansible.builtin.set_fact: + nextcloud_mcp_token: "{{ lookup('mcp_credential', application_id) }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐Ÿฉบ Check the stored app password against the MCP endpoint" + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/mcp/probe.yml" + when: nextcloud_mcp_token | length > 0 + +- name: "๐Ÿ”‘ Mint and persist a fresh MCP app password" + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/mcp/token.yml" + when: nextcloud_mcp_token | length == 0 or nextcloud_mcp_probe.stdout | default('') != '200' + +- name: "๐Ÿฉบ Re-check the freshly minted app password" + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/mcp/probe.yml" + when: nextcloud_mcp_probe is not defined or nextcloud_mcp_probe.stdout != '200' + +- name: "โ™ป๏ธ Re-register the ExApp a rotated app secret left behind" + ansible.builtin.include_tasks: + file: "{{ role_path }}/tasks/utils/mcp/register.yml" + apply: + delegate_to: "{{ NEXTCLOUD_HOST_NODE }}" + run_once: true + vars: + nextcloud_exapp_renew: true + when: nextcloud_mcp_probe.stdout != '200' + +- name: "๐Ÿฉบ Re-check the endpoint behind the re-registered ExApp" + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/mcp/probe.yml" + when: nextcloud_mcp_probe.stdout != '200' + +- name: "๐Ÿ›‘ Refuse an MCP endpoint that rejects the stored app password" + ansible.builtin.assert: + that: + - nextcloud_mcp_probe.stdout == '200' + fail_msg: >- + The MCP endpoint {{ NEXTCLOUD_MCP_PATH }} answered + {{ nextcloud_mcp_probe.stdout | default('no status') }} for the app password stored + for {{ application_id }}, so every MCP client would be configured with a + bearer the endpoint rejects. + +- name: "๐Ÿ”‘ Hand the minted app password to the adapter" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/upstream_key.yml') }}" + vars: + mcp_upstream_key_path: "{{ NEXTCLOUD_MCP_ADAPTER_UPSTREAM_ENV }}" + mcp_upstream_key: "{{ lookup('mcp_credential', application_id) }}" + +- name: "๐Ÿงฑ Rebuild the MCP adapter of {{ application_id }} now the credential exists" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/rebuild.yml') }}" + +- name: "๐Ÿšฟ Flush compose handlers for {{ application_id }}" + ansible.builtin.meta: flush_handlers diff --git a/roles/web-app-nextcloud/tasks/utils/mcp/probe.yml b/roles/web-app-nextcloud/tasks/utils/mcp/probe.yml new file mode 100644 index 0000000000..ddb5ead0cc --- /dev/null +++ b/roles/web-app-nextcloud/tasks/utils/mcp/probe.yml @@ -0,0 +1,22 @@ +--- +- name: "๐Ÿฉบ Ask the MCP endpoint whether the stored app password authenticates" + ansible.builtin.shell: | + # nocheck: container-exec-resolver + container exec {{ NEXTCLOUD_PROXY_LOCAL_CID | quote }} \ + {{ lookup('timeout', 30) | curl }} -o /dev/null -w '%{http_code}' -X POST \ + -H 'Host: {{ NEXTCLOUD_DOMAIN }}' \ + -H 'Authorization: Bearer {{ nextcloud_mcp_token }}' \ + -H 'Accept: application/json, text/event-stream' \ + -H 'Content-Type: application/json' \ + --data '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"infinito","version":"1"}}}' \ + 'http://127.0.0.1:{{ container_port }}{{ NEXTCLOUD_MCP_PATH }}' + args: + executable: /bin/bash + register: nextcloud_mcp_probe + retries: 30 + delay: 10 + until: nextcloud_mcp_probe.stdout in ['200', '401', '404'] + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ NEXTCLOUD_PROXY_HOST_NODE }}" + run_once: true diff --git a/roles/web-app-nextcloud/tasks/utils/mcp/register.yml b/roles/web-app-nextcloud/tasks/utils/mcp/register.yml new file mode 100644 index 0000000000..631261adde --- /dev/null +++ b/roles/web-app-nextcloud/tasks/utils/mcp/register.yml @@ -0,0 +1,105 @@ +--- +- name: "๐Ÿ” Read the registered AppAPI deploy daemons" + ansible.builtin.command: + argv: + - container + - exec + - -u + - "{{ NEXTCLOUD_DOCKER_USER }}" + - "{{ NEXTCLOUD_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + - "{{ NEXTCLOUD_INTERNAL_OCC_COMMAND }}" + - app_api:daemon:list + register: nextcloud_appapi_daemons + changed_when: false + +- name: "๐Ÿš€ Register the manual-install deploy daemon" + ansible.builtin.command: + argv: + - container + - exec + - -u + - "{{ NEXTCLOUD_DOCKER_USER }}" + - "{{ NEXTCLOUD_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + - "{{ NEXTCLOUD_INTERNAL_OCC_COMMAND }}" + - app_api:daemon:register + - "{{ NEXTCLOUD_CONTEXT_AGENT_DAEMON }}" + - Manual Install + - manual-install + - http + - "{{ NEXTCLOUD_CONTEXT_AGENT_DNS_NAME }}" + - "{{ NEXTCLOUD_CONTEXT_AGENT_NEXTCLOUD_URL }}" + when: NEXTCLOUD_CONTEXT_AGENT_DAEMON not in nextcloud_appapi_daemons.stdout + changed_when: true + +- name: "๐Ÿ” Read the registered ExApps" + ansible.builtin.command: + argv: + - container + - exec + - -u + - "{{ NEXTCLOUD_DOCKER_USER }}" + - "{{ NEXTCLOUD_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + - "{{ NEXTCLOUD_INTERNAL_OCC_COMMAND }}" + - app_api:app:list + register: nextcloud_registered_exapps + changed_when: false + +- name: "๐Ÿงน Drop a registration whose app secret the endpoint no longer accepts" + ansible.builtin.command: + argv: + - container + - exec + - -u + - "{{ NEXTCLOUD_DOCKER_USER }}" + - "{{ NEXTCLOUD_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + - "{{ NEXTCLOUD_INTERNAL_OCC_COMMAND }}" + - app_api:app:unregister + - "{{ NEXTCLOUD_CONTEXT_AGENT_SERVICE }}" + - --force + when: + - nextcloud_exapp_renew | bool + - NEXTCLOUD_CONTEXT_AGENT_SERVICE in nextcloud_registered_exapps.stdout + changed_when: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐Ÿš€ Register the Context Agent ExApp with its MCP route" + ansible.builtin.command: + argv: + - container + - exec + - -u + - "{{ NEXTCLOUD_DOCKER_USER }}" + - "{{ NEXTCLOUD_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + - "{{ NEXTCLOUD_INTERNAL_OCC_COMMAND }}" + - app_api:app:register + - "{{ NEXTCLOUD_CONTEXT_AGENT_SERVICE }}" + - "{{ NEXTCLOUD_CONTEXT_AGENT_DAEMON }}" + - --json-info + - "{{ NEXTCLOUD_CONTEXT_AGENT_JSON_INFO }}" + - --force-scopes + - --wait-finish + when: >- + NEXTCLOUD_CONTEXT_AGENT_SERVICE not in nextcloud_registered_exapps.stdout + or nextcloud_exapp_renew | bool + changed_when: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐ŸŸข Enable the Context Agent ExApp" + ansible.builtin.command: + argv: + - container + - exec + - -u + - "{{ NEXTCLOUD_DOCKER_USER }}" + - "{{ NEXTCLOUD_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + - "{{ NEXTCLOUD_INTERNAL_OCC_COMMAND }}" + - app_api:app:enable + - "{{ NEXTCLOUD_CONTEXT_AGENT_SERVICE }}" + register: nextcloud_context_agent_enable + changed_when: "'already enabled' not in nextcloud_context_agent_enable.stdout" diff --git a/roles/web-app-nextcloud/tasks/utils/mcp/token.yml b/roles/web-app-nextcloud/tasks/utils/mcp/token.yml new file mode 100644 index 0000000000..43b2678049 --- /dev/null +++ b/roles/web-app-nextcloud/tasks/utils/mcp/token.yml @@ -0,0 +1,146 @@ +--- +- name: "๐Ÿ” List the accounts this instance knows" + ansible.builtin.command: + argv: + - container + - exec + - -u + - "{{ NEXTCLOUD_DOCKER_USER }}" + - "{{ NEXTCLOUD_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + - "{{ NEXTCLOUD_INTERNAL_OCC_COMMAND }}" + - user:list + - --output=json + register: nextcloud_mcp_accounts + changed_when: false + delegate_to: "{{ NEXTCLOUD_HOST_NODE }}" + run_once: true + +- name: "๐Ÿ‘ค Create the account the MCP clients authenticate as" + ansible.builtin.command: + argv: + - container + - exec + - -u + - "{{ NEXTCLOUD_DOCKER_USER }}" + - -e + - "OC_PASS={{ NEXTCLOUD_MCP_USER_PASSWORD }}" + - "{{ NEXTCLOUD_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + - "{{ NEXTCLOUD_INTERNAL_OCC_COMMAND }}" + - user:add + - --password-from-env + - "--display-name={{ NEXTCLOUD_MCP_USER_DISPLAY_NAME }}" + - "{{ NEXTCLOUD_MCP_USERNAME }}" + when: NEXTCLOUD_MCP_USERNAME not in (nextcloud_mcp_accounts.stdout | from_json) + changed_when: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ NEXTCLOUD_HOST_NODE }}" + run_once: true + +- name: "๐Ÿ”‘ Set the account's password to the one this deployment declares" + ansible.builtin.command: + argv: + - container + - exec + - -u + - "{{ NEXTCLOUD_DOCKER_USER }}" + - -e + - "OC_PASS={{ NEXTCLOUD_MCP_USER_PASSWORD }}" + - "{{ NEXTCLOUD_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + - "{{ NEXTCLOUD_INTERNAL_OCC_COMMAND }}" + - user:resetpassword + - --password-from-env + - "{{ NEXTCLOUD_MCP_USERNAME }}" + changed_when: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ NEXTCLOUD_HOST_NODE }}" + run_once: true + +- name: "๐Ÿ” List the app passwords the MCP account already holds" + ansible.builtin.command: + argv: + - container + - exec + - -u + - "{{ NEXTCLOUD_DOCKER_USER }}" + - "{{ NEXTCLOUD_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + - "{{ NEXTCLOUD_INTERNAL_OCC_COMMAND }}" + - user:auth-tokens:list + - "{{ NEXTCLOUD_MCP_USERNAME }}" + - --output=json + register: nextcloud_mcp_tokens_held + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ NEXTCLOUD_HOST_NODE }}" + run_once: true + +- name: "๐Ÿงน Revoke the app passwords an earlier run minted under the managed name" + ansible.builtin.command: + argv: + - container + - exec + - -u + - "{{ NEXTCLOUD_DOCKER_USER }}" + - "{{ NEXTCLOUD_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + - "{{ NEXTCLOUD_INTERNAL_OCC_COMMAND }}" + - user:auth-tokens:delete + - "{{ NEXTCLOUD_MCP_USERNAME }}" + - "{{ item | string }}" + loop: >- + {{ nextcloud_mcp_tokens_held.stdout | from_json + | selectattr('name', 'equalto', NEXTCLOUD_MCP_TOKEN_NAME) + | map(attribute='id') | list }} + changed_when: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ NEXTCLOUD_HOST_NODE }}" + run_once: true + +- name: "๐Ÿ”‘ Mint an app password for the MCP clients" + ansible.builtin.command: + argv: + - container + - exec + - -u + - "{{ NEXTCLOUD_DOCKER_USER }}" + - -e + - "NC_PASS={{ NEXTCLOUD_MCP_USER_PASSWORD }}" + - "{{ NEXTCLOUD_LOCAL_CID }}" # nocheck: container-exec-resolver + - php + - "{{ NEXTCLOUD_INTERNAL_OCC_COMMAND }}" + - user:auth-tokens:add + - "{{ NEXTCLOUD_MCP_USERNAME }}" + - --password-from-env + - "--name={{ NEXTCLOUD_MCP_TOKEN_NAME }}" + register: nextcloud_mcp_token_mint + changed_when: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ NEXTCLOUD_HOST_NODE }}" + run_once: true + +- name: "๐Ÿ”ง Take the minted app password from the command output" + ansible.builtin.set_fact: + nextcloud_mcp_token: "{{ nextcloud_mcp_token_mint.stdout_lines | last | trim }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + run_once: true + +- name: "๐Ÿ›‘ Refuse an instance that issued no usable app password" + ansible.builtin.assert: + that: + - nextcloud_mcp_token | length >= 64 + fail_msg: >- + occ user:auth-tokens:add returned no app password, so every MCP client + would be configured with an empty bearer and fail at first use. + +- name: "๐Ÿ’พ Persist the app password so MCP clients can read it" + ansible.builtin.include_role: + name: sys-token-store + tasks_from: write.yml + vars: + sys_token_store_user_key: "{{ lookup('config', application_id, 'mcp.credential.owner') }}" + sys_token_store_app: "{{ application_id }}" + sys_token_store_token: "{{ nextcloud_mcp_token }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-nextcloud/tasks/utils/patch/db_credentials.yml b/roles/web-app-nextcloud/tasks/utils/patch/db_credentials.yml new file mode 100644 index 0000000000..fdd7002721 --- /dev/null +++ b/roles/web-app-nextcloud/tasks/utils/patch/db_credentials.yml @@ -0,0 +1,7 @@ +--- +- name: "๐Ÿ”‘ Realign the password nextcloud persisted in its config" + include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-rdbms/tasks/utils/patch_persisted_password.yml') }}" + vars: + patch_volume: "nextcloud_data" + patch_config_rel: "config/config.php" + patch_expression: "s|'dbpassword' *=> *'.*'|'dbpassword' => '@PASSWORD@'|" diff --git a/roles/web-app-nextcloud/templates/compose.yml.j2 b/roles/web-app-nextcloud/templates/compose.yml.j2 index 79b1867089..c4a1edb7ee 100644 --- a/roles/web-app-nextcloud/templates/compose.yml.j2 +++ b/roles/web-app-nextcloud/templates/compose.yml.j2 @@ -31,14 +31,38 @@ net.ipv6.conf.all.disable_ipv6: "{{ (not NETWORK_IPV6_ENABLED | bool) | int }}" healthcheck: test: ["CMD", "su", "{{ NEXTCLOUD_DOCKER_USER }}", "-s", "/bin/sh", "-c", "php -r 'exit(@fsockopen(\"127.0.0.1\", {{ NEXTCLOUD_FPM_PORT }}) ? 0 : 1);' && php {{ NEXTCLOUD_INTERNAL_OCC_COMMAND }} status"] + # nocheck: healthcheck-timing-override occ boots the whole Nextcloud stack per probe, so it stays off a 30s loop interval: 1m + # nocheck: healthcheck-timing-override occ regularly needs more than the 5s default to answer timeout: 30s retries: 10 + # nocheck: healthcheck-timing-override a role variable the linter cannot compare, tuned per deployment size start_period: {{ container_healthcheck_start_period }} + start_interval: 5s {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_depends_on', application_id) | indent(4) }} - {{ lookup('container_networks') | indent(4) }} + {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} + + {% if NEXTCLOUD_MCP_ENABLED | bool %} + {% set service_name = NEXTCLOUD_CONTEXT_AGENT_SERVICE %} + {% set container_port = NEXTCLOUD_CONTEXT_AGENT_PORT %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, 'context_agent') }} + {{ lookup('compose_only', 'container_name', NEXTCLOUD_CONTEXT_AGENT_CONTAINER) }} + environment: + APP_ID: {{ NEXTCLOUD_CONTEXT_AGENT_SERVICE }} + APP_VERSION: "{{ NEXTCLOUD_CONTEXT_AGENT_VERSION }}" + APP_HOST: 0.0.0.0 + APP_PORT: "{{ container_port }}" + APP_SECRET: "{{ NEXTCLOUD_CONTEXT_AGENT_SECRET }}" + NEXTCLOUD_URL: "{{ NEXTCLOUD_CONTEXT_AGENT_NEXTCLOUD_URL }}" + {{ lookup('container_healthcheck', service_name) | indent(4) }} + expose: + - "{{ container_port }}" + {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} + {% endif %} {% if NEXTCLOUD_HPB_SIGNALING_ENABLED | bool %} {% set service_name = NEXTCLOUD_HPB_SERVICE %} @@ -51,15 +75,17 @@ init: true {% if NEXTCLOUD_HPB_NETWORK_MODE == 'bridge' %} {% if NEXTCLOUD_HPB_TURN_ONBOARD_ENABLED | bool and NEXTCLOUD_HPB_TURN_ONBOARD_PUBLISH_PORTS | bool %} - ports: - - {{ NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST }}:{{ NEXTCLOUD_HPB_TURN_ONBOARD_PORT }}:{{ NEXTCLOUD_HPB_TURN_ONBOARD_PORT }}/tcp # nocheck: compose-ports-must-use-container-ports - - {{ NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST }}:{{ NEXTCLOUD_HPB_TURN_ONBOARD_PORT }}:{{ NEXTCLOUD_HPB_TURN_ONBOARD_PORT }}/udp # nocheck: compose-ports-must-use-container-ports - - {{ NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST }}:{{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_START }}-{{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_END }}:{{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_START }}-{{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_END }}/udp # nocheck: compose-ports-must-use-container-ports - - {{ NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST }}:{{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_START }}-{{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_END }}:{{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_START }}-{{ NEXTCLOUD_HPB_TURN_ONBOARD_RELAY_PORT_END }}/tcp # nocheck: compose-ports-must-use-container-ports + {{ lookup('container_ports', + {'service': 'nextcloud', 'protocol': 'stun_turn', + 'ip': NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST, + 'transport': ['tcp', 'udp'], 'container': 'same'}, + {'service': 'nextcloud', 'protocol': 'relay', + 'ip': NEXTCLOUD_HPB_TURN_ONBOARD_BIND_HOST, + 'transport': ['udp', 'tcp'], 'container': 'same'}) | indent(4) }} {% endif %} expose: - "{{ container_port }}" - {{ lookup('container_networks') | indent(4) }} + {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} {% else %} network_mode: {{ NEXTCLOUD_HPB_NETWORK_MODE }} {% endif %} @@ -83,7 +109,7 @@ expose: - "{{ container_port }}" shm_size: 1g - {{ lookup('container_networks') | indent(4) }} + {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} {%+ if lookup('engine', 'redis', application_id, 'local') %}{{ lookup('depends_on', {'redis': 'service_healthy'}) }}{% endif %} {% endif %} @@ -102,12 +128,16 @@ net.ipv6.conf.all.disable_ipv6: "{{ (not NETWORK_IPV6_ENABLED | bool) | int }}" healthcheck: test: ["CMD", "su", "{{ NEXTCLOUD_DOCKER_USER }}", "-s", "/bin/sh", "-c", "php {{ NEXTCLOUD_INTERNAL_OCC_COMMAND }} status"] + # nocheck: healthcheck-timing-override occ boots the whole Nextcloud stack per probe, so it stays off a 30s loop interval: 1m + # nocheck: healthcheck-timing-override occ regularly needs more than the 5s default to answer timeout: 30s retries: 10 + # nocheck: healthcheck-timing-override a role variable the linter cannot compare, tuned per deployment size start_period: {{ container_healthcheck_start_period }} + start_interval: 5s {{ lookup('container_depends_on', application_id) | indent(4) }} - {{ lookup('container_networks') | indent(4) }} + {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} {% if NEXTCLOUD_RECORDING_ENABLED | bool %} {% set service_name = 'talk_recording' %} @@ -123,10 +153,39 @@ - TZ={{ HOST_TIMEZONE }} expose: - "{{ NEXTCLOUD_RECORDING_PORT }}" - {{ lookup('container_networks') | indent(4) }} + {{ lookup('container_networks', provider_self_alias=False) | indent(4) }} {{ lookup('container_volumes', service_name) | indent(4) }} {% endif %} + {% if NEXTCLOUD_MCP_ENABLED | bool %} + {% set service_name = NEXTCLOUD_MCP_ADAPTER_SERVICE %} + {% set container_port = NEXTCLOUD_MCP_ADAPTER_PORT %} + {% set docker_compose_env = [NEXTCLOUD_MCP_ADAPTER_INSTANCE_DIR, 'upstream.env'] | path_join %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, NEXTCLOUD_MCP_ADAPTER_SERVICE) }} + build: + context: {{ NEXTCLOUD_MCP_ADAPTER_INSTANCE_DIR }} + dockerfile: Dockerfile + args: + MCP_ADAPTER_BASE_IMAGE: {{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_MCP_ADAPTER_SERVICE ~ '.image') }} + MCP_ADAPTER_BASE_VERSION: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_MCP_ADAPTER_SERVICE ~ '.version') }}" + {{ lookup('compose_only', 'container_name', NEXTCLOUD_MCP_ADAPTER_CONTAINER) }} + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + environment: + ADAPTER_CONTRACT: {{ NEXTCLOUD_MCP_ADAPTER_CONTRACT | to_json | to_json | replace('$', '$$') }} + ADAPTER_BEARER: {{ NEXTCLOUD_MCP_ADAPTER_BEARER | to_json }} + ADAPTER_PORT: "{{ container_port }}" + {{ lookup('container_healthcheck', service_name) | indent(4) }} + expose: + - "{{ container_port }}" + {{ lookup('container_networks', own_network_only=True, provider_self_alias=False) | indent(4) }} + {% endif %} + {{ lookup('compose_volumes', extra_volumes=lookup('nextcloud_extra_volumes')) }} {{ lookup('compose_networks') }} diff --git a/roles/web-app-nextcloud/templates/config/proxy.config.php.j2 b/roles/web-app-nextcloud/templates/config/proxy.config.php.j2 index 40a0f2302a..4a910d3158 100644 --- a/roles/web-app-nextcloud/templates/config/proxy.config.php.j2 +++ b/roles/web-app-nextcloud/templates/config/proxy.config.php.j2 @@ -7,6 +7,9 @@ return [ '{{ host }}', {% endfor %} ], + 'social_login_http_client' => [ + 'proxy' => '{{ NEXTCLOUD_TOR_SOCKS_PROXY }}', + ], ]; {% else %} return []; diff --git a/roles/web-app-nextcloud/templates/docker.conf.j2 b/roles/web-app-nextcloud/templates/docker.conf.j2 index 5e87904ba6..e474d2a137 100644 --- a/roles/web-app-nextcloud/templates/docker.conf.j2 +++ b/roles/web-app-nextcloud/templates/docker.conf.j2 @@ -54,6 +54,11 @@ http { log_not_found off; access_log off; } + location = /healthz/ready { + access_log off; + default_type text/plain; + return 200 "ready\n"; + } location ^~ /.well-known { location = /.well-known/carddav { return 301 /remote.php/dav/; } location = /.well-known/caldav { return 301 /remote.php/dav/; } diff --git a/roles/web-app-nextcloud/templates/fpm-pool.conf.j2 b/roles/web-app-nextcloud/templates/fpm-pool.conf.j2 new file mode 100644 index 0000000000..c9b3b4ef0b --- /dev/null +++ b/roles/web-app-nextcloud/templates/fpm-pool.conf.j2 @@ -0,0 +1,8 @@ +{% set fpm = lookup('config', application_id, 'services.nextcloud.performance.php.fpm') %} +[www] +pm = dynamic +pm.max_children = {{ fpm.max_children }} +pm.start_servers = {{ fpm.start_servers }} +pm.min_spare_servers = {{ fpm.min_spare_servers }} +pm.max_spare_servers = {{ fpm.max_spare_servers }} +request_terminate_timeout = {{ fpm.request_terminate_timeout }} diff --git a/roles/web-app-nextcloud/templates/playwright.env.j2 b/roles/web-app-nextcloud/templates/playwright.env.j2 index 8ecf2ca868..8a51fc152f 100644 --- a/roles/web-app-nextcloud/templates/playwright.env.j2 +++ b/roles/web-app-nextcloud/templates/playwright.env.j2 @@ -11,7 +11,7 @@ DISCOURSE_BASE_URL={{ (lookup('tls', 'web-app-discourse', 'url.base') if (lookup # nocheck: playwright-service-gate โ€” covered by sys-svc-mail integration tests, not the persona surface EMAIL_SERVICE_ENABLED={{ lookup('config', application_id, 'services.email.enabled') | string | lower }} -INTEGRATION_OPENAI_EXPECT_API_KEY={{ ((lookup('config', application_id, 'services.flowise.enabled') | bool) and not (lookup('config', application_id, 'services.openwebui.enabled') | bool)) | string | lower }} +INTEGRATION_OPENAI_EXPECT_API_KEY={{ ((lookup('config', application_id, 'services.litellm.enabled') | bool) and not (lookup('config', application_id, 'services.openwebui.enabled') | bool)) | string | lower }} LDAP_SERVICE_ENABLED={{ lookup('config', application_id, 'services.ldap.enabled') | string | lower }} @@ -27,12 +27,17 @@ MATOMO_BASE_URL={{ lookup('tls', 'web-app-matomo', 'url.base') | dotenv_quote }} MATOMO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.matomo.enabled') | string | lower }} +MCP_SERVICE_ENABLED={{ lookup('config', application_id, 'mcp.enabled') | string | lower }} + MOODLE_BASE_URL={{ (lookup('tls', 'web-app-moodle', 'url.base') if (lookup('config', application_id, 'services.moodle.enabled') | bool) else '') | dotenv_quote }} NEXTCLOUD_BASE_URL={{ lookup('tls', 'web-app-nextcloud', 'url.base') | dotenv_quote }} NEXTCLOUD_DIRECT_LOGIN_PASSWORD={{ lookup('config', application_id, 'secrets.credentials.administrator_password') | dotenv_quote }} +NEXTCLOUD_MCP_ENDPOINT_PATH={{ lookup('config', application_id, 'mcp.endpoint.path') | dotenv_quote }} +NEXTCLOUD_MCP_UPSTREAM_PATH={{ lookup('config', application_id, 'mcp.adapter.upstream_path') | dotenv_quote }} + NEXTCLOUD_ONLYOFFICE_EXPECTED_DOCUMENT_SERVER_URL={{ NEXTCLOUD_ONLYOFFICE_URL | dotenv_quote }} diff --git a/roles/web-app-nextcloud/templates/proxy.conf.j2 b/roles/web-app-nextcloud/templates/proxy.conf.j2 index 0a679453c2..43d1d957cb 100644 --- a/roles/web-app-nextcloud/templates/proxy.conf.j2 +++ b/roles/web-app-nextcloud/templates/proxy.conf.j2 @@ -41,4 +41,8 @@ server try_files $uri $uri/ =404; } + + {% include 'roles/web-app-prometheus/templates/nginx/locations.conf.j2' %} + + {% include 'roles/sys-svc-proxy/templates/mcp/vhost.conf.j2' %} } diff --git a/roles/web-app-nextcloud/templates/test.env.j2 b/roles/web-app-nextcloud/templates/test.env.j2 new file mode 100644 index 0000000000..3c7bacad44 --- /dev/null +++ b/roles/web-app-nextcloud/templates/test.env.j2 @@ -0,0 +1 @@ +{{ lookup('template', lookup('path_absolute', 'roles/test-e2e-cli/templates/mcp/test.env.j2')) }} diff --git a/roles/web-app-nextcloud/vars/main.yml b/roles/web-app-nextcloud/vars/main.yml index dc663f42b4..f0cdb2c8c5 100644 --- a/roles/web-app-nextcloud/vars/main.yml +++ b/roles/web-app-nextcloud/vars/main.yml @@ -18,12 +18,18 @@ NEXTCLOUD_OIDC_HOST: "{{ lookup('tls', 'web-app-keycloak', 'domain') }}" NEXTCLOUD_TOR_SOCKS_PROXY: "{{ lookup('tor_socks_proxy') }}" NEXTCLOUD_PLUGIN_ITEMS: "{{ lookup('config', application_id, 'addons') | dict2items }}" +NEXTCLOUD_PINNED_PLUGINS: >- + {{ NEXTCLOUD_PLUGIN_ITEMS + | selectattr('value.config.archive', 'defined') + | selectattr('value.enabled', 'true') + | map(attribute='key') | list }} NEXTCLOUD_PLUGINS_ENABLED: "{{ lookup('config', application_id, 'services.nextcloud.plugins_enabled') }}" NEXTCLOUD_USER_LDAP_ENABLED: "{{ lookup('config', application_id, 'addons.user_ldap.enabled') }}" NEXTCLOUD_LDAP_CONFIG_PREFIX: "s01" NEXTCLOUD_HOST_CONF_ADD_PATH: "{{ [ lookup('container', application_id, 'directories.volumes'), 'infinito' ] | path_join }}" NEXTCLOUD_HOST_NGINX_PATH: "{{ [ lookup('container', application_id, 'directories.volumes'), 'nginx.conf' ] | path_join }}" +NEXTCLOUD_HOST_FPM_POOL_PATH: "{{ [ lookup('container', application_id, 'directories.volumes'), 'fpm-pool.conf' ] | path_join }}" NEXTCLOUD_CNODE_PLUGIN_TASKS_PATH: "{{ [role_path, 'tasks/addons/'] | path_join }}" @@ -48,15 +54,73 @@ NEXTCLOUD_OPENPROJECT_CONTAINER_ADDRESS: "{{ lookup('container_address', 'web-ap NEXTCLOUD_ZAMMAD_CONTAINER_ADDRESS: "{{ lookup('container_address', 'web-app-zammad', 'railsserver') }}" NEXTCLOUD_GITLAB_CONTAINER_ADDRESS: "{{ lookup('container_address', 'web-app-gitlab', 'webservice') }}" -NEXTCLOUD_PROXY_EXCLUDED_HOSTS: +NEXTCLOUD_PROXY_EXCLUDED_HOSTS: "{{ NEXTCLOUD_PROXY_EXCLUDED_PUBLIC_HOSTS + NEXTCLOUD_PROXY_EXCLUDED_INTERNAL_HOSTS }}" + +NEXTCLOUD_PROXY_EXCLUDED_PUBLIC_HOSTS: - .nextcloud.com - github.com - .githubusercontent.com - codeberg.org - gitlab.com +NEXTCLOUD_PROXY_EXCLUDED_INTERNAL_HOSTS: + - "{{ NEXTCLOUD_PROXY_DNS_NAME }}" + - "{{ NEXTCLOUD_CONTEXT_AGENT_DNS_NAME }}" + NEXTCLOUD_PROXY_SERVICE: "proxy" NEXTCLOUD_PROXY_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_PROXY_SERVICE ~ '.name') }}" +NEXTCLOUD_PROXY_DNS_NAME: "{{ (entity_name ~ '_' ~ NEXTCLOUD_PROXY_SERVICE) if DEPLOYMENT_MODE == 'swarm' else NEXTCLOUD_PROXY_CONTAINER }}" + +NEXTCLOUD_MCP_ENABLED: "{{ lookup('config', application_id, 'services.context_agent.enabled') | bool }}" +NEXTCLOUD_MCP_PATH: "{{ lookup('config', application_id, 'mcp.adapter.upstream_path') }}" +NEXTCLOUD_MCP_TOKEN_NAME: "infinito-mcp" +NEXTCLOUD_MCP_ACCOUNT: "{{ lookup('users', 'mcp-web-app-nextcloud') }}" + +NEXTCLOUD_MCP_ADAPTER_SERVICE: "contextagentmcp" +NEXTCLOUD_MCP_ADAPTER_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_MCP_ADAPTER_SERVICE ~ '.name') }}" +NEXTCLOUD_MCP_ADAPTER_PORT: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_MCP_ADAPTER_SERVICE ~ '.ports.internal.http') }}" +NEXTCLOUD_MCP_ADAPTER_INSTANCE_DIR: "{{ [lookup('container', application_id, 'directories.instance'), 'mcp'] | path_join }}" +NEXTCLOUD_MCP_ADAPTER_BEARER: "{{ lookup('config', application_id, 'secrets.credentials.mcp_bearer') }}" +NEXTCLOUD_MCP_ADAPTER_UPSTREAM_URL: "http://{{ NEXTCLOUD_PROXY_DNS_NAME }}:{{ container_port }}{{ lookup('config', application_id, 'mcp.adapter.upstream_path') }}" +NEXTCLOUD_MCP_ADAPTER_UPSTREAM_ENV: "{{ [NEXTCLOUD_MCP_ADAPTER_INSTANCE_DIR, 'upstream.env'] | path_join }}" +NEXTCLOUD_MCP_ADAPTER_CONTRACT: + upstream_kind: mcp + upstream_transport: "{{ lookup('config', application_id, 'mcp.adapter.upstream_transport') }}" + provider: "{{ application_id }}" + upstream_url: "{{ NEXTCLOUD_MCP_ADAPTER_UPSTREAM_URL }}" + auth_subject: "{{ lookup('config', application_id, 'mcp.auth_subject') }}" + mutating_tools_enabled: "{{ lookup('config', application_id, 'mcp.tools.mutating_tools_enabled') | bool }}" + tools: "{{ lookup('file', 'mcp/tools.json') | from_json }}" + limits: "{{ lookup('config', application_id, 'mcp.limits') }}" + schema_sha256: "{{ lookup('config', application_id, 'mcp.tools.schema_sha256') }}" +NEXTCLOUD_MCP_USERNAME: "{{ NEXTCLOUD_MCP_ACCOUNT.username }}" +NEXTCLOUD_MCP_USER_DISPLAY_NAME: "Infinito MCP" +NEXTCLOUD_MCP_USER_PASSWORD: "{{ NEXTCLOUD_MCP_ACCOUNT.password }}" + +NEXTCLOUD_CONTEXT_AGENT_SERVICE: "context_agent" +NEXTCLOUD_CONTEXT_AGENT_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_CONTEXT_AGENT_SERVICE ~ '.name') }}" +NEXTCLOUD_CONTEXT_AGENT_VERSION: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_CONTEXT_AGENT_SERVICE ~ '.version') }}" +NEXTCLOUD_CONTEXT_AGENT_PORT: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_CONTEXT_AGENT_SERVICE ~ '.ports.internal.http') }}" +NEXTCLOUD_CONTEXT_AGENT_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.context_agent_app_secret') }}" +NEXTCLOUD_CONTEXT_AGENT_DNS_NAME: "{{ (entity_name ~ '_' ~ NEXTCLOUD_CONTEXT_AGENT_SERVICE) if DEPLOYMENT_MODE == 'swarm' else NEXTCLOUD_CONTEXT_AGENT_CONTAINER }}" +NEXTCLOUD_CONTEXT_AGENT_DAEMON: "manual_install" +NEXTCLOUD_CONTEXT_AGENT_NEXTCLOUD_URL: "http://{{ NEXTCLOUD_PROXY_DNS_NAME }}:{{ container_port }}" +NEXTCLOUD_CONTEXT_AGENT_ROUTES: + - url: "^/mcp" + verb: "POST,GET,DELETE" + access_level: 1 + headers_to_exclude: [] +NEXTCLOUD_CONTEXT_AGENT_JSON_INFO: >- + {{ + { + 'id': NEXTCLOUD_CONTEXT_AGENT_SERVICE, + 'name': 'Nextcloud Context Agent', + 'version': NEXTCLOUD_CONTEXT_AGENT_VERSION, + 'secret': NEXTCLOUD_CONTEXT_AGENT_SECRET, + 'port': NEXTCLOUD_CONTEXT_AGENT_PORT | int, + 'routes': NEXTCLOUD_CONTEXT_AGENT_ROUTES + } | to_json + }} NEXTCLOUD_CRON_SERVICE: "cron" NEXTCLOUD_CRON_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ NEXTCLOUD_CRON_SERVICE ~ '.name') }}" @@ -162,7 +226,9 @@ NEXTCLOUD_DOCKER_USER: "www-data" NEXTCLOUD_FPM_PORT: "{{ lookup('config', application_id, 'services.nextcloud.ports.internal.fpm') }}" NEXTCLOUD_INTERNAL_OCC_COMMAND: "{{ [ NEXTCLOUD_DOCKER_WORK_DIRECTORY, 'occ'] | path_join }}" +NEXTCLOUD_APPS_DIRECTORY: "{{ [ NEXTCLOUD_DOCKER_WORK_DIRECTORY, 'custom_apps'] | path_join }}" NEXTCLOUD_DOCKER_EXEC: "container exec -u {{ NEXTCLOUD_DOCKER_USER }} {{ NEXTCLOUD_LOCAL_CID | quote }}" # nocheck: container-exec-resolver NEXTCLOUD_LOCAL_CID resolved at delegate_to runtime; container_address would return a manager-only subshell NEXTCLOUD_DOCKER_EXEC_OCC: "{{ NEXTCLOUD_DOCKER_EXEC }} {{ NEXTCLOUD_INTERNAL_OCC_COMMAND }}" +NEXTCLOUD_DOCKER_EXEC_INTERACTIVE: "container exec -i -u {{ NEXTCLOUD_DOCKER_USER }} {{ NEXTCLOUD_LOCAL_CID | quote }}" # nocheck: container-exec-resolver NEXTCLOUD_LOCAL_CID resolved at delegate_to runtime, as for NEXTCLOUD_DOCKER_EXEC NEXTCLOUD_REDIS_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, 'redis') }}" diff --git a/roles/web-app-nextcloud/vars/system.yml b/roles/web-app-nextcloud/vars/system.yml index b2354f260c..b18d7954ed 100644 --- a/roles/web-app-nextcloud/vars/system.yml +++ b/roles/web-app-nextcloud/vars/system.yml @@ -22,6 +22,12 @@ nextcloud_system_config: - parameter: "trusted_domains 0" value: "{{ NEXTCLOUD_DOMAIN }}" + - parameter: "trusted_domains 1" + value: "{{ NEXTCLOUD_PROXY_SERVICE }}" + + - parameter: "trusted_domains 2" + value: "{{ NEXTCLOUD_PROXY_DNS_NAME }}" + - parameter: "overwrite.cli.url" value: "{{ NEXTCLOUD_URL }}" diff --git a/roles/web-app-odoo/README.md b/roles/web-app-odoo/README.md index eae1ac3195..674855a5f1 100644 --- a/roles/web-app-odoo/README.md +++ b/roles/web-app-odoo/README.md @@ -116,19 +116,20 @@ Run the published image to provision the inventory and deploy Odoo ERP to a mana ```bash APP=web-app-odoo HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-odoo/meta/info.yml b/roles/web-app-odoo/meta/info.yml index cb1ce0a32c..a9a28bc2fa 100644 --- a/roles/web-app-odoo/meta/info.yml +++ b/roles/web-app-odoo/meta/info.yml @@ -2,4 +2,4 @@ logo: class: fa-solid fa-briefcase homepage: https://www.odoo.com/ -video: https://www.odoo.com/slides/getting-started-15 +video: https://www.youtube.com/watch?v=FCmFgHVzd3E diff --git a/roles/web-app-odoo/meta/services.yml b/roles/web-app-odoo/meta/services.yml index 823ce59e53..84beb3525f 100644 --- a/roles/web-app-odoo/meta/services.yml +++ b/roles/web-app-odoo/meta/services.yml @@ -34,7 +34,6 @@ odoo: healthcheck: flavor: tcp path: web/health - start_period: 5m modes: compose: enabled: true diff --git a/roles/web-app-odoo/tasks/03_install_modules/module_ops.yml b/roles/web-app-odoo/tasks/03_install_modules/module_ops.yml index ba2a2461ef..7829592d9a 100644 --- a/roles/web-app-odoo/tasks/03_install_modules/module_ops.yml +++ b/roles/web-app-odoo/tasks/03_install_modules/module_ops.yml @@ -1,5 +1,6 @@ --- - name: "๐Ÿ“ฆ Install core modules" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec {{ ODOO_LOCAL_CID | quote }} odoo -i {{ odoo_modules_to_install }} @@ -22,6 +23,7 @@ when: ODOO_OIDC_ENABLED | bool block: - name: "๐Ÿ“ฆ Install auth_oauth module for OIDC support" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec {{ ODOO_LOCAL_CID | quote }} odoo -i auth_oauth @@ -40,6 +42,7 @@ or 'invalid module names' in (auth_oauth_install.stdout ~ auth_oauth_install.stderr) - name: "๐Ÿ“ฆ Install auth_signup module for OAuth user auto-creation" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec {{ ODOO_LOCAL_CID | quote }} odoo -i auth_signup @@ -58,6 +61,7 @@ or 'invalid module names' in (auth_signup_install.stdout ~ auth_signup_install.stderr) - name: "๐Ÿ“ฆ Install auth_oauth_https module for HTTPS redirect URI fix" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec {{ ODOO_LOCAL_CID | quote }} odoo -i auth_oauth_https @@ -76,6 +80,7 @@ or 'invalid module names' in (auth_oauth_https_install.stdout ~ auth_oauth_https_install.stderr) - name: "๐Ÿ“ฆ Install auth_ldap module for LDAP support" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec {{ ODOO_LOCAL_CID | quote }} odoo -i auth_ldap diff --git a/roles/web-app-openclaw/README.md b/roles/web-app-openclaw/README.md new file mode 100644 index 0000000000..8c2301a9ed --- /dev/null +++ b/roles/web-app-openclaw/README.md @@ -0,0 +1,174 @@ +# OpenClaw + +## Description + +[OpenClaw](https://openclaw.ai/) is an open-source personal AI agent that runs on hardware you control. It ships a gateway process with a browser Control UI next to its CLI and TUI, keeps persistent memory and a workspace on disk, and performs browser and filesystem tasks inside its own sandbox. + +## Overview + +This role deploys OpenClaw as a gateway container behind the reverse proxy on its own canonical domain. Its compose service is pinned to the isolating runtime that the Kata & gVisor role selects for the host, its gateway configuration file is rendered from the role, and its state directory is kept in a persistent volume. Access is fronted by an OAuth2 proxy with Keycloak sign-in when Keycloak is part of the deployment. + +## Cosmos + +The diagram places OpenClaw in the Infinito.Nexus cosmos: the components it deploys (capabilities), the central services it consumes (dependencies), and its outward reach (federation and bridged external networks). + +```mermaid +flowchart LR + subgraph deps [Dependencies] + dep_svc_ai_litellm["svc-ai-litellm ๐Ÿณ๐Ÿ"] + dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local ๐Ÿ’ป"] + dep_svc_net_tor["svc-net-tor ๐Ÿณ๐Ÿ"] + dep_svc_virt_kata["svc-virt-kata ๐Ÿ’ป"] + dep_web_app_dashboard["web-app-dashboard ๐Ÿณ๐Ÿ"] + dep_web_app_keycloak["web-app-keycloak ๐Ÿณ๐Ÿ"] + dep_web_app_matomo["web-app-matomo ๐Ÿณ๐Ÿ"] + dep_web_app_prometheus["web-app-prometheus ๐Ÿณ๐Ÿ"] + dep_web_svc_css["web-svc-css ๐Ÿ’ป"] + dep_web_svc_logout["web-svc-logout ๐Ÿณ๐Ÿ"] + end + subgraph role [web-app-openclaw ๐Ÿณ๐Ÿ] + svc_openclaw["openclaw"] + svc_kata["kata"] + svc_sso["sso"] + svc_litellm["litellm"] + svc_logout["logout"] + svc_dashboard["dashboard"] + svc_matomo["matomo"] + svc_css["css"] + svc_prometheus["prometheus"] + svc_tor["tor"] + svc_container_backup["container_backup"] + end + subgraph dependents [Dependents] + dpt_svc_ai_robot["svc-ai-robot ๐Ÿ’ป"] + dpt_svc_db_qdrant["svc-db-qdrant ๐Ÿณ๐Ÿ"] + dpt_web_app_baserow["web-app-baserow ๐Ÿณ๐Ÿ"] + dpt_web_app_checkmk["web-app-checkmk ๐Ÿณ๐Ÿ"] + dpt_web_app_fider["web-app-fider ๐Ÿณ๐Ÿ"] + dpt_web_app_gitea["web-app-gitea ๐Ÿณ๐Ÿ"] + dpt_web_app_gitlab["web-app-gitlab ๐Ÿณ๐Ÿ"] + dpt_web_app_homeassistant["web-app-homeassistant ๐Ÿณ๐Ÿ"] + dpt_web_app_jellyfin["web-app-jellyfin ๐Ÿณ๐Ÿ"] + dpt_web_app_jenkins["web-app-jenkins ๐Ÿณ๐Ÿ"] + dpt_web_app_listmonk["web-app-listmonk ๐Ÿณ๐Ÿ"] + dpt_web_app_mattermost["web-app-mattermost ๐Ÿณ๐Ÿ"] + dpt_more["..."] + end + dep_svc_ai_litellm -. "0..1" .-> svc_litellm + dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup + dep_svc_net_tor -. "0..1" .-> svc_tor + dep_svc_virt_kata -- "1:1" --> svc_kata + dep_web_app_dashboard -. "0..1" .-> svc_dashboard + dep_web_app_keycloak -. "0..1" .-> svc_sso + dep_web_app_matomo -. "0..1" .-> svc_matomo + dep_web_app_prometheus -. "0..1" .-> svc_prometheus + dep_web_svc_css -. "0..1" .-> svc_css + dep_web_svc_logout -. "0..1" .-> svc_logout + svc_openclaw -- "1:1" --> dpt_more + svc_openclaw -. "0..1" .-> dpt_svc_ai_robot + svc_openclaw -. "0..1" .-> dpt_svc_db_qdrant + svc_openclaw -. "0..1" .-> dpt_web_app_baserow + svc_openclaw -. "0..1" .-> dpt_web_app_checkmk + svc_openclaw -. "0..1" .-> dpt_web_app_fider + svc_openclaw -. "0..1" .-> dpt_web_app_gitea + svc_openclaw -. "0..1" .-> dpt_web_app_gitlab + svc_openclaw -. "0..1" .-> dpt_web_app_homeassistant + svc_openclaw -. "0..1" .-> dpt_web_app_jellyfin + svc_openclaw -. "0..1" .-> dpt_web_app_jenkins + svc_openclaw -. "0..1" .-> dpt_web_app_listmonk + svc_openclaw -. "0..1" .-> dpt_web_app_mattermost +``` + +Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (๐Ÿ’ป host, ๐Ÿณ compose, ๐Ÿ swarm); โŒ marks a service that is explicitly turned off, and โš™๏ธ an Ansible role dependency declared in `meta/main.yml`. + +## Features + +- **Agent gateway:** The container runs the OpenClaw gateway bound to the LAN interface on port 18789, with an HTTP health check against `/healthz`. +- **Isolating runtime:** The compose service is pinned to Kata Containers where `/dev/kvm` and the Kata shim are available, and to gVisor otherwise. +- **Single sign-on:** When Keycloak is deployed, an OAuth2 proxy sits in front of the gateway and admits only members of the administrator group of this application. +- **Gateway token:** A generated gateway token guards the Control UI and the API, and the Control UI accepts the canonical domain as its only allowed origin. +- **Model gateway key:** With the LiteLLM Gateway deployed, that gateway provisions a per-consumer virtual key aliased to this application. +- **MCP client contract:** With Home Assistant deployed, the role declares the MCP client side of the platform contract as an internal streamable-HTTP client with a read-only tool policy. The MCP server list itself lives in `openclaw.json`, not in the container environment. +- **Persistent state:** Memory and workspace live in a volume mounted at `/home/node/.openclaw`, with the rendered `openclaw.json` mounted into it, and are included in the container volume backup when that service is deployed. +- **Compose and Swarm:** The role deploys in both modes and renders the gateway configuration file for the local host and the swarm peers. + +## Quick Setup + +### Development + +Clone, set up the workstation, and deploy OpenClaw onto the local stack: + +```bash +git clone https://github.com/infinito-nexus/core.git +cd core +make onboard +make compose-deploy mode=reinstall apps=web-app-openclaw full_cycle=false +``` + +### Production + +Run the published image to provision the inventory and deploy OpenClaw to a managed server (the mounted volume persists the inventory): + +```bash +APP=web-app-openclaw +HOST= +DOMAIN= +TLS_MODE=self_signed +SSH_PUBLIC_KEY="" + +docker run --rm -it \ + -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + ghcr.io/infinito-nexus/core/debian bash -c ' + INVENTORY=/etc/infinito.nexus/inventories/production + infinito administration inventory provision "$INVENTORY" \ + --inventory-file "$INVENTORY/devices.yml" \ + --host "$HOST" \ + --include "$APP" \ + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + infinito administration deploy dedicated "$INVENTORY/devices.yml" \ + --password-file "$INVENTORY/.password" \ + --diff -vv' +``` + +## MCP Client + +OpenClaw consumes MCP. Every deployed shared MCP server role is discovered +through `MCP_DISCOVERED_SERVERS` and written into the agent configuration. + +### Configuration + +| Property | Value | +| --- | --- | +| Direction | `client` | +| Transport | Streamable HTTP | +| Config file | `openclaw.json` | +| Auth | `Authorization` header per server, from the discovery data | + +Servers whose auth scheme cannot be presented as a header are dropped before +rendering, so no entry carries a credential the server would reject. + +### Verification + +OpenClaw exposes no administrator-visible list of configured MCP servers, so the +configured set is proven by a CLI test instead: +[`files/test/test.sh`](./files/test/test.sh) probes the agent's `mcp` surface and +fails when the exec itself fails or the output carries a `failed to start server` +line. The Playwright spec covers the complementary case, that the gateway +holding the MCP credentials refuses an unauthenticated caller. + +### Default state + +Off. `mcp.enabled` is false unless an MCP server role is part of the +deployment. + +### How to disable + +Remove the MCP server roles, or pin `mcp.enabled: false` for this role. +The rendered config then contains no MCP server entry. + +## Credits + +Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. +Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) and maintained by [Kevin Veen-Birkenbach](https://www.veen.world). +Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/web-app-openclaw/TODO.md b/roles/web-app-openclaw/TODO.md new file mode 100644 index 0000000000..80680513ce --- /dev/null +++ b/roles/web-app-openclaw/TODO.md @@ -0,0 +1,4 @@ +# TODO + +- Administrator persona: `PERSONA_ADMINISTRATOR_BLOCKED=true` because the Control UI is a WebSocket SPA whose session lives behind gateway device pairing; there is no DOM logout control the shared `inAppLogout` helper can reach. The SSO round-trip itself is covered by `test-oidc-login.js`. Unblock once the Control UI exposes a plain logout affordance or the persona helpers learn the pairing handshake. +- MCP client wiring: the native `@modelcontextprotocol/sdk` client is configured through `openclaw.json`, not env. diff --git a/roles/web-app-openclaw/files/playwright/.nocheck b/roles/web-app-openclaw/files/playwright/.nocheck new file mode 100644 index 0000000000..9ceebc5e82 --- /dev/null +++ b/roles/web-app-openclaw/files/playwright/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Playwright discovers this suite by path; the runner copies the tree as it stands and the specs import their helpers relatively. Sorting by extension would break discovery. diff --git a/roles/web-app-openclaw/files/playwright/_shared.js b/roles/web-app-openclaw/files/playwright/_shared.js new file mode 100644 index 0000000000..198f5c97ea --- /dev/null +++ b/roles/web-app-openclaw/files/playwright/_shared.js @@ -0,0 +1,12 @@ +const { decodeDotenvQuotedValue, normalizeBaseUrl } = require("./personas"); + +const env = { + baseUrl: normalizeBaseUrl(process.env.OPENCLAW_BASE_URL || ""), + canonicalDomain: decodeDotenvQuotedValue(process.env.CANONICAL_DOMAIN || ""), + gatewayToken: decodeDotenvQuotedValue(process.env.OPENCLAW_GATEWAY_TOKEN || ""), + ssoEnabled: String(process.env.SSO_SERVICE_ENABLED || "").toLowerCase() === "true", +}; + +async function beforeEach() {} + +module.exports = { env, beforeEach }; diff --git a/roles/web-app-openclaw/files/playwright/playwright.spec.js b/roles/web-app-openclaw/files/playwright/playwright.spec.js new file mode 100644 index 0000000000..684db6fe2f --- /dev/null +++ b/roles/web-app-openclaw/files/playwright/playwright.spec.js @@ -0,0 +1,14 @@ +const { test } = require("@playwright/test"); + +const shared = require("./_shared"); + +test.use({ + ignoreHTTPSErrors: true, +}); + +test.beforeEach(shared.beforeEach); + +require("./test-guest").register(shared); +require("./test-mcp").register(shared); +require("./test-administrator-persona").register(shared); +require("./test-oidc-login"); diff --git a/roles/web-app-openclaw/files/playwright/test-administrator-persona.js b/roles/web-app-openclaw/files/playwright/test-administrator-persona.js new file mode 100644 index 0000000000..1fa6989024 --- /dev/null +++ b/roles/web-app-openclaw/files/playwright/test-administrator-persona.js @@ -0,0 +1,8 @@ +const { test } = require("@playwright/test"); +const { runAdminFlow } = require("./personas"); + +exports.register = function () { + test("administrator: app โ†’ universal logout", async ({ page }) => { + await runAdminFlow(page, {}); + }); +}; diff --git a/roles/web-app-openclaw/files/playwright/test-guest.js b/roles/web-app-openclaw/files/playwright/test-guest.js new file mode 100644 index 0000000000..4accefb91f --- /dev/null +++ b/roles/web-app-openclaw/files/playwright/test-guest.js @@ -0,0 +1,18 @@ +const { test, expect } = require("@playwright/test"); + +const { assertCspResponseHeader, assertCspMetaParity, gotoOnion } = require("./personas"); + +exports.register = function (shared) { + test("guest: OpenClaw dashboard reachable, serves CSP, never exposes an authenticated surface", async ({ page }) => { + const response = await gotoOnion(page, `${shared.env.baseUrl}/`); + expect(response, "Expected a OpenClaw dashboard response").toBeTruthy(); + expect(response.status(), "Expected OpenClaw status to be < 400").toBeLessThan(400); + expect( + response.url().includes(shared.env.canonicalDomain), + `Expected canonical domain "${shared.env.canonicalDomain}" to back the OpenClaw URL`, + ).toBe(true); + + const directives = assertCspResponseHeader(response, "openclaw dashboard"); + await assertCspMetaParity(page, directives, "openclaw dashboard"); + }); +}; diff --git a/roles/web-app-openclaw/files/playwright/test-mcp.js b/roles/web-app-openclaw/files/playwright/test-mcp.js new file mode 100644 index 0000000000..38de4c1f06 --- /dev/null +++ b/roles/web-app-openclaw/files/playwright/test-mcp.js @@ -0,0 +1,27 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); + +const { skipUnlessServiceEnabled } = require("./service-gating"); + +exports.register = function (shared) { + test("mcp: the gateway holding the MCP credentials refuses an unauthenticated caller", async ({ request }) => { + skipUnlessServiceEnabled("mcp"); + + const anonymous = await request.post(`${shared.env.baseUrl.replace(/\/+$/, "")}/api/agent`, { + failOnStatusCode: false, + maxRedirects: 0, + headers: { "Content-Type": "application/json" }, + data: { prompt: "list your configured mcp servers" }, + timeout: resolveTimeout(30_000), + }); + expect( + anonymous.status(), + "an unauthenticated agent call must be redirected or refused; the gateway holds one bearer per MCP server", + ).toBeGreaterThanOrEqual(300); + + expect( + await anonymous.text(), + "a refused request must not leak the configured MCP servers", + ).not.toContain("jsonrpc"); + }); +}; diff --git a/roles/web-app-openclaw/files/playwright/test-oidc-login.js b/roles/web-app-openclaw/files/playwright/test-oidc-login.js new file mode 100644 index 0000000000..4bd3614292 --- /dev/null +++ b/roles/web-app-openclaw/files/playwright/test-oidc-login.js @@ -0,0 +1,44 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); +const { skipUnlessServiceEnabled } = require("./service-gating"); +const { + decodeDotenvQuotedValue, + normalizeBaseUrl, + performKeycloakLoginForm, + gotoOnion, +} = require("./personas"); + +const baseUrl = normalizeBaseUrl(process.env.OPENCLAW_BASE_URL || ""); +const oidcIssuerUrl = normalizeBaseUrl(process.env.OIDC_ISSUER_URL || ""); +const canonicalDomain = decodeDotenvQuotedValue(process.env.CANONICAL_DOMAIN || ""); +const adminUsername = decodeDotenvQuotedValue(process.env.ADMIN_USERNAME); +const adminPassword = decodeDotenvQuotedValue(process.env.ADMIN_PASSWORD); + +test.use({ ignoreHTTPSErrors: true }); + +test("OIDC: oauth2-proxy redirects visitors through Keycloak onto the gateway", async ({ page }) => { + expect(baseUrl, "OPENCLAW_BASE_URL must be set").toBeTruthy(); + expect(canonicalDomain, "CANONICAL_DOMAIN must be set").toBeTruthy(); + await page.context().clearCookies(); + + skipUnlessServiceEnabled("sso"); + expect(adminUsername, "ADMIN_USERNAME must be set when OIDC is enabled").toBeTruthy(); + expect(adminPassword, "ADMIN_PASSWORD must be set when OIDC is enabled").toBeTruthy(); + expect(oidcIssuerUrl, "OIDC_ISSUER_URL must be set when OIDC is enabled").toBeTruthy(); + const expectedOidcAuthUrl = `${oidcIssuerUrl}/protocol/openid-connect/auth`; + await gotoOnion(page, `${baseUrl}/`); + await expect + .poll(() => page.url(), { + timeout: resolveTimeout(60_000), + message: `expected redirect to Keycloak OIDC auth (${expectedOidcAuthUrl})`, + }) + .toContain(expectedOidcAuthUrl); + await performKeycloakLoginForm(page, adminUsername, adminPassword); + await expect + .poll(() => page.url(), { + timeout: resolveTimeout(90_000), + message: `expected redirect back to the OpenClaw gateway at ${baseUrl}`, + }) + .toContain(canonicalDomain); + await expect(page.locator("body")).toBeVisible({ timeout: resolveTimeout(60_000) }); +}); diff --git a/roles/web-app-openclaw/files/test/.nocheck b/roles/web-app-openclaw/files/test/.nocheck new file mode 100644 index 0000000000..2b9d82d840 --- /dev/null +++ b/roles/web-app-openclaw/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; test-e2e-cli stages files/test/ by that fixed path. diff --git a/roles/web-app-openclaw/files/test/test.sh b/roles/web-app-openclaw/files/test/test.sh new file mode 100644 index 0000000000..1e4ed523a6 --- /dev/null +++ b/roles/web-app-openclaw/files/test/test.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# CLI test for web-app-openclaw: the agent reaches every MCP server it was +# configured against. +# +# Env (rendered into test.env from templates/test.env.j2): +# MCP_TEST_ENABLED whether this round configures MCP for OpenClaw at all +# MCP_CLIENT_CONTAINER addressable OpenClaw container +set -euo pipefail + +: "${MCP_TEST_ENABLED:?}" +: "${MCP_CLIENT_CONTAINER:?}" + +RETRIES=20 +SLEEP_SECONDS=6 + +if [[ "${MCP_TEST_ENABLED}" != "true" ]]; then + echo "SKIP: MCP is switched off in this round" + exit 0 +fi + +attempt=0 +while :; do + reached=0 + out="$(container exec -i "${MCP_CLIENT_CONTAINER}" node dist/index.js mcp probe 2>&1)" || reached=$? + if [[ ${reached} -eq 0 && -n "${out}" && "${out}" != *"failed to start server"* ]]; then + echo "${out}" + echo "ALL CHECKS PASSED" + exit 0 + fi + attempt=$((attempt + 1)) + if [[ ${attempt} -ge ${RETRIES} ]]; then + echo "[FAIL] OpenClaw could not connect to a configured MCP server: ${out}" >&2 + exit 1 + fi + sleep "${SLEEP_SECONDS}" +done diff --git a/roles/web-app-openclaw/meta/csp.yml b/roles/web-app-openclaw/meta/csp.yml new file mode 100644 index 0000000000..ca1af6faf9 --- /dev/null +++ b/roles/web-app-openclaw/meta/csp.yml @@ -0,0 +1,9 @@ +--- +flags: + script-src: + unsafe-eval: true # nocheck: csp-unsafe Reason: set when the role first deployed, with no console error recorded against it; TODO: re-verify against the running Control UI and drop the flag if the WebSocket SPA works without it + script-src-elem: + unsafe-inline: true # nocheck: csp-unsafe Reason: set when the role first deployed, with no console error recorded against it; TODO: re-verify against the running Control UI and drop the flag if the dashboard renders without it +whitelist: + font-src: [] + connect-src: [] diff --git a/roles/web-app-openclaw/meta/domains.yml b/roles/web-app-openclaw/meta/domains.yml new file mode 100644 index 0000000000..cb290d150d --- /dev/null +++ b/roles/web-app-openclaw/meta/domains.yml @@ -0,0 +1,4 @@ +--- +canonical: + openclaw: claw.ai.{{ DOMAIN_PRIMARY }} +aliases: [] diff --git a/roles/web-app-openclaw/meta/info.yml b/roles/web-app-openclaw/meta/info.yml new file mode 100644 index 0000000000..6ce7904b79 --- /dev/null +++ b/roles/web-app-openclaw/meta/info.yml @@ -0,0 +1,5 @@ +--- +# nocheck: info-media no official demo video +logo: + class: fa-solid fa-hand-sparkles +homepage: https://openclaw.ai/ diff --git a/roles/web-app-openclaw/meta/main.yml b/roles/web-app-openclaw/meta/main.yml new file mode 100644 index 0000000000..6907b6076c --- /dev/null +++ b/roles/web-app-openclaw/meta/main.yml @@ -0,0 +1,35 @@ +--- +galaxy_info: + author: Kevin Veen-Birkenbach + description: Self-hosted personal AI agent gateway with a browser control UI, sandboxed in a Kata microVM or gVisor runtime + license: Infinito.Nexus Community License (Non-Commercial) + company: | + Kevin Veen-Birkenbach + https://www.veen.world + galaxy_tags: + - ai + - agent + - openclaw + - assistant + - llm + - automation + - self-hosted + issue_tracker_url: https://s.infinito.nexus/issues + min_ansible_version: "2.9" + platforms: + - name: ArchLinux + versions: + - all + - name: Debian + versions: + - all + - name: EL + versions: + - all + - name: Fedora + versions: + - all + - name: Ubuntu + versions: + - all +dependencies: [] diff --git a/roles/web-app-openclaw/meta/mcp.yml b/roles/web-app-openclaw/meta/mcp.yml new file mode 100644 index 0000000000..7f400395c9 --- /dev/null +++ b/roles/web-app-openclaw/meta/mcp.yml @@ -0,0 +1,16 @@ +--- +classification: native_client +direction: client +source_url: https://openclaw.ai/ +implementation: native +supported_transports: + - streamable_http + - sse +supported_auths: + - bearer_token + - app_password + - upstream_session + - basic_auth +tools: + read_only_default: true + mutating_tools_enabled: false diff --git a/roles/web-app-openclaw/meta/networks.yml b/roles/web-app-openclaw/meta/networks.yml new file mode 100644 index 0000000000..c954900473 --- /dev/null +++ b/roles/web-app-openclaw/meta/networks.yml @@ -0,0 +1,3 @@ +--- +local: + subnet: 192.168.78.0/24 diff --git a/roles/web-app-openclaw/meta/rbac.yml b/roles/web-app-openclaw/meta/rbac.yml new file mode 100644 index 0000000000..70019a9c87 --- /dev/null +++ b/roles/web-app-openclaw/meta/rbac.yml @@ -0,0 +1,4 @@ +--- +roles: + mcp: + description: May drive this agent's MCP clients, which reach every admitted provider with the credentials the deployment issued rather than the caller's own diff --git a/roles/web-app-openclaw/meta/secrets.yml b/roles/web-app-openclaw/meta/secrets.yml new file mode 100644 index 0000000000..e94315ff5f --- /dev/null +++ b/roles/web-app-openclaw/meta/secrets.yml @@ -0,0 +1,12 @@ +--- +credentials: + litellm_api_key: + description: Per-consumer virtual key for the shared svc-ai-litellm gateway + algorithm: sk_prefixed + validation: + min_length: 50 + gateway_token: + description: OpenClaw gateway token guarding the control UI and API + algorithm: alphanumeric + validation: + min_length: 32 diff --git a/roles/web-app-openclaw/meta/server.yml b/roles/web-app-openclaw/meta/server.yml new file mode 100644 index 0000000000..dc2aa3200e --- /dev/null +++ b/roles/web-app-openclaw/meta/server.yml @@ -0,0 +1,3 @@ +--- +status_codes: + default: [200, 301, 302] diff --git a/roles/web-app-openclaw/meta/services.yml b/roles/web-app-openclaw/meta/services.yml new file mode 100644 index 0000000000..ba79f514df --- /dev/null +++ b/roles/web-app-openclaw/meta/services.yml @@ -0,0 +1,91 @@ +--- +# nocheck: playwright-service-flag +openclaw: + mcp_consumer: true + modes: + compose: + enabled: true + swarm: + enabled: true + replicas: 1 # nocheck: single-replica single-writer SQLite state on swarm-shared NFS; concurrent multi-node writers corrupt the agent's state directory + bond: 1 + enabled: true + shared: true + backup: + no_stop_required: true + image: ghcr.io/openclaw/openclaw + version: "2026.7.1" + name: openclaw + min_storage: 562MB + cpus: "2.0" + mem_reservation: 2g + mem_limit: 4g + pids_limit: 2048 + ports: + local: + http: 8090 + sso: 16511 + internal: + http: 18789 + lifecycle: beta + proxy: + service_key: openclaw + +# nocheck: playwright-service-flag, dynamic-flag +kata: + bond: 1 + enabled: true + shared: true + +sso: + bond: 1 + enabled: "{{ 'web-app-keycloak' in group_names }}" + shared: "{{ 'web-app-keycloak' in group_names }}" + flavor: oauth2 + oauth2: + origin: + host: openclaw + port: 18789 + allowed_groups: + - "{{ lookup('rbac_group_path', application_id='web-app-openclaw', role='administrator') }}" + - "{{ lookup('rbac_group_path', application_id='web-app-openclaw', role='mcp') }}" + +# nocheck: playwright-service-flag, dynamic-flag - the gateway is a single shared instance, never deployed per consumer +litellm: + bond: 1 + enabled: "{{ LITELLM_USABLE }}" + shared: true + +logout: + bond: 1 + enabled: "{{ 'web-svc-logout' in group_names }}" + shared: "{{ 'web-svc-logout' in group_names }}" +dashboard: + bond: 1 + enabled: "{{ 'web-app-dashboard' in group_names }}" + shared: "{{ 'web-app-dashboard' in group_names }}" +matomo: + bond: 1 + enabled: "{{ 'web-app-matomo' in group_names }}" + shared: "{{ 'web-app-matomo' in group_names }}" +css: + bond: 1 + enabled: "{{ 'web-svc-css' in group_names }}" + shared: "{{ 'web-svc-css' in group_names }}" +prometheus: + bond: 1 + enabled: "{{ 'web-app-prometheus' in group_names }}" + shared: "{{ 'web-app-prometheus' in group_names }}" + +# 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 +tor: + bond: 0.5 + enabled: "{{ 'svc-net-tor' in group_names }}" + shared: true # nocheck: dynamic-flag + +# nocheck: playwright-service-flag, dynamic-flag +container_backup: # nocheck: bond-baseline + bond: 1 + enabled: "{{ 'svc-bkp-volume-2-local' in group_names }}" + shared: true diff --git a/roles/web-app-openclaw/meta/tests.yml b/roles/web-app-openclaw/meta/tests.yml new file mode 100644 index 0000000000..aa08240d0e --- /dev/null +++ b/roles/web-app-openclaw/meta/tests.yml @@ -0,0 +1,4 @@ +--- +cli: + timeout: 600 + container_service_key: openclaw diff --git a/roles/web-app-openclaw/meta/users.yml b/roles/web-app-openclaw/meta/users.yml new file mode 100644 index 0000000000..563dcdd566 --- /dev/null +++ b/roles/web-app-openclaw/meta/users.yml @@ -0,0 +1,4 @@ +--- +openclaw: + description: Platform account the OpenClaw agent employee acts as. Non-privileged by design, with its own mailbox. Override the `openclaw` key through the + inventory `users` variable to point the agent at an account that already exists instead. diff --git a/roles/web-app-openclaw/meta/variants.yml b/roles/web-app-openclaw/meta/variants.yml new file mode 100644 index 0000000000..5f0c5ee5b0 --- /dev/null +++ b/roles/web-app-openclaw/meta/variants.yml @@ -0,0 +1,81 @@ +--- +# Matrix-deploy variant overrides for this role. +# See docs/contributing/artefact/files/role/variants.md for the file format. + +- services: + container_backup: + enabled: true + sso: + enabled: true + shared: true + litellm: + enabled: true + logout: + enabled: true + shared: true + dashboard: + enabled: true + shared: true + matomo: + enabled: true + shared: true + css: + enabled: true + shared: true + prometheus: + enabled: true + shared: true + tor: + enabled: true +- services: + container_backup: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + sso: + enabled: true + shared: true + litellm: + enabled: false + logout: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + dashboard: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + matomo: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + css: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + prometheus: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + tor: + enabled: true +- services: + container_backup: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + sso: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + litellm: + enabled: false + logout: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + dashboard: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + matomo: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + css: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + prometheus: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + tor: + enabled: true diff --git a/roles/web-app-openclaw/meta/volumes.yml b/roles/web-app-openclaw/meta/volumes.yml new file mode 100644 index 0000000000..a8cc18dab5 --- /dev/null +++ b/roles/web-app-openclaw/meta/volumes.yml @@ -0,0 +1,14 @@ +--- +openclaw_data: + type: volume + mounts: + - service: openclaw + target: /home/node/.openclaw + +openclaw_config: + type: config + source: "{{ [ lookup('container', 'web-app-openclaw', 'directories.config'), 'openclaw.json' ] | path_join }}" + mode: "0644" + mounts: + - service: openclaw + target: /home/node/.openclaw/openclaw.json diff --git a/roles/web-app-openclaw/tasks/00_core.yml b/roles/web-app-openclaw/tasks/00_core.yml new file mode 100644 index 0000000000..6f2d5001cc --- /dev/null +++ b/roles/web-app-openclaw/tasks/00_core.yml @@ -0,0 +1,28 @@ +--- +- include_tasks: utils/once/flag.yml + +- name: "๐Ÿ” Verify the gateway contract for {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-litellm/tasks/utils/consumer_contract.yml') }}" + when: OPENCLAW_LITELLM_ENABLED | bool + +- name: "๐Ÿค– Admit embodied mode for {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-robot/tasks/utils/admit.yml') }}" + vars: + admit_agent_role: "{{ application_id }}" + when: "'svc-ai-robot' in group_names" + +- name: "๐Ÿงฉ load docker and db for {{ application_id }}" + include_role: + name: sys-stk-full + +- name: "๐Ÿ”Œ Configure the OpenClaw MCP surface" + ansible.builtin.include_tasks: utils/mcp.yml + +- name: "๐Ÿ›ก๏ธ Prove the isolation {{ application_id }} promises" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-virt-kata/tasks/utils/assert_isolated.yml') }}" + vars: + assert_isolated_container: "{{ OPENCLAW_CONTAINER }}" + when: + - DEPLOYMENT_MODE == 'compose' + - "'svc-ai-robot' not in group_names" + - lookup('config', application_id, 'services.kata.enabled') | bool diff --git a/roles/web-app-openclaw/tasks/main.yml b/roles/web-app-openclaw/tasks/main.yml new file mode 100644 index 0000000000..1fa0de62e9 --- /dev/null +++ b/roles/web-app-openclaw/tasks/main.yml @@ -0,0 +1,5 @@ +--- +- include_tasks: 00_core.yml + when: run_once_web_app_openclaw is not defined + vars: + application_id: web-app-openclaw diff --git a/roles/web-app-openclaw/tasks/utils/mcp.yml b/roles/web-app-openclaw/tasks/utils/mcp.yml new file mode 100644 index 0000000000..02e77f830e --- /dev/null +++ b/roles/web-app-openclaw/tasks/utils/mcp.yml @@ -0,0 +1,11 @@ +--- +- name: "๐Ÿ“„ Render the OpenClaw gateway config from the current discovery" + ansible.builtin.include_tasks: + file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" + vars: + role_templates: + - src: "openclaw.json.j2" + dest: "{{ OPENCLAW_CONFIG_PATH_HOST }}" + +- name: "๐Ÿ”„ Start the stack so the gateway reads the config" + ansible.builtin.meta: flush_handlers diff --git a/roles/web-app-openclaw/templates/compose.yml.j2 b/roles/web-app-openclaw/templates/compose.yml.j2 new file mode 100644 index 0000000000..1cc57e2716 --- /dev/null +++ b/roles/web-app-openclaw/templates/compose.yml.j2 @@ -0,0 +1,32 @@ +{% include 'roles/sys-svc-compose/templates/base.yml.j2' %} + + {% set service_name = 'openclaw' %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, 'openclaw') }} + {{ lookup('compose_only', 'container_name', OPENCLAW_CONTAINER) }} + {% if 'svc-ai-robot' in group_names %} + devices: + {% for device in ROBOT_DEVICE_ALLOWLIST %} + - {{ device }} + {% endfor %} + {% elif lookup('config', application_id, 'services.kata.enabled') | bool %} + {{ lookup('compose_only', 'runtime', SANDBOX_RUNTIME) }} + {% endif %} + user: "0:0" + command: ["node", "dist/index.js", "gateway", "run", "--bind", "lan", "--port", "{{ OPENCLAW_PORT_INTERNAL }}"] + healthcheck: + test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:{{ OPENCLAW_PORT_INTERNAL }}/healthz').then((r)=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"] + interval: 2m + timeout: 5s + retries: 5 + start_period: 10m + start_interval: 5s + {{ lookup('container_ports', ['openclaw', 'http', DOCKER_BIND_HOST]) | indent(4) }} + {{ lookup('container_volumes', service_name) | indent(4) }} + {{ lookup('container_networks') | indent(4) }} + {{ lookup('container_depends_on', application_id) | indent(4) }} + +{{ lookup('compose_networks') }} + +{{ lookup('compose_volumes') }} diff --git a/roles/web-app-openclaw/templates/env.j2 b/roles/web-app-openclaw/templates/env.j2 new file mode 100644 index 0000000000..c9583bb4cc --- /dev/null +++ b/roles/web-app-openclaw/templates/env.j2 @@ -0,0 +1,9 @@ +{% include 'roles/sys-svc-container/templates/env.j2' %} + +HOME=/home/node +OPENCLAW_CONFIG_DIR={{ lookup('volume', application_id, 'openclaw_data').target }} +OPENCLAW_CONFIG_PATH={{ lookup('volume', application_id, 'openclaw_config').target }} +OPENCLAW_GATEWAY_TOKEN={{ lookup('config', application_id, 'secrets.credentials.gateway_token') | dotenv_quote }} +OPENCLAW_HOME=/home/node +OPENCLAW_STATE_DIR={{ lookup('volume', application_id, 'openclaw_data').target }} +OPENCLAW_WORKSPACE_DIR={{ [ lookup('volume', application_id, 'openclaw_data').target, 'workspace' ] | path_join }} diff --git a/roles/web-app-openclaw/templates/openclaw.json.j2 b/roles/web-app-openclaw/templates/openclaw.json.j2 new file mode 100644 index 0000000000..0b96f2c4ef --- /dev/null +++ b/roles/web-app-openclaw/templates/openclaw.json.j2 @@ -0,0 +1,37 @@ +{ + "gateway": { + "mode": "local", + "controlUi": { + "allowedOrigins": [{{ OPENCLAW_URL | to_json }}] + } + }{% if OPENCLAW_LITELLM_ENABLED | bool %}, + "agents": { + "defaults": { + "model": {"primary": {{ (OPENCLAW_LITELLM_PROVIDER ~ '/' ~ OPENCLAW_LITELLM_MODEL) | to_json }}} + } + }, + "models": { + "providers": { + {{ OPENCLAW_LITELLM_PROVIDER | to_json }}: { + "baseUrl": {{ OPENCLAW_LITELLM_BASE_URL | to_json }}, + "apiKey": {{ OPENCLAW_LITELLM_API_KEY | to_json }}, + "api": "openai-completions", + "models": [{"id": {{ OPENCLAW_LITELLM_MODEL | to_json }}, "name": {{ OPENCLAW_LITELLM_MODEL | to_json }}}] + } + } + } +{% endif %}{% set renderable = OPENCLAW_MCP_SERVERS | mcp_renderable_servers %}{% if renderable | length > 0 %}, + "mcp": { + "servers": { +{% for server in renderable %}{% set callable_tools = server.tools | reject('in', server.mutating | default([])) | list %} + {{ server.id | to_json }}: { + "url": {{ server.url | to_json }}, + "transport": {{ server.transport | to_json }}, + "headers": {"Authorization": {{ server | mcp_authorization | to_json }}}, + "toolFilter": {"include": {{ callable_tools | to_json }}} + }{{ "," if not loop.last }} +{% endfor %} + } + } +{% endif %} +} diff --git a/roles/web-app-openclaw/templates/playwright.env.j2 b/roles/web-app-openclaw/templates/playwright.env.j2 new file mode 100644 index 0000000000..0d8b96b2a8 --- /dev/null +++ b/roles/web-app-openclaw/templates/playwright.env.j2 @@ -0,0 +1,41 @@ +ADMIN_PASSWORD={{ lookup('users', 'administrator').password | dotenv_quote }} + +ADMIN_USERNAME={{ lookup('users', 'administrator').username | dotenv_quote }} + +APP_BASE_URL={{ lookup('tls', application_id, 'url.base') }} + +BIBER_PASSWORD={{ lookup('users', 'biber').password | dotenv_quote }} + +BIBER_USERNAME={{ lookup('users', 'biber').username | dotenv_quote }} + +CANONICAL_DOMAIN={{ lookup('domain', application_id) | dotenv_quote }} + +# nocheck: playwright-service-gate +CSS_SERVICE_ENABLED={{ lookup('config', application_id, 'services.css.enabled') | string | lower }} + +# nocheck: playwright-service-gate +LITELLM_SERVICE_ENABLED={{ lookup('config', application_id, 'services.litellm.enabled') | string | lower }} + +LOGOUT_SERVICE_ENABLED={{ lookup('config', application_id, 'services.logout.enabled') | string | lower }} + +# nocheck: playwright-service-gate +MATOMO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.matomo.enabled') | string | lower }} + +# nocheck: playwright-service-gate +MCP_SERVICE_ENABLED={{ lookup('config', application_id, 'mcp.enabled') | string | lower }} + +NODE_TLS_REJECT_UNAUTHORIZED=0 + +OIDC_ISSUER_URL={{ OIDC.CLIENT.ISSUER_URL | dotenv_quote }} + +OPENCLAW_BASE_URL={{ lookup('tls', application_id, 'url.base') | dotenv_quote }} + +OPENCLAW_GATEWAY_TOKEN={{ lookup('config', application_id, 'secrets.credentials.gateway_token') | dotenv_quote }} + +# nocheck: persona-block-rationale: the OpenClaw Control UI is a WebSocket SPA whose session lives behind gateway device pairing, so it exposes no DOM logout control the shared inAppLogout helper can reach. files/playwright/test-oidc-login.js covers the SSO round trip instead (see TODO.md). +PERSONA_ADMINISTRATOR_BLOCKED=true + +# nocheck: persona-block-rationale: meta/services.yml admits only the web-app-openclaw administrator and mcp RBAC groups to the oauth2 proxy (sso.oauth2.allowed_groups) and biber carries neither, so biber is refused at the proxy before the Control UI is reached. +PERSONA_BIBER_BLOCKED=true + +SSO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.sso.enabled') | string | lower }} diff --git a/roles/web-app-openclaw/templates/test.env.j2 b/roles/web-app-openclaw/templates/test.env.j2 new file mode 100644 index 0000000000..f6e61e48e5 --- /dev/null +++ b/roles/web-app-openclaw/templates/test.env.j2 @@ -0,0 +1,2 @@ +MCP_CLIENT_CONTAINER={{ CLI_LOCAL_CID }} +MCP_TEST_ENABLED={{ lookup('config', application_id, 'mcp.enabled') | string | lower }} diff --git a/roles/web-app-openclaw/vars/main.yml b/roles/web-app-openclaw/vars/main.yml new file mode 100644 index 0000000000..0e90df6fc6 --- /dev/null +++ b/roles/web-app-openclaw/vars/main.yml @@ -0,0 +1,17 @@ +--- +application_id: "web-app-openclaw" +entity_name: "{{ application_id | get_entity_name }}" +domain: "{{ lookup('domain', application_id) }}" +http_port: "{{ lookup('config', application_id, 'services.openclaw.ports.local.http') }}" + +OPENCLAW_CONTAINER: "{{ lookup('config', application_id, 'services.openclaw.name') }}" +OPENCLAW_PORT_INTERNAL: "{{ lookup('config', application_id, 'services.openclaw.ports.internal.http') }}" +OPENCLAW_URL: "{{ lookup('tls', application_id, 'url.base') }}" +OPENCLAW_CONFIG_PATH_HOST: "{{ [ lookup('container', application_id, 'directories.config'), 'openclaw.json' ] | path_join }}" +OPENCLAW_MCP_SERVERS: "{{ MCP_DISCOVERED_SERVERS if (lookup('config', application_id, 'mcp.enabled') | bool) else [] }}" + +OPENCLAW_LITELLM_ENABLED: "{{ lookup('config', application_id, 'services.litellm.enabled') }}" +OPENCLAW_LITELLM_BASE_URL: "{{ LITELLM_OPENAI_BASE_LOCAL_URL }}" +OPENCLAW_LITELLM_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.litellm_api_key') }}" +OPENCLAW_LITELLM_PROVIDER: litellm +OPENCLAW_LITELLM_MODEL: "{{ LITELLM_CHAT_MODEL }}" diff --git a/roles/web-app-opencloud/README.md b/roles/web-app-opencloud/README.md index d98c48e0c2..a62e146950 100644 --- a/roles/web-app-opencloud/README.md +++ b/roles/web-app-opencloud/README.md @@ -82,19 +82,20 @@ Run the published image to provision the inventory and deploy OpenCloud to a man ```bash APP=web-app-opencloud HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-openproject/README.md b/roles/web-app-openproject/README.md index 26d7517919..d33a5dc532 100644 --- a/roles/web-app-openproject/README.md +++ b/roles/web-app-openproject/README.md @@ -120,19 +120,20 @@ Run the published image to provision the inventory and deploy OpenProject to a m ```bash APP=web-app-openproject HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-openproject/vars/main.yml b/roles/web-app-openproject/vars/main.yml index e2cc94111e..a0ad4b5cf9 100644 --- a/roles/web-app-openproject/vars/main.yml +++ b/roles/web-app-openproject/vars/main.yml @@ -4,8 +4,8 @@ entity_name: "{{ application_id | get_entity_name }}" OPENPROJECT_VERSION: "{{ lookup('config', application_id, 'services.web.version') }}" OPENPROJECT_IMAGE: "{{ lookup('config', application_id, 'services.web.image') }}" -OPENPROJECT_REPOSITORY: "{{ lookup('config', application_id, 'services.openproject.repository') }}" -OPENPROJECT_REF: "{{ lookup('config', application_id, 'services.openproject.ref') }}" +OPENPROJECT_REPOSITORY: "{{ lookup('config', 'web-app-openproject', 'services.openproject.repository') }}" +OPENPROJECT_REF: "{{ lookup('config', 'web-app-openproject', 'services.openproject.ref') }}" OPENPROJECT_WEB_SERVICE: "web" OPENPROJECT_WEB_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ OPENPROJECT_WEB_SERVICE ~ '.name') }}" OPENPROJECT_WEB_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, OPENPROJECT_WEB_SERVICE) }}" diff --git a/roles/web-app-opentalk/README.md b/roles/web-app-opentalk/README.md index fe310cc32f..9c598bcf0c 100644 --- a/roles/web-app-opentalk/README.md +++ b/roles/web-app-opentalk/README.md @@ -99,19 +99,20 @@ Run the published image to provision the inventory and deploy OpenTalk to a mana ```bash APP=web-app-opentalk HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-opentalk/meta/info.yml b/roles/web-app-opentalk/meta/info.yml index a2b7072c3b..57d5a58892 100644 --- a/roles/web-app-opentalk/meta/info.yml +++ b/roles/web-app-opentalk/meta/info.yml @@ -1,4 +1,5 @@ --- +# nocheck: info-media no official demo video logo: class: fa-solid fa-video homepage: https://opentalk.eu/ diff --git a/roles/web-app-opentalk/meta/main.yml b/roles/web-app-opentalk/meta/main.yml index 266b42833e..01224255b5 100644 --- a/roles/web-app-opentalk/meta/main.yml +++ b/roles/web-app-opentalk/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Sovereign open-source video conferencing platform for audio/video calls, screen sharing, breakout rooms, and SSO diff --git a/roles/web-app-opentalk/meta/services.yml b/roles/web-app-opentalk/meta/services.yml index d665e736ec..2918199a75 100644 --- a/roles/web-app-opentalk/meta/services.yml +++ b/roles/web-app-opentalk/meta/services.yml @@ -127,6 +127,11 @@ seaweedfs: enabled: true # nocheck: dynamic-flag shared: "{{ 'web-app-seaweedfs' in group_names }}" rabbit: + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "ping"] + # nocheck: healthcheck-timing-override rabbitmq-diagnostics starts an Erlang CLI node, which does not finish inside the 5s default + timeout: 10s + retries: 5 name: opentalk-rabbit image: rabbitmq version: 4.3.5 @@ -156,7 +161,6 @@ prometheus: # nocheck: playwright-service-flag tor: - bond: 0.5 enabled: false # nocheck: dynamic-flag shared: false # nocheck: dynamic-flag # nocheck: dynamic-flag diff --git a/roles/web-app-opentalk/meta/volumes.yml b/roles/web-app-opentalk/meta/volumes.yml index e91582e949..1fbcdb6011 100644 --- a/roles/web-app-opentalk/meta/volumes.yml +++ b/roles/web-app-opentalk/meta/volumes.yml @@ -1,4 +1,5 @@ --- +# nocheck: config-volume-secret The OpenTalk controller reads one controller.toml that carries the service API secret beside the non-secret settings; the controller has no separate secret source to point at instead. data: type: volume name: opentalk_data diff --git a/roles/web-app-opentalk/templates/compose.yml.j2 b/roles/web-app-opentalk/templates/compose.yml.j2 index 5309978389..1f3b15103a 100644 --- a/roles/web-app-opentalk/templates/compose.yml.j2 +++ b/roles/web-app-opentalk/templates/compose.yml.j2 @@ -42,11 +42,7 @@ {{ lookup('compose_restart') }} environment: RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS: "-rabbit consumer_timeout 30000" - healthcheck: - test: ["CMD", "rabbitmq-diagnostics", "ping"] - interval: 30s - timeout: 10s - retries: 5 + {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_networks') | indent(4) }} logging: diff --git a/roles/web-app-openwebui/README.md b/roles/web-app-openwebui/README.md index a4c83849d3..43ba37378a 100644 --- a/roles/web-app-openwebui/README.md +++ b/roles/web-app-openwebui/README.md @@ -15,7 +15,7 @@ The diagram places Open WebUI in the Infinito.Nexus cosmos: the components it de ```mermaid flowchart LR subgraph deps [Dependencies] - dep_svc_ai_ollama["svc-ai-ollama ๐Ÿณ๐Ÿ"] + dep_svc_ai_litellm["svc-ai-litellm ๐Ÿณ๐Ÿ"] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local ๐Ÿ’ป"] dep_svc_db_openldap["svc-db-openldap ๐Ÿณ๐Ÿ"] dep_svc_net_tor["svc-net-tor ๐Ÿณ๐Ÿ"] @@ -40,16 +40,28 @@ flowchart LR svc_seaweedfs["seaweedfs"] svc_css["css"] svc_javascript["javascript"] - svc_ollama["ollama"] + svc_litellm["litellm"] svc_email["email"] svc_prometheus["prometheus"] svc_tor["tor"] svc_container_backup["container_backup"] end subgraph dependents [Dependents] - dpt_web_app_nextcloud["web-app-nextcloud ๐Ÿณ๐Ÿ"] + dpt_svc_db_qdrant["svc-db-qdrant ๐Ÿณ๐Ÿ"] + dpt_web_app_baserow["web-app-baserow ๐Ÿณ๐Ÿ"] + dpt_web_app_checkmk["web-app-checkmk ๐Ÿณ๐Ÿ"] + dpt_web_app_fider["web-app-fider ๐Ÿณ๐Ÿ"] + dpt_web_app_gitea["web-app-gitea ๐Ÿณ๐Ÿ"] + dpt_web_app_gitlab["web-app-gitlab ๐Ÿณ๐Ÿ"] + dpt_web_app_homeassistant["web-app-homeassistant ๐Ÿณ๐Ÿ"] + dpt_web_app_jellyfin["web-app-jellyfin ๐Ÿณ๐Ÿ"] + dpt_web_app_jenkins["web-app-jenkins ๐Ÿณ๐Ÿ"] + dpt_web_app_listmonk["web-app-listmonk ๐Ÿณ๐Ÿ"] + dpt_web_app_mattermost["web-app-mattermost ๐Ÿณ๐Ÿ"] + dpt_web_app_moodle["web-app-moodle ๐Ÿณ๐Ÿ"] + dpt_more["..."] end - dep_svc_ai_ollama -. "0..1" .-> svc_ollama + dep_svc_ai_litellm -. "0..1" .-> svc_litellm dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup dep_svc_db_openldap -. "0..1" .-> svc_ldap dep_svc_net_tor -. "0..1" .-> svc_tor @@ -61,7 +73,19 @@ flowchart LR dep_web_app_seaweedfs -. "0..1" .-> svc_seaweedfs dep_web_svc_css -. "0..1" .-> svc_css dep_web_svc_logout -. "0..1" .-> svc_logout - svc_sso -. "0..1" .-> dpt_web_app_nextcloud + svc_sso -- "1:1" --> dpt_more + svc_sso -. "0..1" .-> dpt_svc_db_qdrant + svc_sso -. "0..1" .-> dpt_web_app_baserow + svc_sso -. "0..1" .-> dpt_web_app_checkmk + svc_sso -. "0..1" .-> dpt_web_app_fider + svc_sso -. "0..1" .-> dpt_web_app_gitea + svc_sso -. "0..1" .-> dpt_web_app_gitlab + svc_sso -. "0..1" .-> dpt_web_app_homeassistant + svc_sso -. "0..1" .-> dpt_web_app_jellyfin + svc_sso -. "0..1" .-> dpt_web_app_jenkins + svc_sso -. "0..1" .-> dpt_web_app_listmonk + svc_sso -. "0..1" .-> dpt_web_app_mattermost + svc_sso -. "0..1" .-> dpt_web_app_moodle ``` Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (๐Ÿ’ป host, ๐Ÿณ compose, ๐Ÿ swarm); โŒ marks a service that is explicitly turned off, and โš™๏ธ an Ansible role dependency declared in `meta/main.yml`. @@ -94,19 +118,20 @@ Run the published image to provision the inventory and deploy Open WebUI to a ma ```bash APP=web-app-openwebui HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' @@ -117,6 +142,122 @@ docker run --rm -it \ * Open WebUI: [openwebui.com](https://openwebui.com) * Ollama: [ollama.com](https://ollama.com) +## MCP Client + +Open WebUI consumes MCP through its native tool-server support. Every deployed +shared MCP server role is rendered into `TOOL_SERVER_CONNECTIONS` as a +`type: mcp` entry. + +### Configuration + +| Property | Value | +| --- | --- | +| Direction | `client` | +| Transport | Streamable HTTP | +| Env key | `TOOL_SERVER_CONNECTIONS` | +| Auth | `auth_type: bearer` with the token from the discovery data | +| Access | `config.access_grants: []`, administrator-only rather than public | + +Open WebUI's `ToolServerConnection` accepts bearer, session, system_oauth and +oauth_2.1. A server whose scheme it cannot present is skipped rather than +registered with an unusable credential, so a basic-auth server such as Jenkins +does not appear here. + +### Verification + +The token each entry carries is the one the deployment issued, not the signed-in +caller's own, so reaching an MCP tool server is a grant separate from signing +in. The env renders `config.access_grants: []`, which `has_connection_access` +reads as administrator-only, and +[`tasks/utils/mcp.yml`](./tasks/utils/mcp.yml) then narrows each entry to the serving +role's `mcp` RBAC group. + +That second step exists because a group grant addresses an Open WebUI group id +and `insert_new_group` assigns it as a fresh UUID, so the id cannot be known +while the env is rendered. The task signs in as the native administrator, +resolves or creates the group whose name matches the OIDC claim value, and +writes the grant through `POST /api/v1/configs/tool_servers`. It refuses to act +when two groups share a name rather than guessing between them. + +`BYPASS_ADMIN_ACCESS_CONTROL=false` keeps the grant meaningful for +administrators too; upstream defaults it to true, which would let every +administrator past any grant. `ENABLE_OAUTH_GROUP_MANAGEMENT` syncs the +platform's groups on login, so membership follows Keycloak. + +`ENABLE_OAUTH_ROLE_MANAGEMENT` maps the application's administrator group onto +the Open WebUI admin role, and it also makes `OAUTH_ALLOWED_ROLES` a sign-in +gate. The env sets `OAUTH_ALLOWED_ROLES=*` so every platform role passes that +gate; narrow it only to a list that matches the `/roles//` paths +Keycloak emits. + +Entries render **disabled**, and the task enables each one in the same write +that carries its grant. An empty `access_grants` is not "nobody": Open WebUI +reads it as every administrator, which is wider than the `mcp` group. Since +`ENABLE_PERSISTENT_CONFIG=false` makes the env authoritative again on every +start, an enabled-but-ungranted entry would hand access to all administrators +before the first provisioning run and after any bare container restart. A +disabled entry is not served at all, so the fallback is no access rather than +too much. + +### Operational limits + +Three properties follow from how Open WebUI works and none of them is closed by +this role. + +**Only the first start serves nothing.** The env is authoritative again on every +start, so what `TOOL_SERVER_CONNECTIONS` carries is the state the container comes +back with. Before any group exists that is a disabled entry, which is the safe +direction: no access rather than every administrator. Once the provisioning task +has created the group, its id lives in the token store, `vars/main.yml` reads it +back on the next deploy, and the filter renders the entry enabled with its exact +group grant. From then on a bare container restart restores a served, correctly +scoped connection without a deploy. + +**Group revocation is not reliable, in both directions.** Open WebUI removes a +user from a synced group only while the groups claim is non-empty, so a user who +loses their last role keeps stale membership until a later login carries a +non-empty claim. Conversely, a non-empty claim removes the user from *every* +local group the claim does not name, including groups an administrator created by +hand. Reconciling either from the deploy would mean a second writer for group +membership, competing with the login-time sync and able to evict accounts the +platform's own user list does not know about, so both are left to an external +reconciler or an upstream fix. + +**The deploy can create a role-internal administrator.** On an instance with no +users at all there is no OIDC administrator to borrow an API key from, so +[`tasks/utils/mcp.yml`](./tasks/utils/mcp.yml) creates the `openwebui-api-bot` declared +in [`meta/users.yml`](./meta/users.yml), whose password the platform generates +with every other user's. It is deliberately not an OIDC identity: Open WebUI ships +`OAUTH_MERGE_ACCOUNTS_BY_EMAIL` disabled and refuses an OIDC login whose email a +local account already holds, so seeding a person's address would lock them out of +their own login. On an instance that already has an administrator no account is +created. + +**The `mcp` role is granted per platform, not per application.** A user's +`roles:` list carries role names only, and +[`build_realm_rbac_groups`](../web-app-keycloak/filter_plugins/build_realm_rbac_groups.py) +matches them without an application context, so `roles: [mcp]` makes that user a +member of *every* deployed `/roles//mcp` group. Entitling somebody to drive +Baserow but not GitLab is therefore not expressible declaratively today; it needs +the Keycloak membership to be set directly on the single group. The tool-server +side honours whatever membership arrives, so the limit is the platform's user +model, not this wiring, and the Playwright coverage reflects it: it proves "all +groups sees all servers" and "no group sees none", not the selective case. + +The role ships a Playwright spec that signs in as the administrator, reads +`/api/v1/configs/tool_servers`, and asserts that every discovered server appears +with a bearer and a non-empty key. + +### Default state + +Off. `mcp.enabled` is false unless an MCP server role is part of the +deployment. + +### How to disable + +Remove the MCP server roles, or pin `mcp.enabled: false` for this role. +`TOOL_SERVER_CONNECTIONS` then renders empty. + ## Credits Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. diff --git a/roles/web-app-openwebui/files/playwright/_shared.js b/roles/web-app-openwebui/files/playwright/_shared.js index 1b21218647..905c80ef0b 100644 --- a/roles/web-app-openwebui/files/playwright/_shared.js +++ b/roles/web-app-openwebui/files/playwright/_shared.js @@ -18,6 +18,13 @@ const env = { biberUsername: decodeDotenvQuotedValue(process.env.BIBER_USERNAME), biberPassword: decodeDotenvQuotedValue(process.env.BIBER_PASSWORD), canonicalDomain: decodeDotenvQuotedValue(process.env.CANONICAL_DOMAIN), + mcpExpectedServers: decodeDotenvQuotedValue(process.env.MCP_EXPECTED_SERVERS), + mcpExpectedTools: decodeDotenvQuotedValue(process.env.MCP_EXPECTED_TOOLS), + lamBaseUrl: normalizeBaseUrl(process.env.LAM_BASE_URL || ""), + ldapBindDn: decodeDotenvQuotedValue(process.env.LDAP_BIND_DN), + ldapBindPassword: decodeDotenvQuotedValue(process.env.LDAP_BIND_PASSWORD), + ldapUserDnBase: decodeDotenvQuotedValue(process.env.LDAP_USER_DN_BASE), + ldapRoleDnBase: decodeDotenvQuotedValue(process.env.LDAP_ROLE_DN_BASE), }; function attachDiagnostics(page) { diff --git a/roles/web-app-openwebui/files/playwright/playwright.spec.js b/roles/web-app-openwebui/files/playwright/playwright.spec.js index 57546de3dd..047e193078 100644 --- a/roles/web-app-openwebui/files/playwright/playwright.spec.js +++ b/roles/web-app-openwebui/files/playwright/playwright.spec.js @@ -13,5 +13,9 @@ require("./test-admin-native-login").register(shared); require("./test-admin-ldap-login").register(shared); require("./test-biber-ldap-login").register(shared); require("./test-guest-persona").register(shared); -require("./test-ollama-chat").register(shared); +require("./test-litellm-chat").register(shared); +require("./test-mcp-servers").register(shared); +require("./test-mcp-bridge").register(shared); +require("./test-mcp-non-member").register(shared); +require("./test-mcp-grant-via-lam").register(shared); require("./test-seaweedfs"); diff --git a/roles/web-app-openwebui/files/playwright/test-ollama-chat.js b/roles/web-app-openwebui/files/playwright/test-litellm-chat.js similarity index 73% rename from roles/web-app-openwebui/files/playwright/test-ollama-chat.js rename to roles/web-app-openwebui/files/playwright/test-litellm-chat.js index 23d4159a48..c899864e81 100644 --- a/roles/web-app-openwebui/files/playwright/test-ollama-chat.js +++ b/roles/web-app-openwebui/files/playwright/test-litellm-chat.js @@ -3,8 +3,9 @@ const { resolveTimeout } = require("./timeouts"); const { skipUnlessServiceEnabled } = require("./service-gating"); exports.register = function (shared) { - test("ollama chat: the preloaded model answers a chat completion via OpenWebUI", async ({ page }) => { - skipUnlessServiceEnabled("ollama"); + test("litellm chat: a gateway model answers a chat completion via OpenWebUI", async ({ page }) => { + skipUnlessServiceEnabled("litellm"); + skipUnlessServiceEnabled("sso"); test.setTimeout(resolveTimeout(120_000)); await shared.signInViaDashboardOidc( @@ -32,30 +33,30 @@ exports.register = function (shared) { const modelsBody = await modelsResp.json(); const modelIds = (Array.isArray(modelsBody?.data) ? modelsBody.data : []) .map((m) => String(m?.id ?? m?.name ?? "")); - const ollamaModel = modelIds.find((id) => id.startsWith("smollm2")); + const chatModel = modelIds.find((id) => id && !/embed/i.test(id)); expect( - ollamaModel, - `the preloaded Ollama model (smollm2) must be served by OpenWebUI, proving the Ollama backend is reachable and the model pulled (got ${JSON.stringify(modelIds)})` + chatModel, + `a chat model must be served by OpenWebUI through the LiteLLM gateway, proving gateway and backend are reachable and the model pulled (got ${JSON.stringify(modelIds)})` ).toBeTruthy(); const chatResp = await page.request.post(`${base}/api/chat/completions`, { headers, data: { - model: ollamaModel, + model: chatModel, messages: [{ role: "user", content: "Reply with exactly the word: pong" }], stream: false, }, }); expect( chatResp.ok(), - `the ${ollamaModel} chat completion must return 200 over OpenWebUI -> Ollama (HTTP ${chatResp.status()})` + `the ${chatModel} chat completion must return 200 over OpenWebUI -> LiteLLM (HTTP ${chatResp.status()})` ).toBeTruthy(); const chatBody = await chatResp.json(); const content = (chatBody?.choices?.[0]?.message?.content ?? "").trim(); expect( content.length, - `the model must return a non-empty assistant response over OpenWebUI -> Ollama -> ${ollamaModel} (got ${JSON.stringify(chatBody).slice(0, 300)})` + `the model must return a non-empty assistant response over OpenWebUI -> LiteLLM -> ${chatModel} (got ${JSON.stringify(chatBody).slice(0, 300)})` ).toBeGreaterThan(0); }); }; diff --git a/roles/web-app-openwebui/files/playwright/test-mcp-bridge.js b/roles/web-app-openwebui/files/playwright/test-mcp-bridge.js new file mode 100644 index 0000000000..d93bc0436d --- /dev/null +++ b/roles/web-app-openwebui/files/playwright/test-mcp-bridge.js @@ -0,0 +1,87 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); +const { skipUnlessServiceEnabled } = require("./service-gating"); + +exports.register = function (shared) { + test("administrator: every registered MCP server answers Open WebUI's client", async ({ + page, + }) => { + skipUnlessServiceEnabled("mcp"); + skipUnlessServiceEnabled("sso"); + + const expected = (shared.env.mcpExpectedServers || "") + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + expect( + expected.length, + "the deploy must have discovered at least one MCP server when the mcp service is enabled" + ).toBeGreaterThan(0); + + test.setTimeout(resolveTimeout(60_000 + expected.length * 20_000)); + + await shared.signInViaDashboardOidc( + page, + shared.env.adminUsername, + shared.env.adminPassword, + "administrator" + ); + + const token = await page.evaluate(() => window.localStorage.getItem("token")); + expect(token, "OpenWebUI must store a session token after login").toBeTruthy(); + const headers = { Authorization: `Bearer ${token}` }; + const base = shared.env.openwebuiBaseUrl.replace(/\/+$/, ""); + + const readProbes = JSON.parse(shared.env.mcpExpectedTools || "{}"); + + const config = await page.request.get(`${base}/api/v1/configs/tool_servers`, { + headers, + }); + expect( + config.ok(), + `the admin tool-server config must answer the authenticated session (HTTP ${config.status()})` + ).toBeTruthy(); + const connections = (await config.json())?.TOOL_SERVER_CONNECTIONS ?? []; + + const verifiable = expected.filter((id) => { + const connection = connections.find( + (c) => c?.type === "mcp" && String(c?.info?.id ?? "") === id + ); + expect(connection, `${id} must be a configured MCP tool server`).toBeTruthy(); + return connection.auth_type === "bearer"; + }); + expect( + verifiable.length, + `none of ${JSON.stringify(expected)} authenticates with a deployment bearer; only a bearer connection carries its credential in the row, a system_oauth one resolves the caller's own upstream token and the administrator holds none, so there is nothing here this spec can verify against the bridge` + ).toBeGreaterThan(0); + + for (const id of verifiable) { + const connection = connections.find( + (c) => c?.type === "mcp" && String(c?.info?.id ?? "") === id + ); + + const verify = await page.request.post( + `${base}/api/v1/configs/tool_servers/verify`, + { headers, data: connection } + ); + expect( + verify.ok(), + `${id} did not answer Open WebUI's MCP client (HTTP ${verify.status()}); the endpoint is down, the deployed bearer is refused, or the transport disagrees` + ).toBeTruthy(); + + const specs = (await verify.json())?.specs ?? []; + expect( + specs.length, + `${id} completed the handshake but served no tool; a client would be configured against an empty surface` + ).toBeGreaterThan(0); + + const probe = readProbes[id]; + if (probe) { + expect( + specs.map((s) => String(s?.name ?? "")), + `${id} does not serve ${probe}, the read probe its meta/mcp.yml declares` + ).toContain(probe); + } + } + }); +}; diff --git a/roles/web-app-openwebui/files/playwright/test-mcp-grant-via-lam.js b/roles/web-app-openwebui/files/playwright/test-mcp-grant-via-lam.js new file mode 100644 index 0000000000..87537b551f --- /dev/null +++ b/roles/web-app-openwebui/files/playwright/test-mcp-grant-via-lam.js @@ -0,0 +1,316 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); +const { skipUnlessServiceEnabled } = require("./service-gating"); +const { performKeycloakLoginForm, gotoOnion } = require("./personas"); + +const LDAP_MEMBER_ATTRIBUTE = "member"; +const MEMBER_VALUE_LIST = `#attributeList_${LDAP_MEMBER_ATTRIBUTE}`; +const MEMBER_VALUE_INPUT = `input.lam-attr-${LDAP_MEMBER_ATTRIBUTE}`; +const ADD_VALUE_LINK = "a[onclick*='treeview.addValue']"; +const CLEAR_VALUE_LINK = "a[onclick*='treeview.clearValue']"; +const SAVE_BUTTON_NAME = /^\s*save\s*$/i; + +const CLAIM_PROPAGATION_MS = 120_000; + +const PERSONA_CONTEXT = { + ignoreHTTPSErrors: true, + viewport: { width: 1440, height: 1100 }, +}; + +function firstExpectedServer(shared) { + const servers = (shared.env.mcpExpectedServers || "") + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + expect( + servers.length, + "the deploy must have discovered at least one MCP server when the mcp service is enabled" + ).toBeGreaterThan(0); + return servers.slice().sort()[0]; +} + +async function sessionHeaders(page) { + const token = await page.evaluate(() => window.localStorage.getItem("token")); + expect(token, "OpenWebUI must store a session token after login").toBeTruthy(); + return { Authorization: `Bearer ${token}` }; +} + +async function servedToolIds(page, shared) { + const base = shared.env.openwebuiBaseUrl.replace(/\/+$/, ""); + const response = await page.request.get(`${base}/api/v1/tools/`, { + headers: await sessionHeaders(page), + }); + expect( + response.ok(), + `the tool list must answer the signed-in user (HTTP ${response.status()})` + ).toBeTruthy(); + return JSON.stringify(await response.json()); +} + +async function sessionUserId(page, shared) { + const base = shared.env.openwebuiBaseUrl.replace(/\/+$/, ""); + const response = await page.request.get(`${base}/api/v1/auths/`, { + headers: await sessionHeaders(page), + }); + expect( + response.ok(), + `the session endpoint must answer the signed-in user (HTTP ${response.status()})` + ).toBeTruthy(); + const id = (await response.json())?.id; + expect(id, "OpenWebUI must report the id of the signed-in user").toBeTruthy(); + return id; +} + +async function signInToLam(page, shared) { + await gotoOnion(page, `${shared.env.lamBaseUrl.replace(/\/+$/, "")}/`); + + if (/\/protocol\/openid-connect\//.test(page.url())) { + await performKeycloakLoginForm( + page, + shared.env.adminUsername, + shared.env.adminPassword + ); + } + + await expect( + page, + "LAM must be reached after the SSO hop, not left on the identity provider" + ).not.toHaveURL(/\/protocol\/openid-connect\//, { timeout: resolveTimeout(60_000) }); + + const passwordField = page + .locator("input[type='password'], input[name='passwd'], input#passwd") + .first(); + await expect( + passwordField, + "LAM must present its own login form after the SSO hop; the proxy does not bind to LDAP for us" + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + + const userSelect = page.getByRole("combobox", { name: /user ?name/i }).first(); + if (await userSelect.isVisible().catch(() => false)) { + const bindRdnValue = shared.env.ldapBindDn.split(",")[0].split("=").slice(1).join("="); + await userSelect.selectOption({ label: bindRdnValue }); + } + + await passwordField.fill(shared.env.ldapBindPassword); + await page.getByRole("button", { name: /login|anmelden/i }).first().click(); + + await expect( + passwordField, + "LAM must accept the bind credential instead of returning its login form" + ).toBeHidden({ timeout: resolveTimeout(60_000) }); +} + +async function openMemberValueList(page, shared, groupCn) { + const base = shared.env.lamBaseUrl.replace(/\/+$/, ""); + const groupDn = `cn=${groupCn},${shared.env.ldapRoleDnBase}`; + const dnParam = encodeURIComponent(Buffer.from(groupDn, "utf8").toString("base64")); + await gotoOnion(page, `${base}/lam/templates/tools/treeView.php?dn=${dnParam}`); + + await expect( + page.getByRole("heading", { name: new RegExp(`^cn=${groupCn},`) }).first(), + `LAM must open the ${groupCn} role group; a missing entry heading means the LDAP bind did not take` + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + + const memberList = page.locator(MEMBER_VALUE_LIST); + await expect( + memberList, + `LAM must render ${groupCn}'s ${LDAP_MEMBER_ATTRIBUTE} attribute as an editable value list` + ).toBeVisible({ timeout: resolveTimeout(30_000) }); + return memberList; +} + +function memberValues(memberList) { + return memberList + .locator(MEMBER_VALUE_INPUT) + .evaluateAll((inputs) => inputs.map((input) => input.value)); +} + +async function saveLamEntry(page) { + await page.getByRole("button", { name: SAVE_BUTTON_NAME }).first().click(); +} + +async function revokeMemberInLam(page, shared, groupCn, memberDn) { + const memberList = await openMemberValueList(page, shared, groupCn); + const values = await memberValues(memberList); + if (!values.includes(memberDn)) { + return; + } + + await memberList + .locator("li") + .nth(values.indexOf(memberDn)) + .locator(CLEAR_VALUE_LINK) + .click(); + await saveLamEntry(page); + + await expect + .poll(() => memberValues(memberList), { + timeout: resolveTimeout(60_000), + message: `LAM must drop ${memberDn} from ${groupCn}`, + }) + .not.toContain(memberDn); +} + +async function grantMemberInLam(page, shared, groupCn, memberDn) { + const memberList = await openMemberValueList(page, shared, groupCn); + expect( + await memberValues(memberList), + `${groupCn} must not already list ${memberDn}; the grant under test would prove nothing` + ).not.toContain(memberDn); + + await memberList.locator(ADD_VALUE_LINK).first().click(); + await memberList.locator(MEMBER_VALUE_INPUT).last().fill(memberDn); + await saveLamEntry(page); + + await expect + .poll(() => memberValues(memberList), { + timeout: resolveTimeout(60_000), + message: `LAM must persist ${memberDn} as a ${LDAP_MEMBER_ATTRIBUTE} of ${groupCn}`, + }) + .toContain(memberDn); +} + +async function grantedGroupId(page, shared, server) { + const base = shared.env.openwebuiBaseUrl.replace(/\/+$/, ""); + const response = await page.request.get(`${base}/api/v1/configs/tool_servers`, { + headers: await sessionHeaders(page), + }); + expect( + response.ok(), + `the administrator must read the tool-server config (HTTP ${response.status()})` + ).toBeTruthy(); + const connection = ((await response.json())?.TOOL_SERVER_CONNECTIONS || []).find( + (entry) => entry?.info?.id === server + ); + expect(connection, `${server} must be a configured tool server`).toBeTruthy(); + const groupId = (connection.config?.access_grants || [])[0]?.principal_id; + expect(groupId, `${server} must name the group its access grant points at`).toBeTruthy(); + return groupId; +} + +/** + * Take one member out of the Open WebUI group an MCP server grants read to. + * + * Args: + * page: a page holding an administrator session. + * shared: the role's shared spec helpers. + * groupId: the Open WebUI group carrying the server's access grant. + * memberId: the Open WebUI user id to remove. + * + * Withdrawing the LDAP membership does not reach Open WebUI on its own: its + * OIDC sync drops a stale group only while the user's groups claim is + * non-empty, and a user whose only grant was just withdrawn arrives with an + * empty one. This write is what makes the revocation visible. + */ +async function dropGroupMember(page, shared, groupId, memberId) { + const base = shared.env.openwebuiBaseUrl.replace(/\/+$/, ""); + const headers = await sessionHeaders(page); + + const listed = await page.request.post(`${base}/api/v1/groups/id/${groupId}/users`, { headers }); + expect( + listed.ok(), + `the administrator must list the members of ${groupId} (HTTP ${listed.status()})` + ).toBeTruthy(); + if (!(await listed.json()).some((member) => member?.id === memberId)) { + return; + } + + const removed = await page.request.post(`${base}/api/v1/groups/id/${groupId}/users/remove`, { + headers, + data: { user_ids: [memberId] }, + }); + expect( + removed.ok(), + `the administrator must remove the revoked member from ${groupId} (HTTP ${removed.status()})` + ).toBeTruthy(); +} + +async function discardSession(page, shared) { + const base = shared.env.openwebuiBaseUrl.replace(/\/+$/, ""); + if (page.url().startsWith(base)) { + await page.evaluate(() => window.localStorage.clear()); + } + await page.context().clearCookies(); +} + +async function pollBiberTools(page, shared, server, expectServed, resetOnMiss) { + const deadline = Date.now() + CLAIM_PROPAGATION_MS; + for (;;) { + await discardSession(page, shared); + await shared.signInViaDashboardOidc( + page, + shared.env.biberUsername, + shared.env.biberPassword, + "biber" + ); + const userId = await sessionUserId(page, shared); + const served = await servedToolIds(page, shared); + if (served.includes(server) === expectServed || Date.now() >= deadline) { + return { served, userId }; + } + if (resetOnMiss) { + await resetOnMiss(userId); + } + } +} + +exports.register = function (shared) { + test("biber gains MCP access only once the administrator grants it in LAM", async ({ + page, + }) => { + skipUnlessServiceEnabled("mcp"); + skipUnlessServiceEnabled("sso"); + test.skip( + !shared.env.lamBaseUrl, + "LAM_BASE_URL is empty; web-app-lam is not in this deployment's inventory" + ); + test.setTimeout(resolveTimeout(600_000)); + + const server = firstExpectedServer(shared); + const groupCn = `${server}-mcp`; + const memberDn = `uid=${shared.env.biberUsername},${shared.env.ldapUserDnBase}`; + + const browser = page.context().browser(); + const lamPage = await (await browser.newContext(PERSONA_CONTEXT)).newPage(); + const adminPage = await (await browser.newContext(PERSONA_CONTEXT)).newPage(); + + await signInToLam(lamPage, shared); + await shared.signInViaDashboardOidc( + adminPage, + shared.env.adminUsername, + shared.env.adminPassword, + "administrator" + ); + const groupId = await grantedGroupId(adminPage, shared, server); + + await revokeMemberInLam(lamPage, shared, groupCn, memberDn); + + let biberId = null; + try { + const denied = await pollBiberTools(page, shared, server, false, async (userId) => { + biberId = userId; + await dropGroupMember(adminPage, shared, groupId, userId); + }); + biberId = denied.userId; + expect( + denied.served, + `${server} is granted to ${groupCn}, which biber is not in yet, so its tools must not be served` + ).not.toContain(server); + + await shared.expectSignInRequiredAfterLogout(page); + + await grantMemberInLam(lamPage, shared, groupCn, memberDn); + + const allowed = await pollBiberTools(page, shared, server, true, null); + expect( + allowed.served, + `biber now holds ${groupCn}; absence here means the groups claim, the OIDC group mapping or the access grant is wrong` + ).toContain(server); + } finally { + await revokeMemberInLam(lamPage, shared, groupCn, memberDn); + if (biberId) { + await dropGroupMember(adminPage, shared, groupId, biberId); + } + } + }); +}; diff --git a/roles/web-app-openwebui/files/playwright/test-mcp-non-member.js b/roles/web-app-openwebui/files/playwright/test-mcp-non-member.js new file mode 100644 index 0000000000..ab2b2c2d9d --- /dev/null +++ b/roles/web-app-openwebui/files/playwright/test-mcp-non-member.js @@ -0,0 +1,48 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); +const { skipUnlessServiceEnabled } = require("./service-gating"); + +exports.register = function (shared) { + test("biber: a user outside the mcp group reaches no MCP tool", async ({ page }) => { + skipUnlessServiceEnabled("mcp"); + skipUnlessServiceEnabled("sso"); + test.setTimeout(resolveTimeout(120_000)); + + await shared.signInViaDashboardOidc( + page, + shared.env.biberUsername, + shared.env.biberPassword, + "biber" + ); + + const token = await page.evaluate(() => window.localStorage.getItem("token")); + expect(token, "OpenWebUI must store a session token for biber").toBeTruthy(); + + const base = shared.env.openwebuiBaseUrl.replace(/\/+$/, ""); + const config = await page.request.get(`${base}/api/v1/configs/tool_servers`, { + headers: { Authorization: `Bearer ${token}` }, + failOnStatusCode: false, + }); + expect( + config.status(), + "the tool-server configuration is an administrator surface and must refuse a plain user" + ).toBeGreaterThanOrEqual(400); + + const response = await page.request.get(`${base}/api/v1/tools/`, { + headers: { Authorization: `Bearer ${token}` }, + }); + expect(response.ok(), `the tool list must answer biber (HTTP ${response.status()})`).toBeTruthy(); + + const expected = (shared.env.mcpExpectedServers || "") + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + const visible = JSON.stringify(await response.json()); + for (const id of expected) { + expect( + visible, + `${id} is granted to its mcp group, which biber is not in, so its tools must not be listed` + ).not.toContain(id); + } + }); +}; diff --git a/roles/web-app-openwebui/files/playwright/test-mcp-servers.js b/roles/web-app-openwebui/files/playwright/test-mcp-servers.js new file mode 100644 index 0000000000..1415639eb5 --- /dev/null +++ b/roles/web-app-openwebui/files/playwright/test-mcp-servers.js @@ -0,0 +1,100 @@ +const { test, expect } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); +const { skipUnlessServiceEnabled } = require("./service-gating"); + +exports.register = function (shared) { + test("administrator: every discovered MCP server is registered as a tool server", async ({ page }) => { + skipUnlessServiceEnabled("mcp"); + skipUnlessServiceEnabled("sso"); + test.setTimeout(resolveTimeout(120_000)); + + await shared.signInViaDashboardOidc( + page, + shared.env.adminUsername, + shared.env.adminPassword, + "administrator" + ); + + const token = await page.evaluate(() => window.localStorage.getItem("token")); + expect( + token, + "OpenWebUI must store a session token in localStorage after login" + ).toBeTruthy(); + + const base = shared.env.openwebuiBaseUrl.replace(/\/+$/, ""); + const response = await page.request.get(`${base}/api/v1/configs/tool_servers`, { + headers: { Authorization: `Bearer ${token}` }, + }); + expect( + response.ok(), + `the admin tool-server config must answer the authenticated session (HTTP ${response.status()})` + ).toBeTruthy(); + + const body = await response.json(); + const connections = Array.isArray(body?.TOOL_SERVER_CONNECTIONS) + ? body.TOOL_SERVER_CONNECTIONS + : []; + const mcpConnections = connections.filter((c) => c?.type === "mcp"); + + const expected = (shared.env.mcpExpectedServers || "") + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + expect( + expected.length, + "the deploy must have discovered at least one MCP server when the mcp service is enabled" + ).toBeGreaterThan(0); + + const registered = mcpConnections.map((c) => String(c?.info?.id ?? "")); + for (const id of expected) { + expect( + registered, + `the administrator must see ${id} in the configured MCP tool servers (got ${JSON.stringify(registered)})` + ).toContain(id); + } + + for (const connection of mcpConnections) { + expect( + connection.auth_type, + `${connection?.info?.id} must authenticate with a bearer token` + ).toBe("bearer"); + expect( + String(connection.key || "").length, + `${connection?.info?.id} must carry a non-empty bearer, an empty one is rejected by the server` + ).toBeGreaterThan(0); + const grants = connection?.config?.access_grants ?? []; + expect( + grants, + `${connection?.info?.id} must be scoped to its role's mcp group; an empty grant list falls back to administrator-only` + ).toHaveLength(1); + expect( + grants[0], + `${connection?.info?.id} must grant read to a group, not to a user or to everyone` + ).toMatchObject({ principal_type: "group", permission: "read" }); + expect( + String(grants[0]?.principal_id || ""), + `${connection?.info?.id} must name a resolved OpenWebUI group id` + ).not.toHaveLength(0); + expect( + connection?.config?.enable, + `${connection?.info?.id} must be enabled; the deploy enables a server only together with its grant` + ).toBeTruthy(); + } + + const tools = await page.request.get(`${base}/api/v1/tools/`, { + headers: { Authorization: `Bearer ${token}` }, + }); + expect( + tools.ok(), + `the tool list must answer the administrator (HTTP ${tools.status()})` + ).toBeTruthy(); + + const served = JSON.stringify(await tools.json()); + for (const id of expected) { + expect( + served, + `mcp is granted per application, so the administrator role alone must not serve ${id}; BYPASS_ADMIN_ACCESS_CONTROL=false is what keeps an administrator out of a grant they do not hold` + ).not.toContain(id); + } + }); +}; diff --git a/roles/web-app-openwebui/files/playwright/test-seaweedfs.js b/roles/web-app-openwebui/files/playwright/test-seaweedfs.js index 8bfbf981b6..d1fef03b4d 100644 --- a/roles/web-app-openwebui/files/playwright/test-seaweedfs.js +++ b/roles/web-app-openwebui/files/playwright/test-seaweedfs.js @@ -24,6 +24,7 @@ test.use({ ignoreHTTPSErrors: true }); test("seaweedfs: an uploaded Open WebUI document is stored in the SeaweedFS bucket", async ({ page, browser }) => { test.skip(isOnionTarget(), "SeaweedFS filer UI is not a Tor surface on an onion node (headless backend)"); skipUnlessServiceEnabled("seaweedfs"); + skipUnlessServiceEnabled("sso"); test.setTimeout(resolveTimeout(180_000)); await runSeaweedfsStorageCheck(page, browser, { diff --git a/roles/web-app-openwebui/files/python/provision_mcp_grants.py b/roles/web-app-openwebui/files/python/provision_mcp_grants.py new file mode 100644 index 0000000000..885db9993e --- /dev/null +++ b/roles/web-app-openwebui/files/python/provision_mcp_grants.py @@ -0,0 +1,249 @@ +import asyncio +import json +import os +import secrets +import sys +import urllib.error +import urllib.request +from copy import deepcopy + +sys.path.insert(0, "/app/backend") + +BASE = os.environ.get("OPENWEBUI_BASE", "").rstrip("/") +GROUPS = json.loads(os.environ.get("OPENWEBUI_MCP_GROUPS", "{}")) +MEMBERS = json.loads(os.environ.get("OPENWEBUI_MCP_MEMBERS", "{}")) + +DECLARED = json.loads(os.environ.get("OPENWEBUI_MCP_CONNECTIONS", "[]")) +ADMIN_EMAIL = os.environ.get("OPENWEBUI_ADMIN_EMAIL", "") +ADMIN_NAME = os.environ.get("OPENWEBUI_ADMIN_NAME", "administrator") +ADMIN_PASSWORD = os.environ.get("OPENWEBUI_ADMIN_PASSWORD", "") + + +async def resolve_api_key(): + """Return an administrator API key and whether this run minted it. + + Signup cannot be used: Open WebUI only promotes a signup to admin while it + is the very first user, and disables signup afterwards. So the key is taken + from an existing administrator, and only a deployment with no users at all + creates one. A key minted here is removed again once the run is done, so the + deploy leaves no standing admin credential behind. + """ + from open_webui.models.auths import Auths + from open_webui.models.users import Users + from open_webui.utils.auth import get_password_hash + + existing = (await Users.get_users()).get("users") or [] + admin = next((user for user in existing if user.role == "admin"), None) + if admin is None: + admin = await Auths.insert_new_auth( + email=ADMIN_EMAIL.lower(), + password=await get_password_hash(ADMIN_PASSWORD), + name=ADMIN_NAME, + role="admin", + ) + if admin is None: + sys.exit("FAILED: no administrator exists and one could not be created") + + key = await Users.get_user_api_key_by_id(admin.id) + if key: + return admin.id, key, False + + key = f"sk-{secrets.token_hex(32)}" + if not await Users.update_user_api_key_by_id(admin.id, key): + sys.exit(f"FAILED: could not mint an API key for {admin.id}") + return admin.id, key, True + + +async def drop_api_key(user_id): + from open_webui.models.users import Users + + await Users.delete_user_api_key_by_id(user_id) + + +def call(path, key, payload=None): + data = json.dumps(payload).encode() if payload is not None else None + request = urllib.request.Request( # noqa: S310 - fixed http:// base from OPENWEBUI_BASE, no user-supplied scheme + f"{BASE}{path}", + data=data, + method="POST" if data else "GET", + ) + request.add_header("Content-Type", "application/json") + request.add_header("Authorization", f"Bearer {key}") + try: + with urllib.request.urlopen(request, timeout=30) as response: # noqa: S310 - fixed http:// base from OPENWEBUI_BASE, no user-supplied scheme + return response.status, json.loads(response.read() or b"null") + except urllib.error.HTTPError as error: + return error.code, error.read().decode(errors="replace") + + +def group_id(key, name): + status, body = call("/api/v1/groups/", key) + if status != 200: + sys.exit(f"FAILED listing groups: {status} {body}") + + matches = [group for group in body if group.get("name") == name] + if len(matches) > 1: + sys.exit(f"FAILED: {len(matches)} groups named {name}, refusing to guess") + if matches: + return matches[0]["id"], matches[0] + + status, body = call( + "/api/v1/groups/create", + key, + {"name": name, "description": "MCP tool server access"}, + ) + if status != 200: + sys.exit(f"FAILED creating group {name}: {status} {body}") + return body["id"], body + + +async def user_ids_for(members): + """Return the Open WebUI ids of the users named in ``members``. + + Args: + members: ``[{"username": ..., "email": ...}, ...]`` as granted by the + declarative configuration. + + A member Open WebUI has never seen has no id yet, so it is skipped: the + OIDC login that creates the account also carries the groups claim. + """ + if not members: + return [] + + from open_webui.models.users import Users + + existing = (await Users.get_users()).get("users") or [] + by_email = {str(u.email or "").lower(): u.id for u in existing} + by_name = {str(u.name or "").lower(): u.id for u in existing} + + ids = [] + for member in members: + email = str(member.get("email") or "").lower() + name = str(member.get("username") or "").lower() + found = by_email.get(email) or by_name.get(name) + if found and found not in ids: + ids.append(found) + return ids + + +def reconcile_members(key, group, member_ids): + """Set a group's members to exactly ``member_ids``. + + Args: + key: the administrator API key. + group: the group as the API returned it. + member_ids: the Open WebUI user ids that should remain. + + The OIDC groups claim cannot do this on its own: Open WebUI drops a stale + membership only while the claim is non-empty, so a user who loses their + last group keeps the old one until some later login carries another. An + explicit write is what makes removing the last grant revoke access. + """ + if sorted(group.get("user_ids") or []) == sorted(member_ids): + return False + status, body = call( + f"/api/v1/groups/id/{group['id']}/update", + key, + { + "name": group.get("name"), + "description": group.get("description") or "MCP tool server access", + "permissions": group.get("permissions"), + "user_ids": member_ids, + }, + ) + if status != 200: + sys.exit(f"FAILED updating group {group.get('name')}: {status} {body}") + return True + + +def grant(key): + status, body = call("/api/v1/configs/tool_servers", key) + if status != 200: + sys.exit(f"FAILED reading tool servers: {status} {body}") + + connections = body.get("TOOL_SERVER_CONNECTIONS") or [] + original = deepcopy(connections) + declared = {(entry.get("info") or {}).get("id"): entry for entry in DECLARED} + known = { + (connection.get("info") or {}).get("id") + for connection in connections + if connection.get("type") == "mcp" + } + connections += [ + deepcopy(entry) + for server_id, entry in declared.items() + if server_id not in known + ] + wanted = {} + members_changed = False + for connection in connections: + server_id = (connection.get("info") or {}).get("id") + name = GROUPS.get(server_id) + if connection.get("type") != "mcp" or not name: + continue + source = declared.get(server_id) or {} + for field in ("url", "path", "key", "auth_type"): + if field in source: + connection[field] = source[field] + wanted[server_id], group = group_id(key, name) + member_ids = asyncio.run(user_ids_for(MEMBERS.get(server_id) or [])) + members_changed |= reconcile_members(key, group, member_ids) + config = connection.setdefault("config", {}) + config["access_grants"] = [ + { + "principal_type": "group", + "principal_id": wanted[server_id], + "permission": "read", + } + ] + config["enable"] = True + + if connections == original: + return wanted, members_changed + + status, body = call( + "/api/v1/configs/tool_servers", key, {"TOOL_SERVER_CONNECTIONS": connections} + ) + if status != 200: + sys.exit(f"FAILED writing tool servers: {status} {body}") + + status, body = call("/api/v1/configs/tool_servers", key) + if status != 200: + sys.exit(f"FAILED re-reading tool servers: {status} {body}") + + written = body.get("TOOL_SERVER_CONNECTIONS") or [] + missing = {(entry.get("info") or {}).get("id") for entry in connections} - { + (entry.get("info") or {}).get("id") for entry in written + } + if missing: + sys.exit(f"FAILED: the write lost {sorted(missing)}") + + for connection in written: + server_id = (connection.get("info") or {}).get("id") + if server_id not in wanted: + continue + config = connection.get("config") or {} + grants = config.get("access_grants") or [] + ids = [ + g.get("principal_id") for g in grants if g.get("principal_type") == "group" + ] + if ids != [wanted[server_id]]: + sys.exit(f"FAILED: {server_id} carries {grants} instead of one group grant") + if not config.get("enable"): + sys.exit(f"FAILED: {server_id} stayed disabled after the grant was written") + + return wanted, True + + +if __name__ == "__main__": + admin_id, api_key, minted = asyncio.run(resolve_api_key()) + try: + resolved, changed = grant(api_key) + finally: + if minted: + asyncio.run(drop_api_key(admin_id)) + if GROUPS and not resolved: + sys.exit(f"FAILED: none of the {len(GROUPS)} declared MCP servers was granted") + + print(f"{'CHANGED' if changed else 'OK'} granted={len(resolved)}") + print(json.dumps(resolved)) diff --git a/roles/web-app-openwebui/meta/info.yml b/roles/web-app-openwebui/meta/info.yml index e4b2ecaefc..e15be6848f 100644 --- a/roles/web-app-openwebui/meta/info.yml +++ b/roles/web-app-openwebui/meta/info.yml @@ -1,4 +1,5 @@ --- +# nocheck: info-media no official demo video logo: class: fa-solid fa-comments homepage: https://openwebui.com/ diff --git a/roles/web-app-openwebui/meta/main.yml b/roles/web-app-openwebui/meta/main.yml index cf3dd9d2cc..bf42b9cad2 100644 --- a/roles/web-app-openwebui/meta/main.yml +++ b/roles/web-app-openwebui/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Self-hosted chat interface for interacting with local and private AI models via backends such as Ollama diff --git a/roles/web-app-openwebui/meta/mcp.yml b/roles/web-app-openwebui/meta/mcp.yml new file mode 100644 index 0000000000..6efa058bdc --- /dev/null +++ b/roles/web-app-openwebui/meta/mcp.yml @@ -0,0 +1,14 @@ +--- +classification: native_client +direction: client +source_url: https://docs.openwebui.com/features/extensibility/mcp/ +implementation: native +supported_transports: + - streamable_http +supported_auths: + - bearer_token + - app_password + - upstream_session +tools: + read_only_default: true + mutating_tools_enabled: false diff --git a/roles/web-app-openwebui/meta/secrets.yml b/roles/web-app-openwebui/meta/secrets.yml new file mode 100644 index 0000000000..9de984053a --- /dev/null +++ b/roles/web-app-openwebui/meta/secrets.yml @@ -0,0 +1,13 @@ +--- +credentials: + webui_secret_key: + description: "Signing key Open WebUI requires whenever authentication is enabled. Pinned by the deployment so a container exec sees the same value as the server, + which auto-generates it into the process environment only." + algorithm: alphanumeric + validation: "^[A-Za-z0-9]{32,}$" + length: 64 + litellm_api_key: + description: Per-consumer virtual key for the shared svc-ai-litellm gateway + algorithm: sk_prefixed + validation: + min_length: 50 diff --git a/roles/web-app-openwebui/meta/services.yml b/roles/web-app-openwebui/meta/services.yml index 8196783161..8a1fb88846 100644 --- a/roles/web-app-openwebui/meta/services.yml +++ b/roles/web-app-openwebui/meta/services.yml @@ -22,6 +22,7 @@ matomo: shared: "{{ 'web-app-matomo' in group_names }}" # nocheck: playwright-service-flag: shared provider entity; the app itself is covered by this role's own Playwright spec openwebui: + mcp_consumer: true modes: compose: enabled: true @@ -35,7 +36,7 @@ openwebui: backup: no_stop_required: true image: ghcr.io/open-webui/open-webui - version: main + version: 0.11.0 name: open-webui min_storage: 2026MB offline_mode: false @@ -80,11 +81,12 @@ css: javascript: enabled: false # nocheck: dynamic-flag shared: true -# nocheck: playwright-service-flag โ€” AI backend, infrastructural -ollama: +# nocheck: playwright-service-flag, dynamic-flag โ€” AI backend, infrastructural, and a single shared instance +litellm: bond: 1 - enabled: "{{ 'svc-ai-ollama' in group_names }}" - shared: "{{ 'svc-ai-ollama' in group_names }}" + enabled: "{{ LITELLM_USABLE }}" + shared: true + email: bond: 1 enabled: "{{ MAIL_PROVIDER in group_names }}" diff --git a/roles/web-app-openwebui/meta/users.yml b/roles/web-app-openwebui/meta/users.yml new file mode 100644 index 0000000000..4630322e8d --- /dev/null +++ b/roles/web-app-openwebui/meta/users.yml @@ -0,0 +1,8 @@ +--- +administrator: {} +openwebui-api-bot: + username: openwebui-api-bot + firstname: Infinito + lastname: API Bot + accounts: [] + description: API-only administrator used to provision MCP tool-server access grants (NOT an OIDC user) diff --git a/roles/web-app-openwebui/meta/variants.yml b/roles/web-app-openwebui/meta/variants.yml index fb33850486..13acca7e3c 100644 --- a/roles/web-app-openwebui/meta/variants.yml +++ b/roles/web-app-openwebui/meta/variants.yml @@ -25,9 +25,8 @@ sso: enabled: true shared: true - ollama: + litellm: enabled: true - shared: true prometheus: enabled: true shared: true @@ -59,11 +58,10 @@ enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true sso: + enabled: true + shared: true + litellm: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true - ollama: - enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true prometheus: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -100,9 +98,8 @@ matomo: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true - ollama: + litellm: enabled: false - shared: false # nocheck: variants-static-override backup shared stays literally true prometheus: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true diff --git a/roles/web-app-openwebui/tasks/00_core.yml b/roles/web-app-openwebui/tasks/00_core.yml index be0509b805..f97313fe8c 100644 --- a/roles/web-app-openwebui/tasks/00_core.yml +++ b/roles/web-app-openwebui/tasks/00_core.yml @@ -1,8 +1,19 @@ --- - include_tasks: utils/once/flag.yml +- name: "๐Ÿ” Verify the gateway contract for {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-litellm/tasks/utils/consumer_contract.yml') }}" + when: OPENWEBUI_LITELLM_ENABLED | bool + - name: "๐Ÿงฉ load docker, proxy for '{{ application_id }}'" include_role: name: sys-stk-full vars: compose_repository_pull: false + +- name: "๐Ÿšฟ Flush compose handlers for {{ application_id }}" + ansible.builtin.meta: flush_handlers + +- name: "๐Ÿ”Œ Provision MCP tool-server access grants" + ansible.builtin.include_tasks: utils/mcp.yml + when: OPENWEBUI_MCP_SERVERS | length > 0 diff --git a/roles/web-app-openwebui/tasks/utils/mcp.yml b/roles/web-app-openwebui/tasks/utils/mcp.yml new file mode 100644 index 0000000000..b865c2e49e --- /dev/null +++ b/roles/web-app-openwebui/tasks/utils/mcp.yml @@ -0,0 +1,20 @@ +--- +- name: "๐Ÿ” Resolve {{ application_id }} hosting node + container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ entity_name }}" + resolve_output_prefix: OPENWEBUI + resolve_compose_cid: "{{ OPENWEBUI_CONTAINER }}" + +- name: "๐Ÿ”ง Map every discovered MCP server to its role's mcp group" + ansible.builtin.set_fact: + openwebui_mcp_groups: >- + {{ openwebui_mcp_groups | default({}) + | combine({item.id: '/' ~ lookup('rbac_group_path', application_id=item.id, role='mcp')}) }} + loop: "{{ OPENWEBUI_MCP_SERVERS }}" + loop_control: + label: "{{ item.id }}" + +- name: "๐Ÿ”Œ Grant and persist the MCP tool servers this run discovered" + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/mcp_grants.yml" + when: OPENWEBUI_MCP_SERVERS | length > 0 diff --git a/roles/web-app-openwebui/tasks/utils/mcp_grants.yml b/roles/web-app-openwebui/tasks/utils/mcp_grants.yml new file mode 100644 index 0000000000..4f1b389c25 --- /dev/null +++ b/roles/web-app-openwebui/tasks/utils/mcp_grants.yml @@ -0,0 +1,59 @@ +--- +- name: "๐Ÿ”‘ Grant the mcp group read access to every MCP tool server" + ansible.builtin.command: + argv: + - container + - exec + - -i + - -e + - "OPENWEBUI_BASE=http://localhost:{{ OPENWEBUI_INTERNAL_HTTP_PORT }}" + - -e + - "OPENWEBUI_ADMIN_EMAIL={{ OPENWEBUI_API_BOT_USER.email }}" + - -e + - "OPENWEBUI_ADMIN_NAME={{ OPENWEBUI_API_BOT_USER.username }}" + - -e + - "OPENWEBUI_ADMIN_PASSWORD={{ OPENWEBUI_API_BOT_USER.password }}" + - -e + - "OPENWEBUI_MCP_GROUPS={{ openwebui_mcp_groups | to_json }}" + - -e + - "OPENWEBUI_MCP_MEMBERS={{ OPENWEBUI_MCP_MEMBERS | to_json }}" + - -e + - "OPENWEBUI_MCP_CONNECTIONS={{ OPENWEBUI_MCP_SERVERS | mcp_tool_server_connections(OPENWEBUI_MCP_GROUP_IDS) | to_json }}" + - "{{ OPENWEBUI_LOCAL_CID }}" # nocheck: container-exec-resolver + - python3 + - "-" + stdin: "{{ lookup('file', 'python/provision_mcp_grants.py') }}" + register: openwebui_mcp_grants + retries: 30 + delay: 10 + until: openwebui_mcp_grants.rc == 0 + changed_when: openwebui_mcp_grants.stdout.startswith('CHANGED') + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ OPENWEBUI_HOST_NODE }}" + run_once: true + +- name: "๐Ÿ’พ Persist each resolved group id so a bare restart keeps the grant" + ansible.builtin.include_role: + name: sys-token-store + tasks_from: write.yml + vars: + sys_token_store_user_key: "{{ OPENWEBUI_MCP_GROUP_OWNER }}" + sys_token_store_app: "{{ item.key }}" + sys_token_store_token: "{{ item.value }}" + loop: "{{ (openwebui_mcp_grants.stdout_lines | last | from_json) | dict2items }}" + loop_control: + label: "{{ item.key }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "โ™ป๏ธ Re-render the env now that the group ids are known" + stack_host_template: + src: "{{ role_path }}/templates/env.j2" + dest: "{{ lookup('container', application_id, 'files.env') }}" + mode: "0640" + force: true + notify: compose-up + vars: + OPENWEBUI_MCP_GROUP_IDS: "{{ openwebui_mcp_grants.stdout_lines | last | from_json }}" + +- name: "๐Ÿšฟ Restart Open WebUI so it reads the grants it was just given" + ansible.builtin.meta: flush_handlers diff --git a/roles/web-app-openwebui/templates/env.j2 b/roles/web-app-openwebui/templates/env.j2 index 1a0cef7d02..7a0b8635a5 100644 --- a/roles/web-app-openwebui/templates/env.j2 +++ b/roles/web-app-openwebui/templates/env.j2 @@ -1,6 +1,14 @@ {% include 'roles/sys-svc-container/templates/env.j2' %} -OLLAMA_BASE_URL={{ OLLAMA_BASE_LOCAL_URL }} +WEBUI_SECRET_KEY={{ OPENWEBUI_SECRET_KEY | dotenv_quote }} + +{% if OPENWEBUI_LITELLM_ENABLED | bool %} +OPENAI_API_BASE_URL={{ LITELLM_BASE_LOCAL_URL }}/v1 +OPENAI_API_KEY={{ OPENWEBUI_LITELLM_API_KEY | dotenv_quote }} +{% endif %} +{% if OPENWEBUI_MCP_SERVERS | length > 0 %} +TOOL_SERVER_CONNECTIONS={{ OPENWEBUI_MCP_SERVERS | mcp_tool_server_connections(OPENWEBUI_MCP_GROUP_IDS) | to_json(separators=(',', ':')) | dotenv_quote }} +{% endif %} OFFLINE_MODE={{ OPENWEBUI_OFFLINE_MODE | ternary(1, 0) }} HF_HUB_OFFLINE={{ OPENWEBUI_HF_HUB_OFFLINE | ternary(1, 0) }} ENABLE_PERSISTENT_CONFIG=false @@ -48,8 +56,16 @@ OAUTH_SCOPES=openid email profile {{ RBAC.GROUP.CLAIM }} ENABLE_OAUTH_ROLE_MANAGEMENT=true OAUTH_ROLES_CLAIM={{ RBAC.GROUP.CLAIM }} OAUTH_ADMIN_ROLES=/{{ OPENWEBUI_OIDC_ADMIN_GROUP }} +OAUTH_ALLOWED_ROLES=* + +ENABLE_OAUTH_GROUP_MANAGEMENT=true +ENABLE_OAUTH_GROUP_CREATION=true +OAUTH_GROUPS_CLAIM={{ RBAC.GROUP.CLAIM }} +BYPASS_ADMIN_ACCESS_CONTROL=false {% endif %} +BYPASS_MODEL_ACCESS_CONTROL=true + {% if OPENWEBUI_LDAP_ENABLED | bool %} ENABLE_LDAP=true diff --git a/roles/web-app-openwebui/templates/playwright.env.j2 b/roles/web-app-openwebui/templates/playwright.env.j2 index cac06ed409..d72e8209da 100644 --- a/roles/web-app-openwebui/templates/playwright.env.j2 +++ b/roles/web-app-openwebui/templates/playwright.env.j2 @@ -15,9 +15,21 @@ CANONICAL_DOMAIN={{ lookup('domain', application_id) | dotenv_quote }} # nocheck: playwright-service-gate โ€” covered by sys-svc-mail integration tests, not the persona surface EMAIL_SERVICE_ENABLED={{ lookup('config', application_id, 'services.email.enabled') | string | lower }} +LAM_BASE_URL={{ (lookup('tls', 'web-app-lam', 'url.base') if 'web-app-lam' in group_names else '') | dotenv_quote }} + +LDAP_BIND_DN={{ (LDAP.DN.ADMINISTRATOR.DATA if 'web-app-lam' in group_names else '') | dotenv_quote }} + +LDAP_BIND_PASSWORD={{ (LDAP.BIND_CREDENTIAL if 'web-app-lam' in group_names else '') | dotenv_quote }} + +LDAP_ROLE_DN_BASE={{ (LDAP.DN.OU.ROLES if 'web-app-lam' in group_names else '') | dotenv_quote }} + # nocheck: playwright-service-gate โ€” persona drives the OIDC path; LDAP federation is exercised in the LDAP-only matrix variant LDAP_SERVICE_ENABLED={{ lookup('config', application_id, 'services.ldap.enabled') | string | lower }} +LDAP_USER_DN_BASE={{ (LDAP.DN.OU.USERS if 'web-app-lam' in group_names else '') | dotenv_quote }} + +LITELLM_SERVICE_ENABLED={{ lookup('config', application_id, 'services.litellm.enabled') | string | lower }} + # nocheck: playwright-service-gate โ€” consumed via shared persona helpers (roles/test-e2e-playwright/files/personas/) LOGOUT_SERVICE_ENABLED={{ lookup('config', application_id, 'services.logout.enabled') | string | lower }} @@ -26,9 +38,17 @@ MATOMO_BASE_URL={{ lookup('tls', 'web-app-matomo', 'url.base') | dotenv_quote }} # nocheck: playwright-service-gate โ€” consumed via shared persona helpers (roles/test-e2e-playwright/files/personas/) MATOMO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.matomo.enabled') | string | lower }} -OIDC_ISSUER_URL={{ OIDC.CLIENT.ISSUER_URL | dotenv_quote }} +MCP_EXPECTED_SERVERS={{ (OPENWEBUI_MCP_SERVERS | mcp_tool_server_connections | map(attribute='info.id') | list | join(',')) | dotenv_quote }} -OLLAMA_SERVICE_ENABLED={{ lookup('config', application_id, 'services.ollama.enabled') | string | lower }} +{% set _read_probes = {} %} +{% for _server in OPENWEBUI_MCP_SERVERS | mcp_tool_server_connections %} +{% set _ = _read_probes.update({_server.info.id: lookup('config', _server.info.id, 'mcp.tools.read_probe.tool', '')}) %} +{% endfor %} +MCP_EXPECTED_TOOLS={{ _read_probes | to_json | dotenv_quote }} + +MCP_SERVICE_ENABLED={{ lookup('config', application_id, 'mcp.enabled') | string | lower }} + +OIDC_ISSUER_URL={{ OIDC.CLIENT.ISSUER_URL | dotenv_quote }} OPENWEBUI_BASE_URL={{ lookup('tls', application_id, 'url.base') | dotenv_quote }} diff --git a/roles/web-app-openwebui/vars/main.yml b/roles/web-app-openwebui/vars/main.yml index 1231cab277..d6bcdcd866 100644 --- a/roles/web-app-openwebui/vars/main.yml +++ b/roles/web-app-openwebui/vars/main.yml @@ -1,5 +1,6 @@ --- application_id: "web-app-openwebui" +entity_name: "{{ application_id | get_entity_name }}" OPENWEBUI_URL: "{{ lookup('tls', application_id, 'url.base') }}" OPENWEBUI_CONTAINER: "{{ lookup('config', application_id, 'services.openwebui.name') }}" @@ -7,6 +8,15 @@ OPENWEBUI_OFFLINE_MODE: "{{ lookup('config', application_id, 'services.openwebui OPENWEBUI_HF_HUB_OFFLINE: "{{ lookup('config', application_id, 'services.openwebui.hf_hub_offline') }}" OPENWEBUI_ENABLE_API_KEYS: "{{ lookup('config', application_id, 'services.openwebui.enable_api_keys') }}" OPENWEBUI_LDAP_ENABLED: "{{ lookup('config', application_id, 'services.ldap.enabled') }}" +OPENWEBUI_LITELLM_ENABLED: "{{ lookup('config', application_id, 'services.litellm.enabled') }}" +OPENWEBUI_LITELLM_API_KEY: "{{ lookup('config', application_id, 'secrets.credentials.litellm_api_key') }}" +OPENWEBUI_SECRET_KEY: "{{ lookup('config', application_id, 'secrets.credentials.webui_secret_key') }}" +OPENWEBUI_MCP_SERVERS: "{{ MCP_DISCOVERED_SERVERS if (lookup('config', application_id, 'mcp.enabled') | bool) else [] }}" +OPENWEBUI_MCP_GROUP_OWNER: "openwebui-mcp-groups" +OPENWEBUI_MCP_GROUP_IDS: "{{ (lookup('users', OPENWEBUI_MCP_GROUP_OWNER, {}) | default({}, true)).get('tokens', {}) }}" +OPENWEBUI_MCP_MEMBERS: "{{ lookup('users') | mcp_group_members(OPENWEBUI_MCP_SERVERS, 'mcp-reader') }}" +OPENWEBUI_INTERNAL_HTTP_PORT: "{{ lookup('config', application_id, 'services.openwebui.ports.internal.http') }}" +OPENWEBUI_API_BOT_USER: "{{ lookup('users', 'openwebui-api-bot') }}" OPENWEBUI_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') }}" OPENWEBUI_OIDC_REDIRECT_URL: "{{ [OPENWEBUI_URL,'/oauth/oidc/callback'] | url_join }}" diff --git a/roles/web-app-peertube/README.md b/roles/web-app-peertube/README.md index ba48dade08..202f65bf00 100644 --- a/roles/web-app-peertube/README.md +++ b/roles/web-app-peertube/README.md @@ -99,19 +99,20 @@ Run the published image to provision the inventory and deploy PeerTube to a mana ```bash APP=web-app-peertube HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-peertube/meta/services.yml b/roles/web-app-peertube/meta/services.yml index bd28b81470..0d3490d643 100644 --- a/roles/web-app-peertube/meta/services.yml +++ b/roles/web-app-peertube/meta/services.yml @@ -79,6 +79,9 @@ peertube: http: 8011 public: rtmp: 1935 + onion: + # nocheck: onion-flag RTMP is an ingest the broadcaster pushes in, and the encoders that push it speak no SOCKS + rtmp: false internal: http: 9000 rtmp: 1935 @@ -99,7 +102,6 @@ prometheus: # nocheck: dynamic-flag # nocheck: playwright-service-flag โ€” the role never joins the onion topology, so no persona surface can assert it tor: - bond: 0.5 enabled: false shared: false # nocheck: dynamic-flag # nocheck: playwright-service-flag, dynamic-flag infrastructure backup consumer diff --git a/roles/web-app-peertube/tasks/00_core.yml b/roles/web-app-peertube/tasks/00_core.yml index 596c18e492..e4aa750ef9 100644 --- a/roles/web-app-peertube/tasks/00_core.yml +++ b/roles/web-app-peertube/tasks/00_core.yml @@ -6,7 +6,7 @@ name: sys-stk-front-proxy loop: "{{ lookup('domains', application_id) }}" loop_control: - loop_var: domain + loop_var: domain # nocheck: loop-var-shadow sys-stk-front-proxy takes the vhost through this name, see its tasks/main.yml front_proxy_domain vars: http_port: "{{ lookup('config', application_id, 'services.peertube.ports.local.http') }}" websocket_port: "{{ lookup('config', application_id, 'services.peertube.ports.local.http') }}" diff --git a/roles/web-app-penpot/README.md b/roles/web-app-penpot/README.md index bfdbc38433..6f3fbf8ac4 100644 --- a/roles/web-app-penpot/README.md +++ b/roles/web-app-penpot/README.md @@ -115,19 +115,20 @@ Run the published image to provision the inventory and deploy Penpot to a manage ```bash APP=web-app-penpot HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-penpot/meta/services.yml b/roles/web-app-penpot/meta/services.yml index 5705511400..027d0fe9eb 100644 --- a/roles/web-app-penpot/meta/services.yml +++ b/roles/web-app-penpot/meta/services.yml @@ -95,7 +95,6 @@ backend: pids_limit: 512 healthcheck: flavor: tcp - start_period: 5m ports: internal: http: 6060 diff --git a/roles/web-app-penpot/tasks/01_administrator.yml b/roles/web-app-penpot/tasks/01_administrator.yml new file mode 100644 index 0000000000..f55317c8b5 --- /dev/null +++ b/roles/web-app-penpot/tasks/01_administrator.yml @@ -0,0 +1,39 @@ +--- +- name: "๐Ÿ” Resolve the node that holds the Penpot backend and its local id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "{{ PENPOT_BACKEND_SERVICE }}" + resolve_output_prefix: PENPOT_BACKEND + resolve_compose_cid: "{{ PENPOT_BACKEND_CONTAINER_ADDRESS }}" + +- name: "๐Ÿฅพ Bootstrap the Penpot administrator's local account (idempotent)" + ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec -i {{ PENPOT_BACKEND_LOCAL_CID | quote }} + python3 manage.py create-profile + -n {{ PENPOT_ADMIN_FULLNAME | quote }} + -e {{ PENPOT_ADMIN_EMAIL | quote }} + -p {{ PENPOT_ADMIN_PASSWORD | quote }} + register: penpot_admin_create + retries: 30 + delay: 5 + until: >- + penpot_admin_create.rc == 0 or + ('already exists' in (penpot_admin_create.stdout | default('') ~ penpot_admin_create.stderr | default(''))) + changed_when: "'Created' in penpot_admin_create.stdout" + failed_when: + - penpot_admin_create.rc != 0 + - "'already exists' not in (penpot_admin_create.stdout | default('') ~ penpot_admin_create.stderr | default(''))" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ PENPOT_BACKEND_HOST_NODE }}" + +- name: "๐Ÿ”ง Set the Penpot administrator's local password when the profile already exists" + ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec -i {{ PENPOT_BACKEND_LOCAL_CID | quote }} + python3 manage.py update-profile + -e {{ PENPOT_ADMIN_EMAIL | quote }} + -p {{ PENPOT_ADMIN_PASSWORD | quote }} + when: "'already exists' in (penpot_admin_create.stdout | default('') ~ penpot_admin_create.stderr | default(''))" + register: penpot_admin_update + changed_when: "'Updated' in penpot_admin_update.stdout" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ PENPOT_BACKEND_HOST_NODE }}" diff --git a/roles/web-app-penpot/tasks/main.yml b/roles/web-app-penpot/tasks/main.yml index af877d5e90..bdb268b3c3 100644 --- a/roles/web-app-penpot/tasks/main.yml +++ b/roles/web-app-penpot/tasks/main.yml @@ -17,37 +17,7 @@ ansible.builtin.meta: flush_handlers - name: "๐Ÿฅพ Bootstrap the Penpot administrator's local account" - when: IS_STACK_HOST | bool - block: - - name: "๐Ÿฅพ Bootstrap the Penpot administrator's local account (idempotent)" - when: PENPOT_NATIVE_LOGIN_ENABLED | bool - ansible.builtin.shell: > - container exec -i {{ PENPOT_BACKEND_CONTAINER_ADDRESS }} - python3 manage.py create-profile - -n {{ PENPOT_ADMIN_FULLNAME | quote }} - -e {{ PENPOT_ADMIN_EMAIL | quote }} - -p {{ PENPOT_ADMIN_PASSWORD | quote }} - register: penpot_admin_create - retries: 30 - delay: 5 - until: >- - penpot_admin_create.rc == 0 or - ('already exists' in (penpot_admin_create.stdout | default('') ~ penpot_admin_create.stderr | default(''))) - changed_when: "'Created' in penpot_admin_create.stdout" - failed_when: - - penpot_admin_create.rc != 0 - - "'already exists' not in (penpot_admin_create.stdout | default('') ~ penpot_admin_create.stderr | default(''))" - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - - - name: "๐Ÿ”ง Set the Penpot administrator's local password when the profile already exists" - ansible.builtin.shell: > - container exec -i {{ PENPOT_BACKEND_CONTAINER_ADDRESS }} - python3 manage.py update-profile - -e {{ PENPOT_ADMIN_EMAIL | quote }} - -p {{ PENPOT_ADMIN_PASSWORD | quote }} - when: - - PENPOT_NATIVE_LOGIN_ENABLED | bool - - "'already exists' in (penpot_admin_create.stdout | default('') ~ penpot_admin_create.stderr | default(''))" - register: penpot_admin_update - changed_when: "'Updated' in penpot_admin_update.stdout" - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + ansible.builtin.include_tasks: 01_administrator.yml + when: + - IS_STACK_HOST | bool + - PENPOT_NATIVE_LOGIN_ENABLED | bool diff --git a/roles/web-app-pgadmin/README.md b/roles/web-app-pgadmin/README.md index 343f2f8446..18cf0d3e3d 100644 --- a/roles/web-app-pgadmin/README.md +++ b/roles/web-app-pgadmin/README.md @@ -92,19 +92,20 @@ Run the published image to provision the inventory and deploy pgAdmin to a manag ```bash APP=web-app-pgadmin HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-pgadmin/meta/info.yml b/roles/web-app-pgadmin/meta/info.yml index f4ae8f72d3..9f4b268ca3 100644 --- a/roles/web-app-pgadmin/meta/info.yml +++ b/roles/web-app-pgadmin/meta/info.yml @@ -2,4 +2,4 @@ logo: class: fa-solid fa-database homepage: https://www.pgadmin.org/ -video: https://www.pgadmin.org/videos/ +video: https://www.youtube.com/watch?v=WFT5MaZN6g4 diff --git a/roles/web-app-pgadmin/meta/services.yml b/roles/web-app-pgadmin/meta/services.yml index 1b4eeb4d3e..4f72e5a3fc 100644 --- a/roles/web-app-pgadmin/meta/services.yml +++ b/roles/web-app-pgadmin/meta/services.yml @@ -3,7 +3,6 @@ pgadmin: healthcheck: flavor: wget - start_period: 10m modes: compose: enabled: true diff --git a/roles/web-app-phpldapadmin/README.md b/roles/web-app-phpldapadmin/README.md index a3b8c2a03b..94a5c49aa4 100644 --- a/roles/web-app-phpldapadmin/README.md +++ b/roles/web-app-phpldapadmin/README.md @@ -81,19 +81,20 @@ Run the published image to provision the inventory and deploy phpldapadmin to a ```bash APP=web-app-phpldapadmin HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-phpldapadmin/meta/info.yml b/roles/web-app-phpldapadmin/meta/info.yml index cb70ca0038..81b5fd5819 100644 --- a/roles/web-app-phpldapadmin/meta/info.yml +++ b/roles/web-app-phpldapadmin/meta/info.yml @@ -1,4 +1,5 @@ --- +# nocheck: info-media no official demo video logo: class: fa-solid fa-user-lock homepage: https://github.com/leenooks/phpLDAPadmin diff --git a/roles/web-app-phpldapadmin/meta/main.yml b/roles/web-app-phpldapadmin/meta/main.yml index c21e4e2436..d72fac966e 100644 --- a/roles/web-app-phpldapadmin/meta/main.yml +++ b/roles/web-app-phpldapadmin/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Web-based LDAP client for browsing, searching, and administering directory entries in LDAP servers diff --git a/roles/web-app-phpldapadmin/meta/variants.yml b/roles/web-app-phpldapadmin/meta/variants.yml index f81db4c599..c986849575 100644 --- a/roles/web-app-phpldapadmin/meta/variants.yml +++ b/roles/web-app-phpldapadmin/meta/variants.yml @@ -52,24 +52,3 @@ shared: false tor: enabled: true -- services: - sso: - enabled: false - shared: false - css: - enabled: false - shared: false - dashboard: - enabled: false - shared: false - logout: - enabled: false - shared: false - matomo: - enabled: false - shared: false - prometheus: - enabled: false - shared: false - tor: - enabled: true diff --git a/roles/web-app-phpmyadmin/README.md b/roles/web-app-phpmyadmin/README.md index 7d2fabb4f7..3d639bc9f3 100644 --- a/roles/web-app-phpmyadmin/README.md +++ b/roles/web-app-phpmyadmin/README.md @@ -83,19 +83,20 @@ Run the published image to provision the inventory and deploy PhpMyAdmin to a ma ```bash APP=web-app-phpmyadmin HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-phpmyadmin/meta/info.yml b/roles/web-app-phpmyadmin/meta/info.yml index 4ff3584577..c7a653561b 100644 --- a/roles/web-app-phpmyadmin/meta/info.yml +++ b/roles/web-app-phpmyadmin/meta/info.yml @@ -1,4 +1,5 @@ --- +# nocheck: info-media no official demo video logo: class: fa-solid fa-database homepage: https://www.phpmyadmin.net/ diff --git a/roles/web-app-phpmyadmin/meta/main.yml b/roles/web-app-phpmyadmin/meta/main.yml index 1285e921e2..c0290d015d 100644 --- a/roles/web-app-phpmyadmin/meta/main.yml +++ b/roles/web-app-phpmyadmin/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Web-based administration tool for MySQL and MariaDB with schema management, querying, and import/export diff --git a/roles/web-app-pihole/README.md b/roles/web-app-pihole/README.md index 44766270ba..e43b0b15d9 100644 --- a/roles/web-app-pihole/README.md +++ b/roles/web-app-pihole/README.md @@ -88,19 +88,20 @@ Run the published image to provision the inventory and deploy web-app-pihole to ```bash APP=web-app-pihole HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-pihole/files/playwright/native.spec.js b/roles/web-app-pihole/files/playwright/native.spec.js index 63674f2023..732cecfdf0 100644 --- a/roles/web-app-pihole/files/playwright/native.spec.js +++ b/roles/web-app-pihole/files/playwright/native.spec.js @@ -37,6 +37,11 @@ test("administrator: can log in natively to pihole", async ({ page }) => { await page.getByRole("button", { name: /log in|sign in/i }).click({ timeout: resolveTimeout(30_000) }); await page.waitForLoadState("networkidle", { timeout: resolveTimeout(30_000) }).catch(() => {}); - await expect(page.locator("body")).toBeVisible(); - expect(page.url()).toContain("/admin"); + await expect + .poll(() => page.url(), { + timeout: resolveTimeout(30_000), + message: `native login must leave the login form, still at ${page.url()}`, + }) + .not.toContain("/login"); + await expect(passwordInput).toBeHidden({ timeout: resolveTimeout(30_000) }); }); diff --git a/roles/web-app-pihole/files/playwright/oauth2.spec.js b/roles/web-app-pihole/files/playwright/oauth2.spec.js index ff3d0ee50f..8c056a4fc5 100644 --- a/roles/web-app-pihole/files/playwright/oauth2.spec.js +++ b/roles/web-app-pihole/files/playwright/oauth2.spec.js @@ -45,9 +45,11 @@ test("administrator: can log in via SSO and access pihole", async ({ page }) => await gotoOnion(page, `${expectedPiholeBaseUrl}/`); await expect.poll(() => page.url(), { timeout: resolveTimeout(30_000) }).toContain(expectedOidcAuthUrl); await performOidcLogin(page, adminUsername, adminPassword); + await expect.poll(() => page.url(), { timeout: resolveTimeout(60_000) }).toContain(expectedPiholeBaseUrl); + await page.waitForURL(url => !url.toString().includes("/oauth2/callback"), { timeout: resolveTimeout(30_000) }).catch(() => {}); await page.waitForLoadState("networkidle", { timeout: resolveTimeout(60_000) }).catch(() => {}); expect(page.url()).not.toContain(expectedOidcAuthUrl); - await expect(page.locator("body")).toBeVisible(); + expect(page.url()).not.toContain("/oauth2/callback"); }); test("biber: is denied access to pihole admin panel", async ({ page }) => { @@ -57,17 +59,24 @@ test("biber: is denied access to pihole admin panel", async ({ page }) => { await gotoOnion(page, `${expectedPiholeBaseUrl}/`); await expect.poll(() => page.url(), { timeout: resolveTimeout(30_000) }).toContain(expectedOidcAuthUrl); await performOidcLogin(page, biberUsername, biberPassword); - await page.waitForURL(url => !url.toString().includes("/oauth2/callback"), { timeout: resolveTimeout(30_000) }).catch(() => {}); await page.waitForLoadState("networkidle", { timeout: resolveTimeout(30_000) }).catch(() => {}); - const bodyText = await page.locator("body").textContent({ timeout: resolveTimeout(15_000) }).catch(() => ""); - const currentUrl = page.url(); - expect( - bodyText.includes("403") || bodyText.toLowerCase().includes("forbidden") || - bodyText.toLowerCase().includes("access denied") || bodyText.toLowerCase().includes("you do not have permission") || - currentUrl.includes(expectedOidcAuthUrl) || currentUrl.includes("/oauth2/callback"), - `Expected biber to be denied. URL: ${currentUrl}` - ).toBeTruthy(); + const deniedNow = async () => { + const body = await page.locator("body").textContent({ timeout: resolveTimeout(15_000) }).catch(() => ""); + const text = (body || "").toLowerCase(); + const url = page.url(); + if (text.includes("access denied") || text.includes("you do not have permission")) return "denied"; + if (url.includes(expectedOidcAuthUrl)) return "denied"; + if (url.includes("/oauth2/callback")) return "still handing off"; + return `reached ${url}`; + }; + + await expect + .poll(deniedNow, { + timeout: resolveTimeout(30_000), + message: "biber must not reach the pihole admin panel", + }) + .toBe("denied"); }); test("administrator: can log out via logout button", async ({ page }) => { diff --git a/roles/web-app-pihole/templates/compose.yml.j2 b/roles/web-app-pihole/templates/compose.yml.j2 index 0267bab573..93ff1548a8 100644 --- a/roles/web-app-pihole/templates/compose.yml.j2 +++ b/roles/web-app-pihole/templates/compose.yml.j2 @@ -5,11 +5,6 @@ {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {{ lookup('container_image', application_id, 'pihole') }} {{ lookup('compose_only', 'container_name', PIHOLE_CONTAINER) }} - environment: - TZ: "{{ PIHOLE_TIMEZONE }}" - FTLCONF_webserver_api_password: "{{ PIHOLE_PASSWORD }}" - FTLCONF_webserver_domain: "{{ domain }}" - PIHOLE_DNS_: "{{ PIHOLE_UPSTREAM_DNS }}" {{ lookup('container_ports', ['pihole', 'http', DOCKER_BIND_HOST]) | indent(4) }} cap_add: - NET_ADMIN diff --git a/roles/web-app-pihole/templates/env.j2 b/roles/web-app-pihole/templates/env.j2 new file mode 100644 index 0000000000..cf556f6c04 --- /dev/null +++ b/roles/web-app-pihole/templates/env.j2 @@ -0,0 +1,5 @@ +{% include 'roles/sys-svc-container/templates/env.j2' %} + +FTLCONF_webserver_api_password={{ PIHOLE_PASSWORD | dotenv_quote }} +FTLCONF_webserver_domain={{ domain }} +PIHOLE_DNS_={{ PIHOLE_UPSTREAM_DNS }} diff --git a/roles/web-app-pihole/vars/main.yml b/roles/web-app-pihole/vars/main.yml index c150731002..0ba9d3e5d4 100644 --- a/roles/web-app-pihole/vars/main.yml +++ b/roles/web-app-pihole/vars/main.yml @@ -6,7 +6,6 @@ domain: "{{ lookup('domain', application_id) }}" PIHOLE_CONTAINER: "{{ entity_name }}" PIHOLE_UPSTREAM_DNS: "{{ lookup('config', application_id, 'services.pihole.upstream_dns') | join(';') }}" -PIHOLE_TIMEZONE: "{{ HOST_TIMEZONE }}" PIHOLE_OAUTH2_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') | bool }}" PIHOLE_PASSWORD: "{{ '' if PIHOLE_OAUTH2_ENABLED else lookup('users', 'administrator').password }}" diff --git a/roles/web-app-pixelfed/README.md b/roles/web-app-pixelfed/README.md index e3934d3d38..7a7b9487b5 100644 --- a/roles/web-app-pixelfed/README.md +++ b/roles/web-app-pixelfed/README.md @@ -90,19 +90,20 @@ Run the published image to provision the inventory and deploy Pixelfed to a mana ```bash APP=web-app-pixelfed HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-pixelfed/meta/info.yml b/roles/web-app-pixelfed/meta/info.yml index c404c44605..a9439412ff 100644 --- a/roles/web-app-pixelfed/meta/info.yml +++ b/roles/web-app-pixelfed/meta/info.yml @@ -1,4 +1,5 @@ --- +# nocheck: info-media no official demo video logo: class: fa-solid fa-camera homepage: https://pixelfed.org/ diff --git a/roles/web-app-pixelfed/meta/main.yml b/roles/web-app-pixelfed/meta/main.yml index dd6aba77d0..15f0d03bfa 100644 --- a/roles/web-app-pixelfed/meta/main.yml +++ b/roles/web-app-pixelfed/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Decentralized, federated platform for photo sharing and image feeds across the fediverse diff --git a/roles/web-app-pixelfed/meta/services.yml b/roles/web-app-pixelfed/meta/services.yml index 053a193949..4bf143436b 100644 --- a/roles/web-app-pixelfed/meta/services.yml +++ b/roles/web-app-pixelfed/meta/services.yml @@ -49,7 +49,7 @@ pixelfed: shared: true enabled: true # nocheck: dynamic-flag image: zknt/pixelfed - version: latest + version: "20260917" name: pixelfed min_storage: 588MB backup: @@ -71,6 +71,11 @@ worker: # nocheck: single-replica replicas: 1 name: pixelfed_worker + healthcheck: + test: ["CMD-SHELL", "test ! -e /var/www/storage/.docker.init || (php artisan horizon:status | grep running)"] + # nocheck: healthcheck-timing-override php artisan boots Laravel on every probe, so it stays off a 30s steady-state loop + interval: 60s + retries: 5 cpus: 1.0 mem_reservation: 0.75g mem_limit: 1g diff --git a/roles/web-app-pixelfed/templates/compose.yml.j2 b/roles/web-app-pixelfed/templates/compose.yml.j2 index f2607009af..b25729f570 100644 --- a/roles/web-app-pixelfed/templates/compose.yml.j2 +++ b/roles/web-app-pixelfed/templates/compose.yml.j2 @@ -22,12 +22,7 @@ AUTORUN_ENABLED: "false" {{ lookup('container_volumes', service_name) | indent(4) }} entrypoint: "{{ PIXELFED_WORKER_ENTRYPOINT_DOCKER }}" - healthcheck: - test: test ! -e /var/www/storage/.docker.init || (php artisan horizon:status | grep running) - interval: 60s - timeout: 5s - retries: 5 - start_period: 300s + {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_depends_on', application_id, extra={ 'pixelfed': {'condition': 'service_started'}, }) | indent(4) }} diff --git a/roles/web-app-pixelfed/templates/playwright.env.j2 b/roles/web-app-pixelfed/templates/playwright.env.j2 index 7cf2bd23f0..df0ab60782 100644 --- a/roles/web-app-pixelfed/templates/playwright.env.j2 +++ b/roles/web-app-pixelfed/templates/playwright.env.j2 @@ -7,7 +7,7 @@ ADMIN_USERNAME={{ lookup('users', 'administrator').username | dotenv_quote }} APP_BASE_URL={{ lookup('tls', application_id, 'url.base') }} -BIBER_OIDC_EMAIL_OVERRIDE={{ (lookup('users', 'biber').username ~ '@infinito.nexus') | dotenv_quote }} +BIBER_OIDC_EMAIL_OVERRIDE={{ (lookup('users', 'biber').username ~ '@' ~ SOFTWARE_DOMAIN) | dotenv_quote }} BIBER_PASSWORD={{ lookup('users', 'biber').password | dotenv_quote }} diff --git a/roles/web-app-postmarks/README.md b/roles/web-app-postmarks/README.md index 62176f878f..7712560833 100644 --- a/roles/web-app-postmarks/README.md +++ b/roles/web-app-postmarks/README.md @@ -75,19 +75,20 @@ Run the published image to provision the inventory and deploy Postmarks to a man ```bash APP=web-app-postmarks HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-postmarks/meta/info.yml b/roles/web-app-postmarks/meta/info.yml index cffa1e66a6..ebe186463d 100644 --- a/roles/web-app-postmarks/meta/info.yml +++ b/roles/web-app-postmarks/meta/info.yml @@ -1,2 +1,3 @@ --- +# nocheck: info-media no official demo video homepage: https://github.com/ckolderup/postmarks diff --git a/roles/web-app-postmarks/meta/main.yml b/roles/web-app-postmarks/meta/main.yml index 649cd196c6..ce5635132c 100644 --- a/roles/web-app-postmarks/meta/main.yml +++ b/roles/web-app-postmarks/meta/main.yml @@ -1,5 +1,4 @@ --- -# nocheck: info-media no official demo video galaxy_info: author: Kevin Veen-Birkenbach description: Single-user ActivityPub bookmarking site federating public bookmarks to Mastodon and the Fediverse diff --git a/roles/web-app-postmarks/meta/services.yml b/roles/web-app-postmarks/meta/services.yml index 6dd146a1f1..fa6100d4ee 100644 --- a/roles/web-app-postmarks/meta/services.yml +++ b/roles/web-app-postmarks/meta/services.yml @@ -46,7 +46,7 @@ postmarks: swarm: enabled: true image: node - version: 26-bookworm + version: 26-slim custom: true name: web-app-postmarks repository: https://github.com/ckolderup/postmarks.git diff --git a/roles/web-app-pretix/README.md b/roles/web-app-pretix/README.md index 1d205401af..fdb54f9798 100644 --- a/roles/web-app-pretix/README.md +++ b/roles/web-app-pretix/README.md @@ -20,9 +20,12 @@ flowchart LR dep_svc_db_redis["svc-db-redis ๐Ÿณ๐Ÿ"] dep_svc_net_tor["svc-net-tor ๐Ÿณ๐Ÿ"] dep_web_app_dashboard["web-app-dashboard ๐Ÿณ๐Ÿ"] + dep_web_app_hermes["web-app-hermes ๐Ÿณ๐Ÿ"] dep_web_app_keycloak["web-app-keycloak ๐Ÿณ๐Ÿ"] dep_web_app_mailu["web-app-mailu ๐Ÿณ๐Ÿ"] dep_web_app_matomo["web-app-matomo ๐Ÿณ๐Ÿ"] + dep_web_app_openclaw["web-app-openclaw ๐Ÿณ๐Ÿ"] + dep_web_app_openwebui["web-app-openwebui ๐Ÿณ๐Ÿ"] dep_web_app_prometheus["web-app-prometheus ๐Ÿณ๐Ÿ"] dep_web_svc_css["web-svc-css ๐Ÿ’ป"] dep_web_svc_logout["web-svc-logout ๐Ÿณ๐Ÿ"] @@ -40,15 +43,23 @@ flowchart LR svc_prometheus["prometheus"] svc_tor["tor"] svc_container_backup["container_backup"] + svc_pretixmcp["pretixmcp"] + svc_openwebui["openwebui"] + svc_hermes["hermes"] + svc_openclaw["openclaw"] + svc_flowise["flowise โŒ"] end dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup dep_svc_db_postgres -. "0..1" .-> svc_postgres dep_svc_db_redis -. "0..1" .-> svc_redis dep_svc_net_tor -. "0..1" .-> svc_tor dep_web_app_dashboard -. "0..1" .-> svc_dashboard + dep_web_app_hermes -. "0..1" .-> svc_hermes dep_web_app_keycloak -. "0..1" .-> svc_sso dep_web_app_mailu -. "0..1" .-> svc_email dep_web_app_matomo -. "0..1" .-> svc_matomo + dep_web_app_openclaw -. "0..1" .-> svc_openclaw + dep_web_app_openwebui -. "0..1" .-> svc_openwebui dep_web_app_prometheus -. "0..1" .-> svc_prometheus dep_web_svc_css -. "0..1" .-> svc_css dep_web_svc_logout -. "0..1" .-> svc_logout @@ -86,19 +97,20 @@ Run the published image to provision the inventory and deploy Pretix to a manage ```bash APP=web-app-pretix HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-pretix/files/mcp/tools.json b/roles/web-app-pretix/files/mcp/tools.json new file mode 100644 index 0000000000..6eb1baaa04 --- /dev/null +++ b/roles/web-app-pretix/files/mcp/tools.json @@ -0,0 +1,58 @@ +{ + "pretix_get_event": { + "description": "Return one event.", + "input_schema": { + "properties": { + "event": { + "type": "string" + }, + "organizer": { + "type": "string" + } + }, + "required": [ + "organizer", + "event" + ], + "type": "object" + }, + "method": "GET", + "path": "/api/v1/organizers/{organizer}/events/{event}/" + }, + "pretix_get_order_summary": { + "description": "Return the order summary of one event.", + "input_schema": { + "properties": { + "event": { + "type": "string" + }, + "organizer": { + "type": "string" + } + }, + "required": [ + "organizer", + "event" + ], + "type": "object" + }, + "method": "GET", + "path": "/api/v1/organizers/{organizer}/events/{event}/orders/" + }, + "pretix_list_events": { + "description": "List an organizer's events.", + "input_schema": { + "properties": { + "organizer": { + "type": "string" + } + }, + "required": [ + "organizer" + ], + "type": "object" + }, + "method": "GET", + "path": "/api/v1/organizers/{organizer}/events/" + } +} diff --git a/roles/web-app-pretix/files/playwright/playwright.spec.js b/roles/web-app-pretix/files/playwright/playwright.spec.js index 57ec53091a..dc7f816d60 100644 --- a/roles/web-app-pretix/files/playwright/playwright.spec.js +++ b/roles/web-app-pretix/files/playwright/playwright.spec.js @@ -4,6 +4,8 @@ const { resolveTimeout } = require("./timeouts"); const { decodeDotenvQuotedValue, normalizeBaseUrl, runAdminFlow, runBiberFlow, runGuestFlow , expectHstsWhenTls, gotoOnion } = require("./personas"); test.use({ ignoreHTTPSErrors: true }); +require("./test-mcp-guest").register(); + const appBaseUrl = normalizeBaseUrl(process.env.APP_BASE_URL || ""); const canonicalDomain = decodeDotenvQuotedValue(process.env.CANONICAL_DOMAIN || ""); diff --git a/roles/web-app-pretix/files/playwright/test-mcp-guest.js b/roles/web-app-pretix/files/playwright/test-mcp-guest.js new file mode 100644 index 0000000000..bcafb06954 --- /dev/null +++ b/roles/web-app-pretix/files/playwright/test-mcp-guest.js @@ -0,0 +1,10 @@ +const { + mcpEndpointUrl, + registerMcpDisabledState, + registerMcpGuestRejection, +} = require("./mcp-endpoint"); + +exports.register = function () { + registerMcpGuestRejection(mcpEndpointUrl); + registerMcpDisabledState(mcpEndpointUrl); +}; diff --git a/roles/web-app-pretix/files/python/provision_mcp_identity.py b/roles/web-app-pretix/files/python/provision_mcp_identity.py new file mode 100644 index 0000000000..6c44487900 --- /dev/null +++ b/roles/web-app-pretix/files/python/provision_mcp_identity.py @@ -0,0 +1,61 @@ +# nocheck: mirrored-unit-test - imports pretix.base.models at module level and runs its +# queries inside `pretix shell_scoped`, where django-scopes supplies the scope; the +# models are not importable outside the Pretix image +"""Give the MCP adapter a read-only team token in every Pretix organizer. + +Runs inside ``pretix shell_scoped --override``: teams and events are +django-scopes-scoped, so an unscoped query raises rather than returning +everything. + +Pretix has no API endpoint for creating team tokens, only the web UI, and the +model takes an explicit value, so the deployment pins its own credential rather +than capturing a generated one. + +A token belongs to a team and a team belongs to an organizer. The adapter +presents exactly one token, and the same value in two organizers would make +Pretix's token lookup return two rows and answer 500, so the token is pinned in +a single organizer chosen deterministically by slug. With no organizer there is +nothing to attach it to, and no tool call could name one either, so that case +converges to a no-op instead of failing. + +Environment: + MCP_TEAM: team name to converge. + MCP_TOKEN: token value to pin on it. +""" + +import os + +from pretix.base.models import Organizer +from pretix.base.models.organizer import Team, TeamAPIToken + +TEAM = os.environ["MCP_TEAM"] +TOKEN = os.environ["MCP_TOKEN"] +TOKEN_NAME = "mcp-upstream" # noqa: S105 a label, not a secret + +changed = False + +organizer = Organizer.objects.order_by("slug").first() +if organizer is None: + print("UNCHANGED") +else: + team, created = Team.objects.get_or_create( + organizer=organizer, + name=TEAM, + defaults={ + "all_events": True, + "all_event_permissions": False, + "limit_event_permissions": {"event.orders:read": True}, + "all_organizer_permissions": False, + "limit_organizer_permissions": {}, + }, + ) + changed = changed or created + + _, created = TeamAPIToken.objects.update_or_create( + team=team, + name=TOKEN_NAME, + defaults={"token": TOKEN, "active": True}, + ) + changed = changed or created + + print("CHANGED" if changed else "UNCHANGED") diff --git a/roles/web-app-pretix/files/test/.nocheck b/roles/web-app-pretix/files/test/.nocheck new file mode 100644 index 0000000000..2b9d82d840 --- /dev/null +++ b/roles/web-app-pretix/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; test-e2e-cli stages files/test/ by that fixed path. diff --git a/roles/web-app-pretix/files/test/test.sh b/roles/web-app-pretix/files/test/test.sh new file mode 100644 index 0000000000..3836f6f714 --- /dev/null +++ b/roles/web-app-pretix/files/test/test.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# CLI test for web-app-pretix: the MCP endpoint honours its declared contract. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +bash "${here}/shared/mcp/run.sh" diff --git a/roles/web-app-pretix/meta/info.yml b/roles/web-app-pretix/meta/info.yml index cd17a419cc..2e12e42a51 100644 --- a/roles/web-app-pretix/meta/info.yml +++ b/roles/web-app-pretix/meta/info.yml @@ -2,4 +2,4 @@ logo: class: fas fa-ticket homepage: https://pretix.eu/ -video: https://www.youtube.com/channel/UCG1Og1YUpgIJD4geAZLAp5g +video: https://www.youtube.com/watch?v=5F6QkZP1Zf0 diff --git a/roles/web-app-pretix/meta/mcp.yml b/roles/web-app-pretix/meta/mcp.yml new file mode 100644 index 0000000000..b026f86231 --- /dev/null +++ b/roles/web-app-pretix/meta/mcp.yml @@ -0,0 +1,38 @@ +--- +classification: adapter_server +direction: server +source_url: https://s.infinito.nexus/code +transport: streamable_http +exposure: internal +auth: bearer_token +auth_subject: service_account +implementation: adapter +credential: + owner: mcp-web-app-pretix + source: credentials + key: mcp_bearer +endpoint: + service_key: pretixmcp + path: /mcp + port_key: http +adapter: + type: openapi_allowlist + upstream_api_version: v1 + specification_path: roles/web-app-pretix/files/mcp/tools.json + specification_sha256: sha256:7d4044f034d4ee5aa9b427a25dd028ca8eb922d8776ae9ac571512e40abf90f9 +limits: + request_bytes: 65536 + response_bytes: 1048576 + timeout_seconds: 15 + concurrent_requests: 4 + page_size: 100 + result_items: 100 + stream_seconds: 300 +tools: + allowlist: + - pretix_get_event + - pretix_get_order_summary + - pretix_list_events + schema_sha256: sha256:0019dd8228113173b98d5069b183d7206bbcb999b8ac62c19f6a1e6dcaef7b14 + read_only_default: true + mutating_tools_enabled: false diff --git a/roles/web-app-pretix/meta/networks.yml b/roles/web-app-pretix/meta/networks.yml index 9d7c0a4184..057d904b2c 100644 --- a/roles/web-app-pretix/meta/networks.yml +++ b/roles/web-app-pretix/meta/networks.yml @@ -1,3 +1,8 @@ --- local: subnet: 192.168.55.0/24 +overlay: + modes: [compose, swarm] + topology: shared_net + consumer: + kind: mcp_client diff --git a/roles/web-app-pretix/meta/rbac.yml b/roles/web-app-pretix/meta/rbac.yml index 0c37d62134..084e6fbeca 100644 --- a/roles/web-app-pretix/meta/rbac.yml +++ b/roles/web-app-pretix/meta/rbac.yml @@ -1,2 +1,4 @@ --- -roles: {} +roles: + mcp: + description: Can drive this application through an MCP client, which acts with the credentials the deployment issued rather than the caller's own diff --git a/roles/web-app-pretix/meta/secrets.yml b/roles/web-app-pretix/meta/secrets.yml new file mode 100644 index 0000000000..c4d4412317 --- /dev/null +++ b/roles/web-app-pretix/meta/secrets.yml @@ -0,0 +1,14 @@ +--- +credentials: + mcp_bearer: + description: "Bearer an MCP client must present to this role's adapter instance. Distinct from the upstream credential the adapter presents, because authenticating + to the application says nothing about who called the adapter." + algorithm: alphanumeric + validation: "^[A-Za-z0-9]{32,}$" + length: 48 + mcp_upstream_token: + description: "Read-scoped API token the MCP adapter presents to this application. Separate from mcp_bearer, which guards the adapter itself: one says who may + call the adapter, the other what the adapter may read." + algorithm: alphanumeric + validation: "^[A-Za-z0-9]{32,}$" + length: 48 diff --git a/roles/web-app-pretix/meta/services.yml b/roles/web-app-pretix/meta/services.yml index 3beb8e90a8..fa74ddee1b 100644 --- a/roles/web-app-pretix/meta/services.yml +++ b/roles/web-app-pretix/meta/services.yml @@ -39,7 +39,11 @@ postgres: bond: 1 enabled: true # nocheck: dynamic-flag shared: "{{ 'svc-db-postgres' in group_names }}" +# nocheck: playwright-service-flag self-provider pretix: + enabled: true + shared: true + bond: 1 healthcheck: flavor: curl hostname: localhost @@ -49,7 +53,7 @@ pretix: swarm: enabled: true image: pretix/standalone - version: stable + version: 2026.7.0 custom: true name: pretix min_storage: 1003MB @@ -92,3 +96,42 @@ container_backup: # nocheck: bond-baseline backup host joins outside the variant bond: 1 enabled: "{{ 'svc-bkp-volume-2-local' in group_names }}" shared: true +# nocheck: playwright-service-flag internal adapter sidecar, covered by the role's MCP guest spec +# nocheck: dockerfile-custom the Dockerfile is owned by svc-ai-mcp-adapter and staged per instance, so every adapter-backed provider shares one audited build +# nocheck: dynamic-flag the sidecar tracks this role's own mcp flag, not another role's presence; a group_names expression would decide its exposure from an unrelated deployment +pretixmcp: + enabled: "{{ lookup('config', 'web-app-pretix', 'mcp.enabled') | bool }}" + shared: false + image: python + # nocheck: docker-version base of the self-built stdlib adapter, not the served application + version: "3.13.15-slim" + custom: true + name: pretixmcp + cpus: "0.25" + mem_reservation: 16m + mem_limit: 24m + pids_limit: 64 + ports: + internal: + http: 8080 +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openwebui: + bond: 0.5 + enabled: "{{ 'web-app-openwebui' in group_names }}" + shared: "{{ 'web-app-openwebui' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +hermes: + bond: 0.5 + enabled: "{{ 'web-app-hermes' in group_names }}" + shared: "{{ 'web-app-hermes' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openclaw: + bond: 0.5 + enabled: "{{ 'web-app-openclaw' in group_names }}" + shared: "{{ 'web-app-openclaw' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +# nocheck: dynamic-flag the entry refuses this client, so the link is off on every host and no group_names gate can decide it +flowise: + enabled: false + shared: false + mcp_consumer: false diff --git a/roles/web-app-pretix/meta/tests.yml b/roles/web-app-pretix/meta/tests.yml new file mode 100644 index 0000000000..28bea0efe2 --- /dev/null +++ b/roles/web-app-pretix/meta/tests.yml @@ -0,0 +1,3 @@ +--- +cli: + timeout: 900 diff --git a/roles/web-app-pretix/meta/variants.yml b/roles/web-app-pretix/meta/variants.yml index 3ecebdb9a4..d2e647c930 100644 --- a/roles/web-app-pretix/meta/variants.yml +++ b/roles/web-app-pretix/meta/variants.yml @@ -34,6 +34,55 @@ shared: true tor: enabled: true + openwebui: + enabled: false + shared: false + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false +- services: + container_backup: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + dashboard: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + email: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + logout: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + matomo: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + sso: + enabled: true + shared: true + postgres: + shared: false # nocheck: variants-static-override backup shared stays literally true + redis: + shared: false # nocheck: variants-static-override backup shared stays literally true + prometheus: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + css: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + tor: + enabled: true + openwebui: + enabled: true + shared: true + hermes: + enabled: true + shared: true + openclaw: + enabled: true + shared: true - services: container_backup: enabled: false @@ -53,10 +102,6 @@ sso: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true - postgres: - shared: false # nocheck: variants-static-override backup shared stays literally true - redis: - shared: false # nocheck: variants-static-override backup shared stays literally true prometheus: enabled: false shared: false # nocheck: variants-static-override backup shared stays literally true @@ -65,3 +110,12 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + openwebui: + enabled: false + shared: false + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false diff --git a/roles/web-app-pretix/tasks/00_core.yml b/roles/web-app-pretix/tasks/00_core.yml new file mode 100644 index 0000000000..5e13356370 --- /dev/null +++ b/roles/web-app-pretix/tasks/00_core.yml @@ -0,0 +1,18 @@ +--- +- include_tasks: utils/once/flag.yml + +- name: "๐Ÿ”Œ Stage the MCP adapter instance for {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/instance.yml') }}" + vars: + mcp_adapter_instance_dir: "{{ PRETIX_MCP_INSTANCE_DIR }}" + when: PRETIX_MCP_ENABLED | bool + +- name: "๐Ÿงฉ load docker, db and proxy for {{ application_id }}" + include_role: + name: sys-stk-full + vars: + compose_handlers_flush: true + +- name: "๐Ÿ”Œ Serve MCP from {{ application_id }}" + ansible.builtin.include_tasks: utils/mcp.yml + when: PRETIX_MCP_ENABLED | bool diff --git a/roles/web-app-pretix/tasks/main.yml b/roles/web-app-pretix/tasks/main.yml index a9f040727e..60c88aab30 100644 --- a/roles/web-app-pretix/tasks/main.yml +++ b/roles/web-app-pretix/tasks/main.yml @@ -1,9 +1,3 @@ --- -- block: - - name: "๐Ÿงฉ load docker, db and proxy for {{ application_id }}" - include_role: - name: sys-stk-full - vars: - compose_handlers_flush: true - - include_tasks: utils/once/flag.yml +- include_tasks: 00_core.yml when: run_once_web_app_pretix is not defined diff --git a/roles/web-app-pretix/tasks/utils/mcp.yml b/roles/web-app-pretix/tasks/utils/mcp.yml new file mode 100644 index 0000000000..de6b66c016 --- /dev/null +++ b/roles/web-app-pretix/tasks/utils/mcp.yml @@ -0,0 +1,37 @@ +--- +- name: "๐Ÿงฑ Rebuild the MCP adapter of {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/rebuild.yml') }}" + +- name: "๐Ÿšฟ Flush compose handlers for {{ application_id }}" + ansible.builtin.meta: flush_handlers + +- name: "๐Ÿ” Resolve {{ application_id }} hosting node + container id" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}" + vars: + resolve_service_key: "pretix" + resolve_output_prefix: PRETIX_IDENTITY + resolve_compose_cid: "{{ PRETIX_CONTAINER }}" + +- name: "๐Ÿ”‘ Converge the read-only Pretix team token the MCP adapter presents" + ansible.builtin.command: + argv: + - container + - exec + - -i + - -e + - "MCP_TEAM={{ PRETIX_MCP_UPSTREAM_TEAM }}" + - -e + - "MCP_TOKEN={{ PRETIX_MCP_UPSTREAM_KEY }}" + - "{{ PRETIX_IDENTITY_LOCAL_CID }}" # nocheck: container-exec-resolver + - pretix + - shell_scoped + - --override + stdin: "{{ lookup('file', 'python/provision_mcp_identity.py') }}" + register: pretix_mcp_identity + retries: 30 + delay: 10 + until: pretix_mcp_identity.rc == 0 + changed_when: pretix_mcp_identity.stdout_lines[-1] | default('') == 'CHANGED' + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + delegate_to: "{{ PRETIX_IDENTITY_HOST_NODE }}" + run_once: true diff --git a/roles/web-app-pretix/templates/compose.yml.j2 b/roles/web-app-pretix/templates/compose.yml.j2 index 3234790fc3..2062a5c9d1 100644 --- a/roles/web-app-pretix/templates/compose.yml.j2 +++ b/roles/web-app-pretix/templates/compose.yml.j2 @@ -18,5 +18,34 @@ {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} + {% if PRETIX_MCP_ENABLED | bool %} + {% set service_name = PRETIX_MCP_SERVICE_KEY %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, 'pretixmcp') }} + build: + context: {{ PRETIX_MCP_INSTANCE_DIR }} + dockerfile: Dockerfile + args: + MCP_ADAPTER_BASE_IMAGE: {{ lookup('config', application_id, 'services.pretixmcp.image') }} + MCP_ADAPTER_BASE_VERSION: "{{ lookup('config', application_id, 'services.pretixmcp.version') }}" + {{ lookup('compose_only', 'container_name', PRETIX_MCP_CONTAINER) }} + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + environment: + ADAPTER_CONTRACT: {{ PRETIX_MCP_CONTRACT | to_json | to_json | replace('$', '$$') }} + ADAPTER_BEARER: {{ PRETIX_MCP_BEARER | to_json }} + ADAPTER_PORT: "{{ PRETIX_MCP_PORT }}" + ADAPTER_UPSTREAM_KEY: {{ PRETIX_MCP_UPSTREAM_KEY | to_json }} + ADAPTER_UPSTREAM_AUTH_HEADER: {{ PRETIX_MCP_UPSTREAM_AUTH_HEADER | to_json }} + ADAPTER_UPSTREAM_AUTH_FORMAT: {{ PRETIX_MCP_UPSTREAM_AUTH_FORMAT | to_json }} + expose: + - "{{ PRETIX_MCP_PORT }}" + {{ lookup('container_networks', own_network_only=True, provider_self_alias=False) | indent(4) }} + {% endif %} + {{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} diff --git a/roles/web-app-pretix/templates/env.j2 b/roles/web-app-pretix/templates/env.j2 index 676b72fe89..2a8ff4791a 100644 --- a/roles/web-app-pretix/templates/env.j2 +++ b/roles/web-app-pretix/templates/env.j2 @@ -15,6 +15,7 @@ PRETIX_DATABASE_HOST={{ lookup('database', application_id, 'host') }} PRETIX_DATABASE_PORT={{ lookup('database', application_id, 'port') }} PRETIX_WEB_CONCURRENCY={{ POSTGRES_ALLOWED_AVG_CONNECTIONS }} PRETIX_WORKER_THREADS={{ (POSTGRES_ALLOWED_AVG_CONNECTIONS | int // 2 ) }} +NUM_WORKERS={{ [2, (2 * (lookup('config', application_id, 'services.pretix.cpus') | float)) | round(0, 'floor') | int] | max }} {% if PRETIX_REDIS_ENABLED %} {% set redis_host = lookup('engine', 'redis', application_id, 'host') %} diff --git a/roles/web-app-pretix/templates/playwright.env.j2 b/roles/web-app-pretix/templates/playwright.env.j2 index ae88a396d3..1f026eb53c 100644 --- a/roles/web-app-pretix/templates/playwright.env.j2 +++ b/roles/web-app-pretix/templates/playwright.env.j2 @@ -19,6 +19,8 @@ MATOMO_BASE_URL={{ lookup('tls', 'web-app-matomo', 'url.base') | dotenv_quote }} MATOMO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.matomo.enabled') | string | lower }} +MCP_SERVICE_ENABLED={{ lookup('config', application_id, 'mcp.enabled') | string | lower }} + NODE_TLS_REJECT_UNAUTHORIZED=0 # nocheck: persona-block-rationale โ€” the role provisions no pretix account: tasks/main.yml is a bare sys-stk-full include with no admin task, while pretix's NativeAuthBackend (templates/env.j2:6) authenticates against a pretix User row that is only ever created by the interactive first-run setup; the pretix-oidc backend added on top (templates/env.j2:41-43) sits on pretix's /control login page, whereas APP_BASE_URL/ is the public ticket shop the baseline test asserts (files/playwright/playwright.spec.js:15-25). See README "Persona contract opt-outs". diff --git a/roles/web-app-pretix/templates/test.env.j2 b/roles/web-app-pretix/templates/test.env.j2 new file mode 100644 index 0000000000..3c7bacad44 --- /dev/null +++ b/roles/web-app-pretix/templates/test.env.j2 @@ -0,0 +1 @@ +{{ lookup('template', lookup('path_absolute', 'roles/test-e2e-cli/templates/mcp/test.env.j2')) }} diff --git a/roles/web-app-pretix/vars/main.yml b/roles/web-app-pretix/vars/main.yml index 3abeae89d0..b137b3c3de 100644 --- a/roles/web-app-pretix/vars/main.yml +++ b/roles/web-app-pretix/vars/main.yml @@ -27,3 +27,24 @@ PRETIX_REDIS_RESULT_DB: 2 PRETIX_IMAGE: "{{ lookup('config', application_id, 'services.pretix.image') }}" PRETIX_VERSION: "{{ lookup('config', application_id, 'services.pretix.version') }}" PRETIX_CONTAINER: "{{ lookup('config', application_id, 'services.pretix.name') }}" +PRETIX_MCP_ENABLED: "{{ lookup('config', application_id, 'services.pretixmcp.enabled') | bool }}" +PRETIX_MCP_SERVICE_KEY: "pretixmcp" +PRETIX_MCP_CONTAINER: "{{ lookup('config', application_id, 'services.pretixmcp.name') }}" +PRETIX_MCP_PORT: "{{ lookup('config', application_id, 'services.pretixmcp.ports.internal.http') }}" +PRETIX_MCP_BEARER: "{{ lookup('config', application_id, 'secrets.credentials.mcp_bearer') }}" +PRETIX_MCP_INSTANCE_DIR: "{{ [lookup('container', application_id, 'directories.instance'), 'mcp'] | path_join }}" +PRETIX_MCP_UPSTREAM_HOST: "{{ lookup('config', application_id, 'services.pretix.name') }}" +PRETIX_MCP_UPSTREAM_PORT: "{{ lookup('config', application_id, 'services.pretix.ports.internal.http') }}" +PRETIX_MCP_UPSTREAM_URL: "http://{{ PRETIX_MCP_UPSTREAM_HOST }}:{{ PRETIX_MCP_UPSTREAM_PORT }}" +PRETIX_MCP_CONTRACT: + provider: "{{ application_id }}" + upstream_url: "{{ PRETIX_MCP_UPSTREAM_URL }}" + auth_subject: "{{ lookup('config', application_id, 'mcp.auth_subject') }}" + mutating_tools_enabled: "{{ lookup('config', application_id, 'mcp.tools.mutating_tools_enabled') | bool }}" + tools: "{{ lookup('file', 'mcp/tools.json') | from_json }}" + limits: "{{ lookup('config', application_id, 'mcp.limits') }}" + schema_sha256: "{{ lookup('config', application_id, 'mcp.tools.schema_sha256') }}" +PRETIX_MCP_UPSTREAM_KEY: "{{ lookup('config', application_id, 'secrets.credentials.mcp_upstream_token') }}" +PRETIX_MCP_UPSTREAM_TEAM: "mcp-readonly" +PRETIX_MCP_UPSTREAM_AUTH_HEADER: "Authorization" +PRETIX_MCP_UPSTREAM_AUTH_FORMAT: "Token {key}" diff --git a/roles/web-app-prometheus/README.md b/roles/web-app-prometheus/README.md index 23c6a3298f..8551083b87 100644 --- a/roles/web-app-prometheus/README.md +++ b/roles/web-app-prometheus/README.md @@ -18,9 +18,13 @@ flowchart LR dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local ๐Ÿ’ป"] dep_svc_net_tor["svc-net-tor ๐Ÿณ๐Ÿ"] dep_web_app_dashboard["web-app-dashboard ๐Ÿณ๐Ÿ"] + dep_web_app_flowise["web-app-flowise ๐Ÿณ๐Ÿ"] + dep_web_app_hermes["web-app-hermes ๐Ÿณ๐Ÿ"] dep_web_app_keycloak["web-app-keycloak ๐Ÿณ๐Ÿ"] dep_web_app_mailu["web-app-mailu ๐Ÿณ๐Ÿ"] dep_web_app_matomo["web-app-matomo ๐Ÿณ๐Ÿ"] + dep_web_app_openclaw["web-app-openclaw ๐Ÿณ๐Ÿ"] + dep_web_app_openwebui["web-app-openwebui ๐Ÿณ๐Ÿ"] dep_web_svc_css["web-svc-css ๐Ÿ’ป"] dep_web_svc_logout["web-svc-logout ๐Ÿณ๐Ÿ"] end @@ -39,6 +43,11 @@ flowchart LR svc_node_exporter["node-exporter"] svc_tor["tor"] svc_container_backup["container_backup"] + svc_prometheusmcp["prometheusmcp"] + svc_openwebui["openwebui"] + svc_hermes["hermes"] + svc_openclaw["openclaw"] + svc_flowise["flowise"] end subgraph dependents [Dependents] dpt_web_app_akaunting["web-app-akaunting ๐Ÿณ๐Ÿ"] @@ -58,9 +67,13 @@ flowchart LR dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup dep_svc_net_tor -. "0..1" .-> svc_tor dep_web_app_dashboard -. "0..1" .-> svc_dashboard + dep_web_app_flowise -. "0..1" .-> svc_flowise + dep_web_app_hermes -. "0..1" .-> svc_hermes dep_web_app_keycloak -. "0..1" .-> svc_sso dep_web_app_mailu -. "0..1" .-> svc_email dep_web_app_matomo -. "0..1" .-> svc_matomo + dep_web_app_openclaw -. "0..1" .-> svc_openclaw + dep_web_app_openwebui -. "0..1" .-> svc_openwebui dep_web_svc_css -. "0..1" .-> svc_css dep_web_svc_logout -. "0..1" .-> svc_logout svc_sso -- "1:1" --> dpt_more @@ -107,19 +120,20 @@ Run the published image to provision the inventory and deploy Prometheus to a ma ```bash APP=web-app-prometheus HOST= +DOMAIN= TLS_MODE=self_signed SSH_PUBLIC_KEY="" docker run --rm -it \ -v "$PWD/inventories:/etc/infinito.nexus/inventories" \ - -e APP="$APP" -e HOST="$HOST" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ + -e APP="$APP" -e HOST="$HOST" -e DOMAIN="$DOMAIN" -e TLS_MODE="$TLS_MODE" -e SSH_PUBLIC_KEY="$SSH_PUBLIC_KEY" \ ghcr.io/infinito-nexus/core/debian bash -c ' INVENTORY=/etc/infinito.nexus/inventories/production infinito administration inventory provision "$INVENTORY" \ --inventory-file "$INVENTORY/devices.yml" \ --host "$HOST" \ --include "$APP" \ - --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && + --vars "{\"TLS_MODE\": \"$TLS_MODE\", \"DOMAIN_PRIMARY\": \"$DOMAIN\", \"users\": {\"administrator\": {\"authorized_keys\": [\"$SSH_PUBLIC_KEY\"]}}}" && infinito administration deploy dedicated "$INVENTORY/devices.yml" \ --password-file "$INVENTORY/.password" \ --diff -vv' diff --git a/roles/web-app-prometheus/files/mcp/tools.json b/roles/web-app-prometheus/files/mcp/tools.json new file mode 100644 index 0000000000..2196ae7670 --- /dev/null +++ b/roles/web-app-prometheus/files/mcp/tools.json @@ -0,0 +1,51 @@ +{ + "prometheus_get_targets": { + "description": "List the scrape targets and their health.", + "method": "GET", + "path": "/api/v1/targets" + }, + "prometheus_query": { + "description": "Run one instant PromQL query.", + "input_schema": { + "properties": { + "query": { + "type": "string" + } + }, + "required": [ + "query" + ], + "type": "object" + }, + "method": "GET", + "path": "/api/v1/query" + }, + "prometheus_query_range": { + "description": "Run one PromQL query over a time range.", + "input_schema": { + "properties": { + "end": { + "type": "string" + }, + "query": { + "type": "string" + }, + "start": { + "type": "string" + }, + "step": { + "type": "string" + } + }, + "required": [ + "query", + "start", + "end", + "step" + ], + "type": "object" + }, + "method": "GET", + "path": "/api/v1/query_range" + } +} diff --git a/roles/web-app-prometheus/files/playwright/playwright.spec.js b/roles/web-app-prometheus/files/playwright/playwright.spec.js index efaff4cb14..c3a8ecf077 100644 --- a/roles/web-app-prometheus/files/playwright/playwright.spec.js +++ b/roles/web-app-prometheus/files/playwright/playwright.spec.js @@ -6,6 +6,8 @@ test.use({ ignoreHTTPSErrors: true }); +require("./test-mcp-guest").register(); + // `docker --env-file` preserves the quotes emitted by `dotenv_quote`, // so normalize these values before building URLs or typing credentials. const oidcIssuerUrl = decodeDotenvQuotedValue(process.env.OIDC_ISSUER_URL); @@ -130,9 +132,8 @@ test("prometheus: admin sso login, verify ui, logout", async ({ page }) => { page.getByRole("link", { name: /^(Graph|Alerts|Status)$/i }).first() ).toBeVisible({ timeout: resolveTimeout(30_000) }); - // 5. Logout via the injected universal-logout control; let the conductor settle. + // 5. Logout via the injected universal-logout control. await inAppLogout(page); - await page.waitForLoadState("networkidle", { timeout: resolveTimeout(45_000) }).catch(() => {}); // 6. Verify session is gone โ€” oauth2-proxy redirects unauthenticated requests to Keycloak. await gotoOnion(page, `${expectedPrometheusBaseUrl}/`, { waitUntil: "domcontentloaded" }); diff --git a/roles/web-app-prometheus/files/playwright/test-mcp-guest.js b/roles/web-app-prometheus/files/playwright/test-mcp-guest.js new file mode 100644 index 0000000000..bcafb06954 --- /dev/null +++ b/roles/web-app-prometheus/files/playwright/test-mcp-guest.js @@ -0,0 +1,10 @@ +const { + mcpEndpointUrl, + registerMcpDisabledState, + registerMcpGuestRejection, +} = require("./mcp-endpoint"); + +exports.register = function () { + registerMcpGuestRejection(mcpEndpointUrl); + registerMcpDisabledState(mcpEndpointUrl); +}; diff --git a/roles/web-app-prometheus/files/test/.nocheck b/roles/web-app-prometheus/files/test/.nocheck new file mode 100644 index 0000000000..2b9d82d840 --- /dev/null +++ b/roles/web-app-prometheus/files/test/.nocheck @@ -0,0 +1 @@ +# nocheck: role-files-layout - Role test harness with test.sh as its entry point; test-e2e-cli stages files/test/ by that fixed path. diff --git a/roles/web-app-prometheus/files/test/test.sh b/roles/web-app-prometheus/files/test/test.sh new file mode 100644 index 0000000000..396e2ef7c7 --- /dev/null +++ b/roles/web-app-prometheus/files/test/test.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# CLI test for web-app-prometheus: the MCP endpoint honours its declared contract. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +bash "${here}/shared/mcp/run.sh" diff --git a/roles/web-app-prometheus/meta/info.yml b/roles/web-app-prometheus/meta/info.yml index 15e4dce9bd..7ac31312d6 100644 --- a/roles/web-app-prometheus/meta/info.yml +++ b/roles/web-app-prometheus/meta/info.yml @@ -2,4 +2,4 @@ logo: class: fa-solid fa-chart-area homepage: https://prometheus.io/ -video: https://www.youtube.com/c/PrometheusIo +video: https://www.youtube.com/watch?v=PzFUwBflXYc diff --git a/roles/web-app-prometheus/meta/mcp.yml b/roles/web-app-prometheus/meta/mcp.yml new file mode 100644 index 0000000000..c45d7d1756 --- /dev/null +++ b/roles/web-app-prometheus/meta/mcp.yml @@ -0,0 +1,41 @@ +--- +classification: adapter_server +direction: server +source_url: https://s.infinito.nexus/code +transport: streamable_http +exposure: internal +auth: bearer_token +auth_subject: service_account +implementation: adapter +credential: + owner: mcp-web-app-prometheus + source: credentials + key: mcp_bearer +endpoint: + service_key: prometheusmcp + path: /mcp + port_key: http +adapter: + type: openapi_allowlist + upstream_api_version: v1 + specification_path: roles/web-app-prometheus/files/mcp/tools.json + specification_sha256: sha256:a57243126b499a407f4630ceabe738677d199de8d89d27aec39299904cb603f1 +limits: + request_bytes: 65536 + response_bytes: 1048576 + timeout_seconds: 15 + concurrent_requests: 4 + page_size: 100 + result_items: 100 + stream_seconds: 300 +tools: + read_probe: + tool: prometheus_get_targets + arguments: {} + allowlist: + - prometheus_get_targets + - prometheus_query + - prometheus_query_range + schema_sha256: sha256:08fe8ce18b8eb0e2268401294a58ca56c6ed0670693075e228603d156ba75538 + read_only_default: true + mutating_tools_enabled: false diff --git a/roles/web-app-prometheus/meta/networks.yml b/roles/web-app-prometheus/meta/networks.yml index 9204aad2b2..97ffc13ee2 100644 --- a/roles/web-app-prometheus/meta/networks.yml +++ b/roles/web-app-prometheus/meta/networks.yml @@ -1,3 +1,8 @@ --- local: subnet: 192.168.56.0/24 +overlay: + modes: [compose, swarm] + topology: shared_net + consumer: + kind: mcp_client diff --git a/roles/web-app-prometheus/meta/rbac.yml b/roles/web-app-prometheus/meta/rbac.yml new file mode 100644 index 0000000000..084e6fbeca --- /dev/null +++ b/roles/web-app-prometheus/meta/rbac.yml @@ -0,0 +1,4 @@ +--- +roles: + mcp: + description: Can drive this application through an MCP client, which acts with the credentials the deployment issued rather than the caller's own diff --git a/roles/web-app-prometheus/meta/secrets.yml b/roles/web-app-prometheus/meta/secrets.yml index 8734781914..6ace45786e 100644 --- a/roles/web-app-prometheus/meta/secrets.yml +++ b/roles/web-app-prometheus/meta/secrets.yml @@ -6,3 +6,9 @@ credentials: alerting_mattermost_webhook_url: description: Mattermost incoming webhook URL for Alertmanager notifications; set credentials.alerting_mattermost_webhook_url on this role in inventory. default: "" + mcp_bearer: + description: "Bearer an MCP client must present to this role's adapter instance. Distinct from the upstream credential the adapter presents, because authenticating + to the application says nothing about who called the adapter." + algorithm: alphanumeric + validation: "^[A-Za-z0-9]{32,}$" + length: 48 diff --git a/roles/web-app-prometheus/meta/services.yml b/roles/web-app-prometheus/meta/services.yml index 7acfaa0ffa..f4ded909b7 100644 --- a/roles/web-app-prometheus/meta/services.yml +++ b/roles/web-app-prometheus/meta/services.yml @@ -97,8 +97,8 @@ blackbox-exporter: version: v0.28.0 name: prometheus-blackbox cpus: "0.1" - mem_reservation: 32m - mem_limit: 64m + mem_reservation: 16m + mem_limit: 24m pids_limit: 64 min_storage: 218MB ports: @@ -144,3 +144,41 @@ container_backup: # nocheck: bond-baseline backup host joins outside the variant bond: 1 enabled: "{{ 'svc-bkp-volume-2-local' in group_names }}" shared: true +# nocheck: playwright-service-flag internal adapter sidecar, covered by the role's MCP guest spec +# nocheck: dockerfile-custom the Dockerfile is owned by svc-ai-mcp-adapter and staged per instance, so every adapter-backed provider shares one audited build +# nocheck: dynamic-flag the sidecar tracks this role's own mcp flag, not another role's presence; a group_names expression would decide its exposure from an unrelated deployment +prometheusmcp: + enabled: "{{ lookup('config', 'web-app-prometheus', 'mcp.enabled') | bool }}" + shared: false + image: python + # nocheck: docker-version base of the self-built stdlib adapter, not the served application + version: "3.13.15-slim" + custom: true + name: prometheusmcp + cpus: "0.25" + mem_reservation: 16m + mem_limit: 24m + pids_limit: 64 + ports: + internal: + http: 8080 +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openwebui: + bond: 0.5 + enabled: "{{ 'web-app-openwebui' in group_names }}" + shared: "{{ 'web-app-openwebui' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +hermes: + bond: 0.5 + enabled: "{{ 'web-app-hermes' in group_names }}" + shared: "{{ 'web-app-hermes' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +openclaw: + bond: 0.5 + enabled: "{{ 'web-app-openclaw' in group_names }}" + shared: "{{ 'web-app-openclaw' in group_names }}" +# nocheck: playwright-service-flag MCP pairing is proven by the role's own MCP spec, not by a per-consumer gate +flowise: + bond: 0.5 + enabled: "{{ 'web-app-flowise' in group_names }}" + shared: "{{ 'web-app-flowise' in group_names }}" diff --git a/roles/web-app-prometheus/meta/tests.yml b/roles/web-app-prometheus/meta/tests.yml new file mode 100644 index 0000000000..28bea0efe2 --- /dev/null +++ b/roles/web-app-prometheus/meta/tests.yml @@ -0,0 +1,3 @@ +--- +cli: + timeout: 900 diff --git a/roles/web-app-prometheus/meta/variants.yml b/roles/web-app-prometheus/meta/variants.yml index d3a16fa6b8..ef0913b634 100644 --- a/roles/web-app-prometheus/meta/variants.yml +++ b/roles/web-app-prometheus/meta/variants.yml @@ -28,6 +28,54 @@ shared: true tor: enabled: true + openwebui: + enabled: false + shared: false + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false + flowise: + enabled: false + shared: false +- services: + container_backup: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + dashboard: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + email: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + logout: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + matomo: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + sso: + enabled: true + shared: true + css: + enabled: false + shared: false # nocheck: variants-static-override backup shared stays literally true + tor: + enabled: true + openwebui: + enabled: true + shared: true + hermes: + enabled: true + shared: true + openclaw: + enabled: true + shared: true + flowise: + enabled: true + shared: true - services: container_backup: enabled: false @@ -52,3 +100,15 @@ shared: false # nocheck: variants-static-override backup shared stays literally true tor: enabled: true + openwebui: + enabled: false + shared: false + hermes: + enabled: false + shared: false + openclaw: + enabled: false + shared: false + flowise: + enabled: false + shared: false diff --git a/roles/web-app-prometheus/tasks/00_core.yml b/roles/web-app-prometheus/tasks/00_core.yml index 5ff13599bd..1330796833 100644 --- a/roles/web-app-prometheus/tasks/00_core.yml +++ b/roles/web-app-prometheus/tasks/00_core.yml @@ -1,6 +1,11 @@ --- - include_tasks: utils/once/flag.yml +- name: "๐Ÿ”Œ Stage the MCP adapter instance for {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/instance.yml') }}" + vars: + mcp_adapter_instance_dir: "{{ PROMETHEUS_MCP_INSTANCE_DIR }}" + when: PROMETHEUS_MCP_ENABLED | bool - name: "๐Ÿงฉ load docker and proxy for '{{ application_id }}'" include_role: name: sys-stk-backend @@ -13,12 +18,6 @@ state: directory mode: "0755" -- name: "๐Ÿš€ Deploy prometheus nginx http-block config" - stack_host_template: - src: "roles/web-app-prometheus/templates/nginx/prometheus.conf.j2" - dest: "{{ [ lookup('nginx','directories.configuration.global'), 'prometheus.conf' ] | path_join }}" - notify: restart-openresty - - name: "๐Ÿ“„ Render Prometheus config files (local + swarm peers)" ansible.builtin.include_tasks: file: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/render_replicated_templates.yml') }}" @@ -52,3 +51,16 @@ vars: domain: "{{ lookup('domain', application_id) }}" http_port: "{{ lookup('config', application_id, 'services.prometheus.ports.local.http') }}" + +- name: "๐Ÿš€ Deploy prometheus nginx http-block config" + stack_host_template: + src: "roles/web-app-prometheus/templates/nginx/prometheus.conf.j2" + dest: "{{ [ lookup('nginx','directories.configuration.global'), 'prometheus.conf' ] | path_join }}" + notify: restart-openresty + +- name: "๐Ÿงฑ Rebuild the MCP adapter of {{ application_id }}" + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/svc-ai-mcp-adapter/tasks/rebuild.yml') }}" + when: PROMETHEUS_MCP_ENABLED | bool + +- name: "๐Ÿšฟ Flush compose handlers for {{ application_id }}" + ansible.builtin.meta: flush_handlers diff --git a/roles/web-app-prometheus/templates/compose.yml.j2 b/roles/web-app-prometheus/templates/compose.yml.j2 index ad57407c8a..792e93243e 100644 --- a/roles/web-app-prometheus/templates/compose.yml.j2 +++ b/roles/web-app-prometheus/templates/compose.yml.j2 @@ -11,6 +11,7 @@ command: - "--config.file={{ PROMETHEUS_CONFIG_DOCKER }}" - "--storage.tsdb.path={{ lookup('volume', 'web-app-prometheus', 'data').target }}" + - "--query.timeout={{ PROMETHEUS_QUERY_TIMEOUT }}" - "--web.enable-lifecycle" {{ lookup('container_volumes', service_name) | indent(4) }} @@ -70,6 +71,33 @@ - "--collector.filesystem.mount-points-exclude=^/(sys|proc|dev|host|etc)($$|/)" - "--collector.textfile.directory={{ lookup('volume', 'web-app-prometheus', 'metrics_textfile').targets['node-exporter'] }}" + {% if PROMETHEUS_MCP_ENABLED | bool %} + {% set service_name = PROMETHEUS_MCP_SERVICE_KEY %} + {{ service_name }}: + {% include 'roles/sys-svc-container/templates/base.yml.j2' %} + {{ lookup('container_image', application_id, 'prometheusmcp') }} + build: + context: {{ PROMETHEUS_MCP_INSTANCE_DIR }} + dockerfile: Dockerfile + args: + MCP_ADAPTER_BASE_IMAGE: {{ lookup('config', application_id, 'services.prometheusmcp.image') }} + MCP_ADAPTER_BASE_VERSION: "{{ lookup('config', application_id, 'services.prometheusmcp.version') }}" + {{ lookup('compose_only', 'container_name', PROMETHEUS_MCP_CONTAINER) }} + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + environment: + ADAPTER_CONTRACT: {{ PROMETHEUS_MCP_CONTRACT | to_json | to_json | replace('$', '$$') }} + ADAPTER_BEARER: {{ PROMETHEUS_MCP_BEARER | to_json }} + ADAPTER_PORT: "{{ PROMETHEUS_MCP_PORT }}" + ADAPTER_UPSTREAM_KEY: {{ PROMETHEUS_MCP_UPSTREAM_KEY | to_json }} + expose: + - "{{ PROMETHEUS_MCP_PORT }}" + {{ lookup('container_networks', own_network_only=True, provider_self_alias=False) | indent(4) }} + {% endif %} + {{ lookup('compose_volumes') }} {{ lookup('compose_networks') }} {% for metrics_app_id in lookup('native_metrics_apps') %} diff --git a/roles/web-app-prometheus/templates/javascript.js.j2 b/roles/web-app-prometheus/templates/javascript.js.j2 index 0b94a7e1c5..32f43e0657 100644 --- a/roles/web-app-prometheus/templates/javascript.js.j2 +++ b/roles/web-app-prometheus/templates/javascript.js.j2 @@ -1,5 +1,5 @@ (function () { - const LOGOUT_URL = "{{ OIDC.CLIENT.LOGOUT_URL }}"; + const LOGOUT_URL = {{ lookup('sso', application_id, 'logout_url') | to_json }}; const INJECTED_ATTR = "data-injected-logout"; const LOGOUT_SVG = '" or "defaults_"). @@ -32,6 +36,7 @@ class TestVariableDefinitions(unittest.TestCase): self.var_files: list[str] = [] roles_prefix = str(Path(self.project_root) / "roles") + "/" group_vars_prefix = str(Path(self.project_root) / "group_vars" / "all") + "/" + inventory_prefix = str(Path(self.project_root) / "inventories") + "/" def _is_role_var_file(p: str) -> bool: if not p.startswith(roles_prefix): @@ -40,9 +45,13 @@ class TestVariableDefinitions(unittest.TestCase): return len(parts) >= 3 and parts[1] in ("vars", "defaults") for p in iter_project_files(extensions=(".yml",)): - if _is_role_var_file(p) or ( - p.startswith(group_vars_prefix) - and "/" not in p[len(group_vars_prefix) :] + if ( + _is_role_var_file(p) + or ( + p.startswith(group_vars_prefix) + and "/" not in p[len(group_vars_prefix) :] + ) + or p.startswith(inventory_prefix) ): self.var_files.append(p) @@ -237,6 +246,7 @@ class TestVariableDefinitions(unittest.TestCase): "ansible_memtotal_mb", "omit", "group_names", + "ansible_parent_role_names", "ansible_processor_vcpus", "ansible_service_mgr", "ansible_distribution_release", @@ -284,6 +294,7 @@ class TestVariableDefinitions(unittest.TestCase): "ansible_memtotal_mb", "omit", "group_names", + "ansible_parent_role_names", "ansible_processor_vcpus", "ansible_distribution_release", "ansible_distribution", diff --git a/tests/integration/ansible/lookups/config/test_credentials_roundtrip.py b/tests/integration/ansible/lookups/config/test_credentials_roundtrip.py index 616ef21027..59df096f9d 100644 --- a/tests/integration/ansible/lookups/config/test_credentials_roundtrip.py +++ b/tests/integration/ansible/lookups/config/test_credentials_roundtrip.py @@ -5,7 +5,7 @@ ``applications..secrets.credentials``; every role then reads them through ``lookup('config', , 'secrets.credentials.')``. Nothing checked that the two agree on where the values live, which is exactly what the rename from -``meta/schema.yml`` put at risk. +``meta/secrets.yml`` put at risk. The second test guards the caching side of that seam: the assembled defaults must not reach into the YAML cache and truncate the schema every later reader diff --git a/tests/integration/ansible/lookups/config/test_wildcard_paths.py b/tests/integration/ansible/lookups/config/test_wildcard_paths.py index 8eba46fa82..1d038ec24f 100644 --- a/tests/integration/ansible/lookups/config/test_wildcard_paths.py +++ b/tests/integration/ansible/lookups/config/test_wildcard_paths.py @@ -9,7 +9,10 @@ against the same fallback chain the literal-path test uses. The classifier owns the rule "concat-pattern match โ†’ wildcard path keyed by `(role_id, wildcard_path)`". `role_id` resolves from the literal app argument when present, otherwise from the file's -``roles//...`` location. +``roles//...`` location -- and then only when that role declares +an ``application_id`` of its own. A role that does not is rendering the +template on another role's behalf, so its own defaults are the wrong +thing to validate the path against. """ import unittest @@ -33,6 +36,7 @@ from ._validate import match_wildcard_path, match_wildcard_segment def _build_wildcard_paths( matches: Iterable[LookupMatch], + roles_with_application_id: frozenset[str], ) -> dict[tuple[str, str], list[tuple]]: out: dict[tuple[str, str], list[tuple]] = {} for m in matches: @@ -45,8 +49,8 @@ def _build_wildcard_paths( role_id = m.app_literal else: role_id = role_id_from_path(m.file) - if role_id is None: - continue + if role_id is None or role_id not in roles_with_application_id: + continue out.setdefault((role_id, wildcard_path), []).append((m.file, m.lineno)) return out @@ -55,7 +59,9 @@ class TestWildcardPaths(unittest.TestCase): @classmethod def setUpClass(cls): cls.ctx = get_context() - cls.wildcard_paths = _build_wildcard_paths(iter_matches()) + cls.wildcard_paths = _build_wildcard_paths( + iter_matches(), cls.ctx.roles_with_application_id + ) def test_wildcard_paths(self): if not self.wildcard_paths: diff --git a/tests/integration/ansible/lookups/test_objstore_consumers.py b/tests/integration/ansible/lookups/test_objstore_consumers.py index 25e4852fdb..15ddbc9236 100644 --- a/tests/integration/ansible/lookups/test_objstore_consumers.py +++ b/tests/integration/ansible/lookups/test_objstore_consumers.py @@ -42,8 +42,8 @@ def _variables(applications: dict, group_names: list[str]) -> dict: return { "applications": applications, "users": {}, - "DOMAIN_PRIMARY": "infinito.example", - "SYSTEM_EMAIL_DOMAIN": "infinito.example", + "DOMAIN_PRIMARY": "infinito.test", + "SYSTEM_EMAIL_DOMAIN": "infinito.test", "DIR_COMPOSITIONS": "/opt/compose/", "group_names": list(group_names), } diff --git a/tests/integration/iam/passwords/test_quote_in_shell.py b/tests/integration/iam/passwords/test_quote_in_shell.py index af72c5ce0a..280998ecaa 100644 --- a/tests/integration/iam/passwords/test_quote_in_shell.py +++ b/tests/integration/iam/passwords/test_quote_in_shell.py @@ -5,6 +5,7 @@ import unittest from dataclasses import dataclass from typing import TYPE_CHECKING +from utils.annotations.suppress import is_suppressed_at from utils.cache.files import read_text from . import PROJECT_ROOT @@ -22,6 +23,8 @@ STDIN_KEY_RE = re.compile(r"^\s*stdin\s*:\s*[|>]") QUOTE_CHARS = {"'", '"'} +RULE = "password-quote" + @dataclass(frozen=True) class Finding: @@ -119,7 +122,9 @@ def _mask_stdin_subblocks(block: str) -> str: return "\n".join(out) -def _scan_shell_block(file_path: Path, start_line: int, block: str) -> list[Finding]: +def _scan_shell_block( + file_path: Path, start_line: int, block: str, file_lines: list[str] +) -> list[Finding]: findings: list[Finding] = [] block = _mask_stdin_subblocks(block) @@ -131,6 +136,11 @@ def _scan_shell_block(file_path: Path, start_line: int, block: str) -> list[Find rel_line = block.count("\n", 0, m.start()) line_no = start_line + rel_line + if is_suppressed_at(file_lines, line_no, RULE) or is_suppressed_at( + file_lines, start_line, RULE + ): + continue + snippet = "{{ " + " ".join(expr.split()) + " }}" if not QUOTE_FILTER_RE.search(expr): @@ -170,8 +180,9 @@ class TestPasswordQuoteInShellTasks(unittest.TestCase): text = read_text(str(yml)) except UnicodeDecodeError: continue + lines = text.splitlines() for start_line, block in _collect_shell_blocks(text): - all_findings.extend(_scan_shell_block(yml, start_line, block)) + all_findings.extend(_scan_shell_block(yml, start_line, block, lines)) if all_findings: msg = "\n".join(f.format() for f in all_findings) @@ -179,6 +190,11 @@ class TestPasswordQuoteInShellTasks(unittest.TestCase): "Violations found in shell tasks (password expressions must use '| quote' " "and must not be double-quoted):\n" f"{msg}\n" + f"The token is matched anywhere in the expression, so a path or a " + f"filename carrying it trips this too. Suppress such a case with " + f"'# nocheck: {RULE} ' on or above the task's shell: key -- " + f"not inside the scalar, where a folded block would turn the marker " + f"into a shell comment and swallow the rest of the command.\n" ) diff --git a/tests/integration/iam/sso/test_sso_proxy_restarts_on_config_change.py b/tests/integration/iam/sso/test_sso_proxy_restarts_on_config_change.py new file mode 100644 index 0000000000..e9d2eaf688 --- /dev/null +++ b/tests/integration/iam/sso/test_sso_proxy_restarts_on_config_change.py @@ -0,0 +1,43 @@ +import re +import unittest + +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +SSO_PROXY_TASKS = PROJECT_ROOT / "roles/web-app-keycloak/tasks/sso_proxy.yml" +CONTAINER_TEMPLATE = ( + PROJECT_ROOT / "roles/web-app-keycloak/templates/sso_proxy/container.yml.j2" +) +_RENDERED_CFG = re.compile(r"src:\s*\"\{\{\s*lookup\('path_absolute',\s*'([^']+)'\)") +_HASHED_CFG = re.compile( + r"^\s+labels:\n\s+[\w.-]+:\s*\"\{\{\s*lookup\('template',\s*" + r"lookup\('path_absolute',\s*'([^']+)'\).*\|\s*hash\('sha256'\)\s*\}\}\"", + re.MULTILINE, +) + + +class TestSsoProxyRestartsOnConfigChange(unittest.TestCase): + def test_the_sidecar_labels_a_hash_of_the_config_it_mounts(self) -> None: + rendered = _RENDERED_CFG.search(read_text(str(SSO_PROXY_TASKS))) + hashed = _HASHED_CFG.search(read_text(str(CONTAINER_TEMPLATE))) + self.assertIsNotNone( + rendered, f"{SSO_PROXY_TASKS} no longer renders a path_absolute src" + ) + self.assertIsNotNone( + hashed, + "the sso-proxy service must carry a label hashing its rendered " + "config: the config is a bind mount oauth2-proxy reads at start, " + "and docker stack deploy only restarts a service whose spec " + "changed, so a rotated redis password or client secret leaves " + "the running sidecar on the old one (WRONGPASS, HTTP 500)", + ) + self.assertEqual( + rendered.group(1), + hashed.group(1), + "the label must hash the same template sso_proxy.yml renders", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/meta/env/test_bare_bootstrap.py b/tests/integration/meta/env/test_bare_bootstrap.py index 32ad43f6b2..92d924688e 100644 --- a/tests/integration/meta/env/test_bare_bootstrap.py +++ b/tests/integration/meta/env/test_bare_bootstrap.py @@ -58,11 +58,11 @@ class TestBareBootstrap(unittest.TestCase): return result.stdout.strip() def test_generator_runs_without_third_party_modules(self) -> None: - self.assertTrue(int(self._run({})) > 0) + self.assertGreater(int(self._run({})), 0) def test_generator_runs_on_the_github_actions_branch(self) -> None: overlay = {"GITHUB_ACTIONS": "true", "GITHUB_REPOSITORY_OWNER": "acme"} - self.assertTrue(int(self._run(overlay)) > 0) + self.assertGreater(int(self._run(overlay)), 0) if __name__ == "__main__": diff --git a/tests/integration/meta/workflows/test_chunk_blocks_cover_the_budget.py b/tests/integration/meta/workflows/test_chunk_blocks_cover_the_budget.py new file mode 100644 index 0000000000..0c9659d8d9 --- /dev/null +++ b/tests/integration/meta/workflows/test_chunk_blocks_cover_the_budget.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +import math +import re +import unittest + +from cli.meta.ci import slots +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any + +WORKFLOW = PROJECT_ROOT / ".github/workflows/call-orchestrator.yml" + + +class TestChunkBlocksCoverTheBudget(unittest.TestCase): + def test_the_declared_block_count_matches_the_orchestrator(self) -> None: + jobs = load_yaml_any(str(WORKFLOW))["jobs"] + declared = [ + name for name in jobs if re.fullmatch(r"test-deploy-chunk-\d+", name) + ] + self.assertEqual( + len(declared), + slots.chunk_blocks(), + "INFINITO_CI_MAX_CHUNKS must equal the chunk jobs call-orchestrator.yml " + "declares; a plan larger than the chain silently drops its tail", + ) + + def test_a_short_priority_chunk_strands_no_budget(self) -> None: + filled = math.ceil(slots.available() / slots.chunk_size()) + self.assertGreaterEqual( + slots.chunk_blocks(), + filled + 1, + "a priority chunk shorter than a block still occupies one, so the " + "regular rows need a block beyond what the budget fills to spend " + "the rest of it", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/meta/workflows/test_chunk_gate_is_transitive.py b/tests/integration/meta/workflows/test_chunk_gate_is_transitive.py new file mode 100644 index 0000000000..96193a1523 --- /dev/null +++ b/tests/integration/meta/workflows/test_chunk_gate_is_transitive.py @@ -0,0 +1,86 @@ +"""The chunk gate must stop the chain, not just the next chunk. + +``chunk_gate`` promises to "stop the chunk chain at its first failed chunk". +A gate that reads only its immediate predecessor cannot keep that promise: a +blocked chunk reports ``skipped``, ``skipped`` is what the gate accepts, and +the chunk after it runs. Exactly one chunk falls out, the rest of the chain +carries on, and the coverage that chunk owned disappears with nothing reporting +it. + +Run 33279942812 is the case: chunk 0 red, chunk 1 skipped by the gate, chunk 2 +deployed 81 jobs against a chain that was supposed to have stopped. + +Every chunk therefore names every chunk before it, in the gate and in ``needs``. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any + +WORKFLOW = PROJECT_ROOT / ".github/workflows/call-orchestrator.yml" +JOB = "test-deploy-chunk-{index}" +_RESULT_RE = re.compile(r"needs\.test-deploy-chunk-(\d+)\.result") + + +def _chunks() -> dict[int, dict]: + """Return the chunk jobs of the orchestrator, keyed by index.""" + jobs = load_yaml_any(str(WORKFLOW))["jobs"] + return { + int(name.rsplit("-", 1)[1]): body + for name, body in jobs.items() + if re.fullmatch(r"test-deploy-chunk-\d+", name) + } + + +class TestChunkGateIsTransitive(unittest.TestCase): + def setUp(self) -> None: + self.chunks = _chunks() + + def test_the_orchestrator_still_has_a_chunk_chain(self) -> None: + """Without one, every assertion below would pass over nothing.""" + self.assertGreater(len(self.chunks), 1) + self.assertEqual(sorted(self.chunks), list(range(len(self.chunks)))) + + def test_a_gate_reads_every_chunk_before_it(self) -> None: + for index, body in sorted(self.chunks.items()): + with self.subTest(chunk=index): + read = {int(m) for m in _RESULT_RE.findall(body["if"])} + self.assertEqual( + set(range(index)), + read, + f"chunk {index} gates on {sorted(read)}; a chunk it does not " + f"read can fail without stopping it", + ) + + def test_the_finish_job_needs_every_chunk(self) -> None: + """A chunk it does not need can fail while the pipeline reports green.""" + done = load_yaml_any(str(WORKFLOW))["jobs"]["done"] + needed = { + int(name.rsplit("-", 1)[1]) + for name in done["needs"] + if re.fullmatch(r"test-deploy-chunk-\d+", name) + } + self.assertEqual(set(self.chunks), needed) + + def test_a_gate_needs_every_chunk_it_reads(self) -> None: + """An unneeded job's result is empty, which the gate would let pass.""" + for index, body in sorted(self.chunks.items()): + with self.subTest(chunk=index): + read = {int(m) for m in _RESULT_RE.findall(body["if"])} + needed = { + int(name.rsplit("-", 1)[1]) + for name in body["needs"] + if re.fullmatch(r"test-deploy-chunk-\d+", name) + } + self.assertTrue( + read <= needed, + f"chunk {index} reads {sorted(read - needed)} without needing it", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/meta/workflows/test_ci_inputs_documented.py b/tests/integration/meta/workflows/test_ci_inputs_documented.py new file mode 100644 index 0000000000..3676d7d1aa --- /dev/null +++ b/tests/integration/meta/workflows/test_ci_inputs_documented.py @@ -0,0 +1,96 @@ +"""Integration guard: every repository secret and variable a workflow reads is documented. + +Background +========== +A `${{ secrets.X }}` or `${{ vars.X }}` reference is a contract with whoever +administers the repository, and an unset one resolves to the empty string +rather than to an error. An undocumented name is therefore invisible twice: the +administrator cannot know to set it, and the run that needed it degrades +silently. + +The guard also catches the inverse drift, a doc naming a variable the workflows +no longer read under that name, because it compares the reference against the +page rather than the page against itself. + +Scope +===== +Every `${{ secrets. }}` and `${{ vars. }}` on a non-comment line of +`.github/workflows/*.yml`. Secrets MUST appear in `secrets.md`, variables in +`configuration.md`, both under `docs/contributing/tools/github/actions/`. + +Exemptions +========== +`GITHUB_TOKEN` is minted by GitHub for every run; it is not administered and +cannot be set. Any other exemption belongs in `_PROVIDED_SECRETS` with the +reason it is not administrator-supplied. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +WORKFLOWS = PROJECT_ROOT / ".github" / "workflows" +DOCS = PROJECT_ROOT / "docs" / "contributing" / "tools" / "github" / "actions" + +_REFERENCE = re.compile(r"\$\{\{\s*(secrets|vars)\.([A-Za-z_][A-Za-z0-9_]*)") + +_PROVIDED_SECRETS = frozenset({"GITHUB_TOKEN"}) + +_PAGES = {"secrets": "secrets.md", "vars": "configuration.md"} + + +def _referenced() -> dict[str, set[str]]: + """Names the workflows actually read, keyed by `secrets` / `vars`. + + A commented-out line is skipped: it documents an option nobody has taken, + and demanding a doc row for it would describe an input the run never asks + for. + """ + found: dict[str, set[str]] = {"secrets": set(), "vars": set()} + for workflow in sorted(WORKFLOWS.glob("*.yml")): + for line in read_text(str(workflow)).splitlines(): + if line.lstrip().startswith("#"): + continue + for kind, name in _REFERENCE.findall(line): + if kind == "secrets" and name in _PROVIDED_SECRETS: + continue + found[kind].add(name) + return found + + +class TestCiInputsDocumented(unittest.TestCase): + def test_every_referenced_secret_and_variable_is_documented(self) -> None: + offenders: list[str] = [] + for kind, names in _referenced().items(): + documented = read_text(str(DOCS / _PAGES[kind])) + offenders.extend( + f"{kind}.{name} is read by a workflow but absent from " + f"docs/contributing/tools/github/actions/{_PAGES[kind]}" + for name in sorted(names) + if name not in documented + ) + + if offenders: + self.fail( + f"{len(offenders)} CI input(s) undocumented:\n" + + "\n".join(f"- {o}" for o in offenders) + + "\n\nAn unset secret or variable resolves to the empty string, " + "so an undocumented one degrades a run instead of failing it. " + "Add a row naming the workflow, what it enables, and what " + "happens while it is unset." + ) + + def test_the_guard_reads_workflows_that_exist(self) -> None: + self.assertTrue( + any(WORKFLOWS.glob("*.yml")), + f"no workflow files under {WORKFLOWS}; the guard would pass vacuously", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/meta/workflows/test_ci_retrigger_inputs.py b/tests/integration/meta/workflows/test_ci_retrigger_inputs.py index 16470e7c05..f5588594c2 100644 --- a/tests/integration/meta/workflows/test_ci_retrigger_inputs.py +++ b/tests/integration/meta/workflows/test_ci_retrigger_inputs.py @@ -43,11 +43,11 @@ _VALUES = { "filesystem": "btrfs", "tor": "enforced", "offset": "40", + "chunk_size": "25", "chunk_gate": "false", "sweep": "7", "workspace": "true", "workspace_track": "compose", - "instructions": "false", } """A value for every dispatch input, distinct from that input's default so a dropped one shows up as a missing key rather than as a coincidence.""" diff --git a/tests/integration/meta/workflows/test_orchestrator_stays_in_the_entry_group.py b/tests/integration/meta/workflows/test_orchestrator_stays_in_the_entry_group.py new file mode 100644 index 0000000000..ceb3dfbeca --- /dev/null +++ b/tests/integration/meta/workflows/test_orchestrator_stays_in_the_entry_group.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +import re +import unittest + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_any + +WORKFLOWS = PROJECT_ROOT / ".github/workflows" +ORCHESTRATOR = WORKFLOWS / "call-orchestrator.yml" +_CALLS_ORCHESTRATOR = re.compile( + r"uses:\s*\./\.github/workflows/call-orchestrator\.yml" +) +_CALLED = re.compile(r"uses:\s*\./\.github/workflows/(call-[\w-]+\.yml)") +DEDUPLICATING_BUILDS = ("call-images-build-ci.yml", "call-images-mirror-missing.yml") + + +def _entries() -> list: + return [ + path + for path in sorted(WORKFLOWS.glob("*.yml")) + if _CALLS_ORCHESTRATOR.search(read_text(str(path))) + ] + + +class TestOrchestratorStaysInTheEntryGroup(unittest.TestCase): + def test_the_orchestrator_declares_no_concurrency_of_its_own(self) -> None: + self.assertNotIn( + "concurrency", + load_yaml_any(str(ORCHESTRATOR)), + "a called workflow's own group takes its jobs out of the entry's " + "group, and the entry's cancel-in-progress then no longer reaches " + "them: run 34614940508 kept 20 runners for seven hours after its " + "successor arrived, because only chunk jobs were still alive", + ) + + def test_the_chain_below_it_declares_no_group_it_does_not_need(self) -> None: + called = sorted(set(_CALLED.findall(read_text(str(ORCHESTRATOR))))) + self.assertTrue(called) + for name in called: + if name in DEDUPLICATING_BUILDS: + continue + with self.subTest(called=name): + self.assertNotIn( + "concurrency", + load_yaml_any(str(WORKFLOWS / name)), + f"{name} runs inside an orchestrator run, so its own group " + "takes those jobs out of the entry's; a superseded run " + "whose last live job is one of them keeps its runners. " + f"Only {' and '.join(DEDUPLICATING_BUILDS)} may carry one, " + "because their group deduplicates image builds across runs " + "rather than scoping a single run", + ) + + def test_every_entry_that_calls_it_carries_a_cancelling_group(self) -> None: + entries = _entries() + self.assertTrue(entries) + for path in entries: + with self.subTest(entry=path.name): + concurrency = load_yaml_any(str(path)).get("concurrency") or {} + self.assertTrue( + concurrency.get("group"), + f"{path.name} calls the orchestrator, so it owns the " + "grouping the orchestrator no longer declares", + ) + self.assertIn( + "cancel-in-progress", + concurrency, + f"{path.name} must say whether a newer run supersedes a " + "running one; without it the deploy chunks run twice", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/meta/workflows/test_variant_payload_scope.py b/tests/integration/meta/workflows/test_variant_payload_scope.py new file mode 100644 index 0000000000..00a9d18967 --- /dev/null +++ b/tests/integration/meta/workflows/test_variant_payload_scope.py @@ -0,0 +1,96 @@ +"""The swarm matrix bakes a variant payload for every app it deploys.""" + +from __future__ import annotations + +import unittest +from typing import ClassVar + +from cli.administration.deploy.development.inventory.payload import ( + _resolve_variant_payloads, + get_variant_overrides_only, +) +from cli.administration.deploy.development.inventory.planner import ( + plan_dev_inventory_matrix, +) +from utils.cache.files import PROJECT_ROOT +from utils.tests.swarm.derive_includes import ( + _EXPLICIT_INCLUDES, + derive_includes, + variant_scope, +) + +_ROLES_DIR = str(PROJECT_ROOT / "roles") + + +def _rounds(primary: str) -> list[tuple]: + return plan_dev_inventory_matrix( + roles_dir=_ROLES_DIR, + primary_apps=[primary], + base_inventory_dir="/tmp/variant-payload-scope", + ) + + +class TestVariantPayloadScope(unittest.TestCase): + PRIMARIES: ClassVar[tuple[str, ...]] = ( + "svc-ai-litellm", + "web-app-bigbluebutton", + "web-app-peertube", + "web-app-nextcloud", + ) + + def test_every_deployed_app_receives_its_declared_override(self) -> None: + overrides = get_variant_overrides_only(roles_dir=_ROLES_DIR) + for primary in self.PRIMARIES: + for round_index, _inv, round_variants, _include, *_ in _rounds(primary): + scope = variant_scope(primary, variants=round_variants) + payloads = _resolve_variant_payloads( + roles_dir=_ROLES_DIR, + include=scope, + active_variants=round_variants, + ) + for app in derive_includes(primary, variants=round_variants): + declared = overrides.get(app) or [] + if not declared: + continue + index = round_variants.get(app, 0) + if not 0 <= index < len(declared): + index = 0 + if not declared[index] or app in _EXPLICIT_INCLUDES: + continue + self.assertIn( + app, + payloads, + f"{primary}#{round_index} deploys {app}, whose variants.yml " + f"declares an override, but the inventory bakes none, so it " + f"silently runs on its base config", + ) + + def test_a_dependency_keeps_its_override_when_the_include_collapses(self) -> None: + primary = "svc-ai-litellm" + for round_index, _inv, round_variants, round_include, *_ in _rounds(primary): + if "web-app-keycloak" not in variant_scope( + primary, variants=round_variants + ): + continue + payloads = _resolve_variant_payloads( + roles_dir=_ROLES_DIR, + include=variant_scope(primary, variants=round_variants), + active_variants=round_variants, + ) + realm = ( + payloads.get("web-app-keycloak", {}) + .get("services", {}) + .get("keycloak", {}) + .get("realm", {}) + ) + self.assertIs( + realm.get("totp_enabled"), + False, + f"{primary}#{round_index} deploys keycloak with " + f"{len(round_include)} planned app(s); without its variant override " + f"the realm demands CONFIGURE_TOTP and every SSO persona times out", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/roles/meta/services/repositories/test_declared_in_services.py b/tests/integration/roles/meta/services/repositories/test_declared_in_services.py index f79749ee30..d3336c8d5d 100644 --- a/tests/integration/roles/meta/services/repositories/test_declared_in_services.py +++ b/tests/integration/roles/meta/services/repositories/test_declared_in_services.py @@ -1,6 +1,7 @@ """Integration guard: every git-clone URL referenced inside a role (Dockerfile, tasks, templates, files) MUST be declared as a -`repository:` value in that role's ``meta/services.yml``. +`repository:` value in that role's ``meta/services.yml`` or in one of +its ``meta/addons/.yml`` files, which is where an addon pins itself. The same applies symmetrically to git refs: any `compose_repository_ref` or `--branch ` (clone) value that ties to a declared @@ -39,7 +40,7 @@ import unittest from utils.cache.files import iter_project_files, read_text from utils.cache.yaml import load_yaml_any -from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.roles.mapping import ROLE_DIR_META_ADDONS, ROLE_FILE_META_SERVICES from . import PROJECT_ROOT @@ -106,18 +107,20 @@ class TestDeclaredInServices(unittest.TestCase): for role_dir in sorted(p for p in ROLES_DIR.iterdir() if p.is_dir()): role_name = role_dir.name services_path = role_dir / ROLE_FILE_META_SERVICES - declared = ( - _collect_declared_repositories(services_path) - if services_path.is_file() - else set() - ) + declaration_paths = [services_path] + declaration_paths += sorted((role_dir / ROLE_DIR_META_ADDONS).glob("*.yml")) + declared: set[str] = set() + for declaration_path in declaration_paths: + if declaration_path.is_file(): + declared |= _collect_declared_repositories(declaration_path) + declaration_names = {str(p) for p in declaration_paths} seen_paths: set[str] = set() for fpath in _iter_role_files(role_dir): if fpath in seen_paths: continue seen_paths.add(fpath) - if fpath.endswith("/" + ROLE_FILE_META_SERVICES): + if fpath in declaration_names: continue try: text = read_text(fpath) @@ -140,7 +143,8 @@ class TestDeclaredInServices(unittest.TestCase): f"{role_name}: {rel}:{line_no} " f"references `{url}` but it is not declared " f"as `repository:` in " - f"{role_name}/{ROLE_FILE_META_SERVICES}" + f"{role_name}/{ROLE_FILE_META_SERVICES} " + f"or {role_name}/{ROLE_DIR_META_ADDONS}/" ) if offenders: diff --git a/tests/integration/roles/meta/services/test_mcp_disabled_has_no_surface.py b/tests/integration/roles/meta/services/test_mcp_disabled_has_no_surface.py new file mode 100644 index 0000000000..339d904c41 --- /dev/null +++ b/tests/integration/roles/meta/services/test_mcp_disabled_has_no_surface.py @@ -0,0 +1,68 @@ +"""Every MCP server role gates its surface on the role's MCP-enabled flag. + +Without the gate a deployment that switches MCP off would still render the +endpoint, so the flag would document an intent the deployment does not honour. +""" + +from __future__ import annotations + +import unittest + +from utils.cache.files import iter_project_files_with_content +from utils.cache.yaml import load_yaml_any +from utils.roles.applications.mcp import MCP_SERVER_DIRECTIONS +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +ROLES_DIR = PROJECT_ROOT / "roles" + +GATE_MARKERS = ("MCP_ENABLED", "mcp.enabled") +SEARCHED_EXTENSIONS = (".yml", ".yaml", ".j2") +MCP_BASENAME = ROLE_FILE_META_MCP.split("/")[-1] + + +def _server_roles() -> list[str]: + roles = [] + for role_dir in sorted(ROLES_DIR.iterdir()): + mcp_path = role_dir / ROLE_FILE_META_MCP + if not role_dir.is_dir() or not mcp_path.is_file(): + continue + block = load_yaml_any(str(mcp_path)) + if not isinstance(block, dict): + continue + if str(block.get("direction") or "") in MCP_SERVER_DIRECTIONS: + roles.append(role_dir.name) + return roles + + +def _roles_that_gate() -> set[str]: + prefix = f"{ROLES_DIR}/" + gating = set() + for path, text in iter_project_files_with_content( + extensions=SEARCHED_EXTENSIONS, exclude_tests=True + ): + if not path.startswith(prefix) or path.endswith(MCP_BASENAME): + continue + if any(marker in text for marker in GATE_MARKERS): + gating.add(path[len(prefix) :].split("/", 1)[0]) + return gating + + +class TestMcpDisabledHasNoSurface(unittest.TestCase): + def test_server_roles_exist(self) -> None: + self.assertTrue(_server_roles(), "no role declares an MCP server surface") + + def test_every_server_role_gates_its_surface(self) -> None: + gating = _roles_that_gate() + ungated = [r for r in _server_roles() if r not in gating] + self.assertEqual( + ungated, + [], + "MCP server roles that render their surface unconditionally, so " + f"`mcp.enabled=false` would not remove it: {ungated}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/roles/meta/services/test_mcp_variant_coverage.py b/tests/integration/roles/meta/services/test_mcp_variant_coverage.py new file mode 100644 index 0000000000..e11347f301 --- /dev/null +++ b/tests/integration/roles/meta/services/test_mcp_variant_coverage.py @@ -0,0 +1,78 @@ +"""Every deployable MCP surface has at least one peer that can reach it. + +``test_dynamic_flags.py`` exempts the ``mcp`` key from the peer-role rule, +because an MCP provider must not decide its own exposure from another role's +presence. That exemption leaves a hole: a role can declare a whole served +surface, wire its sidecar and its probe, and never enable any of it. The deploy +stays green because every gated task is skipped, so the surface looks proven +while nothing ran. + +This lint closes that hole. ``mcp.enabled`` is derived from the consumer edges +in ``meta/services.yml``, so a role whose surface nobody admits resolves to a +literal ``False`` and can never run. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-variant-coverage`` in the head of a ``meta/mcp.yml`` + file exempts that role. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.applications import get_application_defaults +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.applications.mcp import MCP_DEPLOYABLE_CLASSIFICATIONS +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +_RULE = "mcp-variant-coverage" + + +class TestMcpVariantCoverage(unittest.TestCase): + """Hard lint: a declared MCP surface is reachable by some peer.""" + + def test_every_deployable_mcp_block_has_an_admitted_peer(self) -> None: + roles_root = PROJECT_ROOT / "roles" + if not roles_root.is_dir(): + self.skipTest("no roles/ directory") + + defaults = get_application_defaults(roles_dir=roles_root) + offenders: list[str] = [] + + for role_dir in sorted(p for p in roles_root.iterdir() if p.is_dir()): + mcp_path = role_dir / ROLE_FILE_META_MCP + if not mcp_path.is_file(): + continue + if is_suppressed_in_head(read_text(str(mcp_path)).splitlines(), _RULE): + continue + + mcp = load_yaml_any(str(mcp_path), default_if_missing={}) + if not isinstance(mcp, Mapping): + continue + if mcp.get("classification") not in MCP_DEPLOYABLE_CLASSIFICATIONS: + continue + + block = (defaults.get(role_dir.name) or {}).get("mcp") + resolved = block.get("enabled") if isinstance(block, Mapping) else None + if resolved is None or resolved is False: + offenders.append( + f"{role_dir.name}: no role declares itself an " + f"mcp_consumer this surface admits, so its adapter, probe " + f"and endpoint can never run" + ) + + if offenders: + self.fail( + f"unreachable MCP surfaces ({len(offenders)}):\n" + + "\n".join(f" - {o}" for o in sorted(offenders)) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/roles/meta/services/test_platform_arch_constraint.py b/tests/integration/roles/meta/services/test_platform_arch_constraint.py new file mode 100644 index 0000000000..04aba5a6c9 --- /dev/null +++ b/tests/integration/roles/meta/services/test_platform_arch_constraint.py @@ -0,0 +1,67 @@ +"""A role that pins itself to a CPU architecture reaches the swarm renderer. + +`platform_arch` on a service is only meaningful if +`roles/sys-svc-container/templates/deploy.yml.j2` turns it into a placement +constraint, so the declaration and its consumer are asserted together. +""" + +from __future__ import annotations + +import unittest +from typing import TYPE_CHECKING + +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from pathlib import Path + +ROLES_DIR = PROJECT_ROOT / "roles" +DEPLOY_TEMPLATE = PROJECT_ROOT / "roles/sys-svc-container/templates/deploy.yml.j2" + +DOCKER_ARCHITECTURES = {"x86_64", "aarch64", "armv7l", "ppc64le", "s390x"} + + +def _services(role_dir: Path) -> dict: + path = role_dir / ROLE_FILE_META_SERVICES + if not path.is_file(): + return {} + data = load_yaml_any(str(path)) + return data if isinstance(data, dict) else {} + + +def _declared_arches() -> dict[str, str]: + found: dict[str, str] = {} + for role_dir in sorted(ROLES_DIR.iterdir()): + if not role_dir.is_dir(): + continue + for service_name, service in _services(role_dir).items(): + if not isinstance(service, dict): + continue + arch = service.get("platform_arch") + if arch is not None: + found[f"{role_dir.name}/{service_name}"] = str(arch) + return found + + +class TestPlatformArchConstraint(unittest.TestCase): + def test_renderer_consumes_platform_arch(self) -> None: + template = read_text(str(DEPLOY_TEMPLATE)) + self.assertIn("platform_arch", template) + self.assertIn("node.platform.arch ==", template) + + def test_declared_arches_are_docker_values(self) -> None: + for location, arch in _declared_arches().items(): + with self.subTest(location=location): + self.assertIn(arch, DOCKER_ARCHITECTURES) + + def test_lmstudio_is_pinned_to_x86(self) -> None: + arch = _services(ROLES_DIR / "svc-ai-lmstudio").get("lmstudio", {}) + self.assertEqual(arch.get("platform_arch"), "x86_64") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/roles/meta/test_non_empty.py b/tests/integration/roles/meta/test_non_empty.py index 7397e78691..5d68de05d7 100644 --- a/tests/integration/roles/meta/test_non_empty.py +++ b/tests/integration/roles/meta/test_non_empty.py @@ -1,13 +1,20 @@ import os +import re import unittest import yaml from utils.cache.files import iter_project_files from utils.cache.yaml import load_yaml_any +from utils.roles.applications.topics import CONFIG_TOPICS +from utils.roles.mapping import ROLE_FILE_META_VARIANTS from . import PROJECT_ROOT +_CLEARED_TOPIC = re.compile( + rf"^\[\d+\]\.services\.[^.]+\.(?:{'|'.join(sorted(CONFIG_TOPICS))})$" +) + def find_none_values(data, prefix=None): """ @@ -56,8 +63,11 @@ class TestConfigurationNoNone(unittest.TestCase): data = load_yaml_any(filepath) except yaml.YAMLError as e: self.fail(f"Failed to parse YAML in {filepath}: {e}") + is_variants = filepath.endswith(ROLE_FILE_META_VARIANTS) errors = find_none_values(data) for path, _value in errors: + if is_variants and _CLEARED_TOPIC.match(path): + continue all_errors.append(f"{filepath}: Key '{path}' is None") if all_errors: diff --git a/tests/integration/roles/meta/test_user_lookups_resolve.py b/tests/integration/roles/meta/test_user_lookups_resolve.py new file mode 100644 index 0000000000..04e0bc6cf4 --- /dev/null +++ b/tests/integration/roles/meta/test_user_lookups_resolve.py @@ -0,0 +1,94 @@ +"""Every ``lookup('users', 'mcp-โ€ฆ')`` addresses a service account a role declares. + +A role that reads its MCP service account out of the user registry names it by +a literal key. Nothing validates that key: a typo yields an empty password at +deploy time, deep inside a provisioning task, on the one variant that enables +the surface, and the application answers with a rejected login rather than a +missing variable. + +The rule covers the ``mcp-`` principals only, because the registry is open by +design: an inventory contributes users of its own (the ``biber`` persona the +Playwright environments log in as is declared nowhere in ``roles/``), so a +repository-wide "every looked-up user is declared" rule would report those as +missing. The ``mcp-`` keys are role-owned, so for them the set is closed. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: user-lookup-resolves`` on, or directly above, the line. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_USERS + +from . import PROJECT_ROOT + +_RULE = "user-lookup-resolves" +_LOOKUP = re.compile( + r"""lookup\(\s*['"]users['"]\s*,\s*['"](mcp-[A-Za-z0-9_.-]+)['"]""" +) +_SCANNED = (".yml", ".yaml", ".j2") + + +def _declared_keys(roles_root: Path) -> set[str]: + """Return every user key the roles declare.""" + keys: set[str] = set() + for users_file in sorted(roles_root.glob(f"*/{ROLE_FILE_META_USERS}")): + declared = load_yaml_any(str(users_file), default_if_missing={}) + if isinstance(declared, dict): + keys |= {str(name) for name in declared} + return keys + + +def _referenced_keys(roles_root: Path) -> list[tuple[str, int, str]]: + """Return ``(path, line, key)`` for every literal mcp user lookup.""" + found: list[tuple[str, int, str]] = [] + for path, content in iter_project_files_with_content(extensions=_SCANNED): + if "roles" not in Path(path).parts: + continue + lines = content.splitlines() + for number, line in enumerate(lines, start=1): + match = _LOOKUP.search(line) + if not match or is_suppressed_at(lines, number, _RULE): + continue + found.append((path, number, match.group(1))) + return found + + +class TestUserLookupsResolve(unittest.TestCase): + def test_every_looked_up_user_is_declared(self) -> None: + roles_root = PROJECT_ROOT / "roles" + if not roles_root.is_dir(): + self.skipTest("no roles/ directory") + + declared = _declared_keys(roles_root) + offenders = [ + f"{path}:{line}: lookup('users', {key!r}) addresses a service " + f"account no meta/users.yml declares" + for path, line, key in _referenced_keys(roles_root) + if key not in declared + ] + self.assertEqual( + [], + offenders, + f"unresolvable user lookup(s) ({len(offenders)}):\n" + + "\n".join(f" - {o}" for o in offenders), + ) + + def test_the_scan_finds_lookups(self) -> None: + roles_root = PROJECT_ROOT / "roles" + if not roles_root.is_dir(): + self.skipTest("no roles/ directory") + self.assertTrue( + _referenced_keys(roles_root), + "no role looks an mcp service account up by literal key, so the " + "rule would pass " + "vacuously; check that the scan still reads the right topic", + ) diff --git a/tests/integration/roles/meta/variants/test_resource_budget.py b/tests/integration/roles/meta/variants/test_resource_budget.py index 4de46bbc9f..3d462bed5d 100644 --- a/tests/integration/roles/meta/variants/test_resource_budget.py +++ b/tests/integration/roles/meta/variants/test_resource_budget.py @@ -4,7 +4,11 @@ the host memory budget. For every role and every entry in its ``meta/variants.yml``, the deduplicated footprint (the role's own containers plus the shared dependencies it pulls in, each service counted once via the shared-service logic) is summed and checked -against: +against the budget below. Every role that ships variants is evaluated at the +same round index, falling back to variant 0 when it has fewer, because that is +the combination a matrix round actually deploys: a dependency sized for the +production model tier is not what the round runs. ``meta/services.yml`` only +supplies the roles that declare no variant at all. - ``mem_reservation`` total โ‰ค 32 GB - ``mem_limit`` total โ‰ค 64 GB @@ -67,6 +71,11 @@ def _collect_findings(root: Path) -> list[BudgetFinding]: for role, variant_list in sorted(variants.items()): for index, variant_config in enumerate(variant_list): scoped = dict(applications) + for dep_role, dep_variants in variants.items(): + if not dep_variants: + continue + dep_index = index if index < len(dep_variants) else 0 + scoped[dep_role] = dep_variants[dep_index] or {} scoped[role] = variant_config or {} rows: list = [] collect_role_resources( diff --git a/tests/integration/roles/playwright/test_spec_env_gates.py b/tests/integration/roles/playwright/test_spec_env_gates.py index 4d36a19292..c28ddc0560 100644 --- a/tests/integration/roles/playwright/test_spec_env_gates.py +++ b/tests/integration/roles/playwright/test_spec_env_gates.py @@ -68,8 +68,12 @@ _RULE = "playwright-service-gate" _ENV_TEMPLATE_REL = "templates/playwright.env.j2" # nocheck: role-file-spot _SPEC_FILE_REL = ROLE_FILE_PLAYWRIGHT_SPEC _SHARED_PERSONAS_DIR = "roles/test-e2e-playwright/files/personas" +_SHARED_HARNESS_DIR = "roles/test-e2e-playwright/files" _PERSONA_RUNNERS: tuple[str, ...] = ("runGuestFlow", "runBiberFlow", "runAdminFlow") +_LOCAL_REQUIRE_RE = re.compile(r"""require\(\s*['"]\./([A-Za-z0-9_.-]+)['"]\s*\)""") +_BLOCK_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL) + _FLAG_LINE_RE = re.compile(r"^\s*([A-Z][A-Z0-9_]*)_SERVICE_ENABLED\s*=") _HELPER_CALL_RE = re.compile( r"\b(?:requireService|skipUnlessServiceEnabled|isServiceEnabled|" @@ -111,10 +115,27 @@ def _gated_roots_in_spec(spec_path: Path) -> set[str]: inside the shared personas directory count as consumed by the spec too โ€” every persona scenario fully drives the underlying `skipUnlessServiceEnabled('...')` chain via shared helpers. + + A `require("./")` that resolves to a module of the shared + harness rather than to a sibling counts the same way: the harness is + staged flat into the role's own test directory, so a gate declared + there is the very call the spec makes. Its block comments are stripped + first: `service-gating.js` documents its own contract with literal + `isServiceEnabled("sso")` / `isServiceDisabledReason("email")` examples, + and crediting those would exempt EMAIL, SSO and OICD for every role that + requires it. """ spec_dir_texts = [ read_text(str(js_path)) for js_path in sorted(spec_path.parent.glob("*.js")) ] + for name in {m for text in spec_dir_texts for m in _LOCAL_REQUIRE_RE.findall(text)}: + harness_path = ( + PROJECT_ROOT / _SHARED_HARNESS_DIR / f"{name.removesuffix('.js')}.js" + ) + if harness_path.is_file(): + spec_dir_texts.append( + _BLOCK_COMMENT_RE.sub("", read_text(str(harness_path))) + ) combined_text = "\n".join(spec_dir_texts) roots: set[str] = { _service_to_env_key_root(name) diff --git a/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py b/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py index dcbb53f4a2..4ed72e9dd0 100644 --- a/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py +++ b/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py @@ -1,8 +1,28 @@ import unittest +from ansible.module_utils.parsing.convert_bool import boolean as ansible_boolean from jinja2 import Environment, FileSystemLoader from tests.integration.roles import PROJECT_ROOT +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_str + +ROUTER = PROJECT_ROOT / "roles/svc-net-tor/tasks/router.yml" +CORE = PROJECT_ROOT / "roles/svc-net-tor/tasks/00_core.yml" +ROLE_FILES = PROJECT_ROOT / "roles/svc-net-tor/files" +RESOLV_TASK = "๐Ÿ”€ Egress router | Point the host resolver at dnsmasq (127.0.0.1)" +DROPIN_BLOCK = "๐Ÿ” Egress router | Retry dnsmasq until docker0 exists after a boot" +START_TASK = "๐Ÿš€ Egress router | Enable + (re)start dnsmasq" +REGATHER_TASK = ( + "๐Ÿ“Š Re-gather the docker0 fact so torrc and dnsmasq bind the live bridge" +) + + +def _walk(tasks): + for task in tasks or []: + yield task + for section in ("block", "rescue", "always"): + yield from _walk(task.get(section)) def _render_dnsmasq(**overrides): @@ -38,11 +58,36 @@ class TestDnsmasqListeners(unittest.TestCase): self.assertIn("listen-address=127.0.0.1", rendered) self.assertNotIn("listen-address=172.17", rendered) + def test_loopback_only_binds_statically(self): + """A loopback-only listener has no address to wait for, and the rebuild + that bind-dynamic performs on every netlink event can then only drop it.""" + rendered = _render_dnsmasq(TOR_CONTAINER_DNS_HOST="") + self.assertIn("bind-interfaces", rendered) + self.assertNotIn("bind-dynamic", rendered) + + def test_the_static_bind_claims_no_address_it_was_not_given(self): + """interface= and listen-address= are a union in dnsmasq, so naming lo + would additionally seize 127.0.0.53 and ::1, where a distro stub sits.""" + rendered = _render_dnsmasq(TOR_CONTAINER_DNS_HOST="") + self.assertNotIn("interface=", rendered) + + def test_a_bridge_listener_binds_statically_too(self): + rendered = _render_dnsmasq() + self.assertIn( + "bind-interfaces", + rendered, + "bind-dynamic closes every listener a failed netlink re-enumeration did " + "not re-find, loopback included, and nothing reopens them until the " + "next address event", + ) + self.assertNotIn("bind-dynamic", rendered) + def test_no_bind_policy_when_the_listener_is_not_ours(self): rendered = _render_dnsmasq( TOR_DNSMASQ_OWNS_LISTENER=False, TOR_CONTAINER_DNS_HOST="" ) self.assertNotIn("bind-dynamic", rendered) + self.assertNotIn("bind-interfaces", rendered) self.assertNotIn("listen-address", rendered) def test_onion_queries_go_to_the_tor_resolver(self): @@ -52,10 +97,9 @@ class TestDnsmasqListeners(unittest.TestCase): self.assertIn("server=172.30.0.53", _render_dnsmasq()) def test_upstream_policy_stays_off_a_listener_we_do_not_own(self): - """A shared dnsmasq brings its own upstreams, and in swarm - networks.internet.dns is the docker bridge that very dnsmasq answers - on. Writing a server= there points the resolver at itself, and - no-resolv would cut the upstreams its owner configured.""" + """A shared dnsmasq brings its own upstreams, chosen by whoever set it + up. Writing our server= into it overrides that choice, and no-resolv + would cut the upstreams its owner configured.""" rendered = _render_dnsmasq(TOR_DNSMASQ_OWNS_LISTENER=False) self.assertNotIn("server=172.30.0.53", rendered) self.assertNotIn("no-resolv", rendered) @@ -70,5 +114,100 @@ class TestDnsmasqListeners(unittest.TestCase): self.assertIn("address=/example.onion/172.17.0.1", _render_dnsmasq()) +class TestStaticBindSurvivesBoot(unittest.TestCase): + def _router_tasks(self): + return list(_walk(load_yaml_str(read_text(str(ROUTER))))) + + def test_dnsmasq_retries_until_its_addresses_exist(self): + tasks = self._router_tasks() + block = next(t for t in tasks if t.get("name") == DROPIN_BLOCK) + self.assertEqual( + block["when"], + "TOR_DNSMASQ_OWNS_LISTENER | bool", + "a shared dnsmasq keeps the unit its owner configured", + ) + src = next( + t["ansible.builtin.copy"]["src"] + for t in _walk(block["block"]) + if "ansible.builtin.copy" in t + ) + dropin = read_text(str(ROLE_FILES / src)) + self.assertIn( + "Restart=on-failure", + dropin.splitlines(), + "docker.service orders after nss-lookup.target, which dnsmasq precedes, " + "so a static bind on docker0 fails once per boot and must be retried", + ) + + def test_a_changed_dropin_is_loaded_before_dnsmasq_starts(self): + tasks = self._router_tasks() + names = [t.get("name") for t in tasks] + start = next(t for t in tasks if t.get("name") == START_TASK) + self.assertLess(names.index(DROPIN_BLOCK), names.index(START_TASK)) + + reload_expression = start["ansible.builtin.systemd"]["daemon_reload"] + env = Environment(autoescape=False) # noqa: S701 - renders a boolean, not markup + env.filters["bool"] = ansible_boolean + env.tests["changed"] = lambda result: bool(result.get("changed", False)) + + self.assertEqual( + env.from_string(reload_expression).render( + TOR_DNSMASQ_OWNS_LISTENER=True, _tor_dnsmasq_dropin={"changed": True} + ), + "True", + "a rewritten drop-in has to reach systemd before the unit restarts", + ) + self.assertEqual( + env.from_string(reload_expression).render(TOR_DNSMASQ_OWNS_LISTENER=False), + "False", + "the drop-in task is gated on owning the listener, so the reload " + "expression must not reach for its register when it was skipped", + ) + + def test_the_bridge_fact_is_live_before_anything_binds_it(self): + tasks = list(_walk(load_yaml_str(read_text(str(CORE))))) + names = [t.get("name") for t in tasks] + regather = next(t for t in tasks if t.get("name") == REGATHER_TASK) + self.assertEqual( + regather["ansible.builtin.setup"]["filter"], + ["ansible_docker0"], + "the play-start docker0 fact predates default-address-pools moving the " + "bridge, and a static bind on the stale address makes dnsmasq exit", + ) + self.assertLess(names.index(REGATHER_TASK), names.index("๐Ÿ“ Render torrc")) + self.assertLess( + names.index(REGATHER_TASK), + names.index("๐Ÿง… Wire the host-level transparent .onion egress router"), + ) + + +class TestHostResolver(unittest.TestCase): + """glibc reads resolv.conf per query and keeps no server state, so the + clearnet entry costs nothing while dnsmasq answers and carries the host when + it stops. systemd-resolved does keep state, which is why the role has to + stay out of its way rather than drop the entry.""" + + def _resolv_conf(self) -> str: + tasks = _walk(load_yaml_str(read_text(str(ROUTER)))) + task = next(t for t in tasks if t.get("name") == RESOLV_TASK) + env = Environment( + loader=FileSystemLoader(str(PROJECT_ROOT)), + autoescape=False, # noqa: S701 - resolv.conf, html escaping would corrupt it + ) + template = env.get_template( + f"roles/svc-net-tor/templates/{task['ansible.builtin.template']['src']}" + ) + return template.render(networks={"internet": {"dns": "172.30.0.53"}}) + + def test_dnsmasq_answers_first_and_the_upstream_carries_the_host(self): + servers = [ + line.split()[1] + for line in self._resolv_conf().splitlines() + if line.startswith("nameserver ") + ] + self.assertEqual(len(servers), 2) + self.assertEqual(servers[0], "127.0.0.1") + + if __name__ == "__main__": unittest.main() diff --git a/tests/integration/roles/test-e2e-cli/__init__.py b/tests/integration/roles/test-e2e-cli/__init__.py new file mode 100644 index 0000000000..039b52c789 --- /dev/null +++ b/tests/integration/roles/test-e2e-cli/__init__.py @@ -0,0 +1,3 @@ +from tests.integration.roles import PROJECT_ROOT + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/integration/roles/test-e2e-cli/test_mcp_env_render.py b/tests/integration/roles/test-e2e-cli/test_mcp_env_render.py new file mode 100644 index 0000000000..60141e0a48 --- /dev/null +++ b/tests/integration/roles/test-e2e-cli/test_mcp_env_render.py @@ -0,0 +1,317 @@ +"""The shared MCP env template renders for every provider that has to run it. + +``test.env`` is the whole interface between the deployment and the MCP CLI +test: the endpoint, the credential a client presents, the tool contract and the +networks the sidecar may hold all reach the checkers through it and through +nothing else. A key that fails to resolve does not announce itself there. It +arrives as the literal ``{{ ... }}`` source, the shell accepts it as a string, +and the check that reads it draws a conclusion from text nobody rendered. + +The render runs through Ansible's own templar against the real resolved +applications map, so the lookups, filters and the nested ``lookup('template')`` +are the ones the deploy uses rather than stand-ins for them. + +``MCP_TEST_ENABLED`` gets its own check on top of that. It is derived from +``group_names`` rather than declared, so it is the one key that can arrive as +its own source, and a flag that is neither ``true`` nor ``false`` would switch +the whole suite off for every provider at once. Only one polarity is rendered: +the ``config`` lookup caches per process and stops reading ``group_names`` +after the first resolution, so a second render in the same interpreter would +report the first answer whatever it is handed. +""" + +from __future__ import annotations + +import json +import subprocess +import unittest +from collections.abc import Mapping +from urllib.parse import urlparse + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar, trust_as_template + +from utils.cache.applications import get_application_defaults +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ( + ROLE_FILE_DEFAULTS_MAIN, + ROLE_FILE_META_MCP, + ROLE_FILE_META_TESTS, + ROLE_FILE_VARS_MAIN, +) + +_SHARED = "roles/test-e2e-cli/templates/mcp/test.env.j2" +_DOMAIN = "infinito.test" +_SERVER_DIRECTIONS = frozenset({"server", "both"}) +_CLIENT_DIRECTIONS = frozenset({"client"}) +_MODES = ("compose", "swarm") +_CONSUMERS = ( + "web-app-flowise", + "web-app-hermes", + "web-app-openclaw", + "web-app-openwebui", +) +_REQUIRED = ( + "MCP_AUTH_HEADER", + "MCP_DEADLINE_SECONDS", + "MCP_DEPLOYMENT_MODE", + "MCP_EXPECTED_NETWORKS", + "MCP_EXPECTED_TOOLS", + "MCP_TEST_ENABLED", + "MCP_TEST_IMAGE", + "MCP_TEST_NETWORK", + "MCP_TRANSPORT", + "MCP_URL", +) + + +def _roles_with_direction(directions: frozenset[str]) -> list[str]: + """Return the role ids whose ``meta/mcp.yml`` declares one of ``directions``.""" + roles_root = PROJECT_ROOT / "roles" + found: list[str] = [] + for mcp_path in sorted(roles_root.glob(f"*/{ROLE_FILE_META_MCP}")): + mcp = load_yaml_any(str(mcp_path), default_if_missing={}) + if not isinstance(mcp, Mapping): + continue + if str(mcp.get("direction") or "").strip().lower() in directions: + found.append(mcp_path.parent.parent.name) + return found + + +def _providers() -> list[str]: + """Return the role ids that serve an MCP endpoint.""" + return _roles_with_direction(_SERVER_DIRECTIONS) + + +def _clients() -> list[str]: + """Return the client role ids that ship a CLI test env template.""" + return [ + role + for role in _roles_with_direction(_CLIENT_DIRECTIONS) + if (PROJECT_ROOT / "roles" / role / "templates/test.env.j2").is_file() + ] + + +def _trusted(value: object) -> object: + """Trust nested strings so a loaded var that carries Jinja still templates.""" + if isinstance(value, str): + return trust_as_template(value) + if isinstance(value, Mapping): + return {k: _trusted(v) for k, v in value.items()} + if isinstance(value, list): + return [_trusted(v) for v in value] + return value + + +def _group_vars_all() -> dict: + """The ``group_vars/all`` layer every play carries under the role vars.""" + loaded: dict = {} + for path in sorted((PROJECT_ROOT / "group_vars/all").glob("*.yml")): + data = load_yaml_any(str(path), default_if_missing={}) + if isinstance(data, Mapping): + loaded.update({k: _trusted(v) for k, v in data.items()}) + return loaded + + +def _role_scoped_vars(application_id: str) -> dict: + """Mirror the ``include_vars`` chain ``run_one.yml:44-70`` runs before rendering.""" + loaded: dict = {} + for candidate in ( + PROJECT_ROOT / "roles" / application_id / ROLE_FILE_DEFAULTS_MAIN, + PROJECT_ROOT / "roles" / application_id / ROLE_FILE_VARS_MAIN, + ): + if not candidate.is_file(): + continue + data = load_yaml_any(str(candidate), default_if_missing={}) + if isinstance(data, Mapping): + loaded.update({k: _trusted(v) for k, v in data.items()}) + return loaded + + +def _render(application_id: str, group_names: list[str], mode: str = "compose") -> str: + """Render the role's own env template the way ``run_one.yml`` does.""" + role_template = PROJECT_ROOT / "roles" / application_id / "templates/test.env.j2" + variables = { + **_group_vars_all(), + **_role_scoped_vars(application_id), + "applications": get_application_defaults(roles_dir=PROJECT_ROOT / "roles"), + "application_id": application_id, + "group_names": group_names, + "CLI_HOST_NODE": "stack-host", + "CLI_LOCAL_CID": f"{application_id}-container", + "playbook_dir": str(PROJECT_ROOT), + "compose_mode": mode, + "DEPLOYMENT_MODE": mode, + "TIMEOUT_FACTOR": 1, + "PRIMARY_DOMAIN": _DOMAIN, + "DOMAIN_PRIMARY": _DOMAIN, + "SYSTEM_EMAIL_DOMAIN": _DOMAIN, + } + templar = Templar(loader=DataLoader(), variables=variables) + return templar.template( + trust_as_template(f"{{{{ lookup('template', '{role_template.resolve()}') }}}}") + ) + + +def _entries(rendered: str) -> dict[str, str]: + """Return the KEY=value pairs a shell would read out of the rendering.""" + pairs: dict[str, str] = {} + for line in rendered.splitlines(): + if not line.strip(): + continue + key, separator, value = line.partition("=") + if not separator: + raise AssertionError(f"not a KEY=value line: {line!r}") + pairs[key] = value + return pairs + + +class TestMcpEnvRender(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.providers = _providers() + cls.on = {p: _render(p, [*_CONSUMERS, p]) for p in cls.providers} + + def test_the_scan_finds_providers(self) -> None: + self.assertTrue(self.providers) + self.assertEqual( + [], + [ + p + for p in self.providers + if not (PROJECT_ROOT / "roles" / p / "templates/test.env.j2").is_file() + ], + ) + + def test_every_role_renders_the_shared_template(self) -> None: + shared = read_text(str(PROJECT_ROOT / _SHARED)) + keys = sorted( + line.split("=", 1)[0] + for line in shared.splitlines() + if line and not line.startswith("{%") + ) + for provider, rendered in self.on.items(): + with self.subTest(provider=provider): + missing = [key for key in keys if key not in _entries(rendered)] + self.assertEqual( + [], + missing, + f"{provider} does not render the whole shared template", + ) + + def test_nothing_reaches_the_shell_unrendered(self) -> None: + for provider, rendered in self.on.items(): + with self.subTest(provider=provider): + leaked = [k for k, v in _entries(rendered).items() if "{{" in v] + self.assertEqual([], leaked) + + def test_the_required_keys_are_non_empty(self) -> None: + for provider, rendered in self.on.items(): + entries = _entries(rendered) + with self.subTest(provider=provider): + self.assertEqual( + [], [k for k in _REQUIRED if not entries[k].strip("'")] + ) + + def test_the_flag_resolves_to_a_boolean(self) -> None: + for provider, rendered in self.on.items(): + with self.subTest(provider=provider): + self.assertIn(_entries(rendered)["MCP_TEST_ENABLED"], ("true", "false")) + + def test_the_endpoint_url_is_addressable(self) -> None: + for provider, rendered in self.on.items(): + with self.subTest(provider=provider): + parsed = urlparse(_entries(rendered)["MCP_URL"]) + self.assertEqual("http", parsed.scheme) + self.assertTrue(parsed.hostname) + self.assertTrue(parsed.port) + self.assertTrue(parsed.path) + + def test_the_read_probe_is_inside_the_served_contract(self) -> None: + for provider, rendered in self.on.items(): + entries = _entries(rendered) + tool = entries["MCP_READ_TOOL"] + allowlist = json.loads(entries["MCP_EXPECTED_TOOLS"].strip("'")) + with self.subTest(provider=provider): + if tool and allowlist: + self.assertIn(tool, allowlist) + + def test_the_deadline_stays_under_the_harness_timeout(self) -> None: + for provider, rendered in self.on.items(): + budget = load_yaml_any( + str(PROJECT_ROOT / "roles" / provider / ROLE_FILE_META_TESTS), + default_if_missing={}, + ) + with self.subTest(provider=provider): + deadline = int(_entries(rendered)["MCP_DEADLINE_SECONDS"]) + self.assertLess(deadline, int(budget["cli"]["timeout"])) + + def test_a_shell_reads_every_value_back_whole(self) -> None: + for provider, rendered in self.on.items(): + entries = _entries(rendered) + script = "set -a\n. /dev/stdin\nset +a\n" + "".join( + f'printf "%s\\n" "${{{key}}}"\n' for key in sorted(entries) + ) + with self.subTest(provider=provider): + result = subprocess.run( + ["/bin/bash", "-c", script], + input=rendered, + capture_output=True, + text=True, + check=True, + ) + self.assertEqual( + [entries[k].strip("'") for k in sorted(entries)], + result.stdout.splitlines(), + ) + + +class TestMcpClientEnvRender(unittest.TestCase): + """The client half of the same interface, in both deployment modes. + + ``_providers`` covers the roles that serve an endpoint. The roles that + consume one render their own ``test.env.j2`` through the same path and were + covered by nothing, in either mode, so the swarm branch of + ``lookup('container_address')`` was never exercised under ``tests/``. + ``container_address`` reads ``DEPLOYMENT_MODE`` straight from the templar + variables, so both modes can be rendered in one interpreter; the per-process + ``config`` cache that limits the provider suite to one polarity does not + reach the mode split. + """ + + @classmethod + def setUpClass(cls) -> None: + cls.clients = _clients() + cls.rendered = { + (client, mode): _render(client, [*_CONSUMERS, client], mode) + for client in cls.clients + for mode in _MODES + } + + def test_the_scan_finds_clients_with_a_cli_test(self) -> None: + self.assertTrue(self.clients) + + def test_nothing_reaches_the_shell_unrendered(self) -> None: + for (client, mode), rendered in self.rendered.items(): + with self.subTest(client=client, mode=mode): + leaked = [k for k, v in _entries(rendered).items() if "{{" in v] + self.assertEqual([], leaked) + + def test_every_key_resolves_to_something(self) -> None: + for (client, mode), rendered in self.rendered.items(): + entries = _entries(rendered) + with self.subTest(client=client, mode=mode): + self.assertTrue(entries) + self.assertEqual( + [], [k for k, v in entries.items() if not v.strip("'")] + ) + + def test_the_flag_resolves_to_a_boolean(self) -> None: + for (client, mode), rendered in self.rendered.items(): + with self.subTest(client=client, mode=mode): + self.assertIn(_entries(rendered)["MCP_TEST_ENABLED"], ("true", "false")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/jinja/test_compose_ports_use_container_ports_lookup.py b/tests/lint/ansible/jinja/test_compose_ports_use_container_ports_lookup.py index 8e1758182f..d66c3464c9 100644 --- a/tests/lint/ansible/jinja/test_compose_ports_use_container_ports_lookup.py +++ b/tests/lint/ansible/jinja/test_compose_ports_use_container_ports_lookup.py @@ -7,8 +7,8 @@ declared ``ports.local`` / ``ports.public`` (host) and ``ports.internal`` (container) values, so the published and container ports stay one source of truth: - {{ lookup('container_ports', ['gitea', 'http'], ['gitea', 'ssh'], - ip=DOCKER_BIND_HOST) | indent(4) }} + {{ lookup('container_ports', ['gitea', 'http', DOCKER_BIND_HOST], + ['gitea', 'ssh']) | indent(4) }} Hand-writing the mapping ``- "{{ ... }}:{{ lookup('config', ..., 'services..ports.local.') }}:..."`` @@ -37,31 +37,94 @@ from . import PROJECT_ROOT _RULE = "compose-ports-must-use-container-ports" -_PORT_SEGMENT = re.compile(r"\A(?:\{\{.*\}\}|[\d.]+|\d+/(?:tcp|udp))\Z") +_PORT_SEGMENT = re.compile( + r"\A(?:\{\{.*\}\}|\$\{[^}]*\}|[\d.]+|[\d-]+)(?:/(?:tcp|udp))?\Z", +) -_LIST_ITEM = re.compile(r'-\s*"([^"]*)"') +_LIST_ITEM = re.compile(r"""-\s*["']?(.*?)["']?\s*(?:\#.*)?\Z""") + +_LONG_SYNTAX_KEY = re.compile(r"\A-?\s*(?:target|published|mode|protocol):") + +_BLOCK_KEY = re.compile(r"\A(ports|expose):\s*(.*)\Z") _PAIR = re.compile(r"\[\s*'([\w-]+)'\s*,\s*'([\w-]+)'\s*\]") def _is_scan_target(rel_path: str) -> bool: - if not rel_path.startswith("roles/") or "/templates/" not in rel_path: - return False - name = Path(rel_path).name - return name.endswith(".yml.j2") and "compose" in name + """Every role template that can carry a compose ``ports:`` block. + + ``compose.yml.j2`` and its ``compose..yml.j2`` siblings, plus the + ``*.yml.j2`` fragments they include: a mapping hand-written in an included + file publishes exactly the same port as one written inline. + """ + return ( + rel_path.startswith("roles/") + and "/templates/" in rel_path + and rel_path.endswith(".yml.j2") + ) -def _is_raw_port_mapping(line: str) -> bool: +def _is_raw_port_mapping(line: str, *, mapping_only: bool = False) -> bool: + """Whether *line* publishes a port by hand, quoted or not. + + ``mapping_only`` drops the single-segment form. Under ``expose:`` that form + names a container port for documentation and publishes nothing, so only a + ``host:container`` mapping there is a publication. + """ match = _LIST_ITEM.match(line.strip()) if match is None: return False - inner = match.group(1) - if "=" in inner: + inner = match.group(1).strip() + if not inner or "=" in inner: return False - segments = inner.split(":") - return len(segments) >= 2 and all( - _PORT_SEGMENT.match(segment.strip()) for segment in segments - ) + segments = [segment.strip() for segment in inner.split(":")] + if not all(_PORT_SEGMENT.match(segment) for segment in segments): + return False + if len(segments) >= 2: + return True + return not mapping_only and bool(_PORT_SEGMENT.match(inner)) + + +def _raw_port_lines(lines: list[str]) -> list[int]: + """1-based line numbers that publish a port by hand. + + The block is tracked by the indentation of its ``ports:`` / ``expose:`` key + rather than by the next key seen. Keying on the next line closed the block + on anything shaped like a key, which the long-syntax members ``target:``, + ``published:``, ``protocol:`` and ``mode:`` are, so the block could never + end while it was being read; blank, comment and ``{% %}`` lines equally have + no say in where a YAML block ends. + """ + found: list[int] = [] + block_indent: int | None = None + mapping_only = False + for number, line in enumerate(lines, start=1): + stripped = line.strip() + if not stripped or stripped.startswith(("#", "{%")): + continue + indent = len(line) - len(line.rstrip("\n").lstrip()) + if ( + block_indent is not None + and indent <= block_indent + and not stripped.startswith("- ") + ): + block_indent = None + if block_indent is None: + opener = _BLOCK_KEY.match(stripped) + if opener: + block_indent = indent + mapping_only = opener.group(1) == "expose" + inline = opener.group(2).strip().strip("[]") + if inline and _is_raw_port_mapping( + "- " + inline, mapping_only=mapping_only + ): + found.append(number) + continue + if _LONG_SYNTAX_KEY.match(stripped) or _is_raw_port_mapping( + line, mapping_only=mapping_only + ): + found.append(number) + return found class TestComposePortsUseContainerPortsLookup(unittest.TestCase): @@ -75,27 +138,11 @@ class TestComposePortsUseContainerPortsLookup(unittest.TestCase): if not _is_scan_target(rel): continue lines = content.splitlines() - in_ports_block = False - for idx, line in enumerate(lines): - stripped = line.strip() - if not stripped: - continue - if stripped.startswith("- "): - if ( - in_ports_block - and _is_raw_port_mapping(line) - and not is_suppressed_at( - lines, idx + 1, _RULE, mode="same-or-above" - ) - ): - findings.append((rel, idx + 1, stripped)) - continue - if stripped.startswith("{{"): - in_ports_block = "container_ports" in stripped - continue - key = re.match(r"[\w-]+:", stripped) - if key: - in_ports_block = key.group(0) == "ports:" + findings.extend( + (rel, number, lines[number - 1].strip()) + for number in _raw_port_lines(lines) + if not is_suppressed_at(lines, number, _RULE, mode="same-or-above") + ) if findings: formatted = "\n".join( @@ -107,8 +154,8 @@ class TestComposePortsUseContainerPortsLookup(unittest.TestCase): "Build the `ports:` block with the container_ports lookup instead, " "so the published (local/public) and container (internal) ports stay " "a single declared source of truth:\n\n" - " {{ lookup('container_ports', ['', ''],\n" - " ip=DOCKER_BIND_HOST) | indent(4) }}\n\n" + " {{ lookup('container_ports',\n" + " ['', '', DOCKER_BIND_HOST]) | indent(4) }}\n\n" "One ['', ''] pair per published port; the lookup reads " "ports.local/public for the host side and ports.internal for the " "container side. Mark with " diff --git a/tests/lint/ansible/jinja/test_container_healthcheck_literal_without_variables.py b/tests/lint/ansible/jinja/test_container_healthcheck_literal_without_variables.py new file mode 100644 index 0000000000..ee2a262560 --- /dev/null +++ b/tests/lint/ansible/jinja/test_container_healthcheck_literal_without_variables.py @@ -0,0 +1,114 @@ +"""A literal ``healthcheck:`` block that needs no template variable belongs in +``meta/services.yml``. + +``utils/docker/healthcheck`` is the single point of truth for probe timings. It +carries ``start_interval``, the cadence Docker uses while ``start_period`` is +still running; without it a probe only fires every ``interval``, so a service +ready after three seconds is reported healthy at the next tick and a stack +converges no faster than its slowest quantisation. A block written out in the +template bypasses that default and never gains it, which is how forty six of +them ended up without the key. + +Moving the block is mechanical and provably lossless: the lookup writes +``overrides.get(key, flavor_default)`` for each of ``interval``, ``timeout``, +``retries``, ``start_period`` and ``start_interval``, so a declaration that +repeats the literal values renders the same block plus the missing cadence. + +A block that interpolates a template variable is exempt. Its value is resolved +in the template's own scope, which ``meta/services.yml`` does not share, so +moving it is a rewrite rather than a transcription. + +Per-block opt-out +================= +``# nocheck: container-healthcheck-literal`` on the ``healthcheck:`` line or the +line directly above it, with a short reason. Reserved for a block that is +variable free yet still cannot move: a partial rendered for another role's +``application_id``, or timings the flavor defaults would make worse. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content + +from . import PROJECT_ROOT + +RULE = "container-healthcheck-literal" +SCAN_PREFIX = "roles/" +SCAN_EXTENSIONS = (".j2",) + +_HEALTHCHECK = re.compile(r"^(\s*)healthcheck:\s*(?:#.*)?$") +_VARIABLE = ("{{", "{%") + + +def _block_body(lines: list[str], index: int, indent: int) -> list[str]: + """Return the lines nested under the ``healthcheck:`` at *index*. + + Args: + lines: the whole template. + index: 0-based line number of the ``healthcheck:`` key. + indent: that key's indentation width. + """ + body: list[str] = [] + for line in lines[index + 1 :]: + if not line.strip(): + break + if len(line) - len(line.lstrip()) <= indent: + break + body.append(line) + return body + + +def literal_blocks_without_variables() -> list[tuple[str, int]]: + """Every variable free literal healthcheck block, as ``(path, line_no)``.""" + findings: list[tuple[str, int]] = [] + for path_str, content in iter_project_files_with_content( + extensions=SCAN_EXTENSIONS, + exclude_tests=True, + ): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + if not rel.startswith(SCAN_PREFIX): + continue + lines = content.splitlines() + for index, line in enumerate(lines): + match = _HEALTHCHECK.match(line) + if not match: + continue + body = _block_body(lines, index, len(match.group(1))) + if not body: + continue + if any(token in "\n".join(body) for token in _VARIABLE): + continue + line_no = index + 1 + if is_suppressed_at(lines, line_no, RULE): + continue + findings.append((rel, line_no)) + return findings + + +class TestContainerHealthcheckLiteralWithoutVariables(unittest.TestCase): + def test_variable_free_healthchecks_live_in_meta(self) -> None: + findings = literal_blocks_without_variables() + if not findings: + return + formatted = "\n".join(f"- {path}:{line}" for path, line in sorted(findings)) + self.fail( + "Found literal 'healthcheck:' blocks that interpolate nothing and so " + "belong in meta/services.yml, where the container_healthcheck SPOT " + "adds the start_interval cadence a hand written block never gains.\n\n" + "Fix: copy the block's keys to services..healthcheck in " + "meta/services.yml and render it with\n\n" + " {{ lookup('container_healthcheck', service_name) | indent(4) }}\n\n" + "Cannot move (a partial rendered for another role, or timings the " + "flavor defaults would worsen)? Add on the healthcheck line or the " + f"line above it:\n\n # nocheck: {RULE} \n\n" + f"Offenders:\n{formatted}" + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/lint/ansible/jinja/test_firewall_fragment_verdicts.py b/tests/lint/ansible/jinja/test_firewall_fragment_verdicts.py new file mode 100644 index 0000000000..7c0fefc9a8 --- /dev/null +++ b/tests/lint/ansible/jinja/test_firewall_fragment_verdicts.py @@ -0,0 +1,79 @@ +"""Lint: a firewall fragment may tighten, never overrule. + +A fragment declares its own nftables table. In nftables an ``accept`` verdict +terminates that table's base chain and nothing else: the packet still traverses +every other base chain registered at the same hook, and a ``drop`` in any of +them wins. Docker sets the filter FORWARD policy to ``drop`` by default, so a +fragment that accepts is not permitting anything, it is only declining to +decide. + +Measured, not assumed: converting a role's ``iptables -A FORWARD -i wg0 -j +ACCEPT`` into a fragment rule at priority -10 dropped every forwarded packet +under that policy, 0 of 3 against 3 of 3 for the rule it replaced, with the +fragment's own counter showing the accept had matched all three. The deploy was +green either way. + +A rule that has to overrule a policy another component set belongs in the chain +that carries that policy, not in a fragment. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``nocheck: firewall-fragment-accept`` on the rule's line or the one above it, + for an accept whose only job is to skip the fragment's own later rules. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files, read_text + +from . import PROJECT_ROOT + +_RULE = "firewall-fragment-accept" +_FRAGMENT = "templates/nftables.conf.j2" +_POLICY = re.compile(r"\bpolicy\s+accept\b") +_VERDICT = re.compile(r"\baccept\s*$") + + +def _fragments() -> list[str]: + suffix = "/" + _FRAGMENT + return sorted( + path + for path in iter_project_files(extensions=(".j2",), exclude_tests=True) + if path.endswith(suffix) + ) + + +class TestFirewallFragmentVerdicts(unittest.TestCase): + def test_no_fragment_rule_accepts(self) -> None: + findings: list[str] = [] + for path in _fragments(): + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + lines = read_text(path).splitlines() + for index, line in enumerate(lines): + body = line.split("#")[0].rstrip().rstrip(";") + if _POLICY.search(body) or not _VERDICT.search(body): + continue + if is_suppressed_at(lines, index + 1, _RULE, mode="same-or-above"): + continue + findings.append(f"- {rel}:{index + 1}: {line.strip()}") + + if findings: + self.fail( + "These fragment rules end in an accept verdict, which terminates " + "only this table's base chain. Another chain at the same hook can " + "still drop the packet, so the rule permits nothing:\n" + + "\n".join(findings) + + "\n\nFix: express the intent as a drop of what must not pass, or " + "put the rule in the chain that carries the policy it has to " + f"overrule. Mark it `nocheck: {_RULE}` when the accept only skips " + "the fragment's own later rules." + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/jinja/test_model_backend_via_gateway.py b/tests/lint/ansible/jinja/test_model_backend_via_gateway.py new file mode 100644 index 0000000000..e3700ab0ce --- /dev/null +++ b/tests/lint/ansible/jinja/test_model_backend_via_gateway.py @@ -0,0 +1,95 @@ +"""Keep model traffic on the gateway instead of a provider URL. + +Rationale +========= +``svc-ai-litellm`` is the single entrypoint to every model backend: it owns the +model list, the per-consumer virtual keys and the routing. An application that +addresses a provider directly bypasses all three, so its traffic carries no +consumer identity, ignores the routing, and keeps working after the model list +moved on. + +The gateway itself is the one legitimate holder of provider URLs, because +routing to them is its job. + +Per-line opt-out +================ +Add ``# nocheck: model-backend-via-gateway`` on the offending line or on the +immediately preceding non-empty line, together with the reason this consumer +cannot go through the gateway. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content + +from . import PROJECT_ROOT + +_RULE = "model-backend-via-gateway" + +_GATEWAY_ROLE = "svc-ai-litellm" + +_PROVIDER_URL = re.compile(r"\{\{[^}]*\b(OLLAMA|LMSTUDIO)_BASE_LOCAL_URL\b") + + +class TestModelBackendViaGateway(unittest.TestCase): + def test_only_the_gateway_addresses_a_provider_directly(self) -> None: + findings: list[tuple[str, int, str]] = [] + for path_str, content in iter_project_files_with_content( + extensions=(".j2", ".yml"), + exclude_tests=True, + ): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + parts = rel.split("/") + if len(parts) < 2 or parts[0] != "roles": + continue + if "/templates/" not in rel and "/vars/" not in rel: + continue + if parts[1] == _GATEWAY_ROLE: + continue + lines = content.splitlines() + for idx, line in enumerate(lines): + if not _PROVIDER_URL.search(line): + continue + if is_suppressed_at(lines, idx + 1, _RULE, mode="same-or-above"): + continue + findings.append((rel, idx + 1, line.strip())) + + if findings: + formatted = "\n".join( + f"- {p}:{n}: {s}" + for p, n, s in sorted(set(findings), key=lambda i: (i[0], i[1])) + ) + self.fail( + "These files address a model provider directly instead of " + f"routing through {_GATEWAY_ROLE}, so their traffic carries no " + "consumer identity and ignores the gateway's model list.\n\n" + "Fix: declare `services.litellm` in the role's meta/services.yml " + "and a `litellm_api_key` credential in its meta/secrets.yml, then " + "point the application at LITELLM_BASE_LOCAL_URL with that key. " + "The gateway provisions the virtual key for every role that " + "declares both.\n\n" + f"Offending lines:\n{formatted}" + ) + + def test_the_pattern_still_matches_a_real_provider_reference(self) -> None: + gateway_templates = str(PROJECT_ROOT / "roles" / _GATEWAY_ROLE / "templates") + matched = [ + Path(path).name + for path, content in iter_project_files_with_content(extensions=(".j2",)) + if path.startswith(gateway_templates) and _PROVIDER_URL.search(content) + ] + self.assertTrue( + matched, + f"no file under roles/{_GATEWAY_ROLE}/templates/ matches the provider " + "pattern, so the rule would pass vacuously on every consumer too; " + "check that the backend variables are still named *_BASE_LOCAL_URL", + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/lint/ansible/jinja/test_no_ansible_facts_in_templates.py b/tests/lint/ansible/jinja/test_no_ansible_facts_in_templates.py index e9e4c75613..04ada11afa 100644 --- a/tests/lint/ansible/jinja/test_no_ansible_facts_in_templates.py +++ b/tests/lint/ansible/jinja/test_no_ansible_facts_in_templates.py @@ -1,3 +1,27 @@ +"""Lint: a host-local fact must not reach a role template. + +Such a fact describes whichever host the render happened on, which is not the +host the rendered file will be used by once a stack spans several. Where the +two genuinely coincide - a manager-pinned role writing a file only that node +consumes - the exception is declared rather than left to look like an oversight. + +The rule reads both ``ansible_facts.default_ipv4`` and +``ansible_facts['default_ipv4']``, and it reads a role's ``vars`` and +``defaults`` as well as its templates: a fact assigned to a variable there +reaches the template just the same, and for a while the only real violation in +the tree sat in exactly that blind spot. + +Only facts that ADDRESS a host are banned - its names, its ids, and any +interface's ``ipv4``/``ipv6``. Facts that describe its PLATFORM are not: +``os_family``, ``architecture`` and ``processor_vcpus`` pick behaviour for the +node the rendered file is consumed on, which is the node it was rendered for. +Banning those too would need a suppression on five correct lines out of seven. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: host-local-fact`` on, or directly above, the line. +""" + from __future__ import annotations import re @@ -6,7 +30,9 @@ from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING +from utils.annotations.suppress import is_suppressed_at from utils.cache.files import iter_project_files, read_text +from utils.roles.mapping import ROLE_FILE_DEFAULTS_MAIN, ROLE_FILE_VARS_MAIN from . import PROJECT_ROOT @@ -23,18 +49,40 @@ _HOST_LOCAL_FACT_PATTERNS = ( r"ansible_all_ipv6_addresses", r"ansible_machine_id", r"ansible_product_uuid", - r"ansible_facts\.hostname", - r"ansible_facts\.fqdn", - r"ansible_facts\.nodename", - r"ansible_facts\.default_ipv4", - r"ansible_facts\.default_ipv6", - r"ansible_facts\.all_ipv4_addresses", - r"ansible_facts\.all_ipv6_addresses", ) -_BANNED_RE = re.compile("|".join(_HOST_LOCAL_FACT_PATTERNS)) +_HOST_LOCAL_FACT_KEYS = ( + "hostname", + "fqdn", + "nodename", + "default_ipv4", + "default_ipv6", + "all_ipv4_addresses", + "all_ipv6_addresses", +) + +_RULE = "host-local-fact" + +_INTERFACE_ADDRESS_PATTERNS = ( + r"ansible_facts\[['\"][^'\"]+['\"]\]\[['\"]ipv[46]['\"]\]", + r"ansible_facts\.\w+\.ipv[46]\b", + r"ansible_\w+\[['\"]ipv[46]['\"]\]", + r"ansible_\w+\.ipv[46]\b", +) + +_BANNED_RE = re.compile( + "|".join( + ( + *_HOST_LOCAL_FACT_PATTERNS, + *_INTERFACE_ADDRESS_PATTERNS, + *(rf"ansible_facts\.{key}" for key in _HOST_LOCAL_FACT_KEYS), + *(rf"ansible_facts\[['\"]{key}['\"]\]" for key in _HOST_LOCAL_FACT_KEYS), + ) + ) +) _SCAN_PREFIXES = ("roles/",) -_SCAN_SUFFIXES = (".j2",) +_SCAN_SUFFIXES = (".j2", ".yml") +_SCANNED_YML = (ROLE_FILE_VARS_MAIN, ROLE_FILE_DEFAULTS_MAIN) @dataclass(frozen=True) @@ -52,13 +100,18 @@ class Finding: def _iter_target_files(repo_root: Path) -> Iterable[Path]: for abs_path in iter_project_files(extensions=_SCAN_SUFFIXES): rel = Path(abs_path).relative_to(repo_root).as_posix() - if any(rel.startswith(p) for p in _SCAN_PREFIXES): + if not any(rel.startswith(p) for p in _SCAN_PREFIXES): + continue + if rel.endswith(".j2") or rel.endswith(_SCANNED_YML): yield Path(abs_path) def _scan_file(path: Path) -> list[Finding]: findings: list[Finding] = [] - for lineno, raw in enumerate(read_text(path).splitlines(), start=1): + lines = read_text(path).splitlines() + for lineno, raw in enumerate(lines, start=1): + if is_suppressed_at(lines, lineno, _RULE): + continue findings.extend( Finding( file=path, diff --git a/tests/lint/ansible/jinja/test_sandbox_no_host_escape.py b/tests/lint/ansible/jinja/test_sandbox_no_host_escape.py new file mode 100644 index 0000000000..31d8775ed3 --- /dev/null +++ b/tests/lint/ansible/jinja/test_sandbox_no_host_escape.py @@ -0,0 +1,123 @@ +"""Forbid host escapes in the ``compose.yml.j2`` of a sandboxed role. + +Rationale +========= +A role that declares a ``kata`` service runs its workload under an +isolating runtime, because the workload executes code the model wrote. +Every directive that reaches back into the host namespace cancels that +isolation while leaving the promise in place: + +* ``privileged: true`` grants every device and capability, which makes a + device allowlist decorative. +* ``network_mode: host``, ``pid: host``, ``ipc: host`` and + ``userns_mode: host`` put the workload back into a host namespace. +* mounting ``/var/run/docker.sock`` hands the workload the host engine, + which is a root shell in one API call. + +An unenforced isolation claim is the defect this tier already shipped +once: three agent replicas ran under the shared kernel while every test +was green. + +Per-line opt-out +================ +Add ``# nocheck: sandbox-host-escape`` on the offending line or on the +immediately preceding non-empty line, together with the reason the +escape is safe for this specific service. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +_RULE = "sandbox-host-escape" + +_KATA_SERVICE = re.compile(r"^kata:\s*$", re.MULTILINE) + +_ESCAPES = ( + (re.compile(r"^\s*privileged:\s*[\"']?true[\"']?"), "privileged: true"), + (re.compile(r"^\s*network_mode:\s*[\"']?host[\"']?"), "network_mode: host"), + (re.compile(r"^\s*pid:\s*[\"']?host[\"']?"), "pid: host"), + (re.compile(r"^\s*ipc:\s*[\"']?host[\"']?"), "ipc: host"), + (re.compile(r"^\s*userns_mode:\s*[\"']?host[\"']?"), "userns_mode: host"), + (re.compile(r"docker\.sock"), "host docker socket bind"), +) + + +def _sandboxed_roles() -> set[str]: + roles: set[str] = set() + for path_str, content in iter_project_files_with_content( + extensions=(".yml",), + exclude_tests=True, + ): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + if not rel.startswith("roles/") or not rel.endswith( + "/" + ROLE_FILE_META_SERVICES + ): + continue + if _KATA_SERVICE.search(content): + roles.add(rel.split("/")[1]) + return roles + + +class TestSandboxNoHostEscape(unittest.TestCase): + def test_sandboxed_roles_do_not_escape_to_the_host(self) -> None: + sandboxed = _sandboxed_roles() + self.assertTrue( + sandboxed, + "No role declares a kata service, so this rule can never fire. " + "Either the sandbox tier was removed or the detection broke.", + ) + + findings: list[tuple[str, int, str, str]] = [] + for path_str, content in iter_project_files_with_content( + extensions=(".j2",), + exclude_tests=True, + ): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + parts = rel.split("/") + if len(parts) < 2 or parts[0] != "roles" or parts[1] not in sandboxed: + continue + if "/templates/" not in rel or not rel.endswith("compose.yml.j2"): + continue + lines = content.splitlines() + for idx, line in enumerate(lines): + for pattern, label in _ESCAPES: + if not pattern.search(line): + continue + if is_suppressed_at(lines, idx + 1, _RULE, mode="same-or-above"): + continue + findings.append((rel, idx + 1, label, line.strip())) + + if findings: + formatted = "\n".join( + f"- {p}:{n}: {label} -> {src}" + for p, n, label, src in sorted( + set(findings), key=lambda i: (i[0], i[1]) + ) + ) + self.fail( + "A role that declares a kata service runs model-written code " + "under an isolating runtime. The directives below hand that " + "workload back to the host and cancel the isolation while the " + "role keeps promising it.\n\n" + "Fix: grant the narrowest thing that works. Map individual " + "devices instead of `privileged: true`, publish ports instead " + "of joining the host network, and give the workload its own " + "container daemon instead of the host socket.\n\n" + "Mark with `# nocheck: sandbox-host-escape` plus the reason " + "only when the escape is genuinely required and the role " + "README states that the isolation claim does not hold.\n\n" + f"Offending lines:\n{formatted}" + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/lint/ansible/jinja/test_shell_templates_are_valid.py b/tests/lint/ansible/jinja/test_shell_templates_are_valid.py new file mode 100644 index 0000000000..921e159c9e --- /dev/null +++ b/tests/lint/ansible/jinja/test_shell_templates_are_valid.py @@ -0,0 +1,145 @@ +"""Lint: a shell script shipped as a Jinja template still gets checked. + +``make lint-shellcheck`` walks files on disk, so a ``*.sh.j2`` is invisible to +it: the thing that actually runs on the host is the render, and nothing looks at +the render until it fails on a node. That is an unpleasant place to discover a +quoting mistake in a script which runs as root and rewrites the host packet +filter. + +Every ``roles/*/templates/*.sh.j2`` is rendered here and handed to ``bash -n``, +plus ``shellcheck`` where it is installed. A value the lint does not know +renders as a placeholder token and an unknown collection renders as empty, so +the check judges the shape of the script rather than what a particular +deployment puts in it. Where a template's structure only becomes real with +concrete values, those live in ``_SAMPLE``. + +``SC2034`` is excluded: emptying a conditional branch orphans the variables that +branch used, so a partial render cannot tell a genuinely unused variable from +one whose only reader was not rendered. +""" + +from __future__ import annotations + +import shlex +import shutil +import subprocess +import unittest +from pathlib import Path + +import jinja2 + +from utils.cache.files import iter_project_files, read_text + +from . import PROJECT_ROOT + +_PARTIAL_RENDER_NOISE = "SC2034" + + +class _PassthroughFilters(dict): + """Any filter this environment does not know leaves the value untouched. + + The repo's own filter plugins live in ansible, not in bare jinja2, and the + check is about the shape of the resulting shell rather than about what a + filter computes. + """ + + def __missing__(self, name: str): + def _identity(value: object, *_args: object, **_kwargs: object) -> object: + return value + + return _identity + + def __contains__(self, name: object) -> bool: + """Claim every filter, because jinja resolves them at compile time.""" + return True + + def get(self, name: object, default: object = None) -> object: + """Jinja looks filters up with ``get``, which skips ``__missing__``.""" + return self[name] if name in dict.keys(self) else self.__missing__(str(name)) + + +class _Placeholder(jinja2.Undefined): + """An unknown value that keeps the rendered script syntactically whole.""" + + def __str__(self) -> str: + return "placeholder" + + def __iter__(self): + return iter(()) + + def __bool__(self) -> bool: + return False + + def __getattr__(self, name: str) -> _Placeholder: + return self + + def __getitem__(self, key: object) -> _Placeholder: + return self + + +_SAMPLE: dict[str, object] = {} + + +def _shell_templates() -> list[Path]: + found = [] + for path_str in iter_project_files(extensions=(".j2",)): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + if rel.startswith("roles/") and rel.endswith(".sh.j2"): + found.append(Path(path_str)) + return sorted(found) + + +class TestShellTemplatesAreValid(unittest.TestCase): + def test_every_shell_template_renders_to_valid_bash(self) -> None: + templates = _shell_templates() + self.assertTrue(templates, "no roles/*/templates/*.sh.j2 found to check") + shellcheck = shutil.which("shellcheck") + for path in templates: + rel = path.relative_to(PROJECT_ROOT).as_posix() + with self.subTest(template=rel): + environment = jinja2.Environment( + undefined=_Placeholder, + keep_trailing_newline=True, + autoescape=False, # noqa: S701 shell, not markup + ) + environment.filters = _PassthroughFilters(environment.filters) + environment.filters["quote"] = shlex.quote + environment.globals["lookup"] = lambda *_args, **_kwargs: "placeholder" + rendered = environment.from_string(read_text(str(path))).render( + **_SAMPLE + ) + syntax = subprocess.run( + ["bash", "-n"], + input=rendered, + capture_output=True, + text=True, + check=False, + ) + self.assertEqual( + syntax.returncode, + 0, + f"{rel} does not render to valid bash:\n{syntax.stderr}", + ) + if shellcheck is None: + continue + report = subprocess.run( + [ + shellcheck, + "--shell=bash", + f"--exclude={_PARTIAL_RENDER_NOISE}", + "-", + ], + input=rendered, + capture_output=True, + text=True, + check=False, + ) + self.assertEqual( + report.returncode, + 0, + f"{rel} fails shellcheck once rendered:\n{report.stdout}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/jinja/test_software_identity_variables.py b/tests/lint/ansible/jinja/test_software_identity_variables.py new file mode 100644 index 0000000000..dde53d1aef --- /dev/null +++ b/tests/lint/ansible/jinja/test_software_identity_variables.py @@ -0,0 +1,91 @@ +"""Lint: a template spells the software's identity through its variables. + +``SOFTWARE_NAME``, ``SOFTWARE_DOMAIN``, ``SOFTWARE_URL`` and ``ORGANIZATION`` +are declared once in ``group_vars/all/00_general.yml`` and derive from each +other. A template that writes the value instead of the variable forks that +single point: a rename reaches the four declarations and every consumer that +reads them, and silently misses the literal. + +The check needs one literal only. ``SOFTWARE_DOMAIN`` is ``SOFTWARE_NAME | +lower``, ``SOFTWARE_URL`` is ``https://`` plus the domain and ``ORGANIZATION`` +is the name again, so a case-insensitive search for the name's value finds the +value of all four. The value is read from the declaration rather than written +here, so renaming the software does not leave this lint hunting the old string. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``nocheck: software-identity`` on the offending line or the one above it, + for a literal that must survive a rename, such as an identifier a third + party already issued under the old name. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files, read_text +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +_RULE = "software-identity" +_SPOT = "group_vars/all/00_general.yml" +_NAME_KEY = "SOFTWARE_NAME" + + +def _software_name() -> str: + """The literal value of ``SOFTWARE_NAME``, read from its declaration.""" + declared = load_yaml_any(str(PROJECT_ROOT / _SPOT)) + if not isinstance(declared, dict) or _NAME_KEY not in declared: + raise AssertionError(f"{_SPOT} declares no {_NAME_KEY}") + name = declared[_NAME_KEY] + if not isinstance(name, str) or "{{" in name: + raise AssertionError( + f"{_SPOT}: {_NAME_KEY} is no longer a plain literal ({name!r}), so " + "this lint can no longer derive what to search for" + ) + return name + + +def _variable_for(line: str, start: int, matched: str) -> str: + if line[:start].endswith(("https://", "http://")): + return "SOFTWARE_URL" + if matched.islower(): + return "SOFTWARE_DOMAIN" + return f"{_NAME_KEY} (or ORGANIZATION)" + + +class TestSoftwareIdentityVariables(unittest.TestCase): + def test_no_template_spells_out_the_software_identity(self) -> None: + pattern = re.compile(re.escape(_software_name()), re.IGNORECASE) + + findings: list[str] = [] + for path in iter_project_files(extensions=(".j2",), exclude_tests=True): + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + lines = read_text(path).splitlines() + for index, line in enumerate(lines): + match = pattern.search(line) + if match is None: + continue + if is_suppressed_at(lines, index + 1, _RULE, mode="same-or-above"): + continue + variable = _variable_for(line, match.start(), match.group(0)) + findings.append( + f"- {rel}:{index + 1}: {match.group(0)!r} -> {{{{ {variable} }}}}" + ) + + if findings: + self.fail( + "These templates write the software's identity as a literal, so a " + f"rename in {_SPOT} would leave them behind:\n" + + "\n".join(findings) + + f"\n\nFix: render the declared variable instead. Mark it " + f"`nocheck: {_RULE}` when the literal must survive a rename." + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/modules/test_credential_tasks_are_masked.py b/tests/lint/ansible/modules/test_credential_tasks_are_masked.py new file mode 100644 index 0000000000..ebd45992c8 --- /dev/null +++ b/tests/lint/ansible/modules/test_credential_tasks_are_masked.py @@ -0,0 +1,357 @@ +"""Lint: a task that carries a credential is masked by itself or by a parent. + +At ``-vvv`` Ansible prints every module argument and every result, so a +credential in a command line, a request body, an environment or a fact lands in +the deploy log. A task counts as masked when any of these holds: + +* it, or an enclosing ``block``/``rescue``/``always``, sets ``no_log``; +* every file that pulls it in does so through ``include_tasks`` with + ``apply: {no_log: ...}`` or through ``import_tasks`` with ``no_log``, or sits + in a masked parent itself (checked transitively); +* the credential only reaches a parameter the module masks on its own, or the + module masks its values (``mask_values``). + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: credential-masking`` on, or directly above, the task's ``- name:``. +""" + +from __future__ import annotations + +import re +import unittest +from collections import defaultdict +from pathlib import Path +from typing import ClassVar + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content +from utils.cache.yaml import load_yaml_str + +from . import PROJECT_ROOT + +_RULE = "credential-masking" +_JINJA = re.compile(r"\{\{.*?\}\}|\{%.*?%\}", re.DOTALL) +_SECRET = re.compile( + r"(?i)\b[a-z0-9_]*(?:password|secret|token|api_?key|private_?key)\b(?!\s*\()" + r"|secrets\.credentials\." +) +_TRUTHY = re.compile(r"MASK_CREDENTIALS_IN_LOGS|^\s*(?:true|yes|on)\s*$", re.IGNORECASE) +_NAME_LINE = re.compile(r"^\s*-\s+name:\s*(.+?)\s*$") +_BLOCK_KEYS = ("block", "rescue", "always") +_INCLUDE_KEYS = ("include_tasks", "ansible.builtin.include_tasks") +_IMPORT_KEYS = ("import_tasks", "ansible.builtin.import_tasks") +_SILENT_KEYS = frozenset( + { + "include_role", + "import_role", + "meta", + "ansible.builtin.include_role", + "ansible.builtin.import_role", + "ansible.builtin.meta", + } +) +_TASK_KEYWORDS = frozenset( + { + "name", + "when", + "register", + "until", + "changed_when", + "failed_when", + "no_log", + "tags", + "notify", + "listen", + "delegate_to", + "delegate_facts", + "run_once", + "retries", + "delay", + "loop_control", + "become", + "become_user", + "become_method", + "ignore_errors", + "ignore_unreachable", + "vars", + "timeout", + "async", + "poll", + "check_mode", + "diff", + "throttle", + "any_errors_fatal", + "connection", + } +) +_MODULE_MASKED_PARAMS = frozenset( + {"url_password", "login_password", "password", "api_token", "account_api_key"} +) +_PATH_ABSOLUTE = re.compile(r"path_absolute['\"]\s*,\s*['\"]([^'\"]+)['\"]") +_ROLE_PATH = re.compile(r"\{\{\s*role_path\s*\}\}/(.+)$") + + +def _masks(value: object) -> bool: + return value is not None and value is not False and bool(_TRUTHY.search(str(value))) + + +def _has_secret(value: object) -> bool: + return any(_SECRET.search(span) for span in _JINJA.findall(str(value))) + + +def carries_unmasked_secret(task: dict) -> bool: + """Whether a leaf task prints a credential no module masking hides. + + Args: + task: one parsed task mapping without block keys. + """ + for key, value in task.items(): + if key in _TASK_KEYWORDS: + continue + if isinstance(value, dict): + if _masks(value.get("mask_values")): + return False + printed = {k: v for k, v in value.items() if k not in _MODULE_MASKED_PARAMS} + if _has_secret(printed): + return True + elif _has_secret(value): + return True + return False + + +def _include_spec(task: dict) -> tuple[str, object]: + for key in _INCLUDE_KEYS + _IMPORT_KEYS: + if key in task: + return key, task[key] + return "", None + + +def _resolve(including: Path, spec: object, known: set[Path]) -> Path | None: + file = spec.get("file") if isinstance(spec, dict) else spec + if not isinstance(file, str): + return None + role_dir = next( + (p.parent for p in including.parents if p.name in ("tasks", "handlers")), None + ) + candidates = [] + absolute = _PATH_ABSOLUTE.search(file) + role_relative = _ROLE_PATH.search(file) + if absolute: + candidates.append(PROJECT_ROOT / absolute.group(1)) + elif role_relative and role_dir: + candidates.append(role_dir / role_relative.group(1)) + elif "{{" not in file: + candidates.append(including.parent / file) + if role_dir: + candidates.append(role_dir / "tasks" / file) + for candidate in candidates: + resolved = candidate.resolve() + if resolved in known: + return resolved + return None + + +def find_leaks(tasks_by_file: dict[Path, list]) -> list[tuple[Path, str]]: + """Return ``(file, task name)`` for every credential task no parent masks. + + Args: + tasks_by_file: parsed task lists keyed by resolved file path. + """ + known = set(tasks_by_file) + includers: dict[Path, list[tuple[Path, bool]]] = defaultdict(list) + leaks: list[tuple[Path, str]] = [] + + def walk(path: Path, tasks: object, inherited: bool) -> None: + for task in tasks if isinstance(tasks, list) else (): + if not isinstance(task, dict): + continue + masked = inherited or _masks(task.get("no_log")) + if any(key in task for key in _BLOCK_KEYS): + for key in _BLOCK_KEYS: + walk(path, task.get(key), masked) + continue + kind, spec = _include_spec(task) + if kind: + target = _resolve(path, spec, known) + if target is not None: + apply = spec.get("apply") if isinstance(spec, dict) else None + covers = ( + masked + if kind in _IMPORT_KEYS + else ( + inherited + or (isinstance(apply, dict) and _masks(apply.get("no_log"))) + ) + ) + includers[target].append((path, covers)) + continue + if _SILENT_KEYS & task.keys(): + continue + if not masked and carries_unmasked_secret(task): + leaks.append((path, str(task.get("name", "")))) + + for path, tasks in tasks_by_file.items(): + walk(path, tasks, False) + + def covered(path: Path, seen: frozenset) -> bool: + parents = includers.get(path) + if not parents or path in seen: + return False + return all( + covers or covered(source, seen | {path}) for source, covers in parents + ) + + return [(path, name) for path, name in leaks if not covered(path, frozenset())] + + +def _task_files() -> dict[Path, tuple[list, list[str]]]: + files = {} + for path, content in iter_project_files_with_content(extensions=(".yml",)): + parts = Path(path).relative_to(PROJECT_ROOT).parts + if ( + len(parts) < 3 + or parts[0] != "roles" + or parts[2] not in ("tasks", "handlers") + ): + continue + data = load_yaml_str(content) + if isinstance(data, list): + files[Path(path).resolve()] = (data, content.splitlines()) + return files + + +def _unquote(value: str) -> str: + if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"": + return value[1:-1] + return value + + +def _name_line(lines: list[str], name: str) -> int: + for number, line in enumerate(lines, start=1): + match = _NAME_LINE.match(line) + if match and _unquote(match.group(1)) == name: + return number + return 1 + + +def is_suppressed(lines: list[str], name: str) -> bool: + return is_suppressed_at(lines, _name_line(lines, name), _RULE) + + +def unmasked_credential_tasks() -> list[str]: + files = _task_files() + findings = [] + for path, name in find_leaks({p: data for p, (data, _) in files.items()}): + lines = files[path][1] + if is_suppressed(lines, name): + continue + number = _name_line(lines, name) + rel = path.relative_to(PROJECT_ROOT.resolve()) + findings.append(f"{rel}:{number}: {name[:70]}") + return findings + + +class TestCredentialTasksAreMasked(unittest.TestCase): + def test_every_credential_task_is_masked_by_itself_or_a_parent(self) -> None: + findings = unmasked_credential_tasks() + self.assertEqual( + [], + findings, + f"task(s) print a credential without no_log ({len(findings)}); set " + '`no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}"` on the task or a ' + "parent:\n" + "\n".join(f" - {f}" for f in findings), + ) + + def test_the_scan_reaches_role_task_files(self) -> None: + self.assertGreater(len(_task_files()), 100) + + +class TestParentMasking(unittest.TestCase): + ROOT = PROJECT_ROOT.resolve() / "roles/x/tasks" + SECRET_TASK: ClassVar[dict] = { + "name": "leak", + "ansible.builtin.shell": "run {{ X_PASSWORD }}", + } + + def _leaks(self, main: list, child: list | None = None) -> list[str]: + files = {self.ROOT / "main.yml": main} + if child is not None: + files[self.ROOT / "child.yml"] = child + return [name for _, name in find_leaks(files)] + + def test_an_unmasked_credential_task_is_found(self) -> None: + self.assertEqual(self._leaks([dict(self.SECRET_TASK)]), ["leak"]) + + def test_an_enclosing_block_masks(self) -> None: + block = { + "no_log": "{{ MASK_CREDENTIALS_IN_LOGS | bool }}", + "block": [self.SECRET_TASK], + } + self.assertEqual(self._leaks([block]), []) + + def test_an_include_apply_masks_the_included_file(self) -> None: + include = { + "include_tasks": { + "file": "child.yml", + "apply": {"no_log": "{{ MASK_CREDENTIALS_IN_LOGS | bool }}"}, + } + } + self.assertEqual(self._leaks([include], [self.SECRET_TASK]), []) + + def test_an_import_with_no_log_masks_the_imported_file(self) -> None: + imported = { + "import_tasks": "child.yml", + "no_log": "{{ MASK_CREDENTIALS_IN_LOGS | bool }}", + } + self.assertEqual(self._leaks([imported], [self.SECRET_TASK]), []) + + def test_no_log_on_an_include_itself_does_not_reach_the_included_file(self) -> None: + include = { + "include_tasks": "child.yml", + "no_log": "{{ MASK_CREDENTIALS_IN_LOGS | bool }}", + } + self.assertEqual(self._leaks([include], [self.SECRET_TASK]), ["leak"]) + + def test_a_parameter_the_module_masks_needs_no_no_log(self) -> None: + task = { + "name": "login", + "uri": {"url": "http://x", "url_password": "{{ X_PASSWORD }}"}, + } + self.assertEqual(self._leaks([task]), []) + + def test_a_path_that_only_names_a_secret_is_not_a_credential(self) -> None: + task = { + "name": "dir", + "file": {"path": "{{ DIR_SECRETS }}", "state": "directory"}, + } + self.assertEqual(self._leaks([task]), []) + + +class TestSuppression(unittest.TestCase): + NAME = "๐Ÿ“ฆ bench new-site '{{ SITE }}'" + + def test_a_marker_above_the_name_suppresses_the_task(self) -> None: + lines = [ + "---", + "- name: other", + " shell: y", + "# nocheck: credential-masking", + f'- name: "{self.NAME}"', + " shell: x", + ] + self.assertTrue(is_suppressed(lines, self.NAME)) + + def test_a_marker_above_another_task_does_not_suppress(self) -> None: + lines = [ + "# nocheck: credential-masking", + "- name: other", + " shell: y", + f'- name: "{self.NAME}"', + " shell: x", + ] + self.assertFalse(is_suppressed(lines, self.NAME)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/modules/test_systemd_units_via_sys_service.py b/tests/lint/ansible/modules/test_systemd_units_via_sys_service.py new file mode 100644 index 0000000000..4edb292bfa --- /dev/null +++ b/tests/lint/ansible/modules/test_systemd_units_via_sys_service.py @@ -0,0 +1,80 @@ +"""Lint: a systemd unit is installed through sys-service, not by hand. + +``sys-service`` owns what it takes to make a unit real: resolving the template, +writing it into the system unit directory, reloading the daemon, enabling and +starting it, the timer variant, and the async and flush behaviour the deploy +relies on. A role that renders its own ``*.service.j2`` with a bare ``template:`` +gets the file and none of the rest, and every one of those omissions is silent โ€” +a unit that exists but was never enabled looks installed until the host reboots. + +It is also how the same decisions end up answered differently per role. That is +not hypothetical: the role this lint was written alongside rendered its own unit +and its own reload handler before anyone noticed sys-service already did both. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: systemd-via-sys-service`` on the ``src:`` line or anywhere in the + task body, for a unit sys-service genuinely cannot carry. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content + +from . import PROJECT_ROOT + +_RULE = "systemd-via-sys-service" +_OWNER = "sys-service" +_UNIT_SRC = re.compile(r"^\s*src:\s*[\"']?(?P[^\"'\s]+\.service\.j2)[\"']?") + + +def _is_task_file(rel_path: str) -> bool: + return ( + rel_path.startswith("roles/") + and "/tasks/" in rel_path + and rel_path.endswith((".yml", ".yaml")) + ) + + +def _role_of(rel_path: str) -> str: + return Path(rel_path).parts[1] + + +class TestSystemdUnitsViaSysService(unittest.TestCase): + def test_no_role_installs_its_own_unit(self) -> None: + findings: list[str] = [] + for path_str, content in iter_project_files_with_content( + extensions=(".yml", ".yaml"), + exclude_tests=True, + ): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + if not _is_task_file(rel) or _role_of(rel) == _OWNER: + continue + lines = content.splitlines() + for index, line in enumerate(lines): + match = _UNIT_SRC.match(line) + if match is None: + continue + if is_suppressed_at(lines, index + 1, _RULE, mode="same-or-above"): + continue + findings.append(f"- {rel}:{index + 1}: {match.group('src')}") + + if findings: + self.fail( + "These roles render a systemd unit themselves instead of handing " + "it to sys-service, which also reloads the daemon, enables the " + "unit, and carries the timer, async and flush behaviour:\n" + + "\n".join(sorted(set(findings))) + + "\n\nFix: name the template templates/systemctl.service.j2 and " + "include the sys-service role with system_service_id, or mark the " + f"task `# nocheck: {_RULE}` when sys-service cannot carry it." + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/meta/test_embedded_state_on_nfs.py b/tests/lint/ansible/roles/meta/test_embedded_state_on_nfs.py new file mode 100644 index 0000000000..82361a71b0 --- /dev/null +++ b/tests/lint/ansible/roles/meta/test_embedded_state_on_nfs.py @@ -0,0 +1,166 @@ +"""Lint: a role without an external database MUST NOT keep read-write state on +a shared NFS volume. + +Under swarm an unpinned role's volumes are rewritten onto the shared NFS export +(``utils/storage/nfs.py``) while its services run one task per node. A role that +declares no RDBMS service keeps its state in-process instead: an embedded SQLite +file, a Mnesia store, a Lucene index. Those writers assume POSIX locking that +NFS does not deliver, so the replicas write the same files over NFS and corrupt +them. + +Resolve it by externalising the state into a database service, by taking the +volume off NFS (``nfs: false``) together with a single replica or a manager pin, +or -- when the payload is genuinely share-safe, such as write-once model blobs +or a regenerable asset cache -- with a +``# nocheck: embedded-state-on-nfs `` marker on the volume entry. + +Roles that do declare a database service are out of scope: their shared volumes +carry uploads and media, which several replicas may safely write side by side. +""" + +from __future__ import annotations + +import re +import unittest +from typing import TYPE_CHECKING + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.applications.services.database import RDBMS_SERVICE_KEYS +from utils.roles.entity.name import get_entity_name +from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_META_VOLUMES +from utils.roles.meta_lookup import get_role_mode_enabled +from utils.storage.nfs import swarm_nfs_backed + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from pathlib import Path + +_RULE = "embedded-state-on-nfs" + + +def _load_services(role_dir: Path) -> dict: + content = load_yaml_any( + str(role_dir / ROLE_FILE_META_SERVICES), default_if_missing={} + ) + return content if isinstance(content, dict) else {} + + +def _has_rdbms_service(services: dict) -> bool: + """True when the role runs its own RDBMS, so its state is not in-process. + + A Jinja-valued ``enabled`` counts as enabled: it resolves per inventory, and + treating it as absent would flag every optionally-attached database. + """ + for key in RDBMS_SERVICE_KEYS: + spec = services.get(key) + if not isinstance(spec, dict): + continue + if str(spec.get("enabled", "")).strip().lower() != "false": + return True + return False + + +def _declares_one_replica(spec: object) -> bool: + return isinstance(spec, dict) and str(spec.get("replicas", "")).strip() == "1" + + +def _single_replica_service_names(role_id: str, services: dict) -> set[str] | None: + """Service names that run exactly one task, or ``None`` when the whole role + does. + + A mount names the service by its rendered ``name``, which defaults to the + entity key. Replicas resolve service-first and fall back to the primary + entity, so a pin there covers every service in the role. + """ + primary = get_entity_name(role_id) or role_id + if _declares_one_replica(services.get(primary)): + return None + return { + str(spec.get("name", key)) + for key, spec in services.items() + if _declares_one_replica(spec) + } + + +def _key_lines(lines: list[str]) -> dict[str, int]: + found: dict[str, int] = {} + for idx, line in enumerate(lines, 1): + match = re.match(r"^([A-Za-z0-9_.-]+):", line) + if match and match.group(1) not in found: + found[match.group(1)] = idx + return found + + +def _collect_findings(root: Path) -> list[str]: + findings: list[str] = [] + for volumes_yml in sorted((root / "roles").glob(f"*/{ROLE_FILE_META_VOLUMES}")): + role_dir = volumes_yml.parent.parent + role_id = role_dir.name + if not get_role_mode_enabled(role_dir, mode="swarm", role_name=role_id): + continue + services = _load_services(role_dir) + if _has_rdbms_service(services): + continue + pinned = _single_replica_service_names(role_id, services) + if pinned is None: + continue + + content = load_yaml_any(str(volumes_yml), default_if_missing={}) + if not isinstance(content, dict): + continue + try: + lines = read_text(str(volumes_yml)).splitlines() + except OSError: + continue + key_lines = _key_lines(lines) + + for key, entry in content.items(): + if not isinstance(entry, dict) or entry.get("type") != "volume": + continue + if not swarm_nfs_backed( + entry, + application_id=role_id, + deployment_mode="swarm", + storage_backend="nfs", + ): + continue + line = key_lines.get(key) + if line and is_suppressed_at(lines, line, _RULE, mode="same-or-above"): + continue + for mount in entry.get("mounts") or []: + if not isinstance(mount, dict) or mount.get("read_only") is True: + continue + service = str(mount.get("service", "")) + if service in pinned: + continue + findings.append( + f"{role_id}: volume '{key}' is NFS-backed and mounted " + f"read-write by '{service}' at '{mount.get('target')}', " + "but the role declares no database service, so this is " + "in-process state written by every replica." + ) + break + return findings + + +class TestEmbeddedStateOnNfs(unittest.TestCase): + def test_databaseless_roles_keep_no_rw_state_on_nfs(self) -> None: + findings = _collect_findings(PROJECT_ROOT) + if not findings: + return + details = "\n".join(f" - {f}" for f in findings) + self.fail( + f"{len(findings)} NFS-backed volume(s) hold in-process state that " + "every replica writes. Externalise the state to a database, take " + "the volume off NFS (`nfs: false`) with a single replica or a " + "manager pin, or mark a genuinely share-safe payload with " + "`# nocheck: embedded-state-on-nfs ` on the volume " + f"entry.\n{details}" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/meta/test_healthcheck_binary_on_slim_base.py b/tests/lint/ansible/roles/meta/test_healthcheck_binary_on_slim_base.py new file mode 100644 index 0000000000..a883650bcc --- /dev/null +++ b/tests/lint/ansible/roles/meta/test_healthcheck_binary_on_slim_base.py @@ -0,0 +1,239 @@ +"""A healthcheck must find every program it runs in the image it runs in. + +A stripped base carries the runtime and little else, and which "little else" +differs per family. The declaration does not know that: ``flavor: curl`` renders +``CMD curl -f `` and ``flavor: tcp`` renders ``CMD bash -c`` over +``/dev/tcp`` whatever the image underneath is. Where the program is absent the +probe fails from its first beat and the container never reports healthy. + +The two deploy modes answer differently, and neither answer names the program. +``sys-svc-compose`` waits on the database container alone in compose and on +every stack task in swarm, so a permanently unhealthy service passes unnoticed +under compose and stops the deploy under swarm: the task dies with ``non-zero +exit (137): dockerexec: unhealthy container``, is rescheduled, dies again, and +the wait fails. Every deployment holding the service in its closure fails with +it, reported against the service that was waited for. + +What is checked +=============== +Every ``meta/services.yml`` healthcheck whose service sits on a base this file +has measured. The programs come from the probe the declaration renders +(:func:`utils.docker.healthcheck.compose.compose`), both its ``CMD`` and its +``CMD-SHELL`` form, so a flavor that changes its command moves this check with +it rather than drifting from a table restated here. ``||`` in a shell probe is +read as alternatives, ``&&`` and ``;`` as a sequence that needs all of its +parts, and shell builtins are dropped so a trailing ``|| exit 1`` cannot make +every requirement look satisfiable. + +A requirement is met when the measured base provides the program or the role's +``files/Dockerfile`` installs it. A base that is neither family is skipped: a +vendor image's contents are not knowable from the tree, and for most of them +there is no Dockerfile of ours to add anything to. + +Per-service opt-out +=================== +``# nocheck: healthcheck-binary`` on the ``flavor`` line or the one above it, +with a reason naming where the program comes from instead. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.docker.healthcheck.compose import compose +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +RULE = "healthcheck-binary" + +PROVIDED: dict[str, frozenset[str]] = { + "slim": frozenset({"bash", "sh"}), + "alpine": frozenset({"sh", "wget", "nc"}), +} +"""What each stripped family ships, read out of the images themselves. + +Measured with ``docker create`` plus ``docker cp``, which reports a path that is +absent instead of reporting a shell's opinion of it. Every lookup covered +``/usr/bin``, ``/bin``, ``/usr/local/bin`` and ``/sbin``: + +* ``debian:13-slim``, ``node:26-slim`` and ``python:3.13.15-slim`` carry + ``/bin/bash`` at 1298416 bytes and none of ``curl``, ``wget`` or ``nc``. bash + is Essential in Debian and the other three are not, which is the whole + difference between the stripped tag and the full one: the full ``node:26`` + variant carries ``/usr/bin/curl`` at 280800 bytes. +* ``redis:8-alpine`` and ``node:26-alpine`` carry ``/usr/bin/wget`` and + ``/usr/bin/nc`` as busybox applets, no ``curl``, and no ``/bin/bash`` at all. + Their ``/bin/sh`` is busybox, which does not implement ``/dev/tcp``, so the + flavors built on that redirection need the real shell rather than any shell. + +The family is read from the tag, which holds for every image in the tree today: +every ``slim`` tag here is Debian based and every ``alpine`` tag is Alpine +based. Adding a family means measuring it the same way, not inferring it. +""" + +IMAGE_PROVIDES: dict[str, frozenset[str]] = { + "nginx": frozenset({"curl"}), +} +"""Programs an individual image adds on top of what its family ships. + +nginx installs curl in both of its variants: ``/usr/bin/curl`` at 272432 bytes +in ``nginx:1.31.6-alpine`` and at 321880 bytes in the Debian ``nginx:1.31``. +Base Alpine does not have it at all, measured the same way on ``redis:8-alpine`` +and ``node:26-alpine``. Reading nginx's curl as a property of Alpine would pass +a ``curl`` flavor on any alpine image, so it is recorded against the image that +installs it. +""" + +SHELL_BUILTINS = frozenset({"exit", "true", "false", "test", "[", ":", "echo"}) +"""Words a probe may invoke that no package provides.""" + + +def _families(version: object) -> list[str]: + """The measured families a version tag names, in declaration order.""" + text = str(version) + return [family for family in PROVIDED if family in text] + + +def _image_extras(image: object) -> frozenset[str]: + """What this particular image adds beyond its family. + + Args: + image: the ``image`` value, with or without a registry prefix. + """ + name = str(image).rsplit("/", 1)[-1] + return IMAGE_PROVIDES.get(name, frozenset()) + + +def _requirements(flavor: object) -> list[list[str]]: + """The programs a declared flavor runs, as alternatives of sequences. + + ``[["wget"], ["curl"]]`` means either one satisfies the probe; + ``[["msmtp", "curl"]]`` would mean it needs both. + + Args: + flavor: the ``healthcheck.flavor`` value, one name or a list. + """ + try: + test = [ + str(part) + for part in compose(flavor, port=80, path="/", hostname="h").test() + ] + except Exception: + return [] + if not test: + return [] + if test[0] == "CMD": + return [[test[1]]] if len(test) > 1 else [] + if len(test) < 2: + return [] + groups: list[list[str]] = [] + for alternative in re.split(r"\|\|", test[1]): + words = [ + segment.strip().split()[0] + for segment in re.split(r"&&|;", alternative) + if segment.strip() + ] + needed = [word for word in words if word not in SHELL_BUILTINS] + if needed: + groups.append(needed) + return groups + + +def _installs(dockerfile_body: str, program: str) -> bool: + """Whether the Dockerfile names the program as something it installs.""" + pattern = rf"(? dict[str, int]: + """The 1-based ``flavor:`` line of each top-level service key. + + ``meta/services.yml`` maps one service per top-level key, so the flavor a + key owns is the first one under it. Taking the file's first flavor line + instead would let one service's marker silence another's. + + Args: + lines: the file's lines, as :func:`read_text` splits them. + """ + found: dict[str, int] = {} + current: str | None = None + for number, line in enumerate(lines, start=1): + key = re.match(r"([A-Za-z0-9_.-]+):\s*(?:#.*)?$", line) + if key: + current = key.group(1) + continue + if current and current not in found and re.match(r"\s+flavor:", line): + found[current] = number + return found + + +class TestHealthcheckBinaryOnSlimBase(unittest.TestCase): + def test_a_stripped_base_provides_every_program_its_healthcheck_runs(self): + offenders = [] + for services in sorted( + (PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_SERVICES}") + ): + role_dir = services.parent.parent + data = load_yaml_any(str(services), default_if_missing={}) or {} + lines = read_text(str(services)).splitlines() + flavor_lines = _flavor_lines(lines) + for key, entry in data.items(): + if not isinstance(entry, dict): + continue + health = entry.get("healthcheck") + if not isinstance(health, dict) or "flavor" not in health: + continue + families = _families(entry.get("version", "")) + if not families: + continue + groups = _requirements(health["flavor"]) + if not groups: + continue + if is_suppressed_at(lines, flavor_lines.get(key, 0), RULE): + continue + dockerfile = role_dir / "files" / "Dockerfile" + body = read_text(str(dockerfile)) if dockerfile.is_file() else "" + available = set().union(*(PROVIDED[family] for family in families)) + available |= _image_extras(entry.get("image", "")) + satisfied = any( + all( + program in available or _installs(body, program) + for program in group + ) + for group in groups + ) + if satisfied: + continue + wanted = " or ".join(" and ".join(group) for group in groups) + offenders.append( + f"{role_dir.name}: service '{key}' declares healthcheck " + f"flavor {health['flavor']!r}, which runs {wanted}, on the " + f"{'/'.join(families)} image {entry.get('image')}:" + f"{entry.get('version')} that provides " + f"{', '.join(sorted(available))}; " + + ( + "files/Dockerfile installs none of them" + if body + else "the role has no files/Dockerfile" + ) + ) + + self.assertEqual( + [], + offenders, + "A stripped base carries the runtime and little else, so a program a " + "healthcheck runs has to come from the base or from the role that " + "depends on it. Install it in the role's files/Dockerfile, pick a " + "flavor the image can already run, or mark the line " + f"`# nocheck: {RULE}` with a reason naming where the program comes " + "from:\n " + "\n ".join(offenders), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/meta/test_healthcheck_timing_overrides.py b/tests/lint/ansible/roles/meta/test_healthcheck_timing_overrides.py new file mode 100644 index 0000000000..12d1504829 --- /dev/null +++ b/tests/lint/ansible/roles/meta/test_healthcheck_timing_overrides.py @@ -0,0 +1,366 @@ +"""A ``healthcheck`` timing in ``meta/services.yml`` either matches its flavor's +default and should be gone, or differs and must say why. + +``utils/docker/healthcheck`` owns the five timings. ``Probe`` holds the platform +defaults, every flavor may raise its own (``Curl`` probes every minute, +``Connect`` grants a fifteen minute start window), and a prefix raises them +further. The lookup then writes ``overrides.get(key, effective_default)``, so a +service that repeats what it would have inherited changes nothing and only hides +the moment the default moves. + +A value that differs is a decision, and one that costs something carries a +reason rather than a number alone. Four do. ``interval`` is steady state load +for the life of the deployment. ``timeout`` decides when a slow probe counts as +a failure. ``start_interval`` is the only timing that moves the moment a stack +reports healthy, and ``start_period`` is the window it lives in: shorten that +window below the service's real boot and the fast cadence stops covering it, so +the tail of the boot waits a whole ``interval`` again. ``retries`` only buys +patience with a container that is already broken, so a deviation there needs no +defence and only the redundant restatement is flagged. + +Comparison is against the EFFECTIVE default, resolved through the same +``compose`` the lookup uses. Comparing against ``Probe`` alone would flag every +service that simply agrees with its flavor. + +A definition that does NOT go through the lookup inherits nothing from the SPOT. +Docker has no daemon-wide healthcheck default to fall back on: ``daemon.json`` +carries storage, logging, DNS, registries and runtimes, and no ``health-*`` key +at all. An omitted timing therefore lands on DOCKER's default, not the +platform's, and the two disagree where it matters most, ``start_period`` being +zero rather than thirty seconds, which leaves ``start_interval`` no window to +act in. So a literal ``healthcheck:`` block in a template, and a ``HEALTHCHECK`` +line in a role's own Dockerfile, must spell every timing out at the platform +value. + +Per-key opt-out +=============== +``# nocheck: healthcheck-timing-override`` on the timing line or the one above +it, with a short reason. The reason is the point: a bare marker restates the +number the reader can already see. For a value a literal definition leaves out +entirely, put the marker on the ``healthcheck:`` or ``HEALTHCHECK`` line, which +is the only line the omission has. +""" + +from __future__ import annotations + +import contextlib +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content, read_text +from utils.cache.yaml import load_yaml_any +from utils.docker.healthcheck.compose import compose, timing_rank +from utils.docker.healthcheck.probes import TIMING_DEFAULTS +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +RULE = "healthcheck-timing-override" +COVER_RULE = "healthcheck-start-period-covers-interval" + +DOCUMENTED_KEYS = ("interval", "timeout", "start_interval", "start_period") + + +def _means_the_same(declared: object, default: object) -> bool: + """Whether a declared timing says what the default says, 600s and 10m alike. + + Args: + declared: the value written in the file, possibly a jinja expression. + default: the value the service would inherit. + """ + if str(declared) == str(default): + return True + left, right = timing_rank(declared), timing_rank(default) + return left > 0 and right > 0 and left == right + + +def _effective_defaults(flavor: object) -> dict[str, object]: + """The timings a service inherits when it declares none. + + Args: + flavor: the ``healthcheck.flavor`` value, empty for an explicit test. + """ + if not flavor: + return dict(TIMING_DEFAULTS) + with contextlib.suppress(Exception): + probe = compose(flavor) # type: ignore[arg-type] + return {key: getattr(probe, key) for key in TIMING_DEFAULTS} + return dict(TIMING_DEFAULTS) + + +def _timing_line(lines: list[str], service: str, key: str) -> int | None: + """1-based line of ``key`` inside *service*'s healthcheck block.""" + in_service = False + in_health = False + for index, line in enumerate(lines, start=1): + if re.match(rf"^{re.escape(service)}\s*:", line): + in_service, in_health = True, False + continue + if in_service and re.match(r"^\S", line): + return None + if in_service and re.match(r"^\s+healthcheck\s*:", line): + in_health = True + continue + if in_health and re.match(r"^\s{0,2}\S", line): + in_health = False + if in_health and re.match(rf"^\s+{re.escape(key)}\s*:", line): + return index + return None + + +def timing_findings() -> tuple[list[str], list[str]]: + """Return ``(redundant, undocumented)`` findings as printable lines.""" + redundant: list[str] = [] + undocumented: list[str] = [] + for meta in sorted((PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_SERVICES}")): + try: + content = read_text(str(meta)) + data = load_yaml_any(str(meta), default_if_missing={}) or {} + except (OSError, ValueError): + continue + if not isinstance(data, dict): + continue + lines = content.splitlines() + rel = meta.relative_to(PROJECT_ROOT).as_posix() + for service, entry in data.items(): + if not isinstance(entry, dict): + continue + health = entry.get("healthcheck") + if not isinstance(health, dict): + continue + defaults = _effective_defaults(health.get("flavor")) + for key, default in defaults.items(): + if key not in health: + continue + line_no = _timing_line(lines, service, key) + where = f"{rel}:{line_no or '?'} {service}.{key}" + if _means_the_same(health[key], default): + redundant.append(f"{where} = {health[key]} (the default)") + elif key in DOCUMENTED_KEYS and ( + line_no is None or not is_suppressed_at(lines, line_no, RULE) + ): + undocumented.append(f"{where} = {health[key]}, default {default}") + return redundant, undocumented + + +_YAML_KEY = re.compile(r"^\s*healthcheck:\s*(?:#.*)?$") +_DOCKERFILE_KEY = "HEALTHCHECK" +_DOCKERFILE_FLAG = "--{key}=" + + +def _yaml_literal_timings(lines: list[str], index: int) -> dict[str, tuple[str, int]]: + """Timings declared under the ``healthcheck:`` at *index*, with their lines.""" + indent = len(lines[index]) - len(lines[index].lstrip()) + found: dict[str, tuple[str, int]] = {} + for offset, line in enumerate(lines[index + 1 :], start=index + 2): + if not line.strip(): + break + if len(line) - len(line.lstrip()) <= indent: + break + for key in TIMING_DEFAULTS: + match = re.match(rf"^\s+{key}\s*:\s*(.+?)\s*(?:#.*)?$", line) + if match: + found[key] = (match.group(1), offset - 1) + return found + + +def _dockerfile_timings(lines: list[str], index: int) -> dict[str, tuple[str, int]]: + """Timings on the ``HEALTHCHECK`` at *index*, following its continuations. + + Every timing reports the instruction's own line, not the continuation it + happens to sit on: a backslash continuation cannot carry a comment, so the + only line a marker can live above is where the instruction starts. + """ + found: dict[str, tuple[str, int]] = {} + cursor = index + while cursor < len(lines): + for key in TIMING_DEFAULTS: + flag = _DOCKERFILE_FLAG.format(key=key.replace("_", "-")) + match = re.search(rf"{re.escape(flag)}(\S+)", lines[cursor]) + if match: + found[key] = (match.group(1), index + 1) + if not lines[cursor].rstrip().endswith("\\"): + break + cursor += 1 + return found + + +def literal_findings() -> list[str]: + """Timings a non-lookup definition gets wrong, omits, or leaves unexplained.""" + findings: list[str] = [] + for path_str, content in iter_project_files_with_content(exclude_tests=True): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + if not rel.startswith("roles/"): + continue + is_dockerfile = Path(rel).name.startswith("Dockerfile") + if not (rel.endswith(".j2") or is_dockerfile): + continue + lines = content.splitlines() + for index, line in enumerate(lines): + if is_dockerfile: + if not line.lstrip().startswith(_DOCKERFILE_KEY): + continue + declared = _dockerfile_timings(lines, index) + else: + if not _YAML_KEY.match(line): + continue + declared = _yaml_literal_timings(lines, index) + if not declared and "{{" not in content: + continue + anchor = index + 1 + for key, default in TIMING_DEFAULTS.items(): + value, line_no = declared.get(key, (None, anchor)) + if value is not None and _means_the_same(value, default): + continue + if value is not None and key not in DOCUMENTED_KEYS: + continue + if is_suppressed_at(lines, line_no, RULE): + continue + shown = "omitted" if value is None else value + findings.append(f"{rel}:{line_no} {key} = {shown}, default {default}") + return findings + + +def _uncovered(start_period: object, interval: object) -> bool: + """Whether the start window fails to outlast one steady state tick. + + A jinja expression is unreadable rather than zero, so it is left alone; an + absent window really is zero, because docker defaults it to none. + + Args: + start_period: the effective window, ``None`` when it is not written. + interval: the effective steady state cadence. + """ + tick = timing_rank(interval) + if tick <= 0: + return False + if start_period is None: + return True + window = timing_rank(start_period) + if window <= 0 and str(start_period).strip() not in ("0", "0s"): + return False + return window <= tick + + +def windows_shorter_than_a_tick() -> list[str]: + """Every healthcheck whose start window does not outlast one interval.""" + findings: list[str] = [] + for meta in sorted((PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_SERVICES}")): + try: + content = read_text(str(meta)) + data = load_yaml_any(str(meta), default_if_missing={}) or {} + except (OSError, ValueError): + continue + if not isinstance(data, dict): + continue + lines = content.splitlines() + rel = meta.relative_to(PROJECT_ROOT).as_posix() + for service, entry in data.items(): + if not isinstance(entry, dict): + continue + health = entry.get("healthcheck") + if not isinstance(health, dict): + continue + effective = _effective_defaults(health.get("flavor")) + effective.update({k: v for k, v in health.items() if k in effective}) + if not _uncovered(effective["start_period"], effective["interval"]): + continue + line_no = _timing_line(lines, service, "start_period") or 1 + if is_suppressed_at(lines, line_no, COVER_RULE): + continue + findings.append( + f"{rel}:{line_no} {service} start_period " + f"{effective['start_period']} <= interval {effective['interval']}" + ) + + for path_str, content in iter_project_files_with_content(exclude_tests=True): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + if not rel.startswith("roles/"): + continue + is_dockerfile = Path(rel).name.startswith("Dockerfile") + if not (rel.endswith(".j2") or is_dockerfile): + continue + lines = content.splitlines() + for index, line in enumerate(lines): + if is_dockerfile: + if not line.lstrip().startswith(_DOCKERFILE_KEY): + continue + declared = _dockerfile_timings(lines, index) + else: + if not _YAML_KEY.match(line): + continue + declared = _yaml_literal_timings(lines, index) + if not declared: + continue + window = declared.get("start_period", (None, index + 1)) + tick = declared.get("interval", (None, index + 1)) + if tick[0] is None or not _uncovered(window[0], tick[0]): + continue + if is_suppressed_at(lines, window[1], COVER_RULE): + continue + findings.append( + f"{rel}:{window[1]} start_period {window[0]} <= interval {tick[0]}" + ) + return findings + + +class TestHealthcheckTimingOverrides(unittest.TestCase): + def test_no_timing_restates_its_default(self) -> None: + redundant, _ = timing_findings() + if not redundant: + return + self.fail( + "These healthcheck timings repeat the value their flavor already " + "gives them. They change nothing and hide the day the default " + "moves, so delete the line.\n\n" + "\n".join(f"- {f}" for f in redundant) + ) + + def test_every_deviating_timing_says_why(self) -> None: + _, undocumented = timing_findings() + if not undocumented: + return + self.fail( + "These healthcheck timings differ from their flavor's default " + "without saying why. A number alone outlives the reason for it.\n\n" + "Fix: put the reason on the timing line or the one above it:\n\n" + f" # nocheck: {RULE} \n\n" + + "\n".join(f"- {f}" for f in undocumented) + ) + + def test_definitions_outside_the_lookup_spell_the_defaults_out(self) -> None: + findings = literal_findings() + if not findings: + return + self.fail( + "These healthcheck definitions bypass the lookup, so they inherit " + "nothing from the SPOT. Docker has no daemon-wide default to fall " + "back on, and an omitted timing lands on docker's value rather than " + "the platform's.\n\n" + "Fix: spell the timing out at the platform value, or say why this " + "definition needs another one:\n\n" + f" # nocheck: {RULE} \n\n" + "\n".join(f"- {f}" for f in findings) + ) + + def test_the_start_window_outlasts_one_interval(self) -> None: + findings = windows_shorter_than_a_tick() + if not findings: + return + self.fail( + "These healthchecks close their start window before one steady " + "state tick has passed. The fast start cadence then stops covering " + "the boot, and a service that becomes ready just after the window " + "waits a whole interval anyway, which is the quantisation the " + "cadence exists to remove.\n\n" + "Fix: raise start_period above interval. It costs nothing while the " + "container works, only the time until a broken one is called " + "unhealthy. A probe that deliberately runs without a window says " + "so:\n\n" + f" # nocheck: {COVER_RULE} \n\n" + + "\n".join(f"- {f}" for f in findings) + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/lint/ansible/roles/meta/test_info.py b/tests/lint/ansible/roles/meta/test_info.py index d4b372fa40..e574b68e1d 100644 --- a/tests/lint/ansible/roles/meta/test_info.py +++ b/tests/lint/ansible/roles/meta/test_info.py @@ -1,7 +1,9 @@ """Lint guard: ``roles//meta/info.yml`` schema. * the file is OPTIONAL (a role with no descriptive metadata does not - grow the file); + grow the file), and an otherwise empty one is legal only when it + carries ``# nocheck: info-media``, which is the exemption for a role + with no upstream homepage or demo video to name; * file-root convention: the file's content IS the value of ``applications..info`` โ€” there is NO wrapping ``info:`` key; * allowed top-level keys: ``logo``, ``homepage``, ``video``, ``display``; @@ -23,7 +25,8 @@ from typing import TYPE_CHECKING import yaml as _yaml -from utils.cache.files import PROJECT_ROOT +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import PROJECT_ROOT, read_text from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ROLE_FILE_META_INFO, ROLE_FILE_META_MAIN @@ -34,6 +37,8 @@ ROLES_DIR = PROJECT_ROOT / "roles" _ALLOWED_INFO_KEYS: frozenset[str] = frozenset({"logo", "homepage", "video", "display"}) +_INFO_MEDIA_RULE = "info-media" + _FORBIDDEN_GALAXY_INFO_KEYS: frozenset[str] = frozenset( {"logo", "homepage", "video", "display"} ) @@ -65,6 +70,8 @@ def _validate_meta_info(path: Path) -> list[str]: except _yaml.YAMLError as exc: return [f"YAML parse error: {exc}"] if parsed in (None, {}): + if is_suppressed_in_head(read_text(str(path)).splitlines(), _INFO_MEDIA_RULE): + return [] return ["file is empty (delete the file or add at least one allowed field)"] if not isinstance(parsed, dict): return [f"top-level must be a mapping; got {type(parsed).__name__}"] diff --git a/tests/lint/ansible/roles/meta/test_info_homepage_video.py b/tests/lint/ansible/roles/meta/test_info_homepage_video.py index 42df6fa334..0ddd33278e 100644 --- a/tests/lint/ansible/roles/meta/test_info_homepage_video.py +++ b/tests/lint/ansible/roles/meta/test_info_homepage_video.py @@ -8,10 +8,11 @@ product page or demo video: opt them out with the file-level marker # nocheck: info-media -within the first 30 lines of ``meta/main.yml``. The marker lives in -``meta/main.yml`` (always present) rather than ``meta/info.yml`` because -a comment-only ``info.yml`` parses to an empty document, which the -``meta/info.yml`` schema lint rejects. +within the first 30 lines of ``meta/info.yml``, the file the missing field +would have lived in. A role with nothing else to declare keeps an +``info.yml`` that carries only the marker; the schema lint accepts an +otherwise empty document exactly when it is marked, so the exemption and +the absence it explains stay in one place. """ from __future__ import annotations @@ -21,7 +22,7 @@ import unittest from utils.annotations.suppress import is_suppressed_in_head from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any -from utils.roles.mapping import ROLE_FILE_META_INFO, ROLE_FILE_META_MAIN +from utils.roles.mapping import ROLE_FILE_META_INFO from utils.roles.validation.invokable import _get_invokable_paths, _is_role_invokable from . import PROJECT_ROOT @@ -39,12 +40,11 @@ class TestInfoHomepageVideo(unittest.TestCase): continue if not _is_role_invokable(role_dir.name, invokable): continue - main_path = role_dir / ROLE_FILE_META_MAIN - if main_path.is_file() and is_suppressed_in_head( - read_text(str(main_path)).splitlines(), _RULE + info_path = role_dir / ROLE_FILE_META_INFO + if info_path.is_file() and is_suppressed_in_head( + read_text(str(info_path)).splitlines(), _RULE ): continue - info_path = role_dir / ROLE_FILE_META_INFO info: dict = {} if info_path.is_file(): data = load_yaml_any(str(info_path)) or {} @@ -63,7 +63,8 @@ class TestInfoHomepageVideo(unittest.TestCase): f"{len(findings)} invokable role(s) miss 'homepage' and/or 'video' " f"in {ROLE_FILE_META_INFO}. Add the URLs, or opt a fully " f"self-written role out with '# nocheck: {_RULE} ' in the " - f"first 30 lines of {ROLE_FILE_META_MAIN}:\n" + "\n".join(findings), + f"first 30 lines of that same {ROLE_FILE_META_INFO}:\n" + + "\n".join(findings), ) diff --git a/tests/lint/ansible/roles/meta/test_no_jinja_in_mapping_keys.py b/tests/lint/ansible/roles/meta/test_no_jinja_in_mapping_keys.py new file mode 100644 index 0000000000..6a470104fa --- /dev/null +++ b/tests/lint/ansible/roles/meta/test_no_jinja_in_mapping_keys.py @@ -0,0 +1,82 @@ +"""Lint: a role's meta payload never carries Jinja in a mapping key. + +Ansible renders the values of a structure loaded through ``include_vars`` and +leaves its keys alone, so an expression written as a key reaches the consumer +as its own source text. ``web-app-nextcloud``'s sociallogin provider stored + + "groupMapping": {"/{{ lookup('rbac_group_path', ...) }}": "admin"} + +in Nextcloud, which matches no group Keycloak ever sends, and the administrator +logging in through OIDC stayed out of the ``admin`` group. + +Write the whole mapping as one expression instead, which ``jinja2_native`` +returns as a real mapping with the key computed:: + + groupMapping: >- + {{ { '/' ~ lookup('rbac_group_path', ...): 'admin' } }} + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: jinja-mapping-key`` on, or directly above, the offending line. +""" + +from __future__ import annotations + +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content + +from . import PROJECT_ROOT + +_RULE = "jinja-mapping-key" + + +def _key_before_colon(line: str) -> str: + stripped = line.strip().removeprefix("- ") + if not stripped or stripped.startswith(("#", "{{")): + return "" + if stripped.startswith(('"', "'")): + quote = stripped[0] + end = stripped.find(quote, 1) + if end == -1 or not stripped[end + 1 :].lstrip().startswith(":"): + return "" + return stripped[1:end] + head, sep, _tail = stripped.partition(":") + return head if sep else "" + + +def jinja_mapping_keys() -> list[str]: + findings = [] + for path, content in iter_project_files_with_content(extensions=(".yml",)): + parts = Path(path).relative_to(PROJECT_ROOT).parts + if len(parts) < 3 or parts[0] != "roles" or parts[2] != "meta": + continue + lines = content.splitlines() + for number, line in enumerate(lines, start=1): + if "{{" not in _key_before_colon(line): + continue + if is_suppressed_at(lines, number, _RULE): + continue + rel = Path(path).relative_to(PROJECT_ROOT) + findings.append(f"{rel}:{number}: {line.strip()[:80]}") + return findings + + +class TestNoJinjaInMappingKeys(unittest.TestCase): + def test_no_meta_payload_expects_a_key_to_be_rendered(self) -> None: + findings = jinja_mapping_keys() + self.assertEqual( + [], + findings, + f"Jinja expression(s) used as a mapping key ({len(findings)}). " + "Ansible renders the values of an include_vars payload and leaves " + "the keys as written, so the consumer receives the source text. " + "Write the whole mapping as one expression instead:\n" + + "\n".join(f" - {f}" for f in findings), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/meta/test_role_subnet_pool.py b/tests/lint/ansible/roles/meta/test_role_subnet_pool.py new file mode 100644 index 0000000000..b18f584947 --- /dev/null +++ b/tests/lint/ansible/roles/meta/test_role_subnet_pool.py @@ -0,0 +1,97 @@ +"""Lint: a role's local subnet comes out of the declared pool. + +``NETWORK_ROLE_SUBNET_POOL`` in ``group_vars/all/08_networks.yml`` names the +block role networks are carved from. Until it existed the block was an emergent +property: the allocator in ``cli contributing network address suggest`` derives +its umbrella from the subnets already in use, so the tree defined the rule +instead of the rule defining the tree. Anything that consumes "our own address +space" then has to guess, and a guess that is one role out of date silently +excludes that role. That is not hypothetical: a firewall range derived from the +pool by eye would have cut BigBlueButton off, because its subnet is the one +that sits outside. + +A role that genuinely cannot choose its block is named in +``NETWORK_ROLE_SUBNET_EXCEPTION_ROLES``. The list carries role ids rather than +CIDRs on purpose: the block is already declared in that role's +``meta/networks.yml``, and repeating it here would be the same duplication one +layer up. Consumers resolve the ids through ``lookup('role_subnets', ...)``. +""" + +from __future__ import annotations + +import ipaddress +import unittest + +import jinja2 + +from utils.cache.yaml import load_yaml_any +from utils.meta.scan import iter_subnets + +from . import PROJECT_ROOT + +NETWORKS_FILE = PROJECT_ROOT / "group_vars" / "all" / "08_networks.yml" + + +def _declared_space() -> tuple[list[ipaddress.IPv4Network], list[str]]: + """The pool plus the blocks of the excepted roles, with their raw strings.""" + data = load_yaml_any(str(NETWORKS_FILE), default_if_missing={}) or {} + pool = data.get("NETWORK_ROLE_SUBNET_POOL") + if isinstance(pool, str) and "{{" in pool: + pool = jinja2.Template(pool).render(**data) + roles = data.get("NETWORK_ROLE_SUBNET_EXCEPTION_ROLES") or [] + if not isinstance(pool, str) or not isinstance(roles, list): + raise TypeError( + f"{NETWORKS_FILE} must declare NETWORK_ROLE_SUBNET_POOL as a string " + "and NETWORK_ROLE_SUBNET_EXCEPTION_ROLES as a list of role ids" + ) + declared = dict(iter_subnets()) + raw = [pool] + for role in roles: + subnet = declared.get(str(role)) + if subnet is None: + raise AssertionError( + f"{NETWORKS_FILE}: NETWORK_ROLE_SUBNET_EXCEPTION_ROLES names " + f"'{role}', which declares no networks.local.subnet" + ) + raw.append(str(subnet)) + return [ipaddress.ip_network(entry, strict=True) for entry in raw], raw + + +class TestRoleSubnetPool(unittest.TestCase): + def test_every_role_subnet_sits_in_the_declared_space(self) -> None: + allowed, raw = _declared_space() + findings = [ + f"- {role}: {subnet}" + for role, subnet in sorted(iter_subnets(), key=lambda item: item[0]) + if not any(subnet.subnet_of(block) for block in allowed) + ] + if findings: + self.fail( + "These roles declare networks.local.subnet outside the address " + "space this deployment declares for itself:\n" + + "\n".join(findings) + + "\n\nDeclared space: " + + ", ".join(raw) + + "\n\nFix: pick a subnet inside the pool via " + "`infinito contributing network address suggest`, or, when the " + "block is pinned by something outside this repository, name the " + "role in NETWORK_ROLE_SUBNET_EXCEPTION_ROLES in " + "group_vars/all/08_networks.yml." + ) + + def test_the_exceptions_are_not_already_covered(self) -> None: + """An exception inside the pool is dead weight that outlives its reason.""" + allowed, raw = _declared_space() + pool = allowed[0] + redundant = [entry for entry in allowed[1:] if entry.subnet_of(pool)] + if redundant: + self.fail( + "NETWORK_ROLE_SUBNET_EXCEPTION_ROLES names role(s) whose subnet " + f"already sits inside {raw[0]}: " + f"{', '.join(str(entry) for entry in redundant)}. " + "Remove them; the pool already admits those addresses." + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py b/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py new file mode 100644 index 0000000000..4ad33f9029 --- /dev/null +++ b/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py @@ -0,0 +1,162 @@ +"""Lint guard: the SSO gate hands an upstream a bearer token only on request. + +``roles/web-app-keycloak/templates/sso_proxy/following_directives.conf.j2`` +sets ``X-Forwarded-Access-Token`` only where the consumer declares +``services.sso.oauth2.pass_access_token: true``. Two failure modes follow, and +this lint pins both: + +* A role reads the header without declaring the opt-in. The gate then blanks + the header and the role's identity handling silently degrades, in a code path + no unit test reaches. +* A role declares the opt-in without reading the header. The token is a + full-scope bearer for the signed-in user, so every extra recipient widens + what a compromised container can do, and its length (which grows with the + realm's registered origins) re-enters the upstream's header-size limit. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: sso-access-token-optin`` in the head of ``meta/services.yml``, + naming why the role needs the token without a readable reference to it. +""" + +from __future__ import annotations + +import re +import unittest +from typing import TYPE_CHECKING + +import yaml + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import iter_project_files_with_content, read_text +from utils.cache.yaml import load_yaml_str +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from pathlib import Path + +_RULE = "sso-access-token-optin" + +ROLES_DIR = PROJECT_ROOT / "roles" +GATE = PROJECT_ROOT / ( + "roles/web-app-keycloak/templates/sso_proxy/following_directives.conf.j2" +) +_HEADER_RE = re.compile(r"x[-_]forwarded[-_]access[-_]token", re.IGNORECASE) +_EMITS_RE = re.compile(r"proxy_set_header|auth_request_set") +_SKIP_DIRS = {".git", "node_modules", "__pycache__"} +_TEXT_SUFFIXES = { + ".js", + ".mjs", + ".cjs", + ".ts", + ".py", + ".rb", + ".php", + ".sh", + ".lua", + ".yml", + ".yaml", + ".j2", + ".conf", + ".json", + ".env", +} + + +def _load_services(role_dir: Path): + path = role_dir / ROLE_FILE_META_SERVICES + if not path.is_file(): + return None, "" + try: + text = read_text(str(path)) + except UnicodeDecodeError: + return None, "" + if not text.strip(): + return None, "" + try: + return load_yaml_str(text), text + except yaml.YAMLError: + return None, text + + +def _declares_opt_in(services) -> bool: + if not isinstance(services, dict): + return False + sso = services.get("sso") + oauth2 = sso.get("oauth2") if isinstance(sso, dict) else None + value = oauth2.get("pass_access_token") if isinstance(oauth2, dict) else None + if isinstance(value, str): + return value.strip().lower() in ("true", "1", "yes", "on") + return bool(value) + + +def _reading_roles() -> set[str]: + """Return the roles that consume the header rather than emitting it. + + An nginx line that sets or strips the header names it too; only a line + that does neither is a consumer reading the request. + """ + prefix = str(ROLES_DIR) + "/" + meta_name = ROLE_FILE_META_SERVICES.rsplit("/", 1)[-1] + found: set[str] = set() + for path, content in iter_project_files_with_content( + extensions=tuple(_TEXT_SUFFIXES), exclude_tests=True + ): + if not path.startswith(prefix) or path.endswith(meta_name): + continue + for line in content.splitlines(): + if _HEADER_RE.search(line) and not _EMITS_RE.search(line): + found.add(path[len(prefix) :].split("/", 1)[0]) + break + return found + + +def _roles() -> list[Path]: + return sorted(p for p in ROLES_DIR.iterdir() if p.is_dir()) + + +class TestSsoAccessTokenOptIn(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.declared: set[str] = set() + cls.suppressed: set[str] = set() + for role in _roles(): + services, text = _load_services(role) + if _declares_opt_in(services): + cls.declared.add(role.name) + if text and is_suppressed_in_head(text.splitlines(), _RULE): + cls.suppressed.add(role.name) + cls.readers = _reading_roles() - {"web-app-keycloak"} + + def test_every_reader_of_the_token_declares_the_opt_in(self) -> None: + missing = sorted(self.readers - self.declared - self.suppressed) + self.assertEqual( + [], + missing, + "role(s) reading X-Forwarded-Access-Token without " + "`services.sso.oauth2.pass_access_token: true`, so the gate blanks " + f"the header: {missing}", + ) + + def test_no_role_asks_for_a_token_it_never_reads(self) -> None: + unused = sorted(self.declared - self.readers - self.suppressed) + self.assertEqual( + [], + unused, + "role(s) declaring `pass_access_token: true` with no reference to " + f"the header: {unused}", + ) + + def test_the_scan_finds_the_known_reader(self) -> None: + self.assertIn("web-app-n8n", self.readers) + + def test_the_gate_makes_the_header_conditional(self) -> None: + content = read_text(str(GATE)) + self.assertIn("oauth2_pass_access_token", content) + self.assertIn('proxy_set_header X-Forwarded-Access-Token "";', content) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/meta/test_variants_distinct.py b/tests/lint/ansible/roles/meta/test_variants_distinct.py new file mode 100644 index 0000000000..3dc998b5aa --- /dev/null +++ b/tests/lint/ansible/roles/meta/test_variants_distinct.py @@ -0,0 +1,83 @@ +"""No two entries of a ``meta/variants.yml`` may declare the same override. + +A variant exists to deploy a shape the other entries do not. Two entries with +the same content produce the same rendered payload, so the matrix plans them as +separate rows, assigns each its own axes and spends a deploy job on each. The +measured cost of one such job in this repository's CI is around one hundred +minutes, and the second one proves nothing the first did not. + +The duplicate is also invisible in the plan table, which lists rows by +``role#variant``: the two read as different rows and only their identical +``embeds`` and ``weight`` betray them. + +Comparison is on the parsed payload, not the file text, so two entries that +differ in key order, indentation or comments still count as the same. ``null`` +normalises to ``{}`` the way the loader treats it, because a bare ``- `` list +item and an explicit ``- {}`` declare the same no-override entry. + +Per-file opt-out +================ +``# nocheck: variants-duplicate`` anywhere in the file, with a reason naming +what the repetition buys. Reserve it for a role whose variants are told apart +by something outside the entry, and say what that is; the default path is to +delete the entry, because the axes a duplicate would have covered are assigned +per row rather than declared per variant. +""" + +from __future__ import annotations + +import json +import unittest +from collections import defaultdict + +from utils.annotations.suppress import is_suppressed_anywhere +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_VARIANTS + +from . import PROJECT_ROOT + +RULE = "variants-duplicate" + + +def _fingerprint(entry: object) -> str: + """The entry's content, independent of key order and of ``null`` vs ``{}``.""" + return json.dumps(entry if entry is not None else {}, sort_keys=True, default=str) + + +class TestVariantsDistinct(unittest.TestCase): + def test_no_two_variants_declare_the_same_override(self) -> None: + offenders = [] + for variants_file in sorted( + (PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_VARIANTS}") + ): + entries = load_yaml_any(str(variants_file), default_if_missing=[]) + if not isinstance(entries, list): + continue + if is_suppressed_anywhere(read_text(str(variants_file)).splitlines(), RULE): + continue + + seen: dict[str, list[int]] = defaultdict(list) + for index, entry in enumerate(entries): + seen[_fingerprint(entry)].append(index) + + role = variants_file.parent.parent.name + for indices in seen.values(): + if len(indices) > 1: + joined = ", ".join(f"#{index}" for index in indices) + offenders.append( + f"{role}: variants {joined} declare the same override" + ) + + self.assertEqual( + [], + offenders, + "A duplicated variant entry costs a deploy job and proves nothing the " + "entry it repeats did not. Delete the repetition, give it the override " + f"that makes it a distinct shape, or mark the file `# nocheck: {RULE}` " + "with a reason:\n " + "\n ".join(offenders), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/test_addon_enabled_renders_to_bool.py b/tests/lint/ansible/roles/test_addon_enabled_renders_to_bool.py new file mode 100644 index 0000000000..b69de637d4 --- /dev/null +++ b/tests/lint/ansible/roles/test_addon_enabled_renders_to_bool.py @@ -0,0 +1,137 @@ +"""Every addon ``enabled`` must render to a boolean, even on a bare scope. + +Rationale +========= +``meta/addons/*.yml`` is rendered inside the applications SPOT and consumed as +``plugin_value.enabled | bool``. An expression that cannot resolve does not +fail: ``utils.templating.ansible._templar_render_best_effort`` returns the +string untouched, and for a value carrying a non-env ``lookup(`` it refuses the +fallback as well. The template text reaches the filter, which coerces it to +False and emits:: + + [DEPRECATION WARNING]: The `bool` filter coerced invalid value + "{{ ... }}" (str) to False. + +The deploy gate fails on that warning, and the addon is off in every run that +did not warn loudly enough to be noticed. Run 34893363518, job 104153194109 +lost web-app-nextcloud this way. + +The check renders the whole applications map against a scope carrying only what +every run has -- group_vars plus the deployed role names -- and blanks ``API`` +to the most hostile override an inventory may legally write. Anything that +survives as template text resolves only against something the render scope does +not carry. +""" + +from __future__ import annotations + +import unittest +from typing import Any + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from utils.cache.applications import ( + _MERGED_APPLICATIONS_CACHE, + get_merged_applications, +) +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +_ADDONS_GLOB = "*/meta/addons/*.yml" +_BOOL_LITERALS = frozenset( + {"true", "false", "yes", "no", "on", "off", "1", "0", "y", "n"} +) + + +def _role_names() -> list[str]: + return sorted( + path.name for path in (PROJECT_ROOT / "roles").iterdir() if path.is_dir() + ) + + +def _hostile_scope() -> dict[str, Any]: + variables: dict[str, Any] = {} + for path in sorted((PROJECT_ROOT / "group_vars" / "all").glob("*.yml")): + data = load_yaml_any(path) or {} + if isinstance(data, dict): + variables.update(data) + variables["group_names"] = _role_names() + variables["API"] = {} + return variables + + +def _rendered_addons() -> dict[str, dict[str, Any]]: + variables = _hostile_scope() + templar = Templar(loader=DataLoader(), variables=dict(variables)) + templar.available_variables = dict(variables) + + _MERGED_APPLICATIONS_CACHE.clear() + try: + applications = get_merged_applications( + variables=dict(variables), templar=templar + ) + finally: + _MERGED_APPLICATIONS_CACHE.clear() + + return { + app_id: config["addons"] + for app_id, config in applications.items() + if isinstance(config, dict) and isinstance(config.get("addons"), dict) + } + + +def _verdict(value: Any) -> str: + if isinstance(value, bool): + return "" + if not isinstance(value, str): + return f"is {type(value).__name__}, not a boolean" + if "{{" in value or "{%" in value: + return f"stayed template text: {value}" + if value.strip().lower() not in _BOOL_LITERALS: + return f"is not a boolean literal: {value!r}" + return "" + + +class TestAddonEnabledRendersToBool(unittest.TestCase): + def test_every_addon_enabled_resolves(self) -> None: + findings = [ + f" - roles/{app_id}/meta/addons/{addon_id}.yml: 'enabled' {verdict}" + for app_id, addons in _rendered_addons().items() + for addon_id, spec in sorted(addons.items()) + if isinstance(spec, dict) + for verdict in [_verdict(spec.get("enabled"))] + if verdict + ] + + if findings: + self.fail( + f"{len(findings)} addon gate(s) do not render to a boolean on a " + "scope without inventory extras, so '| bool' coerces the leftover " + "text to False and the deploy fails on the deprecation warning:\n" + + "\n".join(findings) + + "\n\nResolve the value through a lookup that carries its own " + "source instead of a variable the render scope may not hold: " + "lookup('api_enabled', '') gates on credentials, " + "lookup('config', ...) on another application's settings." + ) + + def test_the_scan_reaches_templated_gates(self) -> None: + """A scope that resolved nothing, or addons without gates, passes for free.""" + templated = [ + path + for path in sorted((PROJECT_ROOT / "roles").glob(_ADDONS_GLOB)) + if "{{" in str((load_yaml_any(path) or {}).get("enabled", "")) + ] + self.assertTrue( + templated, + "no addon declares a templated 'enabled', so the rule above is vacuous", + ) + + rendered = _rendered_addons() + self.assertTrue(rendered, "no application carries addons; nothing was checked") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/test_docker_calls_follow_the_stack.py b/tests/lint/ansible/roles/test_docker_calls_follow_the_stack.py new file mode 100644 index 0000000000..3b11a84e5a --- /dev/null +++ b/tests/lint/ansible/roles/test_docker_calls_follow_the_stack.py @@ -0,0 +1,109 @@ +"""Lint: a task that talks to docker must come after the stack that installs it. + +The image ships only ``docker-ce-cli``; the daemon is installed and started by +``sys-svc-container``, which a role pulls in through one of the ``sys-stk-*`` +stacks. A docker call placed before that include therefore runs against a +socket that does not exist yet. + +It fails late and unrecognisably. The play spends minutes in the constructor +and the base roles, the container reports healthy the whole time because its +probe cannot ask about a daemon that is not due yet, and the first role to +touch docker reports ``FileNotFoundError(2)`` from whatever it happened to be +doing - a network probe, in the case that produced this rule. + +Swarm hides it: there the nodes are provisioned with docker before the play +reaches the role, so only the compose path fails. + +The comparison is per file. A role that puts the docker call in one task file +and the stack include in another escapes, because resolving that needs the +include graph rather than two line numbers. Every current caller keeps both in +the same file, which is the shape this rule guards. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: docker-before-stack`` on, or directly above, the include. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import PROJECT_ROOT, read_text + +_RULE = "docker-before-stack" + +DOCKER_INCLUDES = ("sys-svc-compose/tasks/utils/network/create.yml",) + +_STACK_RE = re.compile(r"name:\s*(sys-stk-[a-z-]+|sys-svc-container)") + + +def role_task_files() -> list: + """Return every task file of every role, nested directories included.""" + return sorted((PROJECT_ROOT / "roles").glob("*/tasks/**/*.yml")) + + +def first_line(content: str, pattern) -> int: + """Return the 1-based line of the first match, or 0. + + Args: + content: the file's text. + pattern: a compiled regex or a plain substring. + """ + for index, line in enumerate(content.splitlines(), start=1): + found = pattern.search(line) if hasattr(pattern, "search") else pattern in line + if found: + return index + return 0 + + +def calls_before_the_stack() -> list[str]: + """Return one finding per docker call that precedes its stack include.""" + findings = [] + for path in role_task_files(): + content = read_text(str(path)) + stack = first_line(content, _STACK_RE) + if not stack: + continue + for include in DOCKER_INCLUDES: + call = first_line(content, include) + if not call or call > stack: + continue + if is_suppressed_at(content.splitlines(), call, _RULE): + continue + rel = path.relative_to(PROJECT_ROOT) + findings.append( + f"{rel}:{call}: calls docker before the stack include on line " + f"{stack} installs it" + ) + return findings + + +class TestDockerCallsFollowTheStack(unittest.TestCase): + def test_no_role_calls_docker_before_its_stack(self) -> None: + findings = calls_before_the_stack() + self.assertEqual( + [], + findings, + f"docker call(s) that run before docker exists ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + def test_the_scan_reaches_role_task_files(self) -> None: + self.assertTrue(role_task_files(), "no role task file was scanned") + + def test_a_file_pairing_both_is_actually_reached(self) -> None: + """Without one, the rule would pass over files it never compares.""" + paired = [ + path + for path in role_task_files() + for include in DOCKER_INCLUDES + if first_line(read_text(str(path)), include) + and first_line(read_text(str(path)), _STACK_RE) + ] + self.assertTrue(paired, "no task file both calls docker and loads a stack") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/test_entity_name_is_defined_where_used.py b/tests/lint/ansible/roles/test_entity_name_is_defined_where_used.py new file mode 100644 index 0000000000..7fea8e5c8f --- /dev/null +++ b/tests/lint/ansible/roles/test_entity_name_is_defined_where_used.py @@ -0,0 +1,146 @@ +"""Lint: a role that uses ``entity_name`` has to define it itself. + +Role vars do not cross role boundaries, so a role reading ``entity_name`` +without a ``vars/main.yml`` entry reads nothing. Ansible does not stop there: +in compose the undefined value renders into task names as +``<< error 1 - 'entity_name' is undefined >>`` and the play carries on, so the +gap stays invisible until the swarm path templates it into a real argument and +``any_errors_fatal`` takes the whole play down. + +Five roles shipped that way while seventy-seven define it on the line below +``application_id``, which is why nothing looked odd in review. + +The match needs its lookbehind: ``get_entity_name`` is a filter whose name ends +in this variable's, and without it every role calling that filter reads as a +violation. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: entity-name-undefined`` on, or directly above, the use. +""" + +from __future__ import annotations + +import os +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import PROJECT_ROOT, iter_project_files, read_text +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +_RULE = "entity-name-undefined" +_NAME = "entity_name" +_ROLES = str(PROJECT_ROOT / "roles") + os.sep + +_USE_RE = re.compile(rf"(? dict: + """Return every role's yml and j2 files, keyed by role name.""" + grouped: dict = {} + for path in iter_project_files(extensions=(".yml", ".j2"), exclude_tests=True): + if not path.startswith(_ROLES): + continue + relative = path[len(_ROLES) :] + grouped.setdefault(Path(relative).parts[0], []).append(path) + return grouped + + +def defines_it(role: str, paths: list) -> bool: + """Return whether the role declares the variable in its own vars. + + Args: + role: the role's directory name. + paths: the role's files. + """ + wanted = _ROLES + role + os.sep + ROLE_FILE_VARS_MAIN + return any( + line.strip().startswith(f"{_NAME}:") + for path in paths + if path == wanted + for line in read_text(path).splitlines() + ) + + +def borrowed_files(grouped: dict) -> set: + """Return every role file another role pulls in by absolute path. + + Args: + grouped: the roles' files, keyed by role name. + + Such a file runs in the including role's scope, so it reads that role's + ``entity_name`` and must not be judged against its own role's vars. + """ + borrowed = set() + for owner, paths in grouped.items(): + for path in paths: + for line in read_text(path).splitlines(): + if "path_absolute" not in line or "roles/" not in line: + continue + target = line.split("roles/", 1)[1].split("'")[0].split('"')[0] + if target.split("/")[0] != owner: + borrowed.add(target) + return borrowed + + +def uses_it(role: str, paths: list, borrowed: set) -> list: + """Return one ``path:line`` per unsuppressed use outside the role's vars. + + Args: + role: the role's directory name. + paths: the role's files. + borrowed: role-relative paths other roles include by absolute path. + """ + uses = [] + for path in sorted(paths): + relative = path[len(_ROLES) :] + if relative in borrowed or relative == role + os.sep + ROLE_FILE_VARS_MAIN: + continue + lines = read_text(path).splitlines() + uses.extend( + f"{relative}:{index}" + for index, line in enumerate(lines, start=1) + if _USE_RE.search(line) and not is_suppressed_at(lines, index, _RULE) + ) + return uses + + +def roles_using_it_without_defining_it() -> list[str]: + """Return one finding per role that reads the variable it never sets.""" + grouped = files_by_role() + borrowed = borrowed_files(grouped) + findings = [] + for role, paths in sorted(grouped.items()): + if defines_it(role, paths): + continue + findings.extend( + f"roles/{use}: uses {_NAME}, which {role} never defines" + for use in uses_it(role, paths, borrowed) + ) + return findings + + +class TestEntityNameIsDefinedWhereUsed(unittest.TestCase): + def test_no_role_reads_an_entity_name_it_never_sets(self) -> None: + findings = roles_using_it_without_defining_it() + self.assertEqual( + [], + findings, + f"role(s) reading an undefined {_NAME} ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + def test_the_scan_reaches_the_roles(self) -> None: + self.assertTrue(files_by_role(), "no role file was scanned") + + def test_the_convention_it_guards_is_actually_in_use(self) -> None: + """Without one, an emptied convention would let the rule pass silently.""" + grouped = files_by_role() + definers = [role for role, paths in grouped.items() if defines_it(role, paths)] + self.assertGreater(len(definers), 50, "the convention this rule guards is gone") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/test_foreign_core_entry_guarded.py b/tests/lint/ansible/roles/test_foreign_core_entry_guarded.py new file mode 100644 index 0000000000..3c3a4d8715 --- /dev/null +++ b/tests/lint/ansible/roles/test_foreign_core_entry_guarded.py @@ -0,0 +1,153 @@ +"""A role that enters another role's numbered core must carry its run-once guard. + +Rationale +========= +``roles//tasks/main.yml`` gates ``0N_core.yml`` behind +``run_once_ is not defined``. Reaching that body from a *different* role +with ``include_role: {name: , tasks_from: 0N_core.yml}`` bypasses the +gate, because the guard lives in ``main.yml`` and ``tasks_from`` never reads it. +The body then re-runs once per calling task rather than once per play. + +That is not merely wasteful. ``roles/sys-svc-compose/tasks/00_core.yml`` removes +the shared compose pull-lock directory, which ``files/python/pull.py`` uses to +skip a pull it already did, so a second pass makes every stack deployed so far +pull again; and under ``MODE_RESET`` it reaches ``01_reset.yml``, which brings +every project in ``DIR_COMPOSITIONS`` down and deletes the directory that holds +every application's instance, env and volume paths. +``roles/sys-svc-container/tasks/00_core.yml`` carries an unconditional +``meta: flush_handlers``, so a second pass drains whatever topic is pending. + +The guard belongs at the call site rather than inside the core file, because +``roles/sys-svc-compose/tasks/00_core.yml`` sets its own flag as the first task +to break the recursion back through ``utils/network/routine.yml``. Seven call +sites already guard ``sys-svc-container`` this way; this rule holds the rest to +the same convention. + +``tests/lint/ansible/roles/test_service_core_first_task_run_once.py`` pins the +guard inside the owning role and cannot see a foreign entry point; +``tests/lint/ansible/tasks/test_tasks_from_resolves.py`` only checks that the +referenced file exists. + +Per-line opt-out +================ +Add ``# nocheck: foreign-core-entry-guarded`` on the ``tasks_from`` line or the +one above it, together with a comment naming why the body has to run again. +""" + +from __future__ import annotations + +import re +import unittest +from collections.abc import Mapping +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content +from utils.cache.yaml import load_yaml_str + +from . import PROJECT_ROOT + +_RULE = "foreign-core-entry-guarded" + +_CORE_FILE = re.compile(r"^\d+_core(\.yml)?$") +_CORE_LINE = re.compile( + r"^\s*tasks_from\s*:\s*['\"]?\d+_core(\.yml)?['\"]?\s*(?:#.*)?$" +) + + +def _owning_role(rel_path: str) -> str: + parts = Path(rel_path).parts + return parts[1] if len(parts) > 2 and parts[0] == "roles" else "" + + +def _guard_for(role: str) -> str: + return f"run_once_{role.replace('-', '_')} is not defined" + + +def _role_include(task: Mapping) -> Mapping: + for key in ("include_role", "import_role"): + include = task.get(key) or task.get(f"ansible.builtin.{key}") + if isinstance(include, Mapping): + return include + return {} + + +def _walk(tasks: object): + if not isinstance(tasks, list): + return + for task in tasks: + if not isinstance(task, Mapping): + continue + yield task + for section in ("block", "rescue", "always"): + yield from _walk(task.get(section)) + + +def _core_entries(content: str) -> list[tuple[str, bool, str]]: + """Return (target role, guarded, task name) for every foreign core entry.""" + try: + tasks = load_yaml_str(content) + except Exception: + return [] + found: list[tuple[str, bool, str]] = [] + for task in _walk(tasks): + include = _role_include(task) + target = str(include.get("name") or "").strip() + tasks_from = str(include.get("tasks_from") or "").strip() + if not target or not _CORE_FILE.match(tasks_from): + continue + when = task.get("when") + clauses = when if isinstance(when, list) else [when] + guarded = any(_guard_for(target) in str(c) for c in clauses if c is not None) + found.append((target, guarded, str(task.get("name") or tasks_from))) + return found + + +class TestForeignCoreEntryGuarded(unittest.TestCase): + def test_a_foreign_core_entry_carries_the_owning_role_guard(self) -> None: + findings: list[tuple[str, int, str, str]] = [] + for path_str, content in iter_project_files_with_content( + extensions=(".yml", ".yaml"), + exclude_tests=True, + ): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + if "/tasks/" not in rel and not rel.startswith("tasks/"): + continue + entries = _core_entries(content) + if not entries: + continue + lines = content.splitlines() + anchors = [i for i, line in enumerate(lines) if _CORE_LINE.match(line)] + if len(anchors) != len(entries): + anchors = [0] * len(entries) + owner = _owning_role(rel) + for (target, guarded, name), idx in zip(entries, anchors, strict=True): + if guarded or target == owner: + continue + if idx and is_suppressed_at( + lines, idx + 1, _RULE, mode="same-or-above" + ): + continue + findings.append((rel, idx + 1, name, _guard_for(target))) + + if findings: + formatted = "\n".join( + f"- {p}:{n}: {t!r} needs `when: {g}`" + for p, n, t, g in sorted(set(findings), key=lambda i: (i[0], i[1])) + ) + self.fail( + "A role reaches another role's numbered core body through " + "`tasks_from` without the guard that `main.yml` would have " + "applied. The body then runs once per calling task instead of " + "once per play, which re-runs installs, wipes the shared " + "compose pull-lock directory, and under MODE_RESET tears down " + "DIR_COMPOSITIONS after other applications are already " + "deployed into it.\n\n" + "Default: add the `when:` shown. Use the nocheck only where " + "the body genuinely has to repeat, and say why.\n\n" + f"Offenders:\n{formatted}" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/test_location_identity_strips.py b/tests/lint/ansible/roles/test_location_identity_strips.py new file mode 100644 index 0000000000..69ba8298c2 --- /dev/null +++ b/tests/lint/ansible/roles/test_location_identity_strips.py @@ -0,0 +1,104 @@ +"""Lint: a location that proxies must not forward a client's identity headers. + +The platform authenticates several applications by trusted header: oauth2-proxy +verifies the session and nginx passes ``X-Forwarded-User`` and its siblings to +the upstream, which believes them. That only holds while a *client* cannot set +those headers itself, which is what +``headers/identity_request_strips.conf.j2`` is for. + +nginx makes this easy to lose. ``proxy_set_header`` is array-inherited: a +location declaring any of its own discards every one from the enclosing block, +and ``proxy_pass_request_headers`` defaults to on, so an unlisted client header +reaches the upstream. A location snippet that proxies therefore has to strip +them itself; there is no server-level net below it. + +Only ``html.conf.j2`` did. Websocket, upload and image locations forwarded +whatever the client sent. + +An SSO-gated branch overwrites the same headers from ``auth_request_set``, so it +is safe on its own, but it earns no exemption here: a snippet carrying both +branches would keep passing after the strip was deleted from the other one. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: location-identity-strip`` in the head of the snippet, naming why + the location cannot forge an identity. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import PROJECT_ROOT, read_text + +_RULE = "location-identity-strip" + +LOCATION_DIR = PROJECT_ROOT / "roles/sys-svc-proxy/templates/location" + +STRIP_INCLUDE = "roles/sys-svc-proxy/templates/headers/identity_request_strips.conf.j2" + +_PROXIES_RE = re.compile(r"proxy_pass|lookup\(\s*['\"]proxy_pass['\"]") + + +def snippets() -> list: + """Return every shared location snippet.""" + return sorted(LOCATION_DIR.glob("*.conf.j2")) + + +def proxying_snippets() -> list: + """Return the snippets that hand a request to an upstream.""" + return [p for p in snippets() if _PROXIES_RE.search(read_text(str(p)))] + + +def unstripped() -> list[str]: + """Return one finding per proxying snippet that forwards client identity.""" + findings = [] + for path in proxying_snippets(): + content = read_text(str(path)) + if is_suppressed_in_head(content.splitlines(), _RULE): + continue + if STRIP_INCLUDE in content: + continue + findings.append( + f"{path.relative_to(PROJECT_ROOT)}: proxies without including " + f"{STRIP_INCLUDE!r}, so a client-supplied X-Forwarded-User reaches " + f"the upstream" + ) + return findings + + +class TestLocationIdentityStrips(unittest.TestCase): + def test_no_proxying_location_forwards_client_identity(self) -> None: + findings = unstripped() + self.assertEqual( + [], + findings, + f"location snippet(s) forwarding a forgeable identity " + f"({len(findings)}):\n" + "\n".join(f" - {f}" for f in findings), + ) + + def test_the_scan_finds_proxying_snippets(self) -> None: + self.assertTrue(proxying_snippets(), "no proxying location snippet was scanned") + + def test_a_non_proxying_snippet_is_not_demanded(self) -> None: + """A snippet that serves from disk cannot forge an upstream identity.""" + self.assertLessEqual(len(proxying_snippets()), len(snippets())) + + def test_the_strip_snippet_covers_the_oauth2_proxy_headers(self) -> None: + """The strip is only worth requiring if it names what the bridge trusts.""" + content = read_text(str(PROJECT_ROOT / STRIP_INCLUDE)) + for header in ( + "X-Forwarded-User", + "X-Forwarded-Email", + "X-Forwarded-Groups", + "X-Forwarded-Access-Token", + "X-Forwarded-Preferred-Username", + ): + with self.subTest(header=header): + self.assertIn(f'proxy_set_header {header} ""', content) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/test_no_no_log_in_test_roles.py b/tests/lint/ansible/roles/test_no_no_log_in_test_roles.py new file mode 100644 index 0000000000..a4528978cf --- /dev/null +++ b/tests/lint/ansible/roles/test_no_no_log_in_test_roles.py @@ -0,0 +1,100 @@ +"""Lint: a test role must never carry ``no_log``. + +``roles/test-*`` run only in CI, against a throwaway cluster whose credentials +are generated per deploy and thrown away with it. ``no_log`` there protects +nothing and costs the one thing a red test job is for: the output that says +what failed. A masked task reports ``the output has been hidden`` and the +operator has to re-run the whole matrix round to learn what a single assertion +saw. + +The rule is absolute, so it carries no ``nocheck`` escape hatch. When a test +task's output looks too sensitive to print, extract the field the assertion +needs instead of blinding the task. +""" + +from __future__ import annotations + +import re +import unittest +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from utils.annotations.message import in_github_actions, warning +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from pathlib import Path + +_NO_LOG_RE = re.compile(r"^\s*no_log\s*:") + + +@dataclass(frozen=True) +class Finding: + path: str + line: int + text: str + + +def _collect_findings(root: Path) -> list[Finding]: + findings: list[Finding] = [] + for yaml_file in sorted(root.glob("roles/test-*/**/*.yml")): + try: + lines = read_text(str(yaml_file)).splitlines() + except OSError: + continue + rel = yaml_file.relative_to(root).as_posix() + findings.extend( + Finding(rel, number, line.strip()) + for number, line in enumerate(lines, start=1) + if _NO_LOG_RE.match(line) + ) + return findings + + +def _fix_hint(rel: str) -> str: + return ( + f"{rel} uses no_log in a test role. Test roles run in CI against " + "throwaway credentials, so no_log hides the failure output without " + "protecting anything. Drop it; if a value is genuinely too large or " + "noisy to print, extract the field the assertion reads." + ) + + +class TestNoNoLogInTestRoles(unittest.TestCase): + def test_test_roles_carry_no_no_log(self) -> None: + findings = _collect_findings(PROJECT_ROOT) + + for finding in findings: + warning( + _fix_hint(finding.path), + title="no_log in a test role", + file=finding.path, + line=finding.line, + ) + + if findings and not in_github_actions(): + print() + print(f"[WARNING] no_log in test roles ({len(findings)}):") + for finding in findings: + print(f"- {finding.path}:{finding.line}: {finding.text}") + + if findings: + self.fail( + f"{len(findings)} no_log entr(ies) in roles/test-*:\n" + + "\n".join(f"{f.path}:{f.line}: {_fix_hint(f.path)}" for f in findings) + ) + + def test_the_scan_reaches_the_test_roles(self) -> None: + """A glob that matches nothing would pass vacuously forever.""" + scanned = sorted(PROJECT_ROOT.glob("roles/test-*/**/*.yml")) + self.assertTrue( + scanned, + "no YAML found under roles/test-*; the glob no longer reaches the " + "test roles, so the rule above cannot fire", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/test_playwright_helpers_staged.py b/tests/lint/ansible/roles/test_playwright_helpers_staged.py new file mode 100644 index 0000000000..d66a0d7406 --- /dev/null +++ b/tests/lint/ansible/roles/test_playwright_helpers_staged.py @@ -0,0 +1,157 @@ +"""Lint: a Playwright helper a spec imports must be staged next to it. + +Two stagers copy role specs into `/e2e/tests/` and, beside them, the shared +helpers: the deploy task and `rerun-spec.sh`. Both used to name the helpers, +and had already drifted apart. A spec importing a helper neither stager copies +fails at import with `Cannot find module`, for every role that imports it at +once. + +The scan set is what the specs actually import, not a list of helper names: a +require that resolves to a sibling in the role's own playwright directory is +role-local and needs no staging, and everything else must be staged. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: playwright-helper-staged`` on, or directly above, the require. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import ( + PROJECT_ROOT, + iter_project_files_with_content, + read_text, +) + +_RULE = "playwright-helper-staged" + +RUNNER_FILES = PROJECT_ROOT / "roles/test-e2e-playwright/files" +STAGING_TASK = PROJECT_ROOT / "roles/test-e2e-playwright/tasks/02_run_one.yml" +RERUN_SCRIPT = PROJECT_ROOT / "scripts/tests/e2e/rerun-spec.sh" +LINT_SCRIPT = PROJECT_ROOT / "scripts/lint/playwright.sh" + +_REQUIRE_RE = re.compile(r"""require\(["']\./([A-Za-z0-9._-]+)["']\)""") + +_MOUNTED_AS_DIRECTORY = frozenset({"personas"}) + +_NOT_A_HELPER = frozenset({"playwright.config.js"}) + +_GLOB_MARKER = "roles/test-e2e-playwright/files') }}/*.js" +_SHELL_GLOB_MARKER = 'roles/test-e2e-playwright/files"/*.js' +_LINT_GLOB_MARKER = '"${HELPERS_SRC}"/*.js' + + +def staged_helpers() -> set[str]: + """Return the helper file names both stagers copy into the tests dir. + + Neither stager names them any more: the deploy task globs the runner's own + `files/*.js` and `rerun-spec.sh` does the same, so the directory listing is + the set. Three hand-maintained copies of it had already drifted apart when + that was the design. + """ + return { + path.name + for path in RUNNER_FILES.glob("*.js") + if path.name not in _NOT_A_HELPER + } + + +def spec_files() -> list[tuple[str, str]]: + """Return ``(path, content)`` for every role-local Playwright spec.""" + return [ + (path, content) + for path, content in iter_project_files_with_content(extensions=(".js",)) + if "/files/playwright/" in path.replace("\\", "/") + ] + + +def unstaged_requires() -> list[str]: + """Return one finding per imported helper the runner never stages.""" + staged = staged_helpers() + findings = [] + for path, content in spec_files(): + role_dir = Path(path).parent + lines = content.splitlines() + for index, line in enumerate(lines, start=1): + for name in _REQUIRE_RE.findall(line): + if (role_dir / f"{name}.js").is_file(): + continue + if name in _MOUNTED_AS_DIRECTORY: + continue + if is_suppressed_at(lines, index, _RULE): + continue + if f"{name}.js" not in staged: + findings.append( + f"{path}:{index}: requires {name!r}, which is neither a " + f"sibling spec nor staged by 02_run_one.yml" + ) + return findings + + +def stagers_without_the_glob() -> list[str]: + """Return one finding per stager that stopped deriving the helper set. + + Every stager must glob the runner's `files/*.js`. One that goes back to + naming helpers drifts from the others silently, which is how three copies + of the same set came to hold three different sets: the deploy task named + four, `rerun-spec.sh` three, and `playwright.sh` four again but a + different four. + """ + findings = [] + for path, marker in ( + (STAGING_TASK, _GLOB_MARKER), + (RERUN_SCRIPT, _SHELL_GLOB_MARKER), + (LINT_SCRIPT, _LINT_GLOB_MARKER), + ): + if marker not in read_text(str(path)): + findings.append(f"{path.name} no longer globs the helper directory") + return findings + + +class TestPlaywrightHelpersStaged(unittest.TestCase): + def test_every_imported_helper_is_staged(self) -> None: + findings = unstaged_requires() + self.assertEqual( + [], + findings, + f"Playwright helper import(s) that would fail at runtime " + f"({len(findings)}):\n" + "\n".join(f" - {f}" for f in findings), + ) + + def test_both_stagers_derive_the_helper_set(self) -> None: + findings = stagers_without_the_glob() + self.assertEqual([], findings, "\n".join(findings)) + + def test_the_scan_reaches_the_specs(self) -> None: + self.assertTrue( + spec_files(), "no Playwright spec was scanned, so the rule is vacuous" + ) + + def test_the_helper_set_is_not_empty(self) -> None: + """An empty set would make every shared import look unstaged.""" + self.assertIn("service-gating.js", staged_helpers()) + + def test_the_config_is_not_treated_as_a_helper(self) -> None: + """It is staged one level up, as the run's config, not beside the specs.""" + self.assertNotIn("playwright.config.js", staged_helpers()) + + def test_a_shared_helper_is_actually_reached(self) -> None: + """Role-local siblings dominate the requires; without a shared one in + the set the rule would pass while never testing what it exists for.""" + shared = { + name + for path, content in spec_files() + for name in _REQUIRE_RE.findall(content) + if not (Path(path).parent / f"{name}.js").is_file() + and name not in _MOUNTED_AS_DIRECTORY + } + self.assertTrue(shared, "no spec imports a shared helper") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/test_readme.py b/tests/lint/ansible/roles/test_readme.py index a235956bb9..039f17be3a 100644 --- a/tests/lint/ansible/roles/test_readme.py +++ b/tests/lint/ansible/roles/test_readme.py @@ -12,7 +12,7 @@ Enforced (hard fail) rules from the template ``templates/roles/README.md.j2.tmpl`` (the H2s it emits with no optional context): ``## Description``, ``## Overview``, ``## Cosmos``, ``## Features`` and ``## Credits``. The template is the - single source of truth; ``cli.build.readme.schema`` reads it. + single source of truth; ``cli.build.docs.readme.schema`` reads it. 3. **Section order.** Those required H2s MUST appear in the template order (extra H2s MAY be interleaved between them), and ``## Credits`` MUST be the last H2 heading in the file. @@ -52,9 +52,9 @@ from typing import TYPE_CHECKING import yaml as _yaml -from cli.build.readme import schema -from cli.build.readme.generate import _app_name, _managed_blocks -from cli.build.readme.sections import parse_readme +from cli.build.docs.readme import schema +from cli.build.docs.readme.generate import _app_name, _managed_blocks +from cli.build.docs.readme.sections import parse_readme from utils.cache.files import PROJECT_ROOT, read_text from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ROLE_FILE_META_MAIN diff --git a/tests/lint/ansible/roles/test_stack_vars_resolve_in_their_own_role.py b/tests/lint/ansible/roles/test_stack_vars_resolve_in_their_own_role.py new file mode 100644 index 0000000000..8c45e4ee54 --- /dev/null +++ b/tests/lint/ansible/roles/test_stack_vars_resolve_in_their_own_role.py @@ -0,0 +1,117 @@ +"""Lint: a value handed to a stack include must not read ``application_id``. + +``vars:`` on an ``include_role`` reaches everything the include pulls in, and +the expression is evaluated where it is used rather than where it is written. +``sys-stk-full`` pulls in the proxy and the database, and those roles set +``application_id`` to their own id, so an expression that reads it resolves +against the wrong application by the time anyone asks for it. + +It fails as a missing key in a role that never declared the value: a repository +url written by one app was looked up on ``svc-prx-openresty``, which has no such +service, and the git task died on an unresolvable argument. + +Naming the application literally makes the expression answer the same in every +scope it travels through. + +Only the ``compose_*`` keys are judged, because only those does the included +chain evaluate. A value nobody downstream reads is merely in scope and harmless; +matching every handed-over key instead reported thirteen values, six of them +nothing. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: stack-var-foreign-scope`` on, or directly above, the definition. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import PROJECT_ROOT, read_text +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +_RULE = "stack-var-foreign-scope" +_STACK_INCLUDE = "sys-stk-full" + +_PASSED_RE = re.compile(r"^\s+(compose_[a-z_]+):\s*\"\{\{\s*([A-Z][A-Z0-9_]*)\s*\}\}\"") +_SCOPED_RE = re.compile(r"(? set[str]: + """Return the variable names a role hands to the stack include. + + Args: + role: the role directory. + """ + passed: set[str] = set() + for path in sorted(role.glob("tasks/**/*.yml")): + lines = read_text(str(path)).splitlines() + for index, line in enumerate(lines): + if _STACK_INCLUDE not in line: + continue + for following in lines[index : index + 12]: + match = _PASSED_RE.match(following) + if match: + passed.add(match.group(2)) + return passed + + +def definitions_reading_scope(role, names: set[str]) -> list[str]: + """Return one finding per handed-over definition that reads the scope. + + Args: + role: the role directory. + names: the variable names the role hands to the stack include. + """ + variables = role / ROLE_FILE_VARS_MAIN + if not names or not variables.is_file(): + return [] + findings = [] + lines = read_text(str(variables)).splitlines() + for index, line in enumerate(lines, start=1): + name = line.split(":", 1)[0].strip() + if name not in names or not _SCOPED_RE.search(line): + continue + if is_suppressed_at(lines, index, _RULE): + continue + findings.append( + f"{variables.relative_to(PROJECT_ROOT)}:{index}: {name} is handed to " + f"{_STACK_INCLUDE} and resolves against whichever role reads it" + ) + return findings + + +def stack_vars_reading_foreign_scope() -> list[str]: + """Return one finding per value that would resolve in a foreign role.""" + findings = [] + for role in sorted((PROJECT_ROOT / "roles").iterdir()): + if not role.is_dir(): + continue + findings.extend(definitions_reading_scope(role, passed_into_stack(role))) + return findings + + +class TestStackVarsResolveInTheirOwnRole(unittest.TestCase): + def test_no_handed_over_value_reads_the_reader_s_scope(self) -> None: + findings = stack_vars_reading_foreign_scope() + self.assertEqual( + [], + findings, + f"value(s) that resolve against the wrong role ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + def test_the_shape_it_guards_is_actually_in_use(self) -> None: + """Without one, a renamed include would let the rule pass over everything.""" + handing = [ + role + for role in sorted((PROJECT_ROOT / "roles").iterdir()) + if role.is_dir() and passed_into_stack(role) + ] + self.assertGreater(len(handing), 3, "no role hands a value to the stack") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/test_vhost_cross_cutting_includes.py b/tests/lint/ansible/roles/test_vhost_cross_cutting_includes.py new file mode 100644 index 0000000000..26ddb0d220 --- /dev/null +++ b/tests/lint/ansible/roles/test_vhost_cross_cutting_includes.py @@ -0,0 +1,218 @@ +"""Lint: a role-local vhost must carry the includes every vhost needs. + +`sys-stk-front-proxy` renders a role's own ``templates/proxy.conf.j2`` when it +exists and one of the shared flavours otherwise. Overriding the file is how a +role expresses its own locations, and that is fine. What is not fine is that +overriding it silently drops every cross-cutting concern the shared flavours +carry, because those live as includes inside the file being replaced. + +The MCP policy is the case that made this visible: it decides whether an +application's own vhost serves its declared endpoint path or returns 404, it was +added to both shared flavours, and the one provider whose native path most +needed hiding rendered from its own template and kept serving it. + +The required set is derived from the shared flavours rather than listed here, so +a concern added to them is required of the overrides on the next run. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: vhost-cross-cutting-include`` in the head of the role's + ``templates/proxy.conf.j2``, naming why the concern does not apply. +""" + +from __future__ import annotations + +import re +import unittest +from collections.abc import Mapping + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_MCP, ROLE_FILE_META_SERVICES + +_RULE = "vhost-cross-cutting-include" + +FLAVOUR_DIR = PROJECT_ROOT / "roles/sys-svc-proxy/templates/vhost" +OVERRIDES = sorted((PROJECT_ROOT / "roles").glob("*/templates/proxy.conf.j2")) + +_INCLUDE_RE = re.compile(r"""\{%-?\s*include\s+['"]([^'"]+)['"]""") + +_LOCATION_SNIPPETS = "roles/sys-svc-proxy/templates/location/" + + +def flavour_includes() -> dict[str, set[str]]: + """Return each shared flavour's include set, keyed by flavour name.""" + return { + path.name: set(_INCLUDE_RE.findall(read_text(str(path)))) + for path in sorted(FLAVOUR_DIR.glob("*.conf.j2")) + } + + +def required_includes() -> set[str]: + """Return the includes every shared flavour carries. + + The intersection, not the union: a concern only one flavour needs is that + flavour's business, while one both carry is what a vhost is expected to + have regardless of shape. Location snippets are excluded because they are + the part an override legitimately replaces. + """ + sets = list(flavour_includes().values()) + if not sets: + return set() + common = set.intersection(*sets) + return {inc for inc in common if not inc.startswith(_LOCATION_SNIPPETS)} + + +def role_of(path) -> str: + """Return the role directory name of ``roles//templates/...``. + + Args: + path: an absolute path under ``roles/``. + """ + return path.relative_to(PROJECT_ROOT).parts[1] + + +def serves_mcp(role: str) -> bool: + """Return whether a role declares an MCP endpoint path of its own. + + Args: + role: the role directory name. + """ + meta = PROJECT_ROOT / "roles" / role / ROLE_FILE_META_MCP + if not meta.is_file(): + return False + block = load_yaml_any(str(meta), default_if_missing={}) + if not isinstance(block, Mapping): + return False + return bool((block.get("endpoint") or {}).get("path")) + + +def missing_includes() -> list[str]: + """Return one finding per override dropping a concern that applies to it. + + An override is only asked for a concern its role actually has. The MCP + policy renders nothing for a role with no endpoint path, so demanding it + everywhere would report noise and train the reader to skip the report. + """ + findings = [] + for path in OVERRIDES: + if not serves_mcp(role_of(path)): + continue + content = read_text(str(path)) + if is_suppressed_in_head(content.splitlines(), _RULE): + continue + for missing in sorted(required_includes() - set(_INCLUDE_RE.findall(content))): + rel = path.relative_to(PROJECT_ROOT) + findings.append(f"{rel}: does not include {missing!r}") + return findings + + +GATED_INCLUDES = ( + "roles/web-app-keycloak/templates/sso_proxy/endpoint.conf.j2", + "roles/sys-svc-proxy/templates/headers/buffers.conf.j2", +) + + +def is_proxy_gated(role: str) -> bool: + """Return whether oauth2-proxy fronts the role, per ``meta/services.yml``. + + Args: + role: the role directory name. + + Mirrors ``utils.roles.applications.services.sso``: enabled and flavor + ``oauth2``. An ``oidc`` role authenticates inside the application and its + vhost carries no gate. + """ + meta = PROJECT_ROOT / "roles" / role / ROLE_FILE_META_SERVICES + if not meta.is_file(): + return False + block = load_yaml_any(str(meta), default_if_missing={}) + sso = block.get("sso") if isinstance(block, Mapping) else None + if not isinstance(sso, Mapping): + return False + return bool(sso.get("enabled")) and sso.get("flavor") == "oauth2" + + +def gated_without_the_gate() -> list[str]: + """Return one finding per gated override missing a gate-only include. + + A gated vhost needs the oauth2-proxy endpoint to authenticate at all, and + the raised header buffers because a Keycloak session cookie does not fit + nginx's defaults. Neither is in the shared flavours' intersection, so the + rule above cannot ask for them; an override that flips to ``oauth2`` later + would drop both without a word. + """ + findings = [] + for path in OVERRIDES: + role = role_of(path) + if not is_proxy_gated(role): + continue + content = read_text(str(path)) + if is_suppressed_in_head(content.splitlines(), _RULE): + continue + for missing in GATED_INCLUDES: + if missing not in content: + rel = path.relative_to(PROJECT_ROOT) + findings.append(f"{rel}: is proxy-gated but omits {missing!r}") + return findings + + +class TestVhostCrossCuttingIncludes(unittest.TestCase): + def test_no_override_drops_a_shared_concern(self) -> None: + findings = missing_includes() + self.assertEqual( + [], + findings, + f"role vhost(s) dropping a cross-cutting include ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + def test_the_required_set_is_derived_and_not_empty(self) -> None: + """An empty set would pass every override without checking anything.""" + self.assertTrue( + required_includes(), + "no include is common to the shared flavours, so the rule is vacuous", + ) + + def test_the_mcp_policy_is_required(self) -> None: + """The concern this rule exists for must actually be in the set.""" + self.assertIn( + "roles/sys-svc-proxy/templates/mcp/vhost.conf.j2", required_includes() + ) + + def test_the_overrides_are_found(self) -> None: + self.assertTrue(OVERRIDES, "no role-local proxy.conf.j2 was scanned") + + def test_a_gated_override_carries_its_gate(self) -> None: + findings = gated_without_the_gate() + self.assertEqual( + [], + findings, + f"proxy-gated vhost(s) missing a gate include ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + def test_a_gated_override_is_actually_reached(self) -> None: + """Without one in the set the gate rule would pass over nothing.""" + self.assertTrue( + [role_of(p) for p in OVERRIDES if is_proxy_gated(role_of(p))], + "no role both overrides its vhost and is fronted by oauth2-proxy", + ) + + def test_an_mcp_serving_override_is_actually_reached(self) -> None: + """Most overrides serve no MCP, so the rule needs one that does.""" + reached = [role_of(p) for p in OVERRIDES if serves_mcp(role_of(p))] + self.assertTrue( + reached, "no role both overrides its vhost and declares an MCP endpoint" + ) + + def test_location_snippets_are_not_required(self) -> None: + """Locations are what an override exists to replace.""" + self.assertFalse( + [inc for inc in required_includes() if inc.startswith(_LOCATION_SNIPPETS)] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/roles/web-app/playwright/test_no_raw_timeout_literals.py b/tests/lint/ansible/roles/web-app/playwright/test_no_raw_timeout_literals.py index 23916f4db5..2523e38a22 100644 --- a/tests/lint/ansible/roles/web-app/playwright/test_no_raw_timeout_literals.py +++ b/tests/lint/ansible/roles/web-app/playwright/test_no_raw_timeout_literals.py @@ -8,10 +8,17 @@ scaling and flakes over onion while passing on clearnet. Forbidden (raw milliseconds) Required (scaled) ``timeout: 30_000`` ``timeout: resolveTimeout(30_000)`` + ``timeout: SOME_TIMEOUT_MS`` ``timeout: resolveTimeout(SOME_TIMEOUT_MS)`` ``waitForTimeout(500)`` ``waitForTimeout(resolveTimeout(500))`` ``test.setTimeout(120_000)`` ``test.setTimeout(resolveTimeout(120_000))`` ``setTimeout(resolve, 250)`` ``setTimeout(resolve, resolveTimeout(250))`` +An upper bound must scale, so ``timeout:`` rejects a CONSTANT_CASE name as well +as a digit: a literal keeps bypassing the helper when it hides behind a name. +A poll interval is the opposite โ€” scaling one makes a slow target notice its +element LATER, not sooner โ€” so ``waitForTimeout``/``setTimeout`` accept a named +unscaled interval, which is why they are matched on a leading digit only. + Scope: role specs + companions under ``roles/*/files/playwright/`` and the shared persona flows/utilities under ``roles/test-e2e-playwright/files/``. The scaling primitive itself (``timeouts.js``) is exempt. Per-line opt-out for a @@ -38,6 +45,7 @@ _STRING = re.compile( _RAW_TIMEOUT = re.compile( r"\btimeout:\s*[0-9]" + r"|\btimeout:\s*[A-Z][A-Z0-9_]+\b" r"|\bwaitForTimeout\(\s*[0-9]" r"|\bsetTimeout\(\s*[0-9]" r"|\bsetTimeout\(\s*[^,()]+,\s*[0-9]" diff --git a/tests/lint/ansible/services/test_agent_identity.py b/tests/lint/ansible/services/test_agent_identity.py new file mode 100644 index 0000000000..893e34d38f --- /dev/null +++ b/tests/lint/ansible/services/test_agent_identity.py @@ -0,0 +1,133 @@ +"""Lint: a sandboxed agent acts as its own non-privileged platform account. + +The users machinery reserves a key per role, so ``hermes`` and ``openclaw`` +exist as accounts whether or not anyone claims them. Claiming the key is what +turns a reservation into an identity the agent may authenticate as, and gives +the account its description and its mailbox. + +Two relations per sandboxed role: + +* it claims its own reserved user key in ``meta/users.yml``; +* the claimed account carries no role, because an agent employee is a standard + user and never an administrator. + +The password is deliberately not one of them. Provisioning gives every declared +account a stored password, and a role that needs a different alphabet says so +in its own ``meta/users.yml`` rather than carrying a second credential beside +the account it already owns. + +Pointing an agent at an account that already exists stays possible: the +inventory ``users`` variable overrides the same key, which is the documented +override path and needs no change here. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: agent-identity`` in the head of the role's ``meta/users.yml``. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.entity.name import get_entity_name +from utils.roles.mapping import ROLE_FILE_META_SECRETS, ROLE_FILE_META_USERS + +from . import PROJECT_ROOT +from .test_sandboxed_no_host_socket import _sandboxed_roles + +_RULE = "agent-identity" +_CREDENTIAL = "identity_password" + + +def _users_of(role: str) -> tuple[Mapping | None, list[str]]: + path = PROJECT_ROOT / "roles" / role / ROLE_FILE_META_USERS + if not path.is_file(): + return None, [] + data = load_yaml_any(str(path), default_if_missing={}) + lines = read_text(str(path)).splitlines() + return (data if isinstance(data, Mapping) else None), lines + + +def _claimed_roles() -> list[str]: + kept = [] + for role in sorted(_sandboxed_roles()): + _users, lines = _users_of(role) + if lines and is_suppressed_in_head(lines, _RULE): + continue + kept.append(role) + return kept + + +class TestAgentIdentity(unittest.TestCase): + def test_every_agent_claims_its_own_account(self) -> None: + missing = [] + for role in _claimed_roles(): + users, _lines = _users_of(role) + key = get_entity_name(role) + if users is None or key not in users: + missing.append( + f"{role}: does not claim the reserved user key '{key}' in " + f"{ROLE_FILE_META_USERS}, so the agent has no account of " + f"its own to act as" + ) + self.assertEqual( + [], + missing, + "sandboxed agent(s) without their own account:\n" + + "\n".join(f" - {m}" for m in missing), + ) + + def test_no_agent_account_carries_a_role(self) -> None: + privileged = [] + for role in _claimed_roles(): + users, _lines = _users_of(role) + entry = (users or {}).get(get_entity_name(role)) + if not isinstance(entry, Mapping): + continue + if entry.get("roles"): + privileged.append( + f"{role}: its account declares roles {entry['roles']}; an " + f"agent employee is a standard user, never privileged" + ) + self.assertEqual( + [], + privileged, + "agent account(s) with privileges:\n" + + "\n".join(f" - {p}" for p in privileged), + ) + + def test_no_agent_carries_a_credential_beside_its_own_account(self) -> None: + doubled = [] + for role in _claimed_roles(): + secrets = load_yaml_any( + str(PROJECT_ROOT / "roles" / role / ROLE_FILE_META_SECRETS), + default_if_missing={}, + ) + credentials = (secrets or {}).get("credentials") + if isinstance(credentials, Mapping) and _CREDENTIAL in credentials: + doubled.append( + f"{role}: declares secrets.credentials.{_CREDENTIAL} beside " + f"the account it already owns; an account password belongs " + f"in {ROLE_FILE_META_USERS}, where provisioning stores it" + ) + self.assertEqual( + [], + doubled, + "agent(s) carrying a second credential for their own account:\n" + + "\n".join(f" - {d}" for d in doubled), + ) + + def test_the_scan_finds_agents(self) -> None: + self.assertTrue( + _claimed_roles(), + "no sandboxed agent role found, so every rule here would pass " + "vacuously; check that the scan still reads the right topic", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_config_volume_secrets.py b/tests/lint/ansible/services/test_config_volume_secrets.py new file mode 100644 index 0000000000..89a41d47cb --- /dev/null +++ b/tests/lint/ansible/services/test_config_volume_secrets.py @@ -0,0 +1,133 @@ +"""Lint: a credential does not belong in a volume declared non-secret. + +``meta/volumes.yml`` distinguishes ``type: secret`` from ``type: config``, and +the distinction is load-bearing for anyone reading a role: a config volume is +the thing you may show someone, copy into a bug report, or mount read-only for +every process in the container. A template that renders a live client secret or +an account password into one makes that reading false, and the mode these +volumes carry is usually ``0444``, so every process in the container can read +it. + +The scan derives the credential vocabulary from how the repository actually +writes secrets rather than from a guess: the ``secrets.credentials`` config +path, the OIDC client secret, a resolved user's password, and the MCP +credential lookup. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: config-volume-secret`` in the head of the role's + ``meta/volumes.yml``, naming why the credential has to travel this way. +""" + +from __future__ import annotations + +import re +import unittest +from collections.abc import Mapping + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_VOLUMES + +from . import PROJECT_ROOT + +_RULE = "config-volume-secret" +_NON_SECRET_TYPES = frozenset({"config"}) + +_SOURCE_FILE = re.compile(r"'([^']+)'\s*\]\s*\|\s*path_join") + +_CREDENTIALS = ( + re.compile(r"secrets\.credentials\.[A-Za-z0-9_]+"), + re.compile(r"OIDC\.CLIENT\.SECRET"), + re.compile(r"lookup\(\s*'users'[^)]*\)\s*\.\s*password"), +) + + +def rendered_credentials(text: str) -> list[str]: + """Return the credential expressions a template renders, deduplicated. + + Args: + text: the template's contents. + """ + found = set() + for pattern in _CREDENTIALS: + found.update(pattern.findall(text)) + return sorted(found) + + +def _source_file(entry: Mapping) -> str: + """Return the file name a volume's source expression names, or "". + + Args: + entry: one ``meta/volumes.yml`` entry. + """ + match = _SOURCE_FILE.search(str(entry.get("source") or "")) + return match[1] if match else "" + + +def _non_secret_config_volumes() -> list[tuple[str, str, str, str]]: + """Return ``(role, volume, template path, mode)`` per rendered config volume.""" + found = [] + for path in sorted((PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_VOLUMES}")): + role = path.parent.parent.name + if is_suppressed_in_head(read_text(str(path)).splitlines(), _RULE): + continue + declared = load_yaml_any(str(path), default_if_missing={}) + if not isinstance(declared, Mapping): + continue + for name, entry in declared.items(): + if not isinstance(entry, Mapping): + continue + if str(entry.get("type") or "") not in _NON_SECRET_TYPES: + continue + source = _source_file(entry) + if not source: + continue + template = PROJECT_ROOT / "roles" / role / "templates" / f"{source}.j2" + if template.is_file(): + found.append((role, name, str(template), str(entry.get("mode") or ""))) + return found + + +class TestConfigVolumeSecrets(unittest.TestCase): + def test_no_config_volume_renders_a_credential(self) -> None: + leaking = [] + for role, volume, template, mode in _non_secret_config_volumes(): + rendered = rendered_credentials(read_text(template)) + if rendered: + leaking.append( + f"{role}: volume {volume!r} is declared type config" + f"{f' with mode {mode}' if mode else ''} yet its template " + f"renders {rendered}" + ) + self.assertEqual( + [], + leaking, + f"credential(s) rendered into a non-secret volume ({len(leaking)}):\n" + + "\n".join(f" - {v}" for v in leaking), + ) + + def test_the_scan_finds_rendered_config_volumes(self) -> None: + self.assertTrue( + _non_secret_config_volumes(), + "no config volume resolves to a template, so this rule would pass " + "vacuously; check that the source expression is still parsed", + ) + + def test_the_credential_vocabulary_still_matches_the_repository(self) -> None: + for pattern in _CREDENTIALS: + hits = [ + path + for path in (PROJECT_ROOT / "roles").glob("*/templates/*.j2") + if pattern.search(read_text(str(path))) + ] + self.assertTrue( + hits, + f"nothing in the repository matches {pattern.pattern!r} any " + f"more, so that half of the vocabulary silently checks nothing", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_disabled_service_bond.py b/tests/lint/ansible/services/test_disabled_service_bond.py new file mode 100644 index 0000000000..3ed1fa39e3 --- /dev/null +++ b/tests/lint/ansible/services/test_disabled_service_bond.py @@ -0,0 +1,125 @@ +"""Lint: a permanently disabled services entry carries no resource weight. + +``bond`` is the per-service share the resource model bills a role for. The +model never reaches it on a disabled entry: +:func:`utils.roles.applications.services.resources.collect_role_resources` +skips a service whose ``enabled`` is literally ``false`` before it reads any +resource key, so the number sits in the file describing a cost nobody pays. + +Left there it reads as a live weight and outlives the reason it was written +for. An entry that was switched off because the integration cannot form keeps +claiming a share of the round's budget, which is the same statement the +``enabled`` flag was just used to withdraw. + +Only a literal ``enabled: false`` is in scope. A dynamic +``"{{ '' in group_names }}"`` gate is decided per round, so its ``bond`` +is the weight of the rounds where the service is on. + +Required +-------- + +For every ``services.`` in a ``meta/services.yml`` whose ``enabled`` is +literally ``false``, ``bond`` MUST be absent or ``0``. + +Suppression +----------- + +``# nocheck: disabled-service-bond`` on the ``bond`` line, for an entry whose +weight a consumer outside the resource model still reads. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping + +from utils.annotations.suppress import line_has_rule +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +_RULE = "disabled-service-bond" + + +def _bond_line_no(lines: list[str], key: str) -> int | None: + """Return the 1-based line of ``key``'s ``bond``, or None when absent. + + Args: + lines: the file's lines. + key: the first-level service key whose block to scan. + """ + inside = False + for idx, line in enumerate(lines, start=1): + if line.startswith(f"{key}:"): + inside = True + continue + if inside: + if line and not line.startswith((" ", "\t", "#")): + return None + if line.strip().startswith("bond:"): + return idx + return None + + +def offenders() -> list[str]: + """Return one finding per disabled entry that still declares a bond.""" + findings: list[str] = [] + for path in sorted((PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_SERVICES}")): + services = load_yaml_any(str(path), default_if_missing={}) + if not isinstance(services, Mapping): + continue + lines = read_text(str(path)).splitlines() + role = path.parent.parent.name + for key, entry in services.items(): + if not isinstance(entry, Mapping): + continue + if entry.get("enabled") is not False: + continue + bond = entry.get("bond") + if bond is None or bond == 0: + continue + line_no = _bond_line_no(lines, str(key)) + if line_no is not None and line_has_rule(lines[line_no - 1], _RULE): + continue + findings.append( + f"{role}: services.{key} is disabled but declares " + f"bond: {bond}; the resource model skips the entry before it " + f"reads the weight, so drop it or set it to 0" + ) + return findings + + +class TestDisabledServiceBond(unittest.TestCase): + def test_no_disabled_entry_declares_a_bond(self) -> None: + findings = offenders() + self.assertEqual( + [], + findings, + f"disabled services entries carrying a bond ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + def test_the_scan_reaches_disabled_entries(self) -> None: + seen = 0 + for path in sorted( + (PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_SERVICES}") + ): + services = load_yaml_any(str(path), default_if_missing={}) + if not isinstance(services, Mapping): + continue + seen += sum( + 1 + for entry in services.values() + if isinstance(entry, Mapping) and entry.get("enabled") is False + ) + self.assertTrue( + seen, + "no services entry is literally disabled, so the rule would pass " + "vacuously; check that the scan still reads meta/services.yml", + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/lint/ansible/services/test_gateway_backend_registered.py b/tests/lint/ansible/services/test_gateway_backend_registered.py new file mode 100644 index 0000000000..140b8df5b2 --- /dev/null +++ b/tests/lint/ansible/services/test_gateway_backend_registered.py @@ -0,0 +1,94 @@ +"""Lint: every model backend the gateway declares is also routed by it. + +``svc-ai-litellm`` names each backend twice: once as a ``meta/services.yml`` +flag that pulls the backend role into the deployment, and once as a +``model_list`` branch in ``templates/config.yaml.j2`` that gives it a model +alias. Only the second one routes. A backend declared without its branch +deploys, consumes its memory and storage budget, and answers nothing, because +no alias resolves to it. + +The scan reads the flags rather than a list, so adding a backend flag without +wiring the alias fails here instead of at the first prompt. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: gateway-backend-registered`` on the flag's ``enabled`` line or + the non-empty line above it. +""" + +from __future__ import annotations + +import re +import unittest +from collections.abc import Mapping + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +_RULE = "gateway-backend-registered" +_GATEWAY_ROLE = "svc-ai-litellm" +_GATEWAY_CONFIG = "templates/config.yaml.j2" + +_BACKEND_FLAG = re.compile(r"'(?Psvc-ai-[a-z0-9-]+)'\s+in\s+group_names") + + +def _gateway_dir(): + return PROJECT_ROOT / "roles" / _GATEWAY_ROLE + + +def _declared_backends() -> dict[str, str]: + """Return ``{backend role id: flag name}`` for every backend flag.""" + services_path = _gateway_dir() / ROLE_FILE_META_SERVICES + services = load_yaml_any(str(services_path), default_if_missing={}) + lines = read_text(str(services_path)).splitlines() + backends: dict[str, str] = {} + if not isinstance(services, Mapping): + return backends + for flag, block in services.items(): + if not isinstance(block, Mapping): + continue + match = _BACKEND_FLAG.search(str(block.get("enabled") or "")) + if not match: + continue + line_no = next( + (i + 1 for i, line in enumerate(lines) if line.startswith(f"{flag}:")), + 1, + ) + if is_suppressed_at(lines, line_no, _RULE, mode="same-or-above"): + continue + backends[match["role"]] = flag + return backends + + +class TestGatewayBackendRegistered(unittest.TestCase): + def test_every_declared_backend_has_a_model_list_branch(self) -> None: + config = read_text(str(_gateway_dir() / _GATEWAY_CONFIG)) + missing = [ + f"{role} (flag '{flag}'): pulled into the deployment but " + f"{_GATEWAY_ROLE}/{_GATEWAY_CONFIG} never branches on it, so no " + f"model alias routes to it" + for role, flag in sorted(_declared_backends().items()) + if role not in config + ] + self.assertEqual( + [], + missing, + f"gateway backend(s) without a model_list branch ({len(missing)}):\n" + + "\n".join(f" - {m}" for m in missing), + ) + + def test_the_scan_finds_backend_flags(self) -> None: + self.assertTrue( + _declared_backends(), + f"{_GATEWAY_ROLE} declares no svc-ai-* backend flag, so the rule " + "would pass vacuously; check that the scan still reads the right " + "topic", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_litellm_consumer_contract.py b/tests/lint/ansible/services/test_litellm_consumer_contract.py new file mode 100644 index 0000000000..981a287792 --- /dev/null +++ b/tests/lint/ansible/services/test_litellm_consumer_contract.py @@ -0,0 +1,114 @@ +"""Lint: every LiteLLM consumer role is bound by the gateway's own contract. + +``svc-ai-litellm/tasks/utils/consumer_contract.yml`` is the single place that +refuses an empty virtual key and an AI base URL pointing outside the container +network. A role that declares the ``litellm`` service but never includes it +still renders its AI configuration, so a missing key or a public endpoint +reaches a green deploy and every prompt leaves the deployment unauthenticated. + +The scan derives the consumer set from the repository rather than from a list: +a ``litellm`` block without ``modes`` is a consumer flag, while the gateway +(``svc-ai-litellm``) and its admin UI (``web-app-litellm``) declare the service +they run and are not bound by the contract they own. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: litellm-consumer-contract`` in the head of the role's + ``meta/services.yml``. +""" + +from __future__ import annotations + +import os +import unittest +from collections.abc import Mapping +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import iter_project_files_with_content, read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_SECRETS, ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +_RULE = "litellm-consumer-contract" +_SERVICE = "litellm" +_CREDENTIAL = "litellm_api_key" +_CONTRACT = "roles/svc-ai-litellm/tasks/utils/consumer_contract.yml" + + +def _consumer_roles() -> list[Path]: + """Return the role directories that consume the shared gateway.""" + roles: list[Path] = [] + for services_path in sorted( + Path(PROJECT_ROOT, "roles").glob(f"*/{ROLE_FILE_META_SERVICES}") + ): + services = load_yaml_any(str(services_path), default_if_missing={}) + if not isinstance(services, Mapping): + continue + block = services.get(_SERVICE) + if not isinstance(block, Mapping) or "modes" in block: + continue + if is_suppressed_in_head(read_text(str(services_path)).splitlines(), _RULE): + continue + roles.append(services_path.parent.parent) + return roles + + +def _declares_credential(role: Path) -> bool: + secrets = load_yaml_any(str(role / ROLE_FILE_META_SECRETS), default_if_missing={}) + if not isinstance(secrets, Mapping): + return False + credentials = secrets.get("credentials") + return isinstance(credentials, Mapping) and _CREDENTIAL in credentials + + +def _includes_contract(role: Path) -> bool: + tasks_dir = str(role / "tasks") + os.sep + return any( + path.startswith(tasks_dir) and _CONTRACT in content + for path, content in iter_project_files_with_content(extensions=(".yml",)) + ) + + +class TestLitellmConsumerContract(unittest.TestCase): + def test_every_consumer_mints_its_own_virtual_key(self) -> None: + missing = [ + f"{role.name}: declares services.{_SERVICE} but no " + f"credentials.{_CREDENTIAL} in {ROLE_FILE_META_SECRETS}, so its AI " + f"surface would authenticate with a shared or empty key" + for role in _consumer_roles() + if not _declares_credential(role) + ] + self.assertEqual( + [], + missing, + f"LiteLLM consumer role(s) without their own virtual key " + f"({len(missing)}):\n" + "\n".join(f" - {m}" for m in missing), + ) + + def test_every_consumer_includes_the_gateway_contract(self) -> None: + missing = [ + f"{role.name}: declares services.{_SERVICE} but no task includes " + f"{_CONTRACT}, so neither the empty-key guard nor the " + f"stays-in-the-deployment guard runs for this role" + for role in _consumer_roles() + if not _includes_contract(role) + ] + self.assertEqual( + [], + missing, + f"LiteLLM consumer role(s) without the gateway contract " + f"({len(missing)}):\n" + "\n".join(f" - {m}" for m in missing), + ) + + def test_the_scan_finds_consumer_roles(self) -> None: + self.assertTrue( + _consumer_roles(), + "no role consumes services.litellm, so both rules would pass " + "vacuously; check that the scan still reads the right topic", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_adapter_bearer.py b/tests/lint/ansible/services/test_mcp_adapter_bearer.py new file mode 100644 index 0000000000..746a59a09e --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_adapter_bearer.py @@ -0,0 +1,118 @@ +"""Lint: an adapter sidecar is started with the bearer its role declares. + +Such a provider holds two unrelated credentials: the token the sidecar presents +upstream, read with ``lookup('mcp_credential', ...)``, and the bearer a client +must present to the sidecar, which ``mcp.credential`` declares under the role's +own ``credentials``. Starting the sidecar with anything else leaves a deployment +where the declared credential is the one every client is handed and the one the +endpoint answers 401 to. + +The rule ties two sites to one variable: the ``vars/main.yml`` definition that +reads the declared credential key, and the ``ADAPTER_BEARER`` the sidecar is +started with. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-adapter-bearer`` in the head of the role's ``meta/mcp.yml``. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +_RULE = "mcp-adapter-bearer" +_ADAPTER_ENV = "ADAPTER_BEARER" + + +def _adapter_roles() -> list[tuple[Path, str]]: + """Return the adapter-fronted roles and the credential key each declares.""" + roles: list[tuple[Path, str]] = [] + for mcp_path in sorted(Path(PROJECT_ROOT, "roles").glob(f"*/{ROLE_FILE_META_MCP}")): + mcp = load_yaml_any(str(mcp_path), default_if_missing={}) + if not isinstance(mcp, Mapping): + continue + if str(mcp.get("implementation") or "").strip() != "adapter": + continue + if is_suppressed_in_head(read_text(str(mcp_path)).splitlines(), _RULE): + continue + credential = mcp.get("credential") + credential = credential if isinstance(credential, Mapping) else {} + roles.append((mcp_path.parent.parent, str(credential.get("key") or "").strip())) + return roles + + +def _variables_reading(role: Path, credential_key: str) -> set[str]: + """Return the vars/main.yml names defined from that declared credential.""" + path = Path(role, "vars", "main.yml") + if not path.is_file(): + return set() + needle = f"credentials.{credential_key}" + return { + line.split(":", 1)[0].strip() + for line in read_text(str(path)).splitlines() + if needle in line and ":" in line and not line.startswith((" ", "#")) + } + + +def _starts_sidecar_with(role: Path, variables: set[str]) -> bool: + """Return whether a template starts the sidecar with one of those names.""" + return any( + variable in line + for template in sorted(role.glob("templates/**/*.j2")) + for line in read_text(str(template)).splitlines() + if _ADAPTER_ENV in line + for variable in variables + ) + + +class TestMcpAdapterBearer(unittest.TestCase): + def test_every_adapter_sidecar_serves_the_declared_bearer(self) -> None: + offenders: list[str] = [] + for role, credential_key in _adapter_roles(): + if not credential_key: + offenders.append( + f"{role.name}: fronts its MCP endpoint with an adapter but " + f"its mcp.credential names no key, so nothing states which " + f"secret a client presents" + ) + continue + variables = _variables_reading(role, credential_key) + if not variables: + offenders.append( + f"{role.name}: no vars/main.yml entry reads " + f"credentials.{credential_key}, the credential its mcp block " + f"declares" + ) + continue + if not _starts_sidecar_with(role, variables): + offenders.append( + f"{role.name}: starts its sidecar with an {_ADAPTER_ENV} that " + f"is none of {sorted(variables)}, so the endpoint answers a " + f"different bearer than the one it declares" + ) + self.assertEqual( + [], + offenders, + f"MCP adapter provider(s) serving the wrong credential " + f"({len(offenders)}):\n" + "\n".join(f" - {o}" for o in offenders), + ) + + def test_the_scan_finds_adapter_providers(self) -> None: + self.assertTrue( + _adapter_roles(), + "no MCP block declares an adapter implementation, so the rule would " + "pass vacuously; check that the scan still reads the right topic", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_adapter_endpoint_path.py b/tests/lint/ansible/services/test_mcp_adapter_endpoint_path.py new file mode 100644 index 0000000000..2a625b1fdf --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_adapter_endpoint_path.py @@ -0,0 +1,79 @@ +"""Lint: an adapter provider declares the path its adapter actually serves. + +The adapter answers exactly one path, and every provider that runs behind it +declares its own ``endpoint.path``. That is the same fact in two files. When they +drift, nothing fails at deploy time: the adapter starts, the client registers the +declared URL, and the mismatch only shows up as a 404 on the first tool call, +which reads like an upstream problem rather than a declaration error. + +The transport of ``web-app-flowise`` was this exact shape - a hard-coded constant +disagreeing with ``meta/mcp.yml`` - and cost three deploys before the runtime +settled it. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-adapter-endpoint-path`` in the head of the provider's ``meta/mcp.yml``. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +_RULE = "mcp-adapter-endpoint-path" +_ADAPTER_SERVER = PROJECT_ROOT / "roles/svc-ai-mcp-adapter/files/python/server.py" +_ENDPOINT_CONST = re.compile(r'^ENDPOINT\s*=\s*"([^"]+)"', re.MULTILINE) + + +def served_endpoint() -> str: + match = _ENDPOINT_CONST.search(read_text(str(_ADAPTER_SERVER))) + if not match: + raise AssertionError( + f"{_ADAPTER_SERVER.name} no longer defines ENDPOINT; this lint reads it " + f"to compare against every adapter provider's declared path" + ) + return match.group(1) + + +def drifting_providers() -> list[str]: + expected = served_endpoint() + findings: list[str] = [] + for meta in sorted(PROJECT_ROOT.glob(f"roles/*/{ROLE_FILE_META_MCP}")): + block = load_yaml_any(str(meta), default_if_missing={}) + if not isinstance(block, dict): + continue + if str(block.get("implementation") or "").strip() != "adapter": + continue + declared = str((block.get("endpoint") or {}).get("path") or "").strip() + if declared == expected: + continue + if is_suppressed_in_head(read_text(str(meta)).splitlines(), _RULE): + continue + findings.append( + f"{meta.parent.parent.name}: declares {declared!r} while the adapter " + f"serves {expected!r}" + ) + return findings + + +class TestMcpAdapterEndpointPath(unittest.TestCase): + def test_every_adapter_provider_declares_the_served_path(self) -> None: + findings = drifting_providers() + self.assertEqual( + [], + findings, + f"adapter providers whose declared path is not served ({len(findings)}); " + f"the mismatch surfaces as a 404 on the first tool call, not at deploy:\n" + + "\n".join(f" - {entry}" for entry in findings), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_adapter_modules_staged.py b/tests/lint/ansible/services/test_mcp_adapter_modules_staged.py new file mode 100644 index 0000000000..66e8e0a631 --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_adapter_modules_staged.py @@ -0,0 +1,105 @@ +"""Lint: every module the adapter imports actually reaches the container. + +``server.py`` imports its siblings by bare name, which resolves at runtime +against the directory the image was built from. A module that exists in the +repository but is missing from the image's ``COPY`` line, or from the task that +stages the build context, is not a broken import here: it is a +``ModuleNotFoundError`` at container start, on every adapter-backed surface at +once, and nothing in the repository looks at the two lists. + +The import set is read from the source rather than listed, so a new sibling is +covered the moment it is imported. +""" + +from __future__ import annotations + +import ast +import re +import unittest +from pathlib import Path + +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +_ADAPTER = PROJECT_ROOT / "roles" / "svc-ai-mcp-adapter" +_PYTHON_DIR = _ADAPTER / "files" / "python" +_ENTRYPOINT = _PYTHON_DIR / "server.py" +_DOCKERFILE = _ADAPTER / "files" / "Dockerfile" +_INSTANCE = _ADAPTER / "tasks" / "instance.yml" + +_COPY = re.compile(r"^COPY\s+(?P.+?)\s+/opt/adapter/", re.MULTILINE) + + +def imported_siblings() -> list[str]: + """Return the sibling module file names ``server.py`` imports by bare name. + + A bare ``import x`` that matches ``files/python/x.py`` is a sibling; an + import of a standard-library or third-party name is not. + """ + tree = ast.parse(read_text(str(_ENTRYPOINT))) + found = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module: + names = [node.module] + else: + continue + for name in names: + head = name.split(".")[0] + if (_PYTHON_DIR / f"{head}.py").is_file(): + found.add(f"{head}.py") + return sorted(found) + + +def copied_modules() -> set[str]: + """Return the file names the image's COPY line places in the adapter dir.""" + match = _COPY.search(read_text(str(_DOCKERFILE))) + return set(match["files"].split()) if match else set() + + +def staged_modules() -> set[str]: + """Return the file names the instance task stages into the build context.""" + text = read_text(str(_INSTANCE)) + return {Path(p).name for p in re.findall(r"files/python/([\w./-]+\.py)", text)} + + +class TestMcpAdapterModulesStaged(unittest.TestCase): + def test_every_imported_sibling_is_copied_into_the_image(self) -> None: + missing = sorted(set(imported_siblings()) - copied_modules()) + self.assertEqual( + [], + missing, + f"module(s) imported by the adapter but absent from the image " + f"COPY line {sorted(copied_modules())}: {missing}", + ) + + def test_every_imported_sibling_is_staged_into_the_build_context(self) -> None: + missing = sorted(set(imported_siblings()) - staged_modules()) + self.assertEqual( + [], + missing, + f"module(s) imported by the adapter but never staged by the " + f"instance task {sorted(staged_modules())}: {missing}", + ) + + def test_nothing_is_copied_that_the_entrypoint_never_imports(self) -> None: + entrypoint = _ENTRYPOINT.name + stray = sorted(copied_modules() - set(imported_siblings()) - {entrypoint}) + self.assertEqual( + [], + stray, + f"module(s) copied into the image that nothing imports: {stray}", + ) + + def test_the_scan_finds_imported_siblings(self) -> None: + self.assertTrue( + imported_siblings(), + "the adapter entrypoint imports no sibling module, so every rule " + "here would pass vacuously; check that the parse still reaches it", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_client_entrypoint.py b/tests/lint/ansible/services/test_mcp_client_entrypoint.py new file mode 100644 index 0000000000..cded1ca212 --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_client_entrypoint.py @@ -0,0 +1,69 @@ +"""Lint: every MCP client role carries the entrypoint the reconciler includes. + +``sys-svc-mcp-reconcile`` iterates the client roles the discovery lookup returns +and includes ``tasks/utils/mcp.yml`` from each. The file name is the contract: a +role that declares a client direction without it aborts every deployment that +happens to include the role, long after the change that broke it. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-client-entrypoint`` in the head of the role's ``meta/mcp.yml``. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_MCP, ROLE_FILE_TASKS_MCP + +from . import PROJECT_ROOT + +_RULE = "mcp-client-entrypoint" +_CLIENT_DIRECTIONS = frozenset({"client", "both"}) + + +def _client_roles() -> list[Path]: + """Return the role directories whose MCP block declares a client side.""" + roles: list[Path] = [] + for mcp_path in sorted(Path(PROJECT_ROOT, "roles").glob(f"*/{ROLE_FILE_META_MCP}")): + mcp = load_yaml_any(str(mcp_path), default_if_missing={}) + if not isinstance(mcp, Mapping): + continue + if str(mcp.get("direction") or "").strip().lower() not in _CLIENT_DIRECTIONS: + continue + if is_suppressed_in_head(read_text(str(mcp_path)).splitlines(), _RULE): + continue + roles.append(mcp_path.parent.parent) + return roles + + +class TestMcpClientEntrypoint(unittest.TestCase): + def test_every_client_role_has_the_reconciler_entrypoint(self) -> None: + missing = [ + f"{role.name}: declares an MCP client direction but has no " + f"{ROLE_FILE_TASKS_MCP}, so the reconciler's include fails at runtime" + for role in _client_roles() + if not (role / ROLE_FILE_TASKS_MCP).is_file() + ] + self.assertEqual( + [], + missing, + f"MCP client role(s) without the reconciler entrypoint ({len(missing)}):\n" + + "\n".join(f" - {m}" for m in missing), + ) + + def test_the_scan_finds_client_roles(self) -> None: + self.assertTrue( + _client_roles(), + "no role declares an MCP client direction, so the rule would pass " + "vacuously; check that the scan still reads the right topic", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_client_gate_scoped.py b/tests/lint/ansible/services/test_mcp_client_gate_scoped.py new file mode 100644 index 0000000000..0ee26f4125 --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_client_gate_scoped.py @@ -0,0 +1,123 @@ +"""Lint: signing in to an MCP client does not by itself grant its MCP surface. + +An MCP client holds credentials the deployment issued, not the caller's own, so +whoever reaches its UI reaches every provider that client is registered with, +under an identity that is not theirs. None of these upstreams offers a tested +per-server user authorization boundary, so the boundary has to be the gate in +front of them: the connection is restricted to an administrator and to the +application's own ``mcp`` group, never offered to every account that happens to +have a login. + +An oauth2 gate with no ``allowed_groups`` admits every authenticated user in the +realm, which is exactly the failure this rule exists for โ€” ``web-app-n8n`` +shipped that way while declaring an ``mcp`` role nothing consulted. + +Two relations per client role whose gate is an oauth2 proxy: + +* the gate names ``allowed_groups`` at all; +* every group it names is scoped to that role's own ``application_id``, so a + group belonging to another application cannot open this one. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-client-gate-scoped`` in the head of the role's + ``meta/mcp.yml``, together with the per-server boundary that replaces it. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_MCP, ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +_RULE = "mcp-client-gate-scoped" +_CLIENT_DIRECTIONS = frozenset({"client", "both"}) + + +def _gated_client_roles() -> dict[str, Mapping]: + """Return ``{role: sso block}`` for MCP clients standing behind an oauth2 gate.""" + roles: dict[str, Mapping] = {} + for mcp_path in sorted(Path(PROJECT_ROOT, "roles").glob(f"*/{ROLE_FILE_META_MCP}")): + mcp = load_yaml_any(str(mcp_path), default_if_missing={}) + if not isinstance(mcp, Mapping): + continue + if str(mcp.get("direction") or "").strip().lower() not in _CLIENT_DIRECTIONS: + continue + if is_suppressed_in_head(read_text(str(mcp_path)).splitlines(), _RULE): + continue + role_dir = mcp_path.parent.parent + services = load_yaml_any( + str(role_dir / ROLE_FILE_META_SERVICES), default_if_missing={} + ) + sso = (services or {}).get("sso") + if not isinstance(sso, Mapping): + continue + if str(sso.get("flavor") or "").strip() != "oauth2": + continue + roles[role_dir.name] = sso + return roles + + +def _allowed_groups(sso: Mapping) -> list[str]: + oauth2 = sso.get("oauth2") + if not isinstance(oauth2, Mapping): + return [] + groups = oauth2.get("allowed_groups") + return [str(g) for g in groups] if isinstance(groups, list) else [] + + +class TestMcpClientGateScoped(unittest.TestCase): + def test_every_gated_client_restricts_its_groups(self) -> None: + open_gates = [ + f"{role}: its oauth2 gate names no allowed_groups, so every " + f"authenticated account in the realm reaches an MCP client that " + f"acts with the deployment's provider credentials" + for role, sso in sorted(_gated_client_roles().items()) + if not _allowed_groups(sso) + ] + self.assertEqual( + [], + open_gates, + f"MCP client(s) behind an unrestricted gate ({len(open_gates)}):\n" + + "\n".join(f" - {g}" for g in open_gates), + ) + + def test_every_allowed_group_is_application_scoped(self) -> None: + foreign = [] + for role, sso in sorted(_gated_client_roles().items()): + for group in _allowed_groups(sso): + if ( + f"application_id='{role}'" in group + or f'application_id="{role}"' in group + ): + continue + foreign.append( + f"{role}: allows '{group}', which is not scoped to this " + f"role's own application_id, so another application's " + f"membership opens this client" + ) + self.assertEqual( + [], + foreign, + "MCP client(s) allowing a foreign group:\n" + + "\n".join(f" - {f}" for f in foreign), + ) + + def test_the_scan_finds_gated_clients(self) -> None: + self.assertTrue( + _gated_client_roles(), + "no MCP client role sits behind an oauth2 gate, so both rules " + "would pass vacuously; check that the scan still reads the right " + "topic", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_consumer_services_entry.py b/tests/lint/ansible/services/test_mcp_consumer_services_entry.py new file mode 100644 index 0000000000..56236909b0 --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_consumer_services_entry.py @@ -0,0 +1,140 @@ +"""Lint: an MCP provider carries a services entry for every declared client. + +A client declares itself once, in its own ``meta/services.yml`` self-entry, +as ``mcp_consumer: true``. Every server-capable ``meta/mcp.yml`` MUST then +carry a matching ``services.`` entry whose ``enabled`` and +``shared`` resolve through the ``"{{ '' in group_names }}"`` form. + +Two things depend on that entry. The inventory resolver builds a round's +co-deploy closure from services edges alone, so without it a provider is +never planned together with a client and its MCP surface is never exercised +end to end. The network layer admits a client to the provider's overlay +through the same entry. + +Admission itself is NOT what the entry decides: a provider that must refuse +a client adds ``mcp_consumer: false`` to that entry. Keeping the entry and +spelling the refusal out is what makes a deliberate exclusion +distinguishable from a forgotten one. + +A refused entry inverts the required shape: ``enabled`` and ``shared`` MUST +be literally ``false`` there. The gate exists to plan provider and client +into one round, so leaving it dynamic schedules a client the provider +refuses, costs the round its memory, and states an integration that can +never form. + +Add ``# nocheck: mcp-consumer-services-entry`` to the head of the provider's +``meta/mcp.yml`` for one that legitimately owns no such edge. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.applications.mcp import ( + MCP_CONSUMER_FLAG, + declares_mcp_consumer, +) +from utils.roles.entity.name import get_entity_name +from utils.roles.mapping import ROLE_FILE_META_MCP, ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +_RULE = "mcp-consumer-services-entry" +_SERVER_DIRECTIONS = frozenset({"server", "both"}) + + +def _services_by_role() -> dict[str, Mapping]: + services = {} + for path in sorted((PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_SERVICES}")): + loaded = load_yaml_any(str(path), default_if_missing={}) + if isinstance(loaded, Mapping): + services[path.parent.parent.name] = loaded + return services + + +def _gates_on(value: object, role_id: str) -> bool: + return isinstance(value, str) and f"'{role_id}' in group_names" in value + + +def missing_entries() -> list[str]: + """Return one finding per provider missing a declared client's entry.""" + services_by_role = _services_by_role() + consumers = [ + role_id + for role_id, services in services_by_role.items() + if declares_mcp_consumer(role_id, services) + ] + + findings: list[str] = [] + for meta in sorted((PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_MCP}")): + role = meta.parent.parent.name + block = load_yaml_any(str(meta), default_if_missing={}) + if not isinstance(block, Mapping): + continue + if str(block.get("direction") or "").strip().lower() not in _SERVER_DIRECTIONS: + continue + if is_suppressed_in_head(read_text(str(meta)).splitlines(), _RULE): + continue + + services = services_by_role.get(role) or {} + for consumer in consumers: + if consumer == role: + continue + key = get_entity_name(consumer) + entry = services.get(key) + if not isinstance(entry, Mapping): + findings.append( + f"{role}: no 'services.{key}' entry for the declared MCP " + f"client {consumer!r}; add one gated on " + f"\"{{{{ '{consumer}' in group_names }}}}\", with " + f"'{MCP_CONSUMER_FLAG}: false' if it must not be admitted" + ) + continue + if entry.get(MCP_CONSUMER_FLAG) is False: + findings.extend( + f"{role}: services.{key}.{flag} must be false; the entry " + f"refuses {consumer!r}, so a group_names gate would plan " + f"a pairing that can never form" + for flag in ("enabled", "shared") + if entry.get(flag) is not False + ) + continue + findings.extend( + f"{role}: services.{key}.{flag} must gate on " + f"\"{{{{ '{consumer}' in group_names }}}}\" so the " + f"round plans provider and client together" + for flag in ("enabled", "shared") + if not _gates_on(entry.get(flag), consumer) + ) + return findings + + +class TestMcpConsumerServicesEntry(unittest.TestCase): + def test_every_provider_declares_every_client(self) -> None: + findings = missing_entries() + self.assertEqual( + [], + findings, + f"MCP provider(s) missing a client services entry ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + def test_the_scan_finds_declared_clients(self) -> None: + services_by_role = _services_by_role() + declared = [ + role_id + for role_id, services in services_by_role.items() + if declares_mcp_consumer(role_id, services) + ] + self.assertTrue( + declared, + "no role declares mcp_consumer, so the rule would pass vacuously", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_consumer_speaks_transport.py b/tests/lint/ansible/services/test_mcp_consumer_speaks_transport.py new file mode 100644 index 0000000000..b5ac445da2 --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_consumer_speaks_transport.py @@ -0,0 +1,111 @@ +"""Lint: a provider only admits consumers that can speak its transport. + +Admission and ``supported_transports`` are declared in different +files by different people, and nothing made them agree. Admitting a client that +cannot speak the provider's transport is not a narrowing decision: discovery +classifies it ``transport_unsupported``, which is fatal, so the pair aborts +every deployment that happens to contain both roles. + +Flowise at its pinned release is the case this was written for. It reaches an +MCP server over Streamable HTTP only; pointed at an SSE endpoint the toolkit +falls back and the SDK rejects the response body with ``expected a web +ReadableStream``. Admitting it to an SSE provider therefore cannot work, and the +declaration is where that has to be caught. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-consumer-transport`` in the head of the provider's ``meta/mcp.yml``. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.applications.mcp import ( + DEFAULT_MCP_TRANSPORT, + derive_allowed_consumers, +) +from utils.roles.mapping import ROLE_FILE_META_MCP, ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +_RULE = "mcp-consumer-transport" +_SERVER_DIRECTIONS = frozenset({"server", "both"}) + + +def _blocks() -> dict[str, Mapping]: + """Return every role's MCP block, keyed by role name.""" + blocks = {} + for path in sorted(Path(PROJECT_ROOT, "roles").glob(f"*/{ROLE_FILE_META_MCP}")): + block = load_yaml_any(str(path), default_if_missing={}) + if isinstance(block, Mapping): + blocks[path.parent.parent.name] = block + return blocks + + +def _services_by_role() -> dict[str, object]: + """Return every role's services mapping, keyed by role name.""" + return { + path.parent.parent.name: load_yaml_any(str(path), default_if_missing={}) + for path in sorted( + Path(PROJECT_ROOT, "roles").glob(f"*/{ROLE_FILE_META_SERVICES}") + ) + } + + +def mismatched_pairs() -> list[str]: + """Return one finding per provider admitting a transport-incompatible client.""" + blocks = _blocks() + services_by_role = _services_by_role() + findings = [] + for role, block in blocks.items(): + if str(block.get("direction") or "").strip().lower() not in _SERVER_DIRECTIONS: + continue + path = Path(PROJECT_ROOT, "roles", role, ROLE_FILE_META_MCP) + if is_suppressed_in_head(read_text(str(path)).splitlines(), _RULE): + continue + + transport = str(block.get("transport") or DEFAULT_MCP_TRANSPORT) + for consumer in derive_allowed_consumers(role, services_by_role): + spoken = (blocks.get(str(consumer)) or {}).get("supported_transports") + if not spoken: + continue + if transport in {str(entry) for entry in spoken}: + continue + findings.append( + f"{role}: admits {consumer!r}, but serves {transport!r} while " + f"that client speaks {sorted(str(e) for e in spoken)}" + ) + return findings + + +class TestMcpConsumerSpeaksTransport(unittest.TestCase): + def test_every_admitted_consumer_speaks_the_provider_transport(self) -> None: + findings = mismatched_pairs() + self.assertEqual( + [], + findings, + f"MCP pair(s) that cannot connect ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + def test_the_scan_finds_admitted_consumers(self) -> None: + services_by_role = _services_by_role() + admitted = [ + role + for role in _blocks() + if derive_allowed_consumers(role, services_by_role) + ] + self.assertTrue( + admitted, + "no provider admits a consumer, so the rule would pass vacuously", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_consumer_variant.py b/tests/lint/ansible/services/test_mcp_consumer_variant.py new file mode 100644 index 0000000000..8853ec96f3 --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_consumer_variant.py @@ -0,0 +1,205 @@ +"""Lint: an MCP provider ships a round that proves the pairing. + +A surface nobody deploys against is never exercised, so every role with a +``meta/mcp.yml`` that admits at least one consumer needs one variant pinning +every admitted consumer to ``enabled: true``. + +That round also has to be able to sign in. An MCP client spec signs in through +the client's own OIDC button, which redirects to Keycloak, so a round without +an identity provider skips the lot and proves nothing it was built to prove. +The provider +therefore keeps ``sso`` on in that variant, and so does each consumer in the +variant the round actually pulls in: a round deploys every dependency at its +own index, falling back to variant 0 when it has fewer, so the client that +ships alongside is that one and not the client's variant 0. + +A role that declares no ``sso`` service, or pins it to a literal ``false`` +because upstream speaks no OIDC, is exempt from the flag it cannot have. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-consumer-variant`` in the head of the role's + ``meta/mcp.yml``. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.applications import get_application_defaults, get_variants +from utils.cache.files import read_text +from utils.roles.applications.mcp import derive_allowed_consumers +from utils.roles.entity.name import get_entity_name +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +_RULE = "mcp-consumer-variant" +_SERVER_DIRECTIONS = frozenset({"server", "both"}) + +ROLES_DIR = PROJECT_ROOT / "roles" + + +def _declares_sso(services: Mapping | None) -> bool: + """Whether a role can put an identity provider in front of itself. + + A literal ``enabled: false`` is the shape a role uses when upstream + speaks no OIDC at all, so there is nothing for a variant to pin on. + """ + if not isinstance(services, Mapping): + return False + entry = services.get("sso") + return isinstance(entry, Mapping) and entry.get("enabled") is not False + + +def _sso_flag(variant: Mapping | None) -> object: + """Return a variant's ``services.sso.enabled`` pin, or None when unpinned.""" + services = (variant or {}).get("services") + if not isinstance(services, Mapping): + return None + entry = services.get("sso") + return entry.get("enabled") if isinstance(entry, Mapping) else None + + +def _round_variant(variants: list, index: int) -> Mapping | None: + """Return the entry a round at ``index`` deploys a role at. + + Args: + variants: that role's ``meta/variants.yml`` entries. + index: the round index the provider's variant sits at. + + A round pins every dependency to its own index and falls back to variant 0 + when the dependency has fewer, which is what + :mod:`cli.administration.deploy.development.inventory` plans. + """ + if not variants: + return None + entry = variants[index] if index < len(variants) else variants[0] + return entry if isinstance(entry, Mapping) else None + + +def _variant_findings( + role: str, + consumers: set[str], + variant: Mapping, + index: int, + services_by_role: Mapping, + variants_by_role: Mapping, + consumer_ids: Mapping, +) -> list[str]: + """Return why one variant does not prove the role's MCP pairing. + + Args: + role: the provider role id. + consumers: entity keys of every admitted consumer. + variant: one ``meta/variants.yml`` entry. + index: that entry's position, which is the round index. + services_by_role: every role's services mapping. + variants_by_role: every role's variant list. + consumer_ids: entity key to consumer role id. + """ + services = variant.get("services") + if not isinstance(services, Mapping): + return [f"{role}: variant declares no services"] + findings: list[str] = [] + for key in sorted(consumers): + entry = services.get(key) + if not isinstance(entry, Mapping) or entry.get("enabled") is not True: + findings.append(f"{role}: {key} is not enabled") + if findings: + return findings + + if _declares_sso(services_by_role.get(role)) and _sso_flag(variant) is not True: + findings.append(f"{role}: variant {index} does not pin sso on") + for key in sorted(consumers): + consumer = consumer_ids.get(key) + if not consumer or not _declares_sso(services_by_role.get(consumer)): + continue + pulled = _round_variant(variants_by_role.get(consumer) or [], index) + if _sso_flag(pulled) is False: + findings.append( + f"{role}: {key} ships with sso off in the variant round " + f"{index} pulls in, so its MCP specs skip" + ) + return findings + + +def offenders() -> list[str]: + """Return one finding per provider that never deploys its consumers.""" + defaults = get_application_defaults(roles_dir=ROLES_DIR) + services_by_role = { + role: (config or {}).get("services") + for role, config in defaults.items() + if isinstance(config, dict) + } + variants = get_variants(roles_dir=ROLES_DIR) + findings: list[str] = [] + for meta in sorted(ROLES_DIR.glob(f"*/{ROLE_FILE_META_MCP}")): + role = meta.parent.parent.name + block = (defaults.get(role) or {}).get("mcp") + if not isinstance(block, Mapping): + continue + if str(block.get("direction") or "").strip().lower() not in _SERVER_DIRECTIONS: + continue + if is_suppressed_in_head(read_text(str(meta)).splitlines(), _RULE): + continue + consumer_ids = { + get_entity_name(c): c + for c in derive_allowed_consumers(role, services_by_role) + } + consumers = set(consumer_ids) + if not consumers: + continue + per_variant = [ + _variant_findings( + role, consumers, v, index, services_by_role, variants, consumer_ids + ) + for index, v in enumerate(variants.get(role, [])) + if isinstance(v, Mapping) + ] + if any(not f for f in per_variant): + continue + closest = ( + min( + per_variant, + key=lambda f: (sum("is not enabled" in x for x in f), len(f)), + ) + if per_variant + else [f"{role}: no variants"] + ) + findings.append( + f"{role}: no variant enables every admitted consumer; the closest " + f"one still reports: {'; '.join(closest)}" + ) + return findings + + +class TestMcpConsumerVariant(unittest.TestCase): + def test_every_provider_ships_a_variant_enabling_its_consumers(self) -> None: + findings = offenders() + self.assertEqual( + [], + findings, + f"MCP provider(s) whose consumers never deploy ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + def test_the_scan_finds_providers(self) -> None: + defaults = get_application_defaults(roles_dir=ROLES_DIR) + seen = sum( + 1 + for meta in ROLES_DIR.glob(f"*/{ROLE_FILE_META_MCP}") + if isinstance( + (defaults.get(meta.parent.parent.name) or {}).get("mcp"), Mapping + ) + ) + self.assertTrue( + seen, + "no role ships meta/mcp.yml, so the rule would pass vacuously", + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_contract_digest.py b/tests/lint/ansible/services/test_mcp_contract_digest.py new file mode 100644 index 0000000000..363cb797e4 --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_contract_digest.py @@ -0,0 +1,131 @@ +"""The digests ``meta/mcp.yml`` pins match the contract files they pin. + +Two fields pin the same artefact from different angles. ``tools.schema_sha256`` +hashes the parsed tool mapping the role loads into the adapter contract; the +adapter rehashes it at startup and refuses to serve on a mismatch, so a stale +pin becomes a container that never turns healthy, an hour into a deploy, +reported as a failing probe rather than as the metadata edit it is. +``adapter.specification_sha256`` hashes the checked-in specification file +byte-for-byte and is enforced nowhere at runtime, which is precisely why it +needs a check here: a pin nothing recomputes is indistinguishable from a pin +somebody typed. + +The tool digest is computed with the adapter's own ``policy.schema_digest`` +rather than a reimplementation, so the check cannot drift from the code that +enforces it in production. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-contract-digest`` on, or directly above, the pinning line. +""" + +from __future__ import annotations + +import hashlib +import importlib.util +import json +import sys +import unittest +from typing import TYPE_CHECKING + +from utils.annotations.suppress import is_suppressed_for_key +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from pathlib import Path + +_RULE = "mcp-contract-digest" +_ADAPTER_FILES = PROJECT_ROOT / "roles/svc-ai-mcp-adapter/files/python" +_CONTRACT_RELATIVE = "files/mcp/tools.json" + + +def _schema_digest(tools: dict) -> str: + """Return the digest the adapter itself would compute for *tools*.""" + spec = importlib.util.spec_from_file_location( + "adapter_policy", _ADAPTER_FILES / "policy.py" + ) + module = importlib.util.module_from_spec(spec) + sys.path.insert(0, str(_ADAPTER_FILES)) + try: + spec.loader.exec_module(module) + finally: + sys.path.remove(str(_ADAPTER_FILES)) + return module.schema_digest(tools) + + +def _file_digest(path: Path) -> str: + """Return the byte-exact sha256 of *path*, prefixed like the pin.""" + raw = path.read_bytes() # nocheck: cache-read no newline translation + return "sha256:" + hashlib.sha256(raw).hexdigest() + + +class TestMcpContractDigest(unittest.TestCase): + def test_every_pinned_digest_matches_its_contract(self) -> None: + roles_root = PROJECT_ROOT / "roles" + if not roles_root.is_dir(): + self.skipTest("no roles/ directory") + + offenders: list[str] = [] + checked = 0 + for mcp_path in sorted(roles_root.glob(f"*/{ROLE_FILE_META_MCP}")): + mcp = load_yaml_any(str(mcp_path), default_if_missing={}) or {} + role_dir = mcp_path.parent.parent + lines = read_text(str(mcp_path)).splitlines() + + pinned = str((mcp.get("tools") or {}).get("schema_sha256") or "") + if pinned and not is_suppressed_for_key(lines, "schema_sha256", _RULE): + contract_path = role_dir / _CONTRACT_RELATIVE + if not contract_path.is_file(): + offenders.append( + f"{role_dir.name}: pins tools.schema_sha256 but ships no " + f"{_CONTRACT_RELATIVE}" + ) + else: + found = _schema_digest(json.loads(read_text(str(contract_path)))) + checked += 1 + if found != pinned: + offenders.append( + f"{role_dir.name}: tools.schema_sha256 pins {pinned} " + f"but {_CONTRACT_RELATIVE} hashes to {found}; renew " + f"the pin" + ) + + adapter = mcp.get("adapter") or {} + spec_pin = str(adapter.get("specification_sha256") or "") + spec_path = str(adapter.get("specification_path") or "") + if ( + spec_pin + and spec_path + and not is_suppressed_for_key(lines, "specification_sha256", _RULE) + ): + specification = PROJECT_ROOT / spec_path + if not specification.is_file(): + offenders.append( + f"{role_dir.name}: adapter.specification_path {spec_path!r} " + f"does not exist" + ) + else: + found = _file_digest(specification) + checked += 1 + if found != spec_pin: + offenders.append( + f"{role_dir.name}: adapter.specification_sha256 pins " + f"{spec_pin} but {spec_path} hashes to {found}; renew " + f"the pin" + ) + + self.assertEqual( + [], + offenders, + f"contract digest drift ({len(offenders)}):\n" + + "\n".join(f" - {o}" for o in offenders), + ) + self.assertTrue( + checked, + "no role pins a contract digest, so the rule would pass vacuously; " + "check that the scan still reads the right topic", + ) diff --git a/tests/lint/ansible/services/test_mcp_mutating_tools_named.py b/tests/lint/ansible/services/test_mcp_mutating_tools_named.py new file mode 100644 index 0000000000..fd6a8097fa --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_mutating_tools_named.py @@ -0,0 +1,196 @@ +"""A surface that serves mutating tools has to name them. + +``mutating_tools_enabled: false`` is a claim, not a mechanism. Where the +upstream cannot scope the credential it issues, nothing refuses the call, and +the only remaining boundary is the include list every client renders. That list +is built by subtracting ``tools.mutating`` from ``tools.allowlist``, so a +mutating tool that is served but not named is offered to every client while the +declaration says mutations are off. + +Switching mutations on carries its own obligation. No surface does today, so a +test of the mutating path would assert against nothing and pass forever. What +survives that emptiness is a guard: a surface that permits mutations must name, +per required proof, the artifact that provides it, and the artifact must exist. +That converts an unverifiable promise into a reviewable declaration, and it +costs nothing until somebody flips the flag. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-mutating-tools-named`` in the head of the role's + ``meta/mcp.yml``. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +_RULE = "mcp-mutating-tools-named" +_SERVING = {"server", "both"} +_PROOFS = ( + "confirmation", + "authorization", + "idempotency", + "audit", + "reversal", +) +_PRESENT_FILE = "README.md" + + +def missing_proofs(role: str, block: Mapping) -> list[str]: + """Return what a mutation-permitting surface still owes, or an empty list. + + Args: + role: the role the surface belongs to, for the message. + block: its ``meta/mcp.yml`` mapping. + + A surface that keeps mutations off owes nothing here, which is every + surface today, so the rule is exercised against a synthetic one rather + than trusted to be right the first time somebody needs it. + """ + tools = block.get("tools") + if not isinstance(tools, Mapping) or not tools.get("mutating_tools_enabled"): + return [] + + proofs = block.get("mutating_proofs") + if not isinstance(proofs, Mapping): + return [ + ( + f"{role}: permits mutations without an mcp.mutating_proofs " + f"block naming {list(_PROOFS)}" + ) + ] + + missing = [] + for proof in _PROOFS: + artifact = str(proofs.get(proof) or "").strip() + if not artifact: + missing.append(f"{role}: names no artifact for {proof!r}") + elif not (PROJECT_ROOT / artifact).is_file(): + missing.append( + f"{role}: names {artifact!r} for {proof!r}, which is not a file" + ) + return missing + + +def _surfaces() -> list[tuple[str, Mapping]]: + """Return ``(role, mcp block)`` for every role declaring an MCP surface.""" + found = [] + for path in sorted((PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_MCP}")): + if is_suppressed_in_head(read_text(str(path)).splitlines(), _RULE): + continue + block = load_yaml_any(str(path), default_if_missing={}) + if isinstance(block, Mapping): + found.append((path.parent.parent.name, block)) + return found + + +class TestMcpMutatingToolsNamed(unittest.TestCase): + def test_named_mutating_tools_are_part_of_the_allowlist(self) -> None: + stray = [] + for role, block in _surfaces(): + tools = block.get("tools") + if not isinstance(tools, Mapping): + continue + allowlist = set(tools.get("allowlist") or []) + outside = sorted(set(tools.get("mutating") or []) - allowlist) + if outside: + stray.append( + f"{role}: names {outside} as mutating, but the allowlist " + f"does not serve them, so the subtraction removes nothing " + f"and the name is stale" + ) + self.assertEqual( + [], + stray, + "mutating name(s) outside the served set:\n" + + "\n".join(f" - {s}" for s in stray), + ) + + def test_a_surface_that_permits_mutations_names_none(self) -> None: + contradictory = [] + for role, block in _surfaces(): + tools = block.get("tools") + if not isinstance(tools, Mapping): + continue + if tools.get("mutating_tools_enabled") and tools.get("mutating"): + contradictory.append( + f"{role}: permits mutations yet still names {sorted(tools['mutating'])} " + f"as withheld; a reader cannot tell which half is meant" + ) + self.assertEqual( + [], + contradictory, + "surface(s) both permitting and withholding mutation:\n" + + "\n".join(f" - {c}" for c in contradictory), + ) + + def test_a_mutating_surface_names_an_artifact_per_required_proof(self) -> None: + unproven = [] + for role, block in _surfaces(): + unproven.extend(missing_proofs(role, block)) + self.assertEqual( + [], + unproven, + "mutating surface(s) without a named proof:\n" + + "\n".join(f" - {u}" for u in unproven), + ) + + def test_the_proof_rule_fires_on_a_surface_that_permits_mutations(self) -> None: + bare = {"tools": {"mutating_tools_enabled": True}} + self.assertEqual( + 1, + len(missing_proofs("web-app-example", bare)), + "no surface permits mutations today, so this rule would pass " + "forever unless it is exercised against one that does", + ) + + def test_the_proof_rule_rejects_an_artifact_that_is_not_there(self) -> None: + named = { + "tools": {"mutating_tools_enabled": True}, + "mutating_proofs": dict.fromkeys(_PROOFS, "tests/nowhere.py"), + } + findings = missing_proofs("web-app-example", named) + self.assertEqual(len(_PROOFS), len(findings)) + self.assertTrue(all("is not a file" in f for f in findings)) + + def test_the_proof_rule_accepts_a_fully_proven_surface(self) -> None: + proven = { + "tools": {"mutating_tools_enabled": True}, + "mutating_proofs": dict.fromkeys(_PROOFS, _PRESENT_FILE), + } + self.assertEqual([], missing_proofs("web-app-example", proven)) + + def test_a_read_only_surface_carries_no_mutating_proofs(self) -> None: + premature = [ + f"{role}: declares mutating_proofs while mutations are off, so the " + f"artifacts it names are never the thing under test" + for role, block in _surfaces() + if block.get("mutating_proofs") + and not (block.get("tools") or {}).get("mutating_tools_enabled") + ] + self.assertEqual( + [], + premature, + "read-only surface(s) carrying mutation proofs:\n" + + "\n".join(f" - {p}" for p in premature), + ) + + def test_the_scan_finds_surfaces(self) -> None: + self.assertTrue( + [role for role, block in _surfaces() if block.get("direction") in _SERVING], + "no serving MCP surface was read, so every rule here would pass " + "vacuously; check that the scan still reaches the roles' MCP " + "declarations", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_no_administrator_token.py b/tests/lint/ansible/services/test_mcp_no_administrator_token.py new file mode 100644 index 0000000000..2e622088d0 --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_no_administrator_token.py @@ -0,0 +1,85 @@ +"""Lint: MCP task code reads the declared credential owner, never the administrator. + +``meta/mcp.yml`` names the principal a provider's secret belongs to, and +``credential.owner`` must not be ``administrator``: a provider that borrows the +deployment administrator's token hands every client that account's rights, and +revoking one provider then disarms all of them. + +The declaration alone does not enforce that. Six providers used to write their +token to the store under the declared owner and read it back from +``users.administrator.tokens``, which the store does not carry. The read never +matched, so the "do I already have one?" check was dead and every deploy minted +a fresh credential. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-no-administrator-token`` on, or directly above, the line. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content + +_RULE = "mcp-no-administrator-token" + +_ADMIN_TOKEN_RE = re.compile( + r"""lookup\(\s*['"]users['"]\s*,\s*['"]administrator['"]\s*\)\s* + (?:\.tokens|\[\s*['"]tokens['"]\s*\])""", + re.VERBOSE, +) + + +def _mcp_task_files() -> list[tuple[str, str]]: + """Return ``(path, content)`` for every MCP task file under ``roles/``.""" + files = [] + for path, content in iter_project_files_with_content(extensions=(".yml",)): + parts = Path(path).parts + if "roles" not in parts or "tasks" not in parts: + continue + if "mcp" not in Path(path).stem and "mcp" not in parts: + continue + files.append((path, content)) + return files + + +def administrator_token_reads() -> list[str]: + """Return one finding per MCP task line reading the administrator's tokens.""" + findings = [] + for path, content in _mcp_task_files(): + lines = content.splitlines() + for number, line in enumerate(lines, start=1): + if not _ADMIN_TOKEN_RE.search(line): + continue + if is_suppressed_at(lines, number, _RULE): + continue + findings.append( + f"{path}:{number}: reads users.administrator.tokens; MCP task " + f"code must resolve mcp.credential.owner instead" + ) + return findings + + +class TestMcpNoAdministratorToken(unittest.TestCase): + def test_no_mcp_task_borrows_the_administrator_token(self) -> None: + findings = administrator_token_reads() + self.assertEqual( + [], + findings, + f"MCP task code borrowing the administrator token ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + def test_the_scan_reaches_the_mcp_task_files(self) -> None: + self.assertTrue( + _mcp_task_files(), + "no MCP task file was scanned, so the rule would pass vacuously", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_playwright_coverage.py b/tests/lint/ansible/services/test_mcp_playwright_coverage.py new file mode 100644 index 0000000000..98739c2cb9 --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_playwright_coverage.py @@ -0,0 +1,176 @@ +"""Lint: an enabled MCP surface is covered by a Playwright spec of its own. + +The deploy-time provider probe proves the endpoint answers *its* credential. It +says nothing about what the endpoint answers a stranger, because it never asks +without one. That question belongs to a browser-side spec, and a role that +turns its MCP surface on without one ships an endpoint nobody ever asked the +hostile question of. + +Two relations per role whose ``meta/mcp.yml`` is enabled: + +* it ships at least one file under ``files/playwright/`` whose name carries + ``mcp``, so the surface has a spec rather than being covered incidentally by + a persona test; +* a role serving MCP additionally asserts the unauthenticated case somewhere in + those files. The anchor is vocabulary โ€” ``unauthenticated``, ``bearerless``, + ``without a bearer``, ``refusโ€ฆ`` or ``rejectโ€ฆ`` โ€” so name the assertion in + those words rather than leaving a reader to infer it. + +Disabled surfaces are exempt: nothing is served until an operator turns them on. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-playwright-coverage`` in the head of the role's + ``meta/mcp.yml``. +""" + +from __future__ import annotations + +import re +import unittest +from collections.abc import Mapping +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.applications import get_application_defaults +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +_RULE = "mcp-playwright-coverage" +_SERVER_DIRECTIONS = frozenset({"server", "both"}) +_CLIENT_DIRECTIONS = frozenset({"client", "both"}) +_UNAUTHENTICATED = re.compile( + r"unauthenticated|bearerless|without a bearer|refus|reject", re.IGNORECASE +) +_CLIENT_SURFACE = re.compile( + r"unauthenticated|refus|reject|server list|servers\b", re.IGNORECASE +) + + +def _enabled_mcp_roles() -> dict[str, str]: + """Return ``{role: direction}`` for every role serving or consuming MCP.""" + roles_root = Path(PROJECT_ROOT, "roles") + defaults = get_application_defaults(roles_dir=roles_root) + roles: dict[str, str] = {} + for mcp_path in sorted(roles_root.glob(f"*/{ROLE_FILE_META_MCP}")): + mcp = load_yaml_any(str(mcp_path), default_if_missing={}) + if not isinstance(mcp, Mapping): + continue + role = mcp_path.parent.parent.name + block = (defaults.get(role) or {}).get("mcp") + if not (block.get("enabled") if isinstance(block, Mapping) else None): + continue + if is_suppressed_in_head(read_text(str(mcp_path)).splitlines(), _RULE): + continue + roles[role] = str(mcp.get("direction") or "").strip().lower() + return roles + + +def _mcp_specs(role: str) -> list[Path]: + directory = PROJECT_ROOT / "roles" / role / "files" / "playwright" + return sorted(p for p in directory.glob("*.js") if "mcp" in p.name) + + +class TestMcpPlaywrightCoverage(unittest.TestCase): + def test_every_enabled_surface_has_a_spec(self) -> None: + missing = [ + f"{role}: its MCP surface is enabled but files/playwright/ holds no " + f"mcp spec, so nothing exercises it from outside the deploy" + for role in sorted(_enabled_mcp_roles()) + if not _mcp_specs(role) + ] + self.assertEqual( + [], + missing, + f"enabled MCP surface(s) without a spec ({len(missing)}):\n" + + "\n".join(f" - {m}" for m in missing), + ) + + def test_every_served_surface_asserts_the_unauthenticated_case(self) -> None: + silent = [] + for role, direction in sorted(_enabled_mcp_roles().items()): + if direction not in _SERVER_DIRECTIONS: + continue + specs = _mcp_specs(role) + if specs and not any( + _UNAUTHENTICATED.search(read_text(str(spec))) for spec in specs + ): + silent.append( + f"{role}: serves MCP but no spec names the unauthenticated " + f"case, so the endpoint is only ever asked with a valid " + f"credential" + ) + self.assertEqual( + [], + silent, + f"served MCP surface(s) never probed anonymously ({len(silent)}):\n" + + "\n".join(f" - {s}" for s in silent), + ) + + def test_every_served_surface_asserts_the_disabled_case(self) -> None: + silent = [] + for role, direction in sorted(_enabled_mcp_roles().items()): + if direction not in _SERVER_DIRECTIONS: + continue + specs = _mcp_specs(role) + if specs and not any( + "registerMcpDisabledState" in read_text(str(spec)) for spec in specs + ): + silent.append( + f"{role}: every MCP spec here skips itself when the surface " + f"is switched off, so one that kept serving afterwards looks " + f"exactly like one that was never deployed" + ) + self.assertEqual( + [], + silent, + f"served MCP surface(s) never probed while disabled ({len(silent)}):\n" + + "\n".join(f" - {s}" for s in silent), + ) + + def test_every_consumed_surface_asserts_what_the_client_exposes(self) -> None: + silent = [] + for role, direction in sorted(_enabled_mcp_roles().items()): + if direction not in _CLIENT_DIRECTIONS: + continue + specs = _mcp_specs(role) + if specs and not any( + _CLIENT_SURFACE.search(read_text(str(spec))) for spec in specs + ): + silent.append( + f"{role}: consumes MCP but no spec asserts either the " + f"configured server list or that its own API refuses an " + f"unauthenticated caller, so the credential it holds is " + f"never shown to be out of reach" + ) + self.assertEqual( + [], + silent, + f"MCP client(s) with an unexercised surface ({len(silent)}):\n" + + "\n".join(f" - {s}" for s in silent), + ) + + def test_the_scan_finds_enabled_surfaces(self) -> None: + roles = _enabled_mcp_roles() + self.assertTrue( + roles, + "no role enables an MCP surface, so both rules would pass " + "vacuously; check that the scan still reads the right topic", + ) + self.assertTrue( + any(d in _SERVER_DIRECTIONS for d in roles.values()), + "no enabled role serves MCP, so the anonymous-probe rule would " + "pass vacuously", + ) + self.assertTrue( + any(d in _CLIENT_DIRECTIONS for d in roles.values()), + "no enabled role consumes MCP, so the client-surface rule would " + "pass vacuously", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_provider_cli_test.py b/tests/lint/ansible/services/test_mcp_provider_cli_test.py new file mode 100644 index 0000000000..62dccae390 --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_provider_cli_test.py @@ -0,0 +1,101 @@ +"""Lint: an enabled MCP provider ships a CLI test for its endpoint. + +``auth_subject``, ``credential.owner`` and ``tools.allowlist`` are declarations. +Nothing stops a role from declaring one principal and provisioning another, or +from advertising tools the server never exposes; a client would then discover an +endpoint whose credential belongs to nobody, or whose allowlist is fiction. + +Every provider closes that gap the same way: ``files/test/test.sh`` drives the +shared contract harness, which speaks the declared transport against the live +endpoint with the header a client would send, compares ``tools/list`` against +the allowlist and calls the declared read probe. A provider without that test +has a documentation-only identity. + +Disabled providers are exempt: they serve nothing, so there is nothing to prove +until an operator turns them on. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-provider-cli-test`` in the head of the role's ``meta/mcp.yml``. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.applications import get_application_defaults +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +_RULE = "mcp-provider-cli-test" +_SERVER_DIRECTIONS = frozenset({"server", "both"}) +_SCRIPT = "files/test/test.sh" +_ENV_TEMPLATE = "templates/test.env.j2" +_HARNESS = "shared/mcp/run.sh" + + +def _enabled_providers() -> list[Path]: + """Return the role directories serving an MCP endpoint right now.""" + roles_root = Path(PROJECT_ROOT, "roles") + defaults = get_application_defaults(roles_dir=roles_root) + roles: list[Path] = [] + for mcp_path in sorted(roles_root.glob(f"*/{ROLE_FILE_META_MCP}")): + mcp = load_yaml_any(str(mcp_path), default_if_missing={}) + if not isinstance(mcp, Mapping): + continue + if str(mcp.get("direction") or "").strip().lower() not in _SERVER_DIRECTIONS: + continue + role_dir = mcp_path.parent.parent + block = (defaults.get(role_dir.name) or {}).get("mcp") + resolved = block.get("enabled") if isinstance(block, Mapping) else None + if not resolved: + continue + if is_suppressed_in_head(read_text(str(mcp_path)).splitlines(), _RULE): + continue + roles.append(role_dir) + return roles + + +def _missing_asset(role_dir: Path) -> str | None: + """Return why the role has no usable MCP CLI test, or None when it has one.""" + script = role_dir / _SCRIPT + if not script.is_file(): + return f"missing {_SCRIPT}" + if not (role_dir / _ENV_TEMPLATE).is_file(): + return f"missing {_ENV_TEMPLATE}, so no round ever discovers the test" + if _HARNESS not in read_text(str(script)): + return f"{_SCRIPT} never drives {_HARNESS}" + return None + + +class TestMcpProviderCliTest(unittest.TestCase): + def test_every_enabled_provider_tests_its_endpoint(self) -> None: + offenders = [ + f"{role.name}: serves MCP but {why}, so its declared credential " + f"owner and tool allowlist are never proven against the endpoint" + for role in _enabled_providers() + if (why := _missing_asset(role)) is not None + ] + self.assertEqual( + [], + offenders, + f"MCP provider(s) with an unproven endpoint ({len(offenders)}):\n" + + "\n".join(f" - {o}" for o in offenders), + ) + + def test_the_scan_finds_enabled_providers(self) -> None: + self.assertTrue( + _enabled_providers(), + "no MCP block declares an enabled server, so the rule would pass " + "vacuously; check that the scan still reads the right topic", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_provider_client_network.py b/tests/lint/ansible/services/test_mcp_provider_client_network.py new file mode 100644 index 0000000000..b6968b14db --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_provider_client_network.py @@ -0,0 +1,95 @@ +"""Lint: an MCP provider opens a network the clients it admits can join. + +``mcp_servers`` hands every client the bare URL +``http://:``. That name only resolves when the +client shares a network with the provider, which is what +``meta/networks.yml.overlay`` arranges: a ``topology`` creates the network and +``consumer.kind: mcp_client`` attaches every role the provider admits through +the ``mcp_consumer`` flag. A beacon-only overlay carries neither, so +``utils.networks.attachments._compute_attachments`` produces no attachment at +all. + +Nothing fails when that happens. The docker daemon ships +``dns-search: [DOMAIN_PRIMARY]``, so the unresolvable service name is completed +into a public FQDN, the wildcard record answers with the ingress address, and +the client talks to the reverse proxy over the internet instead of to the +container next door. The tool calls still succeed, which is why this survives a +deploy: only the route is wrong. + +``web-app-wordpress`` was this exact shape and sent every MCP call for its +Apache container out through the public ingress. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-provider-client-network`` in the head of the provider's + ``meta/networks.yml``. +""" + +from __future__ import annotations + +import unittest + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_MCP, ROLE_FILE_META_NETWORKS + +from . import PROJECT_ROOT + +_RULE = "mcp-provider-client-network" +_CLIENT_KIND = "mcp_client" + + +def consumer_kinds(overlay: dict) -> list[str]: + """Return the consumer kinds an overlay declares, always as a list. + + Args: + overlay: the ``overlay`` mapping of a role's ``meta/networks.yml``. + """ + declared = (overlay.get("consumer") or {}).get("kind") or "services_flags" + return [ + str(kind) for kind in (declared if isinstance(declared, list) else [declared]) + ] + + +def unreachable_providers() -> list[str]: + findings: list[str] = [] + for meta in sorted(PROJECT_ROOT.glob(f"roles/*/{ROLE_FILE_META_MCP}")): + block = load_yaml_any(str(meta), default_if_missing={}) + if not isinstance(block, dict) or not block.get("endpoint"): + continue + role = meta.parent.parent + networks = role / ROLE_FILE_META_NETWORKS + if is_suppressed_in_head( + read_text(str(networks)).splitlines() if networks.exists() else [], _RULE + ): + continue + loaded = load_yaml_any(str(networks), default_if_missing={}) + overlay = (loaded or {}).get("overlay") if isinstance(loaded, dict) else None + if not isinstance(overlay, dict) or not overlay.get("topology"): + findings.append( + f"{role.name}: overlay declares no topology, so no network exists to join" + ) + continue + if _CLIENT_KIND not in consumer_kinds(overlay): + findings.append( + f"{role.name}: overlay admits {consumer_kinds(overlay)}, never {_CLIENT_KIND!r}" + ) + return findings + + +class TestMcpProviderClientNetwork(unittest.TestCase): + def test_every_mcp_endpoint_provider_attaches_its_clients(self) -> None: + findings = unreachable_providers() + self.assertEqual( + [], + findings, + f"MCP providers whose clients cannot resolve the endpoint service name " + f"({len(findings)}); the dns-search suffix routes those calls through the " + f"public ingress instead, and the call still succeeds:\n" + + "\n".join(f" - {entry}" for entry in findings), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_schema.py b/tests/lint/ansible/services/test_mcp_schema.py new file mode 100644 index 0000000000..171feb1c3c --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_schema.py @@ -0,0 +1,849 @@ +"""Schema lint for the ``mcp`` block. + +A role declares ``mcp`` only when it actually serves or consumes MCP. Why a +role cannot is recorded once in the design documentation, not in a metadata +block per role restating an enum. What is declared here has to be complete, +with vocabulary from ``utils/roles/applications/mcp.py``. + +It is a hard lint. It rejects: + +* a block without a ``classification``, or with a non-deployable one: a role + that cannot serve declares nothing, + +* an unknown key inside ``mcp``, ``endpoint``, ``credential``, ``delegation``, + ``adapter``, ``limits`` or ``tools``, +* a templated value on any MCP-specific field (only ``enabled``/``shared`` + may carry Jinja), +* an invalid ``direction`` / ``transport`` / ``exposure`` / ``auth`` / + ``auth_subject`` / ``implementation``, +* a ``direction`` that contradicts the ``classification``, +* a server-capable block missing ``auth``, ``credential``, a complete + ``endpoint``, or any admitted client, +* a credential owned by ``administrator``, or read from an unknown source, +* ``auth: none`` combined with an ``exposure`` other than ``internal``, +* ``auth_subject: service_account|administrator`` combined with + ``tools.mutating_tools_enabled: true``, +* ``auth_subject: user`` or ``auth: oidc`` without a ``delegation`` block + recording refresh, revocation and audience binding at one exact version, + because a rendered deployment bearer is a service account whatever the + metadata claims, +* a client-capable block missing ``supported_transports`` / + ``supported_auths``, or declaring an ``endpoint`` it does not serve, +* an ``endpoint.service_key`` that names no service in the same file, or an + ``endpoint.port_key`` that resolves under neither ``ports.local`` nor + ``ports.internal`` of the referenced service, +* an adapter or public surface without a complete ``limits`` block, +* ``implementation: adapter`` without a pinned, hash-checked adapter contract + and an exact tool allowlist, +* a generic URL, runtime specification, free-form query, raw SQL, filesystem + root, shell command, container socket or unrestricted bucket in an adapter. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-schema`` in the head of a ``meta/services.yml`` file + exempts the whole file. +* ``# nocheck: mcp-schema`` on (or directly above) the offending line + exempts that single finding. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping, Sequence +from functools import partial + +from utils.annotations.suppress import is_suppressed_at, is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.applications.mcp import ( + MCP_ADAPTER_KEYS, + MCP_ADAPTER_REQUIRED_KEYS, + MCP_ADAPTER_TYPES, + MCP_AUTH_SUBJECTS, + MCP_AUTHS, + MCP_CLASSIFICATIONS, + MCP_CLIENT_DIRECTIONS, + MCP_CREDENTIAL_KEYS, + MCP_CREDENTIAL_SOURCES, + MCP_DELEGATION_KEYS, + MCP_DEPLOYABLE_CLASSIFICATIONS, + MCP_DIRECTIONS, + MCP_ENDPOINT_KEYS, + MCP_EXPOSURES, + MCP_FORBIDDEN_SURFACE_MARKERS, + MCP_IMPLEMENTATIONS, + MCP_KEYS, + MCP_LIMITS_KEYS, + MCP_PRIVILEGED_AUTH_SUBJECTS, + MCP_READ_PROBE_KEYS, + MCP_REQUIRED_ENDPOINT_KEYS, + MCP_SCOPED_ADAPTER_TYPES, + MCP_SERVER_DIRECTIONS, + MCP_SHA256_PREFIX, + MCP_SPECIFICATION_ADAPTER_TYPES, + MCP_TOOLS_BOOLEAN_KEYS, + MCP_TOOLS_KEYS, + MCP_TRANSPORTS, + MCP_UPSTREAM_MCP_ADAPTER_TYPES, + declares_delegation, + delegation_is_proven, + derive_allowed_consumers, + value_is_templated, +) +from utils.roles.mapping import ROLE_FILE_META_MCP, ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +_RULE = "mcp-schema" + +_ENUMS: tuple[tuple[str, frozenset[str]], ...] = ( + ("classification", MCP_CLASSIFICATIONS), + ("direction", MCP_DIRECTIONS), + ("transport", MCP_TRANSPORTS), + ("exposure", MCP_EXPOSURES), + ("auth", MCP_AUTHS), + ("auth_subject", MCP_AUTH_SUBJECTS), + ("implementation", MCP_IMPLEMENTATIONS), +) + +_CLASSIFICATION_DIRECTIONS: dict[str, frozenset[str]] = { + "native_server": MCP_SERVER_DIRECTIONS, + "plugin_server": MCP_SERVER_DIRECTIONS, + "sidecar_server": MCP_SERVER_DIRECTIONS, + "adapter_server": MCP_SERVER_DIRECTIONS, + "native_client": MCP_CLIENT_DIRECTIONS, + "native_both": frozenset({"both"}), +} + +_FORBIDDEN_OWNER = "administrator" + + +def _flag( + errors: list[str], lines: list[str], rel: str, key: str, message: str +) -> None: + line_no = _locate_line(lines, key) + if line_no is not None and is_suppressed_at(lines, line_no, _RULE): + return + errors.append(f"{message} ({rel})") + + +def _locate_line(lines: list[str], key: str) -> int | None: + """Return the 1-based line declaring ``key``, or None. + + Args: + lines: the role's ``meta/mcp.yml`` split into lines. + key: the schema key a finding is reported against. + + The whole file is the block, so there is no enclosing ``mcp:`` line to + anchor on. Anchoring on one made every lookup miss, which silently + disabled per-line suppression everywhere. + """ + needle = f"{key}:" + for idx, raw in enumerate(lines, start=1): + if raw.strip().startswith(needle): + return idx + return None + + +def _strings(value: object) -> list[str]: + """Return every string reachable inside a nested mapping or sequence. + + Args: + value: any metadata value; scalars, mappings and sequences are walked. + """ + if isinstance(value, str): + return [value] + if isinstance(value, Mapping): + return [s for v in value.values() for s in _strings(v)] + if isinstance(value, Sequence): + return [s for v in value for s in _strings(v)] + return [] + + +def _is_positive_int(value: object) -> bool: + return isinstance(value, int) and not isinstance(value, bool) and value > 0 + + +def _is_exact_names(value: object) -> bool: + return ( + isinstance(value, list) + and bool(value) + and all(isinstance(v, str) and v.strip() and "*" not in v for v in value) + ) + + +def _services_by_role() -> dict[str, object]: + """Return every role's services mapping, keyed by role name.""" + return { + path.parent.parent.name: load_yaml_any(str(path), default_if_missing={}) + for path in sorted( + (PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_SERVICES}") + ) + } + + +class TestMcpSchema(unittest.TestCase): + """Hard lint: every deployable ``mcp`` block obeys the contract.""" + + def test_mcp_schema(self) -> None: + roles_root = PROJECT_ROOT / "roles" + if not roles_root.is_dir(): + self.skipTest("no roles/ directory") + + errors: list[str] = [] + + for role_dir in sorted(p for p in roles_root.iterdir() if p.is_dir()): + mcp_path = role_dir / ROLE_FILE_META_MCP + if not mcp_path.is_file(): + continue + rel = mcp_path.relative_to(PROJECT_ROOT).as_posix() + lines = read_text(str(mcp_path)).splitlines() + + if is_suppressed_in_head(lines, _RULE): + continue + + try: + mcp = load_yaml_any(str(mcp_path), default_if_missing={}) + except Exception: + continue + + services = load_yaml_any( + str(role_dir / ROLE_FILE_META_SERVICES), default_if_missing={} + ) + if not isinstance(services, Mapping): + services = {} + if mcp is None: + continue + + prefix = f"{role_dir.name}: mcp" + flag = partial(_flag, errors, lines, rel) + + if not isinstance(mcp, Mapping): + errors.append(f"{prefix} MUST be a mapping. ({rel})") + continue + + unknown = set(mcp) - MCP_KEYS + if unknown: + flag(min(unknown), f"{prefix} has unknown key(s) {sorted(unknown)}") + + for key, allowed in _ENUMS: + if key not in mcp: + continue + value = mcp.get(key) + if value_is_templated(value): + flag(key, f"{prefix}.{key} MUST be a literal, not Jinja") + elif value not in allowed: + flag( + key, + f"{prefix}.{key} has invalid value {value!r}; " + f"allowed: {sorted(allowed)}", + ) + + classification = mcp.get("classification") + if classification not in MCP_DEPLOYABLE_CLASSIFICATIONS: + flag( + "classification", + f"{prefix}.classification {classification!r} is not " + f"deployable; a role that cannot serve or consume MCP " + f"declares no mcp block at all. Allowed: " + f"{sorted(MCP_DEPLOYABLE_CLASSIFICATIONS)}", + ) + continue + + self._check_deployable( + mcp, services, prefix, flag, role_dir.name, classification + ) + + if errors: + self.fail( + f"mcp schema violations ({len(errors)}):\n" + "\n".join(sorted(errors)) + ) + + def _check_deployable( + self, mcp, services, prefix, flag, role, classification + ) -> None: + direction = mcp.get("direction") + if "direction" not in mcp: + flag("direction", f"{prefix} is missing required 'direction'") + + expected = _CLASSIFICATION_DIRECTIONS.get(str(classification)) + if expected and direction not in expected: + flag( + "direction", + f"{prefix}.direction {direction!r} contradicts classification " + f"{classification!r}; allowed: {sorted(expected)}", + ) + + server_capable = direction in MCP_SERVER_DIRECTIONS + client_capable = direction in MCP_CLIENT_DIRECTIONS + + self._check_no_peer_gate(mcp, prefix, flag) + self._check_delegation(mcp, prefix, flag) + self._check_tools(mcp, prefix, flag) + + if client_capable: + self._check_client(mcp, prefix, flag, server_capable) + if server_capable: + self._check_credential(mcp, prefix, flag) + self._check_consumers(role, prefix, flag) + self._check_endpoint(mcp, services, prefix, flag) + if "auth" not in mcp: + flag("auth", f"{prefix} server-capable block is missing 'auth'") + if "transport" not in mcp: + flag( + "transport", + f"{prefix} server-capable block is missing 'transport'; the " + f"deploy-time probe reads it strictly and a consumer cannot " + f"pick a client without it", + ) + + if mcp.get("auth") == "none" and mcp.get("exposure") != "internal": + flag("auth", f"{prefix} 'auth: none' requires 'exposure: internal'") + + is_adapter = mcp.get("implementation") == "adapter" + if is_adapter != (classification == "adapter_server"): + flag( + "implementation", + f"{prefix} classification {classification!r} and implementation " + f"{mcp.get('implementation')!r} disagree about being an adapter", + ) + + if is_adapter or mcp.get("exposure") == "public": + self._check_limits(mcp, prefix, flag) + if is_adapter: + self._check_adapter(mcp, prefix, flag, role) + + def _check_no_peer_gate(self, mcp, prefix, flag) -> None: + """Admission is declared, presence is derived; never both by hand here. + + A block that reads ``'web-app-openwebui' in group_names`` turns "that + client happens to be deployed" into "that client may connect", which is + a different question and one nobody declared. It also cannot scale: each + new client would need an edit in every provider. + + ``utils/cache/applications.py`` builds exactly that expression from the + ``mcp_consumer`` edges instead, so a hand-written one is a second source + for the same fact and drifts the moment an edge changes. + """ + for key in ("enabled", "shared"): + value = mcp.get(key) + if isinstance(value, str) and "group_names" in value: + flag( + key, + f"{prefix}.{key} gates on group_names by hand; the presence " + f"expression is derived from the allowed_consumers " + f"intersection, so declare admission in meta/services.yml", + ) + + def _check_delegation(self, mcp, prefix, flag) -> None: + delegation = mcp.get("delegation") + if delegation is not None: + if not isinstance(delegation, Mapping): + flag("delegation", f"{prefix}.delegation MUST be a mapping") + return + unknown = set(delegation) - MCP_DELEGATION_KEYS + if unknown: + flag( + "delegation", + f"{prefix}.delegation has unknown key(s) {sorted(unknown)}", + ) + if not declares_delegation(mcp): + if delegation is not None: + flag( + "delegation", + f"{prefix} declares 'delegation' without claiming user " + f"delegation; drop it or set auth_subject: user", + ) + return + if not delegation_is_proven(mcp): + flag( + "auth_subject", + f"{prefix} claims user delegation but records no proof. A " + f"rendered deployment bearer is a service account: either add a " + f"'delegation' block with verified_version, source_url and " + f"refresh/revocation/audience_binding all true, or declare " + f"auth_subject: service_account", + ) + + def _check_client(self, mcp, prefix, flag, server_capable) -> None: + transports = mcp.get("supported_transports") + if not _is_exact_names(transports): + flag( + "supported_transports", + f"{prefix} client-capable block needs a non-empty " + f"'supported_transports' list", + ) + elif set(transports) - MCP_TRANSPORTS: + flag( + "supported_transports", + f"{prefix}.supported_transports has invalid value(s) " + f"{sorted(set(transports) - MCP_TRANSPORTS)}", + ) + + auths = mcp.get("supported_auths") + if not _is_exact_names(auths): + flag( + "supported_auths", + f"{prefix} client-capable block needs a non-empty " + f"'supported_auths' list", + ) + elif set(auths) - MCP_AUTHS: + flag( + "supported_auths", + f"{prefix}.supported_auths has invalid value(s) " + f"{sorted(set(auths) - MCP_AUTHS)}", + ) + + if not server_capable and "endpoint" in mcp: + flag( + "endpoint", + f"{prefix} is a client, so it MUST NOT declare an 'endpoint'", + ) + + def _check_credential(self, mcp, prefix, flag) -> None: + credential = mcp.get("credential") + if not isinstance(credential, Mapping): + flag( + "credential", + f"{prefix} server-capable block is missing 'credential'; the " + f"provider identity MUST be declared, not inherited from the " + f"administrator", + ) + return + unknown = set(credential) - MCP_CREDENTIAL_KEYS + if unknown: + flag( + "credential", + f"{prefix}.credential has unknown key(s) {sorted(unknown)}", + ) + missing = MCP_CREDENTIAL_KEYS - set(credential) + if missing: + flag( + "credential", + f"{prefix}.credential is missing key(s) {sorted(missing)}", + ) + owner = str(credential.get("owner") or "").strip() + if owner == _FORBIDDEN_OWNER: + flag( + "owner", + f"{prefix}.credential.owner MUST NOT be {_FORBIDDEN_OWNER!r}; " + f"declare a dedicated non-login identity for this provider", + ) + source = credential.get("source") + if source is not None and source not in MCP_CREDENTIAL_SOURCES: + flag( + "source", + f"{prefix}.credential.source {source!r} is invalid; allowed: " + f"{sorted(MCP_CREDENTIAL_SOURCES)}", + ) + + def _check_consumers(self, role, prefix, flag) -> None: + if not derive_allowed_consumers(role, _services_by_role()): + flag( + "mcp_consumer", + f"{prefix} server-capable block admits no client; a client " + f"declares 'services..mcp_consumer: true' in its own " + f"role and this provider must not override it to false for " + f"every one of them", + ) + + def _check_endpoint(self, mcp, services, prefix, flag) -> None: + endpoint = mcp.get("endpoint") + if not isinstance(endpoint, Mapping): + flag("endpoint", f"{prefix} server-capable block is missing 'endpoint'") + return + missing = MCP_REQUIRED_ENDPOINT_KEYS - set(endpoint) + if missing: + flag("endpoint", f"{prefix}.endpoint is missing key(s) {sorted(missing)}") + unknown = set(endpoint) - MCP_ENDPOINT_KEYS + if unknown: + flag("endpoint", f"{prefix}.endpoint has unknown key(s) {sorted(unknown)}") + + service_key = endpoint.get("service_key") + if service_key is None: + return + target = services.get(str(service_key)) + if not isinstance(target, Mapping): + flag( + "service_key", + f"{prefix}.endpoint.service_key {service_key!r} names no service " + f"in this file", + ) + return + ports = target.get("ports") + ports = ports if isinstance(ports, Mapping) else {} + port_key = endpoint.get("port_key") + if port_key is not None and not any( + isinstance(ports.get(ns), Mapping) and port_key in ports[ns] + for ns in ("local", "internal") + ): + flag( + "port_key", + f"{prefix}.endpoint.port_key {port_key!r} resolves under neither " + f"ports.local nor ports.internal of service {service_key!r}", + ) + + def _check_limits(self, mcp, prefix, flag) -> None: + limits = mcp.get("limits") + if not isinstance(limits, Mapping): + flag( + "limits", + f"{prefix} needs an explicit 'limits' block; an adapter or " + f"public surface without ceilings is unbounded", + ) + return + unknown = set(limits) - MCP_LIMITS_KEYS + if unknown: + flag("limits", f"{prefix}.limits has unknown key(s) {sorted(unknown)}") + missing = MCP_LIMITS_KEYS - set(limits) + if missing: + flag("limits", f"{prefix}.limits is missing key(s) {sorted(missing)}") + for key in MCP_LIMITS_KEYS & set(limits): + if not _is_positive_int(limits.get(key)): + flag(key, f"{prefix}.limits.{key} MUST be a positive integer") + + def _check_tools(self, mcp, prefix, flag) -> None: + tools = mcp.get("tools") + if "tools" in mcp and not isinstance(tools, Mapping): + flag("tools", f"{prefix}.tools MUST be a mapping") + tools = tools if isinstance(tools, Mapping) else {} + unknown = set(tools) - MCP_TOOLS_KEYS + if unknown: + flag("tools", f"{prefix}.tools has unknown key(s) {sorted(unknown)}") + self._check_writer_allowlist(tools, prefix, flag) + self._check_upstream_serves(mcp, tools, prefix, flag) + self._check_read_probe(tools, prefix, flag) + + for key in MCP_TOOLS_BOOLEAN_KEYS & set(tools): + if not isinstance(tools.get(key), bool): + flag(key, f"{prefix}.tools.{key} MUST be a boolean") + privileged = mcp.get("auth_subject") in MCP_PRIVILEGED_AUTH_SUBJECTS + mutating = tools.get("mutating_tools_enabled") + enforced = mcp.get("implementation") == "adapter" + if privileged and mutating is not False and not enforced: + flag( + "auth_subject", + f"{prefix} '{mcp.get('auth_subject')}' subject may only enable " + f"mutating tools behind a gateway that enforces the allowlist on " + f"tools/call; without one the flag records an intention that " + f"nothing upholds, so it MUST be false", + ) + if ( + privileged + and mutating is True + and enforced + and not tools.get("writer_allowlist") + ): + flag( + "writer_allowlist", + f"{prefix} enables mutating tools but names no " + f"tools.writer_allowlist, so every reader would reach the writes " + f"too; the point of the split is that they get different bearers", + ) + + def _check_read_probe(self, tools, prefix, flag) -> None: + probe = tools.get("read_probe") + if probe is None: + return + if not isinstance(probe, Mapping): + flag("read_probe", f"{prefix}.tools.read_probe MUST be a mapping") + return + unknown = set(probe) - MCP_READ_PROBE_KEYS + if unknown: + flag( + "read_probe", + f"{prefix}.tools.read_probe has unknown key(s) {sorted(unknown)}", + ) + tool = str(probe.get("tool") or "").strip() + if not tool: + flag("read_probe", f"{prefix}.tools.read_probe MUST name a 'tool'") + if "arguments" in probe and not isinstance(probe.get("arguments"), Mapping): + flag( + "read_probe", + f"{prefix}.tools.read_probe.arguments MUST be a mapping", + ) + allowlist = tools.get("allowlist") + if tool and isinstance(allowlist, list) and allowlist and tool not in allowlist: + flag( + "read_probe", + f"{prefix}.tools.read_probe.tool {tool!r} is not in " + f"tools.allowlist, so the gateway rejects the call before the " + f"server ever sees it and the probe can never pass", + ) + + def _check_writer_allowlist(self, tools, prefix, flag) -> None: + allowlist = tools.get("allowlist") + if not isinstance(allowlist, list): + return + writer = tools.get("writer_allowlist") + if writer is None: + return + if not _is_exact_names(writer): + flag( + "writer_allowlist", + f"{prefix}.tools.writer_allowlist MUST name exact tools", + ) + return + missing = sorted(set(allowlist) - set(writer)) + if missing: + flag( + "writer_allowlist", + f"{prefix}.tools.writer_allowlist omits {missing}, which a reader " + f"may already reach; a writer that loses a read tool is a " + f"narrower grant wearing the wider name", + ) + if set(writer) == set(allowlist): + flag( + "writer_allowlist", + f"{prefix}.tools.writer_allowlist repeats the allowlist; omit it, " + f"a provider with no extra write surface needs one contract, " + f"not two", + ) + serves = tools.get("upstream_serves") + if isinstance(serves, list) and serves: + undeclared = sorted(set(writer) - set(serves)) + if undeclared: + flag( + "writer_allowlist", + f"{prefix}.tools.writer_allowlist names {undeclared} which " + f"the upstream does not serve", + ) + + def _check_upstream_serves(self, mcp, tools, prefix, flag) -> None: + """``allowlist`` is what the platform permits; ``upstream_serves`` is what + the upstream actually offers. State the second only where it DIFFERS, + because a provider that serves exactly what is allowed would otherwise + carry the same list twice and the copies would drift apart. + + The difference between the two measures unenforced exposure: where it is + non-empty the allowlist is an intention rather than a constraint, and the + provider needs a gateway in front of it. + + Three exemptions, all semantic: an adapter authors its tools here against + a REST upstream, so there is nothing to observe; a provider declared + ``enabled: false`` is never admitted; and ``upstream_serves: dynamic`` + covers an upstream that composes its surface at runtime, such as one + proxying MCP servers an administrator configures, where no set of names + could be pinned at author time.""" + if mcp.get("direction") not in MCP_SERVER_DIRECTIONS: + return + adapter = mcp.get("adapter") + adapter_type = adapter.get("type") if isinstance(adapter, Mapping) else None + if ( + mcp.get("implementation") == "adapter" + and adapter_type not in MCP_UPSTREAM_MCP_ADAPTER_TYPES + ): + return + if mcp.get("enabled") is False: + return + + allowlist = tools.get("allowlist") + serves = tools.get("upstream_serves") + if serves == "dynamic": + if not _is_exact_names(tools.get("categories")): + flag( + "categories", + f"{prefix}.tools.categories MUST pin the categories the " + f"deployment permits: an upstream that composes its tools at " + f"runtime and switches only whole categories cannot honour a " + f"per-tool allowlist, so the category is the finest contract " + f"it can keep and 'dynamic' alone would permit everything", + ) + return + + if not isinstance(allowlist, list) or not allowlist: + flag( + "allowlist", + f"{prefix}.tools.allowlist MUST name the tools the platform " + f"permits; an empty list reads as a pass while leaving every " + f"tool the upstream serves reachable", + ) + return + + if serves is None: + return + + if not isinstance(serves, list) or not serves: + flag( + "upstream_serves", + f"{prefix}.tools.upstream_serves MUST list every tool the " + f"upstream offers at the deployed version, or be omitted when " + f"it is identical to the allowlist", + ) + return + + undeclared = sorted(set(allowlist) - set(serves)) + if undeclared: + flag( + "allowlist", + f"{prefix}.tools.allowlist names {undeclared} which the " + f"upstream does not serve; the platform would advertise a " + f"tool that cannot run", + ) + return + + if sorted(serves) == sorted(allowlist): + flag( + "upstream_serves", + f"{prefix}.tools.upstream_serves repeats the allowlist; omit it, " + f"absence already means the upstream serves exactly what is " + f"allowed", + ) + + def _check_adapter(self, mcp, prefix, flag, role) -> None: + adapter = mcp.get("adapter") + if not isinstance(adapter, Mapping): + flag("adapter", f"{prefix} implementation: adapter is missing 'adapter'") + return + unknown = set(adapter) - MCP_ADAPTER_KEYS + if unknown: + flag("adapter", f"{prefix}.adapter has unknown key(s) {sorted(unknown)}") + missing = MCP_ADAPTER_REQUIRED_KEYS - set(adapter) + if missing: + flag("adapter", f"{prefix}.adapter is missing key(s) {sorted(missing)}") + + if "upstream_transport" in adapter: + declared = adapter.get("upstream_transport") + if declared not in MCP_TRANSPORTS: + flag( + "upstream_transport", + f"{prefix}.adapter.upstream_transport {declared!r} is " + f"invalid; allowed: {sorted(MCP_TRANSPORTS)}. Omit it where " + f"the upstream speaks streamable HTTP, which the adapter " + f"assumes when nothing says otherwise", + ) + + adapter_type = adapter.get("type") + if adapter_type not in MCP_ADAPTER_TYPES: + flag( + "type", + f"{prefix}.adapter.type {adapter_type!r} is invalid; allowed: " + f"{sorted(MCP_ADAPTER_TYPES)}", + ) + + if adapter_type in MCP_UPSTREAM_MCP_ADAPTER_TYPES: + spec = str(adapter.get("specification_path") or "") + if not spec: + flag( + "specification_path", + f"{prefix}.adapter.specification_path MUST name the tool " + f"contract the passthrough enforces; an MCP upstream exposes " + f"no method to infer a tool's blast radius from, so each tool " + f"has to declare whether it mutates", + ) + + if adapter_type in MCP_SPECIFICATION_ADAPTER_TYPES: + spec = str(adapter.get("specification_path") or "") + if not spec.startswith(f"roles/{role}/files/"): + flag( + "specification_path", + f"{prefix}.adapter.specification_path MUST be a checked-in " + f"path under roles/{role}/files/, never a runtime document " + f"or remote URL", + ) + elif not (PROJECT_ROOT / spec).is_file(): + flag( + "specification_path", + f"{prefix}.adapter.specification_path {spec!r} does not exist", + ) + if not str(adapter.get("specification_sha256") or "").startswith( + MCP_SHA256_PREFIX + ): + flag( + "specification_sha256", + f"{prefix}.adapter.specification_sha256 MUST pin the " + f"checked-in specification", + ) + + if adapter_type in MCP_SCOPED_ADAPTER_TYPES and not _is_exact_names( + adapter.get("scope") + ): + flag( + "scope", + f"{prefix}.adapter.type {adapter_type!r} needs a non-empty " + f"'scope' naming the exact buckets, prefixes, collections or " + f"queries it may reach; an unrestricted scope is rejected", + ) + + for text in _strings(adapter): + for marker in MCP_FORBIDDEN_SURFACE_MARKERS: + if marker in text: + flag( + "adapter", + f"{prefix}.adapter contains {marker!r}, which opens a " + f"shell, socket, filesystem or unrestricted surface", + ) + + tools = mcp.get("tools") + tools = tools if isinstance(tools, Mapping) else {} + if not _is_exact_names(tools.get("allowlist")): + flag( + "allowlist", + f"{prefix}.tools.allowlist MUST name every exposed tool exactly; " + f"an adapter never mirrors a whole upstream API", + ) + if not str(tools.get("schema_sha256") or "").startswith(MCP_SHA256_PREFIX): + flag( + "schema_sha256", + f"{prefix}.tools.schema_sha256 MUST pin the reviewed tool schema " + f"so upstream drift fails closed", + ) + + +class TestMcpConsumerCompatibility(unittest.TestCase): + """Hard lint: a provider only admits clients that can actually connect. + + ``mcp_servers`` aborts a run when a provider authorized a consumer whose + transport or auth it cannot serve, because a client that silently ends up + with fewer tools than declared looks exactly like one that works. Catching + the same mismatch statically means a metadata edit fails here rather than + an hour into a deploy. + """ + + def test_every_allowed_consumer_can_connect(self) -> None: + roles_root = PROJECT_ROOT / "roles" + if not roles_root.is_dir(): + self.skipTest("no roles/ directory") + + blocks: dict[str, Mapping] = {} + for role_dir in sorted(p for p in roles_root.iterdir() if p.is_dir()): + mcp_path = role_dir / ROLE_FILE_META_MCP + if not mcp_path.is_file(): + continue + mcp = load_yaml_any(str(mcp_path), default_if_missing={}) + if isinstance(mcp, Mapping): + blocks[role_dir.name] = mcp + + services_by_role = _services_by_role() + errors: list[str] = [] + for role, mcp in blocks.items(): + if mcp.get("direction") not in MCP_SERVER_DIRECTIONS: + continue + transport = mcp.get("transport") + auth = mcp.get("auth") + for consumer in derive_allowed_consumers(role, services_by_role): + client = blocks.get(consumer) + if client is None: + continue + if transport not in (client.get("supported_transports") or []): + errors.append( + f"{role} admits {consumer}, but speaks {transport!r} " + f"and {consumer} speaks " + f"{client.get('supported_transports')}" + ) + if auth not in (client.get("supported_auths") or []): + errors.append( + f"{role} admits {consumer}, but authenticates with " + f"{auth!r} and {consumer} can present " + f"{client.get('supported_auths')}" + ) + + if errors: + self.fail( + f"incompatible MCP provider/consumer pairs ({len(errors)}):\n" + + "\n".join(f" - {e}" for e in sorted(errors)) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_secret_not_in_playwright.py b/tests/lint/ansible/services/test_mcp_secret_not_in_playwright.py new file mode 100644 index 0000000000..3cb519e1ca --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_secret_not_in_playwright.py @@ -0,0 +1,106 @@ +"""Lint: no MCP credential reaches a Playwright run. + +Playwright keeps a trace of every run it is told to retain, and a value handed +to the browser through ``playwright.env.j2`` is in it: request headers, the +environment dump, the network log. A provider bearer that lands there survives +in a CI artifact long after the deploy that minted it, readable by anyone who +can download the bundle. + +The test suite already respects this. The authenticated MCP contract check is a +CLI test rather than a spec precisely because the spec would capture the bearer, +and the guest specs ask the anonymous question, which needs no credential at +all. This rule keeps that arrangement from eroding one convenient environment +variable at a time. + +Secret URL components count the same: a provider whose endpoint path carries a +generated key hands out a working URL, not merely a hint. + +An application's own login password is a different thing and stays allowed; the +personas need it, and it grants the caller's own rights rather than the +deployment's provider identity. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-secret-not-in-playwright`` on the offending line or the + non-empty line above it. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content + +from . import PROJECT_ROOT + +_RULE = "mcp-secret-not-in-playwright" +_ENV_TEMPLATE = "templates/playwright.env.j2" + +_MCP_SECRET = re.compile( + r"lookup\(\s*['\"]mcp_credential['\"]" + r"|secrets\.credentials\.mcp_" + r"|mcp\.credential\b" + r"|key_credential", +) + + +def _playwright_envs() -> list[tuple[str, str]]: + roles_prefix = str(PROJECT_ROOT / "roles") + "/" + return [ + (path, content) + for path, content in iter_project_files_with_content( + extensions=(".j2",), exclude_tests=True + ) + if path.startswith(roles_prefix) and path.endswith(_ENV_TEMPLATE) + ] + + +class TestMcpSecretNotInPlaywright(unittest.TestCase): + def test_no_playwright_env_renders_an_mcp_secret(self) -> None: + findings: list[str] = [] + for path, content in _playwright_envs(): + lines = content.splitlines() + for idx, line in enumerate(lines): + if not _MCP_SECRET.search(line): + continue + if is_suppressed_at(lines, idx + 1, _RULE, mode="same-or-above"): + continue + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + findings.append(f"{rel}:{idx + 1}: {line.strip()}") + + self.assertEqual( + [], + sorted(findings), + f"MCP credential(s) handed to a Playwright run ({len(findings)}); " + f"the trace outlives the deploy and travels in the CI artifact:\n" + + "\n".join(f" - {f}" for f in sorted(findings)), + ) + + def test_the_scan_reads_playwright_env_templates(self) -> None: + self.assertTrue( + _playwright_envs(), + f"no role ships a {_ENV_TEMPLATE}, so the rule would pass " + "vacuously; check that the scan still reads the right topic", + ) + + def test_the_pattern_matches_a_real_credential_reference(self) -> None: + """A pattern that matches nothing anywhere would pass silently.""" + matched = any( + _MCP_SECRET.search(content) + for _path, content in iter_project_files_with_content( + extensions=(".yml", ".j2"), exclude_tests=True + ) + ) + self.assertTrue( + matched, + "the MCP-secret pattern matches nothing in the repository, so the " + "rule cannot be distinguishing anything; check that the credential " + "lookup is still spelled the way this pattern expects", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_secrets_are_masked.py b/tests/lint/ansible/services/test_mcp_secrets_are_masked.py new file mode 100644 index 0000000000..70d05558bc --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_secrets_are_masked.py @@ -0,0 +1,113 @@ +"""Lint: an MCP task that prints cannot carry a secret unmasked. + +Ansible echoes a command module's arguments and its shell environment once the +run is verbose, which is how a provisioning password ends up in a deploy log +verbatim. A task only leaks if it does both things: handle a secret value and +produce output Ansible prints. A ``set_fact`` or an include that forwards a +variable prints nothing at default verbosity. + +Masking is satisfied by ``no_log`` or, for modules that mask their own payload, +``mask_values``. Both are expected to reference ``MASK_CREDENTIALS_IN_LOGS`` +rather than a literal, which ``tests/lint/ansible/modules/test_no_literal_no_log.py`` +enforces separately. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-secret-masking`` on, or directly above, the task's ``- name:``. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content + +_RULE = "mcp-secret-masking" + +_SECRET_RE = re.compile( + r"token|password|bearer|api_key|secret|credential|authoriz|auth_header", + re.IGNORECASE, +) +_PRINTS_RE = re.compile( + r"ansible\.builtin\.(command|shell|uri|debug)|" + r"^\s+(command|shell|uri|debug):|register:", + re.MULTILINE, +) +_MASKED_RE = re.compile(r"^\s+(no_log|mask_values)\s*:", re.MULTILINE) + + +def _mcp_task_files() -> list[tuple[str, str]]: + """Return ``(path, content)`` for every MCP task file under ``roles/``.""" + files = [] + for path, content in iter_project_files_with_content(extensions=(".yml",)): + parts = Path(path).parts + if "roles" not in parts or "tasks" not in parts: + continue + if "mcp" not in Path(path).stem and not any("mcp" in part for part in parts): + continue + files.append((path, content)) + return files + + +def unmasked_secret_tasks() -> list[str]: + """Return one finding per printing MCP task that carries a secret unmasked.""" + findings = [] + for path, content in _mcp_task_files(): + lines = content.splitlines() + offset = 0 + for block in re.split(r"^(?=- name:)", content, flags=re.MULTILINE): + start = offset + offset += block.count("\n") + if not block.startswith("- name:"): + continue + if not _SECRET_RE.search(block) or not _PRINTS_RE.search(block): + continue + if _MASKED_RE.search(block): + continue + if is_suppressed_at(lines, start + 1, _RULE): + continue + findings.append( + f"{path}:{start + 1}: {block.splitlines()[0][8:70]} handles a " + f"secret and prints, but carries neither no_log nor mask_values" + ) + return findings + + +class TestMcpSecretsAreMasked(unittest.TestCase): + def test_no_printing_mcp_task_carries_a_secret_unmasked(self) -> None: + findings = unmasked_secret_tasks() + self.assertEqual( + [], + findings, + f"MCP task(s) that can print a secret ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + def test_the_scan_reaches_the_mcp_task_files(self) -> None: + self.assertTrue( + _mcp_task_files(), + "no MCP task file was scanned, so the rule would pass vacuously", + ) + + def test_the_scan_reaches_the_adapter_that_holds_every_provider_credential( + self, + ) -> None: + """The non-empty guard above passed while this role was invisible. + + `svc-ai-mcp-adapter` is the one role whose whole job is handling other + roles' MCP credentials, and its directory name contains `mcp` without + being equal to it, so a membership test over the path parts skipped it + and the provider roles kept the scan looking populated. + """ + scanned = {path for path, _ in _mcp_task_files()} + self.assertTrue( + any("svc-ai-mcp-adapter/tasks/" in path for path in scanned), + "svc-ai-mcp-adapter task files are outside the scan", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_server_rbac_role.py b/tests/lint/ansible/services/test_mcp_server_rbac_role.py new file mode 100644 index 0000000000..edff2df04c --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_server_rbac_role.py @@ -0,0 +1,85 @@ +"""Lint: a served MCP surface has an application-scoped role to grant. + +Every client grant resolves to the group named after one role: the provider's +own ``mcp`` RBAC role. A provider that serves without declaring it leaves the +client nothing to scope access to, and the fallback is not "nobody" โ€” Open WebUI +reads an empty grant as every administrator, which is wider than the group was +ever meant to be. + +The role has to be application-scoped rather than a shared ``mcp`` name, which +``utils/roles/rbac/scoped.py`` enforces from the other side: a role listed in +``APPLICATION_SCOPED_ROLES`` grants nothing when declared unscoped, so the +declaration here is what a user's ``application_roles`` entry points at. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-server-rbac-role`` in the head of the role's ``meta/mcp.yml``. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_MCP, ROLE_FILE_META_RBAC +from utils.roles.rbac.scoped import MCP_LEGACY_ROLE + +from . import PROJECT_ROOT + +_RULE = "mcp-server-rbac-role" +_SERVER_DIRECTIONS = frozenset({"server", "both"}) + + +def _server_roles() -> list[str]: + """Return the roles that serve MCP to a client.""" + roles: list[str] = [] + for mcp_path in sorted(Path(PROJECT_ROOT, "roles").glob(f"*/{ROLE_FILE_META_MCP}")): + mcp = load_yaml_any(str(mcp_path), default_if_missing={}) + if not isinstance(mcp, Mapping): + continue + if str(mcp.get("direction") or "").strip().lower() not in _SERVER_DIRECTIONS: + continue + if is_suppressed_in_head(read_text(str(mcp_path)).splitlines(), _RULE): + continue + roles.append(mcp_path.parent.parent.name) + return roles + + +def _declares_mcp_role(role: str) -> bool: + rbac = load_yaml_any( + str(PROJECT_ROOT / "roles" / role / ROLE_FILE_META_RBAC), default_if_missing={} + ) + declared = (rbac or {}).get("roles") + return isinstance(declared, Mapping) and MCP_LEGACY_ROLE in declared + + +class TestMcpServerRbacRole(unittest.TestCase): + def test_every_served_surface_declares_its_own_mcp_role(self) -> None: + missing = [ + f"{role}: serves MCP but declares no '{MCP_LEGACY_ROLE}' role in " + f"{ROLE_FILE_META_RBAC}, so a client grant has no group to name and " + f"an empty grant reads as every administrator" + for role in _server_roles() + if not _declares_mcp_role(role) + ] + self.assertEqual( + [], + missing, + f"served MCP surface(s) without an application-scoped role " + f"({len(missing)}):\n" + "\n".join(f" - {m}" for m in missing), + ) + + def test_the_scan_finds_served_surfaces(self) -> None: + self.assertTrue( + _server_roles(), + "no role serves MCP, so the rule would pass vacuously; check that " + "the scan still reads the right topic", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_mcp_tool_surface.py b/tests/lint/ansible/services/test_mcp_tool_surface.py new file mode 100644 index 0000000000..3038174513 --- /dev/null +++ b/tests/lint/ansible/services/test_mcp_tool_surface.py @@ -0,0 +1,128 @@ +"""The tool surface ``meta/mcp.yml`` declares matches the contract that ships. + +The adapter derives what it serves from ``files/mcp/tools.json`` alone: +``policy.listed_tools`` is ``sorted(contract["tools"])`` and the rendered +contract carries no allowlist at all. Everything in ``meta/mcp.yml`` is +therefore a declaration that nothing recomputes - the same shape as the pinned +digests, which had silently drifted in ten of twelve roles before a check +existed. Reviewers, the requirement documents and the authorization metadata +read the declaration; the running adapter reads the file. + +Three relations, deliberately not all equalities: + +* ``tools.allowlist`` equals the shipped tool names. A name only in the + declaration promises a tool no client can call; a name only in the file + serves one the platform never approved. +* ``tools.writer_allowlist`` is a superset of the allowlist, never an equality: + a writer surface names tools that cannot ship while mutations are off, + because ``passthrough.py`` rejects the whole contract at load time as soon as + one tool declares ``mutating: true`` against ``mutating_tools_enabled: false``. +* ``tools.upstream_serves``, where stated, contains the allowlist. Allowing a + tool the upstream never offered fails at first use, not at deploy. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-tool-surface`` on, or directly above, the declaring line. +""" + +from __future__ import annotations + +import json +import unittest + +from utils.annotations.suppress import is_suppressed_for_key +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +_RULE = "mcp-tool-surface" +_CONTRACT_RELATIVE = "files/mcp/tools.json" + + +def _names(value: object) -> set[str] | None: + """Return the declared names, or ``None`` when the key is absent.""" + if not isinstance(value, list): + return None + return {str(item) for item in value} + + +def _shipped_tools(path) -> set[str]: + """Return the tool names the contract file ships.""" + parsed = json.loads(read_text(str(path))) + tools = parsed.get("tools", parsed) if isinstance(parsed, dict) else {} + return set(tools) if isinstance(tools, dict) else set() + + +class TestMcpToolSurface(unittest.TestCase): + def test_declared_surface_matches_the_shipped_contract(self) -> None: + roles_root = PROJECT_ROOT / "roles" + if not roles_root.is_dir(): + self.skipTest("no roles/ directory") + + offenders: list[str] = [] + checked = 0 + for mcp_path in sorted(roles_root.glob(f"*/{ROLE_FILE_META_MCP}")): + mcp = load_yaml_any(str(mcp_path), default_if_missing={}) or {} + tools_block = mcp.get("tools") + if not isinstance(tools_block, dict): + continue + + role = mcp_path.parent.parent + contract_path = role / _CONTRACT_RELATIVE + allowlist = _names(tools_block.get("allowlist")) + if allowlist is None or not contract_path.is_file(): + continue + + lines = read_text(str(mcp_path)).splitlines() + shipped = _shipped_tools(contract_path) + checked += 1 + + if allowlist != shipped and not is_suppressed_for_key( + lines, "allowlist", _RULE + ): + only_declared = sorted(allowlist - shipped) + only_shipped = sorted(shipped - allowlist) + offenders.append( + f"{role.name}: tools.allowlist and {_CONTRACT_RELATIVE} " + f"disagree; declared only {only_declared}, shipped only " + f"{only_shipped}" + ) + + writers = _names(tools_block.get("writer_allowlist")) + if ( + writers is not None + and not allowlist <= writers + and not is_suppressed_for_key(lines, "writer_allowlist", _RULE) + ): + offenders.append( + f"{role.name}: tools.writer_allowlist omits " + f"{sorted(allowlist - writers)}, so a writer would reach " + f"less than a reader" + ) + + serves = _names(tools_block.get("upstream_serves")) + if ( + serves is not None + and not allowlist <= serves + and not is_suppressed_for_key(lines, "upstream_serves", _RULE) + ): + offenders.append( + f"{role.name}: tools.allowlist names " + f"{sorted(allowlist - serves)}, which tools.upstream_serves " + f"does not report as offered" + ) + + self.assertEqual( + [], + offenders, + f"declared tool surface diverges from the contract ({len(offenders)}):\n" + + "\n".join(f" - {o}" for o in offenders), + ) + self.assertTrue( + checked, + "no role declares a tool allowlist next to a shipped contract, so " + "the rule would pass vacuously; check that the scan still reads the " + "right topic", + ) diff --git a/tests/lint/ansible/services/test_no_placement_manager_with_sandbox.py b/tests/lint/ansible/services/test_no_placement_manager_with_sandbox.py new file mode 100644 index 0000000000..387ad4e5fa --- /dev/null +++ b/tests/lint/ansible/services/test_no_placement_manager_with_sandbox.py @@ -0,0 +1,105 @@ +"""Forbid ``placement: manager`` in a role that also enables the kata sandbox. + +Rationale +========= +``roles/sys-svc-container/templates/deploy.yml.j2`` appends both constraints to +the same ``_constraints`` list, which swarm evaluates as a conjunction: + +* ``node.role == manager`` when the role appears in ``roles_with_placement`` + (``:11-13``), which any ``placement: manager`` in its ``meta/services.yml`` + triggers, for every service of that role. +* ``node.labels. == true`` when + ``services.kata.enabled`` is truthy (``:18-20``), again role-wide. + +``roles/svc-virt-kata/tasks/00_core.yml:62-70`` adds that label only +``when: not (IS_STACK_HOST | bool)``, so the manager never carries it. The two +constraints therefore have an empty intersection and the service becomes +unschedulable: the deploy does not fail at ``docker stack deploy`` but hangs in +the converge wait, which reads as a timeout rather than as a placement error. + +Per-line opt-out +================ +Add ``# nocheck: sandbox-placement-manager`` on the same line as +``placement: manager`` OR on the immediately preceding non-empty line, together +with a comment explaining how the manager is expected to obtain the sandbox +label. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content +from utils.cache.yaml import load_yaml_str + +from . import PROJECT_ROOT + +_RULE = "sandbox-placement-manager" + +_PLACEMENT_MANAGER = re.compile(r"^\s*placement\s*:\s*['\"]?manager['\"]?\s*(?:#.*)?$") + + +def _is_scan_target(rel_path: str) -> bool: + return ( + rel_path.startswith("roles/") + and "/meta/" in rel_path + and rel_path.endswith("services.yml") + ) + + +def _kata_is_enabled(content: str) -> bool: + """True only for a literal ``true``; a template is not statically decidable.""" + try: + data = load_yaml_str(content) + except Exception: + return False + if not isinstance(data, dict): + return False + kata = data.get("kata") + return isinstance(kata, dict) and kata.get("enabled") is True + + +class TestNoPlacementManagerWithSandbox(unittest.TestCase): + def test_a_sandboxed_role_is_never_pinned_to_the_manager(self) -> None: + findings: list[tuple[str, int, str]] = [] + for path_str, content in iter_project_files_with_content( + extensions=(".yml", ".yaml"), + exclude_tests=True, + ): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + if not _is_scan_target(rel) or not _kata_is_enabled(content): + continue + lines = content.splitlines() + for idx, line in enumerate(lines): + if not _PLACEMENT_MANAGER.match(line): + continue + if is_suppressed_at(lines, idx + 1, _RULE, mode="same-or-above"): + continue + findings.append((rel, idx + 1, line.strip())) + + if findings: + formatted = "\n".join( + f"- {p}:{n}: {s}" + for p, n, s in sorted(set(findings), key=lambda i: (i[0], i[1])) + ) + self.fail( + "Found `placement: manager` in a role whose `meta/services.yml` " + "also sets `kata.enabled: true`. Both add a constraint to the " + "same list in roles/sys-svc-container/templates/deploy.yml.j2, " + "swarm ANDs them, and roles/svc-virt-kata/tasks/00_core.yml " + "never labels the stack host, so no node can satisfy both. The " + "service does not fail to deploy, it fails to schedule and the " + "round dies in the converge wait.\n\n" + "Default: drop the pin. A sandboxed workload belongs on a " + "labelled worker; if it has to reach a manager-local resource, " + "delegate that step to the owning node instead of pinning the " + "whole service.\n\n" + f"Offenders:\n{formatted}" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_onion_port_flag.py b/tests/lint/ansible/services/test_onion_port_flag.py new file mode 100644 index 0000000000..04b839edc6 --- /dev/null +++ b/tests/lint/ansible/services/test_onion_port_flag.py @@ -0,0 +1,235 @@ +"""Lint: every host-bound port states whether it answers on the node onion. + +A port under ``ports.local`` or ``ports.public`` binds an address on the stack +host, which is what a ``HiddenServicePort`` can forward to. Whether it should be +forwarded is a decision with a cost in both directions: silently off leaves a +service unreachable that the operator believes is on the onion, and silently on +publishes a database, an admin interface or a SOCKS proxy to everyone holding +the onion address. Neither belongs to a default, so the flag is mandatory and +every ``false`` carries the reason it is false. + +The flag lives next to the numbers it decides about:: + + ports: + public: + smtp: 25 + smtps: 465 + onion: + smtp: true + smtps: false # nocheck: onion-flag no implicit-TLS listener when TLS is off + +Five groups are out of scope, because for them the answer is architectural +rather than per-role, and a hundred-odd copies of one sentence state it worse +than this paragraph does: + +* ``ports.internal`` lives in the container's network namespace, where no + host-side forward reaches it. +* the categories a hidden service cannot carry, listed and reasoned once in + ``plugins.lookup.tor_ports.UDP_ONLY_CATEGORIES``. +* ``http``, ``sso`` and ``websocket``, because the node onion already forwards + port 80 to the reverse proxy, which routes every vhost, every oauth2 hop and + every socket upgrade behind it. A direct forward there would bypass the proxy, + its auth and its CSP. +* the implicit-TLS variants, because Tor is already the transport encryption and + ``container_ports`` drops those listeners entirely when TLS is off, which an + onion deployment always is. +* an entity declaring ``exposed:``, which is the older opt-in for the same + decision and is tested per variant. Two flags for one decision is the trap. + +A flag naming a category the entity never declares is reported too: it reads as +a live forward and forwards nothing. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: onion-flag`` plus a reason, on or directly above a ``false`` flag. +""" + +from __future__ import annotations + +import re +import unittest +from collections.abc import Mapping + +from plugins.lookup.tor_ports import UDP_ONLY_CATEGORIES +from utils.annotations.suppress import line_has_rule +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.meta.scan import iter_role_dirs +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +_RULE = "onion-flag" +_HOST_BOUND_SCOPES = ("local", "public") +_PROXY_FRONTED_CATEGORIES = frozenset({"http", "sso", "websocket"}) +_IMPLICIT_TLS_CATEGORIES = frozenset({"smtps", "imaps", "pop3s", "ldaps"}) +_OUT_OF_SCOPE = ( + UDP_ONLY_CATEGORIES | _PROXY_FRONTED_CATEGORIES | _IMPLICIT_TLS_CATEGORIES +) +_MIN_REASON_CHARS = 10 + +_MARKER_RE = re.compile( + r"(?:noqa|nocheck)\s*:\s*" + r"(?:[a-z0-9][a-z0-9\-]*)(?:\s*,\s*[a-z0-9][a-z0-9\-]*)*(.*)$", + re.IGNORECASE, +) + + +def _host_bound_categories(ports: Mapping) -> set[str]: + """Category names of *ports* that bind a host address as a single TCP port. + + The proxy-fronted categories are skipped under ``local`` and kept under + ``public``, which is the difference between riding behind the edge proxy and + being it: 128 roles declare ``http``/``sso``/``websocket`` on the loopback, + and exactly one publishes ``http`` on the host. + """ + found: set[str] = set() + for scope in _HOST_BOUND_SCOPES: + declared = ports.get(scope) + if not isinstance(declared, Mapping): + continue + skipped = UDP_ONLY_CATEGORIES | _IMPLICIT_TLS_CATEGORIES + if scope == "local": + skipped = skipped | _PROXY_FRONTED_CATEGORIES + found.update( + category + for category, value in declared.items() + if isinstance(value, int) + and not isinstance(value, bool) + and category not in skipped + ) + return found + + +def _flag_line(lines: list[str], entity: str, category: str) -> int | None: + """1-based line of ``:`` inside *entity*'s ``onion:`` block.""" + in_entity = False + onion_indent = -1 + for number, raw in enumerate(lines, start=1): + stripped = raw.strip() + if not stripped or stripped.startswith("#"): + continue + indent = len(raw) - len(raw.lstrip()) + if indent == 0: + in_entity = stripped.startswith(f"{entity}:") + onion_indent = -1 + continue + if not in_entity: + continue + if onion_indent >= 0 and indent <= onion_indent: + onion_indent = -1 + if stripped.startswith("onion:"): + onion_indent = indent + continue + if onion_indent >= 0 and stripped.startswith(f"{category}:"): + return number + return None + + +def _reason_for(lines: list[str], line_no: int) -> str | None: + """The suppression reason governing *line_no*, or None when unsuppressed.""" + candidates = [line_no - 1] + previous = line_no - 2 + while previous >= 0 and not lines[previous].strip(): + previous -= 1 + candidates.append(previous) + for index in candidates: + if index < 0 or not line_has_rule(lines[index], _RULE): + continue + match = _MARKER_RE.search(lines[index]) + return match.group(1).strip().lstrip("-:").strip() if match else "" + return None + + +class TestOnionPortFlag(unittest.TestCase): + def test_every_host_bound_port_declares_an_onion_flag(self) -> None: + findings: list[str] = [] + for role_dir in iter_role_dirs(): + path = role_dir / ROLE_FILE_META_SERVICES + if not path.is_file(): + continue + services = load_yaml_any(str(path), default_if_missing={}) + if not isinstance(services, Mapping): + continue + lines = read_text(str(path)).splitlines() + for entity, config in services.items(): + if not isinstance(config, Mapping): + continue + ports = config.get("ports") + if not isinstance(ports, Mapping) or "exposed" in config: + continue + findings.extend( + self._entity_findings(role_dir.name, entity, ports, lines) + ) + if findings: + self.fail( + "Every host-bound port must state whether it answers on the node " + "onion, via a boolean of the same category name under " + "`ports.onion`. A `false` flag needs `# nocheck: onion-flag` and " + "a reason on or above it.\n" + "\n".join(findings) + ) + + def _entity_findings( + self, + role: str, + entity: str, + ports: Mapping, + lines: list[str], + ) -> list[str]: + declared = _host_bound_categories(ports) + flags = ports.get("onion") + flags = flags if isinstance(flags, Mapping) else {} + where = f"roles/{role}/{ROLE_FILE_META_SERVICES}: {entity}" + findings = [ + f"{where}.ports.onion.{category}: missing, declare true or false" + for category in sorted(declared - set(flags)) + ] + findings.extend( + f"{where}.ports.onion.{category}: " + + ( + "out of scope, remove the flag" + if category in _OUT_OF_SCOPE + else "no such port is declared under " + " or ".join(_HOST_BOUND_SCOPES) + ) + for category in sorted(set(flags) - declared) + ) + for category in sorted(set(flags) & declared): + findings.extend( + self._flag_findings(where, entity, category, flags[category], lines) + ) + return findings + + def _flag_findings( + self, + where: str, + entity: str, + category: str, + flag: object, + lines: list[str], + ) -> list[str]: + at = f"{where}.ports.onion.{category}" + if not isinstance(flag, bool): + return [f"{at}: must be a literal true or false, not {flag!r}"] + if flag: + return [] + line_no = _flag_line(lines, entity, category) + if line_no is None: + return [f"{at}: is false but its line could not be located"] + reason = _reason_for(lines, line_no) + if reason is None: + return [ + ( + f"{at} (line {line_no}): false needs `# nocheck: {_RULE}` and " + f"a reason on or above it" + ) + ] + if len(reason) < _MIN_REASON_CHARS: + return [ + ( + f"{at} (line {line_no}): `# nocheck: {_RULE}` states no reason " + f"why the port stays off the onion" + ) + ] + return [] + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_robot_admission_guard.py b/tests/lint/ansible/services/test_robot_admission_guard.py new file mode 100644 index 0000000000..7fbdbc4799 --- /dev/null +++ b/tests/lint/ansible/services/test_robot_admission_guard.py @@ -0,0 +1,98 @@ +"""Lint: every embodiable agent runs the robot admission guard before deploying. + +``svc-ai-robot`` hands an agent direct hardware access, so its admission checks +refuse a blanket device grant and refuse a host that carries other tenants. The +checks cannot live in ``svc-ai-robot``'s own tasks โ€” the agent is a shared +service that ``sys-service-loader`` preloads a stage earlier โ€” so each agent +role includes them itself. An agent that forgets the include deploys privileged +onto a shared node and nothing says a word. + +The scan derives the agent set from ``svc-ai-robot``'s own service flags rather +than from a list, so a third agent added there fails here until it carries the +guard. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: robot-admission-guard`` on the flag's key line or the non-empty + line above it. +""" + +from __future__ import annotations + +import os +import re +import unittest +from collections.abc import Mapping + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content, read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +_RULE = "robot-admission-guard" +_ROBOT_ROLE = "svc-ai-robot" +_GUARD = "roles/svc-ai-robot/tasks/utils/admit.yml" + +_AGENT_FLAG = re.compile(r"'(?Pweb-app-[a-z0-9-]+)'\s+in\s+group_names") + + +def _embodiable_roles() -> dict[str, str]: + """Return ``{agent role id: flag name}`` for every embodiable agent.""" + services_path = PROJECT_ROOT / "roles" / _ROBOT_ROLE / ROLE_FILE_META_SERVICES + services = load_yaml_any(str(services_path), default_if_missing={}) + lines = read_text(str(services_path)).splitlines() + agents: dict[str, str] = {} + if not isinstance(services, Mapping): + return agents + for flag, block in services.items(): + if not isinstance(block, Mapping): + continue + match = _AGENT_FLAG.search(str(block.get("enabled") or "")) + if not match: + continue + line_no = next( + (i + 1 for i, line in enumerate(lines) if line.startswith(f"{flag}:")), + 1, + ) + if is_suppressed_at(lines, line_no, _RULE, mode="same-or-above"): + continue + agents[match["role"]] = flag + return agents + + +def _includes_guard(role: str) -> bool: + tasks_dir = str(PROJECT_ROOT / "roles" / role / "tasks") + os.sep + return any( + path.startswith(tasks_dir) and _GUARD in content + for path, content in iter_project_files_with_content(extensions=(".yml",)) + ) + + +class TestRobotAdmissionGuard(unittest.TestCase): + def test_every_embodiable_agent_includes_the_guard(self) -> None: + missing = [ + f"{role} (flag '{flag}'): {_ROBOT_ROLE} can embody it but no task " + f"includes {_GUARD}, so it would take privileged hardware access " + f"without the single-tenant and device-allowlist checks" + for role, flag in sorted(_embodiable_roles().items()) + if not _includes_guard(role) + ] + self.assertEqual( + [], + missing, + f"embodiable agent(s) without the admission guard ({len(missing)}):\n" + + "\n".join(f" - {m}" for m in missing), + ) + + def test_the_scan_finds_embodiable_agents(self) -> None: + self.assertTrue( + _embodiable_roles(), + f"{_ROBOT_ROLE} declares no web-app agent flag, so the rule would " + "pass vacuously; check that the scan still reads the right topic", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_sandboxed_no_host_socket.py b/tests/lint/ansible/services/test_sandboxed_no_host_socket.py new file mode 100644 index 0000000000..30cd38ec05 --- /dev/null +++ b/tests/lint/ansible/services/test_sandboxed_no_host_socket.py @@ -0,0 +1,91 @@ +"""Lint: a sandboxed workload never gets the host container socket. + +A role that pins ``SANDBOX_RUNTIME`` on its service does so because it executes +code a model wrote. Handing that container ``/var/run/docker.sock`` gives it the +host daemon, which can start a privileged container on the host kernel โ€” the +isolating runtime is then decoration, and the deploy stays green while the +sandbox is gone. + +The scan derives the sandboxed set from the templates that pin the runtime, so +a third agent added later is covered without touching this file. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: sandboxed-no-host-socket`` on the offending line or the + non-empty line above it. +""" + +from __future__ import annotations + +import os +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content + +from . import PROJECT_ROOT + +_RULE = "sandboxed-no-host-socket" +_RUNTIME_PIN = "SANDBOX_RUNTIME" +_HOST_SOCKET = "/var/run/docker.sock" +_RUNTIME_OWNER = "sys-svc-container" + + +def _role_of(path: str) -> str | None: + roles_prefix = str(PROJECT_ROOT / "roles") + os.sep + if not path.startswith(roles_prefix): + return None + return path[len(roles_prefix) :].split(os.sep, 1)[0] + + +def _sandboxed_roles() -> set[str]: + """Return the roles whose own templates pin the sandbox runtime.""" + roles: set[str] = set() + for path, content in iter_project_files_with_content( + extensions=(".j2",), exclude_tests=True + ): + role = _role_of(path) + if role is None or role == _RUNTIME_OWNER: + continue + if "/templates/" in Path(path).as_posix() and _RUNTIME_PIN in content: + roles.add(role) + return roles + + +class TestSandboxedNoHostSocket(unittest.TestCase): + def test_no_sandboxed_role_mounts_the_host_socket(self) -> None: + sandboxed = _sandboxed_roles() + findings: list[str] = [] + for path, content in iter_project_files_with_content(exclude_tests=True): + role = _role_of(path) + if role not in sandboxed: + continue + lines = content.splitlines() + for idx, line in enumerate(lines): + if _HOST_SOCKET not in line: + continue + if is_suppressed_at(lines, idx + 1, _RULE, mode="same-or-above"): + continue + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + findings.append(f"{rel}:{idx + 1}: {line.strip()}") + + self.assertEqual( + [], + sorted(findings), + f"sandboxed role(s) reaching the host container socket " + f"({len(findings)}); the isolating runtime cannot contain a " + f"container that can drive the host daemon:\n" + + "\n".join(f" - {f}" for f in sorted(findings)), + ) + + def test_the_scan_finds_sandboxed_roles(self) -> None: + self.assertTrue( + _sandboxed_roles(), + f"no role template pins {_RUNTIME_PIN}, so the rule would pass " + "vacuously; check that the scan still reads the right topic", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/services/test_semver_pinning.py b/tests/lint/ansible/services/test_semver_pinning.py index 07e1df230e..c09544eda9 100644 --- a/tests/lint/ansible/services/test_semver_pinning.py +++ b/tests/lint/ansible/services/test_semver_pinning.py @@ -59,6 +59,7 @@ from utils.annotations.message import warning as gha_warning from utils.annotations.suppress import is_suppressed_at from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any +from utils.docker.image.pin import is_digest from utils.roles.mapping import ROLE_FILE_META_SERVICES from utils.update.base import is_semver @@ -69,6 +70,7 @@ if TYPE_CHECKING: _DOCKER_RULE = "docker-version" +_DIGEST_RULE = "docker-digest" _REPO_RULE = "repository-version" _DOCKER_TITLE = "Non-semver Docker image version" @@ -176,7 +178,7 @@ class TestSemverPinning(unittest.TestCase): line_no = _locate_value_line( lines, "version", value, used_version_lines ) - rule = _DOCKER_RULE + rule = _DIGEST_RULE if is_digest(value) else _DOCKER_RULE title = _DOCKER_TITLE category: type[Warning] = NonSemverImageVersionWarning key_label = "version" @@ -208,10 +210,10 @@ class TestSemverPinning(unittest.TestCase): if findings_emitted: print( - "\n๐Ÿ’ก Non-semver pins: suppress with " - "'# nocheck: docker-version' (above or on the `version:` line) " - "or '# nocheck: repository-version' (above or on the `ref:` " - "line) when the non-semver pin is intentional.", + "\n๐Ÿ’ก Non-semver pins: a digest is the preferred fallback and " + "declares itself with '# nocheck: docker-digest'; a general " + "tag uses '# nocheck: docker-version' and a general git ref " + "'# nocheck: repository-version', above or on the pinned line.", flush=True, ) diff --git a/tests/lint/ansible/services/test_service_guard_spot.py b/tests/lint/ansible/services/test_service_guard_spot.py new file mode 100644 index 0000000000..e42448bfc2 --- /dev/null +++ b/tests/lint/ansible/services/test_service_guard_spot.py @@ -0,0 +1,186 @@ +"""Lint: a compose service block is switched by its own services entry. + +``meta/services.yml`` is the single place that says whether a service is part +of a deployment. A ``compose.yml.j2`` that wraps a service key in +``{% if | bool %}`` therefore has to reach that entry, or the template +and the declaration become two switches for one container and drift apart: +the resource model, the README graph and the network layer read the entry +while the container follows something else. + +The reference is not required on the guard itself. A role may name the +condition once in ``vars/`` and reuse it, so the chain is followed through +every variable the guard mentions, and one link in it must resolve the state +through ``lookup('config', โ€ฆ, 'services..enabled')``. + +The chain also runs through config: a value that reads another topic is +followed into the resolved application config and on from there. Nextcloud +reaches its Talk entry that way, over ``addons.spreed.enabled``, and a +resolver that stopped at the role's variables would call that a bypass. + +Scope +----- + +Only guards indented by at most two spaces are checked. That is the +indentation of a compose service key, so a deeper guard selects content +inside a service (a network, an environment line) rather than the service +itself, and its state is the surrounding block's business. + +Variables are resolved from the role's own ``vars/`` and ``defaults/``. A +guard whose variable is built somewhere else, a ``set_fact`` for instance, +cannot be followed here and needs the suppression. + +Suppression +----------- + +``# nocheck: service-guard-spot`` on the guard line in the template. +""" + +from __future__ import annotations + +import re +import unittest +from collections.abc import Mapping +from typing import TYPE_CHECKING + +from utils.annotations.suppress import line_has_rule +from utils.cache.applications import get_application_defaults +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from pathlib import Path + +_RULE = "service-guard-spot" + +ROLES_DIR = PROJECT_ROOT / "roles" + +_TEMPLATE_REL = "templates/compose.yml.j2" # nocheck: role-file-spot +_VAR_DIRS = ("vars", "defaults") +_SERVICE_KEY_INDENT = 2 + +_GUARD_RE = re.compile(r"^(\s*)\{%-?\s*if\s+([A-Z][A-Z0-9_]*)\s*\|\s*bool\s*-?%\}") +_DEFINITION_RE = re.compile(r"^([A-Z][A-Z0-9_]*):\s*(.*)$") +_REFERENCE_RE = re.compile(r"[A-Z][A-Z0-9_]{2,}") +_CONFIG_PATH_RE = re.compile( + r"lookup\(\s*['\"]config['\"]\s*,[^,]+,\s*['\"]([A-Za-z0-9_.\-]+)['\"]" +) +_SPOT_RE = re.compile(r"^services\.[A-Za-z0-9_.\-]+\.enabled$") + + +def _definitions(role_dir: Path) -> dict[str, str]: + """Return ``{VAR: raw definition}`` for one role's variable files. + + Args: + role_dir: the role directory to scan. + """ + definitions: dict[str, str] = {} + for var_dir in _VAR_DIRS: + for path in sorted((role_dir / var_dir).glob("*.yml")): + for line in read_text(str(path)).splitlines(): + match = _DEFINITION_RE.match(line) + if match: + definitions[match.group(1)] = match.group(2) + return definitions + + +def _config_value(config: Mapping, path: str) -> str: + """Return the raw value at a dotted config path, or "" when absent. + + Args: + config: the role's resolved application config. + path: a dotted path such as ``addons.spreed.enabled``. + """ + value: object = config + for part in path.split("."): + if not isinstance(value, Mapping) or part not in value: + return "" + value = value[part] + return str(value) + + +def _reaches_the_spot(var: str, definitions: dict[str, str], config: Mapping) -> bool: + """Return whether ``var``'s definition chain reads a services entry. + + Args: + var: the variable named by the guard. + definitions: the role's ``{VAR: raw definition}`` mapping. + config: the role's resolved application config, for config hops. + """ + seen: set[str] = set() + pending = [definitions.get(var, "")] + while pending: + definition = pending.pop() + for path in _CONFIG_PATH_RE.findall(definition): + if _SPOT_RE.match(path): + return True + if path in seen: + continue + seen.add(path) + pending.append(_config_value(config, path)) + for name in _REFERENCE_RE.findall(definition): + if name in seen: + continue + seen.add(name) + pending.append(definitions.get(name, "")) + return False + + +def offenders() -> list[str]: + """Return one finding per service guard that bypasses its services entry.""" + findings: list[str] = [] + defaults = get_application_defaults(roles_dir=ROLES_DIR) + for role_dir in sorted(p for p in ROLES_DIR.iterdir() if p.is_dir()): + template = role_dir / _TEMPLATE_REL + if not template.is_file(): + continue + definitions = _definitions(role_dir) + config = defaults.get(role_dir.name) or {} + for line_no, line in enumerate(read_text(str(template)).splitlines(), start=1): + guard = _GUARD_RE.match(line) + if not guard or len(guard.group(1)) > _SERVICE_KEY_INDENT: + continue + if line_has_rule(line, _RULE): + continue + var = guard.group(2) + if _reaches_the_spot(var, definitions, config): + continue + findings.append( + f"{role_dir.name}: {_TEMPLATE_REL}:{line_no} switches a service " + f"block on `{var}`, whose definition chain never reads " + f"`lookup('config', โ€ฆ, 'services..enabled')`. Point one link " + f"of the chain at the service's own entry, or mark the guard " + f"with `# nocheck: {_RULE}`." + ) + return findings + + +class TestServiceGuardSpot(unittest.TestCase): + def test_every_service_guard_reads_its_services_entry(self) -> None: + findings = offenders() + self.assertEqual( + [], + findings, + f"service guard(s) bypassing meta/services.yml ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + def test_the_scan_finds_service_guards(self) -> None: + seen = 0 + for role_dir in sorted(p for p in ROLES_DIR.iterdir() if p.is_dir()): + template = role_dir / _TEMPLATE_REL + if not template.is_file(): + continue + for line in read_text(str(template)).splitlines(): + guard = _GUARD_RE.match(line) + if guard and len(guard.group(1)) <= _SERVICE_KEY_INDENT: + seen += 1 + self.assertTrue( + seen, + "no compose template guards a service block, so the rule would pass " + "vacuously; check that the guard shape still matches", + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/lint/ansible/shell/container/test_argv_exec_needs_shell.py b/tests/lint/ansible/shell/container/test_argv_exec_needs_shell.py new file mode 100644 index 0000000000..59ad420652 --- /dev/null +++ b/tests/lint/ansible/shell/container/test_argv_exec_needs_shell.py @@ -0,0 +1,131 @@ +"""Enforce that a ``container_address``-derived target is only ever +reached through a module that runs a shell. + +Rationale +========= +The ``container_address`` lookup does not return a container name in +swarm mode. It returns a shell fragment -- +``"$(/usr/bin/resolve-container-id )"`` -- that only +becomes a name once an interpreter evaluates the command substitution. + +``ansible.builtin.shell`` provides that interpreter. +``ansible.builtin.command`` does not: it execs the binary directly, so +the fragment arrives at ``container exec`` as 47 literal characters and +the call dies with ``No such container: $(...)``. + +Compose hides the whole class of bug, because there the same lookup +returns the bare name and ``command:`` works fine. The failure appears +only in swarm, which is why ``container-exec-resolver`` -- which checks +that the resolver is *used* -- happily passes over it. This rule checks +the other half: that something can *evaluate* what the resolver +returned. + +An ``argv:`` list whose first element is an interpreter +(``bash -lc '...'``) is not matched, because the sibling rule's target +parser only recognises ``container``/``docker`` in first position; such +a task does have a shell and is correct. + +Per-line opt-out +================ +Add ``# nocheck: container-address-needs-shell`` on the ``argv:`` item +holding the container target, or on the line immediately above it. The +legitimate case is a role pinned to compose through +``compose_mode_force``, where the lookup can only ever yield a bare +name. +""" + +from __future__ import annotations + +import unittest +from pathlib import Path + +import yaml + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content + +from . import PROJECT_ROOT +from .test_exec_uses_resolver import ( + _argv_exec_target, + _classify_target, + _collect_approved_variables, + _collect_argv_item_lists, +) + +_RULE = "container-address-needs-shell" + + +def _is_scan_target(rel_path: str) -> bool: + return ( + rel_path.startswith("roles/") + and rel_path.endswith((".yml", ".yaml")) + and ("/tasks/" in rel_path or "/handlers/" in rel_path) + ) + + +def _targets_approved_variable(token: str, approved: set[str]) -> bool: + return _classify_target(token, approved).startswith("ok-") + + +class TestArgvExecNeedsShell(unittest.TestCase): + def test_resolver_targets_are_never_reached_through_argv(self) -> None: + approved = _collect_approved_variables() + findings: list[tuple[str, int, str]] = [] + + for path_str, content in iter_project_files_with_content( + extensions=(".yml", ".yaml"), + exclude_tests=True, + ): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + if not _is_scan_target(rel): + continue + + try: + docs = list(yaml.compose_all(content, Loader=yaml.SafeLoader)) + except yaml.YAMLError: + continue + + item_lists: list[list[tuple[int, str]]] = [] + for doc in docs: + if doc is not None: + _collect_argv_item_lists(doc, item_lists) + + lines = content.splitlines() + for items in item_lists: + target = _argv_exec_target(items) + if target is None: + continue + line_no, token = target + if not _targets_approved_variable(token, approved): + continue + if is_suppressed_at(lines, line_no, _RULE, mode="same-or-above"): + continue + findings.append((rel, line_no, lines[line_no - 1].strip())) + + if findings: + formatted = "\n".join( + f"- {path}:{line_no}: {snippet}" + for path, line_no, snippet in sorted( + set(findings), key=lambda item: (item[0], item[1]) + ) + ) + self.fail( + "Found `container exec` calls that address a " + "container_address-derived variable from an `argv:` list. " + "The lookup returns a shell fragment in swarm mode " + "(`$(/usr/bin/resolve-container-id ...)`), and the command " + "module runs no shell, so the fragment is passed through " + "literally and the call fails with `No such container`. " + "Compose hides this: there the lookup yields a bare name.\n\n" + "Fix: use the shell module and leave the address " + "unquoted, so the substitution can run:\n\n" + " - ansible.builtin.shell: >\n" + " container exec --user {{ X_USER }} {{ X_ADDR }}\n" + " cmd --flag={{ item.value | quote }}\n\n" + "Quote the surrounding values, never the address itself.\n\n" + "Where the role is pinned to compose via " + "`compose_mode_force`, add " + "`# nocheck: container-address-needs-shell` on the " + "container target item.\n\n" + f"Offending lines:\n{formatted}" + ) diff --git a/tests/lint/ansible/shell/container/test_exec_is_stack_host_gated.py b/tests/lint/ansible/shell/container/test_exec_is_stack_host_gated.py index 7517c8aef0..6e90895673 100644 --- a/tests/lint/ansible/shell/container/test_exec_is_stack_host_gated.py +++ b/tests/lint/ansible/shell/container/test_exec_is_stack_host_gated.py @@ -54,6 +54,7 @@ _RULE = "container-exec-stack-host-gate" _EXEC = re.compile(r"\b(?:container|docker)\s+exec\b") _IS_STACK_HOST = re.compile(r"\bIS_STACK_HOST\b") _NAME_LINE = re.compile(r"^\s*-?\s*name\s*:") +_ROLE_PATH_TASKS = re.compile(r"^\{\{\s*role_path\s*\}\}/tasks/") _DEFAULT_PLACEMENT_MANAGER = re.compile( r"^\s*placement\s*:\s*['\"]?manager['\"]?", re.MULTILINE ) @@ -139,7 +140,10 @@ def _include_target_paths(task: dict, tasks_dir: Path, parent_dir: Path) -> list """Resolve the file path(s) an include task references. Handles the static form (``include_tasks: 04_admin.yml``), the dict form (``include_tasks: { file: 04_admin.yml, apply: ... }``) and the loop - form (``include_tasks: "{{ step }}" loop: [step1.yml, step2.yml]``). + form (``include_tasks: "{{ step }}" loop: [step1.yml, step2.yml]``) and + the ``{{ role_path }}/tasks/...`` form, which a file reached through + ``tasks_from`` must use because the relative form resolves against a + different base there. Ansible resolves relative includes against the including file's directory first, then falls back to ``/tasks/``.""" @@ -158,6 +162,7 @@ def _include_target_paths(task: dict, tasks_dir: Path, parent_dir: Path) -> list inc = inc.get("file") if not isinstance(inc, str): continue + inc = _ROLE_PATH_TASKS.sub("", inc) if "{{" in inc and isinstance(task.get("loop"), list): for item in task["loop"]: if isinstance(item, str) and not item.startswith("{{"): diff --git a/tests/lint/ansible/shell/container/test_exec_uses_resolver.py b/tests/lint/ansible/shell/container/test_exec_uses_resolver.py index 7005e375ff..d1c79f23f0 100644 --- a/tests/lint/ansible/shell/container/test_exec_uses_resolver.py +++ b/tests/lint/ansible/shell/container/test_exec_uses_resolver.py @@ -96,10 +96,6 @@ _DIRECT_LOOKUP = re.compile( _VAR_REFERENCE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") -_DEFAULT_FLAG_VALUES_THAT_ARE_NOT_NAMES = frozenset( - {"-i", "-t", "-it", "-ti", "--interactive", "--tty"} -) - def _is_scan_target(rel_path: str) -> bool: if not rel_path.startswith("roles/"): diff --git a/tests/lint/ansible/tasks/test_host_node_resolver_is_unconditional.py b/tests/lint/ansible/tasks/test_host_node_resolver_is_unconditional.py new file mode 100644 index 0000000000..4fb9485a7a --- /dev/null +++ b/tests/lint/ansible/tasks/test_host_node_resolver_is_unconditional.py @@ -0,0 +1,141 @@ +"""Lint: the task that defines ``_HOST_NODE`` runs unconditionally. + +Ansible templates ``delegate_to`` before it evaluates the task's ``when``, so a +task that delegates to ``{{ X_HOST_NODE }}`` fails the play with +``'X_HOST_NODE' is undefined`` whenever the resolver that sets it was skipped, +even though the delegating task itself would have been skipped as well. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: host-node-resolver`` on, or directly above, the include's + ``- name:``. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content +from utils.cache.yaml import load_yaml_str + +from . import PROJECT_ROOT + +_RULE = "host-node-resolver" +_RESOLVER = "swarm/resolve_host_cid.yml" +_PREFIX_KEY = "resolve_output_prefix" +_NAME_LINE = re.compile(r"^\s*-\s+name:\s*(.+?)\s*$") +_BLOCK_KEYS = ("block", "rescue", "always") + + +def _unquote(value: str) -> str: + if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"": + return value[1:-1] + return value + + +def _name_line(lines: list[str], name: str) -> int: + for number, line in enumerate(lines, start=1): + match = _NAME_LINE.match(line) + if match and _unquote(match.group(1)) == name: + return number + return 1 + + +def _walk(tasks: object, guarded: bool, found: list[tuple[dict, bool]]) -> None: + for task in tasks if isinstance(tasks, list) else (): + if not isinstance(task, dict): + continue + conditional = guarded or "when" in task + if any(key in task for key in _BLOCK_KEYS): + for key in _BLOCK_KEYS: + _walk(task.get(key), conditional, found) + continue + found.append((task, conditional)) + + +def _resolver_prefix(task: dict) -> str: + include = task.get("include_tasks") or task.get("ansible.builtin.include_tasks") + target = include.get("file") if isinstance(include, dict) else include + if not isinstance(target, str) or _RESOLVER not in target: + return "" + return str((task.get("vars") or {}).get(_PREFIX_KEY, "")).strip() + + +def _delegated_prefixes(task: dict) -> set[str]: + delegate = str(task.get("delegate_to", "")) + return set(re.findall(r"\b([A-Z][A-Z0-9_]*)_HOST_NODE\b", delegate)) + + +def _role_tasks() -> dict[str, list[tuple[Path, str, list[tuple[dict, bool]]]]]: + roles: dict[str, list[tuple[Path, str, list[tuple[dict, bool]]]]] = {} + for path, content in iter_project_files_with_content(extensions=(".yml",)): + parts = Path(path).relative_to(PROJECT_ROOT).parts + if len(parts) < 3 or parts[0] != "roles" or parts[2] != "tasks": + continue + data = load_yaml_str(content) + if not isinstance(data, list): + continue + tasks: list[tuple[dict, bool]] = [] + _walk(data, False, tasks) + roles.setdefault(parts[1], []).append((Path(path), content, tasks)) + return roles + + +def _defined_unconditionally(files: list[tuple[Path, str, list]]) -> set[str]: + defined = set() + for _path, _content, tasks in files: + for task, conditional in tasks: + if conditional: + continue + if prefix := _resolver_prefix(task): + defined.add(prefix) + facts = task.get("set_fact") or task.get("ansible.builtin.set_fact") or {} + defined |= { + key.removesuffix("_HOST_NODE") + for key in (facts if isinstance(facts, dict) else {}) + if key.endswith("_HOST_NODE") + } + return defined + + +def conditional_resolvers() -> list[str]: + findings = [] + for files in _role_tasks().values(): + defined = _defined_unconditionally(files) + for path, content, tasks in files: + consumed = { + prefix for task, _ in tasks for prefix in _delegated_prefixes(task) + } + lines = content.splitlines() + for task, conditional in tasks: + prefix = _resolver_prefix(task) if conditional else "" + if not prefix or prefix in defined or prefix not in consumed: + continue + name = str(task.get("name", "")) + number = _name_line(lines, name) + if is_suppressed_at(lines, number, _RULE): + continue + rel = path.relative_to(PROJECT_ROOT) + findings.append(f"{rel}:{number}: {prefix}_HOST_NODE ({name[:60]})") + return findings + + +class TestHostNodeResolverIsUnconditional(unittest.TestCase): + def test_no_delegating_task_depends_on_a_skippable_resolver(self) -> None: + findings = conditional_resolvers() + self.assertEqual( + [], + findings, + f"resolver include(s) behind a condition ({len(findings)}) whose " + "prefix a delegate_to in the same file reads; delegate_to is " + "templated before the condition, so the skipped resolver kills the " + "play with an undefined variable:\n" + + "\n".join(f" - {f}" for f in findings), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/tasks/test_loop_var_shadowing.py b/tests/lint/ansible/tasks/test_loop_var_shadowing.py new file mode 100644 index 0000000000..414434dad4 --- /dev/null +++ b/tests/lint/ansible/tasks/test_loop_var_shadowing.py @@ -0,0 +1,103 @@ +"""Lint: a ``loop_var`` may not take the name of a declared variable. + +Ansible warns and carries on: + + [WARNING]: The variable 'application_id' is already in use. + You should set the `loop_var` value in the `loop_control` option for the + task to something else to avoid variable collisions and unexpected + behavior. + +Carrying on is the problem. Inside the loop the original value is gone, so +every lookup, template and nested include that reads the name sees the loop +item instead. The task still succeeds, which is why this shows up as a warning +in a log nobody greps rather than as a failure. + +``application_id`` is the sharp case here: almost every role declares it and +``include_role`` carries it into whatever the loop body reaches, so a loop over +applications that names its item ``application_id`` silently repoints every +config lookup in the nested role. + +Declared means: a key in ``group_vars/**`` or in any role's ``vars/main.yml`` +or ``defaults/main.yml``. Cross-role includes are routine in this repository, +so a name another role declares is a name that can be in scope here. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``nocheck: loop-var-shadow`` on the ``loop_var`` line or the one above it, + when the shadowing is deliberate and the loop body provably reads no other + meaning of the name. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files, read_text +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +_RULE = "loop-var-shadow" +_LOOP_VAR = re.compile(r"^\s*loop_var:\s*[\"']?(?P[A-Za-z_][A-Za-z0-9_]*)") + + +def _declared_names() -> set[str]: + """Every variable name the project declares in a file Ansible loads.""" + names: set[str] = set() + for path in iter_project_files(extensions=(".yml", ".yaml"), exclude_tests=True): + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + is_group_var = rel.startswith("group_vars/") + is_role_var = re.fullmatch(r"roles/[^/]+/(vars|defaults)/main\.ya?ml", rel) + if not (is_group_var or is_role_var): + continue + loaded = load_yaml_any(path) + if isinstance(loaded, dict): + names.update(key for key in loaded if isinstance(key, str)) + return names + + +def _task_files() -> list[str]: + return sorted( + path + for path in iter_project_files(extensions=(".yml", ".yaml"), exclude_tests=True) + if "/tasks/" in Path(path).relative_to(PROJECT_ROOT).as_posix() + ) + + +class TestLoopVarShadowing(unittest.TestCase): + def test_no_loop_var_shadows_a_declared_variable(self) -> None: + declared = _declared_names() + self.assertTrue( + declared, "no variable declarations were found to compare against" + ) + + findings: list[str] = [] + for path in _task_files(): + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + lines = read_text(path).splitlines() + for index, line in enumerate(lines): + match = _LOOP_VAR.match(line) + if match is None or match.group("name") not in declared: + continue + if is_suppressed_at(lines, index + 1, _RULE, mode="same-or-above"): + continue + findings.append(f"- {rel}:{index + 1}: loop_var: {match.group('name')}") + + if findings: + self.fail( + "These loops name their item after a variable the project " + "declares, so inside the loop that variable carries the item " + "instead of its own value and every nested lookup reads the " + "wrong thing:\n" + + "\n".join(findings) + + "\n\nFix: give the loop item a name of its own, for example " + f"`loop_var: _item`, or mark it `nocheck: {_RULE}` when the " + "loop body provably reads no other meaning of the name." + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/tasks/test_tasks_from_resolves.py b/tests/lint/ansible/tasks/test_tasks_from_resolves.py new file mode 100644 index 0000000000..667a361a76 --- /dev/null +++ b/tests/lint/ansible/tasks/test_tasks_from_resolves.py @@ -0,0 +1,210 @@ +"""A ``tasks_from`` entrypoint, and everything it includes, must resolve. + +``tasks_from`` names a file inside the *called* role's ``tasks/`` directory and +is resolved at runtime, so a moved or mistyped target survives ansible-lint, +``--syntax-check`` and both sibling include lints, which only follow +``include_tasks``/``import_tasks``. The play then dies mid-deploy, after +everything before it has already run. + +The second rule covers the trap that follows from the first. Ansible resolves a +relative ``include_tasks`` against the *including file's* directory when that +file was itself reached by path, but against ``tasks/`` when it was reached +through ``tasks_from``. So ``tasks/utils/mcp.yml`` may include ``mcp/probe.yml`` +for as long as only its own role includes it, and breaks the day a caller +reaches it through ``tasks_from`` instead. The same file, unchanged, resolves +differently depending on the caller. Nested includes below a ``tasks_from`` +entrypoint are therefore required to name a path that holds under both bases. + +Templated names and templated targets are skipped: what they resolve to is not +knowable statically. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: tasks-from-resolves`` on, or directly above, the ``tasks_from`` line. +* ``# nocheck: tasks-from-nested-include`` on, or directly above, the include line. +""" + +from __future__ import annotations + +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache import PROJECT_ROOT +from utils.cache.files import iter_project_files, read_text +from utils.cache.yaml import load_yaml_any + +_RULE = "tasks-from-resolves" +_NESTED_RULE = "tasks-from-nested-include" +_INCLUDE_ROLE_KEYS = ( + "include_role", + "ansible.builtin.include_role", + "import_role", + "ansible.builtin.import_role", +) +_INCLUDE_TASKS_KEYS = ( + "include_tasks", + "ansible.builtin.include_tasks", + "import_tasks", + "ansible.builtin.import_tasks", +) + + +def _walk_tasks(node: object): + """Yield every task mapping, descending into block/rescue/always.""" + if isinstance(node, list): + for item in node: + yield from _walk_tasks(item) + elif isinstance(node, dict): + yield node + for key in ("block", "rescue", "always"): + child = node.get(key) + if child: + yield from _walk_tasks(child) + + +def _include_role_args(task: dict) -> dict | None: + for key in _INCLUDE_ROLE_KEYS: + args = task.get(key) + if isinstance(args, dict): + return args + return None + + +def _iter_entrypoints(): + """Yield ``(caller, role, target)``; ``role`` is None when it is templated. + + A templated role name is the reconciliation case: the caller loops over a + discovered set, so the target names an entrypoint of every role that owns + a file under that path, not of one known role. + """ + for path_str in iter_project_files(extensions=(".yml", ".yaml")): + path = Path(path_str) + if "roles" not in path.parts and "tasks" not in path.parts: + continue + document = load_yaml_any(path_str, default_if_missing=None) + if not isinstance(document, list): + continue + for task in _walk_tasks(document): + args = _include_role_args(task) + if not args: + continue + role = args.get("name") + target = args.get("tasks_from") + if not isinstance(role, str) or not isinstance(target, str): + continue + role, target = role.strip(), target.strip() + if "{{" in target: + continue + yield path, None if "{{" in role else role, target + + +def _line_of(path: Path, needle: str) -> tuple[list[str], int]: + lines = read_text(str(path)).splitlines() + number = next((i for i, raw in enumerate(lines, 1) if needle in raw), 1) + return lines, number + + +def unresolved_targets() -> list[str]: + """Return one finding per include_role naming a tasks_from that is absent.""" + findings: list[str] = [] + for path, role, target in _iter_entrypoints(): + if role is None: + continue + candidate = PROJECT_ROOT / "roles" / role / "tasks" / target + if not candidate.suffix: + candidate = candidate.with_suffix(".yml") + if candidate.is_file(): + continue + lines, number = _line_of(path, f"tasks_from: {target}") + if is_suppressed_at(lines, number, _RULE): + continue + findings.append( + f"{path.relative_to(PROJECT_ROOT)}:{number}: role {role!r} has no " + f"tasks/{target}" + ) + return findings + + +def _include_tasks_target(task: dict) -> str | None: + for key in _INCLUDE_TASKS_KEYS: + args = task.get(key) + if isinstance(args, str): + return args.strip() + if isinstance(args, dict) and isinstance(args.get("file"), str): + return args["file"].strip() + return None + + +def _nested_findings_for(role: str, entrypoint: str) -> list[str]: + role_tasks = PROJECT_ROOT / "roles" / role / "tasks" + findings: list[str] = [] + pending, seen = [role_tasks / entrypoint], set() + while pending: + current = pending.pop() + if current in seen or not current.is_file(): + continue + seen.add(current) + document = load_yaml_any(str(current), default_if_missing=None) + if not isinstance(document, list): + continue + for task in _walk_tasks(document): + target = _include_tasks_target(task) + if not target or "{{" in target: + continue + resolved = role_tasks / target + if resolved.is_file(): + pending.append(resolved) + continue + if not (current.parent / target).is_file(): + continue + lines, number = _line_of(current, target) + if is_suppressed_at(lines, number, _NESTED_RULE): + continue + findings.append( + f"{current.relative_to(PROJECT_ROOT)}:{number}: {target!r} resolves " + f"only next to this file, but {role!r} is entered through " + f"tasks_from: {entrypoint}, which resolves against tasks/" + ) + return findings + + +def _roles_owning(target: str) -> list[str]: + return [ + role_dir.name + for role_dir in sorted((PROJECT_ROOT / "roles").iterdir()) + if (role_dir / "tasks" / target).is_file() + ] + + +def unresolved_nested_includes() -> list[str]: + """Return one finding per include below a tasks_from entrypoint that moves.""" + findings: list[str] = [] + for _, role, target in _iter_entrypoints(): + for owner in [role] if role else _roles_owning(target): + findings.extend(_nested_findings_for(owner, target)) + return sorted(set(findings)) + + +class TestTasksFromResolves(unittest.TestCase): + def test_every_tasks_from_target_exists(self) -> None: + findings = unresolved_targets() + self.assertEqual( + [], + findings, + f"include_role targets that do not exist ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + def test_every_nested_include_resolves_from_the_tasks_dir(self) -> None: + findings = unresolved_nested_includes() + self.assertEqual( + [], + findings, + f"includes that break when reached through tasks_from ({len(findings)}):\n" + + "\n".join(f" - {f}" for f in findings), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/variables/test_api_accessed_via_lookup.py b/tests/lint/ansible/variables/test_api_accessed_via_lookup.py new file mode 100644 index 0000000000..803ab4177d --- /dev/null +++ b/tests/lint/ansible/variables/test_api_accessed_via_lookup.py @@ -0,0 +1,105 @@ +"""``API`` is reachable through its lookups only, never as a bare variable. + +Rationale +========= +A bare ``API.github.client_id`` resolves against whatever the scope happens to +hold, and an inventory override replaces the declaration rather than merging +into it -- ``utils/api.py`` carries the mechanism and the consequences. +``lookup('api', '.')`` and ``lookup('api_enabled', '')`` +merge the override over ``group_vars/all/18_api.yml``, so an override narrows +values and never the provider set. Routing every access through them also keeps +one place to change how credentials are sourced. + +Scope +===== +Jinja in ``roles/``, ``group_vars/`` and ``inventories/``. An ``API:`` key +being *declared* is not an access; only a dereference inside ``{{ }}`` or +``{% %}`` is. Test fixtures legitimately build the bare form to exercise the +renderer, so ``tests/`` is out of scope. +""" + +from __future__ import annotations + +import re +import unittest +from dataclasses import dataclass +from pathlib import Path + +from utils.cache.files import iter_project_files_with_content + +from . import PROJECT_ROOT + +_SCOPES = ("roles", "group_vars", "inventories") +_SUFFIXES = (".yml", ".yaml", ".j2") +_JINJA_BLOCK = re.compile(r"\{\{(.*?)\}\}|\{%(.*?)%\}", re.DOTALL) +_BARE_API = re.compile(r"(? list[tuple[str, str]]: + prefixes = tuple(f"{scope}/" for scope in _SCOPES) + scoped: list[tuple[str, str]] = [] + for path, text in iter_project_files_with_content( + extensions=_SUFFIXES, exclude_tests=True + ): + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + if rel.startswith(prefixes): + scoped.append((rel, text)) + return sorted(scoped) + + +def _findings() -> list[Finding]: + findings: list[Finding] = [] + for rel, text in _scoped_files(): + for match in _JINJA_BLOCK.finditer(text): + expression = match.group(1) or match.group(2) or "" + if not _BARE_API.search(expression): + continue + line = text.count("\n", 0, match.start()) + 1 + findings.append(Finding(rel, line, " ".join(expression.split()))) + return findings + + +class TestApiAccessedViaLookup(unittest.TestCase): + def test_no_jinja_dereferences_api_directly(self) -> None: + findings = _findings() + + if findings: + self.fail( + f"{len(findings)} expression(s) read 'API' as a bare variable, which " + "breaks against an inventory that overrides only some providers:\n" + + "\n".join( + f" - {f.path}:{f.line}: {{{{ {f.expression} }}}}" for f in findings + ) + + "\n\nRead the value with lookup('api', '.') and gate " + "on lookup('api_enabled', '')." + ) + + def test_the_scan_reaches_jinja_in_every_scope(self) -> None: + """A suffix or scope typo would make the rule above pass forever.""" + scanned = _scoped_files() + for scope in _SCOPES: + with self.subTest(scope=scope): + blocks = sum( + len(_JINJA_BLOCK.findall(text)) + for rel, text in scanned + if rel.startswith(f"{scope}/") + ) + self.assertTrue(blocks, f"no Jinja found under {scope}/") + + def test_the_pattern_separates_a_dereference_from_a_declaration(self) -> None: + self.assertTrue(_BARE_API.search("API.github.client_id | length")) + self.assertTrue(_BARE_API.search("API['github']")) + self.assertFalse(_BARE_API.search("lookup('api', 'github.client_id')")) + self.assertFalse(_BARE_API.search("LITELLM_API.url")) + self.assertFalse(_BARE_API.search("item.API.key")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/variables/test_role_and_group_vars_used.py b/tests/lint/ansible/variables/test_role_and_group_vars_used.py index d663e8e1e1..89fa90a7f9 100644 --- a/tests/lint/ansible/variables/test_role_and_group_vars_used.py +++ b/tests/lint/ansible/variables/test_role_and_group_vars_used.py @@ -194,8 +194,7 @@ def _build_usage_indices(repo_root: Path) -> tuple[set[str], set[str], set[str]] Routes every read through the project's cached helpers: * ``iter_project_files_with_content`` walks the path list once - per process (``lru_cache(maxsize=1)`` on `_all_project_files`) - and reads each file via the cached ``read_text``; + per process and reads each file via the cached ``read_text``; * ``load_yaml_any`` parses each YAML file once per ``(path, mtime, size)`` signature and reuses the parsed structure on every later call in the same process โ€” no diff --git a/tests/lint/ansible/variables/test_url_base_not_slash_suffixed.py b/tests/lint/ansible/variables/test_url_base_not_slash_suffixed.py new file mode 100644 index 0000000000..60b960c97d --- /dev/null +++ b/tests/lint/ansible/variables/test_url_base_not_slash_suffixed.py @@ -0,0 +1,118 @@ +"""A ``url.base`` value already ends in a slash, so nothing may append one. + +Rationale +========= +``plugins/lookup/tls.py`` builds ``url.base`` as +``f"{web_protocol}://{primary_domain}/"``, and +``tests/unit/python/plugins/lookup/test_tls.py`` pins the trailing slash. +Writing ``{{ SOME_URL }}/`` therefore yields ``https://host//``. + +That is not cosmetic. Consumers differ in whether they normalise: the Nextcloud +ONLYOFFICE connector normalises ``DocumentServerUrl`` but returns +``DocumentServerInternalUrl`` raw, and the swarm vhost forwards +``$request_uri`` verbatim while the compose vhost lets nginx collapse the +double slash. So the same declaration works in one deployment mode and 404s in +the other, and the 404 sets a sticky ``settings_error`` that no redeploy clears. + +Per-line opt-out +================ +Add ``# nocheck: url-base-not-slash-suffixed`` on the offending line or the one +above it, with a comment naming why the extra slash is wanted. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +_RULE = "url-base-not-slash-suffixed" + +_URL_BASE = re.compile(r"lookup\(\s*['\"]tls['\"].*url\.base", re.DOTALL) +_STRIPS_SLASH = re.compile(r"regex_replace\(\s*['\"]/\+\$|trim\(\s*['\"]/") + + +def _is_var_file(rel_path: str) -> bool: + return rel_path.startswith("roles/") and ( + "/vars/" in rel_path or "/defaults/" in rel_path + ) + + +def _base_url_variables() -> set[str]: + """Variable names that carry a tls ``url.base`` with its slash intact. + + A definition that strips the trailing slash again (``regex_replace('/+$')``) + is excluded: appending a path to those is correct. + """ + names: set[str] = set() + for path_str, _content in iter_project_files_with_content( + extensions=(".yml", ".yaml") + ): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + if not _is_var_file(rel): + continue + try: + data = load_yaml_any(path_str, default_if_missing={}) or {} + except Exception: + continue + if not isinstance(data, dict): + continue + for key, value in data.items(): + if not isinstance(key, str) or not isinstance(value, str): + continue + if _URL_BASE.search(value) and not _STRIPS_SLASH.search(value): + names.add(key) + return names + + +class TestUrlBaseNotSlashSuffixed(unittest.TestCase): + def test_no_slash_follows_a_url_base_variable(self) -> None: + names = _base_url_variables() + self.assertTrue( + names, "no tls url.base variable found; the scan would be vacuous" + ) + pattern = re.compile( + r"\{\{-?\s*(" + + "|".join(re.escape(n) for n in sorted(names)) + + r")\s*-?\}\}/" + ) + + findings: list[tuple[str, int, str]] = [] + for path_str, content in iter_project_files_with_content( + extensions=(".yml", ".yaml", ".j2") + ): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + if not rel.startswith("roles/"): + continue + lines = content.splitlines() + for index, line in enumerate(lines): + match = pattern.search(line) + if not match: + continue + if is_suppressed_at(lines, index + 1, _RULE, mode="same-or-above"): + continue + findings.append((rel, index + 1, match.group(1))) + + if findings: + formatted = "\n".join( + f"- {p}:{n}: {v} already ends in a slash" + for p, n, v in sorted(findings) + ) + self.fail( + "A tls url.base value already carries its trailing slash, so " + "appending one produces a double slash. Consumers that do not " + "normalise then build URLs like https://host//healthcheck, " + "which a swarm vhost forwards verbatim.\n\n" + "Default: drop the appended slash.\n\n" + f"Offenders:\n{formatted}" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/filesystem/env/test_no_env_defaults_in_javascript.py b/tests/lint/filesystem/env/test_no_env_defaults_in_javascript.py new file mode 100644 index 0000000000..00ec36df22 --- /dev/null +++ b/tests/lint/filesystem/env/test_no_env_defaults_in_javascript.py @@ -0,0 +1,65 @@ +"""Lint: JavaScript never substitutes a value for an unset environment variable. + +``process.env.X || `` is a second source for something the deployment +already owns, and the two drift without a sound. ``playwright.config.js`` read +``process.env.PLAYWRIGHT_ACTION_TIMEOUT || 30_000`` while nothing ever set that +variable, so every run used the unscaled 30 s and no failure ever said so. + +Normalising an absent variable is allowed, because it substitutes nothing: +``|| ""``, ``|| "[]"``, ``|| false`` and ``|| 0`` only let the caller test +absence itself, and falling through to another ``process.env`` entry leaves the +value with the environment rather than taking it away. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``// nocheck: env-default`` on, or directly above, the offending line. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content + +from . import PROJECT_ROOT + +_RULE = "env-default" +_FALSY = r"""(?:""|''|"\[\]"|'\[\]'|false\b|0\b|process\.env\b)""" +_DEFAULTED = re.compile( + rf"""process\.env(?:\.\w+|\[[^\]]+\])\s*(?:\|\||\?\?)\s*(?!{_FALSY})\S""" +) + + +def env_defaults() -> list[str]: + findings = [] + for path, content in iter_project_files_with_content(extensions=(".js",)): + lines = content.splitlines() + for number, line in enumerate(lines, start=1): + if not _DEFAULTED.search(line): + continue + if is_suppressed_at(lines, number, _RULE): + continue + rel = Path(path).relative_to(PROJECT_ROOT) + findings.append(f"{rel}:{number}: {line.strip()[:90]}") + return findings + + +class TestNoEnvDefaultsInJavaScript(unittest.TestCase): + def test_no_javascript_substitutes_a_value_for_an_unset_variable(self) -> None: + findings = env_defaults() + self.assertEqual( + [], + findings, + f"environment default(s) in JavaScript ({len(findings)}). The value " + "belongs to whoever renders the environment; a fallback here is a " + "second source that hides an unfed variable instead of failing on " + 'it. Normalising to "" stays allowed:\n' + + "\n".join(f" - {f}" for f in findings), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/filesystem/playwright/test_no_orphaned_helpers.py b/tests/lint/filesystem/playwright/test_no_orphaned_helpers.py new file mode 100644 index 0000000000..2ac84cc7e1 --- /dev/null +++ b/tests/lint/filesystem/playwright/test_no_orphaned_helpers.py @@ -0,0 +1,81 @@ +"""Every role Playwright file is either collected or required. + +``playwright.config.js`` collects ``**/*.@(spec|test).js`` and nothing else, so +a ``.js`` file that no sibling requires is dead weight that still reads as part +of the suite. It survives refactors, gets updated by mistake, and a merge can +resurrect one long after the spec that used it was renamed away, which is how +``web-app-openwebui/files/playwright/test-ollama-chat.js`` came back. + +A file therefore has to earn its place one of two ways: it matches the collector +by name, or something else under the same role's ``files/playwright/`` requires +it through a relative path. Requires are resolved the way Node resolves them, +including the bare and ``/index.js`` forms. + +Suppress a file that is staged for a consumer outside this tree with +``// nocheck: playwright-orphan -- `` anywhere in it. +""" + +from __future__ import annotations + +import re +import unittest +from collections import defaultdict +from typing import TYPE_CHECKING + +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from pathlib import Path + +_COLLECTED = re.compile(r"\.(?:spec|test)\.js$") +_REQUIRE = re.compile(r"""require\(\s*['"](\.[^'"]+)['"]\s*\)""") +_NOCHECK = re.compile(r"//\s*nocheck:\s*playwright-orphan\b") + + +def _playwright_files_by_role() -> dict[str, list[Path]]: + by_role: dict[str, list[Path]] = defaultdict(list) + for path in sorted(PROJECT_ROOT.glob("roles/*/files/playwright/**/*.js")): + by_role[path.relative_to(PROJECT_ROOT).parts[1]].append(path) + return by_role + + +def _required_targets(files: list[Path]) -> set[Path]: + """Return every file the given files require through a relative path.""" + reached: set[Path] = set() + for path in files: + for ref in _REQUIRE.findall(read_text(str(path))): + target = (path.parent / ref).resolve() + for candidate in (target, target.with_suffix(".js"), target / "index.js"): + if candidate.is_file(): + reached.add(candidate) + break + return reached + + +class TestNoOrphanedPlaywrightHelpers(unittest.TestCase): + def test_every_playwright_file_is_collected_or_required(self) -> None: + findings: list[str] = [] + for _role, files in sorted(_playwright_files_by_role().items()): + reached = _required_targets(files) + for path in files: + if _COLLECTED.search(path.name) or path.resolve() in reached: + continue + if _NOCHECK.search(read_text(str(path))): + continue + findings.append(str(path.relative_to(PROJECT_ROOT))) + + self.assertFalse( + findings, + f"{len(findings)} Playwright file(s) are neither collected by " + f"playwright.config.js nor required by a sibling under the same " + f"role. Rename to *.spec.js if it is a test, require it where it " + f"belongs, delete it, or mark it with " + f"'// nocheck: playwright-orphan -- ':\n" + + "\n".join(f" {name}" for name in findings), + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/lint/filesystem/shell/test_no_shell_templates.py b/tests/lint/filesystem/shell/test_no_shell_templates.py new file mode 100644 index 0000000000..512c1656c5 --- /dev/null +++ b/tests/lint/filesystem/shell/test_no_shell_templates.py @@ -0,0 +1,64 @@ +"""Lint: a shell script ships as ``.sh``, not as ``.sh.j2``. + +A templated script is opaque to every tool that reads shell. ``shellcheck`` +parses Jinja as syntax errors, the repo's own ``.sh`` guards (``|| true``, +``sh -c pipefail``, inline PHP) skip the file because it is not a ``.sh``, and +nothing can execute it to test it: what runs on the host never exists in the +repository. A defect in the rendered half is found by deploying it. + +The variability belongs in the invocation, not in the text. ``sys-service`` +resolves ``files/shell/script.sh`` alongside ``templates/script.sh.j2``, and a +static script takes its values the way this repo's Python scripts already do: +as arguments on ``ExecStart``, or through ``Environment=``. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``nocheck: shell-template`` anywhere in the first 30 lines, for a script whose + shape itself is generated rather than its values. Put the marker BELOW the + shebang, never above it, and prefer the Jinja comment form ``{# ... #}`` so it + does not land in the rendered script. State what is generated. + +None of the templates present when this guard landed meets that bar: each +interpolates values into a fixed script, and each is grandfathered with a marker +saying so, because converting a deployed script to argv changes what runs on the +host. The guard exists to stop the next one. +""" + +from __future__ import annotations + +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import iter_project_files, read_text + +from . import PROJECT_ROOT + +_RULE = "shell-template" +_SUFFIX = ".sh.j2" + + +class TestNoShellTemplates(unittest.TestCase): + def test_no_shell_script_is_a_template(self) -> None: + findings: list[str] = [] + for path in iter_project_files(extensions=(_SUFFIX,), exclude_tests=True): + lines = read_text(path).splitlines() + if is_suppressed_in_head(lines, _RULE): + continue + findings.append(f"- {Path(path).relative_to(PROJECT_ROOT).as_posix()}") + + if findings: + self.fail( + "These shell scripts are Jinja templates, so shellcheck, the " + "repository's .sh guards and every test read something other " + "than what runs on the host:\n" + + "\n".join(sorted(findings)) + + "\n\nFix: move the script to files/shell/ as a plain .sh and " + "pass its values as ExecStart arguments or Environment= entries, " + f"or mark it `nocheck: {_RULE}` in the file head when the script's " + "shape, not just its values, is generated." + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/filesystem/test_docs_holds_only_documents.py b/tests/lint/filesystem/test_docs_holds_only_documents.py new file mode 100644 index 0000000000..6fdc3ee8e5 --- /dev/null +++ b/tests/lint/filesystem/test_docs_holds_only_documents.py @@ -0,0 +1,56 @@ +"""``docs/`` holds documents, not the code that writes them. + +A generator parked next to its output reads as documentation, so it drifts out +of the checks that apply to code: it grows a ``__file__`` walk to find the +repository root, imports through a ``sys.path`` insert, and carries suppressions +for both. Moving it under ``cli/`` costs nothing and removes the exemptions. + +Generated pages stay here; the module that renders them lives in +``cli/build//`` and runs through its own make target. +""" + +from __future__ import annotations + +import unittest + +from utils.cache.files import iter_non_ignored_files + +from . import PROJECT_ROOT + +ALLOWED_SUFFIXES = frozenset({".md", ".html", ".rst"}) +ALLOWED_NAMES = frozenset({".nocheck"}) + + +def _docs_files() -> list[str]: + """Return every non-ignored path under ``docs/``. + + Build artefacts such as ``__pycache__`` are not the subject of this rule, + so the walk applies ``.gitignore`` rather than listing the directory raw. + It does not ask git directly: the containerised test runner owns the + checkout under a different uid, and git refuses such a repository outright. + """ + docs = PROJECT_ROOT / "docs" + return sorted( + str(path.relative_to(PROJECT_ROOT)) + for raw in iter_non_ignored_files(root=str(PROJECT_ROOT)) + if (path := PROJECT_ROOT / raw).is_relative_to(docs) + ) + + +class TestDocsHoldsOnlyDocuments(unittest.TestCase): + def test_every_tracked_file_under_docs_is_a_document(self) -> None: + offenders = [ + path + for path in _docs_files() + if not path.endswith(tuple(ALLOWED_SUFFIXES)) + and path.rsplit("/", 1)[-1] not in ALLOWED_NAMES + ] + self.assertEqual( + [], + offenders, + "docs/ carries files that are not documents: " + f"{', '.join(sorted(offenders))}. Allowed are " + f"{', '.join(sorted(ALLOWED_SUFFIXES))} plus " + f"{', '.join(sorted(ALLOWED_NAMES))}; a generator belongs under " + "cli/build// with a make target that writes into docs/.", + ) diff --git a/tests/lint/filesystem/test_profile_tasks_output_limit.py b/tests/lint/filesystem/test_profile_tasks_output_limit.py new file mode 100644 index 0000000000..2678b9df90 --- /dev/null +++ b/tests/lint/filesystem/test_profile_tasks_output_limit.py @@ -0,0 +1,51 @@ +"""Lint check: the task profiler must not truncate its summary to the default. + +``ansible.cfg`` enables ``profile_tasks``, whose ``output_limit`` defaults to +20. A deploy round of this size then reports only the twenty slowest tasks and +prints nothing below them, so any role whose cost is spread over many cheap +tasks cannot be attributed at all: in run 33828309745 the recap cut off at +66.07s, leaving 22.7 of ``sys-svc-compose``'s 51.9 minutes unaccounted. + +The limit stays bounded rather than ``all`` because the recap prints one line +per task execution and the Actions worker dies silently on ENOSPC while writing +its own logs, which is the same reason ``utils/tests/swarm/matrix.py`` aborts a +step at ``DISK_FLOOR_MB``. +""" + +from __future__ import annotations + +import configparser +import unittest + +from utils import PROJECT_ROOT + +CONFIG = PROJECT_ROOT / "ansible.cfg" +SECTION = "callback_profile_tasks" +KEY = "task_output_limit" +DEFAULT_LIMIT = 20 + + +class TestProfileTasksOutputLimit(unittest.TestCase): + def setUp(self) -> None: + self.parser = configparser.ConfigParser() + self.parser.read(CONFIG) + + def test_the_profiler_is_enabled(self) -> None: + enabled = self.parser.get("defaults", "callbacks_enabled", fallback="") + self.assertIn("profile_tasks", enabled) + + def test_the_summary_is_not_left_at_the_default_limit(self) -> None: + self.assertTrue( + self.parser.has_option(SECTION, KEY), + f"ansible.cfg must set [{SECTION}] {KEY}; without it the recap " + f"stops after {DEFAULT_LIMIT} tasks and the cost of a role spread " + "over many cheap tasks cannot be attributed", + ) + value = self.parser.get(SECTION, KEY).strip() + if value == "all": + return + self.assertGreater(int(value), DEFAULT_LIMIT) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/documentation/test_credits_attribution.py b/tests/lint/repository/documentation/test_credits_attribution.py new file mode 100644 index 0000000000..dd332eafef --- /dev/null +++ b/tests/lint/repository/documentation/test_credits_attribution.py @@ -0,0 +1,119 @@ +"""Lint inconsistent attribution inside ``## Credits`` sections. + +A person credited in one markdown file with a link +(``[Kevin Veen-Birkenbach](https://www.veen.world)``) but in another with a +bare name (``**Kevin Veen-Birkenbach**``) reads as two different people and +drops the reader's path to that person. This lint requires a name linked +anywhere to carry that same link everywhere it is credited. + +It also rejects the same name pointing at two different URLs, because then +neither mention can be trusted. + +The name -> URL derivation is shared with the README generator +(``utils/roles/credits.py``), so a fix here and the generated output cannot +drift apart. + +Only ``## Credits`` sections are scanned: prose elsewhere legitimately names +people without linking them. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ```` in the head of a markdown file + exempts the whole file. +* ```` on (or directly above) the + offending line exempts that single finding. +""" + +from __future__ import annotations + +import unittest +from pathlib import Path +from typing import NamedTuple + +from utils.annotations.suppress import is_suppressed_at, is_suppressed_in_head +from utils.roles.credits import ( + BARE_BOLD_RE, + CREDITS_HEADING_RE, + LINKED_RE, + collect_author_urls, + credits_lines, + iter_markdown_documents, +) + +from . import PROJECT_ROOT + +_RULE = "credits-attribution" + + +class Finding(NamedTuple): + path: str + line: int + name: str + detail: str + + +class TestCreditsAttribution(unittest.TestCase): + """A name linked in any Credits section must be linked in all of them.""" + + def test_credited_names_carry_their_link_everywhere(self) -> None: + files: list[tuple[str, list[str]]] = [] + for raw_path, lines in iter_markdown_documents(): + if is_suppressed_in_head(lines, _RULE): + continue + if any(CREDITS_HEADING_RE.match(line) for line in lines): + rel = Path(raw_path).relative_to(PROJECT_ROOT).as_posix() + files.append((rel, lines)) + + urls = collect_author_urls([lines for _rel, lines in files]) + findings: list[Finding] = [] + + for name, seen in sorted(urls.items()): + if len(seen) > 1: + findings.append( + Finding( + "", + 0, + name, + f"credited with {len(seen)} different URLs: " + f"{', '.join(sorted(seen))}", + ) + ) + + known = { + name: next(iter(seen)) for name, seen in urls.items() if len(seen) == 1 + } + + for rel, lines in files: + for line_no, text in credits_lines(lines): + linked = {n.strip() for n, _u in LINKED_RE.findall(text)} + for bare in BARE_BOLD_RE.findall(text): + name = bare.strip() + if name in linked or name not in known: + continue + if is_suppressed_at(lines, line_no, _RULE): + continue + findings.append( + Finding( + rel, + line_no, + name, + f"credited bare here but linked to {known[name]} " + f"elsewhere; use [{name}]({known[name]})", + ) + ) + + self.assertFalse( + findings, + f"{len(findings)} inconsistent Credits attribution(s) ({_RULE}).\n" + "A person credited with a link in one place MUST carry that same " + "link everywhere they are credited, so the reader always reaches " + "them.\n" + + "\n".join( + f" - {f.path}:{f.line} {f.name}: {f.detail}" + for f in sorted(findings, key=lambda f: (f.path, f.line)) + ), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/documentation/test_mcp_audit_classification.py b/tests/lint/repository/documentation/test_mcp_audit_classification.py new file mode 100644 index 0000000000..f09fd3b6f1 --- /dev/null +++ b/tests/lint/repository/documentation/test_mcp_audit_classification.py @@ -0,0 +1,132 @@ +"""The audit files a role under the classification the role itself declares. + +``meta/mcp.yml`` carries a ``classification`` and the requirement's audit carries +a list per classification. Nothing tied them together, so a role kept its old +audit entry after it was implemented: twenty-four roles shipped a working MCP +surface while the audit still filed nine of them as untried adapter candidates +and two as having no path at all. Both statements looked authoritative and only +one was true. + +The list a role belongs to is therefore derived from the role, not from the +prose: the audit's section titles are the classification vocabulary, and a role +that declares ``classification: adapter_server`` must appear under +``adapter_server`` and nowhere else. + +Roles without ``meta/mcp.yml`` are out of scope here โ€” that they appear +somewhere at all is what ``test_mcp_audit_completeness.py`` guards. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-audit-classification`` in the head of the role's + ``meta/mcp.yml``. +""" + +from __future__ import annotations + +import unittest +from collections.abc import Mapping +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_MCP, ROLE_FILE_VARS_MAIN + +from . import PROJECT_ROOT +from .test_mcp_audit_completeness import _audit_lists + +_RULE = "mcp-audit-classification" + +CLASSIFICATIONS = frozenset( + { + "native_server", + "native_client", + "native_both", + "plugin_server", + "sidecar_server", + "adapter_server", + "adapter_candidate", + "blocked", + "enabler", + "subordinate", + "no_surface", + } +) + + +def _declared() -> dict[str, str]: + """Return ``{application_id: classification}`` for every role declaring one.""" + declared: dict[str, str] = {} + for mcp_path in sorted(Path(PROJECT_ROOT, "roles").glob(f"*/{ROLE_FILE_META_MCP}")): + mcp = load_yaml_any(str(mcp_path), default_if_missing={}) + if not isinstance(mcp, Mapping): + continue + classification = str(mcp.get("classification") or "").strip() + if not classification: + continue + if is_suppressed_in_head(read_text(str(mcp_path)).splitlines(), _RULE): + continue + role_vars = load_yaml_any( + str(mcp_path.parent.parent / ROLE_FILE_VARS_MAIN), default_if_missing={} + ) + application_id = (role_vars or {}).get("application_id") + if isinstance(application_id, str) and "{{" not in application_id: + declared[application_id] = classification + return declared + + +def _audit_placement() -> dict[str, str]: + """Return ``{application_id: audit list title without its count}``.""" + placement: dict[str, str] = {} + for title, ids in _audit_lists().items(): + name = title.rsplit(" (", 1)[0] + for application_id in ids: + placement[application_id] = name + return placement + + +class TestMcpAuditClassification(unittest.TestCase): + def test_every_declared_classification_is_known(self) -> None: + unknown = sorted( + f"{app}: {classification}" + for app, classification in _declared().items() + if classification not in CLASSIFICATIONS + ) + self.assertEqual( + [], + unknown, + f"role(s) declaring a classification outside {sorted(CLASSIFICATIONS)}:\n" + + "\n".join(f" - {u}" for u in unknown), + ) + + def test_the_audit_files_each_role_under_its_own_classification(self) -> None: + placement = _audit_placement() + mismatched = [] + for app, classification in sorted(_declared().items()): + where = placement.get(app) + if where is None: + mismatched.append( + f"{app}: declares '{classification}' but appears in no audit list" + ) + elif where != classification: + mismatched.append( + f"{app}: declares '{classification}' but the audit files it " + f"under '{where}'" + ) + self.assertEqual( + [], + mismatched, + f"role(s) whose audit entry contradicts their own metadata " + f"({len(mismatched)}):\n" + "\n".join(f" - {m}" for m in mismatched), + ) + + def test_the_scan_finds_declared_classifications(self) -> None: + self.assertTrue( + _declared(), + "no role declares an MCP classification, so the rule would pass " + "vacuously; check that the scan still reads the right topic", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/documentation/test_mcp_audit_completeness.py b/tests/lint/repository/documentation/test_mcp_audit_completeness.py new file mode 100644 index 0000000000..074e3a7620 --- /dev/null +++ b/tests/lint/repository/documentation/test_mcp_audit_completeness.py @@ -0,0 +1,139 @@ +"""The MCP audit must dispose of every role, exactly once. + +The exhaustive audit in the MCP requirement is the record of what each role's +MCP surface is, including the roles that deliberately have none. A role missing +from it reads as "not yet looked at" and as "decided against" at the same time, +and nothing distinguishes the two. A role in two lists carries two dispositions. + +Three checks, all derived from the repository rather than from the snapshot the +requirement was written against: + +* every role whose ``vars/main.yml`` sets a literal ``application_id`` appears + in the audit; +* no role appears in more than one audit list; +* the count each list declares in its heading matches the ids it carries, so a + hand-edited list cannot silently drop an entry. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-audit-completeness`` in the head of the role's ``vars/main.yml``. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +from . import PROJECT_ROOT + +_RULE = "mcp-audit-completeness" +_REQUIREMENT = PROJECT_ROOT / "docs" / "requirements" / "035-mcp-proxy-expansion.md" +_AUDIT_HEADING = "## Exhaustive Application-ID Audit" + +_SECTION_HEADING = re.compile(r"^###\s+(?P.+?)\s+\((?P<count>\d+)\)\s*$") +_INLINE_LIST = re.compile( + r"^\*\*`(?P<title>[^`]+)`\s+\((?P<count>\d+)\):\*\*\s+(?P<body>.+)$" +) +_ID_LIST = re.compile(r"^(`[a-z0-9-]+`)(,\s*`[a-z0-9-]+`)*\.$") +_ID = re.compile(r"`([a-z0-9-]+)`") + + +def _audit_lists() -> dict[str, list[str]]: + """Return ``{list title: [application_id]}`` for every list in the audit. + + A list is a line made only of backticked ids, attributed either to its own + ``**`reason` (n):**`` lead-in or to the nearest ``### Title (n)`` heading. + Prose that merely mentions a backticked term is not a list and is ignored. + """ + lines = read_text(str(_REQUIREMENT)).splitlines() + start = next(i for i, line in enumerate(lines) if line.strip() == _AUDIT_HEADING) + lists: dict[str, list[str]] = {} + heading: tuple[str, int] | None = None + + for line in lines[start + 1 :]: + stripped = line.strip() + if stripped.startswith("## "): + break + section = _SECTION_HEADING.match(stripped) + if section: + heading = (section["title"], int(section["count"])) + continue + inline = _INLINE_LIST.match(stripped) + if inline and _ID_LIST.match(inline["body"]): + lists[f"{inline['title']} ({inline['count']})"] = _ID.findall( + inline["body"] + ) + continue + if heading and _ID_LIST.match(stripped): + lists[f"{heading[0]} ({heading[1]})"] = _ID.findall(stripped) + heading = None + return lists + + +def _declared_count(title: str) -> int: + return int(title.rsplit("(", 1)[1].rstrip(")")) + + +def _literal_application_ids() -> set[str]: + ids = set() + for vars_file in sorted(PROJECT_ROOT.glob(f"roles/*/{ROLE_FILE_VARS_MAIN}")): + data = load_yaml_any(str(vars_file), default_if_missing={}) + if not isinstance(data, dict): + continue + application_id = data.get("application_id") + if not isinstance(application_id, str) or "{{" in application_id: + continue + if is_suppressed_in_head(read_text(str(vars_file)).splitlines(), _RULE): + continue + ids.add(application_id) + return ids + + +class TestMcpAuditCompleteness(unittest.TestCase): + def test_every_role_is_disposed_of(self) -> None: + listed = {app for ids in _audit_lists().values() for app in ids} + missing = sorted(_literal_application_ids() - listed) + self.assertEqual( + [], + missing, + f"roles absent from the MCP audit ({len(missing)}); absence is not a " + f"disposition, so each needs a list in {_REQUIREMENT.name}:\n" + + "\n".join(f" - {app}" for app in missing), + ) + + def test_no_role_carries_two_dispositions(self) -> None: + seen: dict[str, str] = {} + clashes: list[str] = [] + for title, ids in _audit_lists().items(): + for app in ids: + if app in seen: + clashes.append(f"{app}: {seen[app]} and {title}") + seen[app] = title + self.assertEqual( + [], + sorted(clashes), + "application ids in more than one audit list:\n" + + "\n".join(f" - {clash}" for clash in sorted(clashes)), + ) + + def test_each_list_carries_the_count_it_declares(self) -> None: + drift = [ + f"{title}: {len(ids)} ids" + for title, ids in _audit_lists().items() + if len(ids) != _declared_count(title) + ] + self.assertEqual( + [], + drift, + "audit lists whose heading count disagrees with their entries:\n" + + "\n".join(f" - {entry}" for entry in drift), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/documentation/test_mcp_audit_report.py b/tests/lint/repository/documentation/test_mcp_audit_report.py new file mode 100644 index 0000000000..1a766e3ed0 --- /dev/null +++ b/tests/lint/repository/documentation/test_mcp_audit_report.py @@ -0,0 +1,67 @@ +"""The committed MCP audit report matches a fresh generation. + +A generated document that nobody regenerates becomes a snapshot of whenever +somebody last remembered, and it reads exactly like a current one. This report +answers "what does each surface expose, as whom, to whom" for reviewers who +will not open twenty-four ``meta/mcp.yml`` files, so a stale row is worse than +no row. + +The check imports the generator and compares its output to the committed file +rather than reimplementing the rendering, so the two cannot disagree about what +"generated" means. + +Fix a failure by regenerating and committing, never by editing the report. +""" + +from __future__ import annotations + +import unittest + +from cli.build.docs.mcp_audit import __main__ as generator +from utils.cache.files import read_text +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +_DOCS = PROJECT_ROOT / "docs" / "contributing" / "design" / "role" / "services" / "mcp" +_REPORT = _DOCS / "audit.md" + + +def _load_generator(): + return generator + + +class TestMcpAuditReport(unittest.TestCase): + def test_the_committed_report_is_freshly_generated(self) -> None: + rendered = _load_generator().render() + committed = read_text(str(_REPORT)) + self.assertEqual( + rendered, + committed, + f"{_REPORT.name} differs from a fresh generation. Regenerate and " + "commit it by running `make mcp-audit`", + ) + + def test_the_report_carries_a_row_per_role_with_metadata(self) -> None: + module = _load_generator() + roles = sorted( + p.parent.parent.name + for p in module.ROLES_DIR.glob(f"*/{ROLE_FILE_META_MCP}") + ) + self.assertTrue( + roles, + "no role owns meta/mcp.yml, so the report would be empty and this " + "rule would pass vacuously", + ) + committed = read_text(str(_REPORT)) + missing = [role for role in roles if f"`{role}`" not in committed] + self.assertEqual( + [], + missing, + "role(s) owning MCP metadata but absent from the report:\n" + + "\n".join(f" - {m}" for m in missing), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/documentation/test_mcp_blocked_reasons.py b/tests/lint/repository/documentation/test_mcp_blocked_reasons.py new file mode 100644 index 0000000000..b02cabf089 --- /dev/null +++ b/tests/lint/repository/documentation/test_mcp_blocked_reasons.py @@ -0,0 +1,136 @@ +"""Every blocked role names what blocks it, and serves nothing meanwhile. + +"Blocked" is the one disposition that can quietly mean two different things: +somebody looked and found a concrete obstacle, or nobody looked at all. Only a +named reason separates them, and only for as long as the reason stays attached +to the role rather than to a sentence covering the whole list. + +The other half is the dangerous one. A role that declares a blocker while also +shipping an enabled MCP surface tells reviewers the path is shut and clients +the opposite, and the clients are right. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-blocked-reasons`` in the head of the role's ``meta/mcp.yml``. +""" + +from __future__ import annotations + +import re +import unittest +from collections.abc import Mapping + +from utils.annotations.suppress import is_suppressed_in_head +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT +from .test_mcp_audit_completeness import _audit_lists + +_RULE = "mcp-blocked-reasons" +_REQUIREMENT = PROJECT_ROOT / "docs" / "requirements" / "035-mcp-proxy-expansion.md" +_BLOCKED = "blocked" + +_REASON_ROW = re.compile( + r"^\|\s*`(?P<role>[a-z0-9-]+)`\s*\|\s*`(?P<reason>[a-z_]+)`\s*\|\s*(?P<blocker>[^|]+?)\s*\|$" +) +_VOCABULARY = re.compile( + r"^Allowed reasons MUST be documented and linted", re.MULTILINE +) + + +def _allowed_reasons() -> set[str]: + """Return the reason tokens the requirement documents as allowed.""" + text = read_text(str(_REQUIREMENT)) + match = _VOCABULARY.search(text) + if match is None: + return set() + line = text[match.start() : text.index("\n", match.start())] + return set(re.findall(r"`([a-z_]+)`", line)) + + +def _blocked_roles() -> list[str]: + for title, ids in _audit_lists().items(): + if title.rsplit(" (", 1)[0] == _BLOCKED: + return sorted(ids) + return [] + + +def _reason_rows() -> dict[str, str]: + """Return ``{role: reason}`` for every row of the blocked reason table.""" + rows: dict[str, str] = {} + for line in read_text(str(_REQUIREMENT)).splitlines(): + match = _REASON_ROW.match(line.strip()) + if match and match["blocker"].strip("- "): + rows[match["role"]] = match["reason"] + return rows + + +class TestMcpBlockedReasons(unittest.TestCase): + def test_every_blocked_role_names_its_blocker(self) -> None: + rows = _reason_rows() + missing = [ + f"{role}: filed as blocked but the reason table carries no row, so " + f"the entry cannot be told apart from one nobody reviewed" + for role in _blocked_roles() + if role not in rows + ] + self.assertEqual( + [], + missing, + f"blocked role(s) without a named blocker ({len(missing)}):\n" + + "\n".join(f" - {m}" for m in missing), + ) + + def test_every_reason_comes_from_the_documented_vocabulary(self) -> None: + allowed = _allowed_reasons() + self.assertTrue( + allowed, + "the requirement no longer documents an allowed reason vocabulary, " + "so this rule cannot check anything", + ) + rows = _reason_rows() + unknown = sorted( + f"{role}: {reason}" + for role, reason in rows.items() + if role in set(_blocked_roles()) and reason not in allowed + ) + self.assertEqual( + [], + unknown, + f"blocked reason(s) outside the documented vocabulary " + f"{sorted(allowed)}:\n" + "\n".join(f" - {u}" for u in unknown), + ) + + def test_no_blocked_role_also_serves_a_surface(self) -> None: + serving = [] + for role in _blocked_roles(): + mcp_path = PROJECT_ROOT / "roles" / role / ROLE_FILE_META_MCP + if not mcp_path.is_file(): + continue + if is_suppressed_in_head(read_text(str(mcp_path)).splitlines(), _RULE): + continue + mcp = load_yaml_any(str(mcp_path), default_if_missing={}) + if isinstance(mcp, Mapping) and mcp.get("enabled"): + serving.append( + f"{role}: filed as blocked yet ships an enabled MCP surface; " + f"the audit says the path is shut and clients would find it open" + ) + self.assertEqual( + [], + serving, + "blocked role(s) serving anyway:\n" + + "\n".join(f" - {s}" for s in serving), + ) + + def test_the_scan_finds_blocked_roles(self) -> None: + self.assertTrue( + _blocked_roles(), + "the audit lists no blocked role, so every rule here would pass " + "vacuously; check that the scan still reads the right topic", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/structure/test_mcp_reconcile_placement.py b/tests/lint/repository/structure/test_mcp_reconcile_placement.py new file mode 100644 index 0000000000..7ccb183664 --- /dev/null +++ b/tests/lint/repository/structure/test_mcp_reconcile_placement.py @@ -0,0 +1,77 @@ +"""The MCP reconciliation runs after the app pass and before anything reads it. + +Providers write their credentials during the app pass, and the end-to-end tests +read the converged state. The reconciliation therefore has exactly one valid +window, and both edges are silent when crossed: moved earlier it converges +against providers that have not deployed, moved into the destructor it runs +after the tests that need it - and `any_errors_fatal` means one red test skips +it entirely. + +Neither mistake fails anything, which is why this is pinned here rather than +left to review. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: mcp-reconcile-placement`` on, or directly above, the include. +""" + +from __future__ import annotations + +import unittest + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +_RULE = "mcp-reconcile-placement" +_ROLE = "sys-svc-mcp-reconcile" +_STAGE = PROJECT_ROOT / "tasks" / "stages" / "02_server.yml" +_DESTRUCTOR = PROJECT_ROOT / "tasks" / "stages" / "03_destructor.yml" +_APP_PASS = "tasks/utils/setup/group.yml" +_READER = "test-e2e-playwright" + + +def _line_of(lines: list[str], needle: str) -> int | None: + return next((i for i, raw in enumerate(lines, 1) if needle in raw), None) + + +class TestMcpReconcilePlacement(unittest.TestCase): + def setUp(self) -> None: + self.lines = read_text(str(_STAGE)).splitlines() + + def test_the_reconciliation_sits_between_the_app_pass_and_its_reader(self) -> None: + reconcile = _line_of(self.lines, _ROLE) + self.assertIsNotNone( + reconcile, f"{_ROLE} is not invoked from {_STAGE.name}; nothing converges" + ) + if is_suppressed_at(self.lines, reconcile, _RULE): + return + app_pass = _line_of(self.lines, _APP_PASS) + reader = _line_of(self.lines, _READER) + self.assertIsNotNone(app_pass, f"{_STAGE.name} no longer includes the app pass") + self.assertIsNotNone(reader, f"{_STAGE.name} no longer runs {_READER}") + self.assertLess( + app_pass, + reconcile, + "reconciliation before the app pass converges against providers that " + "have not written their credentials yet", + ) + self.assertLess( + reconcile, + reader, + f"{_READER} reads the converged state, so it must run after the " + f"reconciliation, not before it", + ) + + def test_the_reconciliation_is_not_deferred_to_the_destructor(self) -> None: + self.assertNotIn( + _ROLE, + read_text(str(_DESTRUCTOR)), + "the destructor runs after the end-to-end tests, and any_errors_fatal " + "skips it entirely once one of them is red", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/test_distros_spot.py b/tests/lint/repository/test_distros_spot.py index fe92927ab5..5f58618776 100644 --- a/tests/lint/repository/test_distros_spot.py +++ b/tests/lint/repository/test_distros_spot.py @@ -82,6 +82,8 @@ class TestDistrosSpot(unittest.TestCase): for path in sorted(PROJECT_ROOT.glob(f"**/{pattern}")): if {".git", ".claude", "node_modules"} & set(path.parts): continue + if not path.is_file(): + continue if path.resolve() == this_file: continue rel = path.relative_to(PROJECT_ROOT).as_posix() @@ -111,7 +113,7 @@ class TestDistrosSpot(unittest.TestCase): ref = _MATRIX_REF_RE.match(str(axis)) self.assertIsNotNone( ref, - f"test-workspace.yml must derive its matrix from {FILE_META_DISTROS} " + f"call-test-workspace.yml must derive its matrix from {FILE_META_DISTROS} " f"via fromJson(needs.<job>.outputs.<name>), got {axis!r}.", ) resolver_id, output_name = ref.groups() diff --git a/tests/lint/repository/test_no_debian_codename_tags.py b/tests/lint/repository/test_no_debian_codename_tags.py new file mode 100644 index 0000000000..5445e3ab86 --- /dev/null +++ b/tests/lint/repository/test_no_debian_codename_tags.py @@ -0,0 +1,222 @@ +"""Lint: a container image tag MUST NOT name a Debian release by codename. + +Why +--- + +A codename carries no ordering. ``bookworm`` and ``trixie`` are two +opaque strings, so neither the image updater at +[test_image_versions.py](../../external/update/docker/test_image_versions.py) +nor the semver pin lint at +[test_semver_pinning.py](../../lint/ansible/services/test_semver_pinning.py) +can tell that one supersedes the other. A python image pinned to the Debian +12 codename is therefore frozen on that release for as long as it stands: no +job will ever raise it, and the freeze is invisible because the tag keeps +resolving. + +The numeric equivalent (``debian:13``, ``debian:13.6``) is comparable, so +the same pin stays inside the freshness pipeline and crosses a Debian major +the way every other version pin does. + +Scope +----- + +Every tracked file. Two shapes are recognised: + +* a ``name:tag`` image reference with no space after the colon, which + covers ``image:`` values, Dockerfile ``FROM`` lines and heredocs, +* a ``version:`` / ``*_version:`` / ``*_tag:`` YAML value, whose tag + carries no registry prefix to anchor it. + +A tag is split on ``-``, ``.`` and ``_``; a finding needs one whole +component to be a codename, so ``cache buster`` and ``.stretched-link`` +do not match. + +Out of scope: an apt suite name (``deb ... bookworm main``, a Nexus proxy +``"distribution"``). A sources.list has no numeric form, so the rule would +have no fix to offer there. + +Suppression +----------- + +``# nocheck: debian-codename`` on or above the line, for an upstream that +publishes no numeric tag. The marker names which upstream, because the pin +it buys can never be raised. +""" + +from __future__ import annotations + +import re +import subprocess +import unittest +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from pathlib import Path + +_RULE = "debian-codename" + +_CODENAMES = frozenset( + { + "squeeze", + "wheezy", + "jessie", + "stretch", + "buster", + "bullseye", + "bookworm", + "trixie", + "forky", + "duke", + "sid", + } +) + +_MENTION_RE = re.compile( + rf"(?<![a-z])(?:{'|'.join(sorted(_CODENAMES))})(?![a-z])", + re.IGNORECASE, +) + +_IMAGE_REF_RE = re.compile( + r"(?<![\w./:-])([a-z0-9][a-z0-9._/-]{0,127}):([A-Za-z0-9][A-Za-z0-9._-]{0,127})" +) + +_VERSION_KEY_RE = re.compile( + r"^\s*(?:-\s*)?(?P<key>[A-Za-z0-9_]*(?:version|tag))\s*:\s*(?P<value>\S+)", + re.IGNORECASE, +) + +_TAG_SPLIT_RE = re.compile(r"[-._]") + + +@dataclass(frozen=True) +class Violation: + """One codename-tagged reference. + + Args: + file: repo-relative path. + line_no: 1-based line the reference sits on. + reference: the offending text as written. + codename: the release component that triggered the finding. + """ + + file: str + line_no: int + reference: str + codename: str + + +def _codename_of(tag: str) -> str | None: + """Return the codename component of *tag*, or None when it carries none. + + Args: + tag: an image tag, without the ``name:`` prefix. + """ + for component in _TAG_SPLIT_RE.split(tag.strip("'\"")): + if component.lower() in _CODENAMES: + return component.lower() + return None + + +def _references_on(line: str) -> list[tuple[str, str]]: + """Yield ``(reference, codename)`` for every codename-tagged reference. + + Args: + line: one source line already known to mention a codename. + """ + found: list[tuple[str, str]] = [] + for match in _IMAGE_REF_RE.finditer(line): + codename = _codename_of(match.group(2)) + if codename: + found.append((match.group(0), codename)) + if found: + return found + key_match = _VERSION_KEY_RE.match(line) + if key_match: + value = key_match.group("value").split("#", 1)[0] + codename = _codename_of(value) + if codename: + found.append((f"{key_match.group('key')}: {value}", codename)) + return found + + +def _git_lines(*args: str) -> list[str]: + out = subprocess.check_output( + ["git", "-c", "safe.directory=*", "-C", str(PROJECT_ROOT), *args], + text=True, + ) + return [line for line in out.splitlines() if line] + + +def _targets() -> set[str]: + """Every tracked file plus every untracked new one. + + A role added but not yet staged carries its pins like any other, so the + lint MUST see it before the commit rather than after. + """ + return set(_git_lines("ls-files")) | set( + _git_lines("ls-files", "--others", "--exclude-standard") + ) + + +def _scan_file(path: Path) -> list[Violation]: + """Return every unsuppressed codename reference in *path*. + + Args: + path: absolute path to a tracked file. + """ + try: + text = read_text(str(path)) + except (OSError, UnicodeDecodeError, ValueError): + return [] + + if not _MENTION_RE.search(text): + return [] + + rel = path.relative_to(PROJECT_ROOT).as_posix() + lines = text.splitlines() + violations: list[Violation] = [] + for line_no, raw in enumerate(lines, start=1): + if not _MENTION_RE.search(raw): + continue + for reference, codename in _references_on(raw): + if is_suppressed_at(lines, line_no, _RULE): + continue + violations.append(Violation(rel, line_no, reference, codename)) + return violations + + +class TestNoDebianCodenameTags(unittest.TestCase): + """Fails on any image tag that names a Debian release by codename.""" + + def test_no_image_tag_names_a_debian_codename(self) -> None: + violations: list[Violation] = [] + for rel in sorted(_targets()): + path = PROJECT_ROOT / rel + if path.is_file(): + violations.extend(_scan_file(path)) + + if not violations: + return + + shown = "\n".join( + f"{v.file}:{v.line_no}: {v.reference} (Debian {v.codename})" + for v in sorted(violations, key=lambda v: (v.file, v.line_no)) + ) + self.fail( + f"{len(violations)} image reference(s) pinned to a Debian codename. " + "A codename is not ordered, so no updater can raise it across a " + "Debian major and the pin stays frozen on that release forever. " + "Use the numeric tag instead (debian:13, python:3.11-slim), or " + f"declare the exception with '# nocheck: {_RULE}' naming the " + f"upstream that publishes no numeric tag:\n{shown}" + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/lint/repository/test_workflow_references.py b/tests/lint/repository/test_workflow_references.py index fcb8156f37..10340731fb 100644 --- a/tests/lint/repository/test_workflow_references.py +++ b/tests/lint/repository/test_workflow_references.py @@ -2,9 +2,17 @@ Scope ===== -Any occurrence of ``.github/workflows/<file>.yml`` or ``actions/workflows/ -<file>.yml`` in a tracked text file: `uses:` lines, Python constants, Makefile -variables, shell API URLs and Markdown links alike. +Three patterns: + +* ``.github/workflows/<file>.yml`` or ``actions/workflows/<file>.yml`` anywhere + in a tracked text file: `uses:` lines, Python constants, Makefile variables, + shell API URLs and Markdown links alike. +* a **bare** ``<file>.yml`` inside ``.github/workflows/`` itself, where every + such token names a sibling workflow. Elsewhere in the tree a bare name is + ambiguous with role and compose files, so the prefix stays mandatory there. +* the target of a manual dispatch anywhere, which must exist **and** declare + ``workflow_dispatch``. Both forms count: ``gh workflow run <file>.yml`` and a + REST POST to ``actions/workflows/<file>.yml/dispatches``. Why === @@ -13,6 +21,11 @@ the run, a Python constant raises at test time, but a Markdown link or an API URL in a shell script fails only in production, months later. Matching the string against the directory listing catches all of them at once. +A stale `gh workflow run` target is the quietest of the three. GitHub resolves +the name against the deleted workflow's tombstone instead of erroring, answers +HTTP 422, and keeps the tombstone out of `GET /actions/workflows`, so listing a +repository's workflows shows a clean set while every dispatch fails. + A file opts out with a ``nocheck: workflow-references`` marker in its first 30 lines, for documents that name a workflow that does not exist yet. """ @@ -32,16 +45,30 @@ _NOCHECK_RULE = "workflow-references" _WORKFLOW_DIR = PROJECT_ROOT / ".github" / "workflows" _SUFFIXES = {".md", ".yml", ".yaml", ".py", ".sh", ".j2", ".rst", ".txt"} _REFERENCE_RE = re.compile(r"(?:\.github|actions)/workflows/([A-Za-z0-9._-]+\.ya?ml)") +_BARE_RE = re.compile(r"(?<![\w/.-])([A-Za-z0-9][A-Za-z0-9._-]*\.ya?ml)") +_DISPATCH_RE = re.compile( + r"gh workflow run\s+(?P<cli>[A-Za-z0-9._-]+\.ya?ml)" + r"|actions/workflows/(?P<api>[A-Za-z0-9._-]+\.ya?ml)/dispatches" +) def _scanned(path: Path) -> bool: return path.suffix in _SUFFIXES or path.name == "Makefile" -def missing_references() -> list[str]: - """Every `<file>:<line>: <workflow>` whose workflow is not on disk.""" - known = {entry.name for entry in _WORKFLOW_DIR.iterdir() if entry.is_file()} - offenders: list[str] = [] +def _known() -> set[str]: + return {entry.name for entry in _WORKFLOW_DIR.iterdir() if entry.is_file()} + + +def _patterns(path: Path) -> tuple[re.Pattern[str], ...]: + if path.is_relative_to(_WORKFLOW_DIR): + return (_REFERENCE_RE, _BARE_RE) + return (_REFERENCE_RE,) + + +def _candidates() -> list[tuple[str, list[str]]]: + """Every scanned file that did not opt out, as `(relative path, lines)`.""" + found: list[tuple[str, list[str]]] = [] for path_str in iter_non_ignored_files(): path = Path(path_str) if not _scanned(path): @@ -52,16 +79,41 @@ def missing_references() -> list[str]: continue if is_suppressed_in_head(lines, _NOCHECK_RULE): continue - rel = path.relative_to(PROJECT_ROOT).as_posix() + found.append((path.relative_to(PROJECT_ROOT).as_posix(), lines)) + return found + + +def missing_references() -> list[str]: + """Every `<file>:<line>: <workflow>` whose workflow is not on disk.""" + known = _known() + offenders: list[str] = [] + for rel, lines in _candidates(): + patterns = _patterns(PROJECT_ROOT / rel) for number, line in enumerate(lines, 1): + names = {name for pattern in patterns for name in pattern.findall(line)} offenders.extend( - f"{rel}:{number}: {name}" - for name in _REFERENCE_RE.findall(line) - if name not in known + f"{rel}:{number}: {name}" for name in sorted(names) if name not in known ) return offenders +def undispatchable_targets() -> list[str]: + """Every `gh workflow run` target that is absent or not manually dispatchable.""" + known = _known() + offenders: list[str] = [] + for rel, lines in _candidates(): + for number, line in enumerate(lines, 1): + for match in _DISPATCH_RE.finditer(line): + name = match.group("cli") or match.group("api") + if name not in known: + offenders.append(f"{rel}:{number}: {name} does not exist") + elif "workflow_dispatch" not in read_text(str(_WORKFLOW_DIR / name)): + offenders.append( + f"{rel}:{number}: {name} declares no workflow_dispatch trigger" + ) + return offenders + + class TestWorkflowReferences(unittest.TestCase): def test_referenced_workflows_exist(self) -> None: offenders = missing_references() @@ -73,6 +125,17 @@ class TestWorkflowReferences(unittest.TestCase): "that is still to be created:\n" + "\n".join(sorted(offenders)) ) + def test_dispatch_targets_are_dispatchable(self) -> None: + offenders = undispatchable_targets() + if offenders: + self.fail( + f"{len(offenders)} manual dispatch(es) name a workflow GitHub cannot " + "run. Both failures answer HTTP 422 rather than something the caller " + "can read: a stale filename resolves to the deleted workflow's " + "tombstone, and a reusable-only workflow refuses the event:\n" + + "\n".join(sorted(offenders)) + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/performance/test_runtime_performance.py b/tests/performance/test_runtime_performance.py index ef0fa08beb..bad5f4ac0d 100644 --- a/tests/performance/test_runtime_performance.py +++ b/tests/performance/test_runtime_performance.py @@ -52,8 +52,8 @@ def _simulate_ansible_variables( return { "applications": shared_applications, "users": shared_users, - "DOMAIN_PRIMARY": "infinito.example", - "SYSTEM_EMAIL_DOMAIN": "infinito.example", + "DOMAIN_PRIMARY": "infinito.test", + "SYSTEM_EMAIL_DOMAIN": "infinito.test", "group_names": [], } diff --git a/tests/unit/javascript/roles/test-e2e-playwright/files/personas/utils/dom.test.js b/tests/unit/javascript/roles/test-e2e-playwright/files/personas/utils/dom.test.js new file mode 100644 index 0000000000..a74cb0c60a --- /dev/null +++ b/tests/unit/javascript/roles/test-e2e-playwright/files/personas/utils/dom.test.js @@ -0,0 +1,57 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const path = require("node:path"); +const Module = require("node:module"); + +const loadModule = Module._load; +Module._load = function (request, ...rest) { + return request === "@playwright/test" ? {} : loadModule.call(this, request, ...rest); +}; + +const PROJECT_ROOT = path.resolve(__dirname, "../../../../../../../.."); +const { hostnameOf, LOGIN_CONTROL_NAME } = require( + path.join(PROJECT_ROOT, "roles/test-e2e-playwright/files/personas/utils/dom.js"), +); + +Module._load = loadModule; + +const FA_GLYPH = String.fromCodePoint(0xf2f6); + +test("LOGIN_CONTROL_NAME matches a sign-in control behind an icon-font glyph", () => { + for (const name of [ + "Login", + ` ${FA_GLYPH} Login`, + `${FA_GLYPH}Sign in`, + "Sign in with Keycloak", + `${FA_GLYPH} SSO`, + ]) { + assert.match(name, LOGIN_CONTROL_NAME); + } +}); + +test("LOGIN_CONTROL_NAME ignores authenticated navigation entries", () => { + for (const name of [ + `${FA_GLYPH} Logout`, + "Accessories", + "Login Enabled", + `${FA_GLYPH} Login Enabled`, + ]) { + assert.doesNotMatch(name, LOGIN_CONTROL_NAME); + } +}); + +test("hostnameOf rejects an IdP URL whose redirect_uri carries the app domain", () => { + const domain = "app.example.org"; + assert.notEqual( + hostnameOf(`https://auth.example.org/realms/r/protocol/openid-connect/auth?redirect_uri=https://${domain}/`), + domain, + ); + assert.notEqual(hostnameOf(`https://${domain}.evil.test/`), domain); + assert.equal(hostnameOf(`https://${domain}/oauth2/callback?code=x`), domain); + assert.equal(hostnameOf("http://abcdefghijklmnop.onion/"), "abcdefghijklmnop.onion"); +}); + +test("hostnameOf returns an empty host for unparsable frame URLs", () => { + assert.equal(hostnameOf(""), ""); + assert.equal(hostnameOf("about:blank"), ""); +}); diff --git a/tests/unit/javascript/roles/test-e2e-playwright/files/personas/utils/env.test.js b/tests/unit/javascript/roles/test-e2e-playwright/files/personas/utils/env.test.js new file mode 100644 index 0000000000..c100ba0046 --- /dev/null +++ b/tests/unit/javascript/roles/test-e2e-playwright/files/personas/utils/env.test.js @@ -0,0 +1,60 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const path = require("node:path"); +const Module = require("node:module"); + +const loadModule = Module._load; +Module._load = function (request, ...rest) { + return request === "@playwright/test" ? { expect: () => ({}) } : loadModule.call(this, request, ...rest); +}; + +const PROJECT_ROOT = path.resolve(__dirname, "../../../../../../../.."); +const { apiFetchOnion, apiGetOnion } = require( + path.join(PROJECT_ROOT, "roles/test-e2e-playwright/files/personas/utils/env.js"), +); + +Module._load = loadModule; + +const ONION = "http://mattermost.abcdefghijklmnop.onion/api/v4/users/me"; +const CLEARNET = "https://mattermost.example.org/api/v4/users/me"; + +function scriptedRequest(outcomes) { + const calls = []; + return { + calls, + async fetch(url, opts) { + calls.push({ url, method: opts.method }); + const next = outcomes.shift(); + if (next instanceof Error) throw next; + return next; + }, + }; +} + +test("an onion request survives a rejected SOCKS circuit", async () => { + const request = scriptedRequest([ + new Error("apiRequestContext.post: Socks5 proxy rejected connection - Failure"), + "response", + ]); + const response = await apiFetchOnion(request, ONION, { method: "POST" }); + assert.equal(response, "response"); + assert.deepEqual(request.calls.map((call) => call.method), ["POST", "POST"]); +}); + +test("a clearnet request gets exactly one attempt", async () => { + const request = scriptedRequest([new Error("socket hang up"), "response"]); + await assert.rejects(apiFetchOnion(request, CLEARNET, { method: "GET" }), /socket hang up/); + assert.equal(request.calls.length, 1); +}); + +test("a non-transport failure is not retried over tor either", async () => { + const request = scriptedRequest([new Error("apiRequestContext.post: Invalid URL"), "response"]); + await assert.rejects(apiFetchOnion(request, ONION, { method: "POST" }), /Invalid URL/); + assert.equal(request.calls.length, 1); +}); + +test("apiGetOnion is the GET shorthand", async () => { + const request = scriptedRequest(["response"]); + await apiGetOnion(request, ONION, { headers: { a: "b" } }); + assert.deepEqual(request.calls, [{ url: ONION, method: "GET" }]); +}); diff --git a/tests/unit/javascript/roles/test-e2e-playwright/files/personas/utils/logout.test.js b/tests/unit/javascript/roles/test-e2e-playwright/files/personas/utils/logout.test.js new file mode 100644 index 0000000000..c1f1db782f --- /dev/null +++ b/tests/unit/javascript/roles/test-e2e-playwright/files/personas/utils/logout.test.js @@ -0,0 +1,133 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const path = require("node:path"); +const Module = require("node:module"); + +const playwrightStub = { expect: () => ({ toBe() {} }) }; +const loadModule = Module._load; +Module._load = function (request, ...rest) { + return request === "@playwright/test" ? playwrightStub : loadModule.call(this, request, ...rest); +}; + +const PROJECT_ROOT = path.resolve(__dirname, "../../../../../../../.."); +const { confirmKeycloakLogoutIfPrompted, waitForLogoutControl } = require( + path.join(PROJECT_ROOT, "roles/test-e2e-playwright/files/personas/utils/logout.js"), +); + +Module._load = loadModule; + +function fakePage({ visibleAfterMs = Infinity } = {}) { + const start = Date.now(); + const intervals = []; + const locator = () => { + const self = { + count: async () => 1, + nth: () => ({ isVisible: async () => Date.now() - start >= visibleAfterMs }), + filter: () => self, + }; + return self; + }; + return { + intervals, + locator, + getByRole: locator, + waitForTimeout: async (ms) => { + intervals.push(ms); + await new Promise((resolve) => setTimeout(resolve, ms)); + }, + }; +} + +test("returns true immediately when a logout control is already visible", async () => { + const page = fakePage({ visibleAfterMs: 0 }); + const started = Date.now(); + assert.equal(await waitForLogoutControl(page, 3_000), true); + assert.ok(Date.now() - started < 250, "must not sleep once the control is visible"); +}); + +test("returns true as soon as the control appears, well before the deadline", async () => { + const page = fakePage({ visibleAfterMs: 600 }); + const started = Date.now(); + assert.equal(await waitForLogoutControl(page, 5_000), true); + const elapsed = Date.now() - started; + assert.ok(elapsed >= 500, `expected to wait for the control, waited ${elapsed}ms`); + assert.ok(elapsed < 2_000, `expected an early exit, waited ${elapsed}ms`); +}); + +test("costs at most the deadline when no control ever appears", async () => { + const page = fakePage(); + const started = Date.now(); + assert.equal(await waitForLogoutControl(page, 900), false); + const elapsed = Date.now() - started; + assert.ok(elapsed >= 900, `must honour the full deadline, stopped after ${elapsed}ms`); + assert.ok(elapsed < 1_800, `must not exceed the deadline materially, took ${elapsed}ms`); +}); + +test("polls on a fixed interval that no onion multiplier scales", async () => { + const page = fakePage(); + await waitForLogoutControl(page, 900); + assert.ok(page.intervals.length >= 3, `expected repeated polls, got ${page.intervals.length}`); + assert.deepEqual( + [...new Set(page.intervals)], + [250], + "the poll interval must stay 250ms so a slow target is detected sooner, not later", + ); +}); + +const KEYCLOAK_LOGOUT = "https://auth.test/realms/r/protocol/openid-connect/logout"; + +function keycloakLogoutPage({ url = KEYCLOAK_LOGOUT, promptAfterMs = Infinity, leaveAfterMs = Infinity } = {}) { + let current = url; + if (leaveAfterMs !== Infinity) setTimeout(() => { current = "https://app.test/"; }, leaveAfterMs); + const page = { + clicks: 0, + probes: 0, + url: () => current, + locator: () => ({ + first: () => ({ + waitFor: ({ timeout }) => { + page.probes += 1; + return new Promise((resolve, reject) => { + if (promptAfterMs <= timeout) setTimeout(resolve, promptAfterMs); + else setTimeout(() => reject(new Error("waitFor timed out")), timeout); + }); + }, + click: async () => { page.clicks += 1; }, + }), + }), + waitForURL: (predicate, { timeout }) => + new Promise((resolve, reject) => { + const deadline = Date.now() + timeout; + const tick = () => { + if (predicate(new URL(current))) return resolve(); + if (Date.now() >= deadline) return reject(new Error("waitForURL timed out")); + return setTimeout(tick, 20); + }; + tick(); + }), + waitForLoadState: async () => {}, + }; + return page; +} + +test("confirm helper does nothing off the Keycloak logout endpoint", async () => { + const page = keycloakLogoutPage({ url: "https://app.test/" }); + await confirmKeycloakLogoutIfPrompted(page); + assert.equal(page.probes, 0); + assert.equal(page.clicks, 0); +}); + +test("confirm helper clicks the confirmation Keycloak renders", async () => { + const page = keycloakLogoutPage({ promptAfterMs: 100 }); + await confirmKeycloakLogoutIfPrompted(page); + assert.equal(page.clicks, 1); +}); + +test("confirm helper returns once Keycloak redirects away without a prompt", async () => { + const page = keycloakLogoutPage({ leaveAfterMs: 100 }); + const started = Date.now(); + await confirmKeycloakLogoutIfPrompted(page); + const elapsed = Date.now() - started; + assert.equal(page.clicks, 0); + assert.ok(elapsed < 1_000, `must not wait out the confirm window after the redirect, waited ${elapsed}ms`); +}); diff --git a/tests/unit/php/roles/web-app-akaunting/files/RealignAdminPasswordTest.php b/tests/unit/php/roles/web-app-akaunting/files/RealignAdminPasswordTest.php new file mode 100644 index 0000000000..0f9a698f81 --- /dev/null +++ b/tests/unit/php/roles/web-app-akaunting/files/RealignAdminPasswordTest.php @@ -0,0 +1,116 @@ +<?php + +declare(strict_types=1); + +namespace App\Models\Auth { + final class User + { + public static ?User $found = null; + + public static ?string $queriedEmail = null; + + public string $password = ''; + + public int $saves = 0; + + public static function where(string $column, $value): self + { + self::$queriedEmail = $column === 'email' ? (string) $value : null; + + return new self(); + } + + public function first(): ?User + { + return self::$found; + } + + public function save(): void + { + ++$this->saves; + } + } +} + +namespace Illuminate\Support\Facades { + final class Hash + { + public static function check(string $plain, string $stored): bool + { + return $stored === 'bcrypt:' . $plain; + } + } +} + +namespace { + + use App\Models\Auth\User; + use PHPUnit\Framework\TestCase; + + final class RealignAdminPasswordTest extends TestCase + { + private const SNIPPET = '/roles/web-app-akaunting/files/php/realign_admin_password.php'; + + /** + * Evaluate the tinker snippet against the stubs above. + * + * @return string everything the snippet printed + */ + private function runSnippet(?string $email, ?string $password): string + { + putenv($email === null ? 'ADMIN_EMAIL' : 'ADMIN_EMAIL=' . $email); + putenv($password === null ? 'ADMIN_PASSWORD' : 'ADMIN_PASSWORD=' . $password); + + $code = file_get_contents(dirname(__DIR__, 6) . self::SNIPPET); + ob_start(); + eval($code); // nocheck: eval - the snippet is repo-owned and only runs under artisan tinker + return (string) ob_get_clean(); + } + + protected function setUp(): void + { + User::$found = null; + User::$queriedEmail = null; + } + + public function testItFailsWhenNoUserCarriesTheEmail(): void + { + $out = $this->runSnippet('admin@example.org', 'declared'); + + self::assertStringContainsString('FAILED', $out); + self::assertSame('admin@example.org', User::$queriedEmail); + } + + public function testItFailsWhenTheEmailIsMissing(): void + { + $out = $this->runSnippet(null, 'declared'); + + self::assertStringContainsString('FAILED', $out); + } + + public function testItLeavesAMatchingPasswordAlone(): void + { + $user = new User(); + $user->password = 'bcrypt:declared'; + User::$found = $user; + + $out = $this->runSnippet('admin@example.org', 'declared'); + + self::assertSame("UNCHANGED\n", $out); + self::assertSame(0, $user->saves); + } + + public function testItStoresTheDeclaredPasswordInClearTextSoTheModelHashesIt(): void + { + $user = new User(); + $user->password = 'bcrypt:stale'; + User::$found = $user; + + $out = $this->runSnippet('admin@example.org', 'declared'); + + self::assertSame("CHANGED\n", $out); + self::assertSame(1, $user->saves); + self::assertSame('declared', $user->password); + } + } +} diff --git a/tests/unit/python/cli/administration/deploy/ci/test_runs.py b/tests/unit/python/cli/administration/deploy/ci/test_runs.py index cea9c1e6a1..59297e65c9 100644 --- a/tests/unit/python/cli/administration/deploy/ci/test_runs.py +++ b/tests/unit/python/cli/administration/deploy/ci/test_runs.py @@ -395,7 +395,6 @@ class TestConfigFromTitle(unittest.TestCase): "filesystem": "ext4", "chunk_gate": "false", "workspace": "true", - "instructions": "false", } self.assertEqual(runs.config_from_title(render(dispatched)), dispatched) @@ -443,6 +442,90 @@ class TestConfigFromTitle(unittest.TestCase): self.assertNotIn("tor", runs.config_from_run(title, {})) self.assertNotIn("tor", runs.config_from_run(title)) + def _suite_job(self, suite: str, conclusion: str) -> dict: + return { + "name": f"๐ŸŽ›๏ธ Orchestrate CI (manual) / {runs.SUITE_JOB_IDS[suite]} / ๐Ÿ“– X", + "status": "completed", + "conclusion": conclusion, + } + + def test_a_suite_the_source_run_passed_is_not_asked_for_again(self) -> None: + for suite in runs.SUITE_JOB_IDS: + with self.subTest(suite): + title = render({suite: "true"}) + jobs = [self._suite_job(suite, "success")] + self.assertEqual(runs.config_from_run(title, jobs=jobs)[suite], "false") + + def test_a_suite_that_failed_is_asked_for_again(self) -> None: + for suite in runs.SUITE_JOB_IDS: + with self.subTest(suite): + title = render({suite: "true"}) + jobs = [self._suite_job(suite, "failure")] + self.assertEqual(runs.config_from_run(title, jobs=jobs)[suite], "true") + + def test_a_suite_that_never_ran_is_asked_for_again(self) -> None: + """No job at all means it never started, which proves nothing.""" + title = render({"workspace": "true"}) + jobs = [{"name": "๐Ÿงน Lint", "status": "completed", "conclusion": "success"}] + self.assertEqual(runs.config_from_run(title, jobs=jobs)["workspace"], "true") + + def test_a_shard_that_did_not_run_through_is_asked_for_again(self) -> None: + """Only a success retires the suite; every other outcome, a mid-run + force-cancel included, leaves it unproven.""" + for conclusion in ("cancelled", "skipped", "timed_out"): + with self.subTest(conclusion): + title = render({"workspace": "true"}) + jobs = [self._suite_job("workspace", conclusion)] + self.assertEqual( + runs.config_from_run(title, jobs=jobs)["workspace"], "true" + ) + + def test_a_still_running_shard_is_asked_for_again(self) -> None: + title = render({"workspace": "true"}) + jobs = [ + { + "name": f"๐ŸŽ›๏ธ Orchestrate CI (manual) / {runs.SUITE_JOB_IDS['workspace']}", + "status": "in_progress", + "conclusion": None, + } + ] + self.assertEqual(runs.config_from_run(title, jobs=jobs)["workspace"], "true") + + def test_one_failing_shard_keeps_the_whole_suite(self) -> None: + title = render({"workspace": "true"}) + jobs = [ + self._suite_job("workspace", "success"), + self._suite_job("workspace", "failure"), + ] + self.assertEqual(runs.config_from_run(title, jobs=jobs)["workspace"], "true") + + def test_a_suite_passed_on_the_auto_default_is_retired_too(self) -> None: + """``auto`` is the default every unattended run reaches the suite on, + and a ``--failed`` retrigger leaves the whitelist empty, which + call-orchestrator.yml still reads as global scope. Keeping ``auto`` + would rerun a green suite on every retrigger of the chain.""" + for suite in runs.SUITE_JOB_IDS: + with self.subTest(suite): + jobs = [self._suite_job(suite, "success")] + logged = {suite: "auto"} + config = runs.config_from_run(render({}), logged, jobs=jobs) + self.assertEqual(config[suite], "false") + + def test_a_suite_passed_without_any_recorded_input_is_retired_too(self) -> None: + for suite in runs.SUITE_JOB_IDS: + with self.subTest(suite): + jobs = [self._suite_job(suite, "success")] + config = runs.config_from_run(render({}), {}, jobs=jobs) + self.assertEqual(config[suite], "false") + + def test_a_suite_left_on_auto_that_failed_stays_on_auto(self) -> None: + for suite in runs.SUITE_JOB_IDS: + with self.subTest(suite): + jobs = [self._suite_job(suite, "failure")] + logged = {suite: "auto"} + config = runs.config_from_run(render({}), logged, jobs=jobs) + self.assertEqual(config[suite], "auto") + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/cli/administration/deploy/ci/test_selections.py b/tests/unit/python/cli/administration/deploy/ci/test_selections.py index 09756835ce..4f53ab0c55 100644 --- a/tests/unit/python/cli/administration/deploy/ci/test_selections.py +++ b/tests/unit/python/cli/administration/deploy/ci/test_selections.py @@ -5,6 +5,7 @@ from typing import ClassVar from cli.administration.deploy.ci import selections from tests.utils.ci.job_names import deploy_job_name +from utils.github.variant import selection from utils.github.variant.pools import DISTROS, FILESYSTEMS @@ -36,54 +37,226 @@ class TestResumeOffset(unittest.TestCase): _row("web-app-c", "0", "host"), ] + def test_a_row_proven_under_the_source_sweeps_axes_still_counts(self) -> None: + """The retrigger is a new run with a new sweep number, so its ranking + assigns row a a different mode, onion state and distro than the run + that proved it. Comparing the full tokens stopped every walk on its + first row and pinned the regular line to the head forever.""" + jobs = [_job(deploy_job_name("swarm", "web-app-a", "0", tor=True), "success")] + self.assertEqual( + selections.resume_offset(self._REGULAR, selections.proven_rows(jobs)), + "web-app-a#0", + ) + def test_a_run_that_deployed_nothing_starts_at_the_head(self) -> None: self.assertEqual(selections.resume_offset(self._REGULAR, set()), "") def test_the_offset_is_the_last_row_of_the_leading_run(self) -> None: - deployed = { - "web-app-a#0@compose+clearnet" + _AXES, - "web-app-b#1@swarm+tor" + _AXES, - } + proven = {"web-app-a#0", "web-app-b#1"} + self.assertEqual(selections.resume_offset(self._REGULAR, proven), "web-app-b#1") + + def test_a_red_row_stops_the_scan_so_the_line_walks_it_again(self) -> None: + jobs = [ + _job(deploy_job_name("docker", "web-app-a", "0"), "success"), + _job(deploy_job_name("swarm", "web-app-b", "1", tor=True), "failure"), + _job(deploy_job_name("host", "web-app-c", "0"), "success"), + ] self.assertEqual( - selections.resume_offset(self._REGULAR, deployed), "web-app-b#1" + selections.resume_offset(self._REGULAR, selections.proven_rows(jobs)), + "web-app-a#0", ) def test_the_offset_carries_no_axes_so_it_survives_a_new_sweep(self) -> None: """Every axis rotates with the sweep number and a retrigger gets a fresh one, so an axis-pinned offset would resolve only in the sweep it was computed at and abort every chunk's discovery in the others.""" - deployed = {"web-app-a#0@compose+clearnet" + _AXES} - offset = selections.resume_offset(self._REGULAR, deployed) + offset = selections.resume_offset(self._REGULAR, {"web-app-a#0"}) self.assertNotIn("@", offset) self.assertNotIn("+", offset) self.assertNotIn("%", offset) self.assertNotIn("/", offset) def test_a_gap_stops_the_scan_rather_than_skipping_past_it(self) -> None: - deployed = { - "web-app-a#0@compose+clearnet" + _AXES, - "web-app-c#0@host+clearnet" + _AXES, - } - self.assertEqual( - selections.resume_offset(self._REGULAR, deployed), "web-app-a#0" - ) + proven = {"web-app-a#0", "web-app-c#0"} + self.assertEqual(selections.resume_offset(self._REGULAR, proven), "web-app-a#0") def test_a_run_that_covered_everything_resumes_at_the_last_row(self) -> None: - deployed = { - "web-app-a#0@compose+clearnet" + _AXES, - "web-app-b#1@swarm+tor" + _AXES, - "web-app-c#0@host+clearnet" + _AXES, - } self.assertEqual( - selections.resume_offset(self._REGULAR, deployed), "web-app-c#0" + selections.resume_offset(self._REGULAR, self._ALL_PROVEN), "web-app-c#0" ) - def test_the_verdict_does_not_matter_only_that_the_row_ran(self) -> None: - jobs = [ - _job(deploy_job_name("swarm", "web-app-b", "1", tor=True), "failure"), - _job(deploy_job_name("docker", "web-app-a", "0"), "success"), - ] + _ALL_PROVEN: ClassVar[set[str]] = {"web-app-a#0", "web-app-b#1", "web-app-c#0"} + + def test_a_role_the_priority_line_takes_whole_is_never_the_offset(self) -> None: + """A variant-less pin blacklists its whole role from the regular query, + so an offset naming one of its rows resolves against nothing.""" self.assertEqual( - selections.deployed_selections(jobs), - {"web-app-a#0@compose+clearnet" + _AXES, "web-app-b#1@swarm+tor" + _AXES}, + selections.resume_offset( + self._REGULAR, self._ALL_PROVEN, selection.parse_list("web-app-c") + ), + "web-app-b#1", ) + + def test_a_variant_the_priority_line_pins_is_never_the_offset(self) -> None: + self.assertEqual( + selections.resume_offset( + self._REGULAR, self._ALL_PROVEN, selection.parse_list("web-app-c#0") + ), + "web-app-b#1", + ) + + def test_a_pin_on_another_variant_leaves_the_row_offsettable(self) -> None: + self.assertEqual( + selections.resume_offset( + self._REGULAR, self._ALL_PROVEN, selection.parse_list("web-app-c#4") + ), + "web-app-c#0", + ) + + def test_a_claimed_row_mid_line_does_not_stop_the_scan(self) -> None: + self.assertEqual( + selections.resume_offset( + self._REGULAR, self._ALL_PROVEN, selection.parse_list("web-app-b") + ), + "web-app-c#0", + ) + + def test_every_green_row_claimed_starts_at_the_head(self) -> None: + self.assertEqual( + selections.resume_offset( + self._REGULAR, + self._ALL_PROVEN, + selection.parse_list("web-app-a web-app-b web-app-c"), + ), + "", + ) + + +class TestCarriedOffset(unittest.TestCase): + """A retrigger inherits the window its source run was given.""" + + _REGULAR: ClassVar[list[dict]] = [ + _row("web-app-a", "0", "compose"), + _row("web-app-b", "1", "swarm", tor=True), + _row("web-app-c", "0", "host"), + ] + + def test_nothing_green_behind_the_carried_offset_keeps_it(self) -> None: + self.assertEqual( + selections.resume_offset(self._REGULAR, set(), carried="web-app-b#1"), + "web-app-b#1", + ) + + def test_the_green_stretch_behind_it_moves_it_forward(self) -> None: + proven = {"web-app-b#1", "web-app-c#0"} + self.assertEqual( + selections.resume_offset(self._REGULAR, proven, carried="web-app-b#1"), + "web-app-c#0", + ) + + def test_a_red_row_at_the_carried_offset_is_left_to_its_claim(self) -> None: + """The priority line takes the whole role, so naming that row would + emit an offset resolving against nothing; the next free row is the + answer, and it is still ahead of where the source run started.""" + jobs = [_job(deploy_job_name("swarm", "web-app-b", "1", tor=True), "failure")] + self.assertEqual( + selections.resume_offset( + self._REGULAR, + selections.proven_rows(jobs), + selection.parse_list("web-app-b"), + carried="web-app-b#1", + ), + "web-app-c#0", + ) + + def test_a_row_count_anchors_the_window_too(self) -> None: + self.assertEqual( + selections.resume_offset(self._REGULAR, set(), carried="2"), "web-app-c#0" + ) + + def test_a_vanished_token_falls_forward_to_the_first_green_row(self) -> None: + self.assertEqual( + selections.resume_offset( + self._REGULAR, {"web-app-c#0"}, carried="web-app-gone#0" + ), + "web-app-c#0", + ) + + def test_a_vanished_token_with_nothing_green_starts_at_the_head(self) -> None: + self.assertEqual( + selections.resume_offset(self._REGULAR, set(), carried="web-app-gone#0"), "" + ) + + +class TestProvenRows(unittest.TestCase): + """Only a row green in every combination it ran lets the line walk past.""" + + def test_only_the_successes_are_kept(self) -> None: + jobs = [ + _job(deploy_job_name("docker", "web-app-a", "0"), "success"), + _job(deploy_job_name("swarm", "web-app-b", "1", tor=True), "failure"), + _job(deploy_job_name("host", "web-app-c", "0"), "cancelled"), + ] + self.assertEqual(selections.proven_rows(jobs), {"web-app-a#0"}) + + def test_the_axes_are_dropped_so_the_row_survives_a_new_sweep(self) -> None: + jobs = [_job(deploy_job_name("swarm", "web-app-a", "0", tor=True), "success")] + self.assertEqual(selections.proven_rows(jobs), {"web-app-a#0"}) + + def test_one_red_axis_un_proves_the_whole_row(self) -> None: + """A priority row deploys its whole cross-product, so one role#variant + can carry several verdicts; a green compose job must not carry a red + swarm one past the regular line.""" + jobs = [ + _job(deploy_job_name("docker", "web-app-a", "0"), "success"), + _job(deploy_job_name("swarm", "web-app-a", "0", tor=True), "failure"), + ] + self.assertEqual(selections.proven_rows(jobs), set()) + + def test_one_aborted_axis_un_proves_it_too(self) -> None: + """It reached no verdict, which is the same reason a lone aborted row + stops the walk.""" + jobs = [ + _job(deploy_job_name("docker", "web-app-a", "0"), "success"), + _job(deploy_job_name("swarm", "web-app-a", "0", tor=True), "cancelled"), + ] + self.assertEqual(selections.proven_rows(jobs), set()) + + def test_a_red_axis_of_one_variant_leaves_its_siblings_alone(self) -> None: + jobs = [ + _job(deploy_job_name("docker", "web-app-a", "0"), "failure"), + _job(deploy_job_name("docker", "web-app-a", "1"), "success"), + ] + self.assertEqual(selections.proven_rows(jobs), {"web-app-a#1"}) + + +class TestCollapseToRoles(unittest.TestCase): + """Trading the exact red combination for covering the role.""" + + def test_the_combinations_of_one_role_become_one_entry(self) -> None: + collapsed = selections.collapse_to_roles( + [ + "web-app-a#0@compose+clearnet" + _AXES, + "web-app-a#1@swarm+tor" + _AXES, + "web-app-b#0@swarm+clearnet" + _AXES, + ] + ) + self.assertEqual(collapsed, ["web-app-a", "web-app-b"]) + + def test_nothing_stays_pinned(self) -> None: + """A leftover axis would pin the rotation to a combination nobody chose.""" + for token in selections.collapse_to_roles( + ["web-app-a#2@swarm+tor" + _AXES, "web-app-b#0@compose+clearnet" + _AXES] + ): + with self.subTest(token=token): + self.assertFalse(selection.parse(token).pinned) + + def test_no_role_is_dropped(self) -> None: + tokens = [ + f"web-app-{name}#0@compose+clearnet{_AXES}" for name in ("a", "b", "c") + ] + self.assertEqual(len(selections.collapse_to_roles(tokens)), len(tokens)) + + def test_an_already_bare_role_survives_unchanged(self) -> None: + """An untriggered priority entry may already carry no axes.""" + self.assertEqual(selections.collapse_to_roles(["web-app-a"]), ["web-app-a"]) diff --git a/tests/unit/python/cli/administration/deploy/ci/test_trigger.py b/tests/unit/python/cli/administration/deploy/ci/test_trigger.py index 4989e7f4f9..86b0742b56 100644 --- a/tests/unit/python/cli/administration/deploy/ci/test_trigger.py +++ b/tests/unit/python/cli/administration/deploy/ci/test_trigger.py @@ -5,13 +5,14 @@ import subprocess import unittest import unittest.mock as mock from contextlib import redirect_stdout +from typing import ClassVar from cli.administration.deploy.ci import gh, runs from cli.administration.deploy.ci.trigger import __main__ as trigger from cli.meta.ci import matrix from tests.utils.ci.job_names import deploy_job_name from tests.utils.ci.run_name import render -from utils.github.variant.pools import DISTROS +from utils.github.variant.pools import DISTROS, FILESYSTEMS def _job(mode: str, app: str, conclusion: str) -> dict: @@ -22,6 +23,15 @@ def _job(mode: str, app: str, conclusion: str) -> dict: } +def _green(app: str) -> dict: + """The deploy job that proves the ranking row ``app#0``.""" + return { + "name": deploy_job_name("docker", app, "0"), + "status": "completed", + "conclusion": "success", + } + + _JOBS = [ _job("docker", "web-app-x", "success"), _job("swarm", "web-app-x", "failure"), @@ -57,6 +67,7 @@ class TestTriggerMain(unittest.TestCase): argv: list[str], run: dict | None = None, inputs: dict[str, str] | None = None, + entries: list[dict] | None = None, ) -> tuple[int, list]: calls: list[tuple] = [] buf = io.StringIO() @@ -65,7 +76,7 @@ class TestTriggerMain(unittest.TestCase): mock.patch.object(gh, "resolve_repo", return_value="o/r"), mock.patch.object(runs, "find_last_deploy_run", return_value=run), mock.patch.object(runs, "inputs_from_jobs", return_value=inputs or {}), - mock.patch.object(matrix, "entries_of", return_value=[]), + mock.patch.object(matrix, "entries_of", return_value=entries or []), mock.patch.object( runs, "dispatch_workflow", @@ -190,6 +201,39 @@ class TestTriggerMain(unittest.TestCase): self.assertEqual(rc, 0) self.assertEqual(calls[0], "web-app-never") + _RANKING: ClassVar[list[dict]] = [ + { + "apps": f"web-app-{name}", + "variant": "0", + "mode": "compose", + "tor": "false", + "distro": DISTROS[0], + "filesystem": FILESYSTEMS[0], + "priority": "false", + } + for name in ("a", "b", "c") + ] + + def test_the_carried_offset_is_the_floor_for_the_new_one(self) -> None: + """Without it the retrigger restarts at the head every time and + redeploys the stretch its predecessors already proved.""" + _rc, calls = self._run( + ["--failed"], + run={"_jobs": _JOBS}, + inputs={"offset": "web-app-b#0"}, + entries=self._RANKING, + ) + self.assertEqual(calls[0][4]["offset"], "web-app-b#0") + + def test_the_green_stretch_behind_the_carried_offset_moves_it_on(self) -> None: + _rc, calls = self._run( + ["--failed"], + run={"_jobs": [*_JOBS, _green("web-app-b"), _green("web-app-c")]}, + inputs={"offset": "web-app-b#0"}, + entries=self._RANKING, + ) + self.assertEqual(calls[0][4]["offset"], "web-app-c#0") + def test_failed_nothing_does_not_dispatch(self) -> None: green = [ _job("docker", "web-app-x", "success"), @@ -265,6 +309,36 @@ class TestTriggerMain(unittest.TestCase): self.assertEqual(rc, 0) self.assertEqual(calls[0], ("web-app-a", "", _SOURCE_CONFIG)) + def test_chunk_gate_override_replaces_the_carried_value(self) -> None: + calls: list = [] + with ( + mock.patch.object(gh, "current_branch", return_value="feature/x"), + mock.patch.object(gh, "resolve_repo", return_value="o/r"), + mock.patch.object(gh, "fetch_run", return_value=_SOURCE_RUN), + mock.patch.object(matrix, "entries_of", return_value=[]), + mock.patch.object( + runs, + "dispatch_workflow", + side_effect=lambda wf, ref, wl="", priority="", config=None, repo=None: ( + calls.append(config) + ), + ), + redirect_stdout(io.StringIO()), + ): + rc = trigger.main(["--failed", "--run", _RUN_URL, "--chunk-gate", "true"]) + self.assertEqual(rc, 0) + self.assertEqual(calls[0], {**_SOURCE_CONFIG, "chunk_gate": "true"}) + + def test_chunk_gate_override_without_a_source_run(self) -> None: + rc, calls = self._run(["--chunk-gate", "false"]) + self.assertEqual(rc, 0) + self.assertEqual(calls[0][4], {"chunk_gate": "false"}) + + def test_chunk_gate_rejects_other_values(self) -> None: + with self.assertRaises(SystemExit) as ctx, redirect_stdout(io.StringIO()): + trigger.main(["--chunk-gate", "maybe"]) + self.assertEqual(ctx.exception.code, 2) + def test_failed_no_run_found(self) -> None: rc, calls = self._run(["--failed"], run=None) self.assertEqual(rc, 1) diff --git a/tests/unit/python/cli/administration/deploy/development/inventory/test_nested_overrides.py b/tests/unit/python/cli/administration/deploy/development/inventory/test_nested_overrides.py new file mode 100644 index 0000000000..a473f1031d --- /dev/null +++ b/tests/unit/python/cli/administration/deploy/development/inventory/test_nested_overrides.py @@ -0,0 +1,91 @@ +"""Unit tests for `cli.administration.deploy.development.inventory.nested_overrides`. + +The service registry is stubbed: what matters is which role a claim is +attributed to, not how a service key resolves to its provider. +""" + +from __future__ import annotations + +import unittest +from unittest.mock import patch + +from cli.administration.deploy.development.inventory.nested_overrides import ( + NestedOverrideConflictError, + collect_provider_overrides, +) + +_REGISTRY = { + "openwebui": {"role": "web-app-openwebui"}, + "gitea": {"role": "web-app-gitea"}, +} + +_PATCH = ( + "cli.administration.deploy.development.inventory.nested_overrides" + ".build_service_registry_from_roles_dir" +) + + +class TestCollectProviderOverrides(unittest.TestCase): + def _collect(self, payloads, registry=None): + with patch(_PATCH, autospec=True) as build: + build.return_value = _REGISTRY if registry is None else registry + return collect_provider_overrides(payloads, roles_dir="/roles") + + def test_a_named_topic_reaches_its_provider(self) -> None: + payloads = { + "web-app-moodle": {"services": {"openwebui": {"services": None}}}, + } + self.assertEqual( + {"web-app-openwebui": {"services": None}}, self._collect(payloads) + ) + + def test_several_topics_of_one_provider_are_collected_together(self) -> None: + payloads = { + "web-app-moodle": { + "services": { + "openwebui": {"services": None, "addons": {"whisper": False}}, + }, + }, + } + self.assertEqual( + {"web-app-openwebui": {"services": None, "addons": {"whisper": False}}}, + self._collect(payloads), + ) + + def test_a_roles_own_entry_is_not_an_override(self) -> None: + payloads = {"web-app-gitea": {"services": {"gitea": {"users": {"a": 1}}}}} + self.assertEqual({}, self._collect(payloads)) + + def test_an_unregistered_service_key_is_skipped(self) -> None: + payloads = {"web-app-moodle": {"services": {"nowhere": {"services": None}}}} + self.assertEqual({}, self._collect(payloads)) + + def test_two_roles_agreeing_is_not_a_conflict(self) -> None: + payloads = { + "web-app-moodle": {"services": {"openwebui": {"services": None}}}, + "web-app-gitea": {"services": {"openwebui": {"services": None}}}, + } + self.assertEqual( + {"web-app-openwebui": {"services": None}}, self._collect(payloads) + ) + + def test_two_roles_demanding_different_values_raises(self) -> None: + payloads = { + "web-app-moodle": {"services": {"openwebui": {"services": None}}}, + "web-app-gitea": {"services": {"openwebui": {"services": {"a": 1}}}}, + } + with self.assertRaises(NestedOverrideConflictError): + self._collect(payloads) + + def test_a_round_without_overrides_never_builds_the_registry(self) -> None: + payloads = {"web-app-moodle": {"services": {"openwebui": {"enabled": True}}}} + with patch(_PATCH, autospec=True) as build: + build.return_value = _REGISTRY + self.assertEqual( + {}, collect_provider_overrides(payloads, roles_dir="/roles") + ) + build.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/deploy/development/test_coredns.py b/tests/unit/python/cli/administration/deploy/development/test_coredns.py new file mode 100644 index 0000000000..ad09f849a9 --- /dev/null +++ b/tests/unit/python/cli/administration/deploy/development/test_coredns.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path + +from cli.administration.deploy.development.coredns import CoreDNSCorefileRenderer +from utils.cache.files import PROJECT_ROOT, read_text + +TEMPLATE = "compose/coredns/Corefile.tmpl" + + +def _render() -> str: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / ".env").write_text( + 'INFINITO_DOMAIN=infinito.test\nINFINITO_IP4="172.30.0.10"\n', + encoding="utf-8", + ) + template = root / TEMPLATE + template.parent.mkdir(parents=True) + template.write_text(read_text(str(PROJECT_ROOT / TEMPLATE)), encoding="utf-8") + out = CoreDNSCorefileRenderer(repo_root=root).render(show_preview=False) + return read_text(str(out)) + + +class TestCoreDNSCorefileRenderer(unittest.TestCase): + def test_the_domain_regex_is_derived_from_the_domain_escaped_once(self) -> None: + corefile = _render() + self.assertIn("match ^infinito\\.test\\.$", corefile) + self.assertIn("match ^(.*)\\.infinito\\.test\\.$", corefile) + self.assertNotIn("\\\\", corefile) + self.assertNotIn("${", corefile) + + def test_the_deployment_zone_answers_every_type_itself(self) -> None: + corefile = _render() + catch_all = "template IN ANY infinito.test {" + self.assertIn(catch_all, corefile) + self.assertIn("IN SOA ns.infinito.test. hostmaster.infinito.test.", corefile) + lines = corefile.splitlines() + self.assertLess( + max( + index + for index, line in enumerate(lines) + if line.strip() == "template IN A {" + ), + next( + index for index, line in enumerate(lines) if line.strip() == catch_all + ), + "the zone-wide template must come after the A templates, or it " + "answers their names with NODATA and the deployment loses its own " + "addresses", + ) + self.assertLess( + lines.index(f" {catch_all}"), + next(index for index, line in enumerate(lines) if "forward ." in line), + "a type the zone does not answer must not reach the public " + "resolvers: they return NXDOMAIN for the reserved TLD, and a " + "caching resolver in front then denies every type of that name, " + "including the A record the deployment depends on", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/inventory/credentials/test_reset_cli.py b/tests/unit/python/cli/administration/inventory/credentials/test_reset_cli.py new file mode 100644 index 0000000000..a5f4c16444 --- /dev/null +++ b/tests/unit/python/cli/administration/inventory/credentials/test_reset_cli.py @@ -0,0 +1,85 @@ +import re +import shutil +import tempfile +import unittest +from pathlib import Path + +from cli.administration.inventory.credentials.reset.cli import ( + _backup, + _mirror_host_vars, + _parse_app_variants, +) + +STAMPED = re.compile(r"^localhost\.yml\.\d{8}T\d{6}Z\.backup$") + + +class TestBackup(unittest.TestCase): + def setUp(self): + self.workdir = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.workdir, ignore_errors=True) + self.host_vars_file = self.workdir / "localhost.yml" + self.host_vars_file.write_text("TLS_ENABLED: true\n", encoding="utf-8") + + def test_the_copy_carries_a_utc_stamp(self): + self.assertRegex(_backup(self.host_vars_file).name, STAMPED) + + def test_the_copy_holds_the_pre_rotation_content(self): + copy = _backup(self.host_vars_file) + self.host_vars_file.write_text("TLS_ENABLED: false\n", encoding="utf-8") + content = copy.read_text(encoding="utf-8") # nocheck: cache-read + self.assertEqual(content, "TLS_ENABLED: true\n") + + def test_the_original_survives(self): + _backup(self.host_vars_file) + self.assertTrue(self.host_vars_file.exists()) + + +class TestMirrorHostVars(unittest.TestCase): + def setUp(self): + self.host_vars_dir = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.host_vars_dir, ignore_errors=True) + self.source = self.host_vars_dir / "mgr-01.yml" + self.source.write_text("rotated: true\n", encoding="utf-8") + for host in ("wrk-01", "nfs-server"): + (self.host_vars_dir / f"{host}.yml").write_text( + "rotated: false\n", encoding="utf-8" + ) + + def test_every_other_host_gets_the_rotated_file(self): + mirrored = _mirror_host_vars(self.host_vars_dir, self.source) + self.assertEqual(mirrored, ["nfs-server", "wrk-01"]) + for host in mirrored: + path = self.host_vars_dir / f"{host}.yml" + self.assertEqual( + path.read_text(encoding="utf-8"), # nocheck: cache-read + "rotated: true\n", + ) + + def test_a_backup_is_not_mirrored_over(self): + backup = _backup(self.source) + _mirror_host_vars(self.host_vars_dir, self.source) + content = backup.read_text(encoding="utf-8") # nocheck: cache-read + self.assertEqual(content, "rotated: true\n") + self.assertNotIn( + backup.stem, _mirror_host_vars(self.host_vars_dir, self.source) + ) + + +class TestParseAppVariants(unittest.TestCase): + def test_an_absent_value_is_empty(self): + self.assertEqual(_parse_app_variants(None), {}) + + def test_indices_become_integers(self): + self.assertEqual(_parse_app_variants('{"web-app-a": "2"}'), {"web-app-a": 2}) + + def test_broken_json_aborts(self): + with self.assertRaises(SystemExit): + _parse_app_variants("{") + + def test_a_non_integer_index_aborts(self): + with self.assertRaises(SystemExit): + _parse_app_variants('{"web-app-a": "base"}') + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/inventory/credentials/test_vault.py b/tests/unit/python/cli/administration/inventory/credentials/test_vault.py index 5f0c204e33..61fed24732 100644 --- a/tests/unit/python/cli/administration/inventory/credentials/test_vault.py +++ b/tests/unit/python/cli/administration/inventory/credentials/test_vault.py @@ -2,9 +2,12 @@ from __future__ import annotations -import subprocess +import tempfile import unittest import unittest.mock +from pathlib import Path + +from ansible.errors import AnsibleError from cli.administration.inventory.credentials.vault import ( _make_vault_scalar_from_text, @@ -98,27 +101,46 @@ class TestVaultHandlerIntegration(unittest.TestCase): """Black-box coverage of the VaultHandler that ``to_vault_block`` delegates to for plaintext encryption.""" - def test_encrypt_string_success(self): - handler = VaultHandler("dummy_pw_file") - fake_output = "Encrypted data" - completed = subprocess.CompletedProcess( - args=["ansible-vault"], returncode=0, stdout=fake_output, stderr="" - ) - with unittest.mock.patch("subprocess.run", return_value=completed) as proc_run: - result = handler.encrypt_string("plain_val", "name") - proc_run.assert_called_once() - self.assertEqual(result, fake_output) + def setUp(self): + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.password_file = Path(self._tmp.name) / "vault.pw" + self.password_file.write_text("unit-test-vault-password\n", encoding="utf-8") + self.handler = VaultHandler(str(self.password_file)) - def test_encrypt_string_failure_raises(self): - handler = VaultHandler("dummy_pw_file") - completed = subprocess.CompletedProcess( - args=["ansible-vault"], returncode=1, stdout="", stderr="error" + def test_encrypt_string_round_trips_through_the_vault(self): + snippet = self.handler.encrypt_string("plain_val", "name") + body = "\n".join(line.strip() for line in snippet.splitlines()[1:]) + self.assertEqual(self.handler._vault.decrypt(body).decode(), "plain_val") + + def test_encrypt_string_keeps_the_layout_encrypt_leaves_unindents(self): + lines = self.handler.encrypt_string("plain_val", "name").splitlines() + self.assertEqual( + lines[0], "name: !vault |", "first line must stay the YAML key and tag" ) - with ( - unittest.mock.patch("subprocess.run", return_value=completed), - self.assertRaises(RuntimeError), - ): - handler.encrypt_string("plain_val", "name") + indents = {len(line) - len(line.lstrip()) for line in lines[1:]} + self.assertEqual( + indents, {10}, "encrypt_leaves strips a uniform body indent of 10" + ) + self.assertEqual(lines[1].strip(), "$ANSIBLE_VAULT;1.1;AES256") + + def test_values_that_look_like_flags_still_encrypt(self): + for value in ("-leading-dash", "--stdin-name"): + with self.subTest(value=value): + snippet = self.handler.encrypt_string(value, "k") + body = "\n".join(line.strip() for line in snippet.splitlines()[1:]) + self.assertEqual(self.handler._vault.decrypt(body).decode(), value) + + def test_missing_password_file_raises(self): + with self.assertRaises(AnsibleError): + VaultHandler("dummy_pw_file").encrypt_string("plain_val", "name") + + def test_password_file_whitespace_is_stripped_like_ansible_does(self): + padded = Path(self._tmp.name) / "padded.pw" + padded.write_text(" unit-test-vault-password \n", encoding="utf-8") + snippet = VaultHandler(str(padded)).encrypt_string("plain_val", "name") + body = "\n".join(line.strip() for line in snippet.splitlines()[1:]) + self.assertEqual(self.handler._vault.decrypt(body).decode(), "plain_val") if __name__ == "__main__": # pragma: no cover diff --git a/tests/unit/python/cli/administration/inventory/onion/test_onion.py b/tests/unit/python/cli/administration/inventory/onion/test_onion.py index e73707bec9..a767171f5e 100644 --- a/tests/unit/python/cli/administration/inventory/onion/test_onion.py +++ b/tests/unit/python/cli/administration/inventory/onion/test_onion.py @@ -1,7 +1,7 @@ import tempfile import unittest +import unittest.mock as mock from pathlib import Path -from unittest import mock from cli.administration.inventory.onion import ensure_node_onion, identity_hs_dir diff --git a/tests/unit/python/cli/administration/inventory/provision/test_host_vars.py b/tests/unit/python/cli/administration/inventory/provision/test_host_vars.py index d8592fd3d9..d55382d907 100644 --- a/tests/unit/python/cli/administration/inventory/provision/test_host_vars.py +++ b/tests/unit/python/cli/administration/inventory/provision/test_host_vars.py @@ -44,9 +44,14 @@ existing_key: foo self.assertEqual(data["existing_key"], "foo") self.assertEqual(getattr(data["secret"], "tag", None), "!vault") - self.assertNotIn("DOMAIN_PRIMARY", data) - self.assertNotIn("TLS_ENABLED", data) - self.assertNotIn("networks", data) + baked = ( + "must stay out of host_vars; it lives in group_vars or the " + "inventory vars-file so env-driven values propagate instead of " + "being silently overridden" + ) + self.assertNotIn("DOMAIN_PRIMARY", data, f"DOMAIN_PRIMARY {baked}") + self.assertNotIn("TLS_ENABLED", data, f"TLS_ENABLED {baked}") + self.assertNotIn("networks", data, f"networks {baked}") def test_ensure_host_vars_file_sets_local_connection_for_localhost(self): yaml_rt = YAML(typ="rt") @@ -142,7 +147,7 @@ ansible_become_password: !vault | """ with patch( - "cli.administration.inventory.provision.host_vars.VaultHandler" + "cli.administration.inventory.provision.ruamel_io.VaultHandler" ) as vh: inst = vh.return_value inst.encrypt_string.return_value = vaulted_snippet diff --git a/tests/unit/python/cli/administration/inventory/provision/test_reset.py b/tests/unit/python/cli/administration/inventory/provision/test_reset.py new file mode 100644 index 0000000000..4995e6059f --- /dev/null +++ b/tests/unit/python/cli/administration/inventory/provision/test_reset.py @@ -0,0 +1,222 @@ +import shutil +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from ruamel.yaml import YAML + +from cli.administration.inventory.provision.reset import reset_credentials +from cli.administration.inventory.provision.ruamel_io import load_document +from utils.roles.mapping import ROLE_FILE_META_USERS + +MODULE = "cli.administration.inventory.provision.reset" + +HOST_VARS = """\ +--- +# This comment must survive the rotation. +TLS_ENABLED: true + +ansible_become_password: !vault | + $ANSIBLE_VAULT;1.1;AES256 + 6265636f6d65 + +applications: + web-app-a: + secrets: + credentials: + api_key: !vault | + $ANSIBLE_VAULT;1.1;AES256 + 6170695f6b6579 + smtp_password: '' + recaptcha: + secret: !vault | + $ANSIBLE_VAULT;1.1;AES256 + 7365637265740a + features: + matomo: true + web-app-keycloak: + secrets: + credentials: + database_password: !vault | + $ANSIBLE_VAULT;1.1;AES256 + 6462706173730a + +users: + administrator: + password: !vault | + $ANSIBLE_VAULT;1.1;AES256 + 61646d696e0a + newsletter: + password: !vault | + $ANSIBLE_VAULT;1.1;AES256 + 6e6577730a + biber: + password: VeryUnsecurePassword!1 + keycloak-bot: + password: !vault | + $ANSIBLE_VAULT;1.1;AES256 + 626f740a +""" + +DECLARED_USERS = """\ +--- +administrator: + uid: 1001 +newsletter: + uid: 1002 +""" + +KEYCLOAK_USERS = ( + DECLARED_USERS + + """\ +keycloak-bot: + uid: 1003 +""" +) + + +class TestResetCredentials(unittest.TestCase): + def setUp(self): + self.workdir = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.workdir, ignore_errors=True) + + self.roles_dir = self.workdir / "roles" + declarations = { + "web-app-a": DECLARED_USERS, + "web-app-keycloak": KEYCLOAK_USERS, + } + for application_id, declared in declarations.items(): + users_file = self.roles_dir / application_id / ROLE_FILE_META_USERS + users_file.parent.mkdir(parents=True, exist_ok=True) + users_file.write_text(declared, encoding="utf-8") + + self.host_vars_file = self.workdir / "host_vars" / "localhost.yml" + self.host_vars_file.parent.mkdir(parents=True, exist_ok=True) + self.host_vars_file.write_text(HOST_VARS, encoding="utf-8") + + def _reset(self, **overrides): + arguments = { + "application_ids": ["web-app-a", "web-app-keycloak"], + "roles_dir": self.roles_dir, + "host_vars_file": self.host_vars_file, + "vault_password_file": self.workdir / ".password", + "project_root": self.workdir, + "env": None, + "schema": True, + "users": True, + "exclude": {"administrator"}, + } + arguments.update(overrides) + with ( + patch(f"{MODULE}.generate_credentials_for_roles") as credentials, + patch(f"{MODULE}.generate_user_passwords") as users, + ): + rotated = reset_credentials(**arguments) + return rotated, credentials, users + + def _document(self): + return load_document(self.host_vars_file) + + def _credentials(self, application_id): + """Return one application's credentials from the rotated document. + + Args: + application_id: the application to read. + """ + application = self._document()["applications"][application_id] + return application["secrets"]["credentials"] + + def test_every_generated_credential_is_dropped(self): + self._reset() + credentials = self._credentials("web-app-a") + self.assertNotIn("api_key", credentials) + self.assertNotIn("secret", credentials["recaptcha"]) + + def test_an_operator_supplied_plain_value_survives(self): + self._reset() + self.assertEqual(self._credentials("web-app-a")["smtp_password"], "") + + def test_an_excluded_application_is_untouched(self): + self._reset(exclude={"administrator", "web-app-keycloak"}) + self.assertIn("database_password", self._credentials("web-app-keycloak")) + + def test_an_application_outside_the_rotation_keeps_its_credentials(self): + """Dropping must not outrun regeneration. + + The drop side walks the document while the generate side walks + `credential_ids`. A matrix host_vars file carries a block per mirror + artefact too, so a document-wide drop would delete credentials the + caller never writes back. + """ + _, credentials, _ = self._reset(credential_ids=["web-app-a"]) + self.assertIn("database_password", self._credentials("web-app-keycloak")) + self.assertNotIn("api_key", self._credentials("web-app-a")) + self.assertEqual(credentials.call_args.kwargs["application_ids"], ["web-app-a"]) + + def test_narrowing_the_credentials_still_rotates_every_user(self): + """A narrowed credential scope must not narrow the user passwords. + + Both halves used to share one id list, so scoping the credentials to + the round silently stopped rotating the users of every other role. + """ + _, _, users = self._reset(credential_ids=["web-app-a"]) + self.assertNotIn("password", self._document()["users"]["keycloak-bot"]) + self.assertEqual( + users.call_args.kwargs["application_ids"], + ["web-app-a", "web-app-keycloak"], + ) + + def test_an_excluded_user_keeps_its_password(self): + self._reset() + users = self._document()["users"] + self.assertIn("password", users["administrator"]) + self.assertNotIn("password", users["newsletter"]) + + def test_an_undeclared_user_keeps_its_password(self): + self._reset() + self.assertIn("password", self._document()["users"]["biber"]) + + def test_the_become_password_is_untouched(self): + self._reset() + self.assertIn("ansible_become_password", self._document()) + + def test_unrelated_keys_and_comments_survive(self): + self._reset() + text = self.host_vars_file.read_text(encoding="utf-8") # nocheck: cache-read + self.assertIn("This comment must survive the rotation.", text) + self.assertTrue(self._document()["applications"]["web-app-a"]["features"]) + + def test_the_dropped_values_are_regenerated(self): + _, credentials, users = self._reset() + credentials.assert_called_once() + users.assert_called_once() + + def test_only_schema_leaves_the_users_alone(self): + _, credentials, users = self._reset(users=False) + self.assertIn("password", self._document()["users"]["newsletter"]) + users.assert_not_called() + credentials.assert_called_once() + + def test_only_users_leaves_the_credentials_alone(self): + _, credentials, users = self._reset(schema=False) + self.assertIn("api_key", self._credentials("web-app-a")) + credentials.assert_not_called() + users.assert_called_once() + + def test_the_rotated_count_covers_both_sections(self): + rotated, _, _ = self._reset() + self.assertEqual(rotated, 5) + + def test_rotating_nothing_aborts(self): + with self.assertRaises(SystemExit): + self._reset(schema=False, users=False) + + def test_the_result_is_still_loadable_yaml(self): + self._reset() + with self.host_vars_file.open(encoding="utf-8") as handle: + self.assertIsNotNone(YAML(typ="rt").load(handle)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/inventory/provision/test_role_resolver.py b/tests/unit/python/cli/administration/inventory/provision/test_role_resolver.py index a360396359..618a80d9db 100644 --- a/tests/unit/python/cli/administration/inventory/provision/test_role_resolver.py +++ b/tests/unit/python/cli/administration/inventory/provision/test_role_resolver.py @@ -4,11 +4,13 @@ from pathlib import Path from unittest.mock import patch from cli.administration.inventory.provision.role_resolver import resolve_role_path +from cli.meta.roles.applications.role_name import EXIT_NO_SUCH_APPLICATION_ROLE class _Result: - def __init__(self, stdout: str): + def __init__(self, stdout: str, returncode: int): self.stdout = stdout + self.returncode = returncode class TestRoleResolver(unittest.TestCase): @@ -21,7 +23,7 @@ class TestRoleResolver(unittest.TestCase): with patch( "cli.administration.inventory.provision.role_resolver.run_subprocess", - return_value=_Result("web-app-nextcloud\n"), + return_value=_Result("web-app-nextcloud\n", 0), ) as rs: p = resolve_role_path( application_id="nextcloud", @@ -45,7 +47,7 @@ class TestRoleResolver(unittest.TestCase): with patch( "cli.administration.inventory.provision.role_resolver.run_subprocess", - return_value=_Result("roles/web-app-matomo\n"), + return_value=_Result("roles/web-app-matomo\n", 0), ): p = resolve_role_path( application_id="matomo", @@ -64,8 +66,26 @@ class TestRoleResolver(unittest.TestCase): with patch( "cli.administration.inventory.provision.role_resolver.run_subprocess", - return_value=_Result("\n"), + return_value=_Result("\n", 0), ): p = resolve_role_path("x", roles_dir, tmp, env=None) self.assertIsNone(p) + + def test_an_id_that_is_no_application_role_resolves_to_none(self): + with tempfile.TemporaryDirectory() as tmpdir: + tmp = Path(tmpdir) + roles_dir = tmp / "roles" + roles_dir.mkdir() + (roles_dir / "sys-ctl-hlth-csp").mkdir() + + with patch( + "cli.administration.inventory.provision.role_resolver.run_subprocess", + return_value=_Result("", EXIT_NO_SUCH_APPLICATION_ROLE), + ) as rs: + p = resolve_role_path("sys-ctl-hlth-csp", roles_dir, tmp, env=None) + + self.assertIsNone(p) + self.assertIn( + EXIT_NO_SUCH_APPLICATION_ROLE, rs.call_args.kwargs["ok_returncodes"] + ) diff --git a/tests/unit/python/cli/administration/inventory/provision/test_ruamel_io.py b/tests/unit/python/cli/administration/inventory/provision/test_ruamel_io.py new file mode 100644 index 0000000000..dbbe89da1c --- /dev/null +++ b/tests/unit/python/cli/administration/inventory/provision/test_ruamel_io.py @@ -0,0 +1,101 @@ +import tempfile +import unittest +from pathlib import Path + +from ruamel.yaml.comments import CommentedMap + +from cli.administration.inventory.provision.ruamel_io import ( + as_commented_map, + dump_document, + ensure_map, + load_document, +) + + +class TestAsCommentedMap(unittest.TestCase): + """The migration branch every writer in the package relies on.""" + + def test_a_mapping_is_returned_unchanged(self): + original = CommentedMap() + original["a"] = 1 + + self.assertIs(original, as_commented_map(original)) + + def test_none_becomes_an_empty_map(self): + self.assertEqual(CommentedMap(), as_commented_map(None)) + + def test_a_plain_dict_is_migrated(self): + migrated = as_commented_map({"a": 1, "b": {"c": 2}}) + + self.assertIsInstance(migrated, CommentedMap) + self.assertEqual(1, migrated["a"]) + self.assertEqual({"c": 2}, migrated["b"]) + + def test_a_sequence_root_aborts_rather_than_silently_emptying(self): + with self.assertRaises((TypeError, ValueError)): + as_commented_map([1, 2, 3]) + + +class TestLoadDocument(unittest.TestCase): + def test_a_missing_file_yields_an_empty_map(self): + with tempfile.TemporaryDirectory() as tmp: + self.assertEqual(CommentedMap(), load_document(Path(tmp) / "absent.yml")) + + def test_an_empty_file_yields_an_empty_map(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "empty.yml" + path.write_text("", encoding="utf-8") + + self.assertEqual(CommentedMap(), load_document(path)) + + def test_a_sequence_root_is_refused(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "list.yml" + path.write_text("- a\n- b\n", encoding="utf-8") + + with self.assertRaises((TypeError, ValueError)): + load_document(path) + + +class TestDumpDocument(unittest.TestCase): + def test_a_missing_parent_directory_is_created(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "nested" / "deeper" / "host.yml" + document = CommentedMap() + document["a"] = 1 + + dump_document(path, document) + + self.assertTrue(path.exists()) + self.assertEqual(1, load_document(path)["a"]) + + +class TestEnsureMap(unittest.TestCase): + def test_a_missing_key_is_created(self): + node = CommentedMap() + + child = ensure_map(node, "users") + + self.assertIsInstance(child, CommentedMap) + self.assertIs(child, node["users"]) + + def test_an_existing_map_is_reused(self): + node = CommentedMap() + existing = CommentedMap() + existing["keep"] = True + node["users"] = existing + + self.assertIs(existing, ensure_map(node, "users")) + + def test_a_non_map_value_is_replaced(self): + node = CommentedMap() + node["users"] = "not-a-map" + + child = ensure_map(node, "users") + + self.assertIsInstance(child, CommentedMap) + self.assertEqual(CommentedMap(), child) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/inventory/provision/test_services_disabler.py b/tests/unit/python/cli/administration/inventory/provision/test_services_disabler.py index 3b6d865ff2..59155d1424 100644 --- a/tests/unit/python/cli/administration/inventory/provision/test_services_disabler.py +++ b/tests/unit/python/cli/administration/inventory/provision/test_services_disabler.py @@ -188,6 +188,36 @@ class TestApplyServicesDisabled(unittest.TestCase): dump_yaml(role_dir / ROLE_FILE_META_SERVICES, services) dump_yaml(role_dir / ROLE_FILE_VARS_MAIN, {"application_id": role_name}) + def test_a_role_without_shared_in_its_contract_does_not_get_one(self): + self._write_host_vars( + {"applications": {"web-svc-cdn": {"services": {"dashboard": {}}}}} + ) + self._make_role("web-svc-cdn", {"dashboard": {"enabled": False}}) + + apply_services_disabled(self.host_vars, ["dashboard"], self.roles_dir) + + service = self._read_host_vars()["applications"]["web-svc-cdn"]["services"][ + "dashboard" + ] + self.assertEqual(False, service["enabled"]) + self.assertNotIn("shared", service) + + def test_a_role_declaring_both_toggles_still_gets_both(self): + self._write_host_vars( + {"applications": {"web-app-nextcloud": {"services": {"dashboard": {}}}}} + ) + self._make_role( + "web-app-nextcloud", {"dashboard": {"enabled": True, "shared": True}} + ) + + apply_services_disabled(self.host_vars, ["dashboard"], self.roles_dir) + + service = self._read_host_vars()["applications"]["web-app-nextcloud"][ + "services" + ]["dashboard"] + self.assertEqual(False, service["enabled"]) + self.assertEqual(False, service["shared"]) + def test_disables_service_in_host_vars_and_removes_from_inventory(self): self._write_host_vars( { diff --git a/tests/unit/python/cli/administration/inventory/provision/test_subprocess_runner.py b/tests/unit/python/cli/administration/inventory/provision/test_subprocess_runner.py index 1f1ed5b22e..e30a41a104 100644 --- a/tests/unit/python/cli/administration/inventory/provision/test_subprocess_runner.py +++ b/tests/unit/python/cli/administration/inventory/provision/test_subprocess_runner.py @@ -15,3 +15,30 @@ class TestSubprocessRunner(unittest.TestCase): with self.assertRaises(SystemExit): run_subprocess(["false"], capture_output=True, env=None) + + def test_an_expected_nonzero_is_handed_back_instead_of_raising(self): + with patch( + "cli.administration.inventory.provision.subprocess_runner.subprocess.run" + ) as sr: + sr.return_value.returncode = 3 + sr.return_value.stdout = "" + sr.return_value.stderr = "no such application role" + + result = run_subprocess( + ["false"], capture_output=True, env=None, ok_returncodes=(0, 3) + ) + + self.assertEqual(result.returncode, 3) + + def test_an_unexpected_nonzero_still_raises_when_another_is_allowed(self): + with patch( + "cli.administration.inventory.provision.subprocess_runner.subprocess.run" + ) as sr: + sr.return_value.returncode = 1 + sr.return_value.stdout = "" + sr.return_value.stderr = "roles path not found" + + with self.assertRaises(SystemExit): + run_subprocess( + ["false"], capture_output=True, env=None, ok_returncodes=(0, 3) + ) diff --git a/tests/unit/python/cli/administration/inventory/provision/test_users_generator.py b/tests/unit/python/cli/administration/inventory/provision/test_users_generator.py new file mode 100644 index 0000000000..d503658a5c --- /dev/null +++ b/tests/unit/python/cli/administration/inventory/provision/test_users_generator.py @@ -0,0 +1,534 @@ +import re +import shutil +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from ruamel.yaml import YAML +from ruamel.yaml.comments import CommentedMap + +from cli.administration.inventory.provision.credentials_generator import ( + generate_credentials_for_roles, +) +from cli.administration.inventory.provision.passwords import ( + generate_declared_user_password, + generate_user_password, +) +from cli.administration.inventory.provision.users_generator import ( + generate_user_passwords, + required_user_policies, +) +from cli.administration.inventory.validate.users import compare_user_keys +from utils.cache.files import read_text +from utils.roles.mapping import ROLE_FILE_META_USERS + +MODULE = "cli.administration.inventory.provision.users_generator" +CREDENTIALS_MODULE = "cli.administration.inventory.provision.credentials_generator" +RUAMEL_MODULE = "cli.administration.inventory.provision.ruamel_io" + +REALISTIC_HOST_VARS = """\ +--- +# Deployment-wide switches. This comment must survive the round trip. +TLS_ENABLED: true + +ansible_become_password: !vault | + $ANSIBLE_VAULT;1.1;AES256 + 36613066303561353835 + 3131316536383864370a + +applications: + web-app-a: + credentials: + # The role's own generated secret. + api_key: !vault | + $ANSIBLE_VAULT;1.1;AES256 + 62343439323132313 + 6161326533353863 + features: + matomo: true # trailing comment +""" + +VAULTED = """\ +{name}: !vault | + $ANSIBLE_VAULT;1.1;AES256 + ENCRYPTEDVALUE +""" + + +def _yaml(): + yaml_rt = YAML(typ="rt") + yaml_rt.preserve_quotes = True + return yaml_rt + + +def _write_role_users(roles_dir: Path, application_id: str, body: str) -> None: + users_file = roles_dir / application_id / ROLE_FILE_META_USERS + users_file.parent.mkdir(parents=True, exist_ok=True) + users_file.write_text(body, encoding="utf-8") + + +class TestRequiredUserPolicies(unittest.TestCase): + def test_only_the_resolved_roles_contribute(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users(roles_dir, "web-app-a", "alice: {}\n") + _write_role_users(roles_dir, "web-app-b", "bob: {}\n") + + self.assertEqual( + ["alice"], list(required_user_policies(roles_dir, ["web-app-a"])) + ) + + def test_a_user_declared_by_two_roles_appears_once(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users(roles_dir, "web-app-a", "administrator: {}\nalice: {}\n") + _write_role_users(roles_dir, "web-app-b", "administrator: {}\n") + + self.assertEqual( + ["administrator", "alice"], + list(required_user_policies(roles_dir, ["web-app-a", "web-app-b"])), + ) + + def test_a_role_without_users_contributes_none(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users(roles_dir, "web-app-a", "alice: {}\n") + + self.assertEqual( + ["alice"], + list( + required_user_policies(roles_dir, ["web-app-a", "web-app-missing"]) + ), + ) + + def test_a_malformed_definition_aborts(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users(roles_dir, "web-app-a", "alice: not-a-mapping\n") + + with self.assertRaises(SystemExit): + required_user_policies(roles_dir, ["web-app-a"]) + + +class TestGenerateUserPasswords(unittest.TestCase): + def _run(self, declared, application_ids, existing=None): + yaml_rt = _yaml() + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) / "roles" + for application_id, body in declared.items(): + _write_role_users(roles_dir, application_id, body) + + host_vars_file = Path(tmpdir) / "host.yml" + vault_pw_file = Path(tmpdir) / ".password" + vault_pw_file.write_text("dummy\n", encoding="utf-8") + + if existing is not None: + with host_vars_file.open("w", encoding="utf-8") as handle: + yaml_rt.dump(existing, handle) + + with ( + patch(f"{RUAMEL_MODULE}.VaultHandler") as vault, + patch( + f"{MODULE}.generate_declared_user_password", return_value="plain" + ), + ): + vault.return_value.encrypt_string.side_effect = lambda _plain, name: ( + VAULTED.format(name=name) + ) + count = generate_user_passwords( + roles_dir=roles_dir, + application_ids=application_ids, + host_vars_file=host_vars_file, + vault_password_file=vault_pw_file, + ) + + if not host_vars_file.exists(): + return count, None + with host_vars_file.open("r", encoding="utf-8") as handle: + return count, yaml_rt.load(handle) + + def test_every_required_user_gets_a_vaulted_password(self): + count, doc = self._run( + {"web-app-a": "administrator: {}\nbiber: {}\n"}, ["web-app-a"] + ) + + self.assertEqual(2, count) + for username in ("administrator", "biber"): + node = doc["users"][username]["password"] + self.assertEqual("!vault", getattr(node, "tag", None)) + + def test_a_user_of_an_unresolved_role_is_not_pinned(self): + count, doc = self._run( + {"web-app-a": "alice: {}\n", "web-app-b": "bob: {}\n"}, ["web-app-a"] + ) + + self.assertEqual(1, count) + self.assertIn("alice", doc["users"]) + self.assertNotIn("bob", doc["users"]) + + def test_an_existing_password_is_never_overwritten(self): + existing = CommentedMap() + users = CommentedMap() + biber = CommentedMap() + biber["password"] = "KEEP_ME" + users["biber"] = biber + existing["users"] = users + + count, doc = self._run( + {"web-app-a": "administrator: {}\nbiber: {}\n"}, + ["web-app-a"], + existing=existing, + ) + + self.assertEqual(1, count) + self.assertEqual("KEEP_ME", doc["users"]["biber"]["password"]) + self.assertEqual( + "!vault", getattr(doc["users"]["administrator"]["password"], "tag", None) + ) + + def test_a_second_run_writes_nothing(self): + yaml_rt = _yaml() + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) / "roles" + _write_role_users(roles_dir, "web-app-a", "biber: {}\n") + + host_vars_file = Path(tmpdir) / "host.yml" + vault_pw_file = Path(tmpdir) / ".password" + vault_pw_file.write_text("dummy\n", encoding="utf-8") + + with ( + patch(f"{RUAMEL_MODULE}.VaultHandler") as vault, + patch( + f"{MODULE}.generate_declared_user_password", return_value="plain" + ), + ): + vault.return_value.encrypt_string.side_effect = lambda _plain, name: ( + VAULTED.format(name=name) + ) + first = generate_user_passwords( + roles_dir=roles_dir, + application_ids=["web-app-a"], + host_vars_file=host_vars_file, + vault_password_file=vault_pw_file, + ) + with host_vars_file.open("r", encoding="utf-8") as handle: + after_first = yaml_rt.load(handle) + second = generate_user_passwords( + roles_dir=roles_dir, + application_ids=["web-app-a"], + host_vars_file=host_vars_file, + vault_password_file=vault_pw_file, + ) + with host_vars_file.open("r", encoding="utf-8") as handle: + after_second = yaml_rt.load(handle) + + self.assertEqual(1, first) + self.assertEqual(0, second) + self.assertEqual( + str(after_first["users"]["biber"]["password"]), + str(after_second["users"]["biber"]["password"]), + ) + + def test_other_inventory_keys_survive(self): + existing = CommentedMap() + existing["TLS_ENABLED"] = True + + _count, doc = self._run({"web-app-a": "biber: {}\n"}, ["web-app-a"], existing) + + self.assertIs(True, doc["TLS_ENABLED"]) + + def test_no_required_users_writes_no_file(self): + count, doc = self._run({"web-app-a": "alice: {}\n"}, []) + + self.assertEqual(0, count) + self.assertIsNone(doc) + + +class TestGeneratedPasswordIsShellSafe(unittest.TestCase): + """The value travels Ansible -> shell -> container exec -> runtime env.""" + + SHELL_SAFE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") + REALM_POLICY = re.compile( + r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{16,}$" + ) + + def test_only_unreserved_marks_survive_into_a_user_password(self): + for _ in range(200): + password = generate_user_password() + self.assertRegex( + password, + self.SHELL_SAFE, + f"{password!r} carries punctuation the exec chain mangles; only " + "the URL-unreserved marks - _ . are known to survive it", + ) + + def test_every_password_satisfies_the_realm_policy(self): + for _ in range(200): + password = generate_user_password() + self.assertRegex(password, self.REALM_POLICY) + self.assertRegex(password, r"[-_.]") + + def test_the_password_is_long_enough_to_afford_the_smaller_alphabet(self): + self.assertGreaterEqual(len(generate_user_password()), 64) + + def test_a_password_shorter_than_the_realm_minimum_is_refused(self): + with self.assertRaises(ValueError): + generate_user_password(8) + + +class TestRealisticInventoryRoundTrip(unittest.TestCase): + """The generator rewrites the whole host_vars, so nothing else may shift.""" + + def _pin(self, tmpdir: Path): + roles_dir = tmpdir / "roles" + _write_role_users(roles_dir, "web-app-a", "biber: {}\n") + + host_vars_file = tmpdir / "host.yml" + host_vars_file.write_text(REALISTIC_HOST_VARS, encoding="utf-8") + vault_pw_file = tmpdir / ".password" + vault_pw_file.write_text("dummy\n", encoding="utf-8") + + with ( + patch(f"{RUAMEL_MODULE}.VaultHandler") as vault, + patch(f"{MODULE}.generate_declared_user_password", return_value="plain"), + ): + vault.return_value.encrypt_string.side_effect = lambda _plain, name: ( + VAULTED.format(name=name) + ) + generate_user_passwords( + roles_dir=roles_dir, + application_ids=["web-app-a"], + host_vars_file=host_vars_file, + vault_password_file=vault_pw_file, + ) + return host_vars_file + + def test_comments_and_vault_scalars_survive(self): + with tempfile.TemporaryDirectory() as tmp: + host_vars_file = self._pin(Path(tmp)) + written = read_text(host_vars_file) + + self.assertIn( + "# Deployment-wide switches. This comment must survive the round trip.", + written, + ) + self.assertIn("# The role's own generated secret.", written) + self.assertIn("# trailing comment", written) + self.assertIn("ansible_become_password: !vault |", written) + self.assertIn("api_key: !vault |", written) + self.assertIn("3131316536383864370a", written) + self.assertIn("6161326533353863", written) + + def test_every_pre_existing_value_is_unchanged(self): + yaml_rt = _yaml() + with tempfile.TemporaryDirectory() as tmp: + host_vars_file = self._pin(Path(tmp)) + with host_vars_file.open("r", encoding="utf-8") as handle: + doc = yaml_rt.load(handle) + + self.assertIs(True, doc["TLS_ENABLED"]) + self.assertIs(True, doc["applications"]["web-app-a"]["features"]["matomo"]) + self.assertEqual( + "!vault", + getattr( + doc["applications"]["web-app-a"]["credentials"]["api_key"], "tag", None + ), + ) + self.assertEqual( + "!vault", getattr(doc["users"]["biber"]["password"], "tag", None) + ) + + def test_the_generated_block_passes_the_inventory_validator(self): + yaml_rt = _yaml() + with tempfile.TemporaryDirectory() as tmp: + host_vars_file = self._pin(Path(tmp)) + with host_vars_file.open("r", encoding="utf-8") as handle: + doc = yaml_rt.load(handle) + + errors = compare_user_keys( + doc["users"], {"biber": {"username": "biber"}}, "test" + ) + + self.assertEqual([], errors) + + +class TestHandoffToCredentialsGenerator(unittest.TestCase): + """Credential generation rewrites the same document immediately afterwards.""" + + def test_the_pinned_users_survive_credentials_generation(self): + yaml_rt = _yaml() + snippet = yaml_rt.load( + "applications:\n" + " web-app-a:\n" + " secrets:\n" + " credentials:\n" + " api_key: generated\n" + ) + + with tempfile.TemporaryDirectory() as tmp: + tmpdir = Path(tmp) + roles_dir = tmpdir / "roles" + _write_role_users(roles_dir, "web-app-a", "biber: {}\n") + + host_vars_file = tmpdir / "host.yml" + vault_pw_file = tmpdir / ".password" + vault_pw_file.write_text("dummy\n", encoding="utf-8") + + with ( + patch(f"{RUAMEL_MODULE}.VaultHandler") as vault, + patch( + f"{MODULE}.generate_declared_user_password", return_value="plain" + ), + ): + vault.return_value.encrypt_string.side_effect = lambda _plain, name: ( + VAULTED.format(name=name) + ) + generate_user_passwords( + roles_dir=roles_dir, + application_ids=["web-app-a"], + host_vars_file=host_vars_file, + vault_password_file=vault_pw_file, + ) + + with patch( + f"{CREDENTIALS_MODULE}._generate_credentials_snippet_for_app", + return_value=snippet, + ): + generate_credentials_for_roles( + application_ids=["web-app-a"], + roles_dir=roles_dir, + host_vars_file=host_vars_file, + vault_password_file=vault_pw_file, + project_root=tmpdir, + env=None, + ) + + with host_vars_file.open("r", encoding="utf-8") as handle: + doc = yaml_rt.load(handle) + + self.assertEqual( + "!vault", getattr(doc["users"]["biber"]["password"], "tag", None) + ) + self.assertEqual( + "generated", + doc["applications"]["web-app-a"]["secrets"]["credentials"]["api_key"], + ) + + +@unittest.skipIf( + shutil.which("ansible-vault") is None, "ansible-vault is not installed" +) +class TestAgainstRealAnsibleVault(unittest.TestCase): + """The mocked snippet shape is an assumption until ansible-vault confirms it.""" + + def test_a_real_vault_value_is_written_and_reparsed(self): + yaml_rt = _yaml() + with tempfile.TemporaryDirectory() as tmp: + tmpdir = Path(tmp) + roles_dir = tmpdir / "roles" + _write_role_users(roles_dir, "web-app-a", "biber: {}\n") + + host_vars_file = tmpdir / "host.yml" + vault_pw_file = tmpdir / ".password" + vault_pw_file.write_text("s3cr3t-vault-password\n", encoding="utf-8") + + count = generate_user_passwords( + roles_dir=roles_dir, + application_ids=["web-app-a"], + host_vars_file=host_vars_file, + vault_password_file=vault_pw_file, + ) + + written = read_text(host_vars_file) + with host_vars_file.open("r", encoding="utf-8") as handle: + doc = yaml_rt.load(handle) + + second = generate_user_passwords( + roles_dir=roles_dir, + application_ids=["web-app-a"], + host_vars_file=host_vars_file, + vault_password_file=vault_pw_file, + ) + + self.assertEqual(1, count) + self.assertEqual(0, second) + self.assertIn("$ANSIBLE_VAULT;1.1;AES256", written) + self.assertEqual( + "!vault", getattr(doc["users"]["biber"]["password"], "tag", None) + ) + + +class TestDeclaredPasswordPolicy(unittest.TestCase): + def test_a_role_declares_the_algorithm_its_application_accepts(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users( + roles_dir, + "web-app-a", + "bot:\n password:\n algorithm: strong_password\n" + " validation: '[^A-Za-z0-9]'\n", + ) + + self.assertEqual( + { + "bot": { + "algorithm": "strong_password", + "validation": "[^A-Za-z0-9]", + } + }, + required_user_policies(roles_dir, ["web-app-a"]), + ) + + def test_two_roles_disagreeing_on_one_account_abort(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users( + roles_dir, + "web-app-a", + "bot:\n password:\n algorithm: strong_password\n", + ) + _write_role_users( + roles_dir, + "web-app-b", + "bot:\n password:\n algorithm: alphanumeric\n", + ) + + with self.assertRaises(SystemExit): + required_user_policies(roles_dir, ["web-app-a", "web-app-b"]) + + def test_a_role_that_asks_for_nothing_leaves_the_declared_policy_alone(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users( + roles_dir, + "web-app-a", + "bot:\n password:\n algorithm: strong_password\n", + ) + _write_role_users(roles_dir, "web-app-b", "bot: {}\n") + + self.assertEqual( + "strong_password", + required_user_policies(roles_dir, ["web-app-a", "web-app-b"])["bot"][ + "algorithm" + ], + ) + + def test_the_generated_value_satisfies_the_declared_regex(self): + password = generate_declared_user_password( + "bot", "strong_password", "[^A-Za-z0-9]" + ) + self.assertRegex(password, "[^A-Za-z0-9]") + + def test_an_unsatisfiable_pair_aborts_instead_of_looping(self): + with self.assertRaises(SystemExit): + generate_declared_user_password("bot", "alphanumeric", "[^A-Za-z0-9]") + + def test_no_declaration_keeps_the_shell_safe_default(self): + password = generate_declared_user_password("bot", None, None) + self.assertRegex(password, r"^[A-Za-z0-9][A-Za-z0-9._-]*$") + self.assertRegex(password, r"[-_.]") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/build/docs/__init__.py b/tests/unit/python/cli/build/docs/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/build/docs/readme/__init__.py b/tests/unit/python/cli/build/docs/readme/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/build/readme/test_overview.py b/tests/unit/python/cli/build/docs/readme/test_overview.py similarity index 97% rename from tests/unit/python/cli/build/readme/test_overview.py rename to tests/unit/python/cli/build/docs/readme/test_overview.py index 7d05eab205..533f226fe2 100644 --- a/tests/unit/python/cli/build/readme/test_overview.py +++ b/tests/unit/python/cli/build/docs/readme/test_overview.py @@ -2,7 +2,7 @@ from __future__ import annotations import unittest -from cli.build.readme.overview import ( +from cli.build.docs.readme.overview import ( ANCHOR_HEADING, SECTION_HEADING, _cell, diff --git a/tests/unit/python/cli/meta/ci/test_chunks.py b/tests/unit/python/cli/meta/ci/test_chunks.py index 1e96de9443..e35b73192b 100644 --- a/tests/unit/python/cli/meta/ci/test_chunks.py +++ b/tests/unit/python/cli/meta/ci/test_chunks.py @@ -53,6 +53,12 @@ class TestPlan(unittest.TestCase): self.assertEqual([len(c) for c in plan], [5, 80, 80]) self.assertEqual(plan[0], list(range(5))) + def test_a_spare_block_spends_what_a_short_priority_chunk_leaves(self) -> None: + plan = chunks.plan( + list(range(9)), list(range(100, 400)), size=80, blocks=4, budget=210 + ) + self.assertEqual([len(c) for c in plan], [9, 80, 80, 41]) + def test_the_seam_chunk_is_never_topped_up_with_regular_rows(self) -> None: plan = chunks.plan( list(range(5)), diff --git a/tests/unit/python/cli/meta/ci/test_dev_runtime_matrix.py b/tests/unit/python/cli/meta/ci/test_dev_runtime_matrix.py index 4a10c8d458..bb4fd28e5e 100644 --- a/tests/unit/python/cli/meta/ci/test_dev_runtime_matrix.py +++ b/tests/unit/python/cli/meta/ci/test_dev_runtime_matrix.py @@ -7,7 +7,7 @@ import unittest from cli.meta.ci.dev_runtime import image_label, workspace_matrix from utils.symbol_glossary import to_emoji -IMAGES = ["debian:bookworm", "fedora:latest", "ubuntu:latest", "quay.io/centos:latest"] +IMAGES = ["debian:13", "fedora:latest", "ubuntu:latest", "quay.io/centos:latest"] class TestWorkspaceMatrix(unittest.TestCase): @@ -55,7 +55,7 @@ class TestWorkspaceMatrix(unittest.TestCase): def test_a_label_keeps_only_the_last_two_segments(self) -> None: self.assertEqual(image_label("quay.io/centos/centos:latest"), "centos:latest") self.assertEqual(image_label("manjarolinux/base"), "manjarolinux/base") - self.assertEqual(image_label("debian:bookworm"), "debian:bookworm") + self.assertEqual(image_label("debian:13"), "debian:13") self.assertEqual(image_label("ghcr.io/foo/bar/baz:1.2"), "baz:1.2") self.assertEqual(image_label("plainname"), "plainname") diff --git a/tests/unit/python/cli/meta/ci/test_guide_select.py b/tests/unit/python/cli/meta/ci/test_guide_select.py deleted file mode 100644 index 1af990e3ac..0000000000 --- a/tests/unit/python/cli/meta/ci/test_guide_select.py +++ /dev/null @@ -1,53 +0,0 @@ -from __future__ import annotations - -import textwrap -import unittest -from pathlib import Path -from tempfile import TemporaryDirectory - -from cli.meta.ci import guide_select -from utils.cache.files import PROJECT_ROOT -from utils.roles.mapping import ROLE_FILE_META_TESTS -from utils.roles.meta_lookup import MetaServicesShapeError, get_role_test_skips - - -class GuideModeTests(unittest.TestCase): - def test_role_without_stack_deploys_in_host_mode(self): - self.assertEqual( - guide_select._guide_mode(PROJECT_ROOT / "roles" / "svc-storage-nfs-client"), - "host", - ) - - def test_role_with_stack_deploys_in_compose_mode(self): - self.assertEqual( - guide_select._guide_mode(PROJECT_ROOT / "roles" / "web-app-yourls"), - "compose", - ) - - -class TestableRolesTests(unittest.TestCase): - def test_pool_excludes_roles_whose_guide_mode_is_skipped(self): - pool = guide_select._testable_roles() - self.assertNotIn("svc-storage-nfs-client", pool) - self.assertTrue(pool) - - def test_malformed_tests_yml_fails_selection_loudly(self): - with TemporaryDirectory() as tmp: - role_dir = Path(tmp) / "web-app-broken" - tests_path = role_dir / ROLE_FILE_META_TESTS - tests_path.parent.mkdir(parents=True) - tests_path.write_text( - textwrap.dedent( - """ - --- - skip: not-a-list - """ - ), - encoding="utf-8", - ) - with self.assertRaises(MetaServicesShapeError): - get_role_test_skips(role_dir, role_name=role_dir.name) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/unit/python/cli/meta/ci/test_matrix.py b/tests/unit/python/cli/meta/ci/test_matrix.py index 0dab0a2a5a..2eb5b3b780 100644 --- a/tests/unit/python/cli/meta/ci/test_matrix.py +++ b/tests/unit/python/cli/meta/ci/test_matrix.py @@ -31,7 +31,7 @@ class TestChunksOf(unittest.TestCase): def _chunks(self, entries: list[dict], *, size: int) -> list[list[dict]]: with ( mock.patch.object(matrix.slots, "chunk_size", return_value=size), - mock.patch.object(matrix.slots, "chunk_count", return_value=4), + mock.patch.object(matrix.slots, "chunk_blocks", return_value=4), mock.patch.object(matrix.slots, "available", return_value=99), ): return matrix.chunks_of(entries, 0) @@ -58,6 +58,26 @@ class TestChunksOf(unittest.TestCase): [chunk[0]["apps"] for chunk in chunks], ["web-app-z", "web-app-a"] ) + def test_a_short_priority_chunk_leaves_the_regular_rows_a_spare_block( + self, + ) -> None: + entries = [_entry("web-app-p", "0", "compose", priority=True)] + [ + _entry(f"web-app-{index:02d}", "0", "compose") for index in range(20) + ] + with ( + mock.patch.object(matrix.slots, "chunk_size", return_value=10), + mock.patch.object(matrix.slots, "chunk_count", return_value=2), + mock.patch.object(matrix.slots, "chunk_blocks", return_value=3), + mock.patch.object(matrix.slots, "available", return_value=21), + ): + chunks = matrix.chunks_of(entries, 0) + self.assertEqual( + [len(chunk) for chunk in chunks], + [1, 10, 10], + "the split must get every declared block, not only the ones the " + "budget fills, or the rows a short priority chunk leaves go unplanned", + ) + def test_priority_chunks_are_sorted_on_their_own(self) -> None: entries = [ _entry("web-app-z", "0", "compose", priority=True), @@ -80,7 +100,7 @@ class TestRedundant(unittest.TestCase): def _chunked(self, entries: list[dict]) -> list[dict]: with ( mock.patch.object(matrix.slots, "chunk_size", return_value=10), - mock.patch.object(matrix.slots, "chunk_count", return_value=4), + mock.patch.object(matrix.slots, "chunk_blocks", return_value=4), mock.patch.object(matrix.slots, "available", return_value=99), ): return [row for chunk in matrix.chunks_of(entries, 0) for row in chunk] diff --git a/tests/unit/python/cli/meta/ci/test_plan.py b/tests/unit/python/cli/meta/ci/test_plan.py index d8cb6e38ec..9b7d512418 100644 --- a/tests/unit/python/cli/meta/ci/test_plan.py +++ b/tests/unit/python/cli/meta/ci/test_plan.py @@ -15,6 +15,7 @@ def _entry( identifier: str = "0", covered: str = "0", clone: bool = False, + instructions: str = "", ) -> dict: return { "apps": app, @@ -23,7 +24,7 @@ def _entry( "tor": "true" if variant == "0" else "false", "disable": "", "priority": "true" if priority else "false", - "weight": "42", + "instructions": instructions, "id": identifier, "covered": covered, "clone": "true" if clone else "false", @@ -68,6 +69,16 @@ class TestCells(unittest.TestCase): self.assertEqual(rows[0][clone], "") self.assertEqual(rows[-1][clone], to_emoji("clone")) + def test_the_instructions_column_names_the_mode_the_replay_runs_in(self) -> None: + entries = [ + *_ENTRIES, + _entry("web-app-d", "0", "swarm", instructions="compose"), + ] + rows = plan.cells(entries, [_PRIORITY, _REGULAR]) + column = plan._COLUMNS.index("instructions") + self.assertEqual(rows[0][column], "") + self.assertEqual(rows[-1][column], to_emoji("compose")) + def test_the_mode_is_rendered_as_its_glyph(self) -> None: rows = plan.cells(_ENTRIES, [_PRIORITY, _REGULAR]) mode = plan._COLUMNS.index("mode") diff --git a/tests/unit/python/cli/meta/ci/test_validate.py b/tests/unit/python/cli/meta/ci/test_validate.py index 18a2a2e388..e849f331c7 100644 --- a/tests/unit/python/cli/meta/ci/test_validate.py +++ b/tests/unit/python/cli/meta/ci/test_validate.py @@ -54,6 +54,33 @@ class TestProblems(unittest.TestCase): self.assertEqual(errors, []) self.assertIn("web-app-gone", warnings[0]) + def test_a_bare_role_the_run_discovers_is_silent(self) -> None: + self.assertEqual(_problems("web-app-a"), ([], [])) + + def test_a_bare_role_is_judged_on_existence_not_on_variant_zero(self) -> None: + rows = [{"name": "web-app-c", "variant": 4, "test_compose": True}] + with ( + mock.patch.object(validate.query, "discover_rows", return_value=rows), + mock.patch.object( + validate, "get_variants", return_value={"web-app-c": [{"services": {}}]} + ), + ): + errors, warnings = validate.problems( + "web-app-c", + modes=("compose",), + tor_mode="auto", + distros=axes.DISTROS, + filesystems=axes.FILESYSTEMS, + lifecycles="", + label="priority", + ) + self.assertEqual((errors, warnings), ([], [])) + + def test_a_warning_still_separates_a_missing_role_from_a_present_one(self) -> None: + _errors, warnings = _problems("web-app-a web-app-gone web-app-b") + self.assertEqual(len(warnings), 1) + self.assertIn("web-app-gone", warnings[0]) + def test_a_mode_the_row_does_not_offer_is_an_error(self) -> None: errors, _warnings = _problems("web-app-a#1@swarm+clearnet") self.assertIn("pinned mode 'swarm' is not available", errors[0]) diff --git a/tests/unit/python/cli/meta/domains/test_main.py b/tests/unit/python/cli/meta/domains/test_main.py index a3b6954c8c..f69013f19c 100644 --- a/tests/unit/python/cli/meta/domains/test_main.py +++ b/tests/unit/python/cli/meta/domains/test_main.py @@ -70,7 +70,7 @@ class TestCliMetaApplicationsDomains(TestCase): code, out, err = self._run( [ "--domain-primary", - "infinito.example", + "infinito.test", "--alias", "--www", ] @@ -81,12 +81,12 @@ class TestCliMetaApplicationsDomains(TestCase): self.assertEqual( out.strip().splitlines(), [ - "alias.infinito.example", - "dashboard.infinito.example", - "test.infinito.example", - "www.alias.infinito.example", - "www.dashboard.infinito.example", - "www.test.infinito.example", + "alias.infinito.test", + "dashboard.infinito.test", + "test.infinito.test", + "www.alias.infinito.test", + "www.dashboard.infinito.test", + "www.test.infinito.test", ], ) diff --git a/tests/unit/python/cli/meta/roles/applications/bond/__init__.py b/tests/unit/python/cli/meta/roles/applications/bond/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/meta/roles/applications/bond/test_edit.py b/tests/unit/python/cli/meta/roles/applications/bond/test_edit.py new file mode 100644 index 0000000000..21eec53488 --- /dev/null +++ b/tests/unit/python/cli/meta/roles/applications/bond/test_edit.py @@ -0,0 +1,78 @@ +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory + +from cli.meta.roles.applications.bond.edit import EditError, parse_bond, set_bond +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +SOURCE = """--- +litellm: + bond: 0.5 + enabled: "{{ 'svc-ai-litellm' in group_names }}" +# nocheck: dockerfile-custom +sso: + bond: 1 # nocheck: dynamic-flag + flavor: oidc +ldap: + enabled: true +""" + + +class TestSetBond(unittest.TestCase): + def setUp(self) -> None: + self._tmp = TemporaryDirectory() + self.roles = Path(self._tmp.name) + self.path = self.roles / "web-app-demo" / ROLE_FILE_META_SERVICES + self.path.parent.mkdir(parents=True) + self.path.write_text(SOURCE, encoding="utf-8") + self.addCleanup(self._tmp.cleanup) + + def read(self) -> str: + return self.path.read_text( + encoding="utf-8" + ) # nocheck: cache-read โ€” re-reads the file set_bond just rewrote + + def test_rewrites_the_value_in_place(self) -> None: + self.assertEqual(set_bond(self.roles, "web-app-demo", "litellm", 0.25), "0.25") + self.assertIn(" bond: 0.25\n", self.read()) + self.assertIn("# nocheck: dockerfile-custom\n", self.read()) + + def test_keeps_a_trailing_comment(self) -> None: + set_bond(self.roles, "web-app-demo", "sso", 0.5) + self.assertIn(" bond: 0.5 # nocheck: dynamic-flag\n", self.read()) + + def test_inserts_a_missing_bond(self) -> None: + set_bond(self.roles, "web-app-demo", "ldap", 1) + self.assertIn("ldap:\n bond: 1\n enabled: true\n", self.read()) + + def test_removes_on_none(self) -> None: + self.assertEqual(set_bond(self.roles, "web-app-demo", "litellm", None), "") + self.assertNotIn("bond: 0.5", self.read()) + self.assertIn("litellm:\n enabled:", self.read()) + + def test_rejects_an_unknown_key(self) -> None: + with self.assertRaises(EditError): + set_bond(self.roles, "web-app-demo", "nope", 1) + + def test_does_not_match_a_nested_key(self) -> None: + with self.assertRaises(EditError): + set_bond(self.roles, "web-app-demo", "flavor", 1) + + +class TestParseBond(unittest.TestCase): + def test_blank_clears(self) -> None: + self.assertIsNone(parse_bond("")) + self.assertIsNone(parse_bond(" - ")) + + def test_rejects_out_of_range(self) -> None: + for raw in ("2", "-0.1", "abc"): + with self.assertRaises(EditError): + parse_bond(raw) + + def test_accepts_the_edges(self) -> None: + self.assertEqual(parse_bond("0"), 0.0) + self.assertEqual(parse_bond("1"), 1.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/meta/roles/applications/complexity/test_complexity.py b/tests/unit/python/cli/meta/roles/applications/complexity/test_complexity.py index 33d461b1a2..26e35c3170 100644 --- a/tests/unit/python/cli/meta/roles/applications/complexity/test_complexity.py +++ b/tests/unit/python/cli/meta/roles/applications/complexity/test_complexity.py @@ -944,16 +944,54 @@ class TestCoveredBy(unittest.TestCase): ) self.assertEqual([m.covered_by for m in marked], [0, 0, 2, 0]) - def test_variant_gt0_can_still_cover_other_roles(self) -> None: + def test_variant_gt0_covers_a_provider_it_pulls_at_zero(self) -> None: marked = _mark_covered( [ _row("Z", []), _row("A", ["B"], variant=2), _row("B", [], variant=0), - ] + ], + variant_counts={"B": 1}, ) self.assertEqual([m.covered_by for m in marked], [0, 0, 2]) + def test_variant_gt0_does_not_cover_a_provider_with_that_variant(self) -> None: + marked = _mark_covered( + [ + _row("Z", []), + _row("A", ["B"], variant=2), + _row("B", [], variant=0), + ], + variant_counts={"B": 5}, + ) + self.assertEqual([m.covered_by for m in marked], [0, 0, 0]) + + def test_variant_zero_covers_whatever_its_provider_count(self) -> None: + marked = _mark_covered( + [ + _row("Z", []), + _row("A", ["B"], variant=0), + _row("B", [], variant=0), + ], + variant_counts={"B": 9}, + ) + self.assertEqual([m.covered_by for m in marked], [0, 0, 2]) + + def test_a_variant_that_overrides_a_provider_does_not_cover_it(self) -> None: + rows = [_row("A", ["B", "C"], variant=0), _row("B", []), _row("C", [])] + marked = _mark_covered(rows, {("A", 0): {"B"}}) + self.assertEqual([m.covered_by for m in marked], [0, 0, 1]) + + def test_the_override_only_bars_the_provider_it_names(self) -> None: + rows = [_row("A", ["B"], variant=0), _row("B", [])] + marked = _mark_covered(rows, {("A", 0): {"C"}}) + self.assertEqual([m.covered_by for m in marked], [0, 1]) + + def test_an_override_in_another_variant_leaves_coverage_alone(self) -> None: + rows = [_row("A", ["B"], variant=0), _row("B", [])] + marked = _mark_covered(rows, {("A", 2): {"B"}}) + self.assertEqual([m.covered_by for m in marked], [0, 1]) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/group_vars/__init__.py b/tests/unit/python/group_vars/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/group_vars/test_litellm_chat_model.py b/tests/unit/python/group_vars/test_litellm_chat_model.py new file mode 100644 index 0000000000..67a8c4c902 --- /dev/null +++ b/tests/unit/python/group_vars/test_litellm_chat_model.py @@ -0,0 +1,153 @@ +import re +import unittest +from pathlib import Path +from typing import ClassVar + +from jinja2 import Environment, StrictUndefined, select_autoescape + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml + +_AI_VARS = Path(PROJECT_ROOT) / "group_vars" / "all" / "16_ai.yml" + + +def _ansible_bool(value): + if isinstance(value, str): + return value.strip().lower() in ("true", "yes", "on", "1") + return bool(value) + + +def _stub_lookup(preload_models, lmstudio_models): + def lookup(kind, role, path, *args): + if (kind, path) == ("config", "services.ollama.preload_models"): + return preload_models + if (kind, path) == ("config", "services.lmstudio.preload_models"): + return lmstudio_models + raise AssertionError(f"unexpected lookup({kind!r}, {role!r}, {path!r})") + + return lookup + + +class TestLitellmChatModel(unittest.TestCase): + """The gateway only publishes a model it has a backend for + (roles/svc-ai-litellm/templates/config.yaml.j2). These expressions decide + what consumers are told to ask for, so naming an unpublished model makes + every prompt fail with a 400. + """ + + env: ClassVar[Environment] + source: ClassVar[dict] + + @classmethod + def setUpClass(cls): + cls.env = Environment(undefined=StrictUndefined, autoescape=select_autoescape()) + cls.env.tests["search"] = lambda value, pattern: bool( + re.search(pattern, str(value)) + ) + cls.env.filters["bool"] = _ansible_bool + cls.source = load_yaml(_AI_VARS) + + def _render(self, name, *, roles, api_key, preload_models=(), lmstudio_models=()): + return ( + self.env.from_string(self.source[name]) + .render( + LITELLM_BACKEND_ROLES=list(roles), + LITELLM_OLLAMA_BACKEND=str("svc-ai-ollama" in roles), + LITELLM_LMSTUDIO_BACKEND=str("svc-ai-lmstudio" in roles), + AI_REMOTE_ALIASES=(["openrouter/auto"] if api_key else []), + lookup=_stub_lookup( + [{"alias": alias, "name": alias} for alias in preload_models], + [ + {"alias": alias, "name": f"{alias}-gguf"} + for alias in lmstudio_models + ], + ), + ) + .strip() + ) + + def _both(self, **kwargs): + return ( + self._render("LITELLM_CHAT_MODEL", **kwargs), + self._render("LITELLM_CHAT_MODEL_SERVED", **kwargs), + ) + + def test_no_backend_and_no_key_names_no_model(self): + model, served = self._both(roles=["web-app-mattermost"], api_key="") + self.assertEqual(model, "") + self.assertEqual(served, "False") + + def test_no_backend_with_a_key_uses_openrouter(self): + model, served = self._both(roles=["web-app-mattermost"], api_key="sk-test") + self.assertEqual(model, "openrouter/auto") + self.assertEqual(served, "True") + + def test_lmstudio_wins_over_the_openrouter_fallback(self): + model, served = self._both( + roles=["svc-ai-lmstudio"], api_key="", lmstudio_models=["qwen2.5:0.5b"] + ) + self.assertEqual(model, "qwen2.5:0.5b") + self.assertEqual(served, "True") + + def test_lmstudio_without_a_preloaded_model_serves_nothing(self): + served = self._render( + "LITELLM_CHAT_MODEL_SERVED", roles=["svc-ai-lmstudio"], api_key="" + ) + self.assertEqual(served, "False") + + def test_both_backends_name_the_same_model(self): + alias = "qwen2.5:0.5b" + with_ollama = self._render( + "LITELLM_CHAT_MODEL", + roles=["svc-ai-ollama"], + api_key="", + preload_models=[alias], + ) + with_lmstudio = self._render( + "LITELLM_CHAT_MODEL", + roles=["svc-ai-lmstudio"], + api_key="", + lmstudio_models=[alias], + ) + self.assertEqual(with_ollama, with_lmstudio) + self.assertEqual(with_ollama, alias) + + def test_ollama_serves_its_first_non_embedding_model(self): + model, served = self._both( + roles=["svc-ai-ollama"], + api_key="", + preload_models=["nomic-embed-text", "llama3.2"], + ) + self.assertEqual(model, "llama3.2") + self.assertEqual(served, "True") + + def test_ollama_with_only_embedding_models_serves_nothing(self): + served = self._render( + "LITELLM_CHAT_MODEL_SERVED", + roles=["svc-ai-ollama"], + api_key="", + preload_models=["nomic-embed-text"], + ) + self.assertEqual(served, "False") + + def test_the_model_is_named_exactly_when_one_is_served(self): + cases = ( + (["web-app-mattermost"], "", (), ()), + (["web-app-mattermost"], "sk-test", (), ()), + (["svc-ai-lmstudio"], "", (), ()), + (["svc-ai-lmstudio"], "", (), ("qwen2.5:0.5b",)), + (["svc-ai-ollama"], "", ("llama3.2",), ()), + ) + for roles, api_key, preload, lmstudio in cases: + with self.subTest(roles=roles, api_key=bool(api_key), lmstudio=lmstudio): + model, served = self._both( + roles=roles, + api_key=api_key, + preload_models=preload, + lmstudio_models=lmstudio, + ) + self.assertEqual(bool(model), served == "True") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/action/test_applications_carrier.py b/tests/unit/python/plugins/action/test_applications_carrier.py new file mode 100644 index 0000000000..841b2eea44 --- /dev/null +++ b/tests/unit/python/plugins/action/test_applications_carrier.py @@ -0,0 +1,113 @@ +import unittest +from unittest.mock import patch + +from ansible.errors import AnsibleActionFail + +from plugins.action.applications_carrier import ActionModule +from utils.cache.carrier import APPLICATIONS_RENDERED_FACT + + +class _FakeTask: + def __init__(self, args=None): + self.args = {} if args is None else dict(args) + + +class _FakeLookup: + def __init__(self, carrier): + self.carrier = carrier + self.calls = [] + + def run(self, terms, variables=None, **kwargs): + self.calls.append((terms, variables, kwargs)) + return [self.carrier] + + +def _make_action(task: _FakeTask) -> ActionModule: + action = object.__new__(ActionModule) + action._task = task + action._loader = None + action._templar = None + return action + + +class TestApplicationsCarrierActionPlugin(unittest.TestCase): + def test_parks_the_carrier_as_a_masked_fact(self): + carrier = {"key": ["roles", ["a", "b", "c", "d"]], "applications": {"x": {}}} + lookup = _FakeLookup(carrier) + action = _make_action(_FakeTask()) + with ( + patch( + "plugins.action.applications_carrier.ActionBase.run", + autospec=True, + return_value={}, + ), + patch( + "plugins.action.applications_carrier.lookup_loader.get", + return_value=lookup, + ), + ): + result = action.run(task_vars={"applications": {}}) + + self.assertIs(result["ansible_facts"][APPLICATIONS_RENDERED_FACT], carrier) + self.assertTrue(result["_ansible_no_log"]) + self.assertFalse(result["changed"]) + terms, variables, kwargs = lookup.calls[0] + self.assertEqual(terms, []) + self.assertEqual(variables, {"applications": {}}) + self.assertTrue(kwargs["carrier"]) + + def test_rejects_arguments(self): + action = _make_action(_FakeTask(args={"foo": 1})) + with ( + patch( + "plugins.action.applications_carrier.ActionBase.run", + autospec=True, + return_value={}, + ), + self.assertRaises(AnsibleActionFail), + ): + action.run(task_vars={}) + + def test_clear_drops_the_fact_without_rendering(self): + lookup = _FakeLookup({"key": ["roles", []], "applications": {}}) + action = _make_action(_FakeTask(args={"clear": True})) + with ( + patch( + "plugins.action.applications_carrier.ActionBase.run", + autospec=True, + return_value={}, + ), + patch( + "plugins.action.applications_carrier.lookup_loader.get", + return_value=lookup, + ), + ): + result = action.run(task_vars={"applications": {}}) + + self.assertIsNone(result["ansible_facts"][APPLICATIONS_RENDERED_FACT]) + self.assertFalse(result["changed"]) + self.assertEqual(lookup.calls, []) + + def test_clear_false_still_renders(self): + carrier = {"key": ["roles", ["a", "b", "c", "d"]], "applications": {"x": {}}} + lookup = _FakeLookup(carrier) + action = _make_action(_FakeTask(args={"clear": "no"})) + with ( + patch( + "plugins.action.applications_carrier.ActionBase.run", + autospec=True, + return_value={}, + ), + patch( + "plugins.action.applications_carrier.lookup_loader.get", + return_value=lookup, + ), + ): + result = action.run(task_vars={"applications": {}}) + + self.assertIs(result["ansible_facts"][APPLICATIONS_RENDERED_FACT], carrier) + self.assertEqual(len(lookup.calls), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/filter/test_cookie_scope.py b/tests/unit/python/plugins/filter/test_cookie_scope.py index 20e12711ce..a3bdd1e5ee 100644 --- a/tests/unit/python/plugins/filter/test_cookie_scope.py +++ b/tests/unit/python/plugins/filter/test_cookie_scope.py @@ -24,67 +24,67 @@ class CommonDnsSuffixTests(unittest.TestCase): def test_domain_pipeline_normalizes_every_supported_shape(self): mapping = { - "filer": "filer.seaweedfs.s3.infinito.example", - "master": "master.seaweedfs.s3.infinito.example", + "filer": "filer.seaweedfs.s3.infinito.test", + "master": "master.seaweedfs.s3.infinito.test", } self.assertEqual( common_dns_suffix(domain_strings(mapping)), - "seaweedfs.s3.infinito.example", + "seaweedfs.s3.infinito.test", ) self.assertEqual( - common_dns_suffix(domain_strings("cloud.infinito.example")), - "cloud.infinito.example", + common_dns_suffix(domain_strings("cloud.infinito.test")), + "cloud.infinito.test", ) mixed = domain_strings( - ["cloud.infinito.example", "cloud.examplelongonionaddress.onion"] + ["cloud.infinito.test", "cloud.examplelongonionaddress.onion"] ) clearnet = [domain for domain in mixed if not domain.endswith(".onion")] - self.assertEqual(common_dns_suffix(clearnet), "cloud.infinito.example") + self.assertEqual(common_dns_suffix(clearnet), "cloud.infinito.test") def test_single_domain_returned_unchanged(self): self.assertEqual( - common_dns_suffix(["cloud.infinito.example"]), "cloud.infinito.example" + common_dns_suffix(["cloud.infinito.test"]), "cloud.infinito.test" ) def test_multi_domain_collapses_to_shared_parent(self): self.assertEqual( common_dns_suffix( [ - "api.seaweedfs.s3.infinito.example", - "filer.seaweedfs.s3.infinito.example", - "master.seaweedfs.s3.infinito.example", + "api.seaweedfs.s3.infinito.test", + "filer.seaweedfs.s3.infinito.test", + "master.seaweedfs.s3.infinito.test", ] ), - "seaweedfs.s3.infinito.example", + "seaweedfs.s3.infinito.test", ) def test_subdomain_alias_keeps_minimal_shared_suffix(self): self.assertEqual( - common_dns_suffix(["app.infinito.example", "www.app.infinito.example"]), - "app.infinito.example", + common_dns_suffix(["app.infinito.test", "www.app.infinito.test"]), + "app.infinito.test", ) def test_dict_input_uses_values_multi(self): self.assertEqual( common_dns_suffix( { - "filer": "filer.seaweedfs.s3.infinito.example", - "master": "master.seaweedfs.s3.infinito.example", - "api": "api.seaweedfs.s3.infinito.example", + "filer": "filer.seaweedfs.s3.infinito.test", + "master": "master.seaweedfs.s3.infinito.test", + "api": "api.seaweedfs.s3.infinito.test", } ), - "seaweedfs.s3.infinito.example", + "seaweedfs.s3.infinito.test", ) def test_dict_input_single_value(self): self.assertEqual( - common_dns_suffix({"web": "cloud.infinito.example"}), - "cloud.infinito.example", + common_dns_suffix({"web": "cloud.infinito.test"}), + "cloud.infinito.test", ) def test_string_input(self): self.assertEqual( - common_dns_suffix("cloud.infinito.example"), "cloud.infinito.example" + common_dns_suffix("cloud.infinito.test"), "cloud.infinito.test" ) def test_empty_input_returns_empty_string(self): @@ -93,7 +93,7 @@ class CommonDnsSuffixTests(unittest.TestCase): def test_blank_entries_ignored(self): self.assertEqual( - common_dns_suffix(["", "cloud.infinito.example"]), "cloud.infinito.example" + common_dns_suffix(["", "cloud.infinito.test"]), "cloud.infinito.test" ) diff --git a/tests/unit/python/plugins/filter/test_csp_filters/test_onion_mirror.py b/tests/unit/python/plugins/filter/test_csp_filters/test_onion_mirror.py index 893276a480..e0ab1f7e51 100644 --- a/tests/unit/python/plugins/filter/test_csp_filters/test_onion_mirror.py +++ b/tests/unit/python/plugins/filter/test_csp_filters/test_onion_mirror.py @@ -4,7 +4,7 @@ import unittest from plugins.filter.csp_filters import FilterModule NODE = "ndck3kzcxbcem2oskbhytxwevvpzwn7j5dj6q36vbijyrnw3rjf2heqd.onion" -PRIMARY = "infinito.example" +PRIMARY = "infinito.test" class TestCspOnionMirror(unittest.TestCase): @@ -45,6 +45,19 @@ class TestCspOnionMirror(unittest.TestCase): self.assertIn("*." + PRIMARY, frame) self.assertIn("*." + NODE, frame) + def test_onion_sibling_of_a_tls_token_is_plaintext(self): + domains = { + "web-svc-cdn": ["cdn." + PRIMARY], + "app1": ["app1." + PRIMARY, "app1." + NODE], + } + header = self.filter.build_csp_header( + copy.deepcopy(self.apps), "app1", domains, "https", domain_primary=PRIMARY + ) + connect = self._tokens(header, "connect-src") + self.assertIn("https://cdn." + PRIMARY, connect) + self.assertIn("http://cdn." + NODE, connect) + self.assertNotIn("https://cdn." + NODE, connect) + def test_exclusive_replaces_clearnet_with_onion(self): frame = self._tokens(self._header({"app1": ["app1." + NODE]}), "frame-src") self.assertIn("*." + NODE, frame) diff --git a/tests/unit/python/plugins/filter/test_domain_filters_canonical.py b/tests/unit/python/plugins/filter/test_domain_filters_canonical.py index f9f88e39a5..073afe1e43 100644 --- a/tests/unit/python/plugins/filter/test_domain_filters_canonical.py +++ b/tests/unit/python/plugins/filter/test_domain_filters_canonical.py @@ -117,14 +117,14 @@ class TestDomainFilters(unittest.TestCase): import os prev = os.environ.get("DOMAIN") - os.environ["DOMAIN"] = "infinito.example" + os.environ["DOMAIN"] = "infinito.test" try: primary = ( "{{ lookup('env', 'DOMAIN') | default('infinito.localhost', true) }}" ) apps = {"web-app-app1": {}} result = self.filter_module.canonical_domains_map(apps, primary) - self.assertEqual(result, {"web-app-app1": ["app1.infinito.example"]}) + self.assertEqual(result, {"web-app-app1": ["app1.infinito.test"]}) finally: if prev is None: os.environ.pop("DOMAIN", None) diff --git a/tests/unit/python/plugins/filter/test_mcp_authorization.py b/tests/unit/python/plugins/filter/test_mcp_authorization.py new file mode 100644 index 0000000000..85c9453334 --- /dev/null +++ b/tests/unit/python/plugins/filter/test_mcp_authorization.py @@ -0,0 +1,84 @@ +import base64 +import importlib +import unittest + +plugin_module = importlib.import_module("plugins.filter.mcp.authorization") +mcp_authorization = plugin_module.mcp_authorization +mcp_authorization_is_renderable = plugin_module.mcp_authorization_is_renderable +mcp_renderable_servers = plugin_module.mcp_renderable_servers + + +class TestMcpAuthorization(unittest.TestCase): + def test_bearer_token_inlines_the_token(self): + header = mcp_authorization({"auth": "bearer_token", "token": "secret"}) + self.assertEqual(header, "Bearer secret") + + def test_bearer_token_references_the_env_var_when_asked(self): + header = mcp_authorization( + {"auth": "bearer_token", "token": "secret"}, env="HA_MCP_TOKEN" + ) + self.assertEqual(header, "Bearer ${env:HA_MCP_TOKEN}") + self.assertNotIn("secret", header) + + def test_app_password_is_presented_as_a_bearer(self): + self.assertEqual( + mcp_authorization({"auth": "app_password", "token": "pw"}), "Bearer pw" + ) + + def test_basic_auth_encodes_the_credential_owner_and_token(self): + header = mcp_authorization( + {"auth": "basic_auth", "owner": "admin", "token": "t0ken"} + ) + expected = base64.b64encode(b"admin:t0ken").decode() + self.assertEqual(header, f"Basic {expected}") + + def test_basic_auth_ignores_the_env_reference(self): + header = mcp_authorization( + {"auth": "basic_auth", "owner": "admin", "token": "t0ken"}, + env="SOME_VAR", + ) + self.assertNotIn("SOME_VAR", header) + self.assertTrue(header.startswith("Basic ")) + + def test_basic_auth_without_an_owner_raises(self): + with self.assertRaises(ValueError): + mcp_authorization({"id": "web-app-x", "auth": "basic_auth", "token": "t"}) + + def test_unpresentable_scheme_raises(self): + with self.assertRaises(ValueError): + mcp_authorization({"id": "web-app-x", "auth": "none", "token": ""}) + + def test_oidc_refuses_to_render_the_deployment_bearer(self): + with self.assertRaises(ValueError): + mcp_authorization({"id": "web-app-x", "auth": "oidc", "token": "t"}) + + def test_oidc_refuses_even_behind_an_environment_reference(self): + with self.assertRaises(ValueError): + mcp_authorization({"id": "web-app-x", "auth": "oidc"}, env="X_TOKEN") + + def test_renderable_reports_supported_schemes(self): + self.assertTrue(mcp_authorization_is_renderable({"auth": "bearer_token"})) + self.assertTrue(mcp_authorization_is_renderable({"auth": "basic_auth"})) + self.assertFalse(mcp_authorization_is_renderable({"auth": "oidc"})) + self.assertFalse(mcp_authorization_is_renderable({"auth": "none"})) + self.assertFalse(mcp_authorization_is_renderable({})) + + +class TestMcpRenderableServers(unittest.TestCase): + def test_none_yields_empty_list(self): + self.assertEqual(mcp_renderable_servers(None), []) + + def test_unpresentable_servers_are_dropped(self): + bearer = {"id": "a", "auth": "bearer_token"} + basic = {"id": "b", "auth": "basic_auth"} + servers = [bearer, {"id": "c", "auth": "none"}, basic, {"id": "d"}] + self.assertEqual(mcp_renderable_servers(servers), [bearer, basic]) + + def test_delegated_servers_are_dropped_from_static_configs(self): + bearer = {"id": "a", "auth": "bearer_token"} + servers = [bearer, {"id": "b", "auth": "oidc"}] + self.assertEqual(mcp_renderable_servers(servers), [bearer]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/filter/test_mcp_group_members.py b/tests/unit/python/plugins/filter/test_mcp_group_members.py new file mode 100644 index 0000000000..152cb7ff3f --- /dev/null +++ b/tests/unit/python/plugins/filter/test_mcp_group_members.py @@ -0,0 +1,105 @@ +"""Unit tests for ``plugins/filter/mcp/group_members.py``.""" + +import importlib +import unittest + +mcp_group_members = importlib.import_module( + "plugins.filter.mcp.group_members" +).mcp_group_members + +SERVERS = [{"id": "web-app-baserow"}, {"id": "web-app-zammad"}] +READER_ROLE = "mcp-reader" +WRITER_ROLE = "mcp-writer" + + +class TestMcpGroupMembers(unittest.TestCase): + def test_no_servers_yields_no_groups(self): + self.assertEqual(mcp_group_members({"alice": {}}, [], READER_ROLE), {}) + + def test_grant_lands_only_on_the_named_application(self): + users = { + "alice": { + "username": "alice", + "email": "alice@example.org", + "application_roles": {"web-app-baserow": ["mcp"]}, + } + } + self.assertEqual( + mcp_group_members(users, SERVERS, READER_ROLE), + { + "web-app-baserow": [ + {"username": "alice", "email": "alice@example.org"} + ], + "web-app-zammad": [], + }, + ) + + def test_unscoped_mcp_role_grants_nothing(self): + users = {"alice": {"username": "alice", "roles": ["mcp"]}} + self.assertEqual( + mcp_group_members(users, SERVERS, READER_ROLE), + {"web-app-baserow": [], "web-app-zammad": []}, + ) + + def test_removing_the_last_grant_empties_the_group(self): + self.assertEqual( + mcp_group_members({"alice": {"username": "alice"}}, SERVERS, READER_ROLE), + {"web-app-baserow": [], "web-app-zammad": []}, + ) + + def test_members_are_sorted_and_use_the_username_attribute(self): + users = { + "b-key": { + "username": "zoe", + "email": "zoe@example.org", + "application_roles": {"web-app-baserow": ["mcp"]}, + }, + "a-key": { + "username": "amy", + "email": "amy@example.org", + "application_roles": {"web-app-baserow": ["mcp"]}, + }, + } + self.assertEqual( + [ + m["username"] + for m in mcp_group_members(users, SERVERS, READER_ROLE)[ + "web-app-baserow" + ] + ], + ["amy", "zoe"], + ) + + def test_a_member_without_an_email_still_carries_its_username(self): + users = { + "alice": { + "username": "alice", + "application_roles": {"web-app-baserow": ["mcp"]}, + } + } + self.assertEqual( + mcp_group_members(users, SERVERS, READER_ROLE)["web-app-baserow"], + [{"username": "alice", "email": ""}], + ) + + def test_servers_without_an_id_are_skipped(self): + self.assertEqual(mcp_group_members({}, [{"url": "http://x"}], READER_ROLE), {}) + + def test_writer_members_are_resolved_separately(self): + users = { + "alice": { + "application_roles": {"web-app-baserow": [WRITER_ROLE]}, + } + } + self.assertEqual( + [{"username": "alice", "email": ""}], + mcp_group_members(users, SERVERS, WRITER_ROLE)["web-app-baserow"], + ) + + def test_unknown_role_fails(self): + with self.assertRaisesRegex(ValueError, "unknown role"): + mcp_group_members({}, SERVERS, "administrator") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/filter/test_mcp_tool_server_connections.py b/tests/unit/python/plugins/filter/test_mcp_tool_server_connections.py new file mode 100644 index 0000000000..157fd9663b --- /dev/null +++ b/tests/unit/python/plugins/filter/test_mcp_tool_server_connections.py @@ -0,0 +1,197 @@ +import importlib +import unittest + +plugin_module = importlib.import_module("plugins.filter.mcp.tool_server_connections") +mcp_tool_server_connections = plugin_module.mcp_tool_server_connections + + +class TestMcpToolServerConnections(unittest.TestCase): + def test_empty_input_yields_no_connections(self): + self.assertEqual(mcp_tool_server_connections([]), []) + + def test_none_input_yields_no_connections(self): + self.assertEqual(mcp_tool_server_connections(None), []) + + def test_server_becomes_an_mcp_bearer_connection(self): + result = mcp_tool_server_connections( + [ + { + "id": "web-app-homeassistant", + "url": "http://homeassistant:8123/api/mcp", + "token": "secret", + "auth": "bearer_token", + "transport": "streamable-http", + } + ] + ) + + self.assertEqual(len(result), 1) + entry = result[0] + self.assertEqual(entry["url"], "http://homeassistant:8123/api/mcp") + self.assertEqual(entry["path"], "") + self.assertEqual(entry["type"], "mcp") + self.assertEqual(entry["auth_type"], "bearer") + self.assertEqual(entry["key"], "secret") + self.assertFalse( + entry["config"]["enable"], + "an entry with no grant must not be served: OpenWebUI reads empty grants " + "as every administrator, which is wider than the role's mcp group", + ) + self.assertEqual(entry["config"]["access_grants"], []) + self.assertEqual(entry["info"]["id"], "web-app-homeassistant") + + def test_a_known_group_enables_the_entry_with_exactly_that_grant(self): + """This is what survives a restart. + + ``ENABLE_PERSISTENT_CONFIG=false`` makes the env authoritative on every + start, so whatever this filter renders is the state Open WebUI comes + back with. Only when the grant travels in the env does a bare container + restart restore a served, correctly scoped connection instead of a + disabled one that waits for the next deploy. + """ + result = mcp_tool_server_connections( + [ + { + "id": "web-app-homeassistant", + "url": "http://homeassistant:8123/api/mcp", + "token": "secret", + "auth": "bearer_token", + } + ], + {"web-app-homeassistant": "grp-42"}, + ) + + entry = result[0] + self.assertTrue(entry["config"]["enable"]) + self.assertEqual( + entry["config"]["access_grants"], + [ + { + "principal_type": "group", + "principal_id": "grp-42", + "permission": "read", + } + ], + ) + + def test_another_providers_group_does_not_enable_this_one(self): + result = mcp_tool_server_connections( + [ + { + "id": "web-app-homeassistant", + "url": "http://homeassistant:8123/api/mcp", + "token": "secret", + "auth": "bearer_token", + } + ], + {"web-app-gitea": "grp-42"}, + ) + + entry = result[0] + self.assertFalse( + entry["config"]["enable"], + "a group id belonging to a different provider must not open this " + "one; the grant is per application, not per deployment", + ) + self.assertEqual(entry["config"]["access_grants"], []) + + def test_an_empty_group_id_counts_as_unknown(self): + result = mcp_tool_server_connections( + [ + { + "id": "web-app-homeassistant", + "url": "http://homeassistant:8123/api/mcp", + "token": "secret", + "auth": "bearer_token", + } + ], + {"web-app-homeassistant": " "}, + ) + + entry = result[0] + self.assertFalse(entry["config"]["enable"]) + self.assertEqual(entry["config"]["access_grants"], []) + + def test_no_connection_is_offered_to_every_signed_in_user(self): + result = mcp_tool_server_connections( + [ + { + "id": "web-app-baserow", + "url": "http://baserow/mcp/key/sse", + "token": "secret", + "auth": "app_password", + }, + { + "id": "web-app-homeassistant", + "url": "http://homeassistant:8123/api/mcp", + "token": "secret", + "auth": "bearer_token", + }, + ] + ) + + self.assertEqual(len(result), 2) + for entry in result: + self.assertNotIn("access_control", entry["config"]) + self.assertEqual(entry["config"]["access_grants"], []) + + def test_entry_without_url_is_dropped(self): + self.assertEqual( + mcp_tool_server_connections( + [{"id": "x", "url": "", "token": "t", "auth": "bearer_token"}] + ), + [], + ) + + def test_entry_without_id_is_dropped(self): + self.assertEqual( + mcp_tool_server_connections( + [{"id": "", "url": "http://a/mcp", "auth": "bearer_token"}] + ), + [], + ) + + def test_basic_auth_server_is_skipped(self): + self.assertEqual( + mcp_tool_server_connections( + [ + { + "id": "web-app-jenkins", + "url": "http://jenkins:8080/mcp-server/mcp", + "token": "t", + "auth": "basic_auth", + } + ] + ), + [], + ) + + def test_every_discovered_server_is_kept(self): + result = mcp_tool_server_connections( + [ + { + "id": "a", + "url": "http://a/mcp", + "token": "1", + "auth": "bearer_token", + }, + { + "id": "b", + "url": "http://b/mcp", + "token": "2", + "auth": "app_password", + }, + ] + ) + self.assertEqual([e["info"]["id"] for e in result], ["a", "b"]) + + def test_oidc_server_becomes_a_keyless_system_oauth_connection(self): + entry = mcp_tool_server_connections( + [{"id": "a", "url": "http://a/mcp", "token": "deploy", "auth": "oidc"}] + )[0] + self.assertEqual(entry["auth_type"], "system_oauth") + self.assertEqual(entry["key"], "") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/filter/test_redirect_sources.py b/tests/unit/python/plugins/filter/test_redirect_sources.py new file mode 100644 index 0000000000..d0aaa7d712 --- /dev/null +++ b/tests/unit/python/plugins/filter/test_redirect_sources.py @@ -0,0 +1,74 @@ +import sys +import unittest + +from . import PROJECT_ROOT + +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + +from ansible.errors import AnsibleFilterError + +from plugins.filter.redirect_sources import FilterModule, redirect_sources + + +class TestRedirectSources(unittest.TestCase): + def test_every_reference_form_is_covered(self): + self.assertEqual( + redirect_sources("unpkg.com"), + [ + "https://unpkg.com/", + "http://unpkg.com/", + "/", + ], + ) + + def test_the_catch_all_comes_last(self): + sources = redirect_sources("unpkg.com") + + self.assertEqual( + sources[-1], + "/", + "the bare slash is the widest form and reads as the fallback only " + "while it stays at the end", + ) + + def test_no_form_is_a_prefix_of_another(self): + sources = redirect_sources("unpkg.com") + + for index, source in enumerate(sources): + for other in sources[:index]: + self.assertFalse( + source.startswith(other), + f"{source!r} starts with {other!r}, so the two forms " + f"cannot be told apart by a prefix comparison", + ) + + def test_surrounding_whitespace_is_dropped(self): + self.assertEqual(redirect_sources(" unpkg.com ")[0], "https://unpkg.com/") + + def test_the_host_is_not_otherwise_rewritten(self): + self.assertEqual( + redirect_sources("CDN.Example.COM")[1], "http://CDN.Example.COM/" + ) + + def test_a_subdomain_host_keeps_every_label(self): + self.assertEqual( + redirect_sources("cdn.jsdelivr.net")[0], "https://cdn.jsdelivr.net/" + ) + + def test_an_empty_host_is_rejected(self): + for value in ("", " "): + with self.assertRaises(AnsibleFilterError): + redirect_sources(value) + + def test_a_non_string_host_is_rejected(self): + for value in (None, 42, ["unpkg.com"]): + with self.assertRaises(AnsibleFilterError): + redirect_sources(value) + + def test_the_filter_is_exported(self): + self.assertIs(FilterModule().filters()["redirect_sources"], redirect_sources) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/filter/test_status_codes.py b/tests/unit/python/plugins/filter/test_status_codes.py new file mode 100644 index 0000000000..4da0ef76b2 --- /dev/null +++ b/tests/unit/python/plugins/filter/test_status_codes.py @@ -0,0 +1,157 @@ +import unittest + +from plugins.filter.status_codes import FilterModule +from utils.roles.applications.status_codes import ( + DEFAULT_OK, + accepted_status_codes, + declared_status_codes, +) + +SEAWEEDFS = { + "web-app-seaweedfs": { + "domains": { + "canonical": { + "api": "s3.example.org", + "filer": "filer.example.org", + "master": "master.example.org", + } + }, + "server": { + "status_codes": { + "api": [301, 302, 403, 405], + "filer": [302, 403], + "master": [302, 403], + } + }, + } +} + + +class TestDeclaredStatusCodes(unittest.TestCase): + def test_per_vhost_key_wins(self): + for domain, codes in ( + ("s3.example.org", [301, 302, 403, 405]), + ("filer.example.org", [302, 403]), + ("master.example.org", [302, 403]), + ): + with self.subTest(domain=domain): + self.assertEqual( + declared_status_codes(SEAWEEDFS, "web-app-seaweedfs", domain), + codes, + ) + + def test_undeclared_app_declares_nothing(self): + apps = {"web-app-plain": {"domains": {"canonical": ["plain.example.org"]}}} + self.assertEqual( + declared_status_codes(apps, "web-app-plain", "plain.example.org"), [] + ) + + def test_flat_canonical_uses_the_default_key(self): + apps = { + "web-app-prometheus": { + "domains": {"canonical": ["metrics.example.org"]}, + "server": {"status_codes": {"default": [405]}}, + } + } + self.assertEqual( + declared_status_codes(apps, "web-app-prometheus", "metrics.example.org"), + [405], + ) + + def test_unknown_domain_falls_back_to_the_declared_default(self): + apps = { + "web-app-x": { + "domains": {"canonical": {"api": "api.example.org"}}, + "server": {"status_codes": {"api": [403], "default": [404]}}, + } + } + self.assertEqual( + declared_status_codes(apps, "web-app-x", "other.example.org"), [404] + ) + + def test_a_key_without_its_own_codes_uses_the_default(self): + apps = { + "web-app-x": { + "domains": {"canonical": {"api": "api.example.org"}}, + "server": {"status_codes": {"other": [403], "default": [404]}}, + } + } + self.assertEqual( + declared_status_codes(apps, "web-app-x", "api.example.org"), [404] + ) + + def test_scalar_and_string_codes_are_normalized(self): + apps = { + "web-app-x": { + "domains": {"canonical": {"api": ["api.example.org"]}}, + "server": {"status_codes": {"api": "403"}}, + } + } + self.assertEqual( + declared_status_codes(apps, "web-app-x", "api.example.org"), [403] + ) + + def test_out_of_range_declarations_are_dropped(self): + apps = { + "web-app-x": { + "domains": {"canonical": {"api": "api.example.org"}}, + "server": {"status_codes": {"api": [999, "nope"]}}, + } + } + self.assertEqual( + declared_status_codes(apps, "web-app-x", "api.example.org"), [] + ) + + +class TestAcceptedStatusCodes(unittest.TestCase): + def test_filter_is_registered(self): + self.assertIn("accepted_status_codes", FilterModule().filters()) + + def test_declared_codes_are_added_to_the_default(self): + self.assertEqual( + accepted_status_codes(SEAWEEDFS, "web-app-seaweedfs", "filer.example.org"), + [200, 302, 301, 403], + ) + + def test_a_narrower_declaration_never_narrows_the_gate(self): + apps = { + "web-app-mailu": { + "domains": {"canonical": ["mail.example.org"]}, + "server": {"status_codes": {"default": [200, 301]}}, + } + } + self.assertEqual( + accepted_status_codes(apps, "web-app-mailu", "mail.example.org"), + DEFAULT_OK, + ) + + def test_a_disjoint_declaration_only_adds(self): + apps = { + "web-svc-mirror": { + "domains": {"canonical": ["mirror.example.org"]}, + "server": {"status_codes": {"default": [404]}}, + } + } + self.assertEqual( + accepted_status_codes(apps, "web-svc-mirror", "mirror.example.org"), + [200, 302, 301, 404], + ) + + def test_undeclared_app_gets_the_default(self): + apps = {"web-app-plain": {"domains": {"canonical": ["plain.example.org"]}}} + self.assertEqual( + accepted_status_codes(apps, "web-app-plain", "plain.example.org"), + DEFAULT_OK, + ) + + def test_the_result_is_a_copy(self): + first = accepted_status_codes(SEAWEEDFS, "web-app-seaweedfs", "unknown.org") + first.append(418) + self.assertEqual( + accepted_status_codes(SEAWEEDFS, "web-app-seaweedfs", "unknown.org"), + DEFAULT_OK, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/filter/test_swarm_deployed_services.py b/tests/unit/python/plugins/filter/test_swarm_deployed_services.py new file mode 100644 index 0000000000..9c9dd9b34f --- /dev/null +++ b/tests/unit/python/plugins/filter/test_swarm_deployed_services.py @@ -0,0 +1,44 @@ +"""Only the service lines of a stack deploy may reach the convergence gate.""" + +from __future__ import annotations + +import unittest + +from plugins.filter.swarm.deployed_services import swarm_deployed_services + + +class TestSwarmDeployedServices(unittest.TestCase): + def test_it_keeps_created_and_updated_services_in_order(self) -> None: + result = { + "stdout_lines": [ + "2026-09-03T01:24:03Z", + "Creating network cdn_default", + "Creating service cdn_build", + "Updating service cdn_web (id: 9x)", + ] + } + self.assertEqual(swarm_deployed_services(result), ["cdn_build", "cdn_web"]) + + def test_it_drops_every_non_service_line(self) -> None: + result = { + "stdout_lines": [ + "2026-09-03T01:24:03Z", + "Creating config cdn_nginx", + "Creating secret cdn_key", + "Updating network cdn_default", + ] + } + self.assertEqual(swarm_deployed_services(result), []) + + def test_a_service_name_never_carries_the_trailing_id(self) -> None: + result = {"stdout_lines": ["Updating service demo_web (id: abc123)"]} + self.assertEqual(swarm_deployed_services(result), ["demo_web"]) + + def test_a_missing_or_empty_result_yields_nothing(self) -> None: + self.assertEqual(swarm_deployed_services(None), []) + self.assertEqual(swarm_deployed_services({}), []) + self.assertEqual(swarm_deployed_services({"stdout_lines": None}), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/filter/test_swarm_restart_condition.py b/tests/unit/python/plugins/filter/test_swarm_restart_condition.py index 8a0d9d3ed7..b89359bb7b 100644 --- a/tests/unit/python/plugins/filter/test_swarm_restart_condition.py +++ b/tests/unit/python/plugins/filter/test_swarm_restart_condition.py @@ -14,7 +14,7 @@ from __future__ import annotations import unittest -from plugins.filter.swarm_restart_condition import ( +from plugins.filter.swarm.restart_condition import ( FilterModule, swarm_restart_condition, ) diff --git a/tests/unit/python/plugins/filter/test_timeout_start_sec_for_domains.py b/tests/unit/python/plugins/filter/test_timeout_start_sec_for_domains.py index 5be1780922..99f35614dc 100644 --- a/tests/unit/python/plugins/filter/test_timeout_start_sec_for_domains.py +++ b/tests/unit/python/plugins/filter/test_timeout_start_sec_for_domains.py @@ -25,6 +25,41 @@ class TestTimeoutStartSecForDomains(unittest.TestCase): ) self.assertEqual(result, 180) + def test_an_onion_domain_costs_its_own_rate(self): + result = _f()( + ["example.com", "abc.onion"], + include_www=False, + per_domain_seconds=25, + onion_per_domain_seconds=105, + overhead_seconds=30, + min_seconds=0, + max_seconds=3600, + ) + self.assertEqual(result, 160) + + def test_without_an_onion_rate_every_domain_costs_the_same(self): + result = _f()( + ["example.com", "abc.onion"], + include_www=False, + per_domain_seconds=25, + overhead_seconds=30, + min_seconds=0, + max_seconds=3600, + ) + self.assertEqual(result, 80) + + def test_the_onion_rate_covers_the_www_variant_too(self): + result = _f()( + ["abc.onion"], + include_www=True, + per_domain_seconds=25, + onion_per_domain_seconds=105, + overhead_seconds=30, + min_seconds=0, + max_seconds=3600, + ) + self.assertEqual(result, 240) + def test_no_www_min_clamp_applies(self): domains = { "canonical": ["example.com", "foo.bar"], diff --git a/tests/unit/python/plugins/filter/test_url_to_onion.py b/tests/unit/python/plugins/filter/test_url_to_onion.py index b9279f67a4..46205d0bf3 100644 --- a/tests/unit/python/plugins/filter/test_url_to_onion.py +++ b/tests/unit/python/plugins/filter/test_url_to_onion.py @@ -3,25 +3,25 @@ import unittest from plugins.filter.url.to_onion import to_onion_url NODE = "abc123def456ghij789klmno000pqrstuvwx111yz222abc333def444gh.onion" -PRIMARY = "infinito.example" +PRIMARY = "infinito.test" class TestToOnionUrl(unittest.TestCase): def test_subdomain_swapped_and_forced_http(self): self.assertEqual( - to_onion_url("https://auth.infinito.example/realms/x", NODE, PRIMARY), + to_onion_url("https://auth.infinito.test/realms/x", NODE, PRIMARY), f"http://auth.{NODE}/realms/x", ) def test_bare_primary_becomes_node(self): self.assertEqual( - to_onion_url("https://infinito.example/", NODE, PRIMARY), + to_onion_url("https://infinito.test/", NODE, PRIMARY), f"http://{NODE}/", ) def test_path_and_query_preserved(self): self.assertEqual( - to_onion_url("https://cdn.infinito.example/a/b.js?v=3", NODE, PRIMARY), + to_onion_url("https://cdn.infinito.test/a/b.js?v=3", NODE, PRIMARY), f"http://cdn.{NODE}/a/b.js?v=3", ) @@ -30,7 +30,7 @@ class TestToOnionUrl(unittest.TestCase): self.assertEqual(to_onion_url(url, NODE, PRIMARY), url) def test_noop_without_tor_node(self): - url = "https://auth.infinito.example/" + url = "https://auth.infinito.test/" self.assertEqual(to_onion_url(url, "", PRIMARY), url) def test_noop_on_empty_url(self): diff --git a/tests/unit/python/plugins/lookup/test_addon_env_flags.py b/tests/unit/python/plugins/lookup/test_addon_env_flags.py index e9d6114c52..4e1ca6b573 100644 --- a/tests/unit/python/plugins/lookup/test_addon_env_flags.py +++ b/tests/unit/python/plugins/lookup/test_addon_env_flags.py @@ -123,7 +123,7 @@ class TestNoAddons(unittest.TestCase): class TestBridgeDeploymentGating(unittest.TestCase): """A bridged addon's flag is true only when one of its partner roles is in the - deployed playwright set (TEST_E2E_PLAYWRIGHT_APPS). When the set cannot be + round's deployed closure (the inventory groups). When the set cannot be resolved the gating is skipped (flag falls back to enabled AND required).""" def setUp(self): @@ -141,6 +141,11 @@ class TestBridgeDeploymentGating(unittest.TestCase): "required": True, "bridges": ["openwebui", "flowise"], }, + "litellm_bridge": { + "enabled": True, + "required": True, + "bridges": ["litellm"], + }, "no_bridge": {"enabled": True, "required": True}, "disabled_bridge": { "enabled": False, @@ -168,27 +173,31 @@ class TestBridgeDeploymentGating(unittest.TestCase): return dict(line.split("=", 1) for line in out.splitlines()) def test_partner_deployed_keeps_true(self): - f = self._flags( - {"TEST_E2E_PLAYWRIGHT_APPS": ["web-app-gitlab", "web-app-nextcloud"]} - ) + f = self._flags({"group_names": ["web-app-gitlab", "web-app-nextcloud"]}) self.assertEqual(f["GL_BRIDGE_ADDON_ENABLED"], "true") def test_partner_not_deployed_gated_false(self): - f = self._flags( - {"TEST_E2E_PLAYWRIGHT_APPS": ["web-app-gitlab", "web-app-nextcloud"]} - ) + f = self._flags({"group_names": ["web-app-gitlab", "web-app-nextcloud"]}) self.assertEqual(f["MASTO_BRIDGE_ADDON_ENABLED"], "false") def test_any_partner_of_multi_bridge_counts(self): - f = self._flags({"TEST_E2E_PLAYWRIGHT_APPS": ["svc-ai-flowise"]}) + f = self._flags({"group_names": ["svc-ai-flowise"]}) self.assertEqual(f["MULTI_BRIDGE_ADDON_ENABLED"], "true") + def test_provider_role_without_playwright_suite_counts(self): + f = self._flags({"group_names": ["web-app-mediawiki", "svc-ai-litellm"]}) + self.assertEqual(f["LITELLM_BRIDGE_ADDON_ENABLED"], "true") + + def test_provider_role_absent_from_closure_gated_false(self): + f = self._flags({"group_names": ["web-app-mediawiki"]}) + self.assertEqual(f["LITELLM_BRIDGE_ADDON_ENABLED"], "false") + def test_no_bridge_addon_unaffected(self): - f = self._flags({"TEST_E2E_PLAYWRIGHT_APPS": ["web-app-nextcloud"]}) + f = self._flags({"group_names": ["web-app-nextcloud"]}) self.assertEqual(f["NO_BRIDGE_ADDON_ENABLED"], "true") def test_disabled_addon_stays_false(self): - f = self._flags({"TEST_E2E_PLAYWRIGHT_APPS": ["web-app-gitlab"]}) + f = self._flags({"group_names": ["web-app-gitlab"]}) self.assertEqual(f["DISABLED_BRIDGE_ADDON_ENABLED"], "false") def test_no_deployed_set_falls_back_no_gating(self): @@ -197,9 +206,7 @@ class TestBridgeDeploymentGating(unittest.TestCase): self.assertEqual(f["GL_BRIDGE_ADDON_ENABLED"], "true") def test_deployed_set_as_string_is_split(self): - f = self._flags( - {"TEST_E2E_PLAYWRIGHT_APPS": "web-app-gitlab web-app-nextcloud"} - ) + f = self._flags({"group_names": "web-app-gitlab web-app-nextcloud"}) self.assertEqual(f["GL_BRIDGE_ADDON_ENABLED"], "true") self.assertEqual(f["MASTO_BRIDGE_ADDON_ENABLED"], "false") @@ -239,9 +246,7 @@ class TestBridgeResolvesProviderKey(unittest.TestCase): self.addCleanup(lambda: [p.stop() for p in self._patchers]) def _flag(self, apps): - out = self.lookup.run( - ["web-app-wordpress"], variables={"TEST_E2E_PLAYWRIGHT_APPS": apps} - )[0] + out = self.lookup.run(["web-app-wordpress"], variables={"group_names": apps})[0] return dict(line.split("=", 1) for line in out.splitlines())[ "CA_TRUST_ADDON_ENABLED" ] diff --git a/tests/unit/python/plugins/lookup/test_api.py b/tests/unit/python/plugins/lookup/test_api.py index eaa1ecedbb..f9dc81bb27 100644 --- a/tests/unit/python/plugins/lookup/test_api.py +++ b/tests/unit/python/plugins/lookup/test_api.py @@ -90,9 +90,19 @@ class TestApiLookup(unittest.TestCase): self.lookup.run(["cloudflare.api_token"], variables={"API": "nope"}) self.assertIn("mapping", str(ctx.exception)) - def test_missing_api_global_raises_unknown_key(self): + def test_missing_api_global_falls_back_to_the_declaration(self): + self.assertEqual(self.lookup.run(["cloudflare.api_token"], variables={})[0], "") + + def test_a_provider_the_scope_omits_still_resolves(self): + out = self.lookup.run( + ["github.client_id"], + variables={"API": {"cloudflare": {"api_token": "cf"}}}, + ) + self.assertEqual(out, [""]) + + def test_an_undeclared_provider_still_raises(self): with self.assertRaises(AnsibleError): - self.lookup.run(["cloudflare.api_token"], variables={}) + self.lookup.run(["nope.api_key"], variables=self.vars) def test_templar_resolves_jinja_values(self): self.lookup._templar = _FakeTemplar(mapping={"{{ vault_cf }}": "secret-cf"}) diff --git a/tests/unit/python/plugins/lookup/test_applications.py b/tests/unit/python/plugins/lookup/test_applications.py index 4d03eb3fb1..0dfeac601b 100644 --- a/tests/unit/python/plugins/lookup/test_applications.py +++ b/tests/unit/python/plugins/lookup/test_applications.py @@ -9,6 +9,7 @@ from ansible.errors import AnsibleError from plugins.lookup.applications import LookupModule, _reset_cache_for_tests from utils.cache import base as cache_base +from utils.cache.carrier import merged_applications_cache_key from utils.cache.yaml import dump_yaml_str from utils.roles.mapping import ROLE_FILE_META_SERVICES @@ -103,6 +104,32 @@ class TestApplicationsLookup(unittest.TestCase): )[0] self.assertEqual(result, default_value) + def test_carrier_form_returns_cache_key_and_full_mapping(self) -> None: + variables = { + "applications": { + "web-app-foo": {"services": {"smtp": {"host": "override.example.org"}}} + } + } + roles_dir = str(self._tmp / "roles") + result = self.lookup.run( + [], variables=variables, roles_dir=roles_dir, carrier=True + )[0] + key = merged_applications_cache_key(variables, roles_dir=roles_dir) + self.assertEqual(result["key"], [key[0], list(key[1])]) + self.assertEqual( + result["applications"]["web-app-foo"]["services"]["smtp"]["host"], + "override.example.org", + ) + + def test_carrier_form_rejects_terms(self) -> None: + with self.assertRaises(AnsibleError): + self.lookup.run( + ["web-app-foo"], + variables={}, + roles_dir=str(self._tmp / "roles"), + carrier=True, + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_bounded_name.py b/tests/unit/python/plugins/lookup/test_bounded_name.py new file mode 100644 index 0000000000..0fa95092e8 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_bounded_name.py @@ -0,0 +1,70 @@ +import unittest +from unittest.mock import MagicMock, patch + +from ansible.errors import AnsibleError + +from plugins.lookup.bounded_name import LookupModule + +ONION = "x.wiki." + "a" * 56 + ".onion" + + +class TestBoundedNameLookup(unittest.TestCase): + def setUp(self): + self.lookup = LookupModule() + + def _get(name, *args, **kwargs): + plugin = MagicMock() + + def _run(terms, variables=None, **_kwargs): + return [(variables or {}).get("domains", {})] + + plugin.run.side_effect = _run + return plugin + + self._patchers = [ + patch("plugins.lookup.bounded_name.lookup_loader.get", side_effect=_get), + patch( + "plugins.lookup.bounded_name.get_domain", + side_effect=lambda domains, app: domains[app], + ), + patch( + "plugins.lookup.bounded_name.get_entity_name", + side_effect=lambda app: app.rsplit("-", 1)[-1], + ), + ] + for p in self._patchers: + p.start() + self.addCleanup(lambda: [p.stop() for p in self._patchers]) + + def _run(self, domain, limit, app="web-app-xwiki"): + return self.lookup.run([app, limit], variables={"domains": {app: domain}})[0] + + def test_a_fitting_domain_is_kept(self): + self.assertEqual(self._run("wiki.example.org", 63), "wiki.example.org") + + def test_a_domain_at_the_limit_is_kept(self): + self.assertEqual(self._run("a" * 27, 27), "a" * 27) + + def test_a_longer_domain_falls_back_to_the_entity(self): + self.assertEqual(self._run(ONION, 63), "xwiki") + self.assertEqual(self._run("a" * 28, 27), "xwiki") + + def test_an_empty_domain_falls_back_to_the_entity(self): + self.assertEqual(self._run("", 63), "xwiki") + + def test_bad_arity_raises(self): + with self.assertRaises(AnsibleError): + self.lookup.run(["web-app-xwiki"], variables={}) + + def test_an_empty_application_raises(self): + with self.assertRaises(AnsibleError): + self.lookup.run([" ", 63], variables={}) + + def test_a_non_positive_or_non_integer_limit_raises(self): + for limit in (0, -1, "many"): + with self.subTest(limit=limit), self.assertRaises(AnsibleError): + self.lookup.run(["web-app-xwiki", limit], variables={}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py b/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py new file mode 100644 index 0000000000..4cb4765aca --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py @@ -0,0 +1,127 @@ +"""Unit tests for the mariadb credential realignment. + +Pins the two properties the realignment depends on and neither the lint +suite nor the other compose_volumes tests reach: the SQL must stay a no-op +during the entrypoint's first-start server, and the config entry must only +appear for an engine the app owns alone. +""" + +from __future__ import annotations + +import importlib.util +import unittest +import unittest.mock as mock +from typing import ClassVar + +import jinja2 + +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +_TEMPLATE = PROJECT_ROOT / "roles/sys-svc-rdbms/templates/sql/mariadb-realign.sql.j2" + + +def _load_lookup(): + spec = importlib.util.spec_from_file_location( + "lookup_compose_volumes_realign", + str(PROJECT_ROOT / "plugins/lookup/compose_volumes.py"), + ) + mod = importlib.util.module_from_spec(spec) + assert spec and spec.loader + spec.loader.exec_module(mod) + return mod + + +def _render(**answers) -> str: + values = {"username": "appuser", "password": "s3cret", "name": "appdb"} + values.update(answers) + + def _lookup(_plugin, _app, key): + return values[key] + + env = jinja2.Environment(autoescape=False) # noqa: S701 - renders SQL, HTML escaping would corrupt the literals + return env.from_string(read_text(str(_TEMPLATE))).render( + lookup=_lookup, application_id="web-app-x" + ) + + +class TestRealignSql(unittest.TestCase): + def test_it_alters_the_application_user_with_the_current_password(self) -> None: + sql = _render() + self.assertIn("ALTER USER IF EXISTS 'appuser'@'%'", sql) + self.assertIn("IDENTIFIED BY 's3cret'", sql) + + def test_if_exists_keeps_it_a_noop_on_the_entrypoint_s_first_start(self) -> None: + """Without the guard the entrypoint's own CREATE USER dies under set -e.""" + self.assertIn("ALTER USER IF EXISTS", _render()) + self.assertNotIn("CREATE USER", _render()) + + def test_it_never_touches_root(self) -> None: + """Giving root a password breaks the first-start readiness probe.""" + self.assertNotIn("root", _render()) + + def test_it_grants_nothing(self) -> None: + """Rotating a credential changes passwords, not privileges.""" + self.assertNotIn("GRANT", _render()) + + def test_it_stays_a_single_statement(self) -> None: + self.assertEqual(1, _render().count(";")) + + +class TestWithDatabaseRealign(unittest.TestCase): + module: ClassVar = None + + @classmethod + def setUpClass(cls) -> None: + cls.module = _load_lookup() + + def _call(self, service_key, service_cfg, source="/srv/x/.env/mariadb-realign.sql"): + lm = self.module.LookupModule() + lm._loader = None + lm._templar = None + resolve = mock.patch.object( + self.module, + "resolve_database_service_key", + side_effect=service_key + if isinstance(service_key, Exception) + else lambda *_a: service_key, + ) + config = mock.patch.object( + self.module, + "get_database_service_config", + return_value=service_cfg, + ) + with ( + resolve, + config, + mock.patch.object(self.module, "lookup_loader") as loader_mock, + ): + loader_mock.get.return_value = mock.MagicMock( + run=lambda *_a, **_k: [source] + ) + return lm._with_database_realign({}, "web-app-x", {}, None) + + def test_a_dedicated_mariadb_gets_the_config_entry(self) -> None: + result = self._call("mariadb", {}) + self.assertIn(self.module.REALIGN_CONFIG_KEY, result) + entry = result[self.module.REALIGN_CONFIG_KEY] + self.assertEqual("/srv/x/.env/mariadb-realign.sql", entry["file"]) + self.assertTrue(entry["name"].startswith("x_database_realign_")) + + def test_postgres_gets_nothing(self) -> None: + self.assertIsNone(self._call("postgres", {})) + + def test_a_shared_engine_gets_nothing(self) -> None: + self.assertIsNone(self._call("mariadb", {"shared": True})) + + def test_an_unrendered_source_gets_nothing(self) -> None: + self.assertIsNone(self._call("mariadb", {}, source="")) + + def test_two_engines_defer_to_the_caller_s_diagnostic(self) -> None: + """Raising here hides compose_volumes' message naming the collision.""" + self.assertIsNone(self._call(ValueError("web-app-x: two engines"), {})) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_compose_volumes_render.py b/tests/unit/python/plugins/lookup/test_compose_volumes_render.py index 76720e4ef5..bc627be94c 100644 --- a/tests/unit/python/plugins/lookup/test_compose_volumes_render.py +++ b/tests/unit/python/plugins/lookup/test_compose_volumes_render.py @@ -2,8 +2,10 @@ from __future__ import annotations import os import sys +import tempfile import unittest import unittest.mock as mock +from pathlib import Path from typing import Any from ansible.errors import AnsibleFilterError @@ -172,6 +174,29 @@ class TestComposeVolumes(unittest.TestCase): self.assertEqual(data["volumes"]["redis"]["name"], "custom_redis") + def test_extra_secret_without_name_gets_the_content_hashed_name(self): + with tempfile.TemporaryDirectory() as tmp: + one, two = Path(tmp) / "one.yaml", Path(tmp) / "two.yaml" + one.write_text("as_token: one\n", encoding="utf-8") + two.write_text("as_token: two\n", encoding="utf-8") + secrets = self._parse_yaml( + _call( + self._base_apps(), + "app", + extra_secrets={ + "cfg": {"file": str(one)}, + "other": {"file": str(two)}, + "named": {"name": "kept", "file": str(one)}, + }, + ) + )["secrets"] + + self.assertEqual(secrets["cfg"]["file"], str(one)) + self.assertRegex(secrets["cfg"]["name"], r"^app_cfg_[0-9a-f]{8}$") + self.assertRegex(secrets["other"]["name"], r"^app_other_[0-9a-f]{8}$") + self.assertNotEqual(secrets["cfg"]["name"][-8:], secrets["other"]["name"][-8:]) + self.assertEqual(secrets["named"]["name"], "kept") + def test_database_enabled_not_shared_shared_provider_name_used_when_present(self): apps = self._base_apps() apps["app"]["services"]["mariadb"]["enabled"] = True diff --git a/tests/unit/python/plugins/lookup/test_container_dns.py b/tests/unit/python/plugins/lookup/test_container_dns.py index 9d60fbd40f..5436511b06 100644 --- a/tests/unit/python/plugins/lookup/test_container_dns.py +++ b/tests/unit/python/plugins/lookup/test_container_dns.py @@ -1,5 +1,6 @@ import sys import unittest +from typing import ClassVar from . import PROJECT_ROOT @@ -11,18 +12,38 @@ def _ensure_repo_root_on_syspath(): _ensure_repo_root_on_syspath() +from ansible.errors import AnsibleError # noqa: E402 + from plugins.lookup.container_dns import resolve_container_dns # noqa: E402 +from utils.templating.ansible import ( # noqa: E402 + TrustedAsTemplate, + _trust_as_template, +) + +_POOLS = [{"base": "10.208.0.0/12", "size": 24}] +_PUBLIC = ["192.0.2.53", "198.51.100.53"] +_GATEWAY = "10.208.0.1" _BRIDGE = {"docker0": {"ipv4": {"address": "172.17.0.1"}}} _CLEARNET = {"internet": {"dns": "172.30.0.53"}} def _vars(**overrides): + """Return play variables for the lookup. + + Args: + overrides: values replacing the defaults. + + The pools and the public resolvers are group_vars that exist on every host, + so a fixture without them tests a shape production never has. + """ variables = { "ansible_facts": _BRIDGE, "group_names": ["svc-net-tor"], "networks": _CLEARNET, "DEPLOYMENT_MODE": "compose", + "NETWORK_DOCKER_ADDRESS_POOLS": _POOLS, + "NETWORK_PUBLIC_DNS_RESOLVERS": _PUBLIC, } variables.update(overrides) return variables @@ -33,7 +54,7 @@ class TestResolveContainerDns(unittest.TestCase): with the clearnet resolver kept as fallback.""" def test_tor_node_prefers_the_bridge_resolver(self): - self.assertEqual(resolve_container_dns(_vars()), ["172.17.0.1", "172.30.0.53"]) + self.assertEqual(resolve_container_dns(_vars()), [_GATEWAY, "172.30.0.53"]) def test_without_tor_only_clearnet(self): self.assertEqual(resolve_container_dns(_vars(group_names=[])), ["172.30.0.53"]) @@ -41,13 +62,13 @@ class TestResolveContainerDns(unittest.TestCase): def test_the_bridge_follows_ownership_not_the_deploy_mode(self): self.assertEqual( resolve_container_dns(_vars(DEPLOYMENT_MODE="swarm")), - ["172.17.0.1", "172.30.0.53"], + [_GATEWAY, "172.30.0.53"], ) - def test_a_tor_node_without_clearnet_keeps_the_bridge(self): + def test_a_tor_node_without_clearnet_still_gets_a_second_resolver(self): self.assertEqual( resolve_container_dns(_vars(DEPLOYMENT_MODE="swarm", networks={})), - ["172.17.0.1"], + [_GATEWAY, _PUBLIC[0]], ) def test_a_non_tor_node_yields_nothing_without_clearnet(self): @@ -55,26 +76,332 @@ class TestResolveContainerDns(unittest.TestCase): def test_a_bridge_equal_to_clearnet_is_not_emitted_twice(self): self.assertEqual( - resolve_container_dns(_vars(networks={"internet": {"dns": "172.17.0.1"}})), - ["172.17.0.1"], + resolve_container_dns(_vars(networks={"internet": {"dns": _GATEWAY}})), + [_GATEWAY, _PUBLIC[0]], ) - def test_without_bridge_only_clearnet(self): + def test_the_declaration_answers_where_the_fact_is_absent(self): self.assertEqual( - resolve_container_dns(_vars(ansible_facts={})), ["172.30.0.53"] + resolve_container_dns(_vars(ansible_facts={}, group_names=[])), + ["172.30.0.53"], ) - def test_without_clearnet_only_bridge(self): - self.assertEqual(resolve_container_dns(_vars(networks={})), ["172.17.0.1"]) - - def test_nothing_configured_yields_empty_list(self): + def test_a_pool_less_host_has_no_bridge_to_offer(self): self.assertEqual( - resolve_container_dns(_vars(ansible_facts={}, networks={})), [] + resolve_container_dns(_vars(networks={}, NETWORK_DOCKER_ADDRESS_POOLS=[])), + [], ) def test_missing_keys_do_not_raise(self): self.assertEqual(resolve_container_dns({}), []) +class TestALoopbackResolverIsNotAClaim(unittest.TestCase): + """Reading resolv.conf cannot tell who binds the bridge. + + A systemd-resolved stub on ``127.0.0.53`` and a node dnsmasq that also + listens on the bridge look identical from the host's own resolv.conf, and + only the second is reachable from a container. Treating loopback as proof + handed ordinary hosts a bridge address nothing served, and their image + builds resolved nothing while the daemon itself resolved fine. + """ + + @staticmethod + def _facts(nameservers): + return {**_BRIDGE, "dns": {"nameservers": nameservers}} + + def _resolve(self, nameservers, **overrides): + """Return the resolver list for a host with these nameservers. + + Args: + nameservers: what the host's own resolv.conf lists. + overrides: further variables, e.g. the bridge declaration. + """ + return resolve_container_dns( + _vars(group_names=[], ansible_facts=self._facts(nameservers), **overrides) + ) + + def test_a_loopback_stub_alone_earns_no_bridge(self): + for nameservers in (["127.0.0.1"], ["127.0.0.53"], ["::1"]): + with self.subTest(nameservers=nameservers): + self.assertEqual(["172.30.0.53"], self._resolve(nameservers)) + + def test_the_declaration_is_what_earns_it(self): + self.assertEqual( + [_GATEWAY, "172.30.0.53"], + self._resolve(["127.0.0.1"], NETWORK_CONTAINER_BRIDGE_RESOLVER=True), + ) + + def test_a_routable_host_resolver_needs_no_bridge(self): + self.assertEqual(["172.30.0.53"], self._resolve(["172.30.0.53"])) + + def test_an_empty_nameserver_list_earns_no_bridge(self): + self.assertEqual(["172.30.0.53"], self._resolve([])) + + +class _Templar: + """Renders one expression, the way a play's templar would. + + Ansible 2.19+ renders only strings carrying ``TrustedAsTemplate``, and + ``str()`` drops that tag. A stub that renders any string passes while + production returns the expression untouched, so this one refuses an + untagged string exactly as the real templar does. + """ + + def __init__(self, mapping): + self.mapping = mapping + + def template(self, text): + if TrustedAsTemplate is not None and not TrustedAsTemplate.is_tagged_on(text): + return text + for name, value in self.mapping.items(): + if str(text).strip() == "{{ " + name + " | first }}": + return value[0] + return text + + +class TestTheBridgeSurvivesTheFirstRun(unittest.TestCase): + """The run that writes daemon.json is the one with no docker0 fact. + + Facts are gathered at play start and nothing re-gathers them after the + daemon is installed, so a fresh node renders its daemon config while + ``ansible_facts.docker0`` is still absent. Deriving the address from the + fact alone emitted the clearnet resolver on its own, and the inner + containers then asked a public resolver for a domain only the node dnsmasq + knows: ``server can't find infinito.test: NXDOMAIN``. + """ + + POOLS: ClassVar[list] = [{"base": "10.208.0.0/12", "size": 24}] + + def facts(self, **extra): + """Return facts for a host that resolves only through loopback. + + Args: + extra: additional fact keys, e.g. a ``docker0`` entry. + """ + return {"dns": {"nameservers": ["127.0.0.1"]}, **extra} + + def test_the_bridge_is_known_before_docker_ever_ran(self): + self.assertEqual( + resolve_container_dns( + _vars( + ansible_facts=self.facts(), + group_names=[], + networks={"internet": {"dns": "192.0.2.1"}}, + NETWORK_DOCKER_ADDRESS_POOLS=self.POOLS, + NETWORK_CONTAINER_BRIDGE_RESOLVER=True, + ) + ), + ["10.208.0.1", "192.0.2.1"], + ) + + def test_the_pass_after_docker_renders_the_same_bytes(self): + """A differing render restarts the runtime under a live stack.""" + before = resolve_container_dns( + _vars( + ansible_facts=self.facts(), + group_names=[], + networks={"internet": {"dns": "192.0.2.1"}}, + NETWORK_DOCKER_ADDRESS_POOLS=self.POOLS, + ) + ) + after = resolve_container_dns( + _vars( + ansible_facts=self.facts(docker0={"ipv4": {"address": "10.208.0.1"}}), + group_names=[], + networks={"internet": {"dns": "192.0.2.1"}}, + NETWORK_DOCKER_ADDRESS_POOLS=self.POOLS, + ) + ) + self.assertEqual(before, after) + + def test_a_stale_docker0_fact_never_reaches_the_daemon(self): + """Docker's default bridge, read before the pools moved it. + + Facts are gathered before the daemon config is applied, so ``docker0`` + still holds ``172.17.0.1`` while the pools are about to put the bridge + at ``10.208.0.1``. A swarm node shipped exactly that mismatch: its + daemon.json named the address its live interface no longer had, and + every lookup inside a container went to a dead resolver. + """ + self.assertEqual( + resolve_container_dns( + _vars( + ansible_facts=self.facts( + docker0={"ipv4": {"address": "172.17.0.1"}} + ), + group_names=[], + networks={"internet": {"dns": "192.0.2.1"}}, + NETWORK_DOCKER_ADDRESS_POOLS=self.POOLS, + NETWORK_CONTAINER_BRIDGE_RESOLVER=True, + ) + ), + ["10.208.0.1", "192.0.2.1"], + ) + + +class TestTheBridgeNeverGoesOutAlone(unittest.TestCase): + """No host shape may end up with the bridge as its only resolver. + + Whether anything answers on the bridge is not knowable from the host's own + resolv.conf: a systemd-resolved stub and a node dnsmasq both read as + loopback-only and only the second binds the bridge. A list holding just + that address therefore hands the daemon one possibly-dead nameserver, and + every container and image build loses DNS - measured as an apk install + failing on ``DNS: transient error`` with ``"dns": ["10.208.0.1"]``. + + The assertion runs over a cross-product because the regression slipped + through a suite that checked each shape on its own. + """ + + NAMESERVERS: ClassVar[list] = [ + ["127.0.0.1"], + ["127.0.0.53"], + ["::1"], + ["172.30.0.53"], + [], + ] + + def test_every_host_shape_keeps_a_second_resolver(self): + for nameservers in self.NAMESERVERS: + for tor in ([], ["svc-net-tor"]): + for clearnet in ("", "192.0.2.1"): + for docker0 in ( + {}, + {"docker0": {"ipv4": {"address": "172.17.0.1"}}}, + ): + with self.subTest( + nameservers=nameservers, tor=bool(tor), clearnet=clearnet + ): + result = resolve_container_dns( + _vars( + group_names=tor, + networks={"internet": {"dns": clearnet}}, + ansible_facts={ + "dns": {"nameservers": nameservers}, + **docker0, + }, + ) + ) + self.assertNotEqual([_GATEWAY], result) + + def test_the_fallback_is_the_declared_resolver_not_a_literal(self): + """A hardcoded address here would bypass the project's own SPOT.""" + result = resolve_container_dns( + _vars(group_names=["svc-net-tor"], networks={"internet": {"dns": ""}}) + ) + self.assertEqual([_GATEWAY, _PUBLIC[0]], result) + + def test_an_empty_resolver_declaration_fails_loudly(self): + with self.assertRaises(AnsibleError): + resolve_container_dns( + _vars( + group_names=["svc-net-tor"], + networks={"internet": {"dns": ""}}, + NETWORK_PUBLIC_DNS_RESOLVERS=[], + ) + ) + + +class TestTheTrustTagIsStillWhereBothSidesLookForIt(unittest.TestCase): + """Without this the whole class below can pass while production is broken. + + ``_trust_as_template`` and the stub both key off the same private ansible + module. Were it to move, the tagging degrades to a no-op and the templar + stops rendering, while the stub degrades to rendering anything and keeps + the tests green. This asserts the shared premise instead. + """ + + def test_the_tag_class_is_importable(self): + self.assertIsNotNone( + TrustedAsTemplate, + "ansible no longer exposes TrustedAsTemplate where " + "utils.templating.ansible looks for it; every lookup that " + "re-tags before templating silently stopped rendering", + ) + + def test_tagging_is_observable(self): + tagged = _trust_as_template("{{ x }}") + self.assertTrue(TrustedAsTemplate.is_tagged_on(tagged)) + self.assertFalse(TrustedAsTemplate.is_tagged_on(str(tagged))) + + +class TestInventoryExpressionIsRendered(unittest.TestCase): + """The field arrives through `-e @inventory.yml` and is read raw. + + While it held a literal address nobody noticed that nothing rendered it. + An expression there reached the daemon as its own source text, and docker + refused the whole config: ParseAddr("{{ ... }}"): unable to parse IP. + """ + + EXPRESSION = "{{ NETWORK_PUBLIC_DNS_RESOLVERS | first }}" + + def facts(self, nameservers): + return {"dns": {"nameservers": nameservers}, "docker0": {"ipv4": {}}} + + def test_an_expression_is_resolved_against_the_play(self): + templar = _Templar({"NETWORK_PUBLIC_DNS_RESOLVERS": ["192.0.2.1", "192.0.2.2"]}) + result = resolve_container_dns( + { + "networks": {"internet": {"dns": self.EXPRESSION}}, + "group_names": [], + "ansible_facts": self.facts(["192.0.2.9"]), + }, + templar, + ) + self.assertEqual(["192.0.2.1"], result) + + def test_no_resolver_ever_carries_jinja(self): + """What reaches daemon.json must be an address, not its source text.""" + templar = _Templar({"NETWORK_PUBLIC_DNS_RESOLVERS": ["192.0.2.1"]}) + for nameservers in ([], ["127.0.0.1"], ["192.0.2.9"]): + with self.subTest(nameservers=nameservers): + for resolver in resolve_container_dns( + { + "networks": {"internet": {"dns": self.EXPRESSION}}, + "group_names": [], + "ansible_facts": self.facts(nameservers), + }, + templar, + ): + self.assertNotIn("{{", resolver) + + def test_a_literal_survives_without_a_templar(self): + """Outside a play there is nothing to render against, and no need.""" + self.assertEqual( + ["172.30.0.53"], + resolve_container_dns( + { + "networks": {"internet": {"dns": "172.30.0.53"}}, + "group_names": [], + "ansible_facts": self.facts(["192.0.2.9"]), + } + ), + ) + + def test_an_unresolvable_expression_aborts_instead_of_reaching_docker(self): + """This is the shape that reached CI: no templar, so nothing rendered.""" + with self.assertRaises(AnsibleError) as caught: + resolve_container_dns( + { + "networks": {"internet": {"dns": self.EXPRESSION}}, + "group_names": [], + "ansible_facts": self.facts(["192.0.2.9"]), + } + ) + self.assertIn("daemon.json", str(caught.exception)) + + def test_a_templar_that_cannot_resolve_it_aborts_too(self): + with self.assertRaises(AnsibleError): + resolve_container_dns( + { + "networks": {"internet": {"dns": self.EXPRESSION}}, + "group_names": [], + "ansible_facts": self.facts(["192.0.2.9"]), + }, + _Templar({}), + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_container_extra_hosts.py b/tests/unit/python/plugins/lookup/test_container_extra_hosts.py index d1b9c21448..ed5ac4c718 100644 --- a/tests/unit/python/plugins/lookup/test_container_extra_hosts.py +++ b/tests/unit/python/plugins/lookup/test_container_extra_hosts.py @@ -248,6 +248,34 @@ class TestContainerExtraHostsLookup(unittest.TestCase): def test_no_sources_at_all_emit_nothing(self): self.assertEqual(self._run(_sso_enabled=False, extra_hosts=[]), "") + def _run_entries(self, **overrides): + variables = { + "application_id": "web-app-discourse", + "_sso_enabled": True, + "_provider_domain": ONION, + "DEPLOYMENT_MODE": "compose", + } + variables.update(overrides) + return self.lookup.run(None, variables=variables, entries_only=True) + + def test_entries_only_returns_the_raw_mappings(self): + self.assertEqual( + self._run_entries(), + ["host.docker.internal:host-gateway", f"{ONION}:host-gateway"], + ) + + def test_entries_only_follows_the_swarm_address(self): + self.assertEqual( + self._run_entries( + DEPLOYMENT_MODE="swarm", + ansible_facts={"default_ipv4": {"address": "10.0.0.7"}}, + ), + ["host.docker.internal:host-gateway", f"{ONION}:10.0.0.7"], + ) + + def test_entries_only_is_empty_without_sso(self): + self.assertEqual(self._run_entries(_sso_enabled=False), []) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_container_hostname.py b/tests/unit/python/plugins/lookup/test_container_hostname.py index 373066d99b..89ff6ebef8 100644 --- a/tests/unit/python/plugins/lookup/test_container_hostname.py +++ b/tests/unit/python/plugins/lookup/test_container_hostname.py @@ -7,62 +7,22 @@ from plugins.lookup.container_hostname import LookupModule class TestContainerHostnameLookup(unittest.TestCase): - def setUp(self): - self.lookup = LookupModule() + def test_delegates_to_bounded_name_at_the_kernel_limit(self): + bounded = MagicMock() + bounded.run.return_value = ["xwiki"] + with patch( + "plugins.lookup.container_hostname.lookup_loader.get", + return_value=bounded, + ) as get: + result = LookupModule().run(["web-app-xwiki"], variables={"k": "v"}) - def _get(name, *args, **kwargs): - plugin = MagicMock() - - def _run(terms, variables=None, **_kwargs): - return [(variables or {}).get("domains", {})] - - plugin.run.side_effect = _run - return plugin - - self._patchers = [ - patch( - "plugins.lookup.container_hostname.lookup_loader.get", - side_effect=_get, - ), - patch( - "plugins.lookup.container_hostname.get_domain", - side_effect=lambda domains, app: domains[app], - ), - patch( - "plugins.lookup.container_hostname.get_entity_name", - side_effect=lambda app: app.rsplit("-", 1)[-1], - ), - ] - for p in self._patchers: - p.start() - self.addCleanup(lambda: [p.stop() for p in self._patchers]) - - def _run(self, app, domain): - return self.lookup.run([app], variables={"domains": {app: domain}})[0] - - def test_short_domain_is_kept(self): - self.assertEqual( - self._run("web-app-xwiki", "wiki.example.org"), "wiki.example.org" - ) - - def test_long_onion_domain_falls_back_to_entity(self): - onion = "x.wiki." + "a" * 56 + ".onion" - self.assertEqual(self._run("web-app-xwiki", onion), "xwiki") - - def test_63_char_domain_is_kept(self): - name = "a" * 63 - self.assertEqual(self._run("web-app-xwiki", name), name) - - def test_empty_domain_falls_back(self): - self.assertEqual(self._run("web-app-xwiki", ""), "xwiki") + self.assertEqual(result, ["xwiki"]) + self.assertEqual(get.call_args.args[0], "bounded_name") + bounded.run.assert_called_once_with(["web-app-xwiki", 63], variables={"k": "v"}) def test_bad_arity_raises(self): with self.assertRaises(AnsibleError): - self.lookup.run([], variables={}) - - def test_empty_app_raises(self): - with self.assertRaises(AnsibleError): - self.lookup.run([" "], variables={}) + LookupModule().run([], variables={}) if __name__ == "__main__": diff --git a/tests/unit/python/plugins/lookup/test_container_ports.py b/tests/unit/python/plugins/lookup/test_container_ports.py index cf854230f9..385946855a 100644 --- a/tests/unit/python/plugins/lookup/test_container_ports.py +++ b/tests/unit/python/plugins/lookup/test_container_ports.py @@ -119,5 +119,133 @@ class TestContainerPortsLookup(unittest.TestCase): self.assertEqual(out, ['ports:\n - "10.0.0.1:8002:3000"']) +def _edge_apps(): + return { + "web-svc-coturn": { + "services": { + "coturn": { + "ports": { + "public": { + "stun_turn": 3481, + "relay": {"start": 20000, "end": 39999}, + } + } + }, + "openresty": { + "ports": { + "internal": {"http": 80}, + "public": {"http": 80}, + } + }, + "api": {"ports": {"internal": {"http": 5000}}}, + } + } + } + + +def _run_edge(terms): + lookup = LookupModule() + lookup._loader = mock.MagicMock() + apps = _edge_apps() + with patch("plugins.lookup.container_ports.lookup_loader") as loader_mock: + loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [apps]) + return lookup.run(terms, variables={"application_id": "web-svc-coturn"})[0] + + +class TestContainerPortsDictTerms(unittest.TestCase): + def test_one_list_item_per_transport(self): + out = _run_edge( + [ + { + "service": "coturn", + "protocol": "stun_turn", + "transport": ["udp", "tcp"], + "container": "same", + } + ] + ) + self.assertEqual(out, 'ports:\n - "3481:3481/udp"\n - "3481:3481/tcp"') + + def test_a_range_renders_on_both_sides(self): + out = _run_edge( + [ + { + "service": "coturn", + "protocol": "relay", + "transport": "udp", + "container": "same", + } + ] + ) + self.assertEqual(out, 'ports:\n - "20000-39999:20000-39999/udp"') + + def test_host_mode_emits_the_long_block(self): + out = _run_edge([{"service": "openresty", "protocol": "http", "mode": "host"}]) + self.assertEqual( + out, + "ports:\n - target: 80\n published: 80\n" + " protocol: tcp\n mode: host", + ) + + def test_ephemeral_publishes_only_the_container_port(self): + out = _run_edge( + [{"service": "api", "protocol": "http", "publish": "ephemeral"}] + ) + self.assertEqual(out, 'ports:\n - "5000"') + + def test_host_mode_rejects_an_ip(self): + with self.assertRaises(AnsibleError): + _run_edge( + [ + { + "service": "openresty", + "protocol": "http", + "mode": "host", + "ip": "10.0.0.1", + } + ] + ) + + def test_an_unknown_term_key_is_rejected(self): + with self.assertRaises(AnsibleError): + _run_edge([{"service": "openresty", "protocol": "http", "protokol": "tcp"}]) + + def test_key_names_the_block(self): + lookup = LookupModule() + lookup._loader = mock.MagicMock() + with patch("plugins.lookup.container_ports.lookup_loader") as loader_mock: + loader_mock.get.return_value = mock.MagicMock( + run=lambda *_a, **_k: [_edge_apps()] + ) + out = lookup.run( + [["openresty", "http"]], + variables={"application_id": "web-svc-coturn"}, + key="expose", + ) + self.assertEqual(out, ['expose:\n - "80:80"']) + + def test_an_unknown_block_key_is_rejected(self): + lookup = LookupModule() + lookup._loader = mock.MagicMock() + with ( + patch("plugins.lookup.container_ports.lookup_loader") as loader_mock, + self.assertRaises(AnsibleError), + ): + loader_mock.get.return_value = mock.MagicMock( + run=lambda *_a, **_k: [_edge_apps()] + ) + lookup.run( + [["openresty", "http"]], + variables={"application_id": "web-svc-coturn"}, + key="publish", + ) + + def test_an_unknown_transport_is_rejected(self): + with self.assertRaises(AnsibleError): + _run_edge( + [{"service": "openresty", "protocol": "http", "transport": "sctp"}] + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_container_volumes_render.py b/tests/unit/python/plugins/lookup/test_container_volumes_render.py index 2836b61816..906f9c84d2 100644 --- a/tests/unit/python/plugins/lookup/test_container_volumes_render.py +++ b/tests/unit/python/plugins/lookup/test_container_volumes_render.py @@ -1,6 +1,7 @@ from __future__ import annotations import unittest +from collections.abc import Mapping import yaml @@ -122,7 +123,8 @@ class TestContainerVolumesConfigSecret(unittest.TestCase): class TestContainerVolumesTmpfs(unittest.TestCase): - def test_tmpfs_renders_long_form_dict(self) -> None: + def test_tmpfs_size_renders_as_the_byte_count_the_long_form_takes(self) -> None: + """Compose rejects "64m" outright: the long form takes an integer.""" meta = { "scratch": { "type": "tmpfs", @@ -138,7 +140,67 @@ class TestContainerVolumesTmpfs(unittest.TestCase): { "type": "tmpfs", "target": "/scratch", - "tmpfs": {"size": "64m"}, + "tmpfs": {"size": 64 * 1024**2}, + } + ] + }, + ) + + def test_every_unit_a_declaration_may_use_resolves(self) -> None: + for written, expected in ( + ("512m", 512 * 1024**2), + ("64k", 64 * 1024), + ("2g", 2 * 1024**3), + ("900b", 900), + ("900", 900), + (1024, 1024), + ): + with self.subTest(size=written): + meta = { + "scratch": { + "type": "tmpfs", + "mounts": [ + {"service": "app", "target": "/scratch", "size": written} + ], + } + } + data = _parse(container_volumes(_apps(meta), "my-app", "app")) + self.assertEqual(expected, data["volumes"][0]["tmpfs"]["size"]) + + def test_a_size_that_is_not_a_byte_count_is_refused(self) -> None: + """Silently passing it on is what let "512m" reach compose.""" + for written in ("", "abc", "12x"): + with self.subTest(size=written): + meta = { + "scratch": { + "type": "tmpfs", + "mounts": [ + {"service": "app", "target": "/scratch", "size": written} + ], + } + } + with self.assertRaises(Exception): # noqa: B017 - the plugin raises an Ansible error type + container_volumes(_apps(meta), "my-app", "app") + + def test_tmpfs_mode_renders_as_decimal_of_the_octal_string(self) -> None: + meta = { + "scratch": { + "type": "tmpfs", + "mounts": [ + {"service": "app", "target": "/scratch", "mode": "01777"}, + ], + } + } + out = container_volumes(_apps(meta), "my-app", "app") + data = _parse(out) + self.assertEqual( + data, + { + "volumes": [ + { + "type": "tmpfs", + "target": "/scratch", + "tmpfs": {"mode": 0o1777}, } ] }, @@ -270,6 +332,38 @@ class TestContainerVolumesExtras(unittest.TestCase): }, ) + def test_extras_handed_over_as_templating_proxies_still_serialize(self) -> None: + class ProxyMapping(Mapping): + def __init__(self, data): + self._data = data + + def __getitem__(self, key): + return self._data[key] + + def __iter__(self): + return iter(self._data) + + def __len__(self): + return len(self._data) + + class TaggedInt(int): + pass + + out = container_volumes( + _apps(None), + "my-app", + "app", + extra_secrets=[ + ProxyMapping( + {"source": "s", "target": "/run/y", "mode": TaggedInt(0o444)} + ) + ], + ) + self.assertEqual( + _parse(out), + {"secrets": [{"source": "s", "target": "/run/y", "mode": 0o444}]}, + ) + class TestContainerVolumesOutputShape(unittest.TestCase): def test_empty_meta_returns_empty_string(self) -> None: diff --git a/tests/unit/python/plugins/lookup/test_current_play_redirect_domains.py b/tests/unit/python/plugins/lookup/test_current_play_redirect_domains.py index b1711b0057..76e92629e9 100644 --- a/tests/unit/python/plugins/lookup/test_current_play_redirect_domains.py +++ b/tests/unit/python/plugins/lookup/test_current_play_redirect_domains.py @@ -57,7 +57,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): def test_primary_redirect_appended_when_both_domains_set(self): lm = self._make_lookup() variables = { - "DOMAIN_PRIMARY": "infinito.example", + "DOMAIN_PRIMARY": "infinito.test", "DOMAIN_HOMEPAGE": "infinito.nexus", } with self._patch_lookups( @@ -65,28 +65,28 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): ): result = lm.run(terms=[], variables=variables)[0] self.assertIn( - {"source": "infinito.example", "target": "infinito.nexus"}, + {"source": "infinito.test", "target": "infinito.nexus"}, result, ) def test_primary_redirect_appended_even_when_rdr_domains_not_in_deployed(self): lm = self._make_lookup() variables = { - "DOMAIN_PRIMARY": "infinito.example", + "DOMAIN_PRIMARY": "infinito.test", "DOMAIN_HOMEPAGE": "infinito.nexus", } with self._patch_lookups(deployed=["web-opt-rdr-www"], current_play_apps={}): result = lm.run(terms=[], variables=variables)[0] self.assertEqual( result, - [{"source": "infinito.example", "target": "infinito.nexus"}], + [{"source": "infinito.test", "target": "infinito.nexus"}], ) def test_primary_redirect_absent_when_primary_equals_homepage(self): lm = self._make_lookup() variables = { - "DOMAIN_PRIMARY": "infinito.example", - "DOMAIN_HOMEPAGE": "infinito.example", + "DOMAIN_PRIMARY": "infinito.test", + "DOMAIN_HOMEPAGE": "infinito.test", } with self._patch_lookups( deployed=["web-opt-rdr-domains"], current_play_apps={} @@ -96,7 +96,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): def test_primary_redirect_absent_when_domain_homepage_missing(self): lm = self._make_lookup() - variables = {"DOMAIN_PRIMARY": "infinito.example"} + variables = {"DOMAIN_PRIMARY": "infinito.test"} with self._patch_lookups( deployed=["web-opt-rdr-domains"], current_play_apps={} ): @@ -167,7 +167,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): } } variables = { - "DOMAIN_PRIMARY": "infinito.example", + "DOMAIN_PRIMARY": "infinito.test", "DOMAIN_HOMEPAGE": "infinito.nexus", "AUTO_BUILD_ALIASES": False, "redirect_domain_mappings": [ @@ -180,7 +180,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): result = lm.run(terms=[], variables=variables)[0] sources = {entry["source"]: entry["target"] for entry in result} self.assertEqual(sources.get("legacy.example.com"), "current.example.com") - self.assertEqual(sources.get("infinito.example"), "infinito.nexus") + self.assertEqual(sources.get("infinito.test"), "infinito.nexus") self.assertEqual(sources.get("alt-foo.example.com"), "foo.example.com") def test_non_list_redirect_domain_mappings_treated_as_empty(self): @@ -193,7 +193,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): def test_non_mapping_applications_current_play_skipped(self): lm = self._make_lookup() variables = { - "DOMAIN_PRIMARY": "infinito.example", + "DOMAIN_PRIMARY": "infinito.test", "DOMAIN_HOMEPAGE": "infinito.nexus", } with self._patch_lookups( @@ -202,7 +202,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): result = lm.run(terms=[], variables=variables)[0] self.assertEqual( result, - [{"source": "infinito.example", "target": "infinito.nexus"}], + [{"source": "infinito.test", "target": "infinito.nexus"}], ) def test_jinja_tagged_domain_primary_is_templated(self): @@ -219,7 +219,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): lm = LookupModule() lm._templar = _ResolvingTemplar( { - "{{ lookup('env','INFINITO_DOMAIN') }}": "infinito.example", + "{{ lookup('env','INFINITO_DOMAIN') }}": "infinito.test", "{{ lookup('domain','web-app-dashboard') }}": "infinito.nexus", } ) @@ -235,7 +235,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): self.assertEqual( result, - [{"source": "infinito.example", "target": "infinito.nexus"}], + [{"source": "infinito.test", "target": "infinito.nexus"}], ) self.assertIn( "{{ lookup('env','INFINITO_DOMAIN') }}", @@ -244,7 +244,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): def _onion_variables(self, **overrides): variables = { - "DOMAIN_PRIMARY": "infinito.example", + "DOMAIN_PRIMARY": "infinito.test", "DOMAIN_HOMEPAGE": "dashboard.abcdefonion.onion", "group_names": ["svc-net-tor", "web-app-dashboard"], "applications": { @@ -267,7 +267,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): result, [ { - "source": "infinito.example", + "source": "infinito.test", "target": "dashboard.abcdefonion.onion", }, { @@ -288,7 +288,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): result, [ { - "source": "infinito.example", + "source": "infinito.test", "target": "dashboard.abcdefonion.onion", }, ], @@ -307,7 +307,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): result, [ { - "source": "infinito.example", + "source": "infinito.test", "target": "dashboard.abcdefonion.onion", }, ], @@ -331,7 +331,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): result = lm.run(terms=[], variables=variables)[0] self.assertEqual( result, - [{"source": "infinito.example", "target": "abcdefonion.onion"}], + [{"source": "infinito.test", "target": "abcdefonion.onion"}], ) def test_onion_apex_node_value_templated(self): @@ -374,7 +374,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): lm._templar = _FailingTemplar() lm._loader = None variables = { - "DOMAIN_PRIMARY": "infinito.example", + "DOMAIN_PRIMARY": "infinito.test", "DOMAIN_HOMEPAGE": "infinito.nexus", } with self._patch_lookups( @@ -383,7 +383,7 @@ class CurrentPlayRedirectDomainsLookupTests(unittest.TestCase): result = lm.run(terms=[], variables=variables)[0] self.assertEqual( result, - [{"source": "infinito.example", "target": "infinito.nexus"}], + [{"source": "infinito.test", "target": "infinito.nexus"}], ) diff --git a/tests/unit/python/plugins/lookup/test_deployment.py b/tests/unit/python/plugins/lookup/test_deployment.py index c24013a196..8a206ae003 100644 --- a/tests/unit/python/plugins/lookup/test_deployment.py +++ b/tests/unit/python/plugins/lookup/test_deployment.py @@ -22,7 +22,15 @@ class TestDeploymentLookup(unittest.TestCase): self.assertEqual(len(result), 1) self.assertEqual( set(result[0].keys()), - {"whitelist", "running", "groups", "deployed", "runtime", "all"}, + { + "whitelist", + "running", + "groups", + "inventory", + "deployed", + "runtime", + "all", + }, ) @patch("plugins.lookup.deployment.list_invokable_app_ids") @@ -88,6 +96,72 @@ class TestDeploymentLookup(unittest.TestCase): self.assertEqual(result[0]["running"], []) self.assertEqual(result[0]["all"], ["a"]) + @patch("plugins.lookup.deployment.list_invokable_app_ids") + def test_inventory_is_play_wide_not_host_scoped(self, mock_list): + mock_list.return_value = [] + worker = { + "group_names": ["web-app-mattermost"], + "groups": { + "svc-ai-litellm": ["mgr-01"], + "svc-ai-ollama": ["mgr-01"], + "web-app-mattermost": ["mgr-01", "wrk-01"], + }, + } + result = LookupModule().run([], variables=worker) + self.assertEqual(result[0]["groups"], ["web-app-mattermost"]) + self.assertEqual( + result[0]["inventory"], + ["svc-ai-litellm", "svc-ai-ollama", "web-app-mattermost"], + ) + + @patch("plugins.lookup.deployment.list_invokable_app_ids") + def test_inventory_skips_groups_without_hosts(self, mock_list): + mock_list.return_value = [] + result = LookupModule().run( + [], + variables={ + "group_names": [], + "groups": {"has-hosts": ["h1"], "empty": [], "also-empty": None}, + }, + ) + self.assertEqual(result[0]["inventory"], ["has-hosts"]) + + @patch("plugins.lookup.deployment.list_invokable_app_ids") + def test_inventory_drops_the_implicit_groups(self, mock_list): + mock_list.return_value = [] + result = LookupModule().run( + [], + variables={ + "group_names": ["web-app-mattermost"], + "groups": { + "all": ["mgr-01", "wrk-01"], + "ungrouped": ["mgr-01"], + "web-app-mattermost": ["mgr-01", "wrk-01"], + }, + }, + ) + self.assertEqual(result[0]["inventory"], ["web-app-mattermost"]) + + @patch("plugins.lookup.deployment.list_invokable_app_ids") + def test_inventory_empty_without_the_magic_var(self, mock_list): + mock_list.return_value = [] + result = LookupModule().run([], variables={"group_names": ["a"]}) + self.assertEqual(result[0]["inventory"], []) + + @patch("plugins.lookup.deployment.list_invokable_app_ids") + def test_cache_key_separates_hosts_with_equal_group_names(self, mock_list): + mock_list.return_value = [] + first = LookupModule().run( + [], + variables={"group_names": ["a"], "groups": {"a": ["h1"]}}, + ) + second = LookupModule().run( + [], + variables={"group_names": ["a"], "groups": {"a": ["h1"], "b": ["h2"]}}, + ) + self.assertEqual(first[0]["inventory"], ["a"]) + self.assertEqual(second[0]["inventory"], ["a", "b"]) + @patch("plugins.lookup.deployment.list_invokable_app_ids") def test_caches_same_input(self, mock_list): mock_list.return_value = ["a"] diff --git a/tests/unit/python/plugins/lookup/test_engine_qdrant_key.py b/tests/unit/python/plugins/lookup/test_engine_qdrant_key.py new file mode 100644 index 0000000000..4a846b7a7f --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_engine_qdrant_key.py @@ -0,0 +1,56 @@ +"""The read-only qdrant key never leaves the MCP adapter. + +qdrant authenticates with two engine-wide keys and has no per-consumer +principals, so the only thing keeping the adapter unable to write is which key +it is handed. A consumer lookup that reached for the read-only key, or an +adapter that received the full one, would erase that boundary without any +declaration changing. +""" + +from __future__ import annotations + +import importlib +import unittest + +plugin_module = importlib.import_module("plugins.lookup.engine") +qdrant_consumer_key = plugin_module.qdrant_consumer_key + +SVC = "svc-db-qdrant" + +BOTH_KEYS = { + SVC: { + "secrets": { + "credentials": { + "api_key": "full-access-key", + "read_only_api_key": "read-only-key", + } + } + } +} + + +class TestQdrantConsumerKey(unittest.TestCase): + def test_a_data_owning_consumer_gets_the_full_key(self) -> None: + self.assertEqual("full-access-key", qdrant_consumer_key(BOTH_KEYS, SVC)) + + def test_the_read_only_key_is_never_handed_to_a_consumer(self) -> None: + self.assertNotIn( + "read-only-key", + qdrant_consumer_key(BOTH_KEYS, SVC), + "the adapter's read-only guarantee is that it holds this key and " + "nothing else; handing it out elsewhere makes the key meaningless", + ) + + def test_an_engine_without_a_declared_key_yields_nothing(self) -> None: + self.assertEqual("", qdrant_consumer_key({SVC: {}}, SVC)) + + def test_an_absent_service_role_does_not_raise(self) -> None: + self.assertEqual("", qdrant_consumer_key({}, SVC)) + + def test_a_blank_key_does_not_render_as_whitespace(self) -> None: + blank = {SVC: {"secrets": {"credentials": {"api_key": " "}}}} + self.assertEqual("", qdrant_consumer_key(blank, SVC)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py b/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py new file mode 100644 index 0000000000..cfbc4d0e3a --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py @@ -0,0 +1,110 @@ +"""Unit tests for ``plugins/lookup/mcp_client_bearer.py``. + +The sub-lookups are stubbed so the tests stay hermetic: what matters is that +the source declared in ``mcp.credential`` decides which secret comes back, and +that a provider fronted by an adapter never answers with the token its upstream +principal holds. +""" + +from __future__ import annotations + +import importlib.util +import unittest +from unittest import mock +from unittest.mock import patch + +from ansible.errors import AnsibleError + +from . import PROJECT_ROOT + + +def _load_module(): + path = PROJECT_ROOT / "plugins/lookup/mcp_client_bearer.py" + spec = importlib.util.spec_from_file_location("lookup_mcp_client_bearer", str(path)) + module = importlib.util.module_from_spec(spec) + assert spec and spec.loader + spec.loader.exec_module(module) + return module + + +class _DummyTemplar: + def __init__(self): + self.available_variables = {} + + +class TestMcpClientBearerLookup(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.mod = _load_module() + + def _run(self, terms, credential, role_credentials=None, users=None): + lookup = self.mod.LookupModule() + lookup._templar = _DummyTemplar() + lookup._loader = mock.MagicMock() + + class _StubConfig: + def run(self, terms_, variables=None, **kwargs): + if terms_[1] == "mcp.credential": + return [credential] + return [role_credentials if role_credentials is not None else {}] + + class _StubUsers: + def run(self, terms_, variables=None, **kwargs): + return [users if users is not None else {}] + + def _dispatch(name, **_kwargs): + return _StubConfig() if name == "config" else _StubUsers() + + with patch.object(self.mod.lookup_loader, "get", side_effect=_dispatch): + return lookup.run(terms, variables={}) + + def test_an_adapter_answers_with_its_own_rendered_bearer(self): + credential = { + "owner": "mcp-web-app-gitea", + "source": "credentials", + "key": "mcp_bearer", + } + self.assertEqual( + ["adapter-secret"], + self._run( + ["web-app-gitea"], + credential, + role_credentials={"mcp_bearer": "adapter-secret"}, + users={"tokens": {"web-app-gitea": "upstream-pat"}}, + ), + ) + + def test_a_native_provider_answers_with_the_stored_token(self): + credential = { + "owner": "mcp-web-app-nextcloud", + "source": "token_store", + "key": "web-app-nextcloud", + } + self.assertEqual( + ["stored-token"], + self._run( + ["web-app-nextcloud"], + credential, + users={"tokens": {"web-app-nextcloud": "stored-token"}}, + ), + ) + + def test_a_provider_without_a_secret_yet_reads_empty(self): + credential = { + "owner": "mcp-web-app-gitea", + "source": "credentials", + "key": "mcp_bearer", + } + self.assertEqual([""], self._run(["web-app-gitea"], credential)) + + def test_an_undeclared_credential_raises(self): + with self.assertRaises(AnsibleError): + self._run(["web-app-gitea"], None) + + def test_a_missing_application_id_raises(self): + with self.assertRaises(AnsibleError): + self._run([], {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_mcp_credential.py b/tests/unit/python/plugins/lookup/test_mcp_credential.py new file mode 100644 index 0000000000..fc67f6fb62 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_mcp_credential.py @@ -0,0 +1,102 @@ +"""Unit tests for ``plugins/lookup/mcp_credential.py``. + +The sub-lookups are stubbed so the tests stay hermetic: what matters is that +one call site cannot resolve the owner, the token key or the fallbacks +differently from another. +""" + +from __future__ import annotations + +import importlib.util +import unittest +from unittest import mock +from unittest.mock import patch + +from ansible.errors import AnsibleError + +from . import PROJECT_ROOT + + +def _load_module(): + path = PROJECT_ROOT / "plugins/lookup/mcp_credential.py" + spec = importlib.util.spec_from_file_location("lookup_mcp_credential", str(path)) + module = importlib.util.module_from_spec(spec) + assert spec and spec.loader + spec.loader.exec_module(module) + return module + + +class _DummyTemplar: + def __init__(self): + self.available_variables = {} + + +class TestMcpCredentialLookup(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.mod = _load_module() + + def _run(self, terms, owner="mcp-web-app-gitea", users=None): + lookup = self.mod.LookupModule() + lookup._templar = _DummyTemplar() + lookup._loader = mock.MagicMock() + + class _StubConfig: + def run(self, terms_, variables=None, **kwargs): + return [owner] + + class _StubUsers: + def run(self, terms_, variables=None, **kwargs): + return [users if users is not None else {}] + + def _dispatch(name, **_kwargs): + return _StubConfig() if name == "config" else _StubUsers() + + with patch.object(self.mod.lookup_loader, "get", side_effect=_dispatch): + return lookup.run(terms, variables={}) + + def test_the_stored_token_is_returned_trimmed(self): + users = {"tokens": {"web-app-gitea": " tok-123 "}} + self.assertEqual(["tok-123"], self._run(["web-app-gitea"], users=users)) + + def test_a_provider_without_a_token_yet_reads_empty(self): + self.assertEqual([""], self._run(["web-app-gitea"], users={"tokens": {}})) + + def test_another_providers_token_is_not_returned(self): + users = {"tokens": {"web-app-gitlab": "tok-other"}} + self.assertEqual([""], self._run(["web-app-gitea"], users=users)) + + def test_a_missing_owner_declaration_raises(self): + with self.assertRaises(AnsibleError): + self._run(["web-app-gitea"], owner="") + + def test_zero_or_too_many_terms_raise(self): + for terms in ([], ["a", "b", "c"], [" "]): + with self.assertRaises(AnsibleError): + self._run(terms) + + def test_an_unknown_role_raises_instead_of_returning_nothing(self): + with self.assertRaises(AnsibleError): + self._run(["web-app-gitea", "mcp-writter"]) + + def test_a_writer_token_is_read_from_its_own_key(self): + self.assertEqual( + ["w-tok"], + self._run( + ["web-app-gitea", "mcp-writer"], + users={"tokens": {"web-app-gitea:mcp-writer": "w-tok"}}, + ), + ) + + def test_a_role_reads_a_separate_token(self): + self.assertEqual( + [""], + self._run( + ["web-app-gitea", "mcp-writer"], + users={"tokens": {"web-app-gitea": "reader-only"}}, + ), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_mcp_servers.py b/tests/unit/python/plugins/lookup/test_mcp_servers.py new file mode 100644 index 0000000000..6ef82cbe62 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_mcp_servers.py @@ -0,0 +1,422 @@ +"""Unit tests for ``plugins/lookup/mcp_servers.py``. + +Only the pure builder and the credential resolver are exercised; the lookup +wrapper forwards ``roles_with_service``, ``applications`` and ``users`` into +them. +""" + +import importlib +import unittest +from typing import ClassVar + +from ansible.errors import AnsibleError + +plugin_module = importlib.import_module("plugins.lookup.mcp_servers") +build_mcp_discovery = plugin_module.build_mcp_discovery +resolve_credential = plugin_module.resolve_credential +resolve_consumer_id = plugin_module.resolve_consumer_id +role_credentials_of = plugin_module.role_credentials_of + +CONSUMER = "web-app-openwebui" + +CLIENT = { + "supported_transports": ["streamable_http", "sse"], + "supported_auths": ["bearer_token", "app_password"], +} + +HOMEASSISTANT = { + "id": "web-app-homeassistant", + "auth": "bearer_token", + "auth_subject": "service_account", + "transport": "streamable_http", + "allowed_consumers": [CONSUMER], + "credential": { + "owner": "mcp-web-app-homeassistant", + "source": "token_store", + "key": "web-app-homeassistant", + }, + "endpoint": {"service_key": "homeassistant", "port": 8123, "path": "/api/mcp"}, + "tools": ["GetDateTime", "HassTurnOn"], + "mutating": ["HassTurnOn"], +} + +CREDENTIALS = {"web-app-homeassistant": ("ha-token", "mcp-web-app-homeassistant")} + + +def reasons(result): + return {entry["id"]: entry["reason"] for entry in result["rejected"]} + + +class TestSelectDeployed(unittest.TestCase): + """Providers the run does not deploy must not reach a client's config. + + Inventory membership, group_names and the raw whitelist all admit roles the + play never runs; the deployed set is the whitelist's dependency closure, the + same one sys-service-loader preloads from. + """ + + SERVERS: ClassVar[list] = [ + {"id": "web-app-homeassistant"}, + {"id": "web-app-prometheus"}, + ] + + def test_a_provider_outside_the_closure_is_dropped(self): + self.assertEqual( + ["web-app-homeassistant"], + [ + s["id"] + for s in plugin_module.select_deployed( + self.SERVERS, {"web-app-hermes", "web-app-homeassistant"} + ) + ], + ) + + def test_an_unresolvable_closure_filters_nothing(self): + for closure in (None, set()): + self.assertEqual( + 2, + len(plugin_module.select_deployed(self.SERVERS, closure)), + "dropping every provider would look like a deployment with none", + ) + + def test_no_servers_stays_empty(self): + self.assertEqual([], plugin_module.select_deployed(None, {"web-app-hermes"})) + + +class TestBuildMcpDiscovery(unittest.TestCase): + def test_no_servers_yields_nothing(self): + for servers in (None, []): + result = build_mcp_discovery(servers, CONSUMER, CLIENT, {}) + self.assertEqual(result, {"selected": [], "rejected": []}) + + def test_authorized_server_becomes_a_container_network_entry(self): + entry = build_mcp_discovery([HOMEASSISTANT], CONSUMER, CLIENT, CREDENTIALS)[ + "selected" + ][0] + self.assertEqual(entry["id"], "web-app-homeassistant") + self.assertEqual(entry["url"], "http://homeassistant:8123/api/mcp") + self.assertEqual(entry["token"], "ha-token") + self.assertEqual(entry["auth"], "bearer_token") + self.assertEqual(entry["auth_subject"], "service_account") + self.assertEqual(entry["owner"], "mcp-web-app-homeassistant") + self.assertEqual(entry["transport"], "streamable-http") + + def test_unlisted_consumer_is_rejected_with_a_reason(self): + result = build_mcp_discovery( + [HOMEASSISTANT], "web-app-flowise", CLIENT, CREDENTIALS + ) + self.assertEqual(result["selected"], []) + self.assertEqual( + reasons(result), {"web-app-homeassistant": "consumer_not_allowed"} + ) + + def test_transport_the_client_cannot_speak_is_rejected(self): + client = dict(CLIENT, supported_transports=["sse"]) + result = build_mcp_discovery([HOMEASSISTANT], CONSUMER, client, CREDENTIALS) + self.assertEqual( + reasons(result), {"web-app-homeassistant": "transport_unsupported"} + ) + + def test_auth_the_client_cannot_present_is_rejected(self): + client = dict(CLIENT, supported_auths=["app_password"]) + result = build_mcp_discovery([HOMEASSISTANT], CONSUMER, client, CREDENTIALS) + self.assertEqual(reasons(result), {"web-app-homeassistant": "auth_unsupported"}) + + def test_unresolved_credential_is_rejected(self): + result = build_mcp_discovery([HOMEASSISTANT], CONSUMER, CLIENT, {}) + self.assertEqual( + reasons(result), {"web-app-homeassistant": "credential_missing"} + ) + + def test_incomplete_endpoint_is_rejected(self): + no_port = dict(HOMEASSISTANT, endpoint={"service_key": "x", "path": "/mcp"}) + result = build_mcp_discovery([no_port], CONSUMER, CLIENT, CREDENTIALS) + self.assertEqual( + reasons(result), {"web-app-homeassistant": "endpoint_unreachable"} + ) + + def test_two_providers_sharing_one_credential_abort_discovery(self): + twin = dict(HOMEASSISTANT, id="web-app-baserow") + credentials = dict( + CREDENTIALS, + **{"web-app-baserow": ("ha-token", "mcp-web-app-homeassistant")}, + ) + with self.assertRaises(AnsibleError): + build_mcp_discovery([HOMEASSISTANT, twin], CONSUMER, CLIENT, credentials) + + def test_a_client_never_discovers_itself(self): + itself = dict(HOMEASSISTANT, id=CONSUMER) + result = build_mcp_discovery([itself], CONSUMER, CLIENT, CREDENTIALS) + self.assertEqual(result, {"selected": [], "rejected": []}) + + def test_a_discovered_url_never_carries_a_secret_path_segment(self): + """A URL segment cannot be scoped per consumer, nor revoked alone. + + A provider that keys its session that way is fronted by an adapter, so + the segment stays between adapter and upstream and never reaches a + client's rendered configuration. + """ + keyed = dict( + HOMEASSISTANT, + endpoint={ + "service_key": "baserow", + "port": 80, + "path": "/mcp", + "key_credential": "mcp_endpoint_key", + "suffix": "sse", + }, + ) + entry = build_mcp_discovery([keyed], CONSUMER, CLIENT, CREDENTIALS)["selected"][ + 0 + ] + self.assertEqual(entry["url"], "http://baserow:80/mcp") + + def test_an_endpoint_without_a_port_is_rejected(self): + portless = dict(HOMEASSISTANT, endpoint={"service_key": "x", "path": "/mcp"}) + result = build_mcp_discovery([portless], CONSUMER, CLIENT, CREDENTIALS) + self.assertEqual( + reasons(result), {"web-app-homeassistant": "endpoint_unreachable"} + ) + + def test_a_provider_naming_no_tool_is_rejected(self): + """A runtime-composed surface keeps its contract in ``tools.categories``. + + A client filters by tool name, so that contract reaches it as no + contract at all: the rendered filter would be empty and the agent + would carry a server it can never call. + """ + dynamic = dict(HOMEASSISTANT, tools=[], mutating=[]) + result = build_mcp_discovery([dynamic], CONSUMER, CLIENT, CREDENTIALS) + self.assertEqual(result["selected"], []) + self.assertEqual( + reasons(result), {"web-app-homeassistant": "tools_unenforceable"} + ) + + def test_a_provider_withholding_every_tool_it_serves_is_rejected(self): + withheld = dict(HOMEASSISTANT, tools=["HassTurnOn"], mutating=["HassTurnOn"]) + result = build_mcp_discovery([withheld], CONSUMER, CLIENT, CREDENTIALS) + self.assertEqual(result["selected"], []) + self.assertEqual( + reasons(result), {"web-app-homeassistant": "tools_unenforceable"} + ) + + def test_a_provider_keeping_one_callable_tool_is_selected(self): + entry = build_mcp_discovery([HOMEASSISTANT], CONSUMER, CLIENT, CREDENTIALS)[ + "selected" + ][0] + self.assertEqual(["GetDateTime", "HassTurnOn"], entry["tools"]) + self.assertEqual(["HassTurnOn"], entry["mutating"]) + + def test_order_of_the_discovered_servers_is_kept(self): + jenkins = dict(HOMEASSISTANT, id="web-app-jenkins") + credentials = dict(CREDENTIALS, **{"web-app-jenkins": ("jk", "mcp-jenkins")}) + result = build_mcp_discovery( + [jenkins, HOMEASSISTANT], CONSUMER, CLIENT, credentials + ) + self.assertEqual( + [e["id"] for e in result["selected"]], + ["web-app-jenkins", "web-app-homeassistant"], + ) + + +class TestAssertAuthorizedAreRenderable(unittest.TestCase): + assert_renderable = staticmethod(plugin_module.assert_authorized_are_renderable) + + def test_nothing_rejected_passes(self): + self.assert_renderable({"selected": [], "rejected": []}) + + def test_a_narrowing_decision_passes(self): + self.assert_renderable( + { + "selected": [], + "rejected": [ + {"id": "a", "reason": "consumer_not_allowed", "detail": "d"} + ], + } + ) + + def test_a_provider_not_provisioned_yet_does_not_abort(self): + self.assert_renderable( + { + "selected": [], + "rejected": [ + {"id": "a", "reason": "credential_missing", "detail": "d"} + ], + } + ) + + def test_a_credential_that_never_resolved_aborts_the_reconciliation(self): + with self.assertRaises(AnsibleError): + self.assert_renderable( + { + "selected": [], + "rejected": [ + {"id": "a", "reason": "credential_missing", "detail": "d"} + ], + }, + strict=True, + ) + + def test_a_narrowing_decision_still_passes_under_reconciliation(self): + self.assert_renderable( + { + "selected": [], + "rejected": [ + {"id": "a", "reason": "consumer_not_allowed", "detail": "d"} + ], + }, + strict=True, + ) + + def test_an_authorized_but_unrenderable_server_aborts(self): + for reason in ( + "transport_unsupported", + "auth_unsupported", + "endpoint_unreachable", + "tools_unenforceable", + ): + with self.subTest(reason=reason), self.assertRaises(AnsibleError): + self.assert_renderable( + { + "selected": [], + "rejected": [{"id": "a", "reason": reason, "detail": "d"}], + } + ) + + +class TestResolveCredential(unittest.TestCase): + USERS: ClassVar[dict] = { + "mcp-web-app-baserow": {"tokens": {"web-app-baserow": " key "}} + } + + def _server(self, **credential): + return {"credential": credential} + + def test_token_store_owner_yields_its_stripped_token(self): + server = self._server( + owner="mcp-web-app-baserow", source="token_store", key="web-app-baserow" + ) + self.assertEqual( + resolve_credential(server, self.USERS, {}), ("key", "mcp-web-app-baserow") + ) + + def test_role_credentials_source_reads_the_role_secret(self): + server = self._server( + owner="mcp-web-app-x", source="credentials", key="mcp_token" + ) + self.assertEqual( + resolve_credential(server, {}, {"mcp_token": "v"}), ("v", "mcp-web-app-x") + ) + + def test_the_role_secret_is_read_where_the_inventory_writes_it(self): + """The function was tested; the address its caller used was not. + + Provisioning writes `<role>.secrets.credentials.<key>`, which is also + how the roles' own vars address it. Discovery read the top-level + `credentials` and therefore found nothing for all fifteen providers + whose source is `credentials`, aborting the deploy on a secret that + had been generated and vaulted all along. + """ + applications = { + "web-app-prometheus": { + "secrets": {"credentials": {"mcp_bearer": "resolved"}} + } + } + self.assertEqual( + {"mcp_bearer": "resolved"}, + role_credentials_of(applications, "web-app-prometheus"), + ) + + def test_a_top_level_credentials_block_is_not_the_address(self): + applications = {"web-app-x": {"credentials": {"mcp_bearer": "wrong-place"}}} + self.assertEqual({}, role_credentials_of(applications, "web-app-x")) + + def test_an_absent_role_yields_an_empty_mapping(self): + self.assertEqual({}, role_credentials_of({}, "web-app-missing")) + + def test_the_extraction_feeds_resolve_credential(self): + """End to end: the payload shape provisioning produces must resolve.""" + applications = { + "web-app-prometheus": { + "secrets": {"credentials": {"mcp_bearer": "resolved"}} + } + } + server = self._server( + owner="mcp-web-app-prometheus", source="credentials", key="mcp_bearer" + ) + self.assertEqual( + ("resolved", "mcp-web-app-prometheus"), + resolve_credential( + server, {}, role_credentials_of(applications, "web-app-prometheus") + ), + ) + + def test_administrator_owner_resolves_to_nothing(self): + server = self._server( + owner="administrator", source="token_store", key="web-app-baserow" + ) + users = {"administrator": {"tokens": {"web-app-baserow": "k"}}} + self.assertEqual(resolve_credential(server, users, {}), ("", "administrator")) + + def test_unknown_source_resolves_to_nothing(self): + server = self._server(owner="o", source="vault", key="k") + self.assertEqual(resolve_credential(server, {}, {}), ("", "o")) + + def test_missing_declaration_resolves_to_nothing(self): + self.assertEqual(resolve_credential({}, {}, {}), ("", "")) + + def test_a_blank_stored_token_resolves_to_nothing(self): + server = self._server( + owner="mcp-web-app-x", source="token_store", key="web-app-x" + ) + users = {"mcp-web-app-x": {"tokens": {"web-app-x": " "}}} + self.assertEqual(resolve_credential(server, users, {}), ("", "mcp-web-app-x")) + + def test_a_blank_role_credential_resolves_to_nothing(self): + server = self._server( + owner="mcp-web-app-x", source="credentials", key="mcp_token" + ) + self.assertEqual( + resolve_credential(server, {}, {"mcp_token": ""}), ("", "mcp-web-app-x") + ) + + def test_a_principal_the_store_never_saw_resolves_to_nothing(self): + server = self._server( + owner="mcp-web-app-x", source="token_store", key="web-app-x" + ) + self.assertEqual(resolve_credential(server, {}, {}), ("", "mcp-web-app-x")) + + +class TestResolveConsumerId(unittest.TestCase): + """The consumer must be a rendered role id before it is matched. + + sys-svc-mcp-reconcile sets ``application_id`` from a loop variable, so the + lookup receives the literal ``{{ mcp_client.id }}``. An unrendered id + matches no ``allowed_consumers``, which rejects every provider as + ``consumer_not_allowed`` and empties the registry without an error. + """ + + class _Templar: + def template(self, value): + return {"{{ mcp_client.id }}": CONSUMER}[value] + + def test_a_deferred_application_id_is_rendered(self): + self.assertEqual( + resolve_consumer_id( + {"application_id": "{{ mcp_client.id }}"}, self._Templar() + ), + CONSUMER, + ) + + def test_a_plain_application_id_is_kept(self): + self.assertEqual( + resolve_consumer_id({"application_id": CONSUMER}, self._Templar()), CONSUMER + ) + + def test_a_missing_application_id_aborts(self): + with self.assertRaises(AnsibleError): + resolve_consumer_id({}, self._Templar()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_playwright_workers.py b/tests/unit/python/plugins/lookup/test_playwright_workers.py index 881a9bd163..7e25e3483c 100644 --- a/tests/unit/python/plugins/lookup/test_playwright_workers.py +++ b/tests/unit/python/plugins/lookup/test_playwright_workers.py @@ -30,6 +30,27 @@ class TestComputeWorkers(unittest.TestCase): compute_workers(20, 64.0, False, cpu_divisor=2, hard_cap=100), 10 ) + def test_onion_lifts_the_latency_bound_phase(self): + """Tor makes the phase wait on circuits, so cores stop describing it. + + The 4-core runner yields one worker because a quarter of four cores is + one. Over Tor the browser waits rather than computes, so the count is + raised from that base instead of derived from cores again. + """ + self.assertEqual(compute_workers(4, 16.0, True), 1) + self.assertEqual(compute_workers(4, 16.0, True, onion=True), 2) + + def test_onion_yields_to_a_machine_with_no_memory_left(self): + """Free memory, not total, decides: a busy runner keeps one worker.""" + self.assertEqual(compute_workers(4, 5.5, True, onion=True), 1) + + def test_onion_still_respects_memory(self): + """Circuits are cheap, browsers are not: RAM keeps its veto.""" + self.assertEqual(compute_workers(20, 3.0, False, onion=True), 1) + + def test_onion_cap_binds_on_a_large_host(self): + self.assertEqual(compute_workers(64, 256.0, False, onion=True), 3) + class TestLookup(unittest.TestCase): def test_returns_single_int_ge_1(self): diff --git a/tests/unit/python/plugins/lookup/test_postgres_libraries.py b/tests/unit/python/plugins/lookup/test_postgres_libraries.py index 77f961cf37..5100931c71 100644 --- a/tests/unit/python/plugins/lookup/test_postgres_libraries.py +++ b/tests/unit/python/plugins/lookup/test_postgres_libraries.py @@ -50,7 +50,7 @@ class PostgresLibrariesLookupTests(unittest.TestCase): self.assertEqual(len(result), 1) self.assertEqual(result[0]["extension"], "vector") self.assertEqual(result[0]["name"], "pgvector") - self.assertIn("git_source", result[0]) + self.assertEqual(result[0]["apt_package"], "pgvector") def test_base_extensions_are_filtered_out(self): result = self._run([["bloom", "postgis", "pg_trgm", "unaccent"]])[0] diff --git a/tests/unit/python/plugins/lookup/test_redirect_uris.py b/tests/unit/python/plugins/lookup/test_redirect_uris.py index b280ecc7d1..9a4772ea9a 100644 --- a/tests/unit/python/plugins/lookup/test_redirect_uris.py +++ b/tests/unit/python/plugins/lookup/test_redirect_uris.py @@ -1,6 +1,7 @@ from __future__ import annotations import unittest +from unittest import mock from ansible.errors import AnsibleError @@ -83,6 +84,18 @@ class TestBuildRedirectUris(unittest.TestCase): ], ) + def test_only_deployed_consumers_are_registered(self): + domains = {"deployed": "a.example.org", "parked": "b.example.org"} + result = build_redirect_uris( + domains, {"deployed": SSO, "parked": SSO}, True, deployed=["deployed"] + ) + self.assertEqual(result, ["https://a.example.org/*"]) + + def test_no_deployment_scope_registers_every_consumer(self): + domains = {"one": "a.example.org", "two": "b.example.org"} + result = build_redirect_uris(domains, {"one": SSO, "two": SSO}, True) + self.assertEqual(result, ["https://a.example.org/*", "https://b.example.org/*"]) + def test_invalid_domains_type_raises(self): with self.assertRaises(AnsibleError): build_redirect_uris(["not-a-dict"], {}, True) # type: ignore[arg-type] @@ -105,6 +118,31 @@ class TestRedirectUrisLookup(unittest.TestCase): with self.assertRaises(AnsibleError): self.lookup.run([], variables={}) + def test_missing_group_names_raises(self): + with self.assertRaises(AnsibleError): + self.lookup.run([], variables={"TLS_ENABLED": True}) + + def test_group_names_scope_the_registered_consumers(self): + class _Stub: + def __init__(self, payload): + self.payload = payload + + def run(self, terms, variables=None, **kwargs): + return [self.payload] + + payloads = { + "domains": _Stub({"deployed": "a.example.org", "parked": "b.example.org"}), + "applications": _Stub({"deployed": SSO, "parked": SSO}), + } + with mock.patch( + "plugins.lookup.redirect_uris.lookup_loader.get", + side_effect=lambda name, **kwargs: payloads[name], + ): + result = self.lookup.run( + [], variables={"TLS_ENABLED": True, "group_names": ["deployed"]} + ) + self.assertEqual(result, [["https://a.example.org/*"]]) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_roles_with_service.py b/tests/unit/python/plugins/lookup/test_roles_with_service.py index ea6a7177fd..6fa2d754e4 100644 --- a/tests/unit/python/plugins/lookup/test_roles_with_service.py +++ b/tests/unit/python/plugins/lookup/test_roles_with_service.py @@ -329,14 +329,25 @@ class RolesWithServiceLookupTests(unittest.TestCase): result = self._run(["dashboard"], applications)[0] self.assertEqual([r["id"] for r in result], ["web-app-bar"]) - def test_canonical_with_empty_first_entry_is_skipped(self): + def test_canonical_with_empty_first_entry_raises(self): applications = { "web-app-foo": { "services": {"dashboard": {"enabled": True, "shared": True}}, "domains": {"canonical": ["", "foo.example.com"]}, }, } - self.assertEqual(self._run(["dashboard"], applications), [[]]) + with self.assertRaises(AnsibleError): + self._run(["dashboard"], applications) + + def test_canonical_mapping_resolves_to_its_first_domain(self): + applications = { + "web-app-foo": { + "services": {"dashboard": {"enabled": True, "shared": True}}, + "domains": {"canonical": {"foo": "foo.example.com"}}, + }, + } + result = self._run(["dashboard"], applications)[0] + self.assertEqual([r["canonical_domain"] for r in result], ["foo.example.com"]) def test_unrendered_jinja_strings_are_treated_as_truthy(self): """In a real Ansible play, ``get_merged_applications`` runs the @@ -408,6 +419,37 @@ class RolesWithServiceLookupTests(unittest.TestCase): "scope='all' returns deployment-scoped consumers regardless of group_names", ) + def test_deployment_scope_spans_hosts_but_not_the_whole_repository(self): + applications = { + "web-app-foo": { + "services": {"logout": {"enabled": True, "shared": True}}, + "domains": {"canonical": ["foo.example.com"]}, + }, + "web-app-bar": { + "services": {"logout": {"enabled": True, "shared": True}}, + "domains": {"canonical": ["bar.example.com"]}, + }, + "web-app-undeployed": { + "services": {"logout": {"enabled": True, "shared": True}}, + "domains": {"canonical": ["undeployed.example.com"]}, + }, + } + vars_ = { + "group_names": ["web-app-foo"], + "groups": { + "web-app-foo": ["host-a"], + "web-app-bar": ["host-b"], + "web-app-undeployed": [], + }, + } + result = self._run(["logout"], applications, vars_=vars_, scope="deployment")[0] + self.assertEqual( + sorted(r["id"] for r in result), + ["web-app-bar", "web-app-foo"], + "a role deployed on another host of the same deployment is " + "reachable; a role in the repository but in no group is not", + ) + def test_self_provider_is_excluded(self): applications = { "web-svc-logout": { @@ -436,6 +478,86 @@ class RolesWithServiceLookupTests(unittest.TestCase): result = self._run(["logout"], applications)[0] self.assertEqual([r["id"] for r in result], ["web-app-bar", "web-app-foo"]) + def _mcp_role(self, direction: str, **mcp_extra) -> dict: + mcp = { + "enabled": True, + "shared": True, + "direction": direction, + "transport": "streamable_http", + "auth": "bearer_token", + "auth_subject": "user", + "endpoint": { + "service_key": "baserow", + "path": "/mcp", + "port_key": "http", + }, + } + mcp.update(mcp_extra) + return { + "services": { + "mcp": mcp, + "baserow": {"ports": {"local": {"http": 8021}}}, + }, + "domains": {"canonical": ["srv.example.com"]}, + } + + def test_direction_filter_excludes_other_direction(self): + applications = { + "web-app-server": self._mcp_role("server"), + "web-app-client": self._mcp_role("client"), + } + result = self._run(["mcp"], applications, direction="server")[0] + self.assertEqual([r["id"] for r in result], ["web-app-server"]) + + def test_direction_filter_includes_both(self): + applications = {"web-app-duplex": self._mcp_role("both")} + result = self._run(["mcp"], applications, direction="server")[0] + self.assertEqual([r["id"] for r in result], ["web-app-duplex"]) + + def test_direction_entry_carries_endpoint_metadata(self): + applications = {"web-app-server": self._mcp_role("server")} + entry = self._run(["mcp"], applications, direction="server")[0][0] + self.assertEqual(entry["transport"], "streamable_http") + self.assertEqual(entry["auth"], "bearer_token") + self.assertEqual(entry["auth_subject"], "user") + self.assertEqual( + entry["endpoint"], + { + "service_key": "baserow", + "path": "/mcp", + "port": 8021, + }, + ) + + def test_direction_endpoint_port_falls_back_to_internal(self): + role = self._mcp_role("server") + role["services"]["baserow"] = {"ports": {"internal": {"http": 80}}} + applications = {"web-app-server": role} + entry = self._run(["mcp"], applications, direction="server")[0][0] + self.assertEqual(entry["endpoint"]["port"], 80) + + def test_the_internal_port_wins_without_any_exposure_declaration(self): + role = self._mcp_role("server") + role["services"]["baserow"]["ports"]["internal"] = {"http": 80} + applications = {"web-app-server": role} + entry = self._run(["mcp"], applications, direction="server")[0][0] + self.assertEqual(entry["endpoint"]["port"], 80) + + def test_an_exposure_declaration_does_not_change_the_port(self): + role = self._mcp_role("server") + role["services"]["mcp"]["exposure"] = "public" + role["services"]["baserow"]["ports"]["internal"] = {"http": 80} + applications = {"web-app-server": role} + entry = self._run(["mcp"], applications, direction="server")[0][0] + self.assertEqual(entry["endpoint"]["port"], 80) + + def test_without_direction_kwarg_shape_is_unchanged(self): + applications = {"web-app-server": self._mcp_role("server")} + entry = self._run(["mcp"], applications)[0][0] + self.assertEqual( + sorted(entry), ["canonical_domain", "canonical_url", "id", "iframe"] + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_smtp_host.py b/tests/unit/python/plugins/lookup/test_smtp_host.py index ad79655a11..18b956f756 100644 --- a/tests/unit/python/plugins/lookup/test_smtp_host.py +++ b/tests/unit/python/plugins/lookup/test_smtp_host.py @@ -14,7 +14,7 @@ from ansible.errors import AnsibleError from . import PROJECT_ROOT -RELAY = "mail.infinito.example" +RELAY = "mail.infinito.test" MANAGER = "swarm-manager-01" diff --git a/tests/unit/python/plugins/lookup/test_sso.py b/tests/unit/python/plugins/lookup/test_sso.py index ba3b88cfea..050fd488b0 100644 --- a/tests/unit/python/plugins/lookup/test_sso.py +++ b/tests/unit/python/plugins/lookup/test_sso.py @@ -50,6 +50,7 @@ def _apps( oauth2_origin_port=None, oauth2_acl=None, oauth2_allowed_groups=None, + oauth2_pass_access_token=None, include_app=True, ): if not include_app: @@ -67,6 +68,8 @@ def _apps( oauth2_sub["acl"] = oauth2_acl if oauth2_allowed_groups is not None: oauth2_sub["allowed_groups"] = oauth2_allowed_groups + if oauth2_pass_access_token is not None: + oauth2_sub["pass_access_token"] = oauth2_pass_access_token if oauth2_sub: sso["oauth2"] = oauth2_sub return {"web-app-x": {"services": {"sso": sso}}} @@ -126,6 +129,34 @@ class SsoLookupTests(unittest.TestCase): ) self.assertEqual(result, [True]) + def test_pass_access_token_defaults_to_false(self): + result = self._run( + _apps(enabled=True, flavor="oauth2"), + ["web-app-x", "oauth2_pass_access_token"], + ) + self.assertEqual(result, [False]) + + def test_pass_access_token_reads_the_declared_opt_in(self): + result = self._run( + _apps(enabled=True, flavor="oauth2", oauth2_pass_access_token=True), + ["web-app-x", "oauth2_pass_access_token"], + ) + self.assertEqual(result, [True]) + + def test_pass_access_token_accepts_a_rendered_string(self): + result = self._run( + _apps(enabled=True, flavor="oauth2", oauth2_pass_access_token="True"), + ["web-app-x", "oauth2_pass_access_token"], + ) + self.assertEqual(result, [True]) + + def test_pass_access_token_rejects_a_rendered_false_string(self): + result = self._run( + _apps(enabled=True, flavor="oauth2", oauth2_pass_access_token="False"), + ["web-app-x", "oauth2_pass_access_token"], + ) + self.assertEqual(result, [False]) + def test_is_proxy_gated_false_for_oidc(self): result = self._run( _apps(enabled=True, flavor="oidc"), ["web-app-x", "is_proxy_gated"] diff --git a/tests/unit/python/plugins/lookup/test_sso_logout_url.py b/tests/unit/python/plugins/lookup/test_sso_logout_url.py new file mode 100644 index 0000000000..30157e4662 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_sso_logout_url.py @@ -0,0 +1,51 @@ +import unittest +import unittest.mock as mock + +from ansible.errors import AnsibleError + +from .test_sso import _apps, _load_module + +KEYCLOAK_LOGOUT = "https://auth.example.org/realms/r/protocol/openid-connect/logout" +OIDC = {"CLIENT": {"LOGOUT_URL": KEYCLOAK_LOGOUT}} + + +class SsoLogoutUrlLookupTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.mod = _load_module("plugins/lookup/sso.py", "sso") + + def _run(self, applications, variables): + lk = self.mod.LookupModule() + lk._loader = mock.MagicMock() + lk._templar = mock.MagicMock(template=lambda value: value) + with mock.patch.object(self.mod, "lookup_loader") as loader_mock: + loader_mock.get.return_value = mock.MagicMock( + run=lambda *_a, **_k: [applications] + ) + return lk.run(["web-app-x", "logout_url"], variables=variables) + + def test_a_proxy_gated_app_signs_out_of_oauth2_proxy_first(self): + result = self._run(_apps(enabled=True, flavor="oauth2"), {"OIDC": OIDC}) + self.assertEqual( + result, + [ + "/oauth2/sign_out?rd=https%3A//auth.example.org/realms/r/protocol/openid-connect/logout" + ], + ) + + def test_an_oidc_native_app_logs_out_at_the_provider(self): + result = self._run(_apps(enabled=True, flavor="oidc"), {"OIDC": OIDC}) + self.assertEqual(result, [KEYCLOAK_LOGOUT]) + + def test_a_disabled_sso_keeps_the_provider_logout(self): + result = self._run(_apps(enabled=False, flavor="oauth2"), {"OIDC": OIDC}) + self.assertEqual(result, [KEYCLOAK_LOGOUT]) + + def test_a_context_without_oidc_is_refused(self): + with self.assertRaises(AnsibleError) as ctx: + self._run(_apps(enabled=True, flavor="oauth2"), {"applications": {}}) + self.assertIn("OIDC", str(ctx.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_sso_oidc_plugin.py b/tests/unit/python/plugins/lookup/test_sso_oidc_plugin.py index 8f6dc8c580..af94622a39 100644 --- a/tests/unit/python/plugins/lookup/test_sso_oidc_plugin.py +++ b/tests/unit/python/plugins/lookup/test_sso_oidc_plugin.py @@ -66,9 +66,28 @@ class OidcFlavorLookupTests(unittest.TestCase): self._patcher = mock.patch.object(self.mod, "lookup_loader") self._loader_mock = self._patcher.start() self._stub_payload = None - self._loader_mock.get.return_value = mock.MagicMock( - run=lambda *_a, **_k: [self._stub_payload] - ) + self._loader_mock.get.side_effect = self._stub_lookup + + def _stub_lookup(self, name, *_args, **_kwargs): + """Stand in for the lookups the plugin consumes. + + ``config`` resolves a dotted path against the payload the way + ``lookup('config', app, path, default)`` does with a default supplied; + anything else answers with the payload itself. + """ + if name == "config": + return mock.MagicMock( + run=lambda terms, **_kw: [self._stub_config(*terms)], + ) + return mock.MagicMock(run=lambda *_a, **_kw: [self._stub_payload]) + + def _stub_config(self, application_id, config_path, default=None): + node = (self._stub_payload or {}).get(application_id) + for part in str(config_path).split("."): + if not isinstance(node, dict) or part not in node: + return default + node = node[part] + return node def tearDown(self): self._patcher.stop() diff --git a/tests/unit/python/plugins/lookup/test_tor_ports.py b/tests/unit/python/plugins/lookup/test_tor_ports.py index 6efaa52539..67b7a5ad72 100644 --- a/tests/unit/python/plugins/lookup/test_tor_ports.py +++ b/tests/unit/python/plugins/lookup/test_tor_ports.py @@ -9,7 +9,7 @@ from ansible.errors import AnsibleError from plugins.lookup.tor_ports import ( LookupModule, collect_exposed_ports, - collect_public_ports, + collect_onion_ports, ) from utils.cache import _reset_cache_for_tests from utils.cache.yaml import dump_yaml_str @@ -33,7 +33,15 @@ class TestTorPortsLookup(unittest.TestCase): _write_services( self.roles_dir, "web-app-gitea", - {"gitea": {"ports": {"public": {"ssh": 2201}, "local": {"http": 8002}}}}, + { + "gitea": { + "ports": { + "public": {"ssh": 2201}, + "local": {"http": 8002}, + "onion": {"ssh": True}, + } + } + }, ) _write_services( self.roles_dir, @@ -68,40 +76,159 @@ class TestTorPortsLookup(unittest.TestCase): _reset_cache_for_tests() self._tmpdir.cleanup() - def test_collects_public_single_ints_sorted(self) -> None: - ports = collect_public_ports( - ["web-app-gitea", "svc-db-openldap"], self.roles_dir + @staticmethod + def _apps(**roles: dict) -> dict: + """The variant-merged applications view for the given roles. + + Every entity keeps its own ``ports``; the top-level ``tor:`` block of + ``meta/services.yml`` merges in as one more entity alongside them. + """ + return {role: {"services": dict(entities)} for role, entities in roles.items()} + + def test_only_named_categories_are_forwarded_sorted(self) -> None: + apps = self._apps( + **{ + "web-app-gitea": { + "gitea": { + "ports": {"public": {"ssh": 2201}, "onion": {"ssh": True}} + } + }, + "web-app-mailu": { + "mailu": { + "ports": { + "public": {"smtp": 25, "smtps": 465, "imap": 143}, + "onion": {"smtp": True}, + } + } + }, + } ) - self.assertEqual(ports, [636, 2201]) - def test_relay_ranges_excluded(self) -> None: - ports = collect_public_ports(["web-svc-coturn"], self.roles_dir) - self.assertEqual(ports, [3481, 5351]) + ports = collect_onion_ports(apps, ["web-app-gitea", "web-app-mailu"]) - def test_media_category_excluded(self) -> None: - _write_services( - self.roles_dir, - "web-app-jitsi", - {"jitsi": {"ports": {"public": {"media": 10000}, "local": {"http": 8084}}}}, + self.assertEqual(ports, [25, 2201]) + + def test_local_wins_over_public_for_the_same_category(self) -> None: + """``container_ports`` publishes the local port when the category has + one, so the forward must target that and not the public alias.""" + apps = self._apps( + **{ + "web-app-x": { + "x": { + "ports": { + "local": {"http": 8080}, + "public": {"http": 80}, + "onion": {"http": True}, + } + } + } + } ) - self.assertEqual(collect_public_ports(["web-app-jitsi"], self.roles_dir), []) - def test_roles_without_public_ports_yield_nothing(self) -> None: - self.assertEqual(collect_public_ports(["web-app-hugo"], self.roles_dir), []) + self.assertEqual(collect_onion_ports(apps, ["web-app-x"]), [8080]) - def test_tor_disabled_role_excluded(self) -> None: - _write_services( - self.roles_dir, - "web-app-optout", - { - "optout": {"ports": {"public": {"ssh": 2299}}}, - "tor": {"enabled": False}, - }, + def test_a_falsy_or_unrendered_flag_forwards_nothing(self) -> None: + """The input must be the rendered view: template text left in the flag + is not quietly read as enabled.""" + apps = self._apps( + **{ + "web-app-a": { + "a": {"ports": {"public": {"ssh": 22}, "onion": {"ssh": False}}} + }, + "web-app-b": { + "b": { + "ports": { + "public": {"ssh": 23}, + "onion": {"ssh": "{{ 'svc-net-tor' in group_names }}"}, + } + } + }, + } ) - self.assertEqual(collect_public_ports(["web-app-optout"], self.roles_dir), []) - def test_unknown_role_ignored(self) -> None: - self.assertEqual(collect_public_ports(["web-app-nope"], self.roles_dir), []) + self.assertEqual(collect_onion_ports(apps, ["web-app-a", "web-app-b"]), []) + + def test_udp_only_categories_are_never_forwarded(self) -> None: + apps = self._apps( + **{ + "web-svc-coturn": { + "coturn": { + "ports": { + "public": { + "media": 10000, + "stun_turn": 3481, + "stun_turn_tls": 5351, + "ssh": 2299, + "relay": {"start": 20000, "end": 39999}, + }, + "onion": { + "media": True, + "relay": True, + "stun_turn": True, + "stun_turn_tls": True, + "ssh": True, + }, + } + } + } + } + ) + + self.assertEqual(collect_onion_ports(apps, ["web-svc-coturn"]), [2299]) + + def test_a_category_with_no_declared_port_is_skipped(self) -> None: + apps = self._apps( + **{ + "web-app-x": { + "x": {"ports": {"public": {"ssh": 2201}, "onion": {"typo": True}}} + } + } + ) + + self.assertEqual(collect_onion_ports(apps, ["web-app-x"]), []) + + def test_a_role_without_an_onion_block_forwards_nothing(self) -> None: + apps = self._apps( + **{"web-app-hugo": {"hugo": {"ports": {"local": {"http": 8008}}}}} + ) + + self.assertEqual(collect_onion_ports(apps, ["web-app-hugo"]), []) + + def test_the_port_flag_is_the_gate_not_the_tor_flag(self) -> None: + """``services.tor.enabled`` is the dependency edge onto svc-net-tor, not + the port forward; ``ports.onion`` alone decides what gets a + HiddenServicePort.""" + apps = self._apps( + **{ + "web-app-gitea": { + "tor": {"enabled": False}, + "gitea": { + "ports": {"public": {"ssh": 2201}, "onion": {"ssh": True}} + }, + } + } + ) + + self.assertEqual(collect_onion_ports(apps, ["web-app-gitea"]), [2201]) + + def test_role_outside_the_deploy_is_ignored(self) -> None: + apps = self._apps( + **{ + "web-app-gitea": { + "gitea": { + "ports": {"public": {"ssh": 2201}, "onion": {"ssh": True}} + } + } + } + ) + + self.assertEqual(collect_onion_ports(apps, ["web-app-nope"]), []) + + def test_collect_onion_ports_ignores_non_mappings(self) -> None: + self.assertEqual(collect_onion_ports({}, ["a"]), []) + self.assertEqual(collect_onion_ports(None, ["a"]), []) + apps = {"a": {"services": {"s": {"ports": {"onion": True}}}}} + self.assertEqual(collect_onion_ports(apps, ["a"]), []) def test_collect_exposed_ports_gated_and_deployed(self) -> None: apps = { @@ -137,63 +264,6 @@ class TestTorPortsLookup(unittest.TestCase): ) self.assertEqual(ports, [389, 5432]) - def test_exposed_public_forwards_the_public_group(self) -> None: - """The active mail provider's protocol ports ride the node onion.""" - apps = { - "web-app-stalwart": { - "services": { - "stalwart": { - "exposed": "public", - "ports": { - "local": {"http": 8081}, - "public": {"smtp": 25, "smtps": 465, "imaps": 993}, - }, - } - } - } - } - self.assertEqual( - collect_exposed_ports(apps, ["web-app-stalwart"]), [25, 465, 993] - ) - - def test_exposed_public_does_not_leak_the_local_group(self) -> None: - """`public` replaces `local` โ€” the reverse-proxied http port stays off the onion port list.""" - apps = { - "a": { - "services": { - "s": { - "exposed": "public", - "ports": {"local": {"http": 8081}, "public": {"smtps": 465}}, - } - } - } - } - self.assertEqual(collect_exposed_ports(apps, ["a"]), [465]) - - def test_exposed_true_still_never_forwards_public_ports(self) -> None: - """openldap's ldaps 636 must stay a non-forward: nothing listens on it in the exposed variant.""" - apps = { - "svc-db-openldap": { - "services": { - "openldap": { - "exposed": True, - "ports": {"local": {"ldap": 389}, "public": {"ldaps": 636}}, - } - } - } - } - self.assertEqual(collect_exposed_ports(apps, ["svc-db-openldap"]), [389]) - - def test_exposed_unknown_string_forwards_nothing(self) -> None: - apps = { - "a": { - "services": { - "s": {"exposed": "everything", "ports": {"public": {"smtp": 25}}} - } - } - } - self.assertEqual(collect_exposed_ports(apps, ["a"]), []) - def test_collect_exposed_ports_ignores_non_mappings(self) -> None: self.assertEqual(collect_exposed_ports({}, ["a"]), []) self.assertEqual(collect_exposed_ports(None, ["a"]), []) @@ -208,6 +278,14 @@ class TestTorPortsLookup(unittest.TestCase): )[0] self.assertEqual(result, [{"onion_port": 2201, "target": "127.0.0.1:2201"}]) + def test_run_forwards_nothing_without_an_onion_opt_in(self) -> None: + result = self.lookup.run( + [], + variables={"group_names": ["svc-db-openldap", "web-svc-coturn"]}, + roles_dir=str(self.roles_dir), + )[0] + self.assertEqual(result, []) + def test_empty_group_names(self) -> None: result = self.lookup.run([], variables={}, roles_dir=str(self.roles_dir))[0] self.assertEqual(result, []) diff --git a/tests/unit/python/plugins/lookup/test_tor_socks_proxy.py b/tests/unit/python/plugins/lookup/test_tor_socks_proxy.py index 84f9d77e27..11ae7829e4 100644 --- a/tests/unit/python/plugins/lookup/test_tor_socks_proxy.py +++ b/tests/unit/python/plugins/lookup/test_tor_socks_proxy.py @@ -1,7 +1,7 @@ from __future__ import annotations import unittest -from unittest import mock +import unittest.mock as mock from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader diff --git a/tests/unit/python/plugins/lookup/test_users.py b/tests/unit/python/plugins/lookup/test_users.py index ad0f6b0bb6..19f83592c5 100644 --- a/tests/unit/python/plugins/lookup/test_users.py +++ b/tests/unit/python/plugins/lookup/test_users.py @@ -190,7 +190,7 @@ class TestUsersLookup(unittest.TestCase): result = self.lookup.run( ["sld"], - variables={"domain": "auth.infinito.example"}, + variables={"domain": "auth.infinito.test"}, roles_dir=str(self._tmp / "roles"), )[0] diff --git a/tests/unit/python/roles/agents/__init__.py b/tests/unit/python/roles/agents/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/agents/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/agents/test_mcp_tool_filter.py b/tests/unit/python/roles/agents/test_mcp_tool_filter.py new file mode 100644 index 0000000000..d4d8fa0149 --- /dev/null +++ b/tests/unit/python/roles/agents/test_mcp_tool_filter.py @@ -0,0 +1,171 @@ +"""The agent clients register only the tools their providers declare. + +Both upstreams default to registering every tool an MCP server happens to +serve. Hermes says so in ``tools/mcp_tool.py``: "Neither set -> register all +tools (backward-compatible default)". OpenClaw's ``toolFilter`` is absent +unless written. A provider that grows a mutating tool would therefore reach +both agents without anyone declaring it, so the rendered configuration has to +carry the allowlist rather than rely on the default. + +That holds for the empty allowlist too: a provider that declares none is the +case where the default is most dangerous, so the filter is rendered +unconditionally, the way ``web-app-n8n``'s client node pins ``include`` to +``selected`` whatever ``includeTools`` resolves to. +""" + +from __future__ import annotations + +import importlib.util +import json +import unittest + +import yaml +from jinja2 import Environment, FileSystemLoader + +from . import PROJECT_ROOT + +HERMES = PROJECT_ROOT / "roles/web-app-hermes/templates" +OPENCLAW = PROJECT_ROOT / "roles/web-app-openclaw/templates" +FILTERS = PROJECT_ROOT / "plugins/filter/mcp/authorization.py" + +SERVERS = [ + { + "id": "svc-db-qdrant", + "url": "http://qdrantmcp:8080/mcp", + "token": "q" * 40, + "auth": "bearer_token", + "owner": "mcp-svc-db-qdrant", + "tools": ["qdrant_list_collections", "qdrant_get_collection"], + "transport": "streamable-http", + }, + { + "id": "web-app-prometheus", + "url": "http://prometheusmcp:8080/mcp", + "token": "p" * 40, + "auth": "bearer_token", + "owner": "mcp-web-app-prometheus", + "tools": [], + "mutating": [], + "transport": "streamable-http", + }, + { + "id": "web-app-baserow", + "url": "http://baserow:8080/mcp", + "token": "b" * 40, + "auth": "bearer_token", + "owner": "mcp-web-app-baserow", + "tools": ["list_databases", "list_tables", "create_rows", "delete_rows"], + "mutating": ["create_rows", "delete_rows"], + "transport": "streamable-http", + }, +] + + +def _filters() -> dict: + spec = importlib.util.spec_from_file_location("mcp_authorization", FILTERS) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + filters = dict(module.FilterModule().filters()) + filters.update({"to_json": json.dumps, "bool": bool}) + return filters + + +def _yaml(text: str): + """Parse a rendered template. + + Args: + text: the rendered document. + + The project's YAML cache is keyed by path; this input never becomes a file. + """ + return yaml.safe_load(text) # nocheck: direct-yaml a render, not a file + + +def _render(directory, name, **context) -> str: + env = Environment(loader=FileSystemLoader(str(directory)), autoescape=False) # noqa: S701 - renders configuration, not markup + env.filters.update(_filters()) + return env.get_template(name).render(**context) + + +class TestAgentToolFilter(unittest.TestCase): + def test_hermes_pins_the_declared_allowlist(self) -> None: + rendered = _yaml(_render(HERMES, "config.yaml.j2", HERMES_MCP_SERVERS=SERVERS)) + entry = rendered["mcp_servers"]["svc_db_qdrant"] + self.assertEqual( + ["qdrant_list_collections", "qdrant_get_collection"], + entry["tools"]["include"], + ) + + def test_hermes_pins_an_empty_allowlist_rather_than_omitting_it(self) -> None: + rendered = _yaml(_render(HERMES, "config.yaml.j2", HERMES_MCP_SERVERS=SERVERS)) + entry = rendered["mcp_servers"]["web_app_prometheus"] + self.assertEqual( + [], + entry["tools"]["include"], + "omitting the key means 'register all tools' upstream, so a " + "provider that declares no allowlist would reach the agent with " + "every tool it happens to serve", + ) + + def test_openclaw_pins_the_declared_allowlist(self) -> None: + rendered = json.loads( + _render( + OPENCLAW, + "openclaw.json.j2", + OPENCLAW_URL="https://claw.example.org", + OPENCLAW_LITELLM_ENABLED=False, + OPENCLAW_MCP_SERVERS=SERVERS, + ) + ) + entry = rendered["mcp"]["servers"]["svc-db-qdrant"] + self.assertEqual( + ["qdrant_list_collections", "qdrant_get_collection"], + entry["toolFilter"]["include"], + ) + + def test_openclaw_stays_valid_json_with_an_empty_filter(self) -> None: + rendered = json.loads( + _render( + OPENCLAW, + "openclaw.json.j2", + OPENCLAW_URL="https://claw.example.org", + OPENCLAW_LITELLM_ENABLED=False, + OPENCLAW_MCP_SERVERS=SERVERS, + ) + ) + self.assertEqual( + [], + rendered["mcp"]["servers"]["web-app-prometheus"]["toolFilter"]["include"], + ) + self.assertEqual( + {"svc-db-qdrant", "web-app-prometheus", "web-app-baserow"}, + set(rendered["mcp"]["servers"]), + ) + + def test_hermes_never_offers_a_tool_the_provider_calls_mutating(self) -> None: + rendered = _yaml(_render(HERMES, "config.yaml.j2", HERMES_MCP_SERVERS=SERVERS)) + include = rendered["mcp_servers"]["web_app_baserow"]["tools"]["include"] + self.assertEqual(["list_databases", "list_tables"], include) + + def test_openclaw_never_offers_a_tool_the_provider_calls_mutating(self) -> None: + rendered = json.loads( + _render( + OPENCLAW, + "openclaw.json.j2", + OPENCLAW_URL="https://claw.example.org", + OPENCLAW_LITELLM_ENABLED=False, + OPENCLAW_MCP_SERVERS=SERVERS, + ) + ) + entry = rendered["mcp"]["servers"]["web-app-baserow"] + self.assertEqual( + ["list_databases", "list_tables"], entry["toolFilter"]["include"] + ) + + def test_neither_agent_inlines_a_bearer_for_a_bearer_provider(self) -> None: + hermes = _render(HERMES, "config.yaml.j2", HERMES_MCP_SERVERS=SERVERS) + self.assertNotIn("q" * 40, hermes) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/agents/test_openclaw_model_provider.py b/tests/unit/python/roles/agents/test_openclaw_model_provider.py new file mode 100644 index 0000000000..d7939d8710 --- /dev/null +++ b/tests/unit/python/roles/agents/test_openclaw_model_provider.py @@ -0,0 +1,93 @@ +"""OpenClaw refuses to boot on a model entry that misses a key. + +The gateway validates its whole configuration before it serves anything, and +a rejected file is not a degraded start but a crash loop: OpenClaw retries, +trips its own restart breaker after four unclean boots, and the container +exits 128 while the deploy sits in the health check until it gives up. + +The provider block reached the repository without ever being rendered in a +test - every case here passed OPENCLAW_LITELLM_ENABLED=False, so the block was +skipped and its shape was never checked against anything. +""" + +from __future__ import annotations + +import importlib.util +import json +import unittest + +from jinja2 import Environment, FileSystemLoader + +from . import PROJECT_ROOT + +OPENCLAW = PROJECT_ROOT / "roles/web-app-openclaw/templates" +FILTERS = PROJECT_ROOT / "plugins/filter/mcp/authorization.py" + +MODEL = "qwen2.5:0.5b" + +CONTEXT = { + "OPENCLAW_URL": "https://claw.example.org", + "OPENCLAW_LITELLM_ENABLED": True, + "OPENCLAW_LITELLM_PROVIDER": "litellm", + "OPENCLAW_LITELLM_MODEL": MODEL, + "OPENCLAW_LITELLM_BASE_URL": "http://litellm:4000/v1", + "OPENCLAW_LITELLM_API_KEY": "sk-" + "x" * 20, + "OPENCLAW_MCP_SERVERS": [], +} + + +def _filters() -> dict: + spec = importlib.util.spec_from_file_location("mcp_authorization", FILTERS) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + filters = dict(module.FilterModule().filters()) + filters.update({"to_json": json.dumps, "bool": bool}) + return filters + + +def _render(**overrides) -> dict: + """Return the gateway config as OpenClaw would parse it. + + Args: + overrides: context values replacing the defaults. + """ + env = Environment(loader=FileSystemLoader(str(OPENCLAW)), autoescape=False) # noqa: S701 - renders configuration, not markup + env.filters.update(_filters()) + return json.loads( + env.get_template("openclaw.json.j2").render(**{**CONTEXT, **overrides}) + ) + + +class TestOpenClawModelProvider(unittest.TestCase): + def _entry(self, **overrides) -> dict: + """Return the provider's single model entry. + + Args: + overrides: context values replacing the defaults. + """ + return _render(**overrides)["models"]["providers"]["litellm"]["models"][0] + + def test_the_model_entry_carries_both_keys_the_gateway_validates(self) -> None: + self.assertEqual({"id": MODEL, "name": MODEL}, self._entry()) + + def test_the_name_matches_the_id(self) -> None: + """Which key reaches the API is the upstream's choice, not ours.""" + entry = self._entry() + self.assertEqual(entry["id"], entry["name"]) + + def test_the_primary_agent_model_names_the_same_provider(self) -> None: + rendered = _render() + self.assertEqual( + f"litellm/{MODEL}", + rendered["agents"]["defaults"]["model"]["primary"], + ) + self.assertIn("litellm", rendered["models"]["providers"]) + + def test_the_block_disappears_when_litellm_is_off(self) -> None: + rendered = _render(OPENCLAW_LITELLM_ENABLED=False) + self.assertNotIn("models", rendered) + self.assertNotIn("agents", rendered) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-ai-litellm/__init__.py b/tests/unit/python/roles/svc-ai-litellm/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/svc-ai-litellm/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/svc-ai-litellm/files/__init__.py b/tests/unit/python/roles/svc-ai-litellm/files/__init__.py new file mode 100644 index 0000000000..9f69c70b47 --- /dev/null +++ b/tests/unit/python/roles/svc-ai-litellm/files/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] diff --git a/tests/unit/python/roles/svc-ai-litellm/files/test_ensure_keys.py b/tests/unit/python/roles/svc-ai-litellm/files/test_ensure_keys.py new file mode 100644 index 0000000000..98d9d6440c --- /dev/null +++ b/tests/unit/python/roles/svc-ai-litellm/files/test_ensure_keys.py @@ -0,0 +1,152 @@ +from __future__ import annotations + +import importlib.util +import io +import json +import unittest +import urllib.error +from contextlib import redirect_stdout +from typing import ClassVar +from unittest.mock import patch + +from . import PROJECT_ROOT + +SCRIPT_PATH = PROJECT_ROOT / "roles/svc-ai-litellm/files/python/ensure_keys.py" + + +def load_script() -> object: + spec = importlib.util.spec_from_file_location("ensure_keys", SCRIPT_PATH) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +MODULE = load_script() + + +def http_error(code: int) -> urllib.error.HTTPError: + return urllib.error.HTTPError("/", code, "", None, None) + + +class RecordingProxy: + """A `call` answering from a declared key state, recording what it was asked.""" + + def __init__(self, known_keys: set[str], held_aliases: set[str]) -> None: + self.known_keys = known_keys + self.held_aliases = held_aliases + self.paths: list[str] = [] + + def __call__(self, method: str, path: str, body: dict | None = None): + self.paths.append(path) + if path.startswith("/key/info"): + if path.split("=", 1)[1] not in self.known_keys: + raise http_error(404) + return + if path == "/key/delete": + if not set(body["key_aliases"]) & self.held_aliases: + raise http_error(404) + self.held_aliases -= set(body["key_aliases"]) + return + if body["key_alias"] in self.held_aliases: + raise http_error(400) + self.held_aliases.add(body["key_alias"]) + return + + +class TestEnsureKey(unittest.TestCase): + ENTRY: ClassVar[dict[str, str]] = {"alias": "web-app-flowise", "key": "sk-new"} + REPLACED: ClassVar[list[str]] = [ + "/key/info?key=sk-new", + "/key/delete", + "/key/generate", + ] + + def test_registered_key_is_left_alone(self): + proxy = RecordingProxy({"sk-new"}, {"web-app-flowise"}) + self.assertFalse(MODULE.ensure_key(self.ENTRY, proxy)) + self.assertEqual(proxy.paths, ["/key/info?key=sk-new"]) + + def test_held_alias_is_released_before_the_key_is_created(self): + proxy = RecordingProxy(set(), {"web-app-flowise"}) + self.assertTrue(MODULE.ensure_key(self.ENTRY, proxy)) + self.assertEqual(proxy.paths, self.REPLACED) + + def test_free_alias_survives_the_delete_that_finds_nothing(self): + proxy = RecordingProxy(set(), set()) + self.assertTrue(MODULE.ensure_key(self.ENTRY, proxy)) + self.assertEqual(proxy.paths, self.REPLACED) + + def test_a_failing_creation_is_not_swallowed(self): + def call(method, path, body=None): + raise http_error(500 if path == "/key/generate" else 404) + + with self.assertRaises(urllib.error.HTTPError) as raised: + MODULE.ensure_key(self.ENTRY, call) + self.assertEqual(raised.exception.code, 500) + + +class TestHttpCall(unittest.TestCase): + def _capture(self, method: str, path: str, body: dict | None): + captured: dict = {} + + def urlopen(request, timeout): + captured["url"] = request.full_url + captured["method"] = request.get_method() + captured["data"] = request.data + captured["timeout"] = timeout + + call = MODULE.http_call("http://localhost:4000", {"X-Test": "1"}) + with patch.object(MODULE.urllib.request, "urlopen", urlopen): + call(method, path, body) + return captured + + def test_a_body_is_sent_as_json_on_the_declared_method(self): + captured = self._capture("POST", "/key/delete", {"key_aliases": ["a"]}) + self.assertEqual(captured["url"], "http://localhost:4000/key/delete") + self.assertEqual(captured["method"], "POST") + self.assertEqual(json.loads(captured["data"]), {"key_aliases": ["a"]}) + self.assertEqual(captured["timeout"], MODULE.TIMEOUT) + + def test_a_bodyless_request_carries_no_payload(self): + captured = self._capture("GET", "/key/info?key=x", None) + self.assertEqual(captured["method"], "GET") + self.assertIsNone(captured["data"]) + + +class TestMain(unittest.TestCase): + ENV: ClassVar[dict[str, str]] = { + "LITELLM_PORT": "4000", + "LITELLM_MK": "sk-master", + "LITELLM_KEYS_PAYLOAD": json.dumps( + [ + {"alias": "web-app-flowise", "key": "sk-new"}, + {"alias": "web-app-hermes", "key": "sk-known"}, + ] + ), + } + + def test_only_the_created_key_is_announced_as_changed(self): + proxy = RecordingProxy({"sk-known"}, {"web-app-flowise"}) + buffer = io.StringIO() + with ( + patch.dict("os.environ", self.ENV, clear=True), + patch.object(MODULE, "http_call", return_value=proxy), + redirect_stdout(buffer), + ): + MODULE.main() + self.assertEqual(buffer.getvalue(), "CHANGED web-app-flowise\n") + + def test_the_master_key_reaches_the_proxy_as_a_bearer_header(self): + with ( + patch.dict("os.environ", self.ENV, clear=True), + patch.object(MODULE, "http_call") as http_call, + ): + http_call.return_value = RecordingProxy({"sk-new", "sk-known"}, set()) + MODULE.main() + base, headers = http_call.call_args[0] + self.assertEqual(base, "http://localhost:4000") + self.assertEqual(headers["Authorization"], "Bearer sk-master") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-ai-litellm/files/test_probe_auth.py b/tests/unit/python/roles/svc-ai-litellm/files/test_probe_auth.py new file mode 100644 index 0000000000..f06e157187 --- /dev/null +++ b/tests/unit/python/roles/svc-ai-litellm/files/test_probe_auth.py @@ -0,0 +1,133 @@ +from __future__ import annotations + +import importlib.util +import unittest +import urllib.error +from typing import ClassVar + +from . import PROJECT_ROOT + +SCRIPT_PATH = PROJECT_ROOT / "roles/svc-ai-litellm/files/python/probe_auth.py" + + +def load_script() -> object: + spec = importlib.util.spec_from_file_location("probe_auth", SCRIPT_PATH) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +MODULE = load_script() + +CONSUMER_KEY = "sk-consumer" +MINTED_KEY = "sk-minted" + + +class FakeGateway: + """A gateway answering from a declared key state. + + Args: + accepted: keys the gateway answers 200 for. + anonymous_status: status an unauthenticated caller receives. + revocation_lag: how many status reads a deleted key keeps answering 200. + """ + + def __init__( + self, + accepted: set[str], + anonymous_status: int = 401, + revocation_lag: int = 0, + ) -> None: + self.accepted = set(accepted) + self.anonymous_status = anonymous_status + self.revocation_lag = revocation_lag + self.aliases: dict[str, str] = {} + self.stale_reads: dict[str, int] = {} + self.slept: list[int] = [] + + def _revoke(self, key: str) -> None: + self.accepted.discard(key) + self.stale_reads[key] = self.revocation_lag + + def status(self, key: str | None) -> int: + if key is None: + return self.anonymous_status + if key in self.accepted: + return 200 + if self.stale_reads.get(key, 0) > 0: + self.stale_reads[key] -= 1 + return 200 + return 401 + + def call(self, method: str, path: str, body: dict | None = None): + if path == "/key/delete": + for key in body.get("keys", []): + self._revoke(key) + for alias in body.get("key_aliases", []): + if alias not in self.aliases: + raise urllib.error.HTTPError("/", 404, "", None, None) + self._revoke(self.aliases.pop(alias)) + return {} + self.aliases[body["key_alias"]] = MINTED_KEY + self.accepted.add(MINTED_KEY) + return {"key": MINTED_KEY} + + def sleep(self, seconds: int) -> None: + self.slept.append(seconds) + + +def run(gateway: FakeGateway) -> None: + MODULE.probe(gateway.status, gateway.call, CONSUMER_KEY, gateway.sleep) + + +class TestProbeAuth(unittest.TestCase): + ACCEPTED: ClassVar[set[str]] = {CONSUMER_KEY} + + def test_a_closed_and_isolated_gateway_passes(self) -> None: + run(FakeGateway(self.ACCEPTED)) + + def test_an_open_gateway_is_rejected(self) -> None: + with self.assertRaises(MODULE.ProbeError) as caught: + run(FakeGateway(self.ACCEPTED, anonymous_status=200)) + self.assertIn("without a key", str(caught.exception)) + + def test_a_gateway_honouring_a_forged_token_is_rejected(self) -> None: + forged = "sk-" + "0" * 32 + with self.assertRaises(MODULE.ProbeError) as caught: + run(FakeGateway({CONSUMER_KEY, forged})) + self.assertIn("forged bearer token", str(caught.exception)) + + def test_a_revocation_that_never_takes_effect_is_rejected(self) -> None: + gateway = FakeGateway(self.ACCEPTED, revocation_lag=99) + with self.assertRaises(MODULE.ProbeError) as caught: + run(gateway) + self.assertIn("revocation does not take effect", str(caught.exception)) + self.assertEqual(MODULE.REVOCATION_ATTEMPTS, len(gateway.slept)) + + def test_a_lagging_revocation_is_awaited_rather_than_failed(self) -> None: + gateway = FakeGateway(self.ACCEPTED, revocation_lag=2) + run(gateway) + self.assertEqual([MODULE.REVOCATION_DELAY] * 2, gateway.slept) + + def test_a_revocation_that_takes_a_consumer_down_is_rejected(self) -> None: + class Collateral(FakeGateway): + def call(self, method: str, path: str, body: dict | None = None): + result = super().call(method, path, body) + if path == "/key/delete" and body.get("keys"): + self.accepted.discard(CONSUMER_KEY) + return result + + with self.assertRaises(MODULE.ProbeError) as caught: + run(Collateral(self.ACCEPTED)) + self.assertIn("not isolated", str(caught.exception)) + + def test_a_stale_probe_alias_is_cleared_before_minting(self) -> None: + gateway = FakeGateway(self.ACCEPTED) + gateway.aliases[MODULE.PROBE_ALIAS] = "sk-stale" + gateway.accepted.add("sk-stale") + run(gateway) + self.assertNotIn("sk-stale", gateway.accepted) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-ai-litellm/files/test_probe_routing.py b/tests/unit/python/roles/svc-ai-litellm/files/test_probe_routing.py new file mode 100644 index 0000000000..b2073361b1 --- /dev/null +++ b/tests/unit/python/roles/svc-ai-litellm/files/test_probe_routing.py @@ -0,0 +1,216 @@ +"""Unit tests for the svc-ai-litellm routing probe's verdict logic.""" + +from __future__ import annotations + +import importlib.util +import unittest + +from . import PROJECT_ROOT + +MODULE_PATH = PROJECT_ROOT / "roles/svc-ai-litellm/files/test/probe.py" + +spec = importlib.util.spec_from_file_location("litellm_probe", MODULE_PATH) +probe = importlib.util.module_from_spec(spec) +spec.loader.exec_module(probe) + +ALIAS = "qwen2.5:0.5b" +LMSTUDIO_ONLY = "mistral:latest" + + +def verdict(**overrides) -> list[str]: + kwargs = { + "served": set(), + "expected": [], + "chat_model": "", + "chat_model_served": False, + "ollama_enabled": False, + "lmstudio_enabled": False, + "lmstudio_aliases": [LMSTUDIO_ONLY], + "remote_aliases": [], + } + kwargs.update(overrides) + return probe.evaluate(**kwargs) + + +class TestOllamaOnlyDeployment(unittest.TestCase): + """svc-ai-ollama deployed, svc-ai-lmstudio not โ€” variant 0.""" + + def test_a_consistent_gateway_passes(self) -> None: + self.assertEqual( + verdict( + served={ALIAS}, + expected=[ALIAS], + chat_model=ALIAS, + chat_model_served=True, + ollama_enabled=True, + ), + [], + ) + + def test_an_lmstudio_alias_without_its_backend_fails(self) -> None: + failures = verdict( + served={ALIAS, LMSTUDIO_ONLY}, + expected=[ALIAS], + chat_model=ALIAS, + chat_model_served=True, + ollama_enabled=True, + ) + self.assertEqual(len(failures), 1) + self.assertIn("svc-ai-lmstudio is not deployed", failures[0]) + + def test_a_declared_model_the_gateway_dropped_fails(self) -> None: + failures = verdict( + served=set(), + expected=[ALIAS], + chat_model=ALIAS, + chat_model_served=True, + ollama_enabled=True, + ) + self.assertTrue( + any("does not serve" in failure for failure in failures), failures + ) + + def test_the_model_consumers_ask_for_must_be_routable(self) -> None: + failures = verdict( + served={ALIAS}, + expected=[ALIAS], + chat_model="llama3:latest", + chat_model_served=True, + ollama_enabled=True, + ) + self.assertEqual(len(failures), 1) + self.assertIn("llama3:latest", failures[0]) + + +class TestLmstudioOnlyDeployment(unittest.TestCase): + """svc-ai-lmstudio deployed, svc-ai-ollama not โ€” variant 2.""" + + def test_the_same_alias_ollama_would_serve_passes(self) -> None: + self.assertEqual( + verdict( + served={ALIAS}, + expected=[ALIAS], + chat_model=ALIAS, + chat_model_served=True, + lmstudio_enabled=True, + lmstudio_aliases=[ALIAS], + ), + [], + ) + + def test_a_declared_alias_the_gateway_never_routed_fails(self) -> None: + failures = verdict( + served=set(), + expected=[ALIAS], + chat_model=ALIAS, + chat_model_served=True, + lmstudio_enabled=True, + lmstudio_aliases=[ALIAS], + ) + self.assertTrue( + any("declared and not routed" in failure for failure in failures), failures + ) + + def test_an_ollama_model_without_its_backend_fails(self) -> None: + failures = verdict( + served={ALIAS, "llama3:latest"}, + expected=[ALIAS], + chat_model=ALIAS, + chat_model_served=True, + lmstudio_enabled=True, + lmstudio_aliases=[ALIAS], + ) + self.assertTrue( + any("svc-ai-ollama is not deployed" in failure for failure in failures), + failures, + ) + + +class TestBothBackendsDeployment(unittest.TestCase): + """Variant 0 plus lmstudio: a shared alias proves nothing about lmstudio.""" + + def test_only_the_exclusive_alias_is_demanded(self) -> None: + self.assertEqual( + verdict( + served={ALIAS, LMSTUDIO_ONLY}, + expected=[ALIAS, LMSTUDIO_ONLY], + chat_model=ALIAS, + chat_model_served=True, + ollama_enabled=True, + lmstudio_enabled=True, + ), + [], + ) + + def test_a_missing_exclusive_alias_still_fails(self) -> None: + failures = verdict( + served={ALIAS}, + expected=[ALIAS], + chat_model=ALIAS, + chat_model_served=True, + ollama_enabled=True, + lmstudio_enabled=True, + ) + self.assertTrue( + any("declared and not routed" in failure for failure in failures), failures + ) + + +class TestRemoteProviders(unittest.TestCase): + """A configured provider key publishes its alias and serves the gateway.""" + + def test_a_keyed_provider_is_the_only_backend_needed(self) -> None: + self.assertEqual( + verdict( + served={"openai/gpt-4o-mini"}, + expected=["openai/gpt-4o-mini"], + chat_model="openai/gpt-4o-mini", + chat_model_served=True, + remote_aliases=["openai/gpt-4o-mini"], + ), + [], + ) + + def test_a_remote_alias_is_not_mistaken_for_an_ollama_model(self) -> None: + self.assertEqual( + verdict( + served={"anthropic/claude-sonnet-4-5", ALIAS}, + expected=["anthropic/claude-sonnet-4-5", ALIAS], + chat_model=ALIAS, + chat_model_served=True, + lmstudio_enabled=True, + lmstudio_aliases=[ALIAS], + remote_aliases=["anthropic/claude-sonnet-4-5"], + ), + [], + ) + + def test_a_declared_provider_the_gateway_dropped_fails(self) -> None: + failures = verdict( + served=set(), + expected=["openrouter/auto"], + chat_model="openrouter/auto", + chat_model_served=True, + remote_aliases=["openrouter/auto"], + ) + self.assertTrue( + any("does not serve" in failure for failure in failures), failures + ) + + +class TestNoBackendDeployment(unittest.TestCase): + def test_an_empty_gateway_passes(self) -> None: + self.assertEqual(verdict(), []) + + def test_any_published_model_fails(self) -> None: + failures = verdict(served={"openrouter/auto"}) + self.assertTrue( + any("no backend is deployed" in failure for failure in failures), failures + ) + + def test_the_chat_model_is_not_demanded_when_nothing_serves_it(self) -> None: + self.assertEqual(verdict(chat_model=ALIAS), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-ai-litellm/files/test_warm_model.py b/tests/unit/python/roles/svc-ai-litellm/files/test_warm_model.py new file mode 100644 index 0000000000..94ae49d7ad --- /dev/null +++ b/tests/unit/python/roles/svc-ai-litellm/files/test_warm_model.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +import importlib.util +import io +import json +import unittest +from contextlib import redirect_stdout +from typing import Self +from unittest.mock import patch + +from . import PROJECT_ROOT + +SCRIPT_PATH = PROJECT_ROOT / "roles/svc-ai-litellm/files/python/warm_model.py" + +ENVIRONMENT = { + "LITELLM_MK": "sk-master-key", + "LITELLM_PORT": "4000", + "LITELLM_MODEL": "smollm2:135m", +} + + +class FakeResponse: + def __enter__(self) -> Self: + return self + + def __exit__(self, *exc_info: object) -> bool: + return False + + def read(self) -> bytes: + return b'{"choices": []}' + + +def run_script() -> None: + spec = importlib.util.spec_from_file_location("warm_model", SCRIPT_PATH) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + + +class TestWarmModel(unittest.TestCase): + def test_posts_a_minimal_completion_to_the_local_gateway(self) -> None: + seen: dict[str, object] = {} + + def fake_urlopen(request: object, timeout: float | None = None) -> FakeResponse: + seen["url"] = request.full_url + seen["method"] = request.get_method() + seen["headers"] = {k.lower(): v for k, v in request.header_items()} + seen["body"] = json.loads(request.data.decode()) + seen["timeout"] = timeout + return FakeResponse() + + with ( + patch.dict("os.environ", ENVIRONMENT, clear=False), + patch("urllib.request.urlopen", fake_urlopen), + redirect_stdout(io.StringIO()) as captured, + ): + run_script() + + self.assertEqual(seen["url"], "http://127.0.0.1:4000/v1/chat/completions") + self.assertEqual(seen["method"], "POST") + self.assertEqual(seen["headers"]["authorization"], "Bearer sk-master-key") + self.assertEqual(seen["headers"]["content-type"], "application/json") + self.assertEqual(seen["body"]["model"], "smollm2:135m") + self.assertEqual(seen["body"]["max_tokens"], 1) + self.assertIn("WARMED smollm2:135m", captured.getvalue()) + + def test_waits_far_longer_than_a_proxy_read_timeout(self) -> None: + seen: dict[str, object] = {} + + def fake_urlopen(request: object, timeout: float | None = None) -> FakeResponse: + seen["timeout"] = timeout + return FakeResponse() + + with ( + patch.dict("os.environ", ENVIRONMENT, clear=False), + patch("urllib.request.urlopen", fake_urlopen), + redirect_stdout(io.StringIO()), + ): + run_script() + + self.assertGreater(seen["timeout"], 60) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-ai-litellm/templates/__init__.py b/tests/unit/python/roles/svc-ai-litellm/templates/__init__.py new file mode 100644 index 0000000000..9f69c70b47 --- /dev/null +++ b/tests/unit/python/roles/svc-ai-litellm/templates/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] diff --git a/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py b/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py new file mode 100644 index 0000000000..e1728d0e72 --- /dev/null +++ b/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py @@ -0,0 +1,169 @@ +"""The gateway config publishes one alias per model, whichever backend serves it. + +``config.yaml.j2`` is where the two local backends meet: Ollama pulls a model +under the alias and LM Studio under its own hub name, and both must surface to +consumers as the same ``model_name``. A wrong accessor or a missing de-duplicate +condition does not fail the render, it publishes a route nothing answers, so the +template is rendered here rather than read. +""" + +from __future__ import annotations + +import unittest + +import yaml +from jinja2 import Environment, StrictUndefined + +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +TEMPLATE = PROJECT_ROOT / "roles/svc-ai-litellm/templates/config.yaml.j2" + +SHARED = {"alias": "qwen2.5:0.5b", "name": "qwen2.5-0.5b-instruct"} +OLLAMA_ONLY = {"alias": "llama3:latest", "name": "llama-3.2-3b-instruct"} +LMSTUDIO_ONLY = {"alias": "mistral:latest", "name": "mistral-7b-instruct-v0.3"} + +OLLAMA_URL = "http://ollama:11434" +LMSTUDIO_URL = "http://lmstudio:1234" + + +def _ansible_bool(value): + if isinstance(value, str): + return value.strip().lower() in ("true", "yes", "on", "1") + return bool(value) + + +def _stub_lookup(ollama_models, lmstudio_models): + def lookup(kind, role, path, *args): + if (kind, path) == ("config", "services.ollama.preload_models"): + return ollama_models + if (kind, path) == ("config", "services.lmstudio.preload_models"): + return lmstudio_models + raise AssertionError(f"unexpected lookup({kind!r}, {role!r}, {path!r})") + + return lookup + + +REMOTE_BACKENDS = ( + ("openai/gpt-4o-mini", "openai/gpt-4o-mini", "OPENAI_API_KEY"), + ("anthropic/claude-sonnet-4-5", "anthropic/claude-sonnet-4-5", "ANTHROPIC_API_KEY"), + ("openrouter/auto", "openrouter/openrouter/auto", "OPENROUTER_API_KEY"), +) + + +def _remote(keys): + """The LITELLM_REMOTE_BACKENDS list vars/main.yml builds, with these keys. + + Args: + keys: env-name -> key value; a provider absent from it stays unkeyed. + """ + return [ + {"alias": alias, "model": model, "env": env, "key": keys.get(env, "")} + for alias, model, env in REMOTE_BACKENDS + ] + + +def render(*, ollama=(), lmstudio=(), keys=None): + """The rendered config as a parsed mapping. + + Args: + ollama: preload entries svc-ai-ollama declares; empty means not deployed. + lmstudio: preload entries svc-ai-lmstudio declares; empty means not deployed. + keys: env-name -> provider key for the remote backends. + """ + env = Environment(undefined=StrictUndefined, autoescape=False) # noqa: S701 - YAML, not markup + env.filters["bool"] = _ansible_bool + rendered = env.from_string(read_text(str(TEMPLATE))).render( + LITELLM_OLLAMA_BACKEND=str(bool(ollama)), + LITELLM_LMSTUDIO_BACKEND=str(bool(lmstudio)), + lookup=_stub_lookup(list(ollama), list(lmstudio)), + OLLAMA_BASE_LOCAL_URL=OLLAMA_URL, + LMSTUDIO_BASE_LOCAL_URL=LMSTUDIO_URL, + LITELLM_MAX_OUTPUT_TOKENS=512, + LITELLM_UPSTREAM_TIMEOUT=60, + LITELLM_REMOTE_BACKENDS=_remote(keys or {}), + ) + return yaml.safe_load( + rendered + ) # nocheck: direct-yaml - parses this test's own render + + +def routes(config) -> dict: + return { + entry["model_name"]: entry["litellm_params"] + for entry in (config.get("model_list") or []) + } + + +class TestOllamaOnly(unittest.TestCase): + def test_every_alias_is_published_against_the_ollama_backend(self) -> None: + published = routes(render(ollama=[SHARED, OLLAMA_ONLY])) + self.assertEqual(set(published), {SHARED["alias"], OLLAMA_ONLY["alias"]}) + self.assertEqual( + published[SHARED["alias"]]["model"], f"ollama/{SHARED['alias']}" + ) + self.assertEqual(published[SHARED["alias"]]["api_base"], OLLAMA_URL) + + +class TestLmstudioOnly(unittest.TestCase): + def test_the_alias_is_published_against_the_lmstudio_name(self) -> None: + published = routes(render(lmstudio=[SHARED, LMSTUDIO_ONLY])) + self.assertEqual(set(published), {SHARED["alias"], LMSTUDIO_ONLY["alias"]}) + self.assertEqual( + published[SHARED["alias"]]["model"], f"openai/{SHARED['name']}" + ) + self.assertEqual(published[SHARED["alias"]]["api_base"], f"{LMSTUDIO_URL}/v1") + + def test_an_alias_reaches_the_same_name_ollama_would_publish(self) -> None: + self.assertEqual( + set(routes(render(lmstudio=[SHARED]))), + set(routes(render(ollama=[SHARED]))), + ) + + +class TestBothBackends(unittest.TestCase): + def test_a_shared_alias_is_published_once_and_routed_to_ollama(self) -> None: + published = routes( + render(ollama=[SHARED, OLLAMA_ONLY], lmstudio=[SHARED, LMSTUDIO_ONLY]) + ) + self.assertEqual( + set(published), + {SHARED["alias"], OLLAMA_ONLY["alias"], LMSTUDIO_ONLY["alias"]}, + ) + self.assertEqual(published[SHARED["alias"]]["api_base"], OLLAMA_URL) + self.assertEqual( + published[LMSTUDIO_ONLY["alias"]]["api_base"], f"{LMSTUDIO_URL}/v1" + ) + + +class TestNoBackend(unittest.TestCase): + def test_the_model_list_is_empty(self) -> None: + self.assertEqual(render()["model_list"], []) + + def test_one_provider_key_alone_publishes_its_route(self) -> None: + published = routes(render(keys={"OPENROUTER_API_KEY": "sk-or-test"})) + self.assertEqual(set(published), {"openrouter/auto"}) + self.assertEqual( + published["openrouter/auto"]["api_key"], "os.environ/OPENROUTER_API_KEY" + ) + + def test_each_keyed_provider_gets_its_own_route(self) -> None: + published = routes( + render( + keys={ + "OPENAI_API_KEY": "sk-test", + "ANTHROPIC_API_KEY": "sk-ant-test", + } + ) + ) + self.assertEqual( + set(published), {"openai/gpt-4o-mini", "anthropic/claude-sonnet-4-5"} + ) + + def test_an_unkeyed_provider_publishes_nothing(self) -> None: + self.assertEqual(render(keys={"OPENAI_API_KEY": ""})["model_list"], []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/__init__.py b/tests/unit/python/roles/svc-ai-mcp-adapter/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/__init__.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/__init__.py new file mode 100644 index 0000000000..9f69c70b47 --- /dev/null +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_passthrough.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_passthrough.py new file mode 100644 index 0000000000..2e7a682899 --- /dev/null +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_passthrough.py @@ -0,0 +1,167 @@ +"""Unit tests for the adapter's policy layer over an MCP-speaking upstream.""" + +from __future__ import annotations + +import importlib.util +import json +import sys +import unittest +from typing import ClassVar + +from . import PROJECT_ROOT + +FILES_DIR = PROJECT_ROOT / "roles/svc-ai-mcp-adapter/files/python" +MODULE_PATH = FILES_DIR / "passthrough.py" + +LIMITS: dict[str, int] = { + "request_bytes": 64, + "response_bytes": 1048576, + "timeout_seconds": 15, + "concurrent_requests": 4, + "page_size": 100, + "result_items": 5, + "stream_seconds": 300, +} + + +def load(): + """Import the passthrough layer the way the image lays it out. + + It imports ``policy`` as a sibling, so its own directory has to be + importable before the module body runs. + """ + spec = importlib.util.spec_from_file_location("adapter_passthrough", MODULE_PATH) + module = importlib.util.module_from_spec(spec) + sys.path.insert(0, str(FILES_DIR)) + try: + spec.loader.exec_module(module) + finally: + sys.path.remove(str(FILES_DIR)) + return module + + +passthrough = load() +sys.path.insert(0, str(FILES_DIR)) +import policy # noqa: E402 sibling module, importable only via FILES_DIR + +sys.path.remove(str(FILES_DIR)) + + +def contract(tools, *, mutating=False, kind="mcp"): + body = { + "upstream_kind": kind, + "provider": "web-app-example", + "upstream_url": "http://example:8065/mcp", + "tools": tools, + "limits": LIMITS, + "mutating_tools_enabled": mutating, + } + body["schema_sha256"] = policy.schema_digest(tools) + return body + + +READ_TOOLS: dict[str, dict] = { + "read_post": {"mutating": False}, + "search_users": {"mutating": False}, +} + + +class TestContractKind(unittest.TestCase): + def test_an_undeclared_kind_is_refused(self) -> None: + with self.assertRaises(policy.ContractError): + passthrough.contract_kind({"provider": "x"}) + + def test_a_rest_contract_is_not_loaded_as_mcp(self) -> None: + raw = json.dumps(contract(READ_TOOLS, kind="rest")) + with self.assertRaises(policy.ContractError): + passthrough.load_mcp_contract(raw) + + +class TestRouting(unittest.TestCase): + def test_a_contract_without_the_key_routes_to_rest(self) -> None: + legacy = {"provider": "x", "tools": {"a": {"method": "GET", "path": "/a"}}} + self.assertFalse(passthrough.declares_mcp_upstream(json.dumps(legacy))) + + def test_an_mcp_contract_routes_to_passthrough(self) -> None: + self.assertTrue( + passthrough.declares_mcp_upstream(json.dumps(contract(READ_TOOLS))) + ) + + def test_unparseable_input_routes_to_rest_rather_than_raising(self) -> None: + self.assertFalse(passthrough.declares_mcp_upstream("{not json")) + + +class TestContractLoading(unittest.TestCase): + def test_a_read_only_contract_loads(self) -> None: + loaded = passthrough.load_mcp_contract(json.dumps(contract(READ_TOOLS))) + self.assertEqual(sorted(loaded["tools"]), ["read_post", "search_users"]) + + def test_a_tool_without_a_mutating_flag_is_refused(self) -> None: + raw = json.dumps(contract({"read_post": {}})) + with self.assertRaises(policy.ContractError): + passthrough.load_mcp_contract(raw) + + def test_a_mutating_tool_is_refused_while_mutations_are_off(self) -> None: + raw = json.dumps(contract({"delete_post": {"mutating": True}})) + with self.assertRaises(policy.ContractError): + passthrough.load_mcp_contract(raw) + + def test_a_mutating_tool_loads_once_mutations_are_enabled(self) -> None: + raw = json.dumps(contract({"delete_post": {"mutating": True}}, mutating=True)) + self.assertIn("delete_post", passthrough.load_mcp_contract(raw)["tools"]) + + +class TestCallAuthorization(unittest.TestCase): + CONTRACT: ClassVar[dict] = contract(READ_TOOLS) + + def test_a_listed_tool_is_forwarded_by_name(self) -> None: + self.assertEqual( + passthrough.authorize_mcp_call(self.CONTRACT, "read_post", {}), "read_post" + ) + + def test_an_unlisted_tool_is_refused_even_though_upstream_serves_it(self) -> None: + with self.assertRaises(PermissionError) as caught: + passthrough.authorize_mcp_call(self.CONTRACT, "delete_post", {}) + self.assertIn(policy.DENY_UNKNOWN_TOOL, str(caught.exception)) + + def test_an_oversized_argument_payload_is_refused(self) -> None: + with self.assertRaises(PermissionError) as caught: + passthrough.authorize_mcp_call(self.CONTRACT, "read_post", {"q": "x" * 200}) + self.assertIn(policy.DENY_REQUEST_TOO_LARGE, str(caught.exception)) + + def test_a_mutating_tool_is_refused_at_call_time_when_disabled(self) -> None: + loaded = contract({"delete_post": {"mutating": True}}, mutating=True) + loaded["mutating_tools_enabled"] = False + with self.assertRaises(PermissionError) as caught: + passthrough.authorize_mcp_call(loaded, "delete_post", {}) + self.assertIn(policy.DENY_MUTATION, str(caught.exception)) + + +class TestUpstreamSurface(unittest.TestCase): + CONTRACT: ClassVar[dict] = contract(READ_TOOLS) + SERVED: ClassVar[list] = [ + {"name": "read_post"}, + {"name": "search_users"}, + {"name": "delete_post"}, + {"name": "archive_channel"}, + ] + + def test_only_contracted_tools_are_advertised(self) -> None: + kept = passthrough.filter_upstream_tools(self.CONTRACT, self.SERVED) + self.assertEqual([t["name"] for t in kept], ["read_post", "search_users"]) + + def test_upstream_growth_is_reported_not_silently_filtered(self) -> None: + self.assertEqual( + passthrough.undeclared_upstream_tools(self.CONTRACT, self.SERVED), + ["archive_channel", "delete_post"], + ) + + def test_a_contract_tool_the_upstream_dropped_is_reported(self) -> None: + self.assertEqual( + passthrough.missing_upstream_tools(self.CONTRACT, [{"name": "read_post"}]), + ["search_users"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py new file mode 100644 index 0000000000..376ac03ab3 --- /dev/null +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py @@ -0,0 +1,405 @@ +"""Unit tests for the reusable MCP adapter's policy layer.""" + +from __future__ import annotations + +import importlib.util +import json +import unittest + +from . import PROJECT_ROOT + +MODULE_PATH = PROJECT_ROOT / "roles/svc-ai-mcp-adapter/files/python/policy.py" + +spec = importlib.util.spec_from_file_location("adapter_policy", MODULE_PATH) +policy = importlib.util.module_from_spec(spec) +spec.loader.exec_module(policy) + +TOOLS = { + "checkmk_list_hosts": { + "method": "GET", + "path": "/domain-types/host_config/collections/all", + }, + "checkmk_get_host_status": { + "method": "GET", + "path": "/objects/host/{host}", + "input_schema": { + "type": "object", + "properties": {"host": {"type": "string"}, "columns": {"type": "string"}}, + "required": ["host"], + }, + }, +} + +LIMITS = { + "request_bytes": 64, + "response_bytes": 1048576, + "timeout_seconds": 15, + "concurrent_requests": 4, + "page_size": 100, + "result_items": 5, + "stream_seconds": 300, +} + + +def contract(**overrides): + base = { + "provider": "web-app-checkmk", + "upstream_url": "http://checkmk:5000", + "auth_subject": "service_account", + "tools": TOOLS, + "limits": LIMITS, + "schema_sha256": policy.schema_digest(TOOLS), + } + base.update(overrides) + return base + + +class TestLoadContract(unittest.TestCase): + def test_a_complete_contract_loads(self): + loaded = policy.load_contract(json.dumps(contract())) + self.assertEqual("web-app-checkmk", loaded["provider"]) + + def test_non_json_is_refused(self): + with self.assertRaises(policy.ContractError): + policy.load_contract("not json") + + def test_a_missing_limit_is_refused_at_startup(self): + broken = contract( + limits={k: v for k, v in LIMITS.items() if k != "timeout_seconds"} + ) + with self.assertRaises(policy.ContractError): + policy.load_contract(json.dumps(broken)) + + def test_a_non_positive_limit_is_refused(self): + with self.assertRaises(policy.ContractError): + policy.load_contract( + json.dumps(contract(limits={**LIMITS, "page_size": 0})) + ) + + def test_an_empty_allowlist_is_refused(self): + with self.assertRaises(policy.ContractError): + policy.load_contract(json.dumps(contract(tools={}))) + + def test_a_wildcard_path_is_refused(self): + wild = {"anything": {"method": "GET", "path": "/objects/*"}} + broken = contract(tools=wild, schema_sha256=policy.schema_digest(wild)) + with self.assertRaises(policy.ContractError): + policy.load_contract(json.dumps(broken)) + + def test_an_unpinned_schema_is_refused(self): + with self.assertRaises(policy.ContractError): + policy.load_contract(json.dumps(contract(schema_sha256=""))) + + def test_a_declared_write_tool_is_refused_while_mutations_are_off(self): + tools = {"x_translate": {"method": "POST", "path": "/translate"}} + broken = contract(tools=tools, schema_sha256=policy.schema_digest(tools)) + with self.assertRaises(policy.ContractError) as error: + policy.load_contract(json.dumps(broken)) + self.assertIn("mutations are off", str(error.exception)) + + def test_a_declared_write_tool_loads_once_mutations_are_enabled(self): + tools = {"x_translate": {"method": "POST", "path": "/translate"}} + allowed = contract( + tools=tools, + schema_sha256=policy.schema_digest(tools), + mutating_tools_enabled=True, + ) + self.assertEqual( + "x_translate", + next(iter(policy.load_contract(json.dumps(allowed))["tools"])), + ) + + +class TestDrift(unittest.TestCase): + def test_a_matching_hash_passes(self): + policy.assert_no_drift(contract()) + + def test_an_added_tool_fails_closed(self): + drifted = dict(contract()) + drifted["tools"] = { + **TOOLS, + "checkmk_delete_host": {"method": "DELETE", "path": "/x"}, + } + with self.assertRaises(policy.ContractError) as error: + policy.assert_no_drift(drifted) + self.assertIn(policy.DENY_SCHEMA_DRIFT, str(error.exception)) + + +class TestAuthorizeClient(unittest.TestCase): + def test_the_issued_bearer_is_accepted(self): + policy.authorize_client("s3cret", "Bearer s3cret") + + def test_a_wrong_bearer_is_refused(self): + with self.assertRaises(PermissionError): + policy.authorize_client("s3cret", "Bearer other") + + def test_a_missing_header_is_refused(self): + with self.assertRaises(PermissionError): + policy.authorize_client("s3cret", "") + + def test_an_unset_bearer_refuses_everyone(self): + with self.assertRaises(PermissionError): + policy.authorize_client("", "Bearer anything") + + +class TestAuthorizeCall(unittest.TestCase): + def test_a_listed_read_tool_resolves_to_its_upstream_operation(self): + method, path = policy.authorize_call(contract(), "checkmk_list_hosts", {}) + self.assertEqual("GET", method) + self.assertEqual("/domain-types/host_config/collections/all", path) + + def test_an_unlisted_tool_is_refused_by_name(self): + with self.assertRaises(PermissionError) as error: + policy.authorize_call(contract(), "checkmk_delete_host", {}) + self.assertIn(policy.DENY_UNKNOWN_TOOL, str(error.exception)) + + def test_a_mutating_tool_is_refused_while_mutations_stay_off(self): + tools = {"checkmk_activate": {"method": "POST", "path": "/activate"}} + with self.assertRaises(PermissionError) as error: + policy.authorize_call(contract(tools=tools), "checkmk_activate", {}) + self.assertIn(policy.DENY_MUTATION, str(error.exception)) + + def test_a_mutating_tool_passes_once_explicitly_enabled(self): + tools = {"checkmk_activate": {"method": "POST", "path": "/activate"}} + method, _ = policy.authorize_call( + contract(tools=tools, mutating_tools_enabled=True), "checkmk_activate", {} + ) + self.assertEqual("POST", method) + + def test_an_oversized_argument_payload_is_refused(self): + with self.assertRaises(PermissionError) as error: + policy.authorize_call(contract(), "checkmk_list_hosts", {"f": "x" * 200}) + self.assertIn(policy.DENY_REQUEST_TOO_LARGE, str(error.exception)) + + +class TestLimits(unittest.TestCase): + def test_listed_tools_are_exactly_the_allowlist(self): + self.assertEqual(sorted(TOOLS), policy.listed_tools(contract())) + + def test_a_page_size_above_the_ceiling_is_clamped(self): + self.assertEqual(100, policy.clamp_page(contract(), 5000)) + + def test_a_missing_page_size_falls_back_to_the_ceiling(self): + self.assertEqual(100, policy.clamp_page(contract(), None)) + + def test_a_page_size_below_one_is_raised_to_one(self): + self.assertEqual(1, policy.clamp_page(contract(), 0)) + + def test_results_are_truncated_to_the_contract_ceiling(self): + self.assertEqual(5, len(policy.truncate_results(contract(), list(range(50))))) + + +class TestDeclaredArguments(unittest.TestCase): + """A published input schema is enforced, not merely advertised. + + On the openapi path an argument the contract does not name is appended to + the upstream request as a query parameter, so an unchecked schema lets a + client add parameters the reviewed operation never granted. + """ + + def test_a_declared_argument_passes(self): + method, path = policy.authorize_call( + contract(), "checkmk_get_host_status", {"host": "web-01"} + ) + self.assertEqual(("GET", "/objects/host/{host}"), (method, path)) + + def test_an_optional_declared_argument_passes(self): + policy.authorize_call( + contract(), + "checkmk_get_host_status", + {"host": "web-01", "columns": "state"}, + ) + + def test_an_undeclared_argument_is_refused(self): + with self.assertRaises(PermissionError) as caught: + policy.authorize_call( + contract(), + "checkmk_get_host_status", + {"host": "web-01", "site": "other"}, + ) + self.assertIn(policy.DENY_UNKNOWN_ARGUMENT, str(caught.exception)) + + def test_a_missing_required_argument_is_refused(self): + with self.assertRaises(PermissionError) as caught: + policy.authorize_call(contract(), "checkmk_get_host_status", {}) + self.assertIn(policy.DENY_MISSING_ARGUMENT, str(caught.exception)) + + def test_a_tool_declaring_no_schema_takes_no_arguments(self): + with self.assertRaises(PermissionError) as caught: + policy.authorize_call(contract(), "checkmk_list_hosts", {"limit": 5000}) + self.assertIn(policy.DENY_UNKNOWN_ARGUMENT, str(caught.exception)) + + def test_a_tool_declaring_no_schema_still_serves_a_bare_call(self): + method, _path = policy.authorize_call(contract(), "checkmk_list_hosts", {}) + self.assertEqual("GET", method) + + +RANGE_TOOLS = { + "prometheus_query_range": { + "method": "GET", + "path": "/api/v1/query_range", + "input_schema": { + "type": "object", + "properties": { + "query": {"type": "string"}, + "start": {"type": "string"}, + "end": {"type": "string"}, + "step": {"type": "string"}, + }, + "required": ["query", "start", "end", "step"], + }, + } +} + + +class TestRangeCeiling(unittest.TestCase): + """A client picks start, end and step, so nothing bounded the point count. + + The timeout bounds how long the upstream burns, not how much it scans, and + the adapter discards all but `result_items` rows regardless. + """ + + def contract(self, **overrides): + return contract( + tools=RANGE_TOOLS, + schema_sha256=policy.schema_digest(RANGE_TOOLS), + limits={**LIMITS, "request_bytes": 4096}, + **overrides, + ) + + def call(self, **arguments): + return policy.authorize_call( + self.contract(), "prometheus_query_range", {"query": "up", **arguments} + ) + + def test_a_range_inside_the_ceiling_passes(self): + method, path = self.call(start="0", end="4", step="1s") + self.assertEqual(("GET", "/api/v1/query_range"), (method, path)) + + def test_a_range_above_the_ceiling_is_refused(self): + with self.assertRaises(PermissionError) as caught: + self.call(start="0", end="86400", step="1s") + self.assertIn(policy.DENY_RANGE_TOO_WIDE, str(caught.exception)) + + def test_the_refusal_names_a_step_that_would_fit(self): + with self.assertRaises(PermissionError) as caught: + self.call(start="0", end="86400", step="1s") + self.assertIn("a step of at least 21600s fits", str(caught.exception)) + + def test_rfc3339_boundaries_are_understood(self): + with self.assertRaises(PermissionError) as caught: + self.call( + start="2026-01-01T00:00:00+00:00", + end="2026-01-02T00:00:00+00:00", + step="1m", + ) + self.assertIn(policy.DENY_RANGE_TOO_WIDE, str(caught.exception)) + + def test_a_compound_duration_is_understood(self): + self.call(start="0", end="5400", step="1h30m") + + def test_an_unparseable_boundary_is_refused_rather_than_waved_through(self): + with self.assertRaises(PermissionError) as caught: + self.call(start="yesterday", end="now", step="1s") + self.assertIn(policy.DENY_RANGE_TOO_WIDE, str(caught.exception)) + + def test_a_zero_step_is_refused_instead_of_dividing_by_zero(self): + with self.assertRaises(PermissionError) as caught: + self.call(start="0", end="10", step="0s") + self.assertIn("step must be positive", str(caught.exception)) + + def test_a_tool_without_the_three_range_arguments_is_untouched(self): + policy.authorize_call(contract(), "checkmk_list_hosts", {}) + + +class TestDurationGrammar(unittest.TestCase): + def test_bare_seconds_parse(self): + self.assertEqual(30.0, policy.parse_duration("30")) + + def test_each_unit_parses(self): + self.assertEqual(0.001, policy.parse_duration("1ms")) + self.assertEqual(604800, policy.parse_duration("1w")) + self.assertEqual(31536000, policy.parse_duration("1y")) + + def test_a_trailing_unit_of_its_own_is_refused(self): + """`1h30` is not a Prometheus duration; accepting it would guess.""" + with self.assertRaises(ValueError): + policy.parse_duration("1h30") + + +class TestAudit(unittest.TestCase): + def test_the_event_names_both_sides_and_the_outcome(self): + event = policy.audit_event( + contract(), "web-app-openwebui", "checkmk_list_hosts", "ok", 12, "cid-1" + ) + self.assertEqual("web-app-checkmk", event["provider"]) + self.assertEqual("web-app-openwebui", event["consumer"]) + self.assertEqual("ok", event["status"]) + self.assertEqual("cid-1", event["correlation_id"]) + + def test_the_event_carries_neither_arguments_nor_payload(self): + event = policy.audit_event( + contract(), "web-app-openwebui", "checkmk_list_hosts", "ok", 12, "cid-1" + ) + self.assertEqual( + { + "provider", + "consumer", + "tool", + "subject", + "status", + "duration_ms", + "correlation_id", + }, + set(event), + ) + + +class TestUpstreamUrl(unittest.TestCase): + """A provider that keys its endpoint by URL segment instead of by header. + + The secret must not reach the contract the sidecar advertises, so it + arrives as its own environment variable and is spliced in here. + """ + + BASE = "http://baserow:80/mcp" + + def test_without_a_path_key_the_url_is_returned_untouched(self) -> None: + self.assertEqual(policy.upstream_url(self.BASE), self.BASE) + + def test_a_trailing_slash_survives_when_nothing_is_appended(self) -> None: + self.assertEqual(policy.upstream_url(self.BASE + "/"), self.BASE + "/") + + def test_a_path_key_is_appended_as_its_own_segment(self) -> None: + self.assertEqual( + policy.upstream_url(self.BASE, "abc123"), + "http://baserow:80/mcp/abc123", + ) + + def test_a_suffix_follows_the_key(self) -> None: + self.assertEqual( + policy.upstream_url(self.BASE, "abc123", "sse"), + "http://baserow:80/mcp/abc123/sse", + ) + + def test_a_suffix_without_a_key_still_lands(self) -> None: + self.assertEqual( + policy.upstream_url(self.BASE, "", "sse"), + "http://baserow:80/mcp/sse", + ) + + def test_a_trailing_slash_does_not_double_up(self) -> None: + self.assertEqual( + policy.upstream_url(self.BASE + "/", "abc123", "/sse/"), + "http://baserow:80/mcp/abc123/sse", + ) + + def test_a_key_carrying_url_syntax_is_escaped(self) -> None: + self.assertEqual( + policy.upstream_url(self.BASE, "a/b?c=d"), + "http://baserow:80/mcp/a%2Fb%3Fc%3Dd", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_server.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_server.py new file mode 100644 index 0000000000..f91d0d311e --- /dev/null +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_server.py @@ -0,0 +1,257 @@ +"""Unit tests for the adapter's JSON-RPC request handling.""" + +from __future__ import annotations + +import importlib.util +import json +import sys +import unittest +from unittest.mock import patch + +from . import PROJECT_ROOT + +FILES_DIR = PROJECT_ROOT / "roles/svc-ai-mcp-adapter/files/python" +MODULE_PATH = FILES_DIR / "server.py" + +TOOLS = { + "example_list": {"method": "GET", "path": "/api/things"}, + "example_get": {"method": "GET", "path": "/api/things/{id}"}, +} + +LIMITS = { + "request_bytes": 64, + "response_bytes": 1048576, + "timeout_seconds": 15, + "concurrent_requests": 4, + "page_size": 100, + "result_items": 5, + "stream_seconds": 300, +} + + +def load(): + """Import the adapter server the way the image lays it out. + + ``server.py`` imports ``policy`` as a sibling, so its own directory has to + be importable before the module body runs. + """ + spec = importlib.util.spec_from_file_location("adapter_server", MODULE_PATH) + module = importlib.util.module_from_spec(spec) + sys.path.insert(0, str(FILES_DIR)) + try: + import policy + + contract = { + "provider": "web-app-example", + "upstream_url": "http://example:80", + "auth_subject": "service_account", + "tools": TOOLS, + "limits": LIMITS, + "schema_sha256": policy.schema_digest(TOOLS), + } + env = {"ADAPTER_CONTRACT": json.dumps(contract), "ADAPTER_BEARER": "real"} + with patch.dict("os.environ", env, clear=False): + spec.loader.exec_module(module) + finally: + sys.path.remove(str(FILES_DIR)) + return module + + +class Recorder: + """Capture what the handler wrote, without opening a socket.""" + + def __init__(self): + self.status = None + self.headers = {} + self.body = b"" + + def send_response(self, status): + self.status = status + + def send_header(self, name, value): + self.headers[name] = value + + def end_headers(self): + return None + + +class TestNotificationHandling(unittest.TestCase): + def setUp(self): + self.module = load() + + def _handle(self, request): + handler = self.module.Handler.__new__(self.module.Handler) + recorder = Recorder() + handler.send_response = recorder.send_response + handler.send_header = recorder.send_header + handler.end_headers = recorder.end_headers + handler.wfile = type("W", (), {"write": lambda _self, data: None})() + handler.headers = {} + handler.path = self.module.ENDPOINT + payload = json.dumps(request).encode() + handler.rfile = type("R", (), {"read": lambda _self, _n: payload})() + handler.headers = { + "Content-Length": str(len(payload)), + "Authorization": "Bearer real", + } + handler.do_POST() + return recorder + + def test_a_notification_is_accepted_without_a_body(self): + recorder = self._handle( + {"jsonrpc": "2.0", "method": "notifications/initialized"} + ) + self.assertEqual(recorder.status, 202) + self.assertEqual(recorder.headers.get("Content-Length"), "0") + + def test_an_unknown_method_with_an_id_still_errors(self): + recorder = self._handle({"jsonrpc": "2.0", "id": 1, "method": "nope"}) + self.assertEqual(recorder.status, 400) + + +class FakeResponse: + """Stands in for what the opener returns.""" + + def __init__(self, body=b"{}"): + self._body = body + + def read(self, _limit=None): + return self._body + + def __enter__(self): + return self + + def __exit__(self, *_args): + return False + + +class TestFixedTarget(unittest.TestCase): + """No client input may move the request off the contracted upstream.""" + + def setUp(self): + self.module = load() + + def _opened(self, tool, arguments): + seen = {} + + def fake_open(request, timeout=None): + seen["url"] = request.full_url + return FakeResponse() + + spec = self.module.CONTRACT["tools"][tool] + with patch.object(self.module.OPENER, "open", fake_open): + self.module.call_upstream(spec["method"], spec["path"], arguments) + return seen["url"] + + def test_the_request_stays_on_the_contracted_origin(self): + url = self._opened("example_get", {"id": "7"}) + self.assertEqual("http://example:80/api/things/7", url) + + def test_an_argument_naming_another_host_cannot_move_the_request(self): + url = self._opened("example_get", {"id": "http://evil.example/steal"}) + self.assertTrue( + url.startswith("http://example:80/api/things/"), + f"a client argument reached outside the contracted origin: {url}", + ) + self.assertNotIn("evil.example/steal", url) + + def test_a_path_argument_cannot_escape_its_segment(self): + url = self._opened("example_get", {"id": "../../admin"}) + self.assertEqual("http://example:80/api/things/..%2F..%2Fadmin", url) + + def test_an_uncontracted_argument_lands_in_the_query_not_the_path(self): + url = self._opened("example_get", {"id": "7", "extra": "/etc/passwd"}) + self.assertTrue(url.startswith("http://example:80/api/things/7?"), url) + self.assertIn("extra=%2Fetc%2Fpasswd", url) + + def test_an_upstream_redirect_is_refused_rather_than_followed(self): + handler = self.module.NoRedirect() + self.assertIsNone( + handler.redirect_request( + None, None, 302, "Found", {}, "http://evil.example/" + ), + "urllib copies the request headers onto the redirect target, so " + "following one would hand the upstream credential to whoever the " + "upstream named", + ) + + +class TestConcurrencyCeiling(unittest.TestCase): + """The declared ``concurrent_requests`` is refused past, not just declared. + + ``ThreadingHTTPServer`` starts a thread per connection and consults no + contract, so before the handler refused the surplus itself the limit was + validated at load time and then never applied. + """ + + def setUp(self): + self.module = load() + + def _handle(self, request, result=None, error=None): + handler = self.module.Handler.__new__(self.module.Handler) + recorder = Recorder() + handler.send_response = recorder.send_response + handler.send_header = recorder.send_header + handler.end_headers = recorder.end_headers + written = [] + handler.wfile = type( + "W", (), {"write": lambda _s, data: written.append(data)} + )() + handler.path = self.module.ENDPOINT + payload = json.dumps(request).encode() + handler.rfile = type("R", (), {"read": lambda _s, _n: payload})() + handler.headers = { + "Content-Length": str(len(payload)), + "Authorization": "Bearer real", + } + + def _dispatch(*_args): + if error is not None: + raise error + return result + + with patch.object(self.module, "dispatch", _dispatch): + handler.do_POST() + recorder.body = b"".join(written) + return recorder + + def test_a_request_within_the_ceiling_is_served(self): + recorder = self._handle({"jsonrpc": "2.0", "id": 1, "method": "x"}, result={}) + self.assertEqual(200, recorder.status) + + def test_the_surplus_request_is_refused_not_queued(self): + for _ in range(LIMITS["concurrent_requests"]): + self.module.IN_FLIGHT.acquire() + recorder = self._handle({"jsonrpc": "2.0", "id": 1, "method": "x"}, result={}) + self.assertEqual(503, recorder.status) + self.assertIn("too_many_concurrent_requests", recorder.body.decode()) + + def test_a_served_request_gives_its_slot_back(self): + for _ in range(LIMITS["concurrent_requests"]): + self._handle({"jsonrpc": "2.0", "id": 1, "method": "x"}, result={}) + recorder = self._handle({"jsonrpc": "2.0", "id": 1, "method": "x"}, result={}) + self.assertEqual( + 200, + recorder.status, + "a slot held past the response would let the ceiling shrink to zero " + "over the adapter's lifetime", + ) + + def test_a_failed_request_gives_its_slot_back(self): + for _ in range(LIMITS["concurrent_requests"]): + self._handle( + {"jsonrpc": "2.0", "id": 1, "method": "x"}, + error=RuntimeError("upstream down"), + ) + recorder = self._handle({"jsonrpc": "2.0", "id": 1, "method": "x"}, result={}) + self.assertEqual(200, recorder.status) + + def test_a_notification_takes_no_slot(self): + for _ in range(LIMITS["concurrent_requests"] * 2): + self._handle({"jsonrpc": "2.0", "method": "notifications/initialized"}) + recorder = self._handle({"jsonrpc": "2.0", "id": 1, "method": "x"}, result={}) + self.assertEqual(200, recorder.status) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_server_passthrough.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_server_passthrough.py new file mode 100644 index 0000000000..c6a1ef259c --- /dev/null +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_server_passthrough.py @@ -0,0 +1,303 @@ +"""The adapter's behaviour when the upstream it fronts already speaks MCP.""" + +from __future__ import annotations + +import importlib.util +import io +import json +import sys +import unittest +from typing import ClassVar +from unittest.mock import patch + +from . import PROJECT_ROOT + +FILES_DIR = PROJECT_ROOT / "roles/svc-ai-mcp-adapter/files/python" +MODULE_PATH = FILES_DIR / "server.py" + +TOOLS: dict[str, dict] = { + "read_post": { + "mutating": False, + "input_schema": { + "type": "object", + "properties": {"id": {"type": "string"}}, + "required": ["id"], + }, + }, + "search_users": {"mutating": False}, +} + +LIMITS: dict[str, int] = { + "request_bytes": 4096, + "response_bytes": 1048576, + "timeout_seconds": 15, + "concurrent_requests": 4, + "page_size": 100, + "result_items": 5, + "stream_seconds": 300, +} + + +def load(tools=None, *, mutating=False, transport=None): + """Import the adapter server against an MCP-kind contract.""" + spec = importlib.util.spec_from_file_location("adapter_server_mcp", MODULE_PATH) + module = importlib.util.module_from_spec(spec) + sys.path.insert(0, str(FILES_DIR)) + try: + import policy + + payload = tools if tools is not None else TOOLS + contract = { + "upstream_kind": "mcp", + "provider": "web-app-example", + "upstream_url": "http://example:8065/plugins/x/mcp", + "auth_subject": "service_account", + "tools": payload, + "limits": LIMITS, + "mutating_tools_enabled": mutating, + "schema_sha256": policy.schema_digest(payload), + } + if transport is not None: + contract["upstream_transport"] = transport + env = {"ADAPTER_CONTRACT": json.dumps(contract), "ADAPTER_BEARER": "real"} + with patch.dict("os.environ", env, clear=False): + spec.loader.exec_module(module) + finally: + sys.path.remove(str(FILES_DIR)) + return module + + +class FakeResponse(io.BytesIO): + """Stands in for the object urlopen returns, headers included.""" + + def __init__(self, body: bytes, content_type: str, status: int): + super().__init__(body) + self.headers = {"Content-Type": content_type, "Mcp-Session-Id": "sess-1"} + self.status = status + + def __enter__(self): + return self + + def __exit__(self, *_exc): + return False + + +class TestPassthroughDispatch(unittest.TestCase): + MODULE: ClassVar = load() + + def test_the_contract_selects_the_mcp_transport(self) -> None: + self.assertTrue(self.MODULE.UPSTREAM_IS_MCP) + + def test_only_contracted_tools_are_advertised(self) -> None: + listed = self.MODULE.dispatch({"method": "tools/list"}, "consumer", "cid") + self.assertEqual( + sorted(tool["name"] for tool in listed["tools"]), + ["read_post", "search_users"], + ) + + def test_a_call_is_forwarded_as_jsonrpc_by_name(self) -> None: + seen = {"methods": [], "sessions": []} + + def fake_urlopen(request, timeout=None): + seen["url"] = request.full_url + body = json.loads(request.data.decode()) + seen["methods"].append(body.get("method")) + seen["sessions"].append(request.get_header("Mcp-session-id")) + seen["body"] = body + return FakeResponse( + json.dumps( + {"jsonrpc": "2.0", "id": "1", "result": {"ok": True}} + ).encode(), + content_type="application/json", + status=200, + ) + + with patch.object(self.MODULE.OPENER, "open", fake_urlopen): + self.MODULE.dispatch( + { + "method": "tools/call", + "params": {"name": "read_post", "arguments": {"id": "7"}}, + }, + "consumer", + "cid", + ) + + self.assertEqual(seen["url"], "http://example:8065/plugins/x/mcp") + self.assertEqual( + seen["methods"], ["initialize", "notifications/initialized", "tools/call"] + ) + self.assertEqual(seen["sessions"][-1], "sess-1") + self.assertEqual(seen["body"]["method"], "tools/call") + self.assertEqual(seen["body"]["params"]["name"], "read_post") + self.assertEqual(seen["body"]["params"]["arguments"], {"id": "7"}) + + def test_an_unlisted_tool_never_reaches_the_upstream(self) -> None: + def fail_if_called(*_args, **_kwargs): + raise AssertionError("the upstream must not be contacted") + + with ( + patch.object(self.MODULE.OPENER, "open", fail_if_called), + self.assertRaises(PermissionError), + ): + self.MODULE.dispatch( + {"method": "tools/call", "params": {"name": "delete_post"}}, + "consumer", + "cid", + ) + + def test_an_upstream_error_object_carries_the_real_status(self) -> None: + calls = {"n": 0} + + def fake_urlopen(request, timeout=None): + calls["n"] += 1 + body = json.loads(request.data.decode()) + if body.get("method") != "tools/call": + return FakeResponse( + json.dumps({"jsonrpc": "2.0", "id": "1", "result": {}}).encode(), + content_type="application/json", + status=200, + ) + return FakeResponse( + json.dumps( + { + "jsonrpc": "2.0", + "id": "1", + "error": {"code": -32000, "message": "nope"}, + } + ).encode(), + content_type="application/json", + status=200, + ) + + with ( + patch.object(self.MODULE.OPENER, "open", fake_urlopen), + self.assertRaises(ValueError) as caught, + ): + self.MODULE.dispatch( + { + "method": "tools/call", + "params": {"name": "read_post", "arguments": {"id": "7"}}, + }, + "consumer", + "cid", + ) + self.assertEqual(self.MODULE.upstream_status(caught.exception), 200) + + +class TestEventStreamDecoding(unittest.TestCase): + MODULE: ClassVar = load() + + def test_a_single_sse_frame_is_unwrapped(self) -> None: + body = b'event: message\ndata: {"jsonrpc":"2.0","id":"1","result":{"ok":1}}\n\n' + parsed = self.MODULE.passthrough.decode_jsonrpc(body, "text/event-stream") + self.assertEqual(parsed["result"], {"ok": 1}) + + def test_a_stream_without_a_data_frame_is_an_error(self) -> None: + with self.assertRaises(ValueError): + self.MODULE.passthrough.decode_jsonrpc( + b"event: ping\n\n", "text/event-stream" + ) + + def test_a_plain_json_body_is_parsed_directly(self) -> None: + parsed = self.MODULE.passthrough.decode_jsonrpc( + b'{"result": 2}', "application/json" + ) + self.assertEqual(parsed["result"], 2) + + +class FakeSseSession: + """Stands in for an open SSE session, recording what was driven through it.""" + + def __init__(self, *_args, **kwargs): + self.headers = kwargs.get("headers") or {} + self.calls = [] + self.notifications = [] + self.opened = 0 + + def open(self): + self.opened += 1 + return self + + def call(self, method, params=None, request_id=1): + self.calls.append((method, params, request_id)) + return {"jsonrpc": "2.0", "id": request_id, "result": {"served": True}} + + def notify(self, method, params=None): + self.notifications.append((method, params)) + + +class TestSseUpstream(unittest.TestCase): + """A contract may name the classic HTTP+SSE transport instead of POST.""" + + def _sse_module(self): + module = load(transport="sse") + made = [] + + def factory(*args, **kwargs): + session = FakeSseSession(*args, **kwargs) + made.append(session) + return session + + return module, made, factory + + def test_the_default_transport_stays_streamable_http(self) -> None: + module = load() + self.assertEqual("streamable_http", module.UPSTREAM_TRANSPORT) + + def test_a_declared_sse_upstream_is_driven_over_a_stream(self) -> None: + module, made, factory = self._sse_module() + + def refuse(*_args, **_kwargs): + raise AssertionError("an SSE upstream must not be reached by POST") + + with ( + patch.object(module.sse, "SseSession", factory), + patch.object(module.OPENER, "open", refuse), + ): + module.dispatch( + { + "method": "tools/call", + "params": {"name": "read_post", "arguments": {"id": "7"}}, + }, + "consumer", + "cid", + ) + self.assertEqual(1, made[0].opened) + self.assertIn("initialize", [call[0] for call in made[0].calls]) + self.assertIn("tools/call", [call[0] for call in made[0].calls]) + + def test_the_initialized_notification_carries_no_id(self) -> None: + module, made, factory = self._sse_module() + with patch.object(module.sse, "SseSession", factory): + module.handshake_upstream() + self.assertEqual( + [("notifications/initialized", None)], + made[0].notifications, + "a notification has no id, so awaiting a matching response would " + "wait for something the protocol never sends", + ) + + def test_the_stream_is_opened_once_and_reused(self) -> None: + module, made, factory = self._sse_module() + with patch.object(module.sse, "SseSession", factory): + module.handshake_upstream() + module.exchange({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}) + self.assertEqual(1, len(made)) + + def test_the_upstream_credential_rides_the_stream(self) -> None: + module, made, factory = self._sse_module() + with ( + patch.object(module.sse, "SseSession", factory), + patch.object(module, "UPSTREAM_KEY", "upstream-secret"), + ): + module.handshake_upstream() + self.assertEqual({"Authorization": "Bearer upstream-secret"}, made[0].headers) + + def test_an_unknown_transport_is_refused_at_load(self) -> None: + with self.assertRaises(Exception) as caught: + load(transport="carrier-pigeon") + self.assertIn("upstream_transport", str(caught.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_shipped_contracts.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_shipped_contracts.py new file mode 100644 index 0000000000..305f9d48dd --- /dev/null +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_shipped_contracts.py @@ -0,0 +1,154 @@ +"""Every shipped tool contract survives the loader the sidecar runs at startup. + +`svc-ai-mcp-adapter` validates its contract while importing, and a rejection +kills the process. Compose then reports a container that never turns healthy, +which surfaces an hour into a deploy as a failing probe rather than as the +metadata edit it is -- and `server.py` answers `/health` unconditionally, so a +contract that loads but advertises the wrong set fails even later, at the first +`tools/call`. + +Nothing else runs a shipped `roles/*/files/mcp/tools.json` through that path: +the sibling suites here build synthetic contracts, `test_mcp_contract_digest.py` +recomputes the hash without loading, and `test_mcp_tool_surface.py` compares +YAML to YAML. This file closes that gap by assembling the contract the role's +own `vars/main.yml` assembles and handing it to the real `load_contract` / +`load_mcp_contract`, so a limit that stopped being a positive integer, a +`mutating: true` tool in a read-only surface, an unspeakable upstream transport +or a stale digest fails here in a second instead of on a deployed host. +""" + +from __future__ import annotations + +import importlib.util +import json +import sys +import unittest + +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +FILES_DIR = PROJECT_ROOT / "roles/svc-ai-mcp-adapter/files/python" + +MCP_UPSTREAM_ADAPTER_TYPES = frozenset({"mcp_passthrough"}) + + +def load_adapter(): + """Import the adapter's policy layer the way the image lays it out. + + `passthrough` imports `policy` as a sibling, so its own directory has to be + importable before the module body runs. + """ + spec = importlib.util.spec_from_file_location( + "shipped_passthrough", FILES_DIR / "passthrough.py" + ) + module = importlib.util.module_from_spec(spec) + sys.path.insert(0, str(FILES_DIR)) + try: + spec.loader.exec_module(module) + import policy as policy_module + finally: + sys.path.remove(str(FILES_DIR)) + return module, policy_module + + +passthrough, policy = load_adapter() + + +def shipped() -> list[tuple[str, dict, dict]]: + """Return `(role, mcp block, tool mapping)` for every shipped contract.""" + found = [] + for spec in sorted(PROJECT_ROOT.glob("roles/*/files/mcp/tools.json")): + role = spec.parent.parent.parent.name + block = load_yaml(PROJECT_ROOT / "roles" / role / ROLE_FILE_META_MCP) + found.append((role, block, json.loads(read_text(str(spec))))) + return found + + +def contract_of(role: str, block: dict, tools: dict) -> str: + """Return the `ADAPTER_CONTRACT` the role's compose template hands the sidecar. + + Args: + role: the role directory name. + block: the role's `meta/mcp.yml`. + tools: the shipped tool mapping. + """ + adapter = block.get("adapter") or {} + contract = { + "provider": role, + "upstream_url": f"http://{role}:8080{adapter.get('upstream_path', '/')}", + "auth_subject": block.get("auth_subject"), + "mutating_tools_enabled": bool( + (block.get("tools") or {}).get("mutating_tools_enabled") + ), + "tools": tools, + "limits": block["limits"], + "schema_sha256": (block.get("tools") or {}).get("schema_sha256"), + } + if adapter.get("type") in MCP_UPSTREAM_ADAPTER_TYPES: + contract["upstream_kind"] = passthrough.KIND_MCP + contract["upstream_transport"] = adapter.get("upstream_transport") + return json.dumps(contract) + + +def load(block: dict, raw: str) -> dict: + """Return the contract as the sidecar loads it. + + Args: + block: the role's `meta/mcp.yml`. + raw: the serialised contract. + """ + adapter_type = (block.get("adapter") or {}).get("type") + if adapter_type in MCP_UPSTREAM_ADAPTER_TYPES: + return passthrough.load_mcp_contract(raw) + return policy.load_contract(raw) + + +class TestShippedContracts(unittest.TestCase): + def test_every_shipped_contract_loads(self): + for role, block, tools in shipped(): + with self.subTest(role=role): + load(block, contract_of(role, block, tools)) + + def test_every_shipped_contract_matches_its_pinned_digest(self): + for role, block, tools in shipped(): + with self.subTest(role=role): + policy.assert_no_drift(load(block, contract_of(role, block, tools))) + + def test_the_advertised_tools_are_the_declared_allowlist(self): + for role, block, tools in shipped(): + with self.subTest(role=role): + loaded = load(block, contract_of(role, block, tools)) + self.assertEqual( + sorted((block.get("tools") or {}).get("allowlist") or []), + policy.listed_tools(loaded), + f"{role} advertises a set its meta does not declare", + ) + + def test_a_read_only_surface_ships_no_mutating_tool(self): + for role, block, tools in shipped(): + if (block.get("tools") or {}).get("mutating_tools_enabled"): + continue + with self.subTest(role=role): + mutating = sorted( + name for name, spec in tools.items() if spec.get("mutating") + ) + self.assertEqual( + [], + mutating, + f"{role} withholds mutations yet ships {mutating}, which the " + f"loader refuses at startup", + ) + + def test_the_scan_finds_contracts(self): + self.assertTrue( + shipped(), + "no shipped contract was read, so every assertion here would pass " + "vacuously", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_sse.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_sse.py new file mode 100644 index 0000000000..2afcebb412 --- /dev/null +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_sse.py @@ -0,0 +1,165 @@ +"""Unit tests for the adapter's classic HTTP+SSE upstream client.""" + +from __future__ import annotations + +import importlib.util +import json +import unittest +from unittest.mock import patch + +from . import PROJECT_ROOT + +MODULE_PATH = PROJECT_ROOT / "roles/svc-ai-mcp-adapter/files/python/sse.py" + +STREAM = "http://provider:8080/mcp/key/sse" +ENDPOINT = "http://provider:8080/mcp/key/messages?session=1" + + +def load(): + spec = importlib.util.spec_from_file_location("adapter_sse", MODULE_PATH) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def frames(*lines): + """Return the byte lines an SSE reader iterates over. + + Args: + lines: the raw stream lines, without terminators. + """ + return [f"{line}\n".encode() for line in lines] + + +class FakeStream: + """An open SSE response the reader thread iterates.""" + + def __init__(self, lines, status=200): + self._lines = list(lines) + self.status = status + self.headers = {"Content-Type": "text/event-stream"} + self.closed = False + + def __iter__(self): + return iter(self._lines) + + def close(self): + self.closed = True + + +class FakePost: + """The empty response a message POST returns.""" + + def __enter__(self): + return self + + def __exit__(self, *_args): + return False + + +class TestSseSession(unittest.TestCase): + def setUp(self): + self.module = load() + self.posted = [] + + def _opener(self, stream_lines): + def fake_open(request, timeout=None): + if request.get_method() == "GET": + return FakeStream(stream_lines) + self.posted.append(json.loads(request.data.decode())) + return FakePost() + + return fake_open + + def _session(self, stream_lines, **kwargs): + with patch.object(self.module.OPENER, "open", self._opener(stream_lines)): + return self.module.SseSession(STREAM, timeout=2, **kwargs).open() + + def test_the_announced_endpoint_becomes_the_request_channel(self): + session = self._session(frames("event: endpoint", f"data: {ENDPOINT}", "")) + self.assertEqual(ENDPOINT, session.endpoint) + + def test_a_relative_announcement_resolves_against_the_stream(self): + session = self._session(frames("event: endpoint", "data: /mcp/messages", "")) + self.assertEqual("http://provider:8080/mcp/messages", session.endpoint) + + def test_a_stream_that_announces_nothing_raises(self): + with self.assertRaises(self.module.SseError) as caught: + self._session(frames("event: message", 'data: {"jsonrpc":"2.0"}', "")) + self.assertIn("announced no message endpoint", str(caught.exception)) + + def test_a_response_is_matched_by_id_off_the_stream(self): + lines = frames( + "event: endpoint", + f"data: {ENDPOINT}", + "", + "event: message", + 'data: {"jsonrpc":"2.0","id":7,"result":{"ok":true}}', + "", + ) + with patch.object(self.module.OPENER, "open", self._opener(lines)): + session = self.module.SseSession(STREAM, timeout=2).open() + answer = session.call("tools/list", request_id=7) + self.assertEqual({"ok": True}, answer["result"]) + self.assertEqual( + [{"jsonrpc": "2.0", "id": 7, "method": "tools/list"}], self.posted + ) + + def test_another_caller_s_response_is_not_returned(self): + lines = frames( + "event: endpoint", + f"data: {ENDPOINT}", + "", + "event: message", + 'data: {"jsonrpc":"2.0","id":99,"result":{"other":true}}', + "", + "event: message", + 'data: {"jsonrpc":"2.0","id":7,"result":{"mine":true}}', + "", + ) + with patch.object(self.module.OPENER, "open", self._opener(lines)): + session = self.module.SseSession(STREAM, timeout=2).open() + answer = session.call("tools/list", request_id=7) + self.assertEqual({"mine": True}, answer["result"]) + + def test_a_call_before_opening_raises_rather_than_posting_nowhere(self): + session = self.module.SseSession(STREAM, timeout=2) + with self.assertRaises(self.module.SseError): + session.call("tools/list") + + def test_the_credential_rides_both_channels(self): + seen = [] + + def fake_open(request, timeout=None): + seen.append((request.get_method(), request.get_header("Authorization"))) + if request.get_method() == "GET": + return FakeStream( + frames( + "event: endpoint", + f"data: {ENDPOINT}", + "", + "event: message", + 'data: {"jsonrpc":"2.0","id":1,"result":{}}', + "", + ) + ) + return FakePost() + + with patch.object(self.module.OPENER, "open", fake_open): + session = self.module.SseSession( + STREAM, headers={"Authorization": "Bearer secret"}, timeout=2 + ).open() + session.call("tools/list") + self.assertEqual([("GET", "Bearer secret"), ("POST", "Bearer secret")], seen) + + def test_an_upstream_redirect_is_refused_rather_than_followed(self): + handler = self.module.NoRedirect() + self.assertIsNone( + handler.redirect_request(None, None, 302, "Found", {}, "http://evil/"), + "urllib copies the request headers onto the redirect target, so " + "following one would hand the upstream credential away", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-net-firewall/__init__.py b/tests/unit/python/roles/svc-net-firewall/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/svc-net-firewall/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/svc-net-firewall/test_fragments.py b/tests/unit/python/roles/svc-net-firewall/test_fragments.py new file mode 100644 index 0000000000..99152196b5 --- /dev/null +++ b/tests/unit/python/roles/svc-net-firewall/test_fragments.py @@ -0,0 +1,236 @@ +"""Every role's nftables fragment parses, and replaces its table instead of merging. + +``nft -f`` on ``table inet x { ... }`` MERGES into an existing table: a rule +dropped from the declaration stays in the kernel, and the ruleset can only ever +grow. The three-line idiom below is what makes a fragment a replacement: + + table inet x <- creates it when absent, so the delete cannot fail + delete table inet x <- removes whatever the last deploy left + table inet x { ... } <- the declaration, applied in the same transaction + +``nft -f`` is atomic, so the table is never observed empty. Without the first +line the delete fails on a fresh host; without the second the fragment merges. + +The checks run the real ``nft`` over the rendered text, so a fragment that is +valid Jinja but invalid nftables fails here rather than on the host. They render +every deploy mode, because a fragment may branch on one, and feed plausible +rather than real values: nft needs shapes, not this host's addresses. +""" + +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import tempfile +import unittest +from contextlib import contextmanager +from functools import lru_cache +from pathlib import Path + +import jinja2 + +from utils.cache.files import iter_project_files, read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +from . import PROJECT_ROOT + +FRAGMENT = "templates/nftables.conf.j2" +TABLE = "infinito_probe" + +PROBE_PORTS = { + "TOR_TRANS_PORT": "9040", + "TOR_DNS_PORT": "9053", + "TOR_SOCKS_PORT": "9050", + "TOR_DNSMASQ_PORT": "53", +} + +_PORT_VARIABLE = re.compile(r"\{\{\s*([A-Z][A-Z0-9_]*)\s*\}\}") + + +def _guarded_ports() -> list[dict]: + """The role's own guard list, with its port variables filled from stand-ins. + + The shape has to come from the declaration: an entry that gains a key, a + protocol or a whole port must reach the rendered table here, or this check + keeps passing on a fixture the role stopped shipping. + """ + declared = load_yaml_any( + str(PROJECT_ROOT / "roles" / "svc-net-tor" / ROLE_FILE_VARS_MAIN) + )["TOR_EGRESS_GUARDED_PORTS"] + return [ + {**entry, "port": PROBE_PORTS[_PORT_VARIABLE.search(entry["port"]).group(1)]} + for entry in declared + ] + + +COMMON = { + "FIREWALL_TABLE": TABLE, + "TOR_EGRESS_CLIENT_CIDRS": ["127.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"], + "TOR_EGRESS_GUARDED_PORTS": _guarded_ports(), + "TOR_EGRESS_VIRTUAL_NET_IPV4": "10.192.0.0/10", + **PROBE_PORTS, + "TOR_CONTAINER_DNS_HOST": "172.17.0.1", + "NETWORK_INTERNAL_CIDRS": [ + "127.0.0.0/8", + "10.0.0.0/8", + "172.16.0.0/12", + "192.168.0.0/16", + ], +} + +MODES = ("compose", "swarm") + + +def _run(argv: list[str]) -> subprocess.CompletedProcess[str]: + return subprocess.run(argv, capture_output=True, text=True, check=False) + + +@lru_cache(maxsize=1) +def _nft_can_check() -> bool: + """Whether `nft -c` works here. + + It is not a parser: it opens netlink and builds a cache against the live + kernel first, so on a runner without CAP_NET_ADMIN it fails on a valid + ruleset. Probing the binary's presence would make this suite red there. + """ + if shutil.which("nft") is None: + return False + with tempfile.NamedTemporaryFile("w", suffix=".conf") as handle: + handle.write("table inet infinito_capability_probe\n") + handle.flush() + return _run(["nft", "-c", "-f", handle.name]).returncode == 0 + + +@contextmanager +def _network_namespace(name: str): + """An empty namespace, so a loaded ruleset cannot reach the live one.""" + created = _run(["ip", "netns", "add", name]) + if created.returncode != 0: + raise unittest.SkipTest(f"cannot create a network namespace: {created.stderr}") + try: + yield ["ip", "netns", "exec", name] + finally: + _run(["ip", "netns", "del", name]) + + +def _fragments() -> list[str]: + suffix = "/" + FRAGMENT + return sorted( + path + for path in iter_project_files(extensions=(".j2",), exclude_tests=True) + if path.endswith(suffix) + ) + + +def _render(path: str, mode: str = "swarm") -> str: + environment = jinja2.Environment( + keep_trailing_newline=True, + trim_blocks=True, + autoescape=False, # noqa: S701 nftables, not markup + ) + return environment.from_string(read_text(path)).render( + DEPLOYMENT_MODE=mode, **COMMON + ) + + +class TestFirewallFragments(unittest.TestCase): + def test_at_least_one_fragment_exists(self) -> None: + """Otherwise every assertion below passes over an empty list.""" + self.assertTrue(_fragments(), "no role declares templates/nftables.conf.j2") + + def test_each_fragment_replaces_its_table(self) -> None: + for path in _fragments(): + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + with self.subTest(fragment=rel): + lines = [ + line.strip() for line in _render(path).splitlines() if line.strip() + ] + declarations = [ + line for line in lines if re.match(r"^(delete )?table inet ", line) + ] + self.assertEqual( + declarations[:3], + [ + f"table inet {TABLE}", + f"delete table inet {TABLE}", + f"table inet {TABLE} {{", + ], + f"{rel} must open with the create, delete and declare idiom, " + "or nft merges the new rules into the old table", + ) + + def test_each_fragment_parses(self) -> None: + if not _nft_can_check(): + self.skipTest("nft -c needs CAP_NET_ADMIN, which this runner lacks") + nft = shutil.which("nft") + for path in _fragments(): + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + for mode in MODES: + with self.subTest(fragment=rel, mode=mode): + with tempfile.NamedTemporaryFile("w", suffix=".conf") as handle: + handle.write(_render(path, mode)) + handle.flush() + result = subprocess.run( + [nft, "-c", "-f", handle.name], + capture_output=True, + text=True, + check=False, + ) + self.assertEqual( + result.returncode, + 0, + f"{rel} is not valid nftables in {mode}:\n{result.stderr}", + ) + + def test_each_fragment_loads_and_reloads(self) -> None: + """A dry run cannot show what happens on the second deploy. + + Loading the same fragment twice is what proves the idiom: the second + pass meets the table the first one left and must replace it, which is + exactly the case ``nft -c`` never sees. + """ + if not _nft_can_check() or shutil.which("ip") is None: + self.skipTest("loading a ruleset needs nft with CAP_NET_ADMIN and ip") + for index, path in enumerate(_fragments()): + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + for mode in MODES: + with self.subTest(fragment=rel, mode=mode): + with ( + tempfile.NamedTemporaryFile("w", suffix=".conf") as handle, + _network_namespace(f"nftprobe{os.getpid()}x{index}") as netns, + ): + handle.write(_render(path, mode)) + handle.flush() + listings = [] + for attempt in ("first", "second"): + loaded = _run([*netns, "nft", "-f", handle.name]) + self.assertEqual( + loaded.returncode, + 0, + f"{rel} failed to load on the {attempt} pass " + f"in {mode}:\n{loaded.stderr}", + ) + listed = _run( + [*netns, "nft", "list", "table", "inet", TABLE] + ) + self.assertEqual( + listed.returncode, + 0, + f"{rel} loaded but left no table on the {attempt} " + f"pass in {mode}:\n{listed.stderr}", + ) + listings.append(listed.stdout) + self.assertIn(f"table inet {TABLE}", listings[0]) + self.assertEqual( + listings[0], + listings[1], + f"{rel} grew on the second pass in {mode}, so it merges " + "into the table it found instead of replacing it", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-net-tor/__init__.py b/tests/unit/python/roles/svc-net-tor/__init__.py index e69de29bb2..8ee16d7567 100644 --- a/tests/unit/python/roles/svc-net-tor/__init__.py +++ b/tests/unit/python/roles/svc-net-tor/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/svc-net-tor/test_egress_clients.py b/tests/unit/python/roles/svc-net-tor/test_egress_clients.py new file mode 100644 index 0000000000..52a558a9a9 --- /dev/null +++ b/tests/unit/python/roles/svc-net-tor/test_egress_clients.py @@ -0,0 +1,101 @@ +"""The egress guard admits every address a container can come from. + +The guard drops any source outside ``tor_egress_clients``, and containers reach +the TransPort and the DNSPort through exactly those rules. So the list is not a +convenience: if it ever stops covering docker's own address pools, every +container loses the resolver and the transparent proxy at once, and it fails in +production rather than here. + +This runs the real lookup over the repository's real network declarations. A +narrowed pool, a renamed key or a dropped entry in the lookup all surface as a +failure of the property the rules depend on. +""" + +from __future__ import annotations + +import importlib.util +import sys +import unittest +from unittest import mock + +import jinja2 + +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +NETWORKS = PROJECT_ROOT / "group_vars/all/08_networks.yml" +LOOKUP = "roles/svc-net-tor/lookup_plugins/tor_egress_clients.py" + + +def _load_lookup(): + path = PROJECT_ROOT / LOOKUP + spec = importlib.util.spec_from_file_location("tor_egress_clients_lookup", path) + module = importlib.util.module_from_spec(spec) + assert spec and spec.loader + sys.modules["tor_egress_clients_lookup"] = module + spec.loader.exec_module(module) + return module + + +class _Templar: + """Resolves the group_vars cross-references the lookup renders.""" + + def __init__(self, variables: dict): + self.available_variables = variables + + def template(self, value): + return ( + jinja2.Environment(autoescape=False) # noqa: S701 - renders CIDRs, not markup + .from_string(str(value)) + .render(**self.available_variables) + ) + + +class TestEgressClients(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.module = _load_lookup() + cls.variables = load_yaml_any(str(NETWORKS)) + + def _admitted(self) -> list[str]: + lookup = self.module.LookupModule() + lookup._templar = _Templar(self.variables) + lookup._loader = mock.MagicMock() + with mock.patch.object(self.module, "lookup_loader") as loader: + loader.get.return_value = mock.MagicMock( + run=mock.MagicMock(return_value=[[]]) + ) + return lookup.run([], variables=self.variables)[0] + + def test_every_docker_address_pool_is_admitted(self) -> None: + admitted = self._admitted() + pools = self.variables["NETWORK_DOCKER_ADDRESS_POOLS"] + self.assertTrue(pools, "no docker address pool is declared") + for pool in pools: + with self.subTest(pool=pool["base"]): + self.assertIn( + pool["base"], + admitted, + "containers draw their address from this pool and reach the " + "guarded ports through the guard, so dropping it from the " + "admitted list takes the resolver away from every container", + ) + + def test_loopback_is_admitted(self) -> None: + """The host resolves .onion through its own loopback.""" + self.assertIn(self.variables["NETWORK_LOOPBACK_CIDR"], self._admitted()) + + def test_the_lan_is_not_admitted_wholesale(self) -> None: + """The guarded ports carry no access policy, so the LAN is not a client. + + Admitting 10.0.0.0/8 would hand a transparent proxy and a resolver to + every host the operator's network happens to contain. + """ + self.assertNotIn( + self.variables["NETWORK_PRIVATE_CIDRS"]["class_a"], self._admitted() + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-net-tor/test_extra_ports.py b/tests/unit/python/roles/svc-net-tor/test_extra_ports.py new file mode 100644 index 0000000000..4deb747de1 --- /dev/null +++ b/tests/unit/python/roles/svc-net-tor/test_extra_ports.py @@ -0,0 +1,135 @@ +"""The node onion forwards HTTP whether or not the proxy is in the inventory. + +``lookup('tor_ports')`` collects what the roles in ``group_names`` declare under +``ports.onion``. Port 80 belongs to ``svc-prx-openresty``, which a node acquires +through ``sys-stk-front-proxy`` and which therefore appears in no dependency +list an inventory holds. A node provisioned with ``--include svc-net-tor`` alone +published an onion forwarding SSH and nothing else. + +These run the real lookup over a stubbed ``tor_ports``, so a flag that stops +reaching the forward list, or a derived port that starts duplicating a flagged +one, fails here rather than on the node. +""" + +from __future__ import annotations + +import importlib.util +import sys +import unittest +from typing import Any +from unittest import mock + +from ansible.errors import AnsibleError + +from . import PROJECT_ROOT + +LOOKUP = "roles/svc-net-tor/lookup_plugins/tor_extra_ports.py" +SSH_ENTRY = {"onion_port": 22, "target": "127.0.0.1:22"} +HTTP_ENTRY = {"onion_port": 80, "target": "127.0.0.1:80"} +ENABLED = {"TOR_ONION_SSH_ENABLED": True, "TOR_ONION_HTTP_ENABLED": True} + + +def _load_lookup(): + path = PROJECT_ROOT / LOOKUP + spec = importlib.util.spec_from_file_location("tor_extra_ports_lookup", path) + module = importlib.util.module_from_spec(spec) + assert spec and spec.loader + sys.modules["tor_extra_ports_lookup"] = module + spec.loader.exec_module(module) + return module + + +class _DerivedPorts: + """Stands in for the tor_ports lookup the plugin composes with.""" + + def __init__(self, entries: list[dict[str, Any]]): + self.entries = entries + + def run(self, _terms, **_kwargs): + return [self.entries] + + +class _Templar: + """Resolves a group_var reference the way the play's templar does.""" + + def __init__(self, rendered: Any): + self.rendered = rendered + + def template(self, _value): + return self.rendered + + +class TestExtraPorts(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.module = _load_lookup() + + def _ports(self, derived: list[dict], **variables) -> list[dict]: + lookup = self.module.LookupModule() + lookup._templar = None + lookup._loader = None + with mock.patch.object( + self.module.lookup_loader, "get", return_value=_DerivedPorts(derived) + ): + return lookup.run([], variables={**ENABLED, **variables})[0] + + def test_a_flag_that_arrives_as_template_text_is_still_read(self) -> None: + lookup = self.module.LookupModule() + lookup._templar = _Templar(True) + lookup._loader = None + variables = dict.fromkeys( + ENABLED, + "{{ lookup('config', application_id, 'services.tor.forwards.x') | bool }}", + ) + with mock.patch.object( + self.module.lookup_loader, "get", return_value=_DerivedPorts([]) + ): + ports = lookup.run([], variables=variables)[0] + self.assertIn( + HTTP_ENTRY, + ports, + "group vars reach a lookup unrendered, so the flag arrives as its own " + "template text; reading it without templating aborts the torrc render " + "on every tor row", + ) + + def test_http_is_forwarded_without_the_proxy_in_the_inventory(self) -> None: + self.assertIn( + HTTP_ENTRY, + self._ports([]), + "a node whose inventory lists only svc-net-tor still serves its apps " + "over the onion, so the forward cannot depend on the proxy being listed", + ) + + def test_a_derived_port_does_not_duplicate_a_flagged_one(self) -> None: + ports = self._ports([HTTP_ENTRY]) + self.assertEqual( + [entry for entry in ports if entry["onion_port"] == 80], + [HTTP_ENTRY], + "torrc writes one HiddenServicePort line per entry, so a duplicate " + "publishes the same forward twice", + ) + + def test_derived_ports_still_reach_the_forward_list(self) -> None: + onion_dns = {"onion_port": 9053, "target": "127.0.0.1:9053"} + self.assertIn( + onion_dns, + self._ports([onion_dns]), + "the flags add to what the services declare, they do not replace it", + ) + + def test_a_flag_turns_its_forward_off(self) -> None: + ports = self._ports([], TOR_ONION_HTTP_ENABLED=False) + self.assertNotIn(HTTP_ENTRY, ports) + self.assertIn(SSH_ENTRY, ports, "the other flag is untouched") + + def test_an_undeclared_flag_is_refused(self) -> None: + lookup = self.module.LookupModule() + lookup._templar = None + with self.assertRaises(AnsibleError) as raised: + lookup.run([], variables={"TOR_ONION_SSH_ENABLED": True}) + self.assertIn("TOR_ONION_HTTP_ENABLED", str(raised.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-net-tor/test_guarded_ports.py b/tests/unit/python/roles/svc-net-tor/test_guarded_ports.py new file mode 100644 index 0000000000..f3c2c0ba88 --- /dev/null +++ b/tests/unit/python/roles/svc-net-tor/test_guarded_ports.py @@ -0,0 +1,130 @@ +"""Every port the egress router binds locally is dropped for foreign sources. + +The guard chain is the only thing between these listeners and anyone who can +route a packet to the node. A port that is bound but not named in a drop rule +answers the whole reachable network: the transparent proxy relays, the DNSPort +resolves, and the split-DNS forwarder both resolves recursively and hands out +the node's own ``.onion`` records. + +This walks the real declaration chain rather than a fixture: ``meta/services.yml`` +names the ports tor itself binds, ``vars/main.yml`` turns each into a +``TOR_*_PORT`` variable, and the guard list plus the fragment template spend +those variables on drop rules. A port added to the service declaration without a +rule fails the first test. + +The forwarder sits outside that chain because it is not tor's own port: it takes +the well-known resolver port from ``NETWORK_DNS_PORT``, and the host already +assigns that number to whichever resolver owns it. The second test covers it by +name instead. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_VARS_MAIN + +from . import PROJECT_ROOT + +ROLE = PROJECT_ROOT / "roles/svc-net-tor" +SERVICES = ROLE / ROLE_FILE_META_SERVICES +VARS = ROLE / ROLE_FILE_VARS_MAIN +FRAGMENT = ROLE / "templates/nftables.conf.j2" + +_VARIABLE = re.compile(r"\{\{\s*([A-Z][A-Z0-9_]*)\s*\}\}") +_PORT_KEY = re.compile(r"services\.tor\.ports\.local\.([a-z0-9_]+)") +_DROP_RULE = re.compile(r"^\s*(?!#).*\b(?P<protocol>tcp|udp)\s+dport\b.*\bdrop\b") + + +def _declared_ports() -> dict[str, int]: + return load_yaml_any(str(SERVICES))["tor"]["ports"]["local"] + + +def _port_variables() -> dict[str, str]: + """Maps each ``TOR_*_PORT`` variable to the port key it reads.""" + declared = load_yaml_any(str(VARS)) + names = {} + for name, value in declared.items(): + if not isinstance(value, str): + continue + key = _PORT_KEY.search(value) + if key is not None: + names[name] = key.group(1) + return names + + +def _entries_for(variable: str) -> list[dict]: + """Guard entries whose port comes from *variable*.""" + return [ + entry + for entry in load_yaml_any(str(VARS))["TOR_EGRESS_GUARDED_PORTS"] + if _VARIABLE.search(str(entry["port"])).group(1) == variable + ] + + +def _guarded_keys() -> set[str]: + """Port keys that reach a drop rule, through the vars list or the template.""" + variables = _port_variables() + guarded: set[str] = set() + + for entry in load_yaml_any(str(VARS))["TOR_EGRESS_GUARDED_PORTS"]: + name = _VARIABLE.search(str(entry["port"])) + if name is not None and name.group(1) in variables: + guarded.add(variables[name.group(1)]) + + for line in read_text(str(FRAGMENT)).splitlines(): + if _DROP_RULE.match(line) is None: + continue + for name in _VARIABLE.findall(line): + if name in variables: + guarded.add(variables[name]) + + return guarded + + +class TestGuardedPorts(unittest.TestCase): + def test_every_locally_bound_port_reaches_a_drop_rule(self) -> None: + declared = _declared_ports() + self.assertTrue(declared, f"{SERVICES} declares no local ports") + + unguarded = sorted(set(declared) - _guarded_keys()) + self.assertEqual( + unguarded, + [], + "these ports are bound on the node but no guard rule drops a " + "foreign source for them, so they answer everything that can route " + f"to the node: {', '.join(f'{key} ({declared[key]})' for key in unguarded)}", + ) + + def test_the_forwarder_is_guarded_on_both_transports(self) -> None: + entries = _entries_for("TOR_DNSMASQ_PORT") + self.assertEqual( + {entry["protocol"] for entry in entries}, + {"tcp", "udp"}, + "dnsmasq answers on both transports, and a TCP query returns the " + "same records a UDP one does", + ) + + def test_the_forwarder_admits_every_source_the_node_calls_internal(self) -> None: + """The resolver may not be stricter than the proxy it sits next to. + + ``internal`` is ``NETWORK_INTERNAL_CIDRS``, the same list ``torrc.j2`` + spends on ``SocksPolicy accept``. ``containers`` is narrower: out of + ``10.0.0.0/8`` it carries only the docker pool and the exception role, + which leaves out swarm's ingress network and every overlay docker + allocates without an ipam block. Guarding the resolver with the narrow + set hands a source a full SOCKS proxy and refuses it a name lookup. + """ + self.assertEqual( + {entry["admitted"] for entry in _entries_for("TOR_DNSMASQ_PORT")}, + {"internal"}, + "the resolver carries ordinary name resolution for everything the " + "node routes, so it takes the internal set, not the container pools", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-net-tor/test_onion_ports_probe.py b/tests/unit/python/roles/svc-net-tor/test_onion_ports_probe.py new file mode 100644 index 0000000000..e9ab2bb600 --- /dev/null +++ b/tests/unit/python/roles/svc-net-tor/test_onion_ports_probe.py @@ -0,0 +1,162 @@ +"""The onion port probe speaks SOCKS5 and reports only real successes. + +The handshake used to live in a heredoc inside a shell script, where no linter +and no test could reach it: forty lines assembling protocol bytes, checked by +nothing. These tests run it against a fake proxy that answers by script, so the +bytes on the wire and the verdict drawn from the reply are both pinned. +""" + +from __future__ import annotations + +import importlib.util +import socket +import threading +import unittest + +from . import PROJECT_ROOT + + +def _load_probe(): + path = PROJECT_ROOT / "roles" / "svc-net-tor" / "files" / "test" / "onion_ports.py" + spec = importlib.util.spec_from_file_location("onion_ports_probe", str(path)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +PROBE = _load_probe() + + +class _FakeSocks(threading.Thread): + """A one-shot SOCKS5 proxy that replies with a scripted CONNECT code.""" + + def __init__(self, reply_code: int | None, greeting: bytes = b"\x05\x00") -> None: + super().__init__(daemon=True) + self._reply_code = reply_code + self._greeting = greeting + self._server = socket.socket() + self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self._server.bind(("127.0.0.1", 0)) + self._server.listen(1) + self.request = b"" + + @property + def endpoint(self) -> str: + host, port = self._server.getsockname() + return f"{host}:{port}" + + def run(self) -> None: + conn, _ = self._server.accept() + with conn: + conn.recv(3) + conn.sendall(self._greeting) + if self._greeting != b"\x05\x00": + return + self.request = conn.recv(512) + if self._reply_code is None: + return + conn.sendall(bytes([0x05, self._reply_code, 0x00, 0x01])) + self._server.close() + + +class TestConnectThroughSocks(unittest.TestCase): + def test_a_success_reply_passes_and_carries_the_target(self) -> None: + proxy = _FakeSocks(reply_code=0x00) + proxy.start() + PROBE.connect_through_socks(proxy.endpoint, "example.onion", 25, 5) + proxy.join(timeout=5) + self.assertTrue( + proxy.request.startswith(b"\x05\x01\x00\x03"), + f"the CONNECT request is malformed: {proxy.request!r}", + ) + self.assertIn(b"example.onion", proxy.request) + self.assertTrue( + proxy.request.endswith((25).to_bytes(2, "big")), + "the port must travel big-endian in the last two bytes", + ) + + def test_a_refusal_reply_fails(self) -> None: + proxy = _FakeSocks(reply_code=0x05) + proxy.start() + with self.assertRaises(PROBE.ProbeError) as raised: + PROBE.connect_through_socks(proxy.endpoint, "example.onion", 25, 5) + self.assertIn("0x05", str(raised.exception)) + + def test_a_refused_auth_method_fails(self) -> None: + proxy = _FakeSocks(reply_code=None, greeting=b"\x05\xff") + proxy.start() + with self.assertRaises(PROBE.ProbeError): + PROBE.connect_through_socks(proxy.endpoint, "example.onion", 25, 5) + + def test_a_closed_connection_fails(self) -> None: + proxy = _FakeSocks(reply_code=None) + proxy.start() + with self.assertRaises(PROBE.ProbeError): + PROBE.connect_through_socks(proxy.endpoint, "example.onion", 25, 5) + + def test_an_unreachable_proxy_fails(self) -> None: + with self.assertRaises(PROBE.ProbeError) as raised: + PROBE.connect_through_socks("127.0.0.1:1", "example.onion", 25, 1) + self.assertIn("unreachable", str(raised.exception)) + + +class TestProbe(unittest.TestCase): + def test_only_the_failures_are_retried(self) -> None: + attempts: list[int] = [] + + def _connect(_proxy, _host, port, _timeout): + attempts.append(port) + if port == 25: + raise PROBE.ProbeError("still down") + + original = PROBE.connect_through_socks + PROBE.connect_through_socks = _connect + try: + failures = PROBE.probe( + proxy="p:9050", + host="example.onion", + ports=[25, 143], + timeout=1, + retries=3, + sleep_seconds=0, + sleeper=lambda _seconds: None, + ) + finally: + PROBE.connect_through_socks = original + + self.assertEqual(failures, {25: "still down"}) + self.assertEqual( + attempts.count(143), + 1, + "a healthy port must not be probed again on a retry pass", + ) + self.assertEqual(attempts.count(25), 3) + + def test_a_port_that_recovers_is_not_reported(self) -> None: + seen: list[int] = [] + + def _connect(_proxy, _host, port, _timeout): + seen.append(port) + if len(seen) == 1: + raise PROBE.ProbeError("first pass fails") + + original = PROBE.connect_through_socks + PROBE.connect_through_socks = _connect + try: + failures = PROBE.probe( + proxy="p:9050", + host="example.onion", + ports=[25], + timeout=1, + retries=2, + sleep_seconds=0, + sleeper=lambda _seconds: None, + ) + finally: + PROBE.connect_through_socks = original + + self.assertEqual(failures, {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-net-tor/test_onion_timeout_multipliers.py b/tests/unit/python/roles/svc-net-tor/test_onion_timeout_multipliers.py new file mode 100644 index 0000000000..2ba9c33c36 --- /dev/null +++ b/tests/unit/python/roles/svc-net-tor/test_onion_timeout_multipliers.py @@ -0,0 +1,30 @@ +import unittest + +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_META_SERVICES + +from . import PROJECT_ROOT + +SERVICES_PATH = PROJECT_ROOT / "roles" / "svc-net-tor" / ROLE_FILE_META_SERVICES +FLAVOR_DIR = PROJECT_ROOT / "roles" / "svc-net-tor" / "tasks" / "flavor" + + +class TestOnionTimeoutMultipliers(unittest.TestCase): + def test_every_tor_flavor_has_a_multiplier(self) -> None: + multipliers = load_yaml_any(str(SERVICES_PATH))["tor"]["timeout_multipliers"] + flavors = {path.name for path in FLAVOR_DIR.iterdir() if path.is_dir()} + + self.assertTrue(flavors) + self.assertEqual( + sorted(flavors - set(multipliers)), + [], + "the Playwright run and the CSP health check look the multiplier up " + "by the tor flavor and fail without one", + ) + for flavor, value in multipliers.items(): + self.assertIsInstance(value, int, flavor) + self.assertGreaterEqual(value, 1, flavor) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-ctl-cln-bkps/files/test_script.py b/tests/unit/python/roles/sys-ctl-cln-bkps/files/test_script.py index 71b5a43518..10988f5af5 100644 --- a/tests/unit/python/roles/sys-ctl-cln-bkps/files/test_script.py +++ b/tests/unit/python/roles/sys-ctl-cln-bkps/files/test_script.py @@ -178,8 +178,9 @@ class TestSysCtlClnBkpsScript(unittest.TestCase): ) self.assertIn("contains the last version of the backup. Skipped.", out) - self.assertIn("No deletable backup versions left", out) + self.assertIn("No deletable backup version", out) self.assertIn("Cleaning up finished.", out) + self.assertIn("Delete Iteration: 1", out) self.assertNotIn("Delete Iteration: 2", out) rmtree_mock.assert_not_called() diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/__init__.py b/tests/unit/python/roles/sys-ctl-hlth-csp/__init__.py index 8b13789179..8ee16d7567 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-csp/__init__.py +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/__init__.py @@ -1 +1,3 @@ +from pathlib import Path +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-csp/files/test_script.py index a834c72fe5..8d7e98aac8 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-csp/files/test_script.py +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/files/test_script.py @@ -58,11 +58,11 @@ class TestSplitOnionDomains(unittest.TestCase): def test_splits_families(self) -> None: domains = [ "auth.abc123.onion", - "app.infinito.example", + "app.infinito.test", "matomo.abc123.onion", ] clearnet, onion = script.split_onion_domains(domains) - self.assertEqual(clearnet, ["app.infinito.example"]) + self.assertEqual(clearnet, ["app.infinito.test"]) self.assertEqual(onion, ["auth.abc123.onion", "matomo.abc123.onion"]) def test_clearnet_only(self) -> None: @@ -75,31 +75,31 @@ class TestSplitOnionDomains(unittest.TestCase): class TestIsSkippedDomain(unittest.TestCase): def test_explicit_clearnet_domain_is_skipped(self) -> None: - skip_set = {"mirror.infinito.example"} + skip_set = {"mirror.infinito.test"} labels = {d.split(".", 1)[0] for d in skip_set} self.assertTrue( - script.is_skipped_domain("mirror.infinito.example", skip_set, labels) + script.is_skipped_domain("mirror.infinito.test", skip_set, labels) ) def test_onion_sibling_of_skipped_clearnet_is_skipped(self) -> None: - skip_set = {"mirror.infinito.example"} + skip_set = {"mirror.infinito.test"} labels = {d.split(".", 1)[0] for d in skip_set} self.assertTrue( script.is_skipped_domain("mirror.abc123.onion", skip_set, labels) ) def test_unrelated_onion_is_not_skipped(self) -> None: - skip_set = {"mirror.infinito.example"} + skip_set = {"mirror.infinito.test"} labels = {d.split(".", 1)[0] for d in skip_set} self.assertFalse( script.is_skipped_domain("auth.abc123.onion", skip_set, labels) ) def test_unrelated_clearnet_is_not_skipped(self) -> None: - skip_set = {"mirror.infinito.example"} + skip_set = {"mirror.infinito.test"} labels = {d.split(".", 1)[0] for d in skip_set} self.assertFalse( - script.is_skipped_domain("auth.infinito.example", skip_set, labels) + script.is_skipped_domain("auth.infinito.test", skip_set, labels) ) @@ -114,7 +114,7 @@ class TestMainSkipsOnionSiblings(unittest.TestCase): mock_run_checker: MagicMock, ) -> None: mock_extract.return_value = [ - "mirror.infinito.example", + "mirror.infinito.test", "mirror.abc123.onion", "auth.abc123.onion", ] @@ -134,7 +134,7 @@ class TestMainSkipsOnionSiblings(unittest.TestCase): "--image", "img:tag", "--skip-domain", - "mirror.infinito.example", + "mirror.infinito.test", "--tor-proxy", "socks5://127.0.0.1:9050", ], @@ -144,7 +144,7 @@ class TestMainSkipsOnionSiblings(unittest.TestCase): script.main() probed = [d for call in mock_build_urls.call_args_list for d in call.args[1]] - self.assertNotIn("mirror.infinito.example", probed) + self.assertNotIn("mirror.infinito.test", probed) self.assertNotIn("mirror.abc123.onion", probed) self.assertIn("auth.abc123.onion", probed) @@ -171,6 +171,86 @@ class TestBuildDockerCmdProxy(unittest.TestCase): self.assertNotIn("--proxy", cmd) +class TestBuildDockerCmdTimeout(unittest.TestCase): + def test_timeout_arg_appended(self) -> None: + cmd = script.build_docker_cmd( + image="img", + urls=["http://a.onion/"], + short_mode=True, + ignore_network_blocks_from=[], + timeout_ms=100000, + ) + idx = cmd.index("--timeout") + self.assertEqual(cmd[idx + 1], "100000") + + def test_no_timeout_arg_without_one(self) -> None: + cmd = script.build_docker_cmd( + image="img", + urls=["https://a.example/"], + short_mode=True, + ignore_network_blocks_from=[], + ) + self.assertNotIn("--timeout", cmd) + + def test_the_timeout_precedes_the_url_separator(self) -> None: + cmd = script.build_docker_cmd( + image="img", + urls=["http://a.onion/"], + short_mode=True, + ignore_network_blocks_from=["cdn.example"], + timeout_ms=100000, + ) + self.assertLess( + cmd.index("--timeout"), + cmd.index("--"), + "an argument after the separator reaches the checker as a URL", + ) + + +class TestMainTimesOutOnionsOnly(unittest.TestCase): + @patch("script.run_checker") + @patch("script.build_urls_from_nginx_confs") + @patch("script.extract_domains_from_filenames") + def test_the_onion_batch_alone_carries_the_budget( + self, + mock_extract: MagicMock, + mock_build_urls: MagicMock, + mock_run_checker: MagicMock, + ) -> None: + mock_extract.return_value = ["auth.infinito.test", "auth.abc123.onion"] + mock_build_urls.side_effect = lambda _dir, domains: [ + f"http://{d}/" for d in domains + ] + mock_run_checker.return_value = 0 + + with ( + patch.object( + script.sys, + "argv", + [ + "script.py", + "--nginx-config-dir", + "/etc/nginx", + "--image", + "img:tag", + "--tor-proxy", + "socks5://127.0.0.1:9050", + "--onion-timeout", + "100000", + ], + ), + self.assertRaises(SystemExit), + ): + script.main() + + budgets = { + call.kwargs["urls"][0]: call.kwargs["timeout_ms"] + for call in mock_run_checker.call_args_list + } + self.assertEqual(budgets["http://auth.abc123.onion/"], 100000) + self.assertEqual(budgets["http://auth.infinito.test/"], 0) + + class TestDetectSchemeFromConf(unittest.TestCase): def test_detects_https_via_443(self) -> None: with patch("pathlib.Path.read_text", return_value="listen 443 ssl;"): diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_accept_status.py b/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_accept_status.py new file mode 100644 index 0000000000..3378cc06e2 --- /dev/null +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_accept_status.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import importlib.util +import sys +import unittest +import unittest.mock as mock +from unittest.mock import patch + +from . import PROJECT_ROOT + + +def _load_module(rel_path: str, name: str): + path = PROJECT_ROOT / rel_path + spec = importlib.util.spec_from_file_location(name, str(path)) + mod = importlib.util.module_from_spec(spec) + assert spec and spec.loader + sys.modules[name] = mod + spec.loader.exec_module(mod) + return mod + + +class _DummyTemplar: + def __init__(self, available_variables: dict | None = None): + self.available_variables = available_variables or {} + + +class CspAcceptStatusLookupTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.module = _load_module( + "roles/sys-ctl-hlth-csp/lookup_plugins/csp_accept_status.py", + "csp_accept_status_lookup", + ) + + def _run(self, applications, **kwargs): + lm = self.module.LookupModule() + lm._templar = _DummyTemplar() + lm._loader = mock.MagicMock() + with patch.object(self.module, "lookup_loader") as loader_mock: + loader_mock.get.return_value = mock.MagicMock( + run=lambda *_a, **_k: [applications] + ) + return lm.run(terms=[], variables={}, **kwargs)[0] + + def test_empty_applications_returns_empty_list(self): + self.assertEqual(self._run({}), []) + + def test_non_mapping_applications_returns_empty(self): + self.assertEqual(self._run([]), []) + + def test_a_declared_4xx_is_named_with_its_domain(self): + apps = { + "web-svc-mirror": { + "domains": {"canonical": ["mirror.example.com"]}, + "server": {"status_codes": {"default": [404]}}, + } + } + self.assertEqual(self._run(apps), ["mirror.example.com=404"]) + + def test_aliases_are_named_too(self): + apps = { + "web-app-bridgy": { + "domains": { + "canonical": ["bridgy.example.com"], + "aliases": ["fed.example.com"], + }, + "server": {"status_codes": {"default": [200, 404]}}, + } + } + self.assertEqual( + self._run(apps), + ["bridgy.example.com=404", "fed.example.com=404"], + ) + + def test_a_2xx_only_declaration_names_nothing(self): + apps = { + "web-app-foo": { + "domains": {"canonical": ["foo.example.com"]}, + "server": {"status_codes": {"default": [200]}}, + } + } + self.assertEqual(self._run(apps), []) + + def test_a_redirect_is_named_because_the_checker_rejects_it(self): + apps = { + "web-app-foo": { + "domains": {"canonical": ["foo.example.com"]}, + "server": {"status_codes": {"default": [200, 301]}}, + } + } + self.assertEqual(self._run(apps), ["foo.example.com=301"]) + + def test_two_vhosts_of_one_role_keep_their_own_codes(self): + apps = { + "web-app-split": { + "domains": { + "canonical": { + "api": "api.example.com", + "web": "web.example.com", + } + }, + "server": { + "status_codes": { + "api": [405], + "web": [200], + "default": [200], + } + }, + } + } + self.assertEqual(self._run(apps), ["api.example.com=405"]) + + def test_several_codes_of_one_domain_are_joined(self): + apps = { + "web-app-foo": { + "domains": {"canonical": ["foo.example.com"]}, + "server": {"status_codes": {"default": [200, 403, 404]}}, + } + } + self.assertEqual(self._run(apps), ["foo.example.com=403,404"]) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_skip_domains.py b/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_skip_domains.py index 2ab1e503f5..8fcc53d0c1 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_skip_domains.py +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_skip_domains.py @@ -24,6 +24,13 @@ class _DummyTemplar: self.available_variables = available_variables or {} +def _app(service_enabled, domain="filer.example.com"): + return { + "server": {"domains": {"canonical": {"filer": domain}}}, + "services": {"filer": {"enabled": service_enabled, "domains": ["filer"]}}, + } + + class CspSkipDomainsLookupTests(unittest.TestCase): @classmethod def setUpClass(cls): @@ -45,89 +52,47 @@ class CspSkipDomainsLookupTests(unittest.TestCase): def test_empty_applications_returns_empty_list(self): self.assertEqual(self._run({}), []) - def test_app_with_status_code_ge_400_skips_canonical_and_aliases(self): - apps = { - "web-app-bridgy": { - "domains": { - "canonical": ["bridgy.example.com"], - "aliases": ["fed.example.com"], - }, - "server": { - "status_codes": {"default": [200, 404]}, - }, - } - } - self.assertEqual(self._run(apps), ["bridgy.example.com", "fed.example.com"]) + def test_non_mapping_applications_returns_empty(self): + self.assertEqual(self._run([]), []) - def test_app_without_status_code_ge_400_is_not_skipped(self): + def test_a_disabled_service_hides_its_canonical_domain(self): + self.assertEqual( + self._run({"web-app-seaweedfs": _app(False)}), + ["filer.example.com"], + ) + + def test_an_enabled_service_keeps_its_domain_under_probe(self): + self.assertEqual(self._run({"web-app-seaweedfs": _app(True)}), []) + + def test_a_service_without_domains_is_ignored(self): apps = { "web-app-foo": { - "domains": {"canonical": ["foo.example.com"]}, - "server": { - "status_codes": {"default": [200]}, - }, + "server": {"domains": {"canonical": {"web": "foo.example.com"}}}, + "services": {"worker": {"enabled": False}}, } } self.assertEqual(self._run(apps), []) - def test_app_without_status_codes_field_is_not_skipped(self): - apps = {"web-app-foo": {"domains": {"canonical": ["foo.example.com"]}}} - self.assertEqual(self._run(apps), []) - - def test_group_names_selection_filters_apps(self): + def test_the_selection_filters_which_apps_are_inspected(self): apps = { - "web-app-bridgy": { - "domains": {"canonical": ["bridgy.example.com"]}, - "server": { - "status_codes": {"default": [404]}, - }, - }, - "web-app-other": { - "domains": {"canonical": ["other.example.com"]}, - "server": { - "status_codes": {"default": [404]}, - }, - }, + "web-app-a": _app(False, "a.example.com"), + "web-app-b": _app(False, "b.example.com"), } self.assertEqual( - self._run(apps, group_names=["web-app-bridgy"]), - ["bridgy.example.com"], + self._run(apps, group_names=["web-app-a"]), + ["a.example.com"], ) def test_group_names_csv_string_is_accepted(self): apps = { - "a": { - "domains": {"canonical": ["a.example.com"]}, - "server": { - "status_codes": {"default": [404]}, - }, - }, - "b": { - "domains": {"canonical": ["b.example.com"]}, - "server": { - "status_codes": {"default": [404]}, - }, - }, + "web-app-a": _app(False, "a.example.com"), + "web-app-b": _app(False, "b.example.com"), } self.assertEqual( - self._run(apps, group_names="a,b"), + self._run(apps, group_names="web-app-a,web-app-b"), ["a.example.com", "b.example.com"], ) - def test_non_4xx_codes_dont_count(self): - apps = { - "web-app-foo": { - "domains": {"canonical": ["foo.example.com"]}, - "server": { - "status_codes": {"default": [200, 301, 302]}, - }, - } - } - self.assertEqual(self._run(apps), []) - - def test_non_mapping_applications_returns_empty(self): - self.assertEqual(self._run([]), []) - if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/test_accept_status_reaches_onions.py b/tests/unit/python/roles/sys-ctl-hlth-csp/test_accept_status_reaches_onions.py new file mode 100644 index 0000000000..770713510c --- /dev/null +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/test_accept_status_reaches_onions.py @@ -0,0 +1,57 @@ +import importlib.util +import unittest + +from . import PROJECT_ROOT + +SCRIPT = PROJECT_ROOT / "roles" / "sys-ctl-hlth-csp" / "files" / "python" / "script.py" +ONION = "mirror.b5abfs7uwr23x6vbjxqjatyscpmkm6qkmkla7eyapdi4zpwtrz6o4nqd.onion" +DOMAINS = ["mirror.infinito.test", ONION, "html.infinito.test"] + + +def _expand(accept_status, domains=None): + spec = importlib.util.spec_from_file_location("csp_wrapper", SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module.expand_accept_status( + accept_status, DOMAINS if domains is None else domains + ) + + +class TestAcceptStatusReachesOnions(unittest.TestCase): + def test_the_onion_sibling_inherits_the_declaration(self): + expanded = _expand(["mirror.infinito.test=404"]) + + self.assertIn( + f"{ONION}=404", + expanded, + "the checker matches accepted codes by hostname, so a code declared " + "for the clearnet vhost never reaches its onion twin on its own", + ) + + def test_a_vhost_without_an_onion_twin_gains_nothing(self): + self.assertEqual( + _expand(["html.infinito.test=403"]), ["html.infinito.test=403"] + ) + + def test_several_codes_carry_over_unchanged(self): + expanded = _expand(["mirror.infinito.test=301,302,404"]) + + self.assertIn(f"{ONION}=301,302,404", expanded) + + def test_an_onion_entry_is_not_expanded_again(self): + self.assertEqual(_expand([f"{ONION}=404"]), [f"{ONION}=404"]) + + def test_an_entry_without_codes_is_left_alone(self): + self.assertEqual(_expand(["mirror.infinito.test"]), ["mirror.infinito.test"]) + + def test_only_the_matching_label_is_extended(self): + expanded = _expand(["html.infinito.test=403", "mirror.infinito.test=404"]) + + self.assertEqual( + [e for e in expanded if e.endswith(".onion=404")], [f"{ONION}=404"] + ) + self.assertEqual([e for e in expanded if e.endswith(".onion=403")], []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/test_list_flags_are_separated.py b/tests/unit/python/roles/sys-ctl-hlth-csp/test_list_flags_are_separated.py new file mode 100644 index 0000000000..59fb813bef --- /dev/null +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/test_list_flags_are_separated.py @@ -0,0 +1,55 @@ +import importlib.util +import unittest + +from . import PROJECT_ROOT + +SCRIPT = PROJECT_ROOT / "roles" / "sys-ctl-hlth-csp" / "files" / "python" / "script.py" +URLS = ["https://a.test/", "https://b.test/"] + + +def _load(): + spec = importlib.util.spec_from_file_location("csp_wrapper", SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _cmd(**kwargs): + return _load().build_docker_cmd( + image="img", + urls=URLS, + short_mode=False, + ignore_network_blocks_from=kwargs.get("ignore", []), + accept_status=kwargs.get("accept", []), + ) + + +class TestListFlagsAreSeparatedFromUrls(unittest.TestCase): + def test_accept_status_is_separated_from_the_urls(self): + cmd = _cmd(accept=["a.test=403"]) + + self.assertEqual( + cmd[cmd.index("--accept-status") + 2], + "--", + "the checker consumes every token after a list flag that does not " + "start with '--', and a URL does not, so the URLs would be read as " + "more status declarations", + ) + + def test_two_list_flags_share_a_single_separator(self): + cmd = _cmd(ignore=["x.test"], accept=["y.test=403"]) + + self.assertEqual(cmd.count("--"), 1) + self.assertLess(cmd.index("--"), cmd.index(URLS[0])) + + def test_without_a_list_flag_no_separator_is_emitted(self): + self.assertNotIn("--", _cmd()) + + def test_every_url_survives_the_separator(self): + cmd = _cmd(accept=["y.test=403"]) + + self.assertEqual(cmd[cmd.index("--") + 1 :], URLS) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/test_onion_timeout_is_passed.py b/tests/unit/python/roles/sys-ctl-hlth-csp/test_onion_timeout_is_passed.py new file mode 100644 index 0000000000..5a1679b0f9 --- /dev/null +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/test_onion_timeout_is_passed.py @@ -0,0 +1,36 @@ +import re +import unittest + +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +TASKS = PROJECT_ROOT / "roles" / "sys-ctl-hlth-csp" / "tasks" / "00_core.yml" +_TOR_BRANCH = re.compile(r"--tor-proxy=.{0,200}?--onion-timeout=", re.DOTALL) +_START_BUDGET = re.compile( + r"timeout_start_sec_for_domains\(\s*onion_per_domain_seconds=", re.DOTALL +) + + +class TestOnionTimeoutIsPassed(unittest.TestCase): + def test_the_tor_branch_also_carries_the_onion_budget(self) -> None: + self.assertRegex( + read_text(str(TASKS)), + _TOR_BRANCH, + "the service reaches onion vhosts over Tor, where the checker's own " + "20 s navigation budget expires before a heavy page finishes; pass " + "--onion-timeout wherever --tor-proxy is passed", + ) + + def test_the_unit_start_budget_knows_the_onion_rate(self) -> None: + self.assertRegex( + read_text(str(TASKS)), + _START_BUDGET, + "TimeoutStartSec defaults to 25 s per domain, which an onion vhost " + "with a multiplied navigation budget outlasts; systemd then kills " + "the check mid-run instead of letting it report", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/test_unit_flags_are_parsable.py b/tests/unit/python/roles/sys-ctl-hlth-csp/test_unit_flags_are_parsable.py new file mode 100644 index 0000000000..759832c95a --- /dev/null +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/test_unit_flags_are_parsable.py @@ -0,0 +1,75 @@ +import re +import subprocess +import sys +import unittest + +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +ROLE = PROJECT_ROOT / "roles" / "sys-ctl-hlth-csp" +TASKS = ROLE / "tasks" / "00_core.yml" +SCRIPT = ROLE / "files" / "python" / "script.py" + +_FLAG = re.compile(r"'\s*(--[a-z][a-z0-9-]*)") +_VALUE = { + "--nginx-config-dir": "/nonexistent", + "--image": "img", + "--tor-proxy": "socks5://127.0.0.1:9050", + "--onion-timeout": "1000", +} +_LIST_VALUE = { + "--ignore-network-blocks-from": "a.test", + "--skip-domain": "a.test", + "--accept-status": "a.test=403", +} + + +def _flags_the_unit_passes() -> set[str]: + return set(_FLAG.findall(read_text(str(TASKS)))) + + +def _invoke(flag: str) -> subprocess.CompletedProcess: + argv = [ + sys.executable, + str(SCRIPT), + "--nginx-config-dir", + "/nonexistent", + "--image", + "img", + ] + if flag in _LIST_VALUE: + argv.extend([flag, _LIST_VALUE[flag]]) + elif flag in _VALUE and flag not in ("--nginx-config-dir", "--image"): + argv.extend([flag, _VALUE[flag]]) + elif flag not in _VALUE: + argv.append(flag) + return subprocess.run(argv, capture_output=True, text=True, timeout=60, check=False) + + +class TestUnitFlagsAreParsable(unittest.TestCase): + def test_the_unit_passes_at_least_the_known_flags(self): + found = _flags_the_unit_passes() + + self.assertIn("--accept-status", found) + self.assertIn("--onion-timeout", found) + + def test_every_flag_the_unit_passes_is_accepted_by_the_script(self): + for flag in sorted(_flags_the_unit_passes()): + with self.subTest(flag=flag): + completed = _invoke(flag) + self.assertNotIn( + "unrecognized arguments", + completed.stderr, + f"the systemd unit passes {flag} but script.py rejects it, " + f"which fails the service with status=2/INVALIDARGUMENT", + ) + + def test_an_undeclared_flag_is_still_rejected(self): + completed = _invoke("--definitely-not-a-flag") + + self.assertIn("unrecognized arguments", completed.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-ctl-hlth-disc-space/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-disc-space/files/test_script.py index bdf7622a42..9e97a4528e 100755 --- a/tests/unit/python/roles/sys-ctl-hlth-disc-space/files/test_script.py +++ b/tests/unit/python/roles/sys-ctl-hlth-disc-space/files/test_script.py @@ -92,7 +92,7 @@ class TestDiskSpaceScript(TestCase): with contextlib.redirect_stdout(buffer), self.assertRaises(SystemExit): SCRIPT_MODULE.main() - mock_exit.assert_called_once_with(2) + mock_exit.assert_called_once_with(1) output = buffer.getvalue() self.assertIn("Checking disk space usage...", output) diff --git a/tests/unit/python/roles/sys-ctl-hlth-volumes/files/test_hlth_volumes_script.py b/tests/unit/python/roles/sys-ctl-hlth-volumes/files/test_hlth_volumes_script.py index 913893871c..0bc37be75b 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-volumes/files/test_hlth_volumes_script.py +++ b/tests/unit/python/roles/sys-ctl-hlth-volumes/files/test_hlth_volumes_script.py @@ -1,4 +1,5 @@ import os +import socket import subprocess import tempfile import unittest @@ -15,11 +16,22 @@ VOL_B = "b" * 64 CONTAINER_STUB = """#!/usr/bin/env bash if [ "$1" = "volume" ] && [ "$2" = "ls" ]; then \tif [[ "$*" == *"driver=local"* ]]; then +\t\tif [ -n "$STUB_NFS_VOLUMES" ]; then +\t\t\tprintf '%s\\n' $STUB_NFS_VOLUMES +\t\tfi \t\texit 0 \tfi \tprintf '%s\\n' $STUB_VOLUMES \texit 0 fi +if [ "$1" = "volume" ] && [ "$2" = "inspect" ]; then +\tcase "$*" in +\t\t*Options.type*) printf 'nfs\\n' ;; +\t\t*Options.device*) printf ':/export\\n' ;; +\t\t*Options.o*) printf 'addr=127.0.0.1\\n' ;; +\tesac +\texit 0 +fi if [ "$1" = "ps" ]; then \targs="$*" \tvol="${args##*volume=}" @@ -43,7 +55,9 @@ exit 0 class TestHlthVolumesScript(unittest.TestCase): - def run_script(self, *, volumes, containers, mounts, running=None, whitelist=""): + def run_script( + self, *, volumes, containers, mounts, running=None, whitelist="", nfs=() + ): """Run the health script against a stubbed container CLI. Args: @@ -53,6 +67,8 @@ class TestHlthVolumesScript(unittest.TestCase): running: volume name -> the subset of those ids still running; a volume absent here has no running container left. whitelist: value for the script's only positional argument. + nfs: nfs-backed volume names; their server is 127.0.0.1, whose + port 2049 refuses the connection in the test environment. Returns: Tuple of the exit code and stdout. @@ -66,6 +82,7 @@ class TestHlthVolumesScript(unittest.TestCase): env = dict(os.environ) env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}" env["STUB_VOLUMES"] = " ".join(volumes) + env["STUB_NFS_VOLUMES"] = " ".join(nfs) for volume, ids in containers.items(): env[f"STUB_CONTAINERS_{volume}"] = ids env[f"STUB_RUNNING_{volume}"] = running.get(volume, "") @@ -124,6 +141,30 @@ class TestHlthVolumesScript(unittest.TestCase): self.assertEqual(code, 1) self.assertIn("is not used by any container", out) + def test_an_unreachable_nfs_server_fails_the_probe(self): + code, _ = self.run_script( + volumes=[VOL_B], + containers={}, + mounts={}, + whitelist=VOL_B, + nfs=[VOL_A], + ) + self.assertEqual(code, 1) + + def test_a_listening_nfs_port_passes(self): + with socket.socket() as server: + server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + server.bind(("127.0.0.1", 2049)) + server.listen(1) + code, _ = self.run_script( + volumes=[VOL_B], + containers={}, + mounts={}, + whitelist=VOL_B, + nfs=[VOL_A], + ) + self.assertEqual(code, 0) + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/sys-ctl-hlth-webserver/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-webserver/files/test_script.py index ff99bd0adc..ac58907870 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-webserver/files/test_script.py +++ b/tests/unit/python/roles/sys-ctl-hlth-webserver/files/test_script.py @@ -131,7 +131,7 @@ class TestStandaloneCheckerScript(unittest.TestCase): exp_json, ] ) - self.assertEqual(exit_code, 2) + self.assertEqual(exit_code, 1) self.assertIn( "foo.example.org: ERROR: No expectations provided. Got 200.", output ) diff --git a/tests/unit/python/roles/sys-ctl-hlth-webserver/filter_plugins/test_web_health_expectations.py b/tests/unit/python/roles/sys-ctl-hlth-webserver/filter_plugins/test_web_health_expectations.py index e7e1050aa8..6ff7f937e6 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-webserver/filter_plugins/test_web_health_expectations.py +++ b/tests/unit/python/roles/sys-ctl-hlth-webserver/filter_plugins/test_web_health_expectations.py @@ -562,7 +562,7 @@ class TestWebHealthExpectationsFilter(unittest.TestCase): def _tor_app(self, canonical=None, status_codes=None, **tor): returns = { ("app-a", "domains.canonical"): ( - ["a.infinito.example"] if canonical is None else canonical + ["a.infinito.test"] if canonical is None else canonical ), } if status_codes is not None: @@ -575,7 +575,7 @@ class TestWebHealthExpectationsFilter(unittest.TestCase): out = self.mod.web_health_expectations( apps, group_names=["app-a"], - primary_domain="infinito.example", + primary_domain="infinito.test", node_onion=self.ONION, ) self.assertEqual(out, {f"a.{self.ONION}": [200, 302, 301]}) @@ -585,59 +585,57 @@ class TestWebHealthExpectationsFilter(unittest.TestCase): out = self.mod.web_health_expectations( apps, group_names=["app-a"], - primary_domain="infinito.example", + primary_domain="infinito.test", node_onion=self.ONION, ) self.assertEqual( out, { - "a.infinito.example": [200, 302, 301], + "a.infinito.test": [200, 302, 301], f"a.{self.ONION}": [200, 302, 301], }, ) def test_onion_inherits_clearnet_status_codes(self): apps = self._tor_app( - canonical={"default": ["a.infinito.example"]}, + canonical={"default": ["a.infinito.test"]}, status_codes={"default": [301, 200]}, exclusive=True, ) out = self.mod.web_health_expectations( apps, group_names=["app-a"], - primary_domain="infinito.example", + primary_domain="infinito.test", node_onion=self.ONION, ) self.assertEqual(out, {f"a.{self.ONION}": [301, 200]}) def test_onion_disabled_app_stays_clearnet(self): - self._configure_returns( - {("app-a", "domains.canonical"): ["a.infinito.example"]} - ) + self._configure_returns({("app-a", "domains.canonical"): ["a.infinito.test"]}) apps = {"app-a": {"services": {"tor": {"enabled": False}}}} out = self.mod.web_health_expectations( apps, group_names=["app-a"], - primary_domain="infinito.example", + primary_domain="infinito.test", node_onion=self.ONION, ) - self.assertEqual(out, {"a.infinito.example": [200, 302, 301]}) + self.assertEqual(out, {"a.infinito.test": [200, 302, 301]}) def test_onion_skipped_without_node_onion(self): apps = self._tor_app(exclusive=True) out = self.mod.web_health_expectations( apps, group_names=["app-a"], - primary_domain="infinito.example", + primary_domain="infinito.test", node_onion="", ) - self.assertEqual(out, {"a.infinito.example": [200, 302, 301]}) + self.assertEqual(out, {"a.infinito.test": [200, 302, 301]}) # --------- Reverse-proxy bare apex gating --------- def _proxy_apex_app(self, **tor): self._configure_returns( - {("svc-prx-openresty", "domains.canonical"): ["infinito.example"]} + {("svc-prx-openresty", "domains.canonical"): ["infinito.test"]} ) services = {"tor": {"enabled": True, **tor}} if tor else {} return {"svc-prx-openresty": {"services": services}} @@ -646,7 +644,7 @@ class TestWebHealthExpectationsFilter(unittest.TestCase): out = self.mod.web_health_expectations( self._proxy_apex_app(), group_names=["svc-prx-openresty"], - primary_domain="infinito.example", + primary_domain="infinito.test", ) self.assertEqual(out, {}) @@ -654,15 +652,15 @@ class TestWebHealthExpectationsFilter(unittest.TestCase): out = self.mod.web_health_expectations( self._proxy_apex_app(), group_names=["svc-prx-openresty", "web-opt-rdr-domains"], - primary_domain="infinito.example", + primary_domain="infinito.test", ) - self.assertEqual(out, {"infinito.example": [200, 302, 301]}) + self.assertEqual(out, {"infinito.test": [200, 302, 301]}) def test_onion_apex_dropped_when_rdr_domains_not_deployed(self): out = self.mod.web_health_expectations( self._proxy_apex_app(exclusive=True), group_names=["svc-prx-openresty"], - primary_domain="infinito.example", + primary_domain="infinito.test", node_onion=self.ONION, ) self.assertEqual(out, {}) diff --git a/tests/unit/python/roles/sys-stk-backend/test_handler_registration_order.py b/tests/unit/python/roles/sys-stk-backend/test_handler_registration_order.py new file mode 100644 index 0000000000..2d3b278a69 --- /dev/null +++ b/tests/unit/python/roles/sys-stk-backend/test_handler_registration_order.py @@ -0,0 +1,173 @@ +"""A role may only notify a handler topic that is already registered.""" + +from __future__ import annotations + +import re +import unittest + +from utils.cache.files import PROJECT_ROOT, iter_project_files_with_content, read_text +from utils.cache.yaml import load_yaml_str +from utils.roles.mapping import ROLE_FILE_TASKS_MAIN + +BACKEND = PROJECT_ROOT / "roles/sys-stk-backend" / ROLE_FILE_TASKS_MAIN +RDBMS_DEDICATED = PROJECT_ROOT / "roles/sys-svc-rdbms/tasks/dedicated.yml" +BLUESKY_CORE = PROJECT_ROOT / "roles/web-app-bluesky/tasks/00_core.yml" +BLUESKY_STAGING = tuple( + PROJECT_ROOT / "roles/web-app-bluesky/tasks" / name + for name in ("01_social_app.yml", "02_login_broker.yml", "03_pds.yml") +) +COMPOSE_OWNER = "sys-svc-compose" +_NOTIFY = re.compile(r"^\s*notify:\s*(?:\[\s*)?['\"]?(compose-[\w-]+)", re.MULTILINE) + + +def _role_include(task: dict) -> dict: + for key in ("include_role", "import_role"): + include = task.get(key) or task.get(f"ansible.builtin.{key}") + if isinstance(include, dict): + return include + return {} + + +def _role_includes(tasks: list) -> list[dict]: + includes = [] + for task in tasks: + include = _role_include(task) + if include.get("name"): + includes.append(include) + return includes + + +class TestHandlerRegistrationOrder(unittest.TestCase): + def test_the_backend_renders_the_stack_after_every_foreign_provider(self) -> None: + includes = _role_includes(load_yaml_str(read_text(str(BACKEND)))) + order = [include["name"] for include in includes] + self.assertIn(COMPOSE_OWNER, order) + render = next( + index + for index, include in enumerate(includes) + if include["name"] == COMPOSE_OWNER and not include.get("tasks_from") + ) + for provider in ("sys-svc-rdbms", "sys-svc-objstore", "sys-svc-engine"): + with self.subTest(provider=provider): + self.assertLess(order.index(provider), render) + + def test_the_owner_is_reloaded_directly_before_the_flush(self) -> None: + tasks = load_yaml_str(read_text(str(BACKEND))) + flush = next( + index + for index, task in enumerate(tasks) + if task.get("meta") == "flush_handlers" + or task.get("ansible.builtin.meta") == "flush_handlers" + ) + previous = tasks[flush - 1] + loader = _role_include(previous) + self.assertEqual(loader.get("name"), COMPOSE_OWNER) + self.assertEqual(loader.get("handlers_from"), "main") + + def test_the_notifier_registers_the_owner_before_its_first_notify(self) -> None: + loader = _role_include(load_yaml_str(read_text(str(RDBMS_DEDICATED)))[0]) + self.assertEqual(loader.get("name"), COMPOSE_OWNER) + self.assertEqual(loader.get("handlers_from"), "main") + + def test_bluesky_pre_compose_staging_notifies_no_compose_topic(self) -> None: + for path in BLUESKY_STAGING: + with self.subTest(path=path.name): + self.assertEqual( + _NOTIFY.findall(read_text(str(path))), + [], + "staging runs before sys-stk-backend, where any flush (the " + "container runtime's first one on a fresh host) would run " + "the compose handlers before ca-inject and compose.yml exist", + ) + + def test_bluesky_rebuilds_after_the_backend_renders_the_stack(self) -> None: + tasks = load_yaml_str(read_text(str(BLUESKY_CORE))) + backend = next( + index + for index, task in enumerate(tasks) + if _role_include(task).get("name") == "sys-stk-backend" + ) + rebuild = next( + index + for index, task in enumerate(tasks) + if {"compose-build", "compose-up"} <= set(task.get("notify") or []) + ) + self.assertGreater(rebuild, backend) + + def test_bluesky_flushes_its_own_compose_handlers_before_the_front_proxy( + self, + ) -> None: + tasks = load_yaml_str(read_text(str(BLUESKY_CORE))) + rebuild = next( + index + for index, task in enumerate(tasks) + if {"compose-build", "compose-up"} <= set(task.get("notify") or []) + ) + flush = next( + index + for index, task in enumerate(tasks) + if index > rebuild + and ( + task.get("meta") == "flush_handlers" + or task.get("ansible.builtin.meta") == "flush_handlers" + ) + ) + proxy = next( + index + for index, task in enumerate(tasks) + if _role_include(task).get("name") == "sys-stk-front-proxy" + ) + self.assertLess( + flush, + proxy, + "the front proxy pulls in svc-prx-openresty, which flushes; a " + "compose topic still pending there is run with openresty's " + "application_id and brings up its stack instead of this one", + ) + + loader = _role_include(tasks[flush - 1]) + self.assertEqual(loader.get("name"), COMPOSE_OWNER) + self.assertEqual( + loader.get("handlers_from"), + "main", + "the handler resolves its chdir from application_id at flush " + "time, so the topics are re-owned here rather than left on " + "whatever value the play happens to carry", + ) + + def test_the_notifier_bootstraps_the_compose_host_before_its_first_notify( + self, + ) -> None: + tasks = load_yaml_str(read_text(str(RDBMS_DEDICATED))) + bootstrap = next( + index + for index, task in enumerate(tasks) + if _role_include(task).get("tasks_from") == "00_core.yml" + ) + notify = next(index for index, task in enumerate(tasks) if task.get("notify")) + self.assertLess(bootstrap, notify) + self.assertIn( + "run_once_sys_svc_compose is not defined", str(tasks[bootstrap].get("when")) + ) + + def test_the_owner_still_holds_every_compose_topic_that_is_notified(self) -> None: + owner = "" + for path, content in iter_project_files_with_content( + extensions=(".yml",), exclude_tests=True + ): + if f"roles/{COMPOSE_OWNER}/handlers/" in path: + owner += content + notified = set() + for path, content in iter_project_files_with_content( + extensions=(".yml",), exclude_tests=True + ): + if "/roles/" in path: + notified.update(_NOTIFY.findall(content)) + self.assertTrue(notified) + for topic in sorted(notified): + with self.subTest(topic=topic): + self.assertIn(topic, owner) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-svc-compose-ca/files/test_compose_ca.py b/tests/unit/python/roles/sys-svc-compose-ca/files/test_compose_ca.py index 2efb48214b..cbc8e8a566 100644 --- a/tests/unit/python/roles/sys-svc-compose-ca/files/test_compose_ca.py +++ b/tests/unit/python/roles/sys-svc-compose-ca/files/test_compose_ca.py @@ -1,6 +1,7 @@ # tests/unit/python/roles/sys-svc-compose-ca/files/test_compose_ca_inject.py import importlib.util import json +import tempfile import unittest from pathlib import Path from unittest.mock import patch @@ -491,12 +492,12 @@ class TestComposeCaInject(unittest.TestCase): def fake_run(cmd, *, cwd, env, timeout=None, capture=True): calls.append(cmd) if cmd[:3] == ["docker", "image", "inspect"]: - return 1, "", "No such image: python:3.14-bookworm" + return 1, "", "No such image: python:3.14-slim" return 1, "", "unexpected" with patch.object(self.m, "run", side_effect=fake_run): exists, _ep, _cmd, _has_sh = self.m._gather_one_image( - "python:3.14-bookworm", cwd=Path("/tmp"), env={}, pull_if_absent=False + "python:3.14-slim", cwd=Path("/tmp"), env={}, pull_if_absent=False ) self.assertFalse(exists) self.assertFalse(any(c[:2] == ["docker", "pull"] for c in calls)) @@ -959,6 +960,53 @@ class TestComposeCaInject(unittest.TestCase): ["sh", "-lc", 'exec "$$CHESS_ENTRYPOINT_INT"'], ) + def test_render_override_points_the_replacing_vars_at_the_bundle(self): + """A host that has a CA bundle gets the verifying vars pointed at it. + + SSL_CERT_FILE, CURL_CA_BUNDLE and REQUESTS_CA_BUNDLE replace the trust + store, so leaving them on the single root CA is what stops a container + from reaching any public HTTPS endpoint. NODE_EXTRA_CA_CERTS is + additive and stays on the root CA, and CA_TRUST_CERT stays single + because the anchor installers take one certificate. + """ + services = {"svc": {"image": "img:1"}} + service_to_cmd = {"svc": ["docker", "compose", "-p", "p", "-f", "compose.yml"]} + + with tempfile.TemporaryDirectory() as tmp: + ca_host = Path(tmp) / "root-ca.crt" + ca_host.write_text("root\n") + (Path(tmp) / "ca-bundle.crt").write_text("root\npublic\n") + + with ( + patch.object(self.m, "ensure_image_available"), + patch.object(self.m, "docker_image_inspect"), + patch.object(self.m, "docker_image_has_bin_sh"), + ): + doc = self.m.render_override( + services, + service_to_cmd, + cwd=Path("/tmp"), + env={}, + ca_host=str(ca_host), + wrapper_host="/host/with-ca-trust.sh", + ca_container=CA_CERT_CONTAINER, + wrapper_container=CA_WRAPPER_CONTAINER, + trust_name="infinito.local", + wrap=False, + ) + + out = doc["services"]["svc"] + bundle_container = str(Path(CA_CERT_CONTAINER).parent / "ca-bundle.crt") + self.assertIn( + f"{Path(tmp) / 'ca-bundle.crt'}:{bundle_container}:ro", out["volumes"] + ) + for key in ("SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE"): + self.assertEqual(out["environment"].get(key), bundle_container) + self.assertEqual( + out["environment"].get("NODE_EXTRA_CA_CERTS"), CA_CERT_CONTAINER + ) + self.assertEqual(out["environment"].get("CA_TRUST_CERT"), CA_CERT_CONTAINER) + def test_render_override_no_wrapper_emits_env_and_mounts_only(self): """ render_override(wrap=False): swarm path must emit only volumes + environment, diff --git a/tests/unit/python/roles/sys-svc-compose/files/test_service_converged.py b/tests/unit/python/roles/sys-svc-compose/files/test_service_converged.py new file mode 100644 index 0000000000..93843c1fe7 --- /dev/null +++ b/tests/unit/python/roles/sys-svc-compose/files/test_service_converged.py @@ -0,0 +1,141 @@ +"""Behaviour of the swarm service convergence probe. + +``service_converged.sh`` gates a swarm deploy on one service and is driven by an +Ansible ``until`` loop of up to 600 polls, so both its verdict and how much it +prints on a failing poll matter. Exercised here against a stub docker: a running +service passes silently, every refusal names its reason on stderr, and only the +branch that has task rows to show prints them, filtered to the rows carrying an +error. +""" + +from __future__ import annotations + +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils.cache.files import PROJECT_ROOT + +PROBE = ( + PROJECT_ROOT + / "roles" + / "sys-svc-compose" + / "files" + / "shell" + / "swarm" + / "service_converged.sh" +) +STUB = """#!/usr/bin/env bash +case "$1 $2" in +"service inspect") printf '%s' "${UPDATE_STATE}" ;; +"service ps") + case "$*" in + *--filter*) printf '%s' "${FILTERED_PS}" ;; + *) printf '%s' "${FULL_PS}" ;; + esac + ;; +esac +exit "${PS_RC:-0}" +""" + + +class TestServiceConverged(unittest.TestCase): + def _run( + self, + update_state: str = "", + filtered_ps: str = "", + full_ps: str = "", + ps_rc: str = "0", + ) -> subprocess.CompletedProcess: + with tempfile.TemporaryDirectory() as tmp: + stub_bin = Path(tmp) / "bin" + stub_bin.mkdir() + container = stub_bin / "container" + container.write_text(STUB) + container.chmod(0o755) + timeout = stub_bin / "timeout" + timeout.write_text('#!/usr/bin/env bash\nshift\nexec "$@"\n') + timeout.chmod(0o755) + env = dict(os.environ) + env.update( + { + "PATH": f"{stub_bin}:{env['PATH']}", + "SERVICE": "demo_app", + "UPDATE_STATE": update_state, + "FILTERED_PS": filtered_ps, + "FULL_PS": full_ps, + "PS_RC": ps_rc, + } + ) + return subprocess.run( + ["bash", str(PROBE)], + env=env, + capture_output=True, + text=True, + check=False, + ) + + def test_running_service_passes_without_output(self): + proc = self._run( + update_state="completed", filtered_ps="Running 2 minutes ago\n" + ) + self.assertEqual(proc.returncode, 0) + self.assertEqual(proc.stderr, "") + + def test_update_in_progress_is_worth_another_poll(self): + proc = self._run(update_state="updating", filtered_ps="Running 2 minutes ago\n") + self.assertEqual(proc.returncode, 1) + self.assertIn("UpdateStatus.State=updating", proc.stderr) + + def test_latched_update_gives_up_instead_of_polling(self): + for latched in ("paused", "rollback_paused"): + with self.subTest(state=latched): + proc = self._run( + update_state=latched, + filtered_ps="Running 2 minutes ago\n", + full_ps="demo_app.1 node-a Shutdown Failed error=task: non-zero exit (1)\n", + ) + self.assertEqual(proc.returncode, 2) + self.assertIn(f"UpdateStatus.State={latched}", proc.stderr) + self.assertIn("cannot leave this state on its own", proc.stderr) + + def test_a_rolled_back_update_is_not_reported_as_converged(self): + for reverted in ("rollback_started", "rollback_completed"): + with self.subTest(state=reverted): + proc = self._run( + update_state=reverted, + filtered_ps="Running 2 minutes ago\n", + full_ps="demo_app.1 node-a Shutdown Failed error=task: non-zero exit (1)\n", + ) + self.assertEqual(proc.returncode, 2) + self.assertIn(f"UpdateStatus.State={reverted}", proc.stderr) + self.assertIn("not the desired one", proc.stderr) + + def test_missing_desired_running_task_is_named(self): + proc = self._run(filtered_ps="") + self.assertEqual(proc.returncode, 1) + self.assertIn("no task carries desired-state=running", proc.stderr) + + def test_failing_service_ps_is_named_instead_of_leaking_its_code(self): + proc = self._run(ps_rc="124") + self.assertEqual(proc.returncode, 1) + self.assertIn("service ps failed or timed out", proc.stderr) + + def test_pending_tasks_report_only_the_rows_carrying_an_error(self): + proc = self._run( + filtered_ps="Preparing\n", + full_ps=( + "demo_app.1 node-a Running Preparing error=\n" + "demo_app.2 node-b Shutdown Failed error=task: non-zero exit (1)\n" + ), + ) + self.assertEqual(proc.returncode, 1) + self.assertIn("tasks not running yet", proc.stderr) + self.assertIn("demo_app.2", proc.stderr) + self.assertNotIn("demo_app.1", proc.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-svc-compose/files/test_stack_ready.py b/tests/unit/python/roles/sys-svc-compose/files/test_stack_ready.py index 14c0eefed1..3b2532acaf 100644 --- a/tests/unit/python/roles/sys-svc-compose/files/test_stack_ready.py +++ b/tests/unit/python/roles/sys-svc-compose/files/test_stack_ready.py @@ -16,6 +16,14 @@ only the grace-gated strike counter may end it - never on the newest row alone, and never on errors left below a finished attempt. That counter is armed off the service's own ``UpdatedAt``, so an unreadable epoch has to keep the caller waiting rather than arm it. + +A service whose ``UpdateStatus`` latched or rolled back is terminal on its own, +without any task row: swarm will not leave that state until the next stack +deploy, and a revert leaves the replica count full for the previous spec. A +service still ``updating`` keeps the caller waiting instead, and so does a +service whose desired replicas are only met by old-spec tasks that have not been +replaced yet - docker's own replica column counts those as running, so the gate +counts the tasks carrying desired-state=running rather than reading that column. """ from __future__ import annotations @@ -41,9 +49,21 @@ GATE = ( STUB = """#!/usr/bin/env bash case "$1 $2" in "stack services") printf '%s' "${STACK_SERVICES}" ;; -"service inspect") printf '%s' "${SERVICE_UPDATED_AT}" ;; +"service inspect") + case "$4" in + *UpdatedAt*) printf '%s' "${SERVICE_UPDATED_AT}" ;; + *StartedAt*) + [ -n "${INSPECT_STARTEDAT_FAILS}" ] && exit 1 + printf '%s' "${SERVICE_INSPECT}" + ;; + *) printf '%s' "${SERVICE_INSPECT_PLAIN:-${SERVICE_INSPECT}}" ;; + esac + ;; "service ps") - case "$5" in + case "$*" in + *'desired-state=running'*) + printf '%s' "${SERVICE_RUNNING}" | awk -F'|' -v s="$3" '$1 == s { print $2 }' + ;; *'{{.Name}}|{{.CurrentState}}|{{.Error}}'*) printf '%s' "${SERVICE_ERRORS}" ;; *) printf '%s' "${SERVICE_PS}" ;; esac @@ -51,6 +71,11 @@ case "$1 $2" in esac exit 0 """ +WEB_THREE_RUNNING = ( + "demo_web|Running 2 minutes ago\n" + "demo_web|Running 2 minutes ago\n" + "demo_web|Running 2 minutes ago\n" +) class TestStackReady(unittest.TestCase): @@ -59,8 +84,14 @@ class TestStackReady(unittest.TestCase): services: str, service_ps: str = "", service_errors: str = "", + service_inspect: str = "", + service_running: str = "", churning: int = 0, updated_at: str | None = None, + deploy_since: str = "", + deployed_services: str = "", + inspect_startedat_fails: bool = False, + service_inspect_plain: str = "", ) -> subprocess.CompletedProcess: """Poll the gate once, ``churning`` seconds into a non-converged deploy. @@ -68,8 +99,17 @@ class TestStackReady(unittest.TestCase): services: ``docker stack services`` table the stub returns. service_ps: verbose ``docker service ps`` table for the report. service_errors: ``name|current state|error`` rows, newest first. + service_inspect: ``name update-state`` rows for the latched check. + service_running: ``service|current state`` rows carrying + desired-state=running, one per task of the current spec. churning: seconds since the deploy bumped the service ``UpdatedAt``. updated_at: raw ``UpdatedAt`` epoch, overriding ``churning``. + deploy_since: epoch seconds the deploy stamped before it ran. + deployed_services: space-separated services the deploy reported + creating or updating. + inspect_startedat_fails: reject the StartedAt format, as an older + docker would. + service_inspect_plain: rows the fallback format returns. """ if updated_at is None: updated_at = str(int(time.time()) - churning) @@ -90,7 +130,13 @@ class TestStackReady(unittest.TestCase): STACK_SERVICES=services, SERVICE_PS=service_ps, SERVICE_ERRORS=service_errors, + SERVICE_INSPECT=service_inspect, + SERVICE_RUNNING=service_running, SERVICE_UPDATED_AT=updated_at, + DEPLOY_SINCE=deploy_since, + DEPLOYED_SERVICES=deployed_services, + INSPECT_STARTEDAT_FAILS="1" if inspect_startedat_fails else "", + SERVICE_INSPECT_PLAIN=service_inspect_plain, PATH=f"{stub_bin}:{env['PATH']}", BASH_ENV="", ) @@ -102,8 +148,144 @@ class TestStackReady(unittest.TestCase): check=False, ) + def test_a_service_with_no_update_in_flight_converges(self) -> None: + proc = self._run( + "demo_web 3/3\n", + service_inspect="demo_web none\n", + service_running=WEB_THREE_RUNNING, + ) + self.assertEqual(proc.returncode, 0) + + def test_an_update_in_flight_keeps_the_caller_waiting(self) -> None: + proc = self._run( + "demo_web 3/3\n", + service_ps="demo_web.1 desired=Running current=Starting error=\n", + service_inspect="demo_web updating\n", + service_running=WEB_THREE_RUNNING, + ) + self.assertEqual(proc.returncode, 1) + self.assertIn("demo_web(updating)", proc.stderr) + self.assertIn("rolling update still in flight", proc.stderr) + + def test_the_previous_rounds_completed_update_does_not_count_as_converged( + self, + ) -> None: + proc = self._run( + "demo_web 3/3\n", + service_inspect="demo_web completed 1788397200\n", + service_running=WEB_THREE_RUNNING, + deploy_since="1788398643", + deployed_services="demo_web", + ) + self.assertEqual(proc.returncode, 1) + self.assertIn("demo_web(pending)", proc.stderr) + + def test_a_service_the_deploy_left_alone_converges_on_its_old_update( + self, + ) -> None: + proc = self._run( + "demo_web 3/3\n", + service_inspect="demo_web completed 1788397200\n", + service_running=WEB_THREE_RUNNING, + deploy_since="1788398643", + deployed_services="demo_other", + ) + self.assertEqual(proc.returncode, 0) + + def test_an_update_registered_after_the_deploy_converges(self) -> None: + proc = self._run( + "demo_web 3/3\n", + service_inspect="demo_web completed 1788398649\n", + service_running=WEB_THREE_RUNNING, + deploy_since="1788398643", + deployed_services="demo_web", + ) + self.assertEqual(proc.returncode, 0) + + def test_a_stamp_that_is_not_epoch_seconds_disables_the_check(self) -> None: + proc = self._run( + "demo_web 3/3\n", + service_inspect="demo_web completed 2026-09-03 01:00:00 +0000 UTC\n", + service_running=WEB_THREE_RUNNING, + deploy_since="2026-09-03T01:24:03Z", + deployed_services="demo_web", + ) + self.assertEqual(proc.returncode, 0) + + def test_a_docker_that_rejects_the_stamp_format_falls_back_instead_of_stalling( + self, + ) -> None: + proc = self._run( + "demo_web 3/3\n", + service_running=WEB_THREE_RUNNING, + deploy_since="1788398643", + deployed_services="demo_web", + inspect_startedat_fails=True, + service_inspect_plain="demo_web completed -\n", + ) + self.assertEqual(proc.returncode, 0) + + def test_a_service_without_a_recorded_update_start_is_left_alone(self) -> None: + proc = self._run( + "demo_web 3/3\n", + service_inspect="demo_web completed -\n", + service_running=WEB_THREE_RUNNING, + deploy_since="1788398643", + deployed_services="demo_web", + ) + self.assertEqual(proc.returncode, 0) + + def test_without_a_deploy_stamp_the_gate_keeps_its_old_behaviour(self) -> None: + proc = self._run( + "demo_web 3/3\n", + service_inspect="demo_web completed 1788397200\n", + service_running=WEB_THREE_RUNNING, + ) + self.assertEqual(proc.returncode, 0) + + def test_old_spec_tasks_left_running_do_not_fill_the_replica_count(self) -> None: + """Docker's replica column counts every Running task, draining old-spec + ones included, so a stack mid-rollout reads as full.""" + proc = self._run( + "demo_web 3/3\n", + service_ps="demo_web.1 desired=Running current=Preparing error=\n", + service_inspect="demo_web completed\n", + service_running=( + "demo_web|Running 2 minutes ago\ndemo_web|Running 2 minutes ago\n" + ), + ) + self.assertEqual(proc.returncode, 1) + self.assertIn("not converged", proc.stderr) + self.assertIn("demo_web", proc.stderr) + + def test_a_latched_update_gives_up_instead_of_polling(self) -> None: + for latched in ("paused", "rollback_paused"): + with self.subTest(state=latched): + proc = self._run( + "demo_web 3/3\n", + service_ps="demo_web.1 desired=Shutdown current=Failed error=oom\n", + service_inspect=f"demo_web {latched}\n", + ) + self.assertEqual(proc.returncode, 2) + self.assertIn(f"demo_web({latched})", proc.stderr) + self.assertIn("without another stack deploy", proc.stderr) + + def test_a_rolled_back_update_fails_even_though_replicas_are_full(self) -> None: + """A revert leaves N/N of the PREVIOUS spec, so the replica check alone + would report this stack as converged.""" + for reverted in ("rollback_started", "rollback_completed"): + with self.subTest(state=reverted): + proc = self._run( + "demo_web 3/3\n", service_inspect=f"demo_web {reverted}\n" + ) + self.assertEqual(proc.returncode, 2) + self.assertIn(f"demo_web({reverted})", proc.stderr) + def test_a_fully_replicated_stack_converges(self) -> None: - proc = self._run("demo_web 3/3\ndemo_db 1/1\n") + proc = self._run( + "demo_web 3/3\ndemo_db 1/1\n", + service_running=WEB_THREE_RUNNING + "demo_db|Running 4 minutes ago\n", + ) self.assertEqual(proc.returncode, 0) def test_a_short_service_does_not_converge(self) -> None: diff --git a/tests/unit/python/roles/sys-svc-container/test_sandbox_placement.py b/tests/unit/python/roles/sys-svc-container/test_sandbox_placement.py new file mode 100644 index 0000000000..7438176bf6 --- /dev/null +++ b/tests/unit/python/roles/sys-svc-container/test_sandbox_placement.py @@ -0,0 +1,126 @@ +import unittest +from pathlib import Path + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +from utils import PROJECT_ROOT + +TEMPLATES = Path(PROJECT_ROOT) / "roles" / "sys-svc-container" / "templates" + +SANDBOX_LABEL = "kata-capable" + + +def _ansible_bool(value): + if isinstance(value, bool): + return value + if value is None: + return False + if isinstance(value, str): + return value.strip().lower() in {"y", "yes", "true", "on", "1"} + return bool(value) + + +BASE = { + "compose_mode": "swarm", + "application_id": "web-app-hermes", + "service_name": "hermes", + "RUNTIME": "local", + "SANDBOX_NODE_LABEL": SANDBOX_LABEL, + "DOCKER_RESTART_POLICY": "unless-stopped", + "RESOURCE_CPUS": "1", + "RESOURCE_MEM_LIMIT": "1g", + "RESOURCE_MEM_RESERVATION": "256m", + "RESOURCE_PIDS_LIMIT": "512", +} + + +class TestSandboxPlacement(unittest.TestCase): + def _render( + self, kata_enabled, manager_placed=False, sandbox_tier=True, **overrides + ): + env = Environment( + loader=FileSystemLoader(str(TEMPLATES)), + trim_blocks=True, + lstrip_blocks=False, + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters["bool"] = _ansible_bool + env.filters["resource_filter"] = lambda _apps, *_a, **_k: "" + env.filters["swarm_restart_condition"] = lambda value: value + + def _lookup(name, *args, **kwargs): + if name == "applications": + return {} + if name == "compose_replicas": + return "replicas: 3" + if name == "roles_with_placement": + return ["web-app-hermes"] if manager_placed else [] + if name == "config": + return kata_enabled + raise AssertionError(f"unexpected lookup: {name}") + + env.globals["lookup"] = _lookup + groups = {"svc-virt-kata": ["wrk-02"]} if sandbox_tier else {} + return env.get_template("deploy.yml.j2").render( + {**BASE, "groups": groups, **overrides} + ) + + def _constraints(self, rendered): + lines = [line.strip() for line in rendered.splitlines()] + return [line[2:] for line in lines if line.startswith("- node.")] + + def test_sandbox_consumer_is_pinned_to_a_sandbox_node(self): + constraints = self._constraints(self._render(kata_enabled=True)) + self.assertIn(f"node.labels.{SANDBOX_LABEL} == true", constraints) + + def test_every_other_service_is_kept_off_the_sandbox_nodes(self): + constraints = self._constraints(self._render(kata_enabled=False)) + self.assertIn(f"node.labels.{SANDBOX_LABEL} != true", constraints) + + def test_the_two_directions_are_mutually_exclusive(self): + for enabled in (True, False): + with self.subTest(kata_enabled=enabled): + constraints = self._constraints(self._render(kata_enabled=enabled)) + self.assertEqual(len([c for c in constraints if SANDBOX_LABEL in c]), 1) + + def test_a_cluster_without_a_sandbox_tier_gets_no_sandbox_constraint(self): + for enabled in (True, False): + with self.subTest(kata_enabled=enabled): + constraints = self._constraints( + self._render(kata_enabled=enabled, sandbox_tier=False) + ) + self.assertEqual([c for c in constraints if SANDBOX_LABEL in c], []) + + def test_manager_placement_composes_with_the_sandbox_constraint(self): + constraints = self._constraints( + self._render(kata_enabled=False, manager_placed=True) + ) + self.assertIn("node.role == manager", constraints) + self.assertIn(f"node.labels.{SANDBOX_LABEL} != true", constraints) + + def test_manager_placement_survives_without_a_sandbox_tier(self): + constraints = self._constraints( + self._render(kata_enabled=False, manager_placed=True, sandbox_tier=False) + ) + self.assertEqual(constraints, ["node.role == manager"]) + + def test_compose_mode_emits_no_deploy_block(self): + rendered = self._render(kata_enabled=True, compose_mode="compose") + self.assertEqual(rendered.strip(), "") + + def test_a_failed_task_does_not_latch_the_rollout(self): + """Swarm's default pauses forever on the first task that fails. + + With no failure_action, swarmkit applies pause at a max_failure_ratio + of zero, so one transient failure stops the rollout for good and no + step in the deploy resumes it. The restart policy replaces the task and + the service ends up healthy, while the update status stays latched and + the convergence check reports the deploy as failed. + """ + rendered = self._render(kata_enabled=False) + self.assertIn("failure_action: continue", rendered) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-svc-container/test_sandbox_runtime.py b/tests/unit/python/roles/sys-svc-container/test_sandbox_runtime.py new file mode 100644 index 0000000000..f5d24ad050 --- /dev/null +++ b/tests/unit/python/roles/sys-svc-container/test_sandbox_runtime.py @@ -0,0 +1,152 @@ +import json +import unittest +from pathlib import Path +from types import SimpleNamespace + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +from utils import PROJECT_ROOT + +TEMPLATES = Path(PROJECT_ROOT) / "roles" / "sys-svc-container" / "templates" + + +def _ansible_bool(value): + if isinstance(value, bool): + return value + if value is None: + return False + if isinstance(value, str): + return value.strip().lower() in {"y", "yes", "true", "on", "1"} + return bool(value) + + +def _shim(exists): + return SimpleNamespace(stat=SimpleNamespace(exists=exists)) + + +DNS_SERVERS = ["192.0.2.53"] + + +def _lookup(name, *_args, **_kwargs): + if name == "container_dns": + return DNS_SERVERS + raise AssertionError(f"unexpected lookup: {name}") + + +BASE = { + "DEPLOYMENT_MODE": "swarm", + "IS_STACK_HOST": False, + "DOCKER_IN_CONTAINER": True, + "DOMAIN_PRIMARY": "infinito.test", + "KATA_SHIM_BINARY": "/usr/bin/containerd-shim-kata-v2", + "RUNSC_SHIM_BINARY": "/usr/local/bin/runsc", + "SANDBOX_RUNTIME": "runsc", + "SYS_SVC_CONTAINER_DATA_ROOT": "", + "swarm": {"registry": {"host": "reg", "port": 5000}}, + "groups": {"svc-registry-cache": []}, + "group_names": ["svc-virt-kata"], + "ansible_facts": {"os_family": "Debian"}, + "SYS_SVC_CONTAINER_DOCKER_FIREWALL_BACKEND_BY_OS_FAMILY": {"Debian": "iptables"}, + "NETWORK_DOCKER_ADDRESS_POOLS": [{"base": "10.208.0.0/12", "size": 24}], + "SYS_DOCKER_DAEMONM_MTU": 1400, + "sys_svc_container_kvm": _shim(False), + "sys_svc_container_kata_shim": _shim(False), + "sys_svc_container_runsc_shim": _shim(False), +} + + +class TestSandboxRuntimeRegistration(unittest.TestCase): + def _render(self, **overrides): + env = Environment( + loader=FileSystemLoader(str(TEMPLATES)), + trim_blocks=True, + lstrip_blocks=False, + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters["bool"] = _ansible_bool + env.filters["to_json"] = json.dumps + env.globals["lookup"] = _lookup + raw = env.get_template("daemon.json.j2").render({**BASE, **overrides}) + return json.loads(raw) + + def test_absent_shim_is_never_registered(self): + parsed = self._render() + self.assertNotIn("runtimes", parsed) + self.assertNotIn("default-runtime", parsed) + + def test_swarm_worker_defaults_to_the_installed_sandbox_runtime(self): + parsed = self._render(sys_svc_container_runsc_shim=_shim(True)) + self.assertEqual(sorted(parsed["runtimes"]), ["runsc"]) + self.assertEqual(parsed["default-runtime"], "runsc") + + def test_stack_host_keeps_the_shared_kernel(self): + parsed = self._render( + IS_STACK_HOST=True, sys_svc_container_runsc_shim=_shim(True) + ) + self.assertIn("runsc", parsed["runtimes"]) + self.assertNotIn("default-runtime", parsed) + + def test_compose_mode_never_sets_a_default_runtime(self): + parsed = self._render( + DEPLOYMENT_MODE="compose", sys_svc_container_runsc_shim=_shim(True) + ) + self.assertIn("runsc", parsed["runtimes"]) + self.assertNotIn("default-runtime", parsed) + + def test_kata_wins_over_runsc_when_hardware_virtualization_is_present(self): + parsed = self._render( + DOCKER_IN_CONTAINER=False, + SANDBOX_RUNTIME="kata", + sys_svc_container_kvm=_shim(True), + sys_svc_container_kata_shim=_shim(True), + sys_svc_container_runsc_shim=_shim(True), + ) + self.assertEqual(sorted(parsed["runtimes"]), ["kata", "runsc"]) + self.assertEqual(parsed["default-runtime"], "kata") + + def test_registration_follows_the_probe_not_the_inventory_group(self): + parsed = self._render( + group_names=["web-app-hermes"], sys_svc_container_runsc_shim=_shim(True) + ) + self.assertEqual(sorted(parsed["runtimes"]), ["runsc"]) + self.assertEqual(parsed["default-runtime"], "runsc") + + def test_a_default_runtime_is_always_a_registered_one(self): + for kata, runsc in ((False, False), (False, True), (True, True)): + with self.subTest(kata=kata, runsc=runsc): + parsed = self._render( + DOCKER_IN_CONTAINER=False, + sys_svc_container_kvm=_shim(kata), + sys_svc_container_kata_shim=_shim(kata), + sys_svc_container_runsc_shim=_shim(runsc), + SANDBOX_RUNTIME="kata" if kata else "runsc", + ) + if "default-runtime" in parsed: + self.assertIn(parsed["default-runtime"], parsed["runtimes"]) + + +class TestDaemonStorageDriver(unittest.TestCase): + def _render(self, **overrides): + env = Environment( + loader=FileSystemLoader(str(TEMPLATES)), + trim_blocks=True, + lstrip_blocks=False, + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters["bool"] = _ansible_bool + env.filters["to_json"] = json.dumps + env.globals["lookup"] = _lookup + raw = env.get_template("daemon.json.j2").render({**BASE, **overrides}) + return json.loads(raw) + + def test_docker_in_docker_overrides_the_storage_driver(self): + self.assertEqual(self._render()["storage-driver"], "fuse-overlayfs") + + def test_a_bare_host_keeps_the_native_storage_driver(self): + self.assertNotIn("storage-driver", self._render(DOCKER_IN_CONTAINER=False)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py b/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py index 9048df5ff8..3e7e435f11 100644 --- a/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py +++ b/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py @@ -2,9 +2,11 @@ The rendered file is read inside a container while the template is rendered on the Ansible target, so naming a host-resolved bundle path measured the wrong -machine. Only two answers are correct: the CA file the compose override mounts -into every service of a self-signed app, or nothing at all - msmtp then falls -back to its own ``system`` default, which ``with-ca-trust.sh`` curates. +machine. Only two answers are correct: the trust bundle the compose override +mounts into every service of a self-signed app, or nothing at all - msmtp then +falls back to its own ``system`` default, which ``with-ca-trust.sh`` curates. +The bundle rather than the bare root CA, because ``tls_trust_file`` replaces +the trust store and a relay outside the deployment presents a public chain. The conditions are Jinja and compile with a plain environment plus a ``bool`` filter shim, since ``bool`` is an Ansible filter. @@ -26,14 +28,15 @@ TEMPLATE = ( PROJECT_ROOT / "roles" / "sys-svc-mail-msmtp" / "templates" / "msmtprc.conf.j2" ) CA_CONTAINER = "/tmp/infinito/ca/root-ca.crt" # nocheck: S108 - CA_TRUST.inject_cert_container, a container path +CA_BUNDLE_CONTAINER = "/tmp/infinito/ca/ca-bundle.crt" # nocheck: S108 - CA_TRUST.inject_bundle_container, a container path EMAIL = { "timeout": 30, "auth_mechanism": "PLAIN", "start_tls": True, "tls": True, - "host": "mail.infinito.example", + "host": "mail.infinito.test", "port": 587, - "from": "no-reply@infinito.example", + "from": "no-reply@infinito.test", "auth": False, } @@ -86,7 +89,10 @@ def _render( lookup=lookup, sys_svc_mail_msmtp_in_container=in_container, MODE_DEBUG=False, - CA_TRUST={"inject_cert_container": CA_CONTAINER}, + CA_TRUST={ + "inject_cert_container": CA_CONTAINER, + "inject_bundle_container": CA_BUNDLE_CONTAINER, + }, DOMAIN_PRIMARY="infinito.example", **extra, ) @@ -104,7 +110,7 @@ class TestMsmtprcCaTrust(unittest.TestCase): rendered = _render( in_container=True, ca_injected=True, application_id="web-app-moodle" ) - self.assertEqual(_trust_line(rendered), CA_CONTAINER) + self.assertEqual(_trust_line(rendered), CA_BUNDLE_CONTAINER) def test_a_container_without_the_injected_ca_names_nothing(self): rendered = _render( @@ -121,7 +127,9 @@ class TestMsmtprcCaTrust(unittest.TestCase): extra = {"application_id": "web-app-moodle"} if in_container else {} rendered = _render(in_container=in_container, ca_injected=injected, **extra) trust = _trust_line(rendered) - self.assertIn(trust, (None, CA_CONTAINER), f"host path leaked: {trust}") + self.assertIn( + trust, (None, CA_BUNDLE_CONTAINER), f"host path leaked: {trust}" + ) class TestMsmtprcOnionProxy(unittest.TestCase): diff --git a/tests/unit/python/roles/sys-svc-proxy/__init__.py b/tests/unit/python/roles/sys-svc-proxy/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/sys-svc-proxy/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/__init__.py b/tests/unit/python/roles/sys-svc-proxy/templates/__init__.py new file mode 100644 index 0000000000..9f69c70b47 --- /dev/null +++ b/tests/unit/python/roles/sys-svc-proxy/templates/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py new file mode 100644 index 0000000000..8c6880baec --- /dev/null +++ b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py @@ -0,0 +1,260 @@ +"""The edge limits a public MCP surface is served behind. + +Every role declares seven `mcp.limits`, and the adapter enforces five of them +on its own request path. Two only ever bite at the reverse proxy: +`concurrent_requests`, which no adapter sees until a connection already +occupies a thread, and `stream_seconds`, which bounds a held stream the +adapter never holds. These templates are where the declaration becomes an +nginx directive, so the values are pinned here rather than merely rendered. +""" + +from __future__ import annotations + +import unittest + +from jinja2 import Environment, FileSystemLoader, StrictUndefined + +from utils.cache.applications import get_application_defaults +from utils.cache.yaml import load_yaml +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +TEMPLATE_DIR = PROJECT_ROOT / "roles/sys-svc-proxy/templates/mcp" + +PUBLIC_ROLES = ("web-app-moodle", "web-app-wordpress") + + +def declared_limits(role: str) -> dict: + """Return a role's own `mcp.limits`, as its meta declares them. + + Args: + role: the role directory name. + """ + return load_yaml(PROJECT_ROOT / "roles" / role / ROLE_FILE_META_MCP)["limits"] + + +def render(name: str, **context) -> str: + """Return one template rendered with a stubbed `config` lookup. + + Args: + name: template file name inside the MCP template directory. + context: variables the template reads. + """ + env = Environment( + loader=FileSystemLoader(str(TEMPLATE_DIR)), + undefined=StrictUndefined, + autoescape=False, # noqa: S701 - nginx config, not markup; Ansible renders it the same way and HTML-escaping `$binary_remote_addr` would break it + ) + return env.get_template(name).render(**context) + + +class TestZones(unittest.TestCase): + def test_the_rate_follows_the_declared_concurrency(self): + limits = declared_limits("web-app-moodle") + rendered = render( + "zones.conf.j2", + application_id="web-app-moodle", + lookup=lambda *_a, **_k: limits, + ) + self.assertIn( + f"rate={limits['concurrent_requests']}r/s", + rendered, + ) + + def test_each_role_gets_a_zone_name_of_its_own(self): + rendered = render( + "zones.conf.j2", + application_id="web-app-moodle", + lookup=lambda *_a, **_k: declared_limits("web-app-moodle"), + ) + self.assertIn("zone=mcp_web_app_moodle_req:10m", rendered) + self.assertIn("zone=mcp_web_app_moodle_conn:10m", rendered) + + def test_the_two_zone_kinds_never_share_a_name(self): + """nginx refuses a `limit_conn_zone` reusing a `limit_req_zone` name.""" + rendered = render( + "zones.conf.j2", + application_id="web-app-nextcloud", + lookup=lambda *_a, **_k: declared_limits("web-app-nextcloud"), + ) + names = [ + part.split(":", 1)[0] + for line in rendered.splitlines() + for part in line.split() + if part.startswith("zone=") + ] + self.assertEqual(len(names), len(set(names))) + + def test_every_public_role_renders_a_zone_pair(self): + for role in PUBLIC_ROLES: + with self.subTest(role=role): + rendered = render( + "zones.conf.j2", + application_id=role, + lookup=lambda *_a, _r=role, **_k: declared_limits(_r), + ) + self.assertIn("limit_req_zone", rendered) + self.assertIn("limit_conn_zone", rendered) + + +class TestDirectives(unittest.TestCase): + def context(self, role: str) -> dict: + return { + "mcp_zone": "mcp_" + role.replace("-", "_"), + "mcp_limits": declared_limits(role), + } + + def test_the_connection_ceiling_is_the_declared_concurrency(self): + limits = declared_limits("web-app-nextcloud") + rendered = render("directives.conf.j2", **self.context("web-app-nextcloud")) + self.assertIn( + f"limit_conn mcp_web_app_nextcloud_conn {limits['concurrent_requests']};", + rendered, + ) + + def test_the_burst_matches_the_ceiling_so_a_legal_client_is_never_delayed(self): + limits = declared_limits("web-app-moodle") + rendered = render("directives.conf.j2", **self.context("web-app-moodle")) + self.assertIn( + f"burst={limits['concurrent_requests']} nodelay;", + rendered, + ) + + def test_a_refusal_is_429_rather_than_the_nginx_default_503(self): + """503 reads as an outage; a client that backs off needs 429.""" + rendered = render("directives.conf.j2", **self.context("web-app-moodle")) + self.assertIn("limit_req_status 429;", rendered) + self.assertIn("limit_conn_status 429;", rendered) + + def test_the_directives_reference_the_zones_the_zone_file_declares(self): + for role in PUBLIC_ROLES: + with self.subTest(role=role): + zone = "mcp_" + role.replace("-", "_") + zones = render( + "zones.conf.j2", + application_id=role, + lookup=lambda *_a, _r=role, **_k: declared_limits(_r), + ) + directives = render("directives.conf.j2", **self.context(role)) + self.assertIn(f"zone={zone}_req:", zones) + self.assertIn(f"zone={zone}_req ", directives) + self.assertIn(f"zone={zone}_conn:", zones) + self.assertIn(f"{zone}_conn ", directives) + + +class TestPublicSurfacesAreCovered(unittest.TestCase): + def test_the_pinned_roles_are_exactly_the_public_ones(self): + """A new public surface must not reach the edge without these limits.""" + found = set() + for meta in (PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_MCP}"): + if load_yaml(meta).get("exposure") == "public": + found.add(meta.parent.parent.name) + self.assertEqual(found, set(PUBLIC_ROLES)) + + +def endpoint_roles() -> dict[str, dict]: + """Return every role declaring an MCP endpoint path, by role name. + + ``enabled`` comes from the resolved defaults, not from the meta file: it is + derived from the admitted clients and a role's own ``meta/mcp.yml`` carries + it only when it overrides that. + """ + defaults = get_application_defaults(roles_dir=PROJECT_ROOT / "roles") + found = {} + for meta in (PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_MCP}"): + role = meta.parent.parent.name + block = dict(load_yaml(meta)) + if not (block.get("endpoint") or {}).get("path"): + continue + resolved = (defaults.get(role) or {}).get("mcp") or {} + block["enabled"] = resolved.get("enabled") + found[role] = block + return found + + +class TestTheAppVhostServesOnlyPublicSurfaces(unittest.TestCase): + """`vhost.conf.j2` serves the MCP path, or returns 404 for it. + + A surface reachable on the application's own public vhost while the + service is off, or while its declared exposure is internal, is a surface + nobody decided to publish. For an adapter-fronted provider it is worse + than untidy: the adapter exists to narrow the upstream's tool set, and a + publicly routed native path walks straight past it. + """ + + def served(self, block: dict) -> bool: + return bool(block.get("enabled")) and block.get("exposure") == "public" + + def test_an_internal_surface_is_not_served_on_the_public_vhost(self): + for role, block in endpoint_roles().items(): + if block.get("exposure") != "public": + with self.subTest(role=role): + self.assertFalse(self.served(block)) + + def test_the_adapter_fronted_provider_hides_its_native_path(self): + """Reaching baserow's own endpoint would bypass the four-tool contract.""" + block = endpoint_roles()["web-app-baserow"] + self.assertEqual("adapter_server", block["classification"]) + self.assertFalse(self.served(block)) + + def test_a_disabled_surface_is_never_served(self): + for role, block in endpoint_roles().items(): + if not block.get("enabled"): + with self.subTest(role=role): + self.assertFalse(self.served(block)) + + def test_the_public_roles_are_the_only_ones_served(self): + served = {r for r, b in endpoint_roles().items() if self.served(b)} + self.assertEqual(served, set(PUBLIC_ROLES)) + + +class TestTheHiddenPathIsTheOneTheAppServes(unittest.TestCase): + """What must be hidden is the upstream, not the sidecar's endpoint. + + An adapter-fronted provider declares `endpoint.path` on its sidecar and + serves the real MCP surface somewhere else on its own vhost. Blocking the + sidecar's path there hides nothing: mattermost declares `/mcp` and answers + on `/plugins/mattermost-ai/mcp-server/mcp`, so the native surface stayed + reachable while the deploy looked correct. Baserow's two paths happen to + coincide, which is why one role passing proved nothing about the rest. + """ + + def passthrough_roles(self) -> dict[str, dict]: + found = {} + for meta in (PROJECT_ROOT / "roles").glob(f"*/{ROLE_FILE_META_MCP}"): + block = load_yaml(meta) + if (block.get("adapter") or {}).get("type") == "mcp_passthrough": + found[meta.parent.parent.name] = block + return found + + def test_a_passthrough_provider_says_where_its_upstream_lives(self): + """Either on the application's own vhost, or on a separate network.""" + for role, block in self.passthrough_roles().items(): + with self.subTest(role=role): + adapter = block["adapter"] + self.assertTrue( + adapter.get("upstream_path") or adapter.get("upstream_network"), + f"{role} declares neither upstream_path nor upstream_network, " + f"so nothing states whether its native surface is exposed", + ) + + def test_the_role_that_made_this_visible_declares_its_real_path(self): + adapter = self.passthrough_roles()["web-app-mattermost"]["adapter"] + self.assertEqual( + "/plugins/mattermost-ai/mcp-server/mcp", adapter["upstream_path"] + ) + self.assertNotEqual( + adapter["upstream_path"], + self.passthrough_roles()["web-app-mattermost"]["endpoint"]["path"], + ) + + def test_a_sidecar_upstream_declares_no_path_on_the_app_vhost(self): + """Gitea's upstream is its own service, so it has nothing to hide.""" + adapter = self.passthrough_roles()["web-app-gitea"]["adapter"] + self.assertNotIn("upstream_path", adapter) + self.assertTrue(adapter.get("upstream_network")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py new file mode 100644 index 0000000000..cc2eaea1c3 --- /dev/null +++ b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py @@ -0,0 +1,206 @@ +"""An internal MCP surface is withdrawn from the edge under every spelling. + +The adapter exists to narrow an upstream's tool set, so a publicly routed +native path walks straight past it. `mcp/vhost.conf.j2` withdraws such a path +with `return 404`, and the question this file answers is whether the withdrawal +covers the URLs the application actually answers. + +It does not follow from the declared path alone. A front-controller application +serves one route under two spellings -- `/index.php/apps/โ€ฆ` and `/apps/โ€ฆ` -- +and a prefix `location` for the first leaves the second reachable, because the +app's own `try_files โ€ฆ /index.php$request_uri` rewrites it back onto the route +after the edge has already decided not to block it. Nextcloud is the one +provider whose `adapter.upstream_path` carries the front controller today, so +the case is pinned here rather than left to the next reader to rediscover. + +The sibling `test_mcp_edge_limits.py` pins the values a *public* surface is +served behind; this file pins what an *internal* one must not be served at. +""" + +from __future__ import annotations + +import re +import unittest + +from jinja2 import Environment, FileSystemLoader, StrictUndefined + +from utils.cache.yaml import load_yaml +from utils.roles.mapping import ROLE_FILE_META_MCP + +from . import PROJECT_ROOT + +TEMPLATE_DIR = PROJECT_ROOT / "roles/sys-svc-proxy/templates/mcp" + +FRONT_CONTROLLER_ROLE = "web-app-nextcloud" + + +def meta(role: str) -> dict: + """Return a role's `meta/mcp.yml`. + + Args: + role: the role directory name. + """ + return load_yaml(PROJECT_ROOT / "roles" / role / ROLE_FILE_META_MCP) + + +def render(role: str, *, exposure: str, sso_gated: bool = False) -> str: + """Return `vhost.conf.j2` for one role at one exposure. + + Args: + role: the role directory name. + exposure: the `mcp.exposure` value to render under. + sso_gated: whether the vhost sits behind an SSO proxy ACL. + """ + block = meta(role) + values = { + "mcp.endpoint.path": block["endpoint"]["path"], + "mcp.adapter.upstream_path": (block.get("adapter") or {}).get( + "upstream_path", "" + ), + "mcp.exposure": exposure, + "mcp.enabled": True, + "mcp.limits": block["limits"], + } + + def config(_app, key, default=None): + return values.get(key, default) + + sso_values = { + "is_proxy_gated": sso_gated, + "oauth2_acl": ["group:staff"] if sso_gated else [], + } + + def lookup(kind, *args, **_kw): + if kind == "config": + return config(*args) + if kind == "sso": + return sso_values.get(args[1], "") + return "" + + env = Environment( + loader=FileSystemLoader(str(TEMPLATE_DIR)), + undefined=StrictUndefined, + autoescape=False, # noqa: S701 - nginx config, not markup; HTML-escaping would corrupt the directives + ) + env.filters["regex_replace"] = lambda value, pattern, repl="": re.sub( + pattern, repl, value + ) + env.filters["regex_escape"] = re.escape + env.filters["bool"] = lambda value: ( + value + if isinstance(value, bool) + else str(value).strip().lower() in {"true", "1", "yes", "on"} + ) + return env.get_template("vhost.conf.j2").render( + application_id=role, + lookup=lookup, + ) + + +def withdrawals(rendered: str) -> list[tuple[str, str]]: + """Return `(kind, value)` for every `return 404` location. + + Args: + rendered: the rendered vhost fragment. + + `kind` is `regex` for a `location ~ โ€ฆ` and `prefix` for a bare one, so a + caller matches each the way nginx does rather than assuming one form. + """ + return re.findall(r"location\s+(~)?\s*(\S+)\s*\{\s*return 404;", rendered) + + +def is_blocked(rendered: str, url_path: str) -> bool: + """Return whether a request path matches any withdrawal. + + Args: + rendered: the rendered vhost fragment. + url_path: the path a client would request. + """ + return any( + re.match(value, url_path) if tilde else url_path.startswith(value) + for tilde, value in withdrawals(rendered) + ) + + +class TestInternalSurfaceIsWithdrawn(unittest.TestCase): + def test_both_declared_paths_are_withdrawn(self): + block = meta(FRONT_CONTROLLER_ROLE) + rendered = render(FRONT_CONTROLLER_ROLE, exposure="internal") + for declared in ( + block["endpoint"]["path"], + block["adapter"]["upstream_path"], + ): + with self.subTest(path=declared): + self.assertTrue( + is_blocked(rendered, declared), + f"{declared} stays reachable at the edge", + ) + + def test_the_front_controller_alias_is_withdrawn_too(self): + block = meta(FRONT_CONTROLLER_ROLE) + alias = block["adapter"]["upstream_path"].replace("/index.php", "", 1) + rendered = render(FRONT_CONTROLLER_ROLE, exposure="internal") + self.assertTrue( + is_blocked(rendered, alias), + f"{alias} reaches the same route as the declared path and must be " + f"withdrawn with it", + ) + + def test_the_withdrawal_does_not_reach_unrelated_paths(self): + rendered = render(FRONT_CONTROLLER_ROLE, exposure="internal") + for spared in ("/index.php/login", "/apps/files", "/status.php"): + with self.subTest(path=spared): + self.assertFalse( + is_blocked(rendered, spared), + f"{spared} is not an MCP path and must stay served", + ) + + def test_an_internal_surface_proxies_nothing(self): + rendered = render(FRONT_CONTROLLER_ROLE, exposure="internal") + self.assertNotIn("proxy_pass", rendered) + + def test_the_front_controller_path_is_withdrawn_as_a_regex(self): + """A prefix location cannot cover both spellings; only a regex can.""" + rendered = render(FRONT_CONTROLLER_ROLE, exposure="internal") + upstream = meta(FRONT_CONTROLLER_ROLE)["adapter"]["upstream_path"] + covering = [ + value + for tilde, value in withdrawals(rendered) + if tilde and re.match(value, upstream) + ] + self.assertTrue( + covering, + f"{upstream} carries a front controller, so its withdrawal must be " + f"a regex location", + ) + + def test_the_scan_finds_a_withdrawal(self): + rendered = render(FRONT_CONTROLLER_ROLE, exposure="internal") + self.assertTrue( + withdrawals(rendered), + "no withdrawal was rendered at all, so every assertion here would " + "pass vacuously", + ) + + def test_an_acl_gated_public_surface_is_withdrawn_not_left_to_the_acl(self): + block = meta(FRONT_CONTROLLER_ROLE) + rendered = render(FRONT_CONTROLLER_ROLE, exposure="public", sso_gated=True) + self.assertNotIn( + "proxy_pass", + rendered, + "an ACL-gated surface must not be served at the edge", + ) + for declared in ( + block["endpoint"]["path"], + block["adapter"]["upstream_path"], + ): + with self.subTest(path=declared): + self.assertTrue( + is_blocked(rendered, declared), + f"{declared} is left to the SSO ACL alone instead of being " + f"withdrawn at the edge", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-svc-rdbms/__init__.py b/tests/unit/python/roles/sys-svc-rdbms/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/sys-svc-rdbms/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/sys-svc-rdbms/files/__init__.py b/tests/unit/python/roles/sys-svc-rdbms/files/__init__.py new file mode 100644 index 0000000000..9f69c70b47 --- /dev/null +++ b/tests/unit/python/roles/sys-svc-rdbms/files/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] diff --git a/tests/unit/python/roles/sys-svc-rdbms/files/test_patch_persisted_password.py b/tests/unit/python/roles/sys-svc-rdbms/files/test_patch_persisted_password.py new file mode 100644 index 0000000000..521fa2805b --- /dev/null +++ b/tests/unit/python/roles/sys-svc-rdbms/files/test_patch_persisted_password.py @@ -0,0 +1,211 @@ +"""Guards around the persisted database password patch. + +``roles/sys-svc-rdbms/files/shell/patch_persisted_password.sh`` rewrites a +credential inside a config file on an application's own volume, on whichever +node holds it. These tests run the script against a stubbed ``container`` +rather than trusting a reading of it: it has to find the volume, refuse to +touch a mountpoint without the config, and leave a password the app can use. + +The parameters come from the environment, so each consuming role's own +``patch_db_credentials.yml`` supplies them here exactly as the task would. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path +from typing import ClassVar + +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +SCRIPT = PROJECT_ROOT / "roles/sys-svc-rdbms/files/shell/patch_persisted_password.sh" + +CONSUMERS: ClassVar = { + "friendica": "<?php\n 'password' => 'OLDPW',\n 'database' => 'friendica',\n", + "joomla": "<?php\nclass JConfig {\n public $password = 'OLDPW';\n}\n", + "kix": "[Database]\n 'DatabasePw' => 'OLDPW',\n 'DatabaseHost' => 'postgres',\n", + "matomo": "[database]\npassword = OLDPW\nhost = db\n", + "moodle": "<?php\n$CFG->dbpass = 'OLDPW';\n$CFG->dbname = 'moodle';\n", + "nextcloud": "<?php\n 'dbpassword' => 'OLDPW',\n 'dbname' => 'nc',\n", + "suitecrm": "<?php\n 'db_password' => 'OLDPW',\n 'db_name' => 'suitecrm',\n", +} + + +def _caller_vars(app: str) -> dict: + """Return the parameters a consuming role hands to the shared task. + + Args: + app: the web-app suffix of the consuming role. + """ + caller = load_yaml_any( + str(PROJECT_ROOT / f"roles/web-app-{app}/tasks/utils/patch/db_credentials.yml") + ) + return caller[0]["vars"] + + +def _script_env(app: str, bindir: Path) -> dict[str, str]: + """Return the environment the task hands the script for one consumer. + + Args: + app: the web-app suffix of the consuming role. + bindir: directory holding the stubbed ``container``. + """ + params = _caller_vars(app) + return { + **os.environ, + "PATH": f"{bindir}:{os.environ['PATH']}", + "PATCH_VOLUME": params["patch_volume"], + "PATCH_CONFIG_REL": params["patch_config_rel"], + "PATCH_EXPRESSION": params["patch_expression"], + "PATCH_PASSWORD": "NEWPW", + } + + +def _write_stub(bindir: Path, volumes: dict[str, Path]) -> None: + """Write a ``container`` that knows only the volumes it is given. + + Args: + bindir: directory placed first on PATH. + volumes: volume name to mountpoint. + """ + bindir.mkdir(parents=True, exist_ok=True) + listed = "\n".join(f' "name=^{n}$") echo "{n}";;' for n in volumes) + inspected = "\n".join(f' "{n}") echo "{p}";;' for n, p in volumes.items()) + stub = bindir / "container" + stub.write_text( + "#!/bin/sh\n" + 'if [ "$1" = "volume" ] && [ "$2" = "ls" ]; then\n' + f' case "$5" in\n{listed}\n *) : ;;\n esac\n exit 0\nfi\n' + 'if [ "$1" = "volume" ] && [ "$2" = "inspect" ]; then\n' + f' case "$5" in\n{inspected}\n *) exit 1;;\n esac\n exit 0\nfi\n' + "exit 1\n" + ) + stub.chmod(0o755) + + +class TestPatchPersistedPassword(unittest.TestCase): + def setUp(self) -> None: + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, ignore_errors=True) + + def _run(self, app: str, *, volume_exists: bool, config_exists: bool): + params = _caller_vars(app) + mount = self.tmp / "mount" + if config_exists: + target = mount / params["patch_config_rel"] + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(CONSUMERS[app]) + bindir = self.tmp / "bin" + _write_stub(bindir, {params["patch_volume"]: mount} if volume_exists else {}) + proc = subprocess.run( + ["/bin/bash", str(SCRIPT)], + env=_script_env(app, bindir), + capture_output=True, + text=True, + check=False, + ) + target = mount / params["patch_config_rel"] + content = "" + if config_exists: + content = target.read_text() # nocheck: cache-read shell just rewrote it + return proc, content + + def test_it_replaces_the_password_each_consumer_persists(self) -> None: + for app in CONSUMERS: + with self.subTest(app=app): + proc, content = self._run(app, volume_exists=True, config_exists=True) + self.assertEqual(0, proc.returncode, proc.stderr) + self.assertIn("NEWPW", content) + self.assertNotIn("OLDPW", content) + self.assertIn("PATCHED", proc.stdout) + + def test_a_node_without_the_volume_reports_no_change(self) -> None: + """Every swarm node runs this; only the one holding the volume acts.""" + for app in CONSUMERS: + with self.subTest(app=app): + proc, _ = self._run(app, volume_exists=False, config_exists=False) + self.assertEqual(0, proc.returncode, proc.stderr) + self.assertNotIn("PATCHED", proc.stdout) + + def test_a_volume_without_the_config_reports_no_change(self) -> None: + """The volume exists before the app has ever written its config.""" + for app in CONSUMERS: + with self.subTest(app=app): + proc, _ = self._run(app, volume_exists=True, config_exists=False) + self.assertEqual(0, proc.returncode, proc.stderr) + self.assertNotIn("PATCHED", proc.stdout) + + def test_the_placeholder_never_survives_into_the_config(self) -> None: + """Bash does not expand a ``${...}`` that arrives inside a variable.""" + for app in CONSUMERS: + with self.subTest(app=app): + _, content = self._run(app, volume_exists=True, config_exists=True) + self.assertNotIn("@PASSWORD@", content) + self.assertNotIn("PATCH_PASSWORD", content) + + def test_it_finds_a_config_the_volume_object_does_not_point_at(self) -> None: + """A node can hold the volume without its driver options, so the + mountpoint names the empty node-local path, not the NFS export.""" + params = _caller_vars("kix") + export = self.tmp / "export" + export.mkdir(parents=True) + (export / params["patch_config_rel"]).write_text(CONSUMERS["kix"]) + bindir = self.tmp / "bin" + _write_stub(bindir, {params["patch_volume"]: self.tmp / "node-local"}) + proc = subprocess.run( + ["/bin/bash", str(SCRIPT)], + env={**_script_env("kix", bindir), "PATCH_DATA_DIR": str(export)}, + capture_output=True, + text=True, + check=False, + ) + self.assertIn("PATCHED", proc.stdout, proc.stderr) + content = ( # nocheck: cache-read shell just rewrote it + export / params["patch_config_rel"] + ).read_text() + self.assertIn("NEWPW", content) + self.assertNotIn("OLDPW", content) + + def test_a_config_found_nowhere_names_both_paths_it_tried(self) -> None: + """A silent skip here left KIX crash-looping on a stale password until + the converge gate gave up 44 retries later.""" + params = _caller_vars("kix") + bindir = self.tmp / "bin" + _write_stub(bindir, {params["patch_volume"]: self.tmp / "node-local"}) + proc = subprocess.run( + ["/bin/bash", str(SCRIPT)], + env={ + **_script_env("kix", bindir), + "PATCH_DATA_DIR": str(self.tmp / "export"), + }, + capture_output=True, + text=True, + check=False, + ) + self.assertEqual(0, proc.returncode, proc.stderr) + self.assertNotIn("PATCHED", proc.stdout) + self.assertIn("SKIPPED", proc.stdout) + self.assertIn("node-local", proc.stdout) + self.assertIn("export", proc.stdout) + + def test_it_refuses_to_run_without_its_parameters(self) -> None: + """A silent no-op would look exactly like a node without the volume.""" + proc = subprocess.run( + ["/bin/bash", str(SCRIPT)], + env={"PATH": os.environ["PATH"]}, + capture_output=True, + text=True, + check=False, + ) + self.assertNotEqual(0, proc.returncode) + self.assertIn("PATCH_VOLUME", proc.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/test-e2e-cli/files/__init__.py b/tests/unit/python/roles/test-e2e-cli/files/__init__.py new file mode 100644 index 0000000000..9f69c70b47 --- /dev/null +++ b/tests/unit/python/roles/test-e2e-cli/files/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] diff --git a/tests/unit/python/roles/test-e2e-cli/files/shared/__init__.py b/tests/unit/python/roles/test-e2e-cli/files/shared/__init__.py new file mode 100644 index 0000000000..86efabd459 --- /dev/null +++ b/tests/unit/python/roles/test-e2e-cli/files/shared/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[7] diff --git a/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/__init__.py b/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/__init__.py new file mode 100644 index 0000000000..1f90564319 --- /dev/null +++ b/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[8] diff --git a/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py b/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py new file mode 100644 index 0000000000..f4fdf6163f --- /dev/null +++ b/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py @@ -0,0 +1,663 @@ +"""Unit tests for the deploy-time MCP provider contract probe.""" + +from __future__ import annotations + +import contextlib +import importlib.util +import io +import json +import queue +import threading +import time +import unittest +import urllib.parse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest.mock import patch + +from . import PROJECT_ROOT + +MODULE_PATH = PROJECT_ROOT / "roles/test-e2e-cli/files/shared/mcp/contract.py" + +ENV = { + "MCP_URL": "http://provider:8080/mcp", + "MCP_TRANSPORT": "streamable_http", + "MCP_PATH_KEY": "", + "MCP_AUTH_HEADER": "Bearer real", + "MCP_EXPECTED_TOOLS": json.dumps(["a_get", "a_list"]), + "MCP_READ_TOOL": "a_list", + "MCP_READ_ARGUMENTS": "{}", +} + + +def load(overrides=None): + spec = importlib.util.spec_from_file_location("probe_contract", MODULE_PATH) + module = importlib.util.module_from_spec(spec) + with patch.dict("os.environ", {**ENV, **(overrides or {})}, clear=False): + spec.loader.exec_module(module) + return module + + +def ok(tools=("a_get", "a_list"), is_error=False): + """Return a fake rpc() honouring the contract. + + Args: + tools: the tool names the fake server advertises. + is_error: whether the read call reports an error result. + """ + + def rpc(method, params=None, authorization=None, url=None, notification=False): + if authorization != "Bearer real": + return 401, '{"error":"unauthenticated"}' + if method == "initialize" and not (params or {}).get("clientInfo"): + return 200, json.dumps( + { + "jsonrpc": "2.0", + "id": 1, + "error": {"code": -32602, "message": "Invalid request parameters"}, + } + ) + if method == "initialize": + return 200, json.dumps({"result": {"protocolVersion": "2025-06-18"}}) + if method == "tools/list": + return 200, json.dumps( + {"result": {"tools": [{"name": name} for name in tools]}} + ) + return 200, json.dumps({"result": {"isError": is_error, "content": []}}) + + return rpc + + +def erroring_at(step): + """Return a fake rpc() answering one authenticated step with an error on 200. + + Args: + step: the MCP method whose authenticated call carries the JSON-RPC error. + """ + honest = ok() + + def rpc(method, params=None, authorization=None, url=None, notification=False): + if method == step and authorization == "Bearer real": + return 200, json.dumps( + { + "jsonrpc": "2.0", + "id": 1, + "error": {"code": -32602, "message": "Invalid params"}, + } + ) + return honest(method, params, authorization) + + return rpc + + +class TestProbeContract(unittest.TestCase): + def test_a_conforming_provider_passes(self): + module = load() + with patch.object(module, "rpc", ok()): + module.main() + + def test_an_endpoint_that_answers_without_a_credential_fails(self): + module = load() + + def rpc(method, params=None, authorization=None, url=None, notification=False): + return 200, json.dumps({"result": {"tools": []}}) + + with patch.object(module, "rpc", rpc), self.assertRaises(SystemExit): + module.main() + + def test_an_endpoint_that_accepts_a_wrong_credential_fails(self): + module = load() + + def rpc(method, params=None, authorization=None, url=None, notification=False): + if authorization is None: + return 401, "{}" + return 200, json.dumps({"result": {"tools": [{"name": "a_get"}]}}) + + with patch.object(module, "rpc", rpc), self.assertRaises(SystemExit): + module.main() + + def test_a_bare_401_without_a_json_rpc_body_still_counts_as_refused(self): + module = load() + conforming = ok() + + def rpc(method, params=None, authorization=None, url=None, notification=False): + if authorization != "Bearer real": + return 401, "401: Unauthorized" + return conforming(method, params, authorization) + + with patch.object(module, "rpc", rpc): + module.main() + + def test_a_404_html_page_counts_as_refused(self): + module = load() + conforming = ok() + + def rpc(method, params=None, authorization=None, url=None, notification=False): + if authorization != "Bearer real": + return 404, "<!DOCTYPE html><html><body>Not Found</body></html>" + return conforming(method, params, authorization) + + with patch.object(module, "rpc", rpc): + module.main() + + def test_an_endpoint_that_hands_out_a_session_without_a_credential_fails(self): + module = load() + conforming = ok() + stderr = io.StringIO() + + def rpc(method, params=None, authorization=None, url=None, notification=False): + if authorization is None and method == "initialize": + return 200, json.dumps( + {"result": {"protocolVersion": "2025-06-18", "capabilities": {}}} + ) + return conforming(method, params, authorization) + + with ( + patch.object(module, "rpc", rpc), + contextlib.redirect_stderr(stderr), + self.assertRaises(SystemExit), + ): + module.main() + self.assertIn("REJECTED", stderr.getvalue()) + + def test_a_502_without_a_json_rpc_body_keeps_the_caller_retrying(self): + module = load() + stderr = io.StringIO() + + def rpc(method, params=None, authorization=None, url=None, notification=False): + return 502, "<html><body>Bad Gateway</body></html>" + + with ( + patch.object(module, "rpc", rpc), + contextlib.redirect_stderr(stderr), + self.assertRaises(SystemExit), + ): + module.main() + self.assertNotIn("REJECTED", stderr.getvalue()) + + def test_the_unauthenticated_handshake_does_not_leak_its_session(self): + module = load() + conforming = ok() + module.SESSION["id"] = "authenticated-session" + + def rpc(method, params=None, authorization=None, url=None, notification=False): + if authorization != "Bearer real": + module.SESSION["id"] = "anonymous-session" + return 401, "401: Unauthorized" + return conforming(method, params, authorization) + + with patch.object(module, "rpc", rpc): + module.main() + self.assertEqual(module.SESSION["id"], "authenticated-session") + + def test_a_200_without_a_json_rpc_body_keeps_the_caller_retrying(self): + module = load() + + def rpc(method, params=None, authorization=None, url=None, notification=False): + return 200, "<br />Fatal error: uncaught Error" + + with ( + patch.object(module, "rpc", rpc), + contextlib.redirect_stderr(io.StringIO()) as stderr, + self.assertRaises(SystemExit), + ): + module.main() + self.assertNotIn("REJECTED", stderr.getvalue()) + + def test_an_extra_upstream_tool_fails_closed(self): + module = load() + stderr = io.StringIO() + with ( + patch.object(module, "rpc", ok(tools=("a_get", "a_list", "a_delete"))), + contextlib.redirect_stderr(stderr), + self.assertRaises(SystemExit), + ): + module.main() + self.assertIn("a_delete", stderr.getvalue()) + + def test_a_missing_declared_tool_fails(self): + module = load() + with ( + patch.object(module, "rpc", ok(tools=("a_get",))), + self.assertRaises(SystemExit), + ): + module.main() + + def test_a_read_call_returning_an_error_result_fails(self): + module = load() + stderr = io.StringIO() + with ( + patch.object(module, "rpc", ok(is_error=True)), + contextlib.redirect_stderr(stderr), + self.assertRaises(SystemExit), + ): + module.main() + self.assertIn("error result", stderr.getvalue()) + + def test_a_json_rpc_error_on_200_fails_each_authenticated_step(self): + for step in ("initialize", "tools/list", "tools/call"): + with self.subTest(step=step): + module = load() + stderr = io.StringIO() + with ( + patch.object(module, "rpc", erroring_at(step)), + contextlib.redirect_stderr(stderr), + self.assertRaises(SystemExit), + ): + module.main() + self.assertIn("REJECTED", stderr.getvalue()) + self.assertIn("Invalid params", stderr.getvalue()) + + def test_every_initialize_names_its_client(self): + module = load() + honest = ok() + seen = [] + + def rpc(method, params=None, authorization=None, url=None, notification=False): + if method == "initialize": + seen.append((params or {}).get("clientInfo")) + return honest(method, params, authorization) + + with patch.object(module, "rpc", rpc): + module.main() + self.assertEqual(len(seen), 3) + self.assertTrue(all(seen)) + + def test_rpc_error_reads_only_a_json_rpc_error_object(self): + module = load() + cases = { + "<br />Fatal error": None, + "": None, + "null": None, + "[1]": None, + '"text"': None, + '{"result": {}}': None, + '{"error": {"code": 1}}': {"code": 1}, + } + for body, expected in cases.items(): + with self.subTest(body=body): + self.assertEqual(module.rpc_error(body), expected) + + def test_the_read_call_is_skipped_when_none_is_declared(self): + module = load({"MCP_READ_TOOL": ""}) + calls = [] + + def rpc(method, params=None, authorization=None, url=None, notification=False): + calls.append(method) + return ok()(method, params, authorization) + + with patch.object(module, "rpc", rpc): + module.main() + self.assertNotIn("tools/call", calls) + + def test_a_provider_that_has_not_started_keeps_the_caller_retrying(self): + module = load() + + def rpc(method, params=None, authorization=None, url=None, notification=False): + if method != "tools/call": + return ok()(method, params, authorization) + return 502, json.dumps( + { + "error": { + "code": -32000, + "message": "upstream_error", + "data": {"upstream_status": 503}, + } + } + ) + + with ( + patch.object(module, "rpc", rpc), + contextlib.redirect_stderr(io.StringIO()) as stderr, + self.assertRaises(SystemExit), + ): + module.main() + self.assertNotIn("REJECTED", stderr.getvalue()) + + def test_a_provider_refusing_the_adapter_credential_fails_closed(self): + module = load() + + def rpc(method, params=None, authorization=None, url=None, notification=False): + if method != "tools/call": + return ok()(method, params, authorization) + return 502, json.dumps( + { + "error": { + "code": -32000, + "message": "upstream_error", + "data": {"upstream_status": 401}, + } + } + ) + + with ( + patch.object(module, "rpc", rpc), + contextlib.redirect_stderr(io.StringIO()) as stderr, + self.assertRaises(SystemExit), + ): + module.main() + self.assertIn("REJECTED", stderr.getvalue()) + + def test_the_session_id_is_carried_after_initialize(self): + module = load() + module.SESSION["id"] = "" + seen = [] + + def rpc(method, params=None, authorization=None, url=None, notification=False): + seen.append((method, module.SESSION["id"])) + if method == "initialize": + module.SESSION["id"] = "sess-1" + return ok()(method, params, authorization) + + with patch.object(module, "rpc", rpc): + module.main() + after_initialize = [ + session for method, session in seen if method == "tools/list" + ] + self.assertEqual( + after_initialize[-1], + "sess-1", + "a streamable-HTTP server answers 404 'Invalid session ID' without it", + ) + self.assertIn( + "notifications/initialized", + [method for method, _ in seen], + "servers built on mcp-go serve no tools until the client confirms", + ) + + def test_an_event_stream_framed_response_is_parsed(self): + module = load() + self.assertEqual( + module.json_body( + "text/event-stream", + 'event: message\ndata: {"jsonrpc":"2.0","id":1,"result":{}}\n\n', + ), + '{"jsonrpc":"2.0","id":1,"result":{}}', + "streamable HTTP may answer a POST with a stream carrying the same object", + ) + self.assertEqual( + module.json_body("application/json", '{"result":{}}'), + '{"result":{}}', + ) + + def test_a_json_rpc_error_counts_as_a_refusal(self): + module = load() + + def rpc(method, params=None, authorization=None, url=None, notification=False): + if authorization != "Bearer real": + return 200, json.dumps( + {"jsonrpc": "2.0", "error": {"code": -32603, "message": "no token"}} + ) + return ok()(method, params, authorization) + + with patch.object(module, "rpc", rpc): + module.main() + + def test_a_served_response_without_an_error_still_fails(self): + module = load() + + def rpc(method, params=None, authorization=None, url=None, notification=False): + if authorization != "Bearer real": + return 200, json.dumps({"jsonrpc": "2.0", "result": {}}) + return ok()(method, params, authorization) + + with ( + patch.object(module, "rpc", rpc), + contextlib.redirect_stderr(io.StringIO()) as stderr, + self.assertRaises(SystemExit), + ): + module.main() + self.assertIn("unauthenticated probe answered 200", stderr.getvalue()) + + def test_an_unreachable_endpoint_keeps_the_caller_retrying(self): + module = load() + + def rpc(method, params=None, authorization=None, url=None, notification=False): + return 0, "unreachable: connection refused" + + with ( + patch.object(module, "rpc", rpc), + contextlib.redirect_stderr(io.StringIO()) as stderr, + self.assertRaises(SystemExit), + ): + module.main() + self.assertNotIn( + "REJECTED", + stderr.getvalue(), + "a sidecar that has not started yet must not settle the retry loop", + ) + + +KEY = "k" * 32 +TOOLS = ("list_databases", "list_tables", "get_table_schema") + +PING_SECONDS = 1 +IDLE_SECONDS = 30 + + +class FakeProvider: + """Serves one SSE MCP surface, guarded by the key in its URL path.""" + + def __init__( + self, + tools=TOOLS, + guarded=True, + preamble_frames=1, + is_error=False, + error_at=None, + ): + """ + Args: + tools: the tool names ``tools/list`` advertises. + guarded: whether a wrong path key is refused. + preamble_frames: comment frames sent before the endpoint event. + is_error: whether ``tools/call`` reports an error result. + error_at: the method answered with a JSON-RPC error, or None. + """ + self.tools = tuple(tools) + self.guarded = guarded + self.preamble_frames = preamble_frames + self.is_error = is_error + self.error_at = error_at + self.sessions: dict[str, queue.Queue] = {} + self._server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler()) + threading.Thread(target=self._server.serve_forever, daemon=True).start() + + @property + def url(self): + host, port = self._server.server_address[:2] + return f"http://{host}:{port}/mcp/{KEY}/sse" + + def stop(self): + self._server.shutdown() + self._server.server_close() + + def _handler(self): + provider = self + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def log_message(self, *args): + pass + + def do_GET(self): + parts = self.path.strip("/").split("/") + if len(parts) != 3 or parts[0] != "mcp" or parts[2] != "sse": + self.send_error(404) + return + if provider.guarded and parts[1] != KEY: + self.send_response(401) + self.send_header("Content-Type", "text/plain") + self.send_header("Content-Length", "0") + self.end_headers() + return + + session_id = f"s{len(provider.sessions)}" + provider.sessions[session_id] = queue.Queue() + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.send_header("Transfer-Encoding", "chunked") + self.end_headers() + for _ in range(provider.preamble_frames): + self._chunk(b": ping\n\n") + self._chunk( + f"event: endpoint\ndata: /mcp/messages/?session_id={session_id}" + f"\n\n".encode() + ) + deadline = time.monotonic() + IDLE_SECONDS + while time.monotonic() < deadline: + try: + message = provider.sessions[session_id].get( + timeout=PING_SECONDS + ) + except queue.Empty: + message = None + try: + if message is None: + self._chunk(b": ping\n\n") + else: + self._chunk(f"event: message\ndata: {message}\n\n".encode()) + except OSError: + return + + def do_POST(self): + parsed = urllib.parse.urlparse(self.path) + if not parsed.path.startswith("/mcp/messages/"): + self.send_error(405) + return + session_id = urllib.parse.parse_qs(parsed.query).get( + "session_id", [""] + )[0] + length = int(self.headers.get("Content-Length", "0")) + payload = json.loads(self.rfile.read(length) or b"{}") + self.send_response(202) + self.send_header("Content-Length", "0") + self.end_headers() + + method = payload.get("method") + answer = {"jsonrpc": "2.0", "id": payload.get("id")} + if method == provider.error_at: + answer["error"] = {"code": -32602, "message": "Invalid params"} + elif method == "initialize": + answer["result"] = { + "protocolVersion": "2025-06-18", + "capabilities": {}, + } + elif method == "tools/list": + answer["result"] = { + "tools": [{"name": name} for name in provider.tools] + } + else: + answer["result"] = {"isError": provider.is_error, "content": []} + provider.sessions[session_id].put(json.dumps(answer)) + + def _chunk(self, body): + self.wfile.write(f"{len(body):X}\r\n".encode() + body + b"\r\n") + self.wfile.flush() + + return Handler + + +def sse_env(provider, tools=TOOLS, read_tool="list_databases"): + """Return the probe environment addressing one fake SSE provider. + + Args: + provider: the FakeProvider to address. + tools: the tool names the contract declares. + read_tool: the deterministic read tool, or "" for none. + """ + return { + "MCP_URL": provider.url, + "MCP_TRANSPORT": "sse", + "MCP_PATH_KEY": KEY, + "MCP_EXPECTED_TOOLS": json.dumps(sorted(tools)), + "MCP_READ_TOOL": read_tool, + "MCP_READ_ARGUMENTS": "{}", + } + + +class TestSseSessionProbe(unittest.TestCase): + def serve(self, **kwargs): + provider = FakeProvider(**kwargs) + self.addCleanup(provider.stop) + return provider + + def test_a_conforming_sse_provider_passes(self): + provider = self.serve() + load(sse_env(provider)).main() + + def test_an_extra_upstream_tool_fails_closed(self): + provider = self.serve(tools=(*TOOLS, "delete_rows")) + module = load(sse_env(provider, tools=TOOLS)) + with ( + contextlib.redirect_stderr(io.StringIO()) as stderr, + self.assertRaises(SystemExit), + ): + module.main() + self.assertIn("delete_rows", stderr.getvalue()) + + def test_a_read_call_returning_an_error_result_fails(self): + provider = self.serve(is_error=True) + module = load(sse_env(provider)) + with ( + contextlib.redirect_stderr(io.StringIO()) as stderr, + self.assertRaises(SystemExit), + ): + module.main() + self.assertIn("error result", stderr.getvalue()) + + def test_an_endpoint_serving_any_path_key_fails(self): + provider = self.serve(guarded=False) + module = load(sse_env(provider)) + with ( + contextlib.redirect_stderr(io.StringIO()) as stderr, + self.assertRaises(SystemExit), + ): + module.main() + self.assertIn("unauthenticated probe answered 200", stderr.getvalue()) + + def test_a_json_rpc_error_on_tools_list_names_the_error(self): + provider = self.serve(error_at="tools/list") + module = load(sse_env(provider)) + with ( + contextlib.redirect_stderr(io.StringIO()) as stderr, + self.assertRaises(SystemExit), + ): + module.main() + self.assertIn("authenticated tools/list returned", stderr.getvalue()) + + def test_a_long_preamble_does_not_hide_the_endpoint_announcement(self): + provider = self.serve(preamble_frames=6) + load(sse_env(provider)).main() + + def test_an_unreachable_stream_keeps_the_caller_retrying(self): + module = load( + { + "MCP_URL": f"http://127.0.0.1:1/mcp/{KEY}/sse", + "MCP_TRANSPORT": "sse", + "MCP_PATH_KEY": KEY, + "MCP_EXPECTED_TOOLS": "[]", + "MCP_READ_TOOL": "", + "MCP_READ_ARGUMENTS": "{}", + } + ) + with ( + contextlib.redirect_stderr(io.StringIO()) as stderr, + self.assertRaises(SystemExit), + ): + module.main() + self.assertNotIn("REJECTED", stderr.getvalue()) + + def test_a_key_absent_from_the_probed_url_fails(self): + provider = self.serve() + module = load({**sse_env(provider), "MCP_PATH_KEY": "z" * 32}) + with ( + contextlib.redirect_stderr(io.StringIO()) as stderr, + self.assertRaises(SystemExit), + ): + module.main() + self.assertIn("absent from the probed URL", stderr.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_surface.py b/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_surface.py new file mode 100644 index 0000000000..44286c93f9 --- /dev/null +++ b/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_surface.py @@ -0,0 +1,65 @@ +"""How the contract probe tells upstream drift apart from a policy mismatch.""" + +from __future__ import annotations + +import importlib.util +import json +import unittest +from unittest.mock import patch + +from . import PROJECT_ROOT + +MODULE_PATH = PROJECT_ROOT / "roles/test-e2e-cli/files/shared/mcp/contract.py" + +BASE_ENV = { + "MCP_URL": "http://example:8080/mcp", + "MCP_TRANSPORT": "streamable_http", + "MCP_AUTH_HEADER": "Bearer token", +} + + +def load(*, allowlist, serves): + """Import the probe with one contract's expectations in the environment.""" + spec = importlib.util.spec_from_file_location("probe_contract", MODULE_PATH) + module = importlib.util.module_from_spec(spec) + env = { + **BASE_ENV, + "MCP_EXPECTED_TOOLS": json.dumps(allowlist), + "MCP_UPSTREAM_SERVES": json.dumps(serves), + } + with patch.dict("os.environ", env, clear=False): + spec.loader.exec_module(module) + return module + + +class TestAssertSurface(unittest.TestCase): + def test_a_matching_surface_passes(self) -> None: + module = load(allowlist=["read_post"], serves=[]) + module.assert_surface(["read_post"]) + + def test_a_policy_mismatch_names_the_contract(self) -> None: + module = load(allowlist=["read_post"], serves=[]) + with self.assertRaises(SystemExit): + module.assert_surface(["read_post", "delete_post"]) + + def test_upstream_drift_is_reported_before_policy(self) -> None: + """The recorded surface is stale, so the reader must be told the vendor + changed something, not that our own contract is wrong.""" + module = load(allowlist=["read_post"], serves=["read_post", "delete_post"]) + with self.assertRaises(SystemExit): + module.assert_surface(["read_post", "delete_post", "archive_channel"]) + + def test_a_recorded_difference_still_fails_policy(self) -> None: + module = load(allowlist=["read_post"], serves=["read_post", "delete_post"]) + with self.assertRaises(SystemExit): + module.assert_surface(["read_post", "delete_post"]) + + def test_an_unrecorded_surface_is_judged_on_policy_alone(self) -> None: + module = load(allowlist=["read_post"], serves=[]) + module.assert_surface(["read_post"]) + with self.assertRaises(SystemExit): + module.assert_surface(["read_post", "delete_post"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/test-e2e-playwright/test_config_timeouts_have_one_source.py b/tests/unit/python/roles/test-e2e-playwright/test_config_timeouts_have_one_source.py new file mode 100644 index 0000000000..d9741fba87 --- /dev/null +++ b/tests/unit/python/roles/test-e2e-playwright/test_config_timeouts_have_one_source.py @@ -0,0 +1,77 @@ +"""One source owns every Playwright timeout, and the config keeps no copy. + +The config and the role each held a literal for the same value. They drifted +without a sound: ``actionTimeout`` carried ``|| 30_000`` while nothing ever set +the variable, so every run used the unscaled 30 s, and ``expect`` had no entry +at all, leaving Playwright's built-in 5 s to govern every assertion over Tor +while its neighbours were scaled. The second login attempt in +``web-app-nextcloud`` died on ``expect(usernameField).toBeVisible()`` after 5 s +with 150 s around it. + +``vars/main.yml`` now owns the values, the harness renders them into the staged +``.env`` that both the deploy and ``scripts/tests/e2e/rerun-spec.sh`` pass, and +the config demands them rather than inventing one. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +from . import PROJECT_ROOT + +_ROLE = PROJECT_ROOT / "roles/test-e2e-playwright" +_CONFIG = _ROLE / "files/playwright.config.js" +_VARS = _ROLE / ROLE_FILE_VARS_MAIN +_LINT = PROJECT_ROOT / "scripts/lint/playwright.sh" +_SPOT = "TEST_E2E_PLAYWRIGHT_CONFIG_TIMEOUTS" + +_REQUIRED = re.compile(r'requiredTimeout\("(PLAYWRIGHT_\w+)"\)') +_ANY_READ = re.compile(r"process\.env\.(PLAYWRIGHT_\w*TIMEOUT\w*)") + + +class TestConfigTimeoutsHaveOneSource(unittest.TestCase): + def test_the_config_demands_exactly_what_the_role_renders(self) -> None: + demanded = set(_REQUIRED.findall(read_text(str(_CONFIG)))) + self.assertTrue( + demanded, + "no requiredTimeout call found in playwright.config.js; the regex " + "no longer matches how the config takes its timeouts, so this test " + "has stopped guarding anything", + ) + rendered = set(load_yaml_any(str(_VARS))[_SPOT]) + self.assertEqual( + demanded, + rendered, + f"the config and {_SPOT} must name the same timeouts: a demanded " + "one nobody renders aborts every run, and a rendered one nobody " + "demands is dead weight that reads as configuration", + ) + + def test_the_lint_stager_reads_the_same_map(self) -> None: + self.assertIn( + _SPOT, + read_text(str(_LINT)), + f"{_LINT.name} stages the config and runs 'playwright test --list', " + "which loads it and therefore hits the same demand. It has to take " + f"the names from {_SPOT}, or a rename leaves every role red with a " + "missing-variable abort that has nothing to do with its spec", + ) + + def test_the_config_keeps_no_timeout_of_its_own(self) -> None: + stray = set(_ANY_READ.findall(read_text(str(_CONFIG)))) + self.assertEqual( + set(), + stray, + "these timeouts are read straight from the environment, so a " + "literal beside them becomes a second source the role cannot see: " + + ", ".join(sorted(stray)), + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py b/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py new file mode 100644 index 0000000000..4fb7076704 --- /dev/null +++ b/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +import unittest + +from jinja2 import Environment + +from utils.cache.yaml import load_yaml_any + +from . import PROJECT_ROOT + +TASKS = PROJECT_ROOT / "roles/test-e2e-playwright/tasks/02_run_one.yml" +TASK_NAME = "โณ Wait until application is ready (any non-error response)" + + +def until_expression() -> str: + tasks = load_yaml_any(str(TASKS)) + for task in tasks: + if task.get("name") == TASK_NAME: + return task["until"] + raise AssertionError(f"task {TASK_NAME!r} not found in {TASKS}") + + +def settles(result: dict) -> bool: + template = Environment(autoescape=False).from_string( # noqa: S701 - ansible condition, not markup + "{{ " + until_expression() + " }}" + ) + return template.render(_wait_result=result) == "True" + + +class TestReadinessUntil(unittest.TestCase): + def test_a_connection_error_keeps_the_gate_waiting(self): + self.assertFalse(settles({"status": -1})) + + def test_a_missing_status_keeps_the_gate_waiting(self): + self.assertFalse(settles({})) + + def test_a_served_response_settles_the_gate(self): + self.assertTrue(settles({"status": 200})) + + def test_a_redirect_settles_the_gate(self): + self.assertTrue(settles({"status": 302})) + + def test_a_server_error_keeps_the_gate_waiting(self): + self.assertFalse(settles({"status": 502})) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/test-e2e-playwright/test_timeouts_helper.py b/tests/unit/python/roles/test-e2e-playwright/test_timeouts_helper.py index 2a4dc43aa2..daed87f110 100644 --- a/tests/unit/python/roles/test-e2e-playwright/test_timeouts_helper.py +++ b/tests/unit/python/roles/test-e2e-playwright/test_timeouts_helper.py @@ -60,7 +60,7 @@ class TestTimeoutsHelper(unittest.TestCase): def test_clearnet_default_factor_is_identity(self): out = self._run( "t.resolveTimeout(60000)", - {"CANONICAL_DOMAIN": '"x.infinito.example"'}, + {"CANONICAL_DOMAIN": '"x.infinito.test"'}, ) self.assertIn("RESULT:60000", out) @@ -75,7 +75,7 @@ class TestTimeoutsHelper(unittest.TestCase): out = self._run( "t.resolveTimeout(60000)", { - "CANONICAL_DOMAIN": "x.infinito.example", + "CANONICAL_DOMAIN": "x.infinito.test", "PLAYWRIGHT_TIMEOUT_FACTOR": "2", }, ) @@ -96,7 +96,7 @@ class TestTimeoutsHelper(unittest.TestCase): out = self._run( "t.resolveTimeout(60000)", { - "CANONICAL_DOMAIN": "x.infinito.example", + "CANONICAL_DOMAIN": "x.infinito.test", "PLAYWRIGHT_TIMEOUT_FACTOR": "0", }, ) @@ -113,9 +113,7 @@ class TestTimeoutsHelper(unittest.TestCase): ) self.assertIn( "RESULT:false", - self._run( - "t.isOnionTarget()", {"CANONICAL_DOMAIN": '"x.infinito.example"'} - ), + self._run("t.isOnionTarget()", {"CANONICAL_DOMAIN": '"x.infinito.test"'}), ) diff --git a/tests/unit/python/roles/web-app-baserow/files/sso/test_infinito_sso.py b/tests/unit/python/roles/web-app-baserow/files/sso/test_infinito_sso.py index b263fe7d7a..57ec5a90bb 100644 --- a/tests/unit/python/roles/web-app-baserow/files/sso/test_infinito_sso.py +++ b/tests/unit/python/roles/web-app-baserow/files/sso/test_infinito_sso.py @@ -10,11 +10,11 @@ from unittest.mock import MagicMock, patch from . import PROJECT_ROOT MODULE_PATH = PROJECT_ROOT / "roles/web-app-baserow/files/sso/infinito_sso.py" -HOSTNAME = "baserow.infinito.example" +HOSTNAME = "baserow.infinito.test" SSO_ON = {"PROXY_HEADER_SSO": "true"} IDENTITY = { "username": "alice", - "email": "alice@baserow.infinito.example", + "email": "alice@baserow.infinito.test", "name": "Alice Smith", "is_admin": False, } @@ -239,7 +239,7 @@ class TestFallbackDomain(unittest.TestCase): self.assertEqual(mod._fallback_domain(), HOSTNAME) def test_strips_scheme_and_path_from_a_url_shaped_hostname(self): - mod = _load_module(hostname="https://baserow.infinito.example/app") + mod = _load_module(hostname="https://baserow.infinito.test/app") with patch.dict(os.environ, {}, clear=True): self.assertEqual(mod._fallback_domain(), HOSTNAME) diff --git a/tests/unit/python/roles/web-app-bigbluebutton/filter_plugins/test_compose_mods.py b/tests/unit/python/roles/web-app-bigbluebutton/filter_plugins/test_compose_mods.py index 87a7385474..d5822c4e59 100644 --- a/tests/unit/python/roles/web-app-bigbluebutton/filter_plugins/test_compose_mods.py +++ b/tests/unit/python/roles/web-app-bigbluebutton/filter_plugins/test_compose_mods.py @@ -146,21 +146,21 @@ services: original, self.compose_repository_path, self.env_file, - extra_hosts=["auth.infinito.example:host-gateway"], + extra_hosts=["auth.infinito.test:host-gateway"], ) ) services = data["services"] self.assertIn( - "auth.infinito.example:host-gateway", services["greenlight"]["extra_hosts"] + "auth.infinito.test:host-gateway", services["greenlight"]["extra_hosts"] ) self.assertNotIn("extra_hosts", services["freeswitch"]) self.assertEqual( services["nginx"]["extra_hosts"], - ["existing.example:1.2.3.4", "auth.infinito.example:host-gateway"], + ["existing.example:1.2.3.4", "auth.infinito.test:host-gateway"], ) self.assertEqual( services["etherpad"]["extra_hosts"], - ["mapped.example:5.6.7.8", "auth.infinito.example:host-gateway"], + ["mapped.example:5.6.7.8", "auth.infinito.test:host-gateway"], ) def test_extra_hosts_absent_without_kwarg(self): diff --git a/tests/unit/python/roles/web-app-bookwyrm/files/sso/test_header_auth.py b/tests/unit/python/roles/web-app-bookwyrm/files/sso/test_header_auth.py index 22847959d8..ba4f6e9209 100644 --- a/tests/unit/python/roles/web-app-bookwyrm/files/sso/test_header_auth.py +++ b/tests/unit/python/roles/web-app-bookwyrm/files/sso/test_header_auth.py @@ -9,7 +9,7 @@ from unittest.mock import MagicMock from . import PROJECT_ROOT MODULE_PATH = PROJECT_ROOT / "roles/web-app-bookwyrm/files/sso/header_auth.py" -DOMAIN = "book.infinito.example" +DOMAIN = "book.infinito.test" class _FakeMiddlewareBase: diff --git a/tests/unit/python/roles/web-app-discourse/__init__.py b/tests/unit/python/roles/web-app-discourse/__init__.py new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/tests/unit/python/roles/web-app-discourse/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/python/roles/web-app-discourse/test_oidc_setting_order.py b/tests/unit/python/roles/web-app-discourse/test_oidc_setting_order.py new file mode 100644 index 0000000000..87ef01cba5 --- /dev/null +++ b/tests/unit/python/roles/web-app-discourse/test_oidc_setting_order.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +import unittest + +from utils.cache.files import PROJECT_ROOT, read_text + +SETTINGS = PROJECT_ROOT / "roles/web-app-discourse/files/ruby/apply_settings.rb" +PREREQUISITES = ( + "openid_connect_discovery_document", + "openid_connect_client_id", + "openid_connect_client_secret", +) + + +def _line_of(lines: list[str], setting: str) -> int: + return next( + index for index, line in enumerate(lines) if f"SiteSetting.{setting} = " in line + ) + + +class TestDiscourseOidcSettingOrder(unittest.TestCase): + def test_oidc_is_enabled_only_after_its_prerequisites_are_set(self) -> None: + lines = read_text(str(SETTINGS)).splitlines() + enable = _line_of(lines, "openid_connect_enabled") + for setting in PREREQUISITES: + with self.subTest(setting=setting): + self.assertLess( + _line_of(lines, setting), + enable, + "Discourse rejects openid_connect_enabled = true on a fresh " + "database until the discovery document, client ID and client " + "secret are set", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-flowise/__init__.py b/tests/unit/python/roles/web-app-flowise/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/web-app-flowise/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/web-app-flowise/files/__init__.py b/tests/unit/python/roles/web-app-flowise/files/__init__.py new file mode 100644 index 0000000000..9f69c70b47 --- /dev/null +++ b/tests/unit/python/roles/web-app-flowise/files/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] diff --git a/tests/unit/python/roles/web-app-flowise/files/reconcile/__init__.py b/tests/unit/python/roles/web-app-flowise/files/reconcile/__init__.py new file mode 100644 index 0000000000..86efabd459 --- /dev/null +++ b/tests/unit/python/roles/web-app-flowise/files/reconcile/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[7] diff --git a/tests/unit/python/roles/web-app-flowise/files/reconcile/test_mcp_servers.py b/tests/unit/python/roles/web-app-flowise/files/reconcile/test_mcp_servers.py new file mode 100644 index 0000000000..35e1bd78dd --- /dev/null +++ b/tests/unit/python/roles/web-app-flowise/files/reconcile/test_mcp_servers.py @@ -0,0 +1,412 @@ +"""Unit tests for ``roles/web-app-flowise/files/python/reconcile/mcp_servers.py``.""" + +from __future__ import annotations + +import importlib.util +import json +import unittest +from unittest.mock import patch + +from . import PROJECT_ROOT + +SCRIPT_PATH = ( + PROJECT_ROOT / "roles/web-app-flowise/files/python/reconcile/mcp_servers.py" +) + +SUPPORTED_SERVER = { + "id": "svc-db-qdrant", + "url": "http://qdrantmcp:8080/mcp", + "transport": "streamable_http", + "header": "Authorization", + "token": "Bearer secret", + "tools": [], +} + + +FIXTURE = {"id": "svc-db-qdrant", "tool": "qdrant_list_collections", "args": {}} + +DENIED = ("127.0.0.1", "169.254.169.254") +PROBE_NAME = "infinito:denylist-probe" + + +def load_script( + desired: list, + workspace: str = "ws-1", + transport: str = "streamable_http", + fixtures: list | None = None, +) -> object: + spec = importlib.util.spec_from_file_location("reconcile_mcp_servers", SCRIPT_PATH) + module = importlib.util.module_from_spec(spec) + with patch.dict( + "os.environ", + { + "FLOWISE_BASE": "http://localhost:3000", + "FLOWISE_API_KEY": "sk-test", + "FLOWISE_WORKSPACE": workspace, + "FLOWISE_MCP_DESIRED": json.dumps(desired), + "FLOWISE_MCP_TRANSPORT": transport, + "FLOWISE_MCP_FIXTURE": json.dumps( + [FIXTURE] if fixtures is None else fixtures + ), + }, + ): + spec.loader.exec_module(module) + return module + + +class FakeApi: + """Minimal stand-in for the Flowise custom-mcp-servers routes.""" + + def __init__( + self, + entries=(), + tools=None, + duplicate=False, + flows=(), + prediction=None, + permissive=False, + refuse_on_create=False, + create_error=None, + ): + self.permissive = permissive + self.refuse_on_create = refuse_on_create + self.create_error = create_error + self.entries = [dict(entry) for entry in entries] + if duplicate and self.entries: + self.entries.append(dict(self.entries[0], id="dup")) + self.tools = list(tools or []) + self.flows = [dict(flow) for flow in flows] + self.prediction = ( + prediction if prediction is not None else (200, {"text": "ok"}) + ) + self.authorized = [] + self.deleted = [] + self.created = [] + self.updated = [] + self.updated_payloads = [] + self.flows_created = [] + self.flows_updated = [] + self.flows_deleted = [] + self.predicted = [] + + def __call__(self, path, method="GET", payload=None): + if path.startswith("/api/v1/prediction/") and method == "POST": + self.predicted.append(path.rsplit("/", 1)[-1]) + return self.prediction + if path == "/api/v1/chatflows" and method == "GET": + return 200, [dict(flow) for flow in self.flows] + if path == "/api/v1/chatflows" and method == "POST": + created = dict(payload, id=f"flow-{payload['name']}") + self.flows.append(created) + self.flows_created.append(payload["name"]) + return 201, created + if path.startswith("/api/v1/chatflows/") and method == "PUT": + self.flows_updated.append(payload["name"]) + return 200, payload + if path.startswith("/api/v1/chatflows/") and method == "DELETE": + dead = path.rsplit("/", 1)[-1] + self.flows_deleted.append(dead) + self.flows = [f for f in self.flows if f["id"] != dead] + return 200, None + if path == "/api/v1/custom-mcp-servers" and method == "GET": + return 200, [dict(entry) for entry in self.entries] + if path == "/api/v1/custom-mcp-servers" and method == "POST": + url = str(payload.get("serverUrl") or "") + if self.create_error and any(bad in url for bad in DENIED): + return self.create_error + if self.refuse_on_create and any(bad in url for bad in DENIED): + return ( + 400, + '{"statusCode":400,"message":"Server URL is not allowed by policy"}', + ) + created = dict(payload, id=f"id-{payload['name']}") + self.entries.append(created) + if payload["name"] != PROBE_NAME: + self.created.append(payload["name"]) + return 201, created + if path.endswith("/authorize"): + entry_id = path.split("/")[-2] + entry = next((e for e in self.entries if e.get("id") == entry_id), {}) + url = str(entry.get("serverUrl") or "") + if not self.permissive and any(bad in url for bad in DENIED): + return 500, "blocked by HTTP_DENY_LIST" + self.authorized.append(entry_id) + return 200, {"status": "AUTHORIZED"} + if path.endswith("/tools"): + return 200, [{"name": name} for name in self.tools] + if method == "PUT": + self.updated.append(payload["name"]) + self.updated_payloads.append(payload) + return 200, payload + if method == "DELETE": + dead = path.rsplit("/", 1)[-1] + self.entries = [e for e in self.entries if e.get("id") != dead] + if PROBE_NAME not in dead: + self.deleted.append(dead) + return 200, None + raise AssertionError(f"unexpected {method} {path}") + + +class TestReconcileMcpServers(unittest.TestCase): + def test_an_unset_transport_aborts_instead_of_registering_nothing(self) -> None: + module = load_script([SUPPORTED_SERVER], transport="") + with ( + patch.object(module, "call", FakeApi()), + self.assertRaises(SystemExit) as exit_, + ): + module.main() + self.assertIn( + "FLOWISE_MCP_TRANSPORT is unset", + str(exit_.exception), + "an empty transport matches no provider, so the registry would " + "converge to empty and report success", + ) + + def test_a_provider_on_another_transport_is_refused_not_registered(self) -> None: + module = load_script([dict(SUPPORTED_SERVER, transport="sse")]) + with ( + patch.object(module, "call", FakeApi()), + self.assertRaises(SystemExit) as exit_, + ): + module.main() + self.assertIn("not streamable_http", str(exit_.exception)) + + def test_a_missing_entry_is_created_under_the_ownership_prefix(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi() + with patch.object(module, "call", api): + module.main() + self.assertEqual(["infinito:svc-db-qdrant"], api.created) + self.assertEqual(["id-infinito:svc-db-qdrant"], api.authorized) + + def test_an_existing_entry_is_updated_instead_of_duplicated(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi( + [ + { + "id": "e1", + "name": "infinito:svc-db-qdrant", + "serverUrl": SUPPORTED_SERVER["url"], + } + ] + ) + with patch.object(module, "call", api): + module.main() + self.assertEqual([], api.created) + self.assertEqual(["infinito:svc-db-qdrant"], api.updated) + + def test_a_rotated_token_replaces_the_one_the_entry_still_carries(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi( + [ + { + "id": "e1", + "name": "infinito:svc-db-qdrant", + "serverUrl": SUPPORTED_SERVER["url"], + "authType": "CUSTOM_HEADERS", + "authConfig": {"headers": {"Authorization": "Bearer stale"}}, + } + ] + ) + with patch.object(module, "call", api): + module.main() + + self.assertEqual(["infinito:svc-db-qdrant"], api.updated) + sent = json.dumps(api.updated_payloads) + self.assertIn("Bearer secret", sent) + self.assertNotIn("stale", sent) + + def test_two_entries_of_one_name_abort_rather_than_guess(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi([{"id": "e1", "name": "infinito:svc-db-qdrant"}], duplicate=True) + with patch.object(module, "call", api), self.assertRaises(SystemExit) as exit_: + module.main() + self.assertIn("2 registry entries", str(exit_.exception)) + + def test_a_human_entry_is_never_deleted(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi([{"id": "human", "name": "my own server"}]) + with patch.object(module, "call", api): + module.main() + self.assertEqual([], api.deleted) + + def test_a_managed_entry_whose_provider_is_gone_is_deleted(self) -> None: + module = load_script([]) + api = FakeApi([{"id": "stale", "name": "infinito:web-app-removed"}]) + with patch.object(module, "call", api): + module.main() + self.assertEqual(["stale"], api.deleted) + + def test_an_unexpected_tool_set_fails_closed(self) -> None: + module = load_script([dict(SUPPORTED_SERVER, tools=["baserow_search"])]) + api = FakeApi(tools=["baserow_search", "baserow_delete_row"]) + with patch.object(module, "call", api), self.assertRaises(SystemExit) as exit_: + module.main() + self.assertIn("must be reviewed", str(exit_.exception)) + + def test_the_declared_tool_contract_passes(self) -> None: + module = load_script([dict(SUPPORTED_SERVER, tools=["baserow_search"])]) + api = FakeApi(tools=["baserow_search"]) + with patch.object(module, "call", api): + module.main() + self.assertEqual(["id-infinito:svc-db-qdrant"], api.authorized) + + def test_the_fixture_flow_is_built_for_the_first_registered_candidate(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi() + with patch.object(module, "call", api): + module.main() + self.assertEqual(["infinito:fixture:svc-db-qdrant"], api.flows_created) + + def test_a_second_run_updates_the_fixture_instead_of_duplicating_it(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi(flows=[{"id": "f1", "name": "infinito:fixture:svc-db-qdrant"}]) + with patch.object(module, "call", api): + module.main() + self.assertEqual([], api.flows_created) + self.assertEqual(["infinito:fixture:svc-db-qdrant"], api.flows_updated) + + def test_the_fixture_carries_the_registry_id_not_a_bearer(self) -> None: + module = load_script([SUPPORTED_SERVER]) + flow = module.fixture_flow_data("entry-1", "qdrant_list_collections", {}) + serialised = json.dumps(flow) + self.assertIn("entry-1", serialised) + self.assertNotIn("secret", serialised) + self.assertNotIn("Bearer", serialised) + + def test_every_fixture_node_carries_the_keys_buildchatflow_iterates(self) -> None: + module = load_script([SUPPORTED_SERVER]) + flow = module.fixture_flow_data("entry-1", "qdrant_list_collections", {}) + for node in flow["nodes"]: + data = node["data"] + for key in ("inputParams", "inputAnchors", "outputAnchors"): + self.assertIsInstance( + data.get(key), + list, + f"node {node['id']} must expose {key} as a list; Flowise " + "iterates it and answers 500 'inputParams is not iterable'", + ) + + def test_the_fixture_calls_one_named_tool_without_a_model(self) -> None: + module = load_script([SUPPORTED_SERVER]) + flow = module.fixture_flow_data("entry-1", "qdrant_list_collections", {}) + tool = flow["nodes"][1]["data"] + self.assertEqual("toolAgentflow", tool["name"]) + self.assertEqual(1.2, tool["version"]) + self.assertEqual( + "customMcpServerTool", tool["inputs"]["toolAgentflowSelectedTool"] + ) + self.assertEqual( + "entry-1", tool["inputs"]["toolAgentflowSelectedToolConfig"]["mcpServerId"] + ) + self.assertEqual( + ["qdrant_list_collections"], + json.loads(tool["inputs"]["toolAgentflowSelectedToolConfig"]["mcpActions"]), + ) + self.assertEqual( + [], + [n for n in flow["nodes"] if "llm" in str(n["data"]["name"]).lower()], + ) + + def test_the_fixture_is_an_agentflow_the_prediction_route_can_run(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi() + with patch.object(module, "call", api): + module.main() + self.assertEqual( + ["AGENTFLOW"], [flow["type"] for flow in api.flows if flow.get("type")] + ) + self.assertEqual(["flow-infinito:fixture:svc-db-qdrant"], api.predicted) + + def test_a_failing_tool_call_fails_the_deploy(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi(prediction=(500, "upstream refused")) + with patch.object(module, "call", api), self.assertRaises(SystemExit) as exit_: + module.main() + self.assertIn("qdrant_list_collections", str(exit_.exception)) + + def test_an_error_body_is_not_read_as_a_successful_call(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi(prediction=(200, {"error": "tool not found"})) + with patch.object(module, "call", api), self.assertRaises(SystemExit) as exit_: + module.main() + self.assertIn("tool not found", str(exit_.exception)) + + def test_no_fixture_runs_when_no_candidate_is_registered(self) -> None: + module = load_script( + [SUPPORTED_SERVER], + fixtures=[{"id": "web-app-absent", "tool": "x", "args": {}}], + ) + api = FakeApi() + with patch.object(module, "call", api): + module.main() + self.assertEqual([], api.predicted) + self.assertEqual([], api.flows_created) + + def test_a_fixture_of_a_gone_provider_is_deleted(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi( + flows=[{"id": "old", "name": "infinito:fixture:web-app-prometheus"}] + ) + with patch.object(module, "call", api): + module.main() + self.assertEqual(["old"], api.flows_deleted) + + def test_loopback_and_metadata_are_probed_and_refused(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi() + with patch.object(module, "call", api): + module.main() + self.assertEqual( + ["http://127.0.0.1:80/mcp", "http://169.254.169.254/latest/meta-data/"], + module.DENIED_PROBES, + ) + self.assertNotIn(f"id-{PROBE_NAME}", api.authorized) + + def test_a_registry_that_refuses_the_denied_url_is_a_pass(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi(refuse_on_create=True) + with patch.object(module, "call", api): + module.main() + self.assertNotIn(f"id-{PROBE_NAME}", api.authorized) + + def test_a_create_that_fails_for_another_reason_still_fails(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi(create_error=(500, "upstream exploded")) + with patch.object(module, "call", api), self.assertRaises(SystemExit) as exit_: + module.main() + self.assertIn("deny-list probe", str(exit_.exception)) + + def test_a_flowise_that_reaches_loopback_fails_the_deploy(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi(permissive=True) + with patch.object(module, "call", api), self.assertRaises(SystemExit) as exit_: + module.main() + self.assertIn("HTTP_DENY_LIST", str(exit_.exception)) + + def test_the_deny_list_probe_leaves_no_entry_behind(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi() + with patch.object(module, "call", api): + module.main() + self.assertEqual([], [e for e in api.entries if e.get("name") == PROBE_NAME]) + + def test_a_human_chatflow_is_never_deleted(self) -> None: + module = load_script([SUPPORTED_SERVER]) + api = FakeApi(flows=[{"id": "mine", "name": "my own flow"}]) + with patch.object(module, "call", api): + module.main() + self.assertEqual([], api.flows_deleted) + + def test_the_token_is_sent_as_an_encrypted_custom_header(self) -> None: + module = load_script([SUPPORTED_SERVER]) + payload = module.desired_payload(SUPPORTED_SERVER) + self.assertEqual("CUSTOM_HEADERS", payload["authType"]) + self.assertEqual( + {"headers": {"Authorization": "Bearer secret"}}, payload["authConfig"] + ) + self.assertEqual("ws-1", payload["workspaceId"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-jellyfin/__init__.py b/tests/unit/python/roles/web-app-jellyfin/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-jellyfin/files/__init__.py b/tests/unit/python/roles/web-app-jellyfin/files/__init__.py new file mode 100644 index 0000000000..9f69c70b47 --- /dev/null +++ b/tests/unit/python/roles/web-app-jellyfin/files/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] diff --git a/tests/unit/python/roles/web-app-jellyfin/files/test_configure_auth.py b/tests/unit/python/roles/web-app-jellyfin/files/test_configure_auth.py new file mode 100644 index 0000000000..68b61f8838 --- /dev/null +++ b/tests/unit/python/roles/web-app-jellyfin/files/test_configure_auth.py @@ -0,0 +1,60 @@ +import re +import subprocess +import unittest + +from utils import PROJECT_ROOT +from utils.cache.files import read_text + +SCRIPT = PROJECT_ROOT / "roles/web-app-jellyfin/files/shell/configure-auth.sh" + +AUTH_RESPONSE = ( + '{"User":{"Name":"administrator","ServerId":"e5c","Id":"a1b2c3d4",' + '"HasPassword":true,"Configuration":{"PlayDefaultAudioTrack":true},' + '"Policy":{"IsAdministrator":true}},"SessionInfo":{"Id":"s1"},' + '"AccessToken":"tok-abc-123","ServerId":"e5c"}' +) + +_SED = re.compile(r"sed -n '(s/\.\*\"(?:AccessToken|User)\".*?/p)'") + + +def _apply(expression: str, payload: str) -> str: + done = subprocess.run( + ["sed", "-n", expression], + input=payload, + capture_output=True, + text=True, + check=True, + ) + return done.stdout.strip() + + +class TestConfigureAuthExtraction(unittest.TestCase): + """One AuthenticateByName response must yield both the token and the user id. + + Authenticating twice with the fixed DeviceId in CLIENT_HDR makes Jellyfin + revoke the first session, so the token from an earlier call is already dead + when the password change presents it. + """ + + def setUp(self) -> None: + self.source = read_text(str(SCRIPT)) + self.expressions = _SED.findall(self.source) + + def test_the_script_keeps_exactly_one_authenticate_call_site_per_field(self): + self.assertEqual(self.source.count("Users/AuthenticateByName"), 1) + + def test_one_response_yields_both_the_token_and_the_user_id(self): + self.assertEqual(len(self.expressions), 2) + extracted = { + _apply(expression, AUTH_RESPONSE) for expression in self.expressions + } + self.assertEqual(extracted, {"tok-abc-123", "a1b2c3d4"}) + + def test_a_response_without_a_token_extracts_nothing(self): + for expression in self.expressions: + with self.subTest(expression=expression): + self.assertEqual(_apply(expression, '{"Error":"Unauthorized"}'), "") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-jellyfin/files/test_provision_mcp_identity.py b/tests/unit/python/roles/web-app-jellyfin/files/test_provision_mcp_identity.py new file mode 100644 index 0000000000..90c09b8702 --- /dev/null +++ b/tests/unit/python/roles/web-app-jellyfin/files/test_provision_mcp_identity.py @@ -0,0 +1,143 @@ +from __future__ import annotations + +import importlib.util +import io +import unittest +from contextlib import redirect_stdout +from typing import ClassVar +from unittest.mock import patch + +from . import PROJECT_ROOT + +SCRIPT_PATH = ( + PROJECT_ROOT / "roles/web-app-jellyfin/files/python/provision_mcp_identity.py" +) + +MCP_USER = "mcpreader" +USER_ID = "0e3f1c9a4b8d4f27a1c6d5e2b7a90f13" + +ENV: dict[str, str] = { + "JELLYFIN_BASE": "http://jellyfin:8096", + "JELLYFIN_ADMIN_USER": "administrator", + "JELLYFIN_ADMIN_PASSWORD": "a" * 32, + "MCP_USER": MCP_USER, + "MCP_PASSWORD": "b" * 32, + "MCP_DEVICE_ID": "infinito-deploy", +} + + +def load(current_token: str = ""): + spec = importlib.util.spec_from_file_location("provision_mcp_identity", SCRIPT_PATH) + module = importlib.util.module_from_spec(spec) + with patch.dict("os.environ", {**ENV, "MCP_CURRENT_TOKEN": current_token}): + spec.loader.exec_module(module) + return module + + +class ScriptedCalls: + """Answers the module's ``call`` from a table of (method, path prefix) rules. + + Args: + rules: ordered (method, path_prefix, answer) triples; the first match wins. + """ + + def __init__(self, rules): + self.rules = rules + self.seen: list[tuple[str, str]] = [] + + def __call__(self, method, path, payload=None, token=None): + self.seen.append((method, path)) + for rule_method, prefix, answer in self.rules: + if method == rule_method and path.startswith(prefix): + return answer + raise AssertionError(f"unscripted call: {method} {path}") + + def paths(self, method: str) -> list[str]: + return [path for seen_method, path in self.seen if seen_method == method] + + +AUTH = "/Users/AuthenticateByName" +TOKEN_OK = (200, {"AccessToken": "fresh-token"}) + + +def run(module, calls) -> str: + buffer = io.StringIO() + with patch.object(module, "call", calls), redirect_stdout(buffer): + module.main() + return buffer.getvalue() + + +class TestIdempotenceProbe(unittest.TestCase): + def test_a_live_stored_token_is_reused(self) -> None: + module = load(current_token="stored-token") + calls = ScriptedCalls( + [("POST", AUTH, TOKEN_OK), ("GET", "/System/Info", (200, {}))] + ) + self.assertEqual(run(module, calls), "UNCHANGED\nstored-token\n") + + def test_a_stale_stored_token_is_replaced(self) -> None: + module = load(current_token="stale-token") + calls = ScriptedCalls( + [("POST", AUTH, TOKEN_OK), ("GET", "/System/Info", (401, "expired"))] + ) + self.assertEqual(run(module, calls), "CHANGED\nfresh-token\n") + + def test_without_a_stored_token_the_fresh_one_is_printed(self) -> None: + module = load() + calls = ScriptedCalls([("POST", AUTH, TOKEN_OK)]) + self.assertEqual(run(module, calls), "CHANGED\nfresh-token\n") + self.assertNotIn("/System/Info", calls.paths("GET")) + + +class TestPasswordConvergence(unittest.TestCase): + EXISTING: ClassVar[list] = [{"Name": MCP_USER, "Id": USER_ID}] + + def _repair_rules(self, password_answer): + """Rules for a run whose MCP password no longer authenticates.""" + answers = iter([(401, "invalid"), TOKEN_OK, TOKEN_OK]) + return [ + ("POST", AUTH, None), + ("GET", "/Users", (200, self.EXISTING)), + ("POST", f"/Users/{USER_ID}/Policy", (204, None)), + ("POST", "/Users/Password", password_answer), + ], answers + + def _run_repair(self, password_answer) -> tuple[str, ScriptedCalls]: + module = load() + rules, answers = self._repair_rules(password_answer) + calls = ScriptedCalls(rules) + + def dispatch(method, path, payload=None, token=None): + calls.seen.append((method, path)) + if method == "POST" and path.startswith(AUTH): + return next(answers) + for rule_method, prefix, answer in rules: + if method == rule_method and path.startswith(prefix) and answer: + return answer + raise AssertionError(f"unscripted call: {method} {path}") + + buffer = io.StringIO() + with patch.object(module, "call", dispatch), redirect_stdout(buffer): + module.main() + return buffer.getvalue(), calls + + def test_a_drifted_password_is_converged_on_the_existing_user(self) -> None: + output, calls = self._run_repair((204, None)) + self.assertIn("fresh-token", output) + self.assertIn(f"/Users/Password?userId={USER_ID}", calls.paths("POST")) + + def test_a_repaired_password_is_reported_as_changed(self) -> None: + output, _ = self._run_repair((204, None)) + self.assertEqual(output.splitlines()[0], "CHANGED") + + def test_a_200_answer_to_the_password_write_is_accepted(self) -> None: + output, _ = self._run_repair((200, {})) + self.assertIn("fresh-token", output) + + def test_a_rejected_password_write_aborts(self) -> None: + with self.assertRaises(SystemExit): + self._run_repair((404, "no such user")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py b/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py index 84bbd98d06..008a48bd8f 100644 --- a/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py +++ b/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py @@ -139,6 +139,17 @@ class TestRealmImportJson(unittest.TestCase): client_ids = [c["clientId"] for c in realm["clients"]] self.assertNotIn(path_join([APP_URL, "saml/metadata"]), client_ids) + def test_the_declarative_profile_declares_uidnumber(self) -> None: + """Keycloak drops writes to an attribute the profile does not declare, and + the unmanaged-attribute policy is DISABLED by default, so an undeclared + uidNumber leaves the mattermost-id mapper with nothing to emit and the + OIDC callback fails on a user id of 0.""" + realm = json.loads(render([])) + provider = realm["components"]["org.keycloak.userprofile.UserProfileProvider"] + profile = json.loads(provider[0]["config"]["kc.user.profile.config"][0]) + declared = {attribute["name"] for attribute in profile["attributes"]} + self.assertIn("uidNumber", declared) + def test_realm_is_valid_json_with_one_saml_app(self) -> None: realm = json.loads(render(["web-app-suitecrm"])) clients = {c["clientId"]: c for c in realm["clients"]} @@ -156,6 +167,20 @@ class TestRealmImportJson(unittest.TestCase): client = next(c for c in realm["clients"] if c.get("protocol") == "saml") self.assertEqual(client["defaultClientScopes"], []) + def test_the_allowed_origins_mapper_stays_out_of_the_access_token(self) -> None: + """The claim grows with every registered origin and rides along in + X-Forwarded-Access-Token, where an app server's header limit ends the + request; Keycloak's own CORS reads client.webOrigins, not the claim.""" + realm = json.loads(render([])) + scope = next(s for s in realm["clientScopes"] if s["name"] == "web-origins") + mapper = next( + m + for m in scope["protocolMappers"] + if m["protocolMapper"] == "oidc-allowed-origins-mapper" + ) + self.assertEqual(mapper["config"]["access.token.claim"], "false") + self.assertEqual(mapper["config"]["introspection.token.claim"], "true") + def test_saml_client_maps_the_username_attribute_the_app_reads(self) -> None: realm = json.loads(render(["web-app-suitecrm"])) client = next(c for c in realm["clients"] if c.get("protocol") == "saml") diff --git a/tests/unit/python/roles/web-app-keycloak/test_build_realm_rbac_groups.py b/tests/unit/python/roles/web-app-keycloak/test_build_realm_rbac_groups.py index 59d83b3e8c..af85e3919f 100644 --- a/tests/unit/python/roles/web-app-keycloak/test_build_realm_rbac_groups.py +++ b/tests/unit/python/roles/web-app-keycloak/test_build_realm_rbac_groups.py @@ -1,6 +1,7 @@ import importlib.util import unittest from pathlib import Path +from typing import ClassVar current_dir = str(Path(__file__).parent) filter_plugin_path = str( @@ -173,5 +174,92 @@ class TestBuildRealmRbacGroupsTenant(unittest.TestCase): ) +class TestApplicationScopedRoles(unittest.TestCase): + """``mcp`` is granted per application, never by the unscoped role list.""" + + APPLICATIONS: ClassVar[dict] = { + "web-app-baserow": {"rbac": {"roles": {"mcp": {"description": "MCP"}}}}, + "web-app-zammad": {"rbac": {"roles": {"mcp": {"description": "MCP"}}}}, + } + + def _groups(self, users): + return _by_path(build_realm_rbac_groups(self.APPLICATIONS, users, "roles")) + + def test_one_of_many_grants_only_the_named_application(self): + groups = self._groups( + { + "alice": { + "roles": [], + "password": "pw", + "application_roles": {"web-app-baserow": ["mcp"]}, + } + } + ) + self.assertEqual(groups["roles/web-app-baserow/mcp"], ["alice"]) + self.assertEqual(groups["roles/web-app-zammad/mcp"], []) + + def test_several_applications_can_be_granted_independently(self): + groups = self._groups( + { + "alice": { + "roles": [], + "password": "pw", + "application_roles": { + "web-app-baserow": ["mcp"], + "web-app-zammad": ["mcp"], + }, + } + } + ) + self.assertEqual(groups["roles/web-app-baserow/mcp"], ["alice"]) + self.assertEqual(groups["roles/web-app-zammad/mcp"], ["alice"]) + + def test_no_membership_grants_nothing(self): + groups = self._groups({"biber": {"roles": [], "password": "pw"}}) + self.assertEqual(groups["roles/web-app-baserow/mcp"], []) + self.assertEqual(groups["roles/web-app-zammad/mcp"], []) + + def test_wrong_application_grants_nothing_here(self): + groups = self._groups( + { + "alice": { + "roles": [], + "password": "pw", + "application_roles": {"web-app-nextcloud": ["mcp"]}, + } + } + ) + self.assertEqual(groups["roles/web-app-baserow/mcp"], []) + self.assertEqual(groups["roles/web-app-zammad/mcp"], []) + + def test_unscoped_mcp_role_grants_no_application(self): + groups = self._groups({"alice": {"roles": ["mcp"], "password": "pw"}}) + self.assertEqual(groups["roles/web-app-baserow/mcp"], []) + self.assertEqual(groups["roles/web-app-zammad/mcp"], []) + + def test_removing_the_last_grant_empties_every_group(self): + granted = { + "alice": { + "roles": [], + "password": "pw", + "application_roles": {"web-app-baserow": ["mcp"]}, + } + } + self.assertEqual(self._groups(granted)["roles/web-app-baserow/mcp"], ["alice"]) + revoked = {"alice": {"roles": [], "password": "pw", "application_roles": {}}} + self.assertEqual(self._groups(revoked)["roles/web-app-baserow/mcp"], []) + + def test_unscoped_roles_other_than_mcp_are_untouched(self): + applications = {"web-app-baserow": {"rbac": {"roles": {"editor": {}}}}} + groups = _by_path( + build_realm_rbac_groups( + applications, + {"alice": {"roles": ["editor"], "password": "pw"}}, + "roles", + ) + ) + self.assertEqual(groups["roles/web-app-baserow/editor"], ["alice"]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/web-app-mailu/lookup_plugins/test_mailu_users.py b/tests/unit/python/roles/web-app-mailu/lookup_plugins/test_mailu_users.py new file mode 100644 index 0000000000..bdaf0664da --- /dev/null +++ b/tests/unit/python/roles/web-app-mailu/lookup_plugins/test_mailu_users.py @@ -0,0 +1,96 @@ +from __future__ import annotations + +import importlib.util +import sys +import unittest +from typing import ClassVar +from unittest.mock import MagicMock, patch + +from ansible.errors import AnsibleError + +from . import PROJECT_ROOT + + +def _load_module(rel_path: str, name: str): + path = PROJECT_ROOT / rel_path + spec = importlib.util.spec_from_file_location(name, str(path)) + mod = importlib.util.module_from_spec(spec) + assert spec and spec.loader + sys.modules[name] = mod + spec.loader.exec_module(mod) + return mod + + +MODULE = _load_module( + "roles/web-app-mailu/lookup_plugins/mailu_users.py", "mailu_users" +) + + +class TestMailuUsers(unittest.TestCase): + CATALOGUE: ClassVar[dict] = { + "administrator": { + "username": "administrator", + "accounts": ["host", "mailbox", "identity"], + }, + "contact": {"username": "contact", "accounts": ["mailbox"]}, + "helpdesk": { + "username": "helpdesk", + "accounts": ["mailbox"], + "roles": ["bot"], + }, + "relay": {"username": "relay", "accounts": [], "roles": ["bot"]}, + "akaunting": {"username": "akaunting", "accounts": []}, + "arduino": {"username": "arduino"}, + "broken": "not-a-mapping", + } + + def setUp(self): + self.lookup = MODULE.LookupModule() + self.catalogue = dict(self.CATALOGUE) + + def _get(name, *args, **kwargs): + plugin = MagicMock() + plugin.run.side_effect = lambda terms, variables=None, **kw: [ + self.catalogue + ] + return plugin + + patcher = patch.object(MODULE.lookup_loader, "get", side_effect=_get) + patcher.start() + self.addCleanup(patcher.stop) + + def _run(self): + return self.lookup.run(None, variables={})[0] + + def test_selects_mailbox_holders_and_bots_only(self): + self.assertEqual( + sorted(self._run()), + ["administrator", "contact", "helpdesk", "relay"], + ) + + def test_a_bot_without_a_mailbox_survives_the_filter(self): + """The token task gates on the role, so dropping it would stop issuing + that bot a token.""" + self.assertIn("relay", self._run()) + + def test_users_no_mailu_task_acts_on_are_dropped(self): + selected = self._run() + self.assertNotIn("akaunting", selected) + self.assertNotIn("arduino", selected) + + def test_entries_keep_the_shape_lookup_users_yields(self): + self.assertEqual(self._run()["contact"], self.CATALOGUE["contact"]) + + def test_a_non_list_accounts_declaration_is_loud(self): + self.catalogue = {"bent": {"username": "bent", "accounts": "mailbox"}} + with self.assertRaises(AnsibleError) as ctx: + self._run() + self.assertIn("bent", str(ctx.exception)) + + def test_positional_terms_are_rejected(self): + with self.assertRaises(AnsibleError): + self.lookup.run(["mailbox"], variables={}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-matrix/__init__.py b/tests/unit/python/roles/web-app-matrix/__init__.py index e69de29bb2..8ee16d7567 100644 --- a/tests/unit/python/roles/web-app-matrix/__init__.py +++ b/tests/unit/python/roles/web-app-matrix/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/web-app-matrix/lookup_plugins/test_matrix_bridge_mounts.py b/tests/unit/python/roles/web-app-matrix/lookup_plugins/test_matrix_bridge_mounts.py index f7a580450a..41fbf7bdd2 100644 --- a/tests/unit/python/roles/web-app-matrix/lookup_plugins/test_matrix_bridge_mounts.py +++ b/tests/unit/python/roles/web-app-matrix/lookup_plugins/test_matrix_bridge_mounts.py @@ -4,7 +4,6 @@ from __future__ import annotations import importlib.util import unittest -import unittest.mock as mock from ansible.errors import AnsibleError @@ -28,17 +27,12 @@ class _DummyTemplar: return value -class _FakeContainerLookup: - def run(self, terms, variables=None, **kwargs): - assert terms == ["web-app-matrix", "directories.instance"], terms - return ["/opt/instances/matrix/"] - - def _vars(**extra): base = { - "application_id": "web-app-matrix", "MATRIX_BRIDGES": [{"bridge_name": "meta"}, {"bridge_name": "signal"}], - "MATRIX_REGISTRATION_FILE_FOLDER": "/data/", + "MATRIX_BRIDGE_SOURCE_DIR": "/opt/instances/matrix/config/mautrix", + "MATRIX_BRIDGE_CONFIG_TARGET": "/config/config.yaml", + "MATRIX_REGISTRATION_FILE_FOLDER": "/registrations/", } base.update(extra) return base @@ -49,50 +43,90 @@ class TestMatrixBridgeMounts(unittest.TestCase): def setUpClass(cls): cls.module = _load_module() - def _make(self, variables): + def _run(self, terms, vars_=None): + vars_ = _vars() if vars_ is None else vars_ lm = self.module.LookupModule() - lm._templar = _DummyTemplar(variables) + lm._templar = _DummyTemplar(vars_) lm._loader = None - return lm + return lm.run(terms, variables=vars_) - def _run(self, vars_): - lm = self._make(vars_) - with mock.patch.object(self.module, "lookup_loader") as loader_mock: - loader_mock.get.return_value = _FakeContainerLookup() - return lm.run([], variables=vars_) - - def test_one_mount_per_bridge(self): - result = self._run(_vars()) + def test_stack_declares_both_files_of_every_bridge(self): self.assertEqual( - result, + self._run(["stack"]), + [ + { + "mautrix_meta_config": { + "file": "/opt/instances/matrix/config/mautrix/meta/config.yaml" + }, + "mautrix_meta_registration": { + "file": "/opt/instances/matrix/config/mautrix/meta/registration.yaml" + }, + "mautrix_signal_config": { + "file": "/opt/instances/matrix/config/mautrix/signal/config.yaml" + }, + "mautrix_signal_registration": { + "file": "/opt/instances/matrix/config/mautrix/signal/registration.yaml" + }, + } + ], + ) + + def test_synapse_mounts_one_registration_per_bridge(self): + self.assertEqual( + self._run(["synapse"]), [ [ - "/opt/instances/matrix/mautrix/meta:/data/mautrix-meta:ro", - "/opt/instances/matrix/mautrix/signal:/data/mautrix-signal:ro", + { + "source": "mautrix_meta_registration", + "target": "/registrations/mautrix-meta/registration.yaml", + "mode": 0o444, + }, + { + "source": "mautrix_signal_registration", + "target": "/registrations/mautrix-signal/registration.yaml", + "mode": 0o444, + }, ] ], ) - def test_no_bridges_yields_empty_list(self): - result = self._run(_vars(MATRIX_BRIDGES=[])) - self.assertEqual(result, [[]]) + def test_bridge_mounts_only_its_own_config(self): + self.assertEqual( + self._run(["bridge", "signal"]), + [ + [ + { + "source": "mautrix_signal_config", + "target": "/config/config.yaml", + "mode": 0o444, + } + ] + ], + ) - def test_terms_raise(self): - lm = self._make(_vars()) + def test_no_bridges_declares_nothing(self): + vars_ = _vars(MATRIX_BRIDGES=[]) + self.assertEqual(self._run(["stack"], vars_), [{}]) + self.assertEqual(self._run(["synapse"], vars_), [[]]) + + def test_unknown_view_raises(self): + for terms in ([], ["x"]): + with self.assertRaises(AnsibleError): + self._run(terms) + + def test_bridge_that_is_not_enabled_raises(self): with self.assertRaises(AnsibleError): - lm.run(["x"], variables=_vars()) + self._run(["bridge", "whatsapp"]) def test_missing_bridges_raises(self): vars_ = _vars() del vars_["MATRIX_BRIDGES"] - lm = self._make(vars_) with self.assertRaises(AnsibleError): - lm.run([], variables=vars_) + self._run(["stack"], vars_) def test_non_list_bridges_raises(self): - lm = self._make(_vars(MATRIX_BRIDGES="meta")) with self.assertRaises(AnsibleError): - lm.run([], variables=_vars(MATRIX_BRIDGES="meta")) + self._run(["stack"], _vars(MATRIX_BRIDGES="meta")) if __name__ == "__main__": diff --git a/tests/unit/python/roles/web-app-matrix/test_ca_trust_passthrough.py b/tests/unit/python/roles/web-app-matrix/test_ca_trust_passthrough.py new file mode 100644 index 0000000000..279a59c620 --- /dev/null +++ b/tests/unit/python/roles/web-app-matrix/test_ca_trust_passthrough.py @@ -0,0 +1,103 @@ +"""Every CA path synapse binds must reach the matrix container at that path. + +The mdad stack runs its own Docker daemon inside the matrix container, so a +bind source in ``matrix_synapse_container_extra_arguments`` is resolved in that +container's mount namespace rather than on the host. A path the compose service +never passes through therefore does not exist where synapse looks for it, and +``docker create`` refuses the unit before anything is logged about Matrix. + +Run 34348821577 lost a job to exactly that: ``vars.yml.j2`` mounted +``CA_TRUST.bundle_host`` while ``services.yml.j2`` passed only +``CA_TRUST.cert_host``, and synapse crash-looped on "bind source path does not +exist". The templates are read as text because rendering them needs a full +Ansible context, and the invariant is about what the two files say to each +other, not about the values. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.cache.files import read_text +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +from . import PROJECT_ROOT + +_ROLE = PROJECT_ROOT / "roles/web-app-matrix" +_MATRIX = _ROLE / "templates/flavor/ansible" +_VARS = _ROLE / ROLE_FILE_VARS_MAIN +_CA_GATE = "MATRIX_CA_INJECTED" + +_BOUND_BY_SYNAPSE = re.compile(r"src='?\s*~?\s*CA_TRUST\.(\w+)") +_PASSED_THROUGH = re.compile( + r"\{\{\s*CA_TRUST\.(\w+)\s*\}\}\s*:\s*\{\{\s*CA_TRUST\.(\w+)\s*\}\}" +) + + +class TestCaTrustPassthrough(unittest.TestCase): + def test_every_ca_path_synapse_mounts_is_passed_through_at_the_same_path( + self, + ) -> None: + wanted = set(_BOUND_BY_SYNAPSE.findall(read_text(str(_MATRIX / "vars.yml.j2")))) + self.assertTrue( + wanted, + "no CA_TRUST bind source found in vars.yml.j2 โ€” the regex no longer " + "matches how synapse's extra arguments are built, so this test has " + "stopped guarding anything", + ) + + services = read_text(str(_MATRIX / "services.yml.j2")) + same_path = { + source + for source, target in _PASSED_THROUGH.findall(services) + if source == target + } + + missing = sorted(wanted - same_path) + self.assertFalse( + missing, + "synapse binds CA_TRUST." + + ", CA_TRUST.".join(missing) + + " inside the nested daemon, but services.yml.j2 does not pass " + "it into the matrix container at the same absolute path. The " + "nested daemon resolves the source in the container's namespace, " + "so docker create fails with 'bind source path does not exist' " + "and matrix-synapse never starts. Add " + + " and ".join( + f"`- {{{{ CA_TRUST.{name} }}}}:{{{{ CA_TRUST.{name} }}}}:ro`" + for name in missing + ) + + " to the ca_injected block.", + ) + + def test_the_ca_blocks_are_gated_by_the_predicate_that_provisions_them( + self, + ) -> None: + drift = ( + "sys-svc-compose-ca provisions the CA material for exactly this " + "predicate, while TLS_MODE is global: on an onion deployment TLS " + "is off per app, the CA is never written, and compose bind-mounts " + "a path docker then creates as a directory. The restart once the " + "file appears fails with 'not a directory' (run 34653754175, " + "Matrix#1)" + ) + self.assertIn( + f"{_CA_GATE}: \"{{{{ lookup('ca_injected', application_id) | bool }}}}\"", + read_text(str(_VARS)), + drift, + ) + for name in ("services.yml.j2", "vars.yml.j2"): + with self.subTest(template=name): + template = read_text(str(_MATRIX / name)) + gate = next( + line + for line in template.splitlines() + if "CA_TRUST" in template and line.strip().startswith("{% if ") + if _CA_GATE in line or "TLS_MODE" in line + ) + self.assertIn(_CA_GATE, gate, drift) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/unit/python/roles/web-app-matrix/test_swarm_convergence_gates.py b/tests/unit/python/roles/web-app-matrix/test_swarm_convergence_gates.py new file mode 100644 index 0000000000..ae4a0369cb --- /dev/null +++ b/tests/unit/python/roles/web-app-matrix/test_swarm_convergence_gates.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +import re +import unittest + +from utils.cache.files import PROJECT_ROOT, read_text + +SERVICES = ( + PROJECT_ROOT / "roles/web-app-matrix/templates/flavor/compose/services.yml.j2" +) + + +class TestSwarmConvergenceGates(unittest.TestCase): + def test_bridge_health_does_not_wait_for_the_homeserver_ping(self) -> None: + probes = re.findall(r"/_matrix/mau/(\w+)", read_text(str(SERVICES))) + self.assertTrue(probes) + self.assertEqual( + set(probes), + {"live"}, + "a /ready probe waits for Synapse to reach the bridge, which swarm " + "only allows once the task is healthy", + ) + + def test_chatgpt_bot_waits_for_the_token_provisioning_issues(self) -> None: + guard = next( + line + for line in read_text(str(SERVICES)).splitlines() + if "plugins.chatgpt" in line and line.lstrip().startswith("{% if") + ) + self.assertIn( + "MATRIX_CHATGPT_ACCESS_TOKEN", + guard, + "the bot account and its token only exist after stack_host_provisioning, " + "so an earlier bot task fails its login until swarm's converge wait " + "calls it stuck", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-n8n/__init__.py b/tests/unit/python/roles/web-app-n8n/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/web-app-n8n/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/web-app-n8n/files/__init__.py b/tests/unit/python/roles/web-app-n8n/files/__init__.py new file mode 100644 index 0000000000..9f69c70b47 --- /dev/null +++ b/tests/unit/python/roles/web-app-n8n/files/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] diff --git a/tests/unit/python/roles/web-app-n8n/files/provision/__init__.py b/tests/unit/python/roles/web-app-n8n/files/provision/__init__.py new file mode 100644 index 0000000000..86efabd459 --- /dev/null +++ b/tests/unit/python/roles/web-app-n8n/files/provision/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[7] diff --git a/tests/unit/python/roles/web-app-n8n/files/provision/test_client.py b/tests/unit/python/roles/web-app-n8n/files/provision/test_client.py new file mode 100644 index 0000000000..d698b892dc --- /dev/null +++ b/tests/unit/python/roles/web-app-n8n/files/provision/test_client.py @@ -0,0 +1,267 @@ +"""Unit tests for ``roles/web-app-n8n/files/python/provision/client.py``.""" + +from __future__ import annotations + +import contextlib +import importlib.util +import io +import json +import unittest +from unittest.mock import patch + +from . import PROJECT_ROOT + +SCRIPT_PATH = PROJECT_ROOT / "roles/web-app-n8n/files/python/provision/client.py" + +PROVIDER = { + "id": "web-app-gitea", + "url": "http://gitea:3000/mcp/sse", + "token": "g" * 40, + "tools": ["gitea_list_repos", "gitea_get_issue"], +} + +ENV = { + "N8N_BASE": "http://n8n:5678", + "N8N_OWNER_EMAIL": "administrator@example.org", + "N8N_OWNER_PASSWORD": "x" * 48, + "N8N_API_KEY_NAME": "infinito:mcp", + "N8N_CLIENT_WORKFLOW": "infinito:mcp-agent", + "N8N_AI_CREDENTIAL": "infinito:litellm", + "N8N_CHAT_MODEL": "llama3", + "N8N_MCP_PROVIDERS": json.dumps([PROVIDER]), +} + +REFERENCE = {"id": "c1", "name": "infinito:mcp-client:web-app-gitea"} + + +def load_script(overrides=None) -> object: + spec = importlib.util.spec_from_file_location("provision_client", SCRIPT_PATH) + module = importlib.util.module_from_spec(spec) + with patch.dict("os.environ", {**ENV, **(overrides or {})}): + spec.loader.exec_module(module) + return module + + +class FakeApi: + """Minimal stand-in for the n8n rest and public API surfaces.""" + + def __init__(self, keys=(), workflows=(), credentials=()): + self.keys = [dict(key) for key in keys] + self.workflows = [dict(flow) for flow in workflows] + self.credentials = [dict(item) for item in credentials] + self.created_workflows = [] + self.updated_workflows = [] + self.deleted_workflows = [] + self.written_credentials = [] + self.deleted_credentials = [] + self.deleted_keys = [] + self.logins = 0 + self.minted = 0 + + def __call__(self, path, method="GET", payload=None, api_key=None): + if path == "/rest/login": + self.logins += 1 + return 200, {"data": {"id": "owner"}} + if path == "/rest/credentials" and method == "GET": + return 200, {"data": [dict(item) for item in self.credentials]} + if path == "/rest/credentials" and method == "POST": + self.minted += 1 + new = {"id": f"c{self.minted}", "name": payload["name"]} + self.written_credentials.append(payload) + self.credentials.append(new) + return 200, {"data": new} + if path.startswith("/rest/credentials/") and method == "PATCH": + self.written_credentials.append(payload) + return 200, {"data": {"id": path.rsplit("/", 1)[-1]}} + if path.startswith("/rest/credentials/") and method == "DELETE": + dead = path.rsplit("/", 1)[-1] + self.deleted_credentials.append(dead) + self.credentials = [c for c in self.credentials if c["id"] != dead] + return 200, {"success": True} + if path == "/rest/api-keys" and method == "GET": + return 200, {"data": [dict(key) for key in self.keys]} + if path == "/rest/api-keys" and method == "POST": + self.keys = [{"id": "k1", "label": payload["label"]}] + return 200, {"data": {"id": "k1", "rawApiKey": "n8n-raw-key"}} + if path.startswith("/rest/api-keys/") and method == "DELETE": + self.deleted_keys.append(path.rsplit("/", 1)[-1]) + return 200, {"success": True} + if path == "/api/v1/workflows" and method == "GET": + return 200, {"data": [dict(flow) for flow in self.workflows]} + if path == "/api/v1/workflows" and method == "POST": + self.created_workflows.append(payload) + return 200, dict(payload, id="w1", active=False) + if path.startswith("/api/v1/workflows/") and method == "PUT": + self.updated_workflows.append(payload) + return 200, payload + if path.startswith("/api/v1/workflows/") and method == "DELETE": + self.deleted_workflows.append(path.rsplit("/", 1)[-1]) + return 200, {"success": True} + raise AssertionError(f"unexpected {method} {path}") + + +class TestProvisionClient(unittest.TestCase): + def test_a_client_node_is_pinned_to_the_providers_allowlist(self) -> None: + module = load_script() + node = module.client_node(PROVIDER, REFERENCE, 2) + self.assertEqual("@n8n/n8n-nodes-langchain.mcpClientTool", node["type"]) + self.assertEqual("selected", node["parameters"]["include"]) + self.assertEqual( + ["gitea_get_issue", "gitea_list_repos"], + node["parameters"]["includeTools"], + ) + self.assertEqual("http://gitea:3000/mcp/sse", node["parameters"]["sseEndpoint"]) + self.assertEqual("bearerAuth", node["parameters"]["authentication"]) + + def test_a_tool_the_provider_calls_mutating_never_reaches_the_agent(self) -> None: + module = load_script() + provider = { + "id": "web-app-baserow", + "url": "http://baserow:8080/mcp", + "token": "b" * 40, + "tools": ["list_databases", "list_tables", "create_rows"], + "mutating": ["create_rows"], + } + node = module.client_node(provider, REFERENCE, 2) + self.assertEqual( + ["list_databases", "list_tables"], node["parameters"]["includeTools"] + ) + + def test_a_provider_without_an_allowlist_gets_no_tools(self) -> None: + module = load_script() + bare = {"id": "web-app-x", "url": "http://x/sse", "token": "t"} + node = module.client_node(bare, REFERENCE, 2) + self.assertEqual([], node["parameters"]["includeTools"]) + self.assertEqual("selected", node["parameters"]["include"]) + + def test_every_client_node_reaches_the_agent(self) -> None: + module = load_script() + body = module.workflow_body({"web-app-gitea": REFERENCE}) + self.assertEqual( + {"ai_tool": [[{"node": "Infinito Agent", "type": "ai_tool", "index": 0}]]}, + body["connections"]["mcp_web_app_gitea"], + ) + self.assertEqual("infinito:mcp-agent", body["name"]) + + def test_the_agent_reaches_the_gateway_model(self) -> None: + module = load_script() + body = module.workflow_body({"web-app-gitea": REFERENCE}) + model = next(node for node in body["nodes"] if node["id"] == "infinito-model") + self.assertEqual("llama3", model["parameters"]["model"]) + self.assertEqual( + {"openAiApi": {"name": "infinito:litellm"}}, model["credentials"] + ) + + def test_each_provider_gets_its_own_named_bearer(self) -> None: + module = load_script() + api = FakeApi() + with patch.object(module, "call", api): + module.main() + self.assertEqual( + ["infinito:mcp-client:web-app-gitea"], + [item["name"] for item in api.written_credentials], + ) + self.assertEqual({"token": "g" * 40}, api.written_credentials[0]["data"]) + + def test_the_agent_workflow_is_never_activated(self) -> None: + module = load_script() + api = FakeApi() + with patch.object(module, "call", api): + module.main() + self.assertEqual( + ["infinito:mcp-agent"], [flow["name"] for flow in api.created_workflows] + ) + + def test_the_run_leaves_no_api_key_behind(self) -> None: + module = load_script() + api = FakeApi() + with patch.object(module, "call", api): + module.main() + self.assertEqual(["k1"], api.deleted_keys) + + def test_a_rotated_provider_token_replaces_the_stored_one(self) -> None: + module = load_script() + api = FakeApi(credentials=[dict(REFERENCE)]) + with patch.object(module, "call", api): + module.main() + sent = api.written_credentials + self.assertEqual([{"token": "g" * 40}], [item["data"] for item in sent]) + self.assertNotIn("stale", json.dumps(sent)) + + def test_a_provider_that_vanished_loses_its_credential(self) -> None: + module = load_script({"N8N_MCP_PROVIDERS": "[]"}) + api = FakeApi( + credentials=[ + {"id": "gone", "name": "infinito:mcp-client:web-app-openproject"}, + {"id": "human", "name": "my own bearer"}, + ] + ) + with patch.object(module, "call", api): + module.main() + self.assertEqual(["gone"], api.deleted_credentials) + + def test_the_agent_workflow_goes_when_no_provider_is_left(self) -> None: + module = load_script({"N8N_MCP_PROVIDERS": "[]"}) + api = FakeApi( + workflows=[{"id": "agent", "name": "infinito:mcp-agent", "active": False}] + ) + with patch.object(module, "call", api): + module.main() + self.assertEqual(["agent"], api.deleted_workflows) + + def test_nothing_happens_when_there_is_nothing_to_reach(self) -> None: + module = load_script({"N8N_MCP_PROVIDERS": "[]"}) + api = FakeApi(credentials=[{"id": "human", "name": "my own bearer"}]) + out = io.StringIO() + with patch.object(module, "call", api), contextlib.redirect_stdout(out): + module.main() + self.assertEqual("OK", out.getvalue().strip()) + self.assertEqual([], api.deleted_credentials) + self.assertEqual([], api.created_workflows) + + def test_a_converged_deployment_reruns_unchanged(self) -> None: + module = load_script() + api = FakeApi( + credentials=[REFERENCE], + workflows=[ + { + "id": "agent", + "name": "infinito:mcp-agent", + "nodes": module.workflow_body({"web-app-gitea": REFERENCE})[ + "nodes" + ], + } + ], + ) + out = io.StringIO() + with patch.object(module, "call", api), contextlib.redirect_stdout(out): + module.main() + self.assertEqual("OK", out.getvalue().strip()) + + def test_two_managed_workflows_abort_rather_than_guess(self) -> None: + module = load_script() + api = FakeApi( + workflows=[ + {"id": "a", "name": "infinito:mcp-agent"}, + {"id": "b", "name": "infinito:mcp-agent"}, + ] + ) + with patch.object(module, "call", api), self.assertRaises(SystemExit) as exit_: + module.main() + self.assertIn("2 workflows", str(exit_.exception)) + + def test_two_managed_credentials_abort_rather_than_guess(self) -> None: + module = load_script() + api = FakeApi( + credentials=[ + {"id": "a", "name": "infinito:mcp-client:web-app-gitea"}, + {"id": "b", "name": "infinito:mcp-client:web-app-gitea"}, + ] + ) + with patch.object(module, "call", api), self.assertRaises(SystemExit) as exit_: + module.main() + self.assertIn("2 credentials", str(exit_.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-n8n/files/provision/test_mcp.py b/tests/unit/python/roles/web-app-n8n/files/provision/test_mcp.py new file mode 100644 index 0000000000..81dcecf03a --- /dev/null +++ b/tests/unit/python/roles/web-app-n8n/files/provision/test_mcp.py @@ -0,0 +1,324 @@ +"""Unit tests for ``roles/web-app-n8n/files/python/provision/mcp.py``.""" + +from __future__ import annotations + +import contextlib +import importlib.util +import io +import json +import unittest +from unittest.mock import patch + +from . import PROJECT_ROOT + +SCRIPT_PATH = PROJECT_ROOT / "roles/web-app-n8n/files/python/provision/mcp.py" + +ENV = { + "N8N_BASE": "http://n8n:5678", + "N8N_OWNER_EMAIL": "administrator@example.org", + "N8N_OWNER_PASSWORD": "x" * 48, + "N8N_API_KEY_NAME": "infinito:mcp", + "N8N_MCP_PATH": "infinito-mcp", + "N8N_MCP_TOKEN": "t" * 48, + "N8N_MCP_WORKFLOW": "infinito:mcp-server", + "N8N_MCP_CREDENTIAL": "infinito:mcp-bearer", +} + +REFERENCE = {"id": "c1", "name": "infinito:mcp-bearer"} + + +def load_script(overrides=None) -> object: + spec = importlib.util.spec_from_file_location("provision_mcp", SCRIPT_PATH) + module = importlib.util.module_from_spec(spec) + with patch.dict("os.environ", {**ENV, **(overrides or {})}): + spec.loader.exec_module(module) + return module + + +class FakeApi: + """Minimal stand-in for the n8n rest and public API surfaces.""" + + def __init__(self, keys=(), workflows=(), credentials=()): + self.keys = [dict(key) for key in keys] + self.workflows = [dict(flow) for flow in workflows] + self.credentials = [dict(item) for item in credentials] + self.created_workflows = [] + self.updated_workflows = [] + self.activated_workflows = [] + self.deleted_workflows = [] + self.written_credentials = [] + self.deleted_credentials = [] + self.deleted_keys = [] + self.logins = 0 + self.minted = 0 + + def __call__(self, path, method="GET", payload=None, api_key=None): + if path == "/rest/login": + self.logins += 1 + return 200, {"data": {"id": "owner"}} + if path == "/rest/credentials" and method == "GET": + return 200, {"data": [dict(item) for item in self.credentials]} + if path == "/rest/credentials" and method == "POST": + self.minted += 1 + new = {"id": f"c{self.minted}", "name": payload["name"]} + self.written_credentials.append(payload) + self.credentials.append(new) + return 200, {"data": new} + if path.startswith("/rest/credentials/") and method == "PATCH": + self.written_credentials.append(payload) + return 200, {"data": {"id": path.rsplit("/", 1)[-1]}} + if path.startswith("/rest/credentials/") and method == "DELETE": + dead = path.rsplit("/", 1)[-1] + self.deleted_credentials.append(dead) + self.credentials = [c for c in self.credentials if c["id"] != dead] + return 200, {"success": True} + if path == "/rest/api-keys" and method == "GET": + return 200, {"data": [dict(key) for key in self.keys]} + if path == "/rest/api-keys" and method == "POST": + self.keys = [{"id": "k1", "label": payload["label"]}] + return 200, {"data": {"id": "k1", "rawApiKey": "n8n-raw-key"}} + if path.startswith("/rest/api-keys/") and method == "DELETE": + self.deleted_keys.append(path.rsplit("/", 1)[-1]) + return 200, {"success": True} + if path == "/api/v1/workflows" and method == "GET": + return 200, {"data": [dict(flow) for flow in self.workflows]} + if path == "/api/v1/workflows" and method == "POST": + self.created_workflows.append(payload) + return 200, dict(payload, id="w1", active=False) + if path.startswith("/api/v1/workflows/") and method == "PUT": + self.updated_workflows.append(payload) + return 200, payload + if path.endswith("/activate") and method == "POST": + self.activated_workflows.append(path.split("/")[-2]) + return 200, {"active": True} + if path.startswith("/api/v1/workflows/") and method == "DELETE": + self.deleted_workflows.append(path.rsplit("/", 1)[-1]) + return 200, {"success": True} + raise AssertionError(f"unexpected {method} {path}") + + +class TestProvisionMcp(unittest.TestCase): + def test_a_missing_workflow_is_created_and_activated(self) -> None: + module = load_script() + api = FakeApi() + with patch.object(module, "call", api): + module.main() + self.assertEqual( + ["infinito:mcp-server"], [flow["name"] for flow in api.created_workflows] + ) + self.assertEqual(["w1"], api.activated_workflows) + + def test_the_trigger_always_requires_a_bearer(self) -> None: + module = load_script() + node = module.workflow_body(REFERENCE)["nodes"][0] + self.assertEqual("bearerAuth", node["parameters"]["authentication"]) + self.assertEqual("@n8n/n8n-nodes-langchain.mcpTrigger", node["type"]) + self.assertEqual(2, node["typeVersion"]) + + def test_the_trigger_carries_the_credential_the_bearer_lives_in(self) -> None: + module = load_script() + node = module.workflow_body(REFERENCE)["nodes"][0] + self.assertEqual({"httpBearerAuth": REFERENCE}, node["credentials"]) + + def test_the_bearer_is_stored_as_an_http_bearer_credential(self) -> None: + module = load_script() + api = FakeApi() + with patch.object(module, "call", api): + module.main() + self.assertEqual( + [ + { + "name": "infinito:mcp-bearer", + "type": "httpBearerAuth", + "data": {"token": "t" * 48}, + } + ], + api.written_credentials, + ) + + def test_an_existing_credential_is_overwritten_not_duplicated(self) -> None: + module = load_script() + api = FakeApi(credentials=[{"id": "c9", "name": "infinito:mcp-bearer"}]) + with patch.object(module, "call", api): + module.main() + node = api.created_workflows[0]["nodes"][0] + self.assertEqual("c9", node["credentials"]["httpBearerAuth"]["id"]) + + def test_a_rotated_bearer_replaces_the_one_the_credential_carries(self) -> None: + module = load_script() + api = FakeApi(credentials=[{"id": "c9", "name": "infinito:mcp-bearer"}]) + with patch.object(module, "call", api): + module.main() + self.assertEqual( + [{"token": "t" * 48}], + [item["data"] for item in api.written_credentials], + "n8n never hands an existing credential's secret back, so the " + "managed one is overwritten rather than compared; a run that " + "skipped the write would leave the revoked bearer in place", + ) + + def test_two_managed_credentials_abort_rather_than_guess(self) -> None: + module = load_script() + api = FakeApi( + credentials=[ + {"id": "a", "name": "infinito:mcp-bearer"}, + {"id": "b", "name": "infinito:mcp-bearer"}, + ] + ) + with patch.object(module, "call", api), self.assertRaises(SystemExit) as exit_: + module.main() + self.assertIn("2 credentials", str(exit_.exception)) + + def test_an_empty_bearer_aborts_before_anything_is_written(self) -> None: + module = load_script({"N8N_MCP_TOKEN": ""}) + api = FakeApi() + with patch.object(module, "call", api), self.assertRaises(SystemExit) as exit_: + module.main() + self.assertIn("unauthenticated", str(exit_.exception)) + self.assertEqual(0, api.logins) + + def test_a_stale_managed_key_is_replaced_not_guessed(self) -> None: + module = load_script() + api = FakeApi(keys=[{"id": "old", "label": "infinito:mcp"}]) + with patch.object(module, "call", api): + module.main() + self.assertEqual(["old", "k1"], api.deleted_keys) + + def test_the_run_leaves_no_api_key_behind(self) -> None: + module = load_script() + api = FakeApi() + with patch.object(module, "call", api): + module.main() + self.assertEqual(["k1"], api.deleted_keys) + + def test_two_managed_keys_abort_rather_than_guess(self) -> None: + module = load_script() + api = FakeApi( + keys=[ + {"id": "a", "label": "infinito:mcp"}, + {"id": "b", "label": "infinito:mcp"}, + ] + ) + with patch.object(module, "call", api), self.assertRaises(SystemExit) as exit_: + module.main() + self.assertIn("2 api keys", str(exit_.exception)) + + def test_an_existing_inactive_workflow_is_updated(self) -> None: + module = load_script() + api = FakeApi( + workflows=[{"id": "w1", "name": "infinito:mcp-server", "active": False}] + ) + with patch.object(module, "call", api): + module.main() + self.assertEqual([], api.created_workflows) + self.assertEqual( + ["infinito:mcp-server"], [flow["name"] for flow in api.updated_workflows] + ) + self.assertEqual(["w1"], api.activated_workflows) + + def test_an_active_workflow_still_gets_its_node_repaired(self) -> None: + module = load_script() + api = FakeApi( + workflows=[ + { + "id": "w1", + "name": "infinito:mcp-server", + "active": True, + "nodes": [{"parameters": {"authentication": "none"}}], + } + ] + ) + with patch.object(module, "call", api): + module.main() + node = api.updated_workflows[0]["nodes"][0] + self.assertEqual("bearerAuth", node["parameters"]["authentication"]) + self.assertIn("httpBearerAuth", node["credentials"]) + + def test_the_only_served_tool_is_the_connected_one(self) -> None: + module = load_script() + body = module.workflow_body(REFERENCE) + tool = body["nodes"][1] + self.assertEqual("@n8n/n8n-nodes-langchain.toolCode", tool["type"]) + self.assertEqual( + { + "infinito_health": { + "ai_tool": [ + [ + { + "node": "Infinito MCP Trigger", + "type": "ai_tool", + "index": 0, + } + ] + ] + } + }, + body["connections"], + ) + + def test_the_served_tool_declares_its_input_schema(self) -> None: + module = load_script() + tool = module.workflow_body(REFERENCE)["nodes"][1] + self.assertIs(True, tool["parameters"]["specifyInputSchema"]) + self.assertEqual("manual", tool["parameters"]["schemaType"]) + schema = json.loads(tool["parameters"]["inputSchema"]) + self.assertEqual(["echo"], schema["required"]) + self.assertIs(False, schema["additionalProperties"]) + + def test_the_served_tool_returns_a_string(self) -> None: + module = load_script() + tool = module.workflow_body(REFERENCE)["nodes"][1] + self.assertIn("JSON.stringify", tool["parameters"]["jsCode"]) + + def test_a_converged_deployment_reruns_unchanged(self) -> None: + module = load_script() + credential = {"id": "c9", "name": "infinito:mcp-bearer"} + api = FakeApi( + credentials=[credential], + workflows=[ + { + "id": "w1", + "name": "infinito:mcp-server", + "active": True, + "nodes": module.workflow_body(credential)["nodes"], + } + ], + ) + out = io.StringIO() + with patch.object(module, "call", api), contextlib.redirect_stdout(out): + module.main() + self.assertEqual("OK", out.getvalue().strip()) + + def test_resources_outside_the_managed_names_are_left_alone(self) -> None: + module = load_script() + api = FakeApi( + keys=[{"id": "human-key", "label": "someone else"}], + credentials=[{"id": "human-cred", "name": "someone else"}], + workflows=[{"id": "human-flow", "name": "someone else", "active": True}], + ) + with patch.object(module, "call", api): + module.main() + self.assertNotIn("human-key", api.deleted_keys) + self.assertEqual([], api.updated_workflows) + self.assertEqual( + ["infinito:mcp-server"], [flow["name"] for flow in api.created_workflows] + ) + self.assertEqual( + ["infinito:mcp-bearer"], [item["name"] for item in api.written_credentials] + ) + + def test_two_managed_workflows_abort_rather_than_guess(self) -> None: + module = load_script() + api = FakeApi( + workflows=[ + {"id": "a", "name": "infinito:mcp-server"}, + {"id": "b", "name": "infinito:mcp-server"}, + ] + ) + with patch.object(module, "call", api), self.assertRaises(SystemExit) as exit_: + module.main() + self.assertIn("2 workflows", str(exit_.exception)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_install.py b/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_install.py index b633104387..3b902b60f8 100644 --- a/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_install.py +++ b/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_install.py @@ -12,6 +12,11 @@ SOCKS_ERROR = ( "for https://garm3.nextcloud.com/api/v1/apps.json" ) TIMEOUT_ERROR = "cURL error 28: Connection timed out after 120002 milliseconds" +ARTIFACT_404 = ( + "Error: Client error: `GET https://github.com/ONLYOFFICE/onlyoffice-nextcloud" + "/releases/download/v10.2.0/onlyoffice.tar.gz` resulted in a " + "`404 Not Found` response:\nNot Found" +) def _load_module(rel_path: str, name: str): @@ -56,6 +61,11 @@ class TestNextcloudInstallStatus(unittest.TestCase): self.assertFalse(status["unavailable"]) self.assertFalse(_tolerated(status)) + def test_an_advertised_release_whose_artifact_is_gone_stays_fatal(self): + status = _status(stdout=ARTIFACT_404) + self.assertFalse(status["unavailable"]) + self.assertFalse(_tolerated(status)) + def test_an_incompatible_plugin_stays_terminal_and_not_runnable(self): status = _status( stdout="deck is not compatible with this version of the server" diff --git a/tests/unit/python/roles/web-app-nextcloud/test_oidc_addon_follows_sso.py b/tests/unit/python/roles/web-app-nextcloud/test_oidc_addon_follows_sso.py new file mode 100644 index 0000000000..3fa9e82bee --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_oidc_addon_follows_sso.py @@ -0,0 +1,68 @@ +"""The OIDC addon must not be on when Nextcloud has no SSO provider. + +``meta/addons/oidc_login.yml`` gates on ``lookup('sso_oidc_plugin')``, which the +applications render evaluates while it is still in flight. Under that re-entry +guard the merged view hands out service flags as their own Jinja text, and +``bool("{{ ... }}")`` is True: the lookup read ``services.ldap.enabled`` as +enabled on a deployment that has neither Keycloak nor OpenLDAP and announced +``oidc_login``. Nextcloud then advertised a login hand-off to a provider that is +not deployed, while ``templates/config/oidc.config.php.j2`` re-read the same +setting at task time and correctly wrote nothing. + +The stubbed lookup tests next to the plugin cannot see this: a stub resolves the +path but does not render it. This renders for real. +""" + +from __future__ import annotations + +import unittest + +from utils.cache import _reset_cache_for_tests +from utils.cache.applications import get_merged_applications + + +def _templar(variables: dict): + from ansible.parsing.dataloader import DataLoader + from ansible.template import Templar + + templar = Templar(loader=DataLoader(), variables=dict(variables)) + templar.available_variables = dict(variables) + return templar + + +def _addon_flags(*deployed: str) -> dict: + variables = {"group_names": list(deployed), "applications": {}} + _reset_cache_for_tests() + try: + applications = get_merged_applications( + variables=variables, templar=_templar(variables) + ) + finally: + _reset_cache_for_tests() + nextcloud = applications["web-app-nextcloud"] + addons = nextcloud.get("addons") or {} + services = nextcloud.get("services") or {} + return { + "sso": (services.get("sso") or {}).get("enabled"), + "ldap": (services.get("ldap") or {}).get("enabled"), + **{ + name: (addons.get(name) or {}).get("enabled") + for name in ("oidc_login", "user_oidc", "sociallogin") + }, + } + + +class TestOidcAddonFollowsSso(unittest.TestCase): + def test_no_provider_means_no_oidc_addon(self) -> None: + flags = _addon_flags("web-app-nextcloud") + + self.assertEqual(flags["sso"], False) + self.assertEqual( + (flags["oidc_login"], flags["user_oidc"], flags["sociallogin"]), + (False, False, False), + "no OIDC plugin may be announced without an SSO provider", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/test_sociallogin_provider_name.py b/tests/unit/python/roles/web-app-nextcloud/test_sociallogin_provider_name.py new file mode 100644 index 0000000000..cb1dc6ad33 --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_sociallogin_provider_name.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +import unittest + +from jinja2 import Environment + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_str + +ADDON = PROJECT_ROOT / "roles/web-app-nextcloud/meta/addons/sociallogin.yml" +UID_LIMIT = 64 +KEYCLOAK_SUB_LENGTH = 36 + + +def _provider_name_call() -> tuple: + config = load_yaml_str(read_text(str(ADDON)))["config"]["plugin_configuration"] + providers = next( + entry["configvalue"] + for entry in config + if entry["configkey"] == "custom_providers" + ) + calls = [] + + def lookup(*args): + calls.append(args) + return "" + + Environment(autoescape=True).from_string( + providers["custom_oidc"][0]["name"] + ).render(lookup=lookup) + return calls[0] + + +class TestSocialLoginProviderName(unittest.TestCase): + def test_the_provider_name_leaves_room_for_the_keycloak_sub(self) -> None: + kind, application_id, max_length = _provider_name_call() + self.assertEqual((kind, application_id), ("bounded_name", "web-app-keycloak")) + self.assertLessEqual( + max_length + 1 + KEYCLOAK_SUB_LENGTH, + UID_LIMIT, + 'Nextcloud rejects a sociallogin uid ("<name>-<sub>") over 64 chars', + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-openwebui/__init__.py b/tests/unit/python/roles/web-app-openwebui/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-openwebui/files/__init__.py b/tests/unit/python/roles/web-app-openwebui/files/__init__.py new file mode 100644 index 0000000000..9f69c70b47 --- /dev/null +++ b/tests/unit/python/roles/web-app-openwebui/files/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] diff --git a/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py b/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py new file mode 100644 index 0000000000..65304f0539 --- /dev/null +++ b/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py @@ -0,0 +1,526 @@ +from __future__ import annotations + +import asyncio +import importlib.util +import json +import unittest +from copy import deepcopy +from typing import ClassVar +from unittest.mock import patch + +from . import PROJECT_ROOT + +SCRIPT_PATH = ( + PROJECT_ROOT / "roles/web-app-openwebui/files/python/provision_mcp_grants.py" +) + + +def load_script( + groups: dict, members: dict | None = None, declared: list | None = None +) -> object: + spec = importlib.util.spec_from_file_location("provision_mcp_grants", SCRIPT_PATH) + module = importlib.util.module_from_spec(spec) + with patch.dict( + "os.environ", + { + "OPENWEBUI_BASE": "http://localhost:8080", + "OPENWEBUI_MCP_GROUPS": json.dumps(groups), + "OPENWEBUI_MCP_MEMBERS": json.dumps(members or {}), + "OPENWEBUI_MCP_CONNECTIONS": json.dumps(declared or []), + "OPENWEBUI_ADMIN_EMAIL": "administrator@example.org", + "OPENWEBUI_ADMIN_PASSWORD": "x" * 32, + }, + ): + spec.loader.exec_module(module) + return module + + +class FakeUser: + def __init__(self, user_id, role, email="", name=""): + self.id = user_id + self.role = role + self.email = email + self.name = name + + +class FakeBackend: + """Stands in for the open_webui models the script imports in-process.""" + + def __init__(self, users, keys=None): + self.users = list(users) + self.keys = dict(keys or {}) + self.created = [] + self.deleted = [] + + def install(self, monkey): + import types + + users = types.SimpleNamespace( + get_users=self._get_users, + get_user_api_key_by_id=self._get_key, + update_user_api_key_by_id=self._set_key, + delete_user_api_key_by_id=self._delete_key, + ) + auths = types.SimpleNamespace(insert_new_auth=self._insert_auth) + for name, attr, value in ( + ("open_webui.models.users", "Users", users), + ("open_webui.models.auths", "Auths", auths), + ("open_webui.utils.auth", "get_password_hash", self._hash), + ): + module = types.ModuleType(name) + setattr(module, attr, value) + monkey[name] = module + + async def _get_users(self): + return {"users": self.users, "total": len(self.users)} + + async def _get_key(self, user_id): + return self.keys.get(user_id) + + async def _set_key(self, user_id, key): + self.keys[user_id] = key + return True + + async def _delete_key(self, user_id): + self.deleted.append(user_id) + self.keys.pop(user_id, None) + return True + + async def _insert_auth(self, email, password, name, role): + created = FakeUser(f"created-{email}", role) + self.created.append(created) + self.users.append(created) + return created + + async def _hash(self, password): + return f"hashed-{password}" + + +class FakeApi: + """Minimal stand-in for the Open WebUI admin API used by the script.""" + + def __init__(self, connections, groups=(), duplicate=False): + self.connections = deepcopy(connections) + self.groups = [{"id": f"id-{name}", "name": name} for name in groups] + if duplicate and self.groups: + self.groups.append(dict(self.groups[0])) + self.writes = 0 + self.member_writes = 0 + + def __call__(self, path, key, payload=None): + if path == "/api/v1/groups/" and payload is None: + return 200, self.groups + if path == "/api/v1/groups/create": + created = {"id": f"id-{payload['name']}", "name": payload["name"]} + self.groups.append(created) + return 200, created + if path == "/api/v1/configs/tool_servers" and payload is None: + return 200, {"TOOL_SERVER_CONNECTIONS": deepcopy(self.connections)} + if path == "/api/v1/configs/tool_servers": + self.writes += 1 + self.connections = deepcopy(payload["TOOL_SERVER_CONNECTIONS"]) + return 200, None + if path.startswith("/api/v1/groups/id/") and path.endswith("/update"): + group_id = path[len("/api/v1/groups/id/") : -len("/update")] + for group in self.groups: + if group["id"] == group_id: + group["user_ids"] = list(payload["user_ids"]) + self.member_writes += 1 + return 200, group + raise AssertionError(f"update of unknown group {group_id}") + raise AssertionError(f"unexpected call to {path}") + + +def connection(server_id, kind="mcp"): + return { + "url": f"http://{server_id}/mcp", + "type": kind, + "auth_type": "bearer", + "key": "secret", + "config": {"enable": False, "access_grants": []}, + "info": {"id": server_id, "name": server_id}, + } + + +class TestDeclaredSetIsRegistered(unittest.TestCase): + """A provider that becomes reachable after the first run must still arrive. + + Open WebUI keeps the tool servers in its own config, so a deployment that + already holds connections answers every later read with them. Reading that + answer as the desired state leaves a newly declared provider registered + nowhere, with nothing failing. + """ + + GROUPS: ClassVar[dict] = { + "web-app-baserow": "/roles/web-app-baserow/mcp", + "svc-db-qdrant": "/roles/svc-db-qdrant/mcp", + } + + def test_a_newly_declared_provider_is_added(self) -> None: + module = load_script(self.GROUPS, declared=[connection("svc-db-qdrant")]) + api = FakeApi([connection("web-app-baserow")]) + + with patch.object(module, "call", api): + granted, changed = module.grant("sk-test") + + self.assertTrue(changed) + self.assertEqual( + ["svc-db-qdrant", "web-app-baserow"], + sorted(c["info"]["id"] for c in api.connections), + ) + self.assertEqual(["svc-db-qdrant", "web-app-baserow"], sorted(granted)) + + def test_an_already_registered_provider_is_not_duplicated(self) -> None: + module = load_script(self.GROUPS, declared=[connection("web-app-baserow")]) + api = FakeApi([connection("web-app-baserow")]) + + with patch.object(module, "call", api): + module.grant("sk-test") + + self.assertEqual( + ["web-app-baserow"], [c["info"]["id"] for c in api.connections] + ) + + def test_a_rotated_bearer_replaces_the_registered_one(self) -> None: + rotated = connection("web-app-baserow") + rotated["key"] = "rotated" + module = load_script(self.GROUPS, declared=[rotated]) + api = FakeApi([connection("web-app-baserow")]) + + with patch.object(module, "call", api): + module.grant("sk-test") + + self.assertEqual( + ["rotated"], + [c["key"] for c in api.connections if c["info"]["id"] == "web-app-baserow"], + "a client left holding the old bearer keeps a credential the provider " + "has already rejected, and nothing reports it", + ) + + def test_a_moved_endpoint_replaces_the_registered_url(self) -> None: + moved = connection("web-app-baserow") + moved["url"] = "http://baserow:80/mcp/moved/sse" + module = load_script(self.GROUPS, declared=[moved]) + api = FakeApi([connection("web-app-baserow")]) + + with patch.object(module, "call", api): + module.grant("sk-test") + + self.assertEqual( + ["http://baserow:80/mcp/moved/sse"], + [c["url"] for c in api.connections if c["info"]["id"] == "web-app-baserow"], + ) + + def test_an_undeclared_connection_keeps_its_own_endpoint(self) -> None: + module = load_script(self.GROUPS, declared=[connection("web-app-baserow")]) + api = FakeApi([connection("web-app-homeassistant")]) + + with patch.object(module, "call", api): + module.grant("sk-test") + + self.assertEqual( + ["http://web-app-homeassistant/mcp"], + [ + c["url"] + for c in api.connections + if c["info"]["id"] == "web-app-homeassistant" + ], + ) + + def test_a_connection_the_operator_added_survives(self) -> None: + module = load_script(self.GROUPS, declared=[connection("svc-db-qdrant")]) + api = FakeApi([connection("some-openapi-server", kind="openapi")]) + + with patch.object(module, "call", api): + module.grant("sk-test") + + self.assertIn("some-openapi-server", [c["info"]["id"] for c in api.connections]) + + +class TestProvisionMcpGrants(unittest.TestCase): + def test_only_mapped_mcp_connections_get_a_group_grant(self) -> None: + module = load_script({"web-app-baserow": "/roles/web-app-baserow/mcp"}) + api = FakeApi( + [ + connection("web-app-baserow"), + connection("web-app-homeassistant"), + connection("some-openapi-server", kind="openapi"), + ] + ) + + with patch.object(module, "call", api): + granted, changed = module.grant("sk-test") + + self.assertEqual(["web-app-baserow"], sorted(granted)) + self.assertTrue(changed) + by_id = {c["info"]["id"]: c for c in api.connections} + self.assertEqual( + [ + { + "principal_type": "group", + "principal_id": "id-/roles/web-app-baserow/mcp", + "permission": "read", + } + ], + by_id["web-app-baserow"]["config"]["access_grants"], + ) + self.assertEqual([], by_id["web-app-homeassistant"]["config"]["access_grants"]) + self.assertEqual([], by_id["some-openapi-server"]["config"]["access_grants"]) + + def test_a_server_is_enabled_only_together_with_its_grant(self) -> None: + module = load_script({"web-app-baserow": "/roles/web-app-baserow/mcp"}) + api = FakeApi( + [connection("web-app-baserow"), connection("web-app-homeassistant")] + ) + + with patch.object(module, "call", api): + module.grant("sk-test") + + by_id = {c["info"]["id"]: c for c in api.connections} + self.assertTrue(by_id["web-app-baserow"]["config"]["enable"]) + self.assertFalse( + by_id["web-app-homeassistant"]["config"]["enable"], + "an ungranted server must stay disabled; an enabled one with empty grants " + "is reachable by every administrator", + ) + + def test_a_second_run_writes_nothing(self) -> None: + module = load_script({"web-app-baserow": "/roles/web-app-baserow/mcp"}) + api = FakeApi([connection("web-app-baserow")]) + + with patch.object(module, "call", api): + module.grant("sk-test") + writes_after_first = api.writes + granted, changed = module.grant("sk-test") + + self.assertEqual(["web-app-baserow"], sorted(granted)) + self.assertFalse(changed) + self.assertEqual(writes_after_first, api.writes) + + def test_an_existing_group_is_reused_instead_of_recreated(self) -> None: + module = load_script({"web-app-baserow": "/roles/web-app-baserow/mcp"}) + api = FakeApi( + [connection("web-app-baserow")], groups=["/roles/web-app-baserow/mcp"] + ) + + with patch.object(module, "call", api): + module.grant("sk-test") + + self.assertEqual(1, len(api.groups)) + + def test_a_group_that_lost_its_last_member_is_emptied(self) -> None: + module = load_script( + {"web-app-baserow": "/roles/web-app-baserow/mcp"}, members={} + ) + api = FakeApi( + [connection("web-app-baserow")], groups=["/roles/web-app-baserow/mcp"] + ) + api.groups[0]["user_ids"] = ["stale-user"] + + with patch.object(module, "call", api): + module.grant("sk-test") + + self.assertEqual([], api.groups[0]["user_ids"]) + self.assertEqual(1, api.member_writes) + + def _grant_with_members(self, members, known_users): + module = load_script( + {"web-app-baserow": "/roles/web-app-baserow/mcp"}, members=members + ) + api = FakeApi( + [connection("web-app-baserow")], groups=["/roles/web-app-baserow/mcp"] + ) + api.groups[0]["user_ids"] = [] + backend = FakeBackend(known_users) + modules = {} + backend.install(modules) + + with patch.dict("sys.modules", modules), patch.object(module, "call", api): + module.grant("sk-test") + return api + + def test_a_declared_member_is_written_into_its_group(self) -> None: + api = self._grant_with_members( + {"web-app-baserow": [{"username": "biber", "email": "biber@example.org"}]}, + [FakeUser("u-biber", "user", email="biber@example.org", name="Biber")], + ) + + self.assertEqual(["u-biber"], api.groups[0]["user_ids"]) + self.assertEqual(1, api.member_writes) + + def test_a_member_is_matched_by_username_when_the_email_differs(self) -> None: + api = self._grant_with_members( + {"web-app-baserow": [{"username": "biber", "email": "unused@example.org"}]}, + [FakeUser("u-biber", "user", email="other@example.org", name="biber")], + ) + + self.assertEqual(["u-biber"], api.groups[0]["user_ids"]) + + def test_the_filter_that_renders_members_produces_what_this_script_consumes( + self, + ) -> None: + mcp_group_members = importlib.import_module( + "plugins.filter.mcp.group_members" + ).mcp_group_members + members = mcp_group_members( + { + "biber": { + "username": "biber", + "email": "biber@example.org", + "application_roles": {"web-app-baserow": ["mcp"]}, + } + }, + [{"id": "web-app-baserow"}], + "mcp-reader", + ) + + api = self._grant_with_members( + json.loads(json.dumps(members)), + [FakeUser("u-biber", "user", email="biber@example.org", name="Biber")], + ) + + self.assertEqual(["u-biber"], api.groups[0]["user_ids"]) + + def test_a_member_openwebui_never_saw_is_skipped(self) -> None: + api = self._grant_with_members( + {"web-app-baserow": [{"username": "biber", "email": "biber@example.org"}]}, + [FakeUser("u-other", "user", email="other@example.org", name="other")], + ) + + self.assertEqual([], api.groups[0]["user_ids"]) + self.assertEqual( + 0, + api.member_writes, + "a member who has never signed in must not trigger a write; the group " + "already matches the resolvable member set", + ) + + def test_a_group_already_matching_its_members_is_left_alone(self) -> None: + module = load_script( + {"web-app-baserow": "/roles/web-app-baserow/mcp"}, members={} + ) + api = FakeApi( + [connection("web-app-baserow")], groups=["/roles/web-app-baserow/mcp"] + ) + api.groups[0]["user_ids"] = [] + + with patch.object(module, "call", api): + module.grant("sk-test") + + self.assertEqual(0, api.member_writes) + + def test_two_groups_of_one_name_abort_rather_than_guess(self) -> None: + module = load_script({"web-app-baserow": "/roles/web-app-baserow/mcp"}) + api = FakeApi( + [connection("web-app-baserow")], + groups=["/roles/web-app-baserow/mcp"], + duplicate=True, + ) + + with patch.object(module, "call", api), self.assertRaises(SystemExit) as exit_: + module.grant("sk-test") + + self.assertIn("refusing to guess", str(exit_.exception)) + + def test_a_write_that_loses_a_connection_aborts(self) -> None: + module = load_script({"web-app-baserow": "/roles/web-app-baserow/mcp"}) + api = FakeApi([connection("web-app-baserow"), connection("web-app-jenkins")]) + + def losing_call(path, key, payload=None): + if path == "/api/v1/configs/tool_servers" and payload is not None: + payload = { + "TOOL_SERVER_CONNECTIONS": payload["TOOL_SERVER_CONNECTIONS"][:1] + } + return api(path, key, payload) + + with ( + patch.object(module, "call", losing_call), + self.assertRaises(SystemExit) as exit_, + ): + module.grant("sk-test") + + self.assertIn("the write lost ['web-app-jenkins']", str(exit_.exception)) + + def test_a_write_the_server_ignores_aborts(self) -> None: + module = load_script({"web-app-baserow": "/roles/web-app-baserow/mcp"}) + api = FakeApi([connection("web-app-baserow")]) + + def ignoring_call(path, key, payload=None): + if path == "/api/v1/configs/tool_servers" and payload is not None: + return 200, None + return api(path, key, payload) + + with ( + patch.object(module, "call", ignoring_call), + self.assertRaises(SystemExit) as exit_, + ): + module.grant("sk-test") + + self.assertIn("instead of one group grant", str(exit_.exception)) + + +class TestResolveApiKey(unittest.TestCase): + def _resolve(self, backend): + module = load_script({}) + modules = {} + backend.install(modules) + with patch.dict("sys.modules", modules): + return module, asyncio.run(module.resolve_api_key()) + + def test_an_existing_administrator_key_is_reused_and_kept(self) -> None: + backend = FakeBackend( + [FakeUser("u1", "user"), FakeUser("admin1", "admin")], + keys={"admin1": "sk-operator"}, + ) + + _module, (user_id, key, minted) = self._resolve(backend) + + self.assertEqual("admin1", user_id) + self.assertEqual("sk-operator", key) + self.assertFalse(minted, "an operator's own key must not be reported as minted") + self.assertEqual([], backend.created) + + def test_a_missing_key_is_minted_and_marked_for_removal(self) -> None: + backend = FakeBackend([FakeUser("admin1", "admin")]) + + _module, (user_id, key, minted) = self._resolve(backend) + + self.assertEqual("admin1", user_id) + self.assertTrue(key.startswith("sk-")) + self.assertTrue(minted) + self.assertEqual(key, backend.keys["admin1"]) + + def test_an_instance_without_users_gets_one_administrator(self) -> None: + backend = FakeBackend([]) + + _module, (user_id, _key, minted) = self._resolve(backend) + + self.assertEqual(["admin"], [user.role for user in backend.created]) + self.assertEqual(backend.created[0].id, user_id) + self.assertTrue(minted) + + def test_a_minted_key_is_dropped_even_when_granting_fails(self) -> None: + backend = FakeBackend([FakeUser("admin1", "admin")]) + module = load_script({}) + modules = {} + backend.install(modules) + + def exploding_grant(_key): + raise RuntimeError("boom") + + with patch.dict("sys.modules", modules): + admin_id, _key, minted = asyncio.run(module.resolve_api_key()) + self.assertTrue(minted) + try: + exploding_grant(_key) + except RuntimeError: + pass + finally: + asyncio.run(module.drop_api_key(admin_id)) + + self.assertEqual(["admin1"], backend.deleted) + self.assertNotIn("admin1", backend.keys) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-openwebui/templates/__init__.py b/tests/unit/python/roles/web-app-openwebui/templates/__init__.py new file mode 100644 index 0000000000..9f69c70b47 --- /dev/null +++ b/tests/unit/python/roles/web-app-openwebui/templates/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] diff --git a/tests/unit/python/roles/web-app-openwebui/templates/test_playwright_read_probes.py b/tests/unit/python/roles/web-app-openwebui/templates/test_playwright_read_probes.py new file mode 100644 index 0000000000..d867b092f9 --- /dev/null +++ b/tests/unit/python/roles/web-app-openwebui/templates/test_playwright_read_probes.py @@ -0,0 +1,95 @@ +"""``MCP_EXPECTED_TOOLS`` names the read probe each registered server declares. + +The bridge spec asserts that a server serves the tool its ``meta/mcp.yml`` +declares, and it learns which tool that is from this one env value. Rendered +wrong it does not fail: an empty map makes the spec skip the tool assertion for +every server and pass on the handshake alone, which is the weaker check it was +written to replace. + +The block is extracted from the template rather than restated here, so a change +to the template is a change to what this test renders. +""" + +from __future__ import annotations + +import json +import re +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar, trust_as_template + +from utils.cache.applications import get_application_defaults +from utils.cache.files import PROJECT_ROOT, read_text + +_TEMPLATE = PROJECT_ROOT / "roles/web-app-openwebui/templates/playwright.env.j2" +_BLOCK = re.compile( + r"\{%\s*set _read_probes.*?^MCP_EXPECTED_TOOLS=.*?$", + re.DOTALL | re.MULTILINE, +) +_SERVERS = ("web-app-gitea", "svc-db-qdrant", "web-svc-libretranslate") + + +def _render(server_ids: tuple[str, ...]) -> str: + """Render the template's own read-probe block for the given servers.""" + block = _BLOCK.search(read_text(str(_TEMPLATE))) + assert block, f"{_TEMPLATE} no longer carries the read-probe block" + variables = { + "applications": get_application_defaults(roles_dir=PROJECT_ROOT / "roles"), + "OPENWEBUI_MCP_SERVERS": [ + { + "id": server_id, + "url": f"http://{server_id}:8080/mcp", + "auth": "bearer_token", + "token": "irrelevant-to-this-test", + } + for server_id in server_ids + ], + } + templar = Templar(loader=DataLoader(), variables=variables) + return templar.template(trust_as_template(block.group(0))) + + +def _rendered_map(server_ids: tuple[str, ...]) -> dict: + """Return the map a spec reads, decoded the way the spec decodes it. + + ``dotenv_quote`` emits a quoted string with escaped inner quotes, which + ``decodeDotenvQuotedValue`` (personas/utils/dotenv.js:17-30) unwraps with a + JSON parse before the spec parses the payload itself. Decoding it once here + would compare against a string that never reaches a spec. + """ + line = _render(server_ids) + _, _, value = line.partition("=") + value = value.strip() + if value.startswith('"') and value.endswith('"'): + value = json.loads(value) + return json.loads(value) + + +class TestPlaywrightReadProbes(unittest.TestCase): + def test_every_server_gets_the_tool_its_role_declares(self) -> None: + rendered = _rendered_map(_SERVERS) + expected = { + server: ( + get_application_defaults(roles_dir=PROJECT_ROOT / "roles")[server] + .get("mcp", {}) + .get("tools", {}) + .get("read_probe", {}) + .get("tool", "") + ) + for server in _SERVERS + } + self.assertEqual(expected, rendered) + + def test_the_probes_are_non_empty_for_these_servers(self) -> None: + self.assertEqual([], [k for k, v in _rendered_map(_SERVERS).items() if not v]) + + def test_a_server_without_a_read_probe_renders_an_empty_string(self) -> None: + self.assertEqual({"web-app-pretix": ""}, _rendered_map(("web-app-pretix",))) + + def test_no_discovered_server_renders_an_empty_map(self) -> None: + self.assertEqual({}, _rendered_map(())) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-wordpress/__init__.py b/tests/unit/python/roles/web-app-wordpress/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/web-app-wordpress/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/web-app-wordpress/test_mcp_transport_guard.py b/tests/unit/python/roles/web-app-wordpress/test_mcp_transport_guard.py new file mode 100644 index 0000000000..86e38b87f0 --- /dev/null +++ b/tests/unit/python/roles/web-app-wordpress/test_mcp_transport_guard.py @@ -0,0 +1,51 @@ +"""The MCP transport guard covers the endpoint the specs probe. + +``infinito-mcp-abilities.php`` refuses every REST route under one namespace +prefix that the site cannot attribute to a user. The specs probe one concrete +endpoint. If the adapter ever moves out of that namespace the guard stops +guarding anything, and both negative specs keep passing on a surface nobody +protects, so the two are read against each other here. +""" + +from __future__ import annotations + +import re +import unittest + +from utils.cache.files import PROJECT_ROOT, read_text + +_ROLE = PROJECT_ROOT / "roles/web-app-wordpress" +_PLUGIN = _ROLE / "files/mu-plugins/infinito-mcp-abilities.php" +_SPECS = (_ROLE / "files/playwright/test-mcp-guest.js",) + +_GUARDED_PREFIX = re.compile(r"get_route\(\),\s*'/'\s*\),\s*'([\w-]+/)'") +_ENDPOINT = re.compile(r'MCP_ENDPOINT\s*=\s*"([^"]+)"') + + +class TestMcpTransportGuard(unittest.TestCase): + def test_the_guarded_prefix_covers_every_endpoint_the_specs_probe(self) -> None: + guarded = _GUARDED_PREFIX.search(read_text(str(_PLUGIN))) + self.assertIsNotNone( + guarded, + "no route prefix found in infinito-mcp-abilities.php; the regex no " + "longer matches how the transport guard scopes itself, so this " + "test has stopped guarding anything", + ) + prefix = guarded.group(1) + + for spec in _SPECS: + with self.subTest(spec=spec.name): + endpoint = _ENDPOINT.search(read_text(str(spec))) + self.assertIsNotNone(endpoint, f"no MCP_ENDPOINT in {spec.name}") + route = endpoint.group(1).removeprefix("/wp-json/") + self.assertTrue( + route.startswith(prefix), + f"{spec.name} probes {endpoint.group(1)}, which does not sit " + f"under the guarded prefix '{prefix}'. The guard would let " + "an anonymous initialize through while the negative specs " + "still pass against whatever else answers", + ) + + +if __name__ == "__main__": # pragma: no cover + unittest.main() diff --git a/tests/unit/python/scripts/tests/deploy/ci/test_dns53_sampler.py b/tests/unit/python/scripts/tests/deploy/ci/test_dns53_sampler.py index 6c6bda6006..d8ca33dc49 100644 --- a/tests/unit/python/scripts/tests/deploy/ci/test_dns53_sampler.py +++ b/tests/unit/python/scripts/tests/deploy/ci/test_dns53_sampler.py @@ -11,6 +11,7 @@ from __future__ import annotations import subprocess import tempfile import unittest +from pathlib import Path from utils.cache.files import PROJECT_ROOT @@ -106,13 +107,40 @@ class ZoneProbeNameTests(unittest.TestCase): def test_the_owned_zone_becomes_a_probe_name(self): self.assertEqual( - self._zone("no-resolv\naddress=/infinito.example/192.168.244.10\n"), - "rescue-probe.infinito.example", + self._zone("no-resolv\naddress=/infinito.test/192.168.244.10\n"), + "rescue-probe.infinito.test", ) def test_a_config_without_a_zone_yields_nothing(self): self.assertEqual(self._zone("no-resolv\nserver=192.0.2.1\n"), "") + def test_a_zone_declared_in_a_drop_in_is_found(self): + """svc-net-tor writes the onion zone to /etc/dnsmasq.d/tor-onion.conf + and leaves only a conf-dir pointer in the main file, so a probe that + reads the main file alone reports no zone on every Tor host.""" + with tempfile.TemporaryDirectory() as tmp: + drop_in_dir = Path(tmp) / "dnsmasq.d" + drop_in_dir.mkdir() + (drop_in_dir / "tor-onion.conf").write_text( + "address=/abc123.onion/127.0.0.1\n", encoding="utf-8" + ) + main = Path(tmp) / "dnsmasq.conf" + main.write_text(f"conf-dir={drop_in_dir},*.conf\n", encoding="utf-8") + proc = subprocess.run( + [ + "sh", + "-c", + 'DNS53_SAMPLER_LIB=1 . "$1" && zone_probe_name "$2"', + "sh", + str(SAMPLER), + str(main), + ], + capture_output=True, + text=True, + check=True, + ) + self.assertEqual(proc.stdout, "rescue-probe.abc123.onion") + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/cache/test_applications.py b/tests/unit/python/utils/cache/test_applications.py index af2812ef09..b62eff677a 100644 --- a/tests/unit/python/utils/cache/test_applications.py +++ b/tests/unit/python/utils/cache/test_applications.py @@ -19,9 +19,15 @@ from pathlib import Path from utils.cache import _reset_cache_for_tests from utils.cache import applications as cache_apps +from utils.cache.carrier import ( + APPLICATIONS_RENDERED_FACT, + merged_applications_cache_key, +) +from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ( ROLE_DIR_META_ADDONS, ROLE_FILE_META_MAIN, + ROLE_FILE_META_MCP, ROLE_FILE_META_SERVICES, ROLE_FILE_META_USERS, ROLE_FILE_META_VARIANTS, @@ -333,6 +339,71 @@ class TestGetMergedApplicationsRespectsOverrides(unittest.TestCase): ) +class TestGetMergedApplicationsCarrierFact(unittest.TestCase): + """The constructor renders once and parks the payload with its cache key in + `_INFINITO_APPLICATIONS_RENDERED`. A worker process whose in-process cache is + empty serves that payload when the key matches and renders only when it + does not. + """ + + def setUp(self) -> None: + _reset_cache_for_tests() + + @staticmethod + def _variables() -> dict: + return { + "applications": { + "web-app-foo": {"services": {"foo": {"image": "override"}}} + } + } + + def test_matching_key_serves_the_carried_payload_without_rendering(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_roles(Path(tmp)) + variables = self._variables() + key = merged_applications_cache_key(variables, roles_dir=roles) + carried = {"web-app-foo": {"carried": True}} + variables[APPLICATIONS_RENDERED_FACT] = { + "key": [key[0], list(key[1])], + "applications": carried, + } + merged = cache_apps.get_merged_applications( + variables=variables, roles_dir=roles, templar=None + ) + self.assertIs(merged, carried) + + def test_stale_key_falls_back_to_a_fresh_render(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_roles(Path(tmp)) + variables = self._variables() + key = merged_applications_cache_key(variables, roles_dir=roles) + variables[APPLICATIONS_RENDERED_FACT] = { + "key": [key[0], ["stale"] * len(key[1])], + "applications": {"web-app-foo": {"carried": True}}, + } + merged = cache_apps.get_merged_applications( + variables=variables, roles_dir=roles, templar=None + ) + self.assertNotIn("carried", merged["web-app-foo"]) + self.assertEqual( + merged["web-app-foo"]["services"]["foo"]["image"], "override" + ) + + def test_malformed_carrier_is_ignored(self): + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_roles(Path(tmp)) + for carrier in ("not-a-mapping", {"key": "x", "applications": {}}, {}): + _reset_cache_for_tests() + variables = self._variables() + variables[APPLICATIONS_RENDERED_FACT] = carrier + merged = cache_apps.get_merged_applications( + variables=variables, roles_dir=roles, templar=None + ) + self.assertEqual( + merged["web-app-foo"]["services"]["foo"]["image"], "override" + ) + + class TestRecursiveMetaWalk(unittest.TestCase): """`_build_role_base_config` walks the whole `meta/` tree: every `meta/**/*.yml` lands at the matching nested path under @@ -449,5 +520,137 @@ class TestApplicationsImportableWithoutAnsible(unittest.TestCase): self.assertIn("OK", result.stdout) +class TestDeriveMcpPresence(unittest.TestCase): + def setUp(self) -> None: + _reset_cache_for_tests() + + @staticmethod + def _seed_pair(tmp: Path) -> Path: + roles = tmp / "roles" + _write( + roles / "web-app-prov" / ROLE_FILE_META_SERVICES, + """ + prov: + image: prov + version: latest + cons: + mcp_consumer: true + """, + ) + _write( + roles / "web-app-prov" / ROLE_FILE_META_MCP, + """ + direction: server + """, + ) + _write( + roles / "web-app-cons" / ROLE_FILE_META_SERVICES, + """ + cons: + image: cons + version: latest + mcp_consumer: true + """, + ) + _write( + roles / "web-app-cons" / ROLE_FILE_META_MCP, + """ + direction: client + """, + ) + return roles + + def test_provider_resolves_to_its_admitted_consumers(self): + with tempfile.TemporaryDirectory() as tmp: + roles = self._seed_pair(Path(tmp)) + defaults = cache_apps.get_application_defaults(roles_dir=roles) + self.assertEqual( + defaults["web-app-prov"]["mcp"]["enabled"], + "{{ 'web-app-cons' in group_names }}", + ) + self.assertEqual( + defaults["web-app-prov"]["mcp"]["shared"], + defaults["web-app-prov"]["mcp"]["enabled"], + ) + + def test_provider_that_excludes_its_only_consumer_resolves_to_false(self): + with tempfile.TemporaryDirectory() as tmp: + roles = self._seed_pair(Path(tmp)) + _write( + roles / "web-app-prov" / ROLE_FILE_META_SERVICES, + """ + prov: + image: prov + version: latest + cons: + mcp_consumer: false + """, + ) + defaults = cache_apps.get_application_defaults(roles_dir=roles) + self.assertIs(defaults["web-app-prov"]["mcp"]["enabled"], False) + + def test_configured_value_wins_over_the_derivation(self): + with tempfile.TemporaryDirectory() as tmp: + roles = self._seed_pair(Path(tmp)) + _write( + roles / "web-app-prov" / ROLE_FILE_META_MCP, + """ + direction: server + enabled: false + shared: false + """, + ) + defaults = cache_apps.get_application_defaults(roles_dir=roles) + self.assertIs(defaults["web-app-prov"]["mcp"]["enabled"], False) + + def test_every_variant_carries_the_derived_value(self): + with tempfile.TemporaryDirectory() as tmp: + roles = self._seed_pair(Path(tmp)) + _write( + roles / "web-app-prov" / ROLE_FILE_META_VARIANTS, + """ + - {} + - services: + prov: + image: prov-alt + """, + ) + variants = cache_apps.get_variants(roles_dir=roles)["web-app-prov"] + self.assertEqual(len(variants), 2) + for variant in variants: + self.assertEqual( + variant["mcp"]["enabled"], + "{{ 'web-app-cons' in group_names }}", + ) + + def test_derivation_leaves_the_yaml_cache_untouched(self): + with tempfile.TemporaryDirectory() as tmp: + roles = self._seed_pair(Path(tmp)) + mcp_path = roles / "web-app-prov" / ROLE_FILE_META_MCP + cache_apps.get_application_defaults(roles_dir=roles) + raw = load_yaml_any(str(mcp_path), default_if_missing={}) + self.assertNotIn("enabled", raw) + self.assertNotIn("shared", raw) + + def test_variant_override_wins_over_the_derivation(self): + with tempfile.TemporaryDirectory() as tmp: + roles = self._seed_pair(Path(tmp)) + _write( + roles / "web-app-prov" / ROLE_FILE_META_VARIANTS, + """ + - {} + - mcp: + enabled: false + shared: false + """, + ) + variants = cache_apps.get_variants(roles_dir=roles)["web-app-prov"] + self.assertEqual( + variants[0]["mcp"]["enabled"], + "{{ 'web-app-cons' in group_names }}", + ) + self.assertIs(variants[1]["mcp"]["enabled"], False) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/cache/test_base.py b/tests/unit/python/utils/cache/test_base.py index ef3071d3ae..044cd168e9 100644 --- a/tests/unit/python/utils/cache/test_base.py +++ b/tests/unit/python/utils/cache/test_base.py @@ -111,23 +111,45 @@ class TestStableVariablesSignature(unittest.TestCase): def test_empty_variables_collapses_to_canonical_tuple(self): self.assertEqual( base._stable_variables_signature(None), - ("0", "0", "", ""), + ("0", "0", "", "", ""), ) self.assertEqual( base._stable_variables_signature({}), - ("0", "0", "", ""), + ("0", "0", "", "", ""), ) + def test_two_hosts_of_one_play_do_not_share_a_key(self): + shared = {"applications": {"web-app-pretix": {}}, "DOMAIN_PRIMARY": "x.test"} + member = base._stable_variables_signature( + {**shared, "group_names": ["web-app-pretix", "svc-db-postgres"]} + ) + outsider = base._stable_variables_signature( + {**shared, "group_names": ["web-app-pretix"]} + ) + + self.assertNotEqual( + member, + outsider, + "a service flag may read group_names, so one host's payload must " + "never answer for a host whose groups differ", + ) + + def test_group_order_does_not_split_the_key(self): + first = base._stable_variables_signature({"group_names": ["a", "b"]}) + second = base._stable_variables_signature({"group_names": ["b", "a"]}) + + self.assertEqual(first, second) + def test_includes_domain_primary_and_email_domain_strings(self): sig = base._stable_variables_signature( { "applications": {"web-app-x": {}}, - "DOMAIN_PRIMARY": "infinito.example", - "SYSTEM_EMAIL_DOMAIN": "mail.infinito.example", + "DOMAIN_PRIMARY": "infinito.test", + "SYSTEM_EMAIL_DOMAIN": "mail.infinito.test", } ) - self.assertEqual(sig[2], "infinito.example") - self.assertEqual(sig[3], "mail.infinito.example") + self.assertEqual(sig[2], "infinito.test") + self.assertEqual(sig[3], "mail.infinito.test") class TestTokensFileSignature(unittest.TestCase): diff --git a/tests/unit/python/utils/cache/test_data.py b/tests/unit/python/utils/cache/test_data.py index 9744417d79..c8ce41ad14 100644 --- a/tests/unit/python/utils/cache/test_data.py +++ b/tests/unit/python/utils/cache/test_data.py @@ -129,8 +129,8 @@ class TestStableVariablesSignature(unittest.TestCase): _reset_cache_for_tests() def test_empty_variables_returns_sentinel(self): - self.assertEqual(_stable_variables_signature(None), ("0", "0", "", "")) - self.assertEqual(_stable_variables_signature({}), ("0", "0", "", "")) + self.assertEqual(_stable_variables_signature(None), ("0", "0", "", "", "")) + self.assertEqual(_stable_variables_signature({}), ("0", "0", "", "", "")) def test_captures_key_subset(self): sig = _stable_variables_signature( diff --git a/tests/unit/python/utils/cache/test_domains.py b/tests/unit/python/utils/cache/test_domains.py index d5ab47fa79..c884e16db2 100644 --- a/tests/unit/python/utils/cache/test_domains.py +++ b/tests/unit/python/utils/cache/test_domains.py @@ -18,6 +18,7 @@ from unittest.mock import patch from utils.cache import _reset_cache_for_tests from utils.cache import domains as cache_domains +from utils.cache.base import _RENDER_GUARD from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_META_USERS from . import PROJECT_ROOT @@ -64,7 +65,7 @@ class TestMissingPrimaryDomain(unittest.TestCase): return_value={}, ): result = cache_domains.get_merged_domains( - variables={"SYSTEM_EMAIL_DOMAIN": "infinito.example"}, + variables={"SYSTEM_EMAIL_DOMAIN": "infinito.test"}, roles_dir=roles, templar=None, ) @@ -83,12 +84,12 @@ class TestCachingPerVariablesSignature(unittest.TestCase): return_value={}, ) as mocked: first = cache_domains.get_merged_domains( - variables={"DOMAIN_PRIMARY": "infinito.example"}, + variables={"DOMAIN_PRIMARY": "infinito.test"}, roles_dir=roles, templar=None, ) second = cache_domains.get_merged_domains( - variables={"DOMAIN_PRIMARY": "infinito.example"}, + variables={"DOMAIN_PRIMARY": "infinito.test"}, roles_dir=roles, templar=None, ) @@ -114,6 +115,37 @@ class TestCachingPerVariablesSignature(unittest.TestCase): ) self.assertEqual(mocked.call_count, 2) + def test_a_map_built_during_the_render_never_becomes_the_finished_one(self): + """Under the guard the applications view is still unrendered, so its + map must not answer a later read; it may still serve the render.""" + with tempfile.TemporaryDirectory() as tmp: + roles = _seed_minimal_role(Path(tmp)) + variables = {"DOMAIN_PRIMARY": "infinito.test"} + with patch( + "utils.cache.applications.get_merged_applications", + return_value={}, + ) as mocked: + _RENDER_GUARD.applications = True + try: + cache_domains.get_merged_domains( + variables=variables, roles_dir=roles, templar=None + ) + cache_domains.get_merged_domains( + variables=variables, roles_dir=roles, templar=None + ) + self.assertEqual(mocked.call_count, 1) + finally: + _RENDER_GUARD.applications = False + cache_domains.get_merged_domains( + variables=variables, roles_dir=roles, templar=None + ) + self.assertEqual(mocked.call_count, 2) + self.assertEqual(len(cache_domains._MERGED_DOMAINS_CACHE), 2) + self.assertEqual( + sorted(key[-1] for key in cache_domains._MERGED_DOMAINS_CACHE), + [False, True], + ) + class TestResetClearsDomainsCache(unittest.TestCase): def test_reset_evicts_cached_entry(self): @@ -125,7 +157,7 @@ class TestResetClearsDomainsCache(unittest.TestCase): return_value={}, ): cache_domains.get_merged_domains( - variables={"DOMAIN_PRIMARY": "infinito.example"}, + variables={"DOMAIN_PRIMARY": "infinito.test"}, roles_dir=roles, templar=None, ) @@ -195,38 +227,38 @@ class TestOnionDomainInjection(unittest.TestCase): } def test_dual_stack_appends_onion(self): - merged = {"web-app-x": ["x.infinito.example"]} + merged = {"web-app-x": ["x.infinito.test"]} out = cache_domains._inject_onion_domains( - merged, self._apps(), "infinito.example", self.ONION + merged, self._apps(), "infinito.test", self.ONION ) - self.assertEqual(out["web-app-x"], ["x.infinito.example", f"x.{self.ONION}"]) + self.assertEqual(out["web-app-x"], ["x.infinito.test", f"x.{self.ONION}"]) def test_exclusive_replaces_clearnet(self): - merged = {"web-app-x": ["x.infinito.example"]} + merged = {"web-app-x": ["x.infinito.test"]} out = cache_domains._inject_onion_domains( - merged, self._apps(exclusive=True), "infinito.example", self.ONION + merged, self._apps(exclusive=True), "infinito.test", self.ONION ) self.assertEqual(out["web-app-x"], [f"x.{self.ONION}"]) def test_primary_puts_onion_first(self): - merged = {"web-app-x": ["x.infinito.example"]} + merged = {"web-app-x": ["x.infinito.test"]} out = cache_domains._inject_onion_domains( - merged, self._apps(primary=True), "infinito.example", self.ONION + merged, self._apps(primary=True), "infinito.test", self.ONION ) - self.assertEqual(out["web-app-x"], [f"x.{self.ONION}", "x.infinito.example"]) + self.assertEqual(out["web-app-x"], [f"x.{self.ONION}", "x.infinito.test"]) def test_disabled_app_untouched(self): - merged = {"web-app-x": ["x.infinito.example"]} + merged = {"web-app-x": ["x.infinito.test"]} apps = {"web-app-x": {"services": {"tor": {"enabled": False}}}} out = cache_domains._inject_onion_domains( - merged, apps, "infinito.example", self.ONION + merged, apps, "infinito.test", self.ONION ) - self.assertEqual(out["web-app-x"], ["x.infinito.example"]) + self.assertEqual(out["web-app-x"], ["x.infinito.test"]) def test_exclusive_primary_default_from_provider(self): """A consumer that omits exclusive/primary inherits the svc-net-tor provider defaults (exclusive: true -> onion only).""" - merged = {"web-app-x": ["x.infinito.example"]} + merged = {"web-app-x": ["x.infinito.test"]} apps = { "web-app-x": {"services": {"tor": {"enabled": True, "shared": True}}}, "svc-net-tor": { @@ -241,14 +273,14 @@ class TestOnionDomainInjection(unittest.TestCase): }, } out = cache_domains._inject_onion_domains( - merged, apps, "infinito.example", self.ONION + merged, apps, "infinito.test", self.ONION ) self.assertEqual(out["web-app-x"], [f"x.{self.ONION}"]) def test_consumer_override_beats_provider_default(self): """A consumer that pins exclusive: false overrides the provider's exclusive: true and stays dual-stack.""" - merged = {"web-app-x": ["x.infinito.example"]} + merged = {"web-app-x": ["x.infinito.test"]} apps = { "web-app-x": { "services": { @@ -267,14 +299,14 @@ class TestOnionDomainInjection(unittest.TestCase): }, } out = cache_domains._inject_onion_domains( - merged, apps, "infinito.example", self.ONION + merged, apps, "infinito.test", self.ONION ) - self.assertEqual(out["web-app-x"], ["x.infinito.example", f"x.{self.ONION}"]) + self.assertEqual(out["web-app-x"], ["x.infinito.test", f"x.{self.ONION}"]) def test_consumer_exclusive_false_inherits_provider_primary_dual(self): """A consumer pinning only exclusive: false inherits the provider's primary: true and stays dual-stack, onion-first.""" - merged = {"web-app-x": ["x.infinito.example"]} + merged = {"web-app-x": ["x.infinito.test"]} apps = { "web-app-x": { "services": { @@ -293,16 +325,82 @@ class TestOnionDomainInjection(unittest.TestCase): }, } out = cache_domains._inject_onion_domains( - merged, apps, "infinito.example", self.ONION + merged, apps, "infinito.test", self.ONION ) - self.assertEqual(out["web-app-x"], [f"x.{self.ONION}", "x.infinito.example"]) + self.assertEqual(out["web-app-x"], [f"x.{self.ONION}", "x.infinito.test"]) def test_bare_primary_domain_maps_to_node_onion(self): - merged = {"web-app-x": ["infinito.example"]} + merged = {"web-app-x": ["infinito.test"]} out = cache_domains._inject_onion_domains( - merged, self._apps(), "infinito.example", self.ONION + merged, self._apps(), "infinito.test", self.ONION ) - self.assertEqual(out["web-app-x"], ["infinito.example", self.ONION]) + self.assertEqual(out["web-app-x"], ["infinito.test", self.ONION]) + + +class TestOnionFlagsAreRendered(unittest.TestCase): + """`services.tor.*` reaches this map as Jinja in 99 of the 105 roles that + declare it, and as its own source text whenever the applications render is + still in flight. Reading that text as a boolean answers False and drops the + onion domains for every app, which is what froze a clearnet asset URL into + the applications payload of run 34922994823. + """ + + ONION = TestOnionDomainInjection.ONION + JINJA_ON = "{{ 'svc-net-tor' in group_names }}" + + _apps = TestOnionDomainInjection._apps + + def _templar(self, **variables): + from ansible.parsing.dataloader import DataLoader + from ansible.template import Templar + + templar = Templar(loader=DataLoader(), variables=dict(variables)) + templar.available_variables = dict(variables) + return templar + + def _inject(self, apps, **variables): + return cache_domains._inject_onion_domains( + {"web-app-x": ["x.infinito.test"]}, + apps, + "infinito.test", + self.ONION, + templar=self._templar(**variables), + variables=dict(variables), + ) + + def test_a_templated_enabled_flag_still_injects_the_onion(self): + out = self._inject( + self._apps(enabled=self.JINJA_ON), + group_names=["svc-net-tor", "web-app-x"], + ) + + self.assertEqual(out["web-app-x"], ["x.infinito.test", f"x.{self.ONION}"]) + + def test_a_templated_flag_resolving_false_leaves_the_clearnet_domain(self): + out = self._inject(self._apps(enabled=self.JINJA_ON), group_names=["web-app-x"]) + + self.assertEqual(out["web-app-x"], ["x.infinito.test"]) + + def test_templated_exclusive_replaces_the_clearnet_domain(self): + out = self._inject( + self._apps(enabled=self.JINJA_ON, exclusive=self.JINJA_ON), + group_names=["svc-net-tor", "web-app-x"], + ) + + self.assertEqual(out["web-app-x"], [f"x.{self.ONION}"]) + + def test_a_flag_that_cannot_be_rendered_is_an_error(self): + """Without a templar the text cannot resolve, and answering False + would drop the onion domains without saying so.""" + with self.assertRaisesRegex(ValueError, "services.tor.enabled"): + cache_domains._inject_onion_domains( + {"web-app-x": ["x.infinito.test"]}, + self._apps(enabled=self.JINJA_ON), + "infinito.test", + self.ONION, + templar=None, + variables={"group_names": ["svc-net-tor"]}, + ) if __name__ == "__main__": diff --git a/tests/unit/python/utils/cache/test_files.py b/tests/unit/python/utils/cache/test_files.py index 40664641ad..466e4f9ef0 100644 --- a/tests/unit/python/utils/cache/test_files.py +++ b/tests/unit/python/utils/cache/test_files.py @@ -177,5 +177,33 @@ class TestReset(_ProjectRootFixture, unittest.TestCase): self.assertEqual(read_text(str(self.root / "x.txt")), "v1-changed") +class TestWalkIsKeyedOnTheRoot(_ProjectRootFixture, unittest.TestCase): + def test_a_second_root_is_walked_rather_than_answered_from_the_first( + self, + ) -> None: + _touch(self.root / "first.txt", "a") + self.assertEqual( + {str(self.root / "first.txt")}, + set(iter_project_files()), + ) + + with TemporaryDirectory() as other: + other_root = Path(other) + _touch(other_root / "second.txt", "b") + with patch.object(files_module, "PROJECT_ROOT", other_root): + self.assertEqual( + {str(other_root / "second.txt")}, + set(iter_project_files()), + "the walk answered for the previous root, so a test that " + "points PROJECT_ROOT at a fixture silently sweeps the real " + "repository instead", + ) + + self.assertEqual( + {str(self.root / "first.txt")}, + set(iter_project_files()), + ) + + if __name__ == "__main__": # pragma: no cover unittest.main() diff --git a/tests/unit/python/utils/cache/users/test_module.py b/tests/unit/python/utils/cache/users/test_module.py index f4dc71e61e..8c38b27c29 100644 --- a/tests/unit/python/utils/cache/users/test_module.py +++ b/tests/unit/python/utils/cache/users/test_module.py @@ -90,6 +90,44 @@ class TestLoadUserDefs(unittest.TestCase): with self.assertRaisesRegex(ValueError, "Conflict for user 'shared'"): cache_users._load_user_defs(roles) + def test_two_roles_register_a_token_for_the_same_user(self): + with tempfile.TemporaryDirectory() as tmp: + roles = Path(tmp) / "roles" + _write( + roles / "web-app-a" / ROLE_FILE_META_USERS, + """ + administrator: {tokens: {web-app-a: ""}} + """, + ) + _write( + roles / "web-app-b" / ROLE_FILE_META_USERS, + """ + administrator: {tokens: {web-app-b: ""}} + """, + ) + defs = cache_users._load_user_defs(roles) + self.assertEqual( + sorted(defs["administrator"]["tokens"]), ["web-app-a", "web-app-b"] + ) + + def test_the_same_token_key_with_two_values_still_conflicts(self): + with tempfile.TemporaryDirectory() as tmp: + roles = Path(tmp) / "roles" + _write( + roles / "web-app-a" / ROLE_FILE_META_USERS, + """ + administrator: {tokens: {shared-app: from-a}} + """, + ) + _write( + roles / "web-app-b" / ROLE_FILE_META_USERS, + """ + administrator: {tokens: {shared-app: from-b}} + """, + ) + with self.assertRaisesRegex(ValueError, "tokens.shared-app"): + cache_users._load_user_defs(roles) + class TestBuildUsers(unittest.TestCase): def test_allocates_distinct_uids_for_users_without_explicit_uid(self): @@ -272,7 +310,7 @@ class TestMaterializeBuiltinUserAliases(unittest.TestCase): } out = cache_users._materialize_builtin_user_aliases( users, - variables={"DOMAIN_PRIMARY": "infinito.example"}, + variables={"DOMAIN_PRIMARY": "infinito.test"}, templar=None, ) self.assertEqual(out["sld"]["username"], "infinito") diff --git a/tests/unit/python/utils/cache/users/test_placeholders.py b/tests/unit/python/utils/cache/users/test_placeholders.py index fa102d59ef..30854958b7 100644 --- a/tests/unit/python/utils/cache/users/test_placeholders.py +++ b/tests/unit/python/utils/cache/users/test_placeholders.py @@ -54,28 +54,28 @@ class TestSubstitutePrimaryDomainPlaceholder(unittest.TestCase): users = _user_dict(email="admin@{{ DOMAIN_PRIMARY }}") out = substitute_primary_domain_placeholder( users, - {"DOMAIN_PRIMARY": "infinito.example"}, - templar=_StubTemplar({"DOMAIN_PRIMARY": "infinito.example"}), + {"DOMAIN_PRIMARY": "infinito.test"}, + templar=_StubTemplar({"DOMAIN_PRIMARY": "infinito.test"}), ) - self.assertEqual(out["administrator"]["email"], "admin@infinito.example") + self.assertEqual(out["administrator"]["email"], "admin@infinito.test") def test_extracts_host_from_url(self) -> None: users = _user_dict(email="admin@{{ DOMAIN_PRIMARY }}") out = substitute_primary_domain_placeholder( users, - {"DOMAIN_PRIMARY": "https://infinito.example/path"}, - templar=_StubTemplar({"DOMAIN_PRIMARY": "https://infinito.example/path"}), + {"DOMAIN_PRIMARY": "https://infinito.test/path"}, + templar=_StubTemplar({"DOMAIN_PRIMARY": "https://infinito.test/path"}), ) - self.assertEqual(out["administrator"]["email"], "admin@infinito.example") + self.assertEqual(out["administrator"]["email"], "admin@infinito.test") def test_strips_port(self) -> None: users = _user_dict(email="admin@{{ DOMAIN_PRIMARY }}") out = substitute_primary_domain_placeholder( users, - {"DOMAIN_PRIMARY": "infinito.example:8443"}, - templar=_StubTemplar({"DOMAIN_PRIMARY": "infinito.example:8443"}), + {"DOMAIN_PRIMARY": "infinito.test:8443"}, + templar=_StubTemplar({"DOMAIN_PRIMARY": "infinito.test:8443"}), ) - self.assertEqual(out["administrator"]["email"], "admin@infinito.example") + self.assertEqual(out["administrator"]["email"], "admin@infinito.test") def test_returns_unchanged_when_var_missing(self) -> None: users = _user_dict(email="admin@{{ DOMAIN_PRIMARY }}") @@ -95,16 +95,16 @@ class TestSubstitutePrimaryDomainPlaceholder(unittest.TestCase): users, { "DOMAIN_PRIMARY": "{{ SOFTWARE_DOMAIN }}", - "SOFTWARE_DOMAIN": "infinito.example", + "SOFTWARE_DOMAIN": "infinito.test", }, templar=_StubTemplar( { "DOMAIN_PRIMARY": "{{ SOFTWARE_DOMAIN }}", - "SOFTWARE_DOMAIN": "infinito.example", + "SOFTWARE_DOMAIN": "infinito.test", } ), ) - self.assertEqual(out["administrator"]["email"], "admin@infinito.example") + self.assertEqual(out["administrator"]["email"], "admin@infinito.test") def test_walks_nested_structures(self) -> None: users = { @@ -119,13 +119,13 @@ class TestSubstitutePrimaryDomainPlaceholder(unittest.TestCase): } out = substitute_primary_domain_placeholder( users, - {"DOMAIN_PRIMARY": "infinito.example"}, - templar=_StubTemplar({"DOMAIN_PRIMARY": "infinito.example"}), + {"DOMAIN_PRIMARY": "infinito.test"}, + templar=_StubTemplar({"DOMAIN_PRIMARY": "infinito.test"}), ) nested = out["administrator"] - self.assertEqual(nested["addresses"][0], "admin@infinito.example") - self.assertEqual(nested["addresses"][1]["alt"], "root@infinito.example") - self.assertEqual(nested["primary"], ("primary@infinito.example",)) + self.assertEqual(nested["addresses"][0], "admin@infinito.test") + self.assertEqual(nested["addresses"][1]["alt"], "root@infinito.test") + self.assertEqual(nested["primary"], ("primary@infinito.test",)) class TestSubstituteScalarPlaceholders(unittest.TestCase): diff --git a/tests/unit/python/utils/cleanup/test_nginx_vhosts.py b/tests/unit/python/utils/cleanup/test_nginx_vhosts.py index 284fba1c0b..4310d469a5 100644 --- a/tests/unit/python/utils/cleanup/test_nginx_vhosts.py +++ b/tests/unit/python/utils/cleanup/test_nginx_vhosts.py @@ -82,15 +82,15 @@ class TestIterVhostFiles(NginxVhostsTestBase, unittest.TestCase): self._mk_role( "web-app-matomo", application_id="web-app-matomo", - canonical=["matomo.infinito.example"], + canonical=["matomo.infinito.test"], ) - existing = self._touch_vhost("matomo.infinito.example", "https") + existing = self._touch_vhost("matomo.infinito.test", "https") got = list( iter_vhost_files_for_entity( "matomo", nginx_dir=self.nginx_dir, - domain_primary="infinito.example", + domain_primary="infinito.test", roles_dir=self.roles_dir, ) ) @@ -100,17 +100,17 @@ class TestIterVhostFiles(NginxVhostsTestBase, unittest.TestCase): self._mk_role( "web-app-matomo", application_id="web-app-matomo", - canonical=["matomo.infinito.example"], - aliases=["stats.infinito.example"], + canonical=["matomo.infinito.test"], + aliases=["stats.infinito.test"], ) - f1 = self._touch_vhost("matomo.infinito.example", "https") - f2 = self._touch_vhost("stats.infinito.example", "https") + f1 = self._touch_vhost("matomo.infinito.test", "https") + f2 = self._touch_vhost("stats.infinito.test", "https") got = sorted( iter_vhost_files_for_entity( "matomo", nginx_dir=self.nginx_dir, - domain_primary="infinito.example", + domain_primary="infinito.test", roles_dir=self.roles_dir, ) ) @@ -120,15 +120,15 @@ class TestIterVhostFiles(NginxVhostsTestBase, unittest.TestCase): self._mk_role( "web-app-matomo", application_id="web-app-matomo", - canonical=["matomo.infinito.example"], + canonical=["matomo.infinito.test"], ) - self._touch_vhost("matomo.infinito.example", "https") + self._touch_vhost("matomo.infinito.test", "https") got = list( iter_vhost_files_for_entity( "no-such-entity", nginx_dir=self.nginx_dir, - domain_primary="infinito.example", + domain_primary="infinito.test", roles_dir=self.roles_dir, ) ) @@ -138,16 +138,16 @@ class TestIterVhostFiles(NginxVhostsTestBase, unittest.TestCase): self._mk_role( "web-svc-cdn", application_id="web-svc-cdn", - canonical=["cdn.infinito.example"], + canonical=["cdn.infinito.test"], ) - bare = self._touch_vhost("cdn.infinito.example", "https") - redirect = self._touch_vhost("www.cdn.infinito.example", "https") + bare = self._touch_vhost("cdn.infinito.test", "https") + redirect = self._touch_vhost("www.cdn.infinito.test", "https") got = sorted( iter_vhost_files_for_entity( "cdn", nginx_dir=self.nginx_dir, - domain_primary="infinito.example", + domain_primary="infinito.test", roles_dir=self.roles_dir, ) ) @@ -157,16 +157,16 @@ class TestIterVhostFiles(NginxVhostsTestBase, unittest.TestCase): self._mk_role( "web-opt-rdr-www", application_id="web-opt-rdr-www", - canonical=["www.w3redirect.infinito.example"], + canonical=["www.w3redirect.infinito.test"], ) - existing = self._touch_vhost("www.w3redirect.infinito.example", "https") - self._touch_vhost("www.www.w3redirect.infinito.example", "https") + existing = self._touch_vhost("www.w3redirect.infinito.test", "https") + self._touch_vhost("www.www.w3redirect.infinito.test", "https") got = list( iter_vhost_files_for_entity( "opt-rdr-www", nginx_dir=self.nginx_dir, - domain_primary="infinito.example", + domain_primary="infinito.test", roles_dir=self.roles_dir, ) ) @@ -178,22 +178,22 @@ class TestPurgeVhostFiles(NginxVhostsTestBase, unittest.TestCase): self._mk_role( "web-app-matomo", application_id="web-app-matomo", - canonical=["matomo.infinito.example"], + canonical=["matomo.infinito.test"], ) self._mk_role( "web-app-dashboard", application_id="web-app-dashboard", - canonical=["dashboard.infinito.example"], + canonical=["dashboard.infinito.test"], ) - matomo_https = self._touch_vhost("matomo.infinito.example", "https") - dashboard_https = self._touch_vhost("dashboard.infinito.example", "https") - unrelated = self._touch_vhost("unrelated.infinito.example", "https") + matomo_https = self._touch_vhost("matomo.infinito.test", "https") + dashboard_https = self._touch_vhost("dashboard.infinito.test", "https") + unrelated = self._touch_vhost("unrelated.infinito.test", "https") removed = purge_vhost_files_for_entities( ["dashboard"], nginx_dir=self.nginx_dir, - domain_primary="infinito.example", + domain_primary="infinito.test", roles_dir=self.roles_dir, ) @@ -206,13 +206,13 @@ class TestPurgeVhostFiles(NginxVhostsTestBase, unittest.TestCase): self._mk_role( "web-app-matomo", application_id="web-app-matomo", - canonical=["matomo.infinito.example"], + canonical=["matomo.infinito.test"], ) removed = purge_vhost_files_for_entities( ["matomo"], nginx_dir=self.nginx_dir, - domain_primary="infinito.example", + domain_primary="infinito.test", roles_dir=self.roles_dir, ) self.assertEqual(removed, []) @@ -221,17 +221,17 @@ class TestPurgeVhostFiles(NginxVhostsTestBase, unittest.TestCase): self._mk_role( "web-svc-cdn", application_id="web-svc-cdn", - canonical=["cdn.infinito.example"], + canonical=["cdn.infinito.test"], ) - bare = self._touch_vhost("cdn.infinito.example", "https") - redirect = self._touch_vhost("www.cdn.infinito.example", "https") - unrelated = self._touch_vhost("www.unrelated.infinito.example", "https") + bare = self._touch_vhost("cdn.infinito.test", "https") + redirect = self._touch_vhost("www.cdn.infinito.test", "https") + unrelated = self._touch_vhost("www.unrelated.infinito.test", "https") removed = sorted( purge_vhost_files_for_entities( ["cdn"], nginx_dir=self.nginx_dir, - domain_primary="infinito.example", + domain_primary="infinito.test", roles_dir=self.roles_dir, ) ) @@ -245,22 +245,22 @@ class TestPurgeVhostFiles(NginxVhostsTestBase, unittest.TestCase): self._mk_role( "web-app-matomo", application_id="web-app-matomo", - canonical=["matomo.infinito.example"], + canonical=["matomo.infinito.test"], ) self._mk_role( "web-app-dashboard", application_id="web-app-dashboard", - canonical=["dashboard.infinito.example"], + canonical=["dashboard.infinito.test"], ) - matomo_https = self._touch_vhost("matomo.infinito.example", "https") - dashboard_https = self._touch_vhost("dashboard.infinito.example", "https") + matomo_https = self._touch_vhost("matomo.infinito.test", "https") + dashboard_https = self._touch_vhost("dashboard.infinito.test", "https") removed = sorted( purge_vhost_files_for_entities( ["matomo", "dashboard"], nginx_dir=self.nginx_dir, - domain_primary="infinito.example", + domain_primary="infinito.test", roles_dir=self.roles_dir, ) ) @@ -300,16 +300,16 @@ class TestOnionVhostVariant(NginxVhostsTestBase, unittest.TestCase): self._mk_role( "web-app-matomo", application_id="matomo", - canonical=["matomo.infinito.example"], + canonical=["matomo.infinito.test"], ) - clearnet = self._touch_vhost("matomo.infinito.example", "https") + clearnet = self._touch_vhost("matomo.infinito.test", "https") onion = self._touch_vhost(f"matomo.{self.ONION}", "http") self._write_node_onion(self.ONION) found = set( iter_vhost_files_for_entity( "matomo", nginx_dir=self.nginx_dir, - domain_primary="infinito.example", + domain_primary="infinito.test", roles_dir=self.roles_dir, ) ) @@ -320,14 +320,14 @@ class TestOnionVhostVariant(NginxVhostsTestBase, unittest.TestCase): self._mk_role( "web-app-matomo", application_id="matomo", - canonical=["matomo.infinito.example"], + canonical=["matomo.infinito.test"], ) onion = self._touch_vhost(f"matomo.{self.ONION}", "http") found = set( iter_vhost_files_for_entity( "matomo", nginx_dir=self.nginx_dir, - domain_primary="infinito.example", + domain_primary="infinito.test", roles_dir=self.roles_dir, ) ) diff --git a/tests/unit/python/utils/diagnostics/test_container.py b/tests/unit/python/utils/diagnostics/test_container.py index f69e41b172..4958ce49c7 100644 --- a/tests/unit/python/utils/diagnostics/test_container.py +++ b/tests/unit/python/utils/diagnostics/test_container.py @@ -44,6 +44,42 @@ def _cp(cmd, rc=0, stdout=b"", stderr=b""): return subprocess.CompletedProcess(cmd, rc, stdout, stderr) +class InZoneProbeTests(unittest.TestCase): + """The probe is a shell one-liner, so run it: svc-net-tor keeps the onion + zone in a drop-in and leaves only a conf-dir pointer in the main file.""" + + def _zone(self, main: Path) -> str: + probe = _load()._INZONE_PROBE.replace("/etc/dnsmasq.conf", str(main)) + inner = probe.split("rescue-probe.$(", 1)[1].rsplit(")", 1)[0] + proc = subprocess.run( + ["sh", "-c", inner], capture_output=True, text=True, check=False + ) + return proc.stdout.strip() + + def test_a_zone_in_a_drop_in_is_found(self): + with tempfile.TemporaryDirectory() as tmp: + drop_ins = Path(tmp) / "dnsmasq.d" + drop_ins.mkdir() + (drop_ins / "tor-onion.conf").write_text( + "address=/abc123.onion/127.0.0.1\n", encoding="utf-8" + ) + main = Path(tmp) / "dnsmasq.conf" + main.write_text(f"conf-dir={drop_ins},*.conf\n", encoding="utf-8") + self.assertEqual(self._zone(main), "abc123.onion") + + def test_a_zone_in_the_main_file_still_wins(self): + with tempfile.TemporaryDirectory() as tmp: + main = Path(tmp) / "dnsmasq.conf" + main.write_text("address=/infinito.test/192.0.2.1\n", encoding="utf-8") + self.assertEqual(self._zone(main), "infinito.test") + + def test_a_config_without_a_zone_yields_nothing(self): + with tempfile.TemporaryDirectory() as tmp: + main = Path(tmp) / "dnsmasq.conf" + main.write_text("no-resolv\nserver=192.0.2.1\n", encoding="utf-8") + self.assertEqual(self._zone(main), "") + + class HelperTests(unittest.TestCase): def test_sanitize_replaces_unsafe_chars(self): mod = _load() diff --git a/tests/unit/python/utils/docker/test_healthcheck.py b/tests/unit/python/utils/docker/test_healthcheck.py index 9393226f9c..bf60848151 100644 --- a/tests/unit/python/utils/docker/test_healthcheck.py +++ b/tests/unit/python/utils/docker/test_healthcheck.py @@ -201,12 +201,12 @@ class TestBuild(unittest.TestCase): def test_each_flavor_brings_its_own_timings(self): self.assertEqual("10s", block("curl", port=80)["timeout"]) self.assertEqual("3s", block("nc", port=80)["timeout"]) - self.assertEqual("120s", block("msmtp_curl", port=80)["start_period"]) + self.assertEqual("20s", block("msmtp_curl", port=80)["timeout"]) def test_the_service_entry_overrides_any_timing(self): got = block("curl", {"start_period": "20m", "retries": 9}, port=80) self.assertEqual( - ("20m", 9, "1m"), (got["start_period"], got["retries"], got["interval"]) + ("20m", 9, "2m"), (got["start_period"], got["retries"], got["interval"]) ) def test_an_empty_flavor_takes_the_explicit_test_argv(self): @@ -262,11 +262,11 @@ class TestBuild(unittest.TestCase): composed = block(["msmtp", "connect"], port=9000) self.assertEqual("15m", composed["start_period"]) self.assertEqual("15m", block("connect", port=9000)["start_period"]) - self.assertEqual("120s", block(["msmtp", "curl"], port=80)["start_period"]) - self.assertEqual("30s", block("curl", port=80)["start_period"]) + self.assertEqual("20s", block(["msmtp", "curl"], port=80)["timeout"]) + self.assertEqual("10s", block("curl", port=80)["timeout"]) def test_composing_takes_the_probes_interval(self): - self.assertEqual("1m", block(["msmtp", "curl"], port=80)["interval"]) + self.assertEqual("2m", block(["msmtp", "curl"], port=80)["interval"]) def test_http_status_inherits_the_request_builder_from_tcp(self): self.assertTrue(issubclass(HttpStatus, Tcp)) diff --git a/tests/unit/python/utils/docker/test_image_pin.py b/tests/unit/python/utils/docker/test_image_pin.py new file mode 100644 index 0000000000..bf95b2650d --- /dev/null +++ b/tests/unit/python/utils/docker/test_image_pin.py @@ -0,0 +1,99 @@ +from __future__ import annotations + +import unittest + +from utils.docker.image.discovery import docker_hub_source, image_source +from utils.docker.image.pin import ( + DIGEST, + REF, + RULE_BY_CLASS, + SEMVER, + is_digest, + pin_class, + pull_reference, + reference_separator, +) + +DIGEST_VALUE = "sha256:d5591131b1d898cd02fc7a17adb8ea026352d67809bc9289707778e9e03a76a4" + + +class TestPinClass(unittest.TestCase): + def test_a_semver_tag_is_a_semver_pin(self): + for value in ("3.0.1", "16", "17-3.5", "5.4.5-php8.3-apache", "v1.12.27"): + self.assertEqual(pin_class(value), SEMVER, value) + + def test_a_content_address_is_a_digest_pin(self): + self.assertEqual(pin_class(DIGEST_VALUE), DIGEST) + + def test_a_moving_name_is_neither(self): + for value in ("latest", "main", "stable", "buildx-stable-1"): + self.assertEqual(pin_class(value), REF, value) + + def test_surrounding_whitespace_does_not_change_the_class(self): + self.assertEqual(pin_class(f" {DIGEST_VALUE} "), DIGEST) + self.assertEqual(pin_class(" 3.0.1 "), SEMVER) + + def test_a_digest_declares_itself_apart_from_a_tag(self): + self.assertNotEqual( + RULE_BY_CLASS[DIGEST], + RULE_BY_CLASS[REF], + "a digest is chosen for a reason a non-semver tag never carries, so " + "the two cannot share one marker", + ) + self.assertEqual(RULE_BY_CLASS[DIGEST], "docker-digest") + self.assertEqual(RULE_BY_CLASS[REF], "docker-version") + + def test_a_semver_pin_needs_no_declaration(self): + self.assertNotIn(SEMVER, RULE_BY_CLASS) + + +class TestPullReference(unittest.TestCase): + def test_a_digest_is_joined_with_an_at_sign(self): + self.assertEqual(reference_separator(DIGEST_VALUE), "@") + self.assertEqual( + pull_reference("ghcr.io/owner/app", DIGEST_VALUE), + f"ghcr.io/owner/app@{DIGEST_VALUE}", + ) + + def test_a_tag_is_joined_with_a_colon(self): + self.assertEqual(reference_separator("3.0.1"), ":") + self.assertEqual( + pull_reference("ghcr.io/owner/app", "3.0.1"), "ghcr.io/owner/app:3.0.1" + ) + + def test_is_digest_rejects_a_tag_that_merely_mentions_sha256(self): + self.assertFalse(is_digest("v2-sha256:abc")) + + +class TestSourceKeepsTheDigest(unittest.TestCase): + """A pull ref that silently drops the digest pins nothing at all.""" + + def test_image_source_keeps_a_digest(self): + self.assertEqual( + image_source("ghcr.io/owner/app", DIGEST_VALUE), + f"ghcr.io/owner/app@{DIGEST_VALUE}", + ) + + def test_image_source_still_tags_a_semver(self): + self.assertEqual( + image_source("ghcr.io/owner/app", "3.0.1"), "ghcr.io/owner/app:3.0.1" + ) + + def test_docker_hub_source_keeps_a_digest(self): + self.assertEqual( + docker_hub_source("postgres", DIGEST_VALUE), + f"docker.io/library/postgres@{DIGEST_VALUE}", + ) + + def test_a_digest_never_yields_a_tag_separator(self): + source = image_source("quay.io/owner/app", DIGEST_VALUE) + + self.assertNotIn( + f":{DIGEST_VALUE}", + source, + "a colon here would make the registry read the digest as a tag name", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/domains/test_list.py b/tests/unit/python/utils/domains/test_list.py index bd4ae6c0af..e1b6b454ff 100644 --- a/tests/unit/python/utils/domains/test_list.py +++ b/tests/unit/python/utils/domains/test_list.py @@ -74,16 +74,16 @@ class TestDomainList(unittest.TestCase): ) with patch.object(domain_list, "ROLES_DIR", roles_dir): - domains = domain_list.list_application_domains("infinito.example") + domains = domain_list.list_application_domains("infinito.test") self.assertEqual( domains, sorted( [ - "api.s3.infinito.example", - "console.s3.infinito.example", - "dashboard.infinito.example", - "test.infinito.example", + "api.s3.infinito.test", + "console.s3.infinito.test", + "dashboard.infinito.test", + "test.infinito.test", ] ), ) @@ -109,7 +109,7 @@ class TestDomainList(unittest.TestCase): with patch.object(domain_list, "ROLES_DIR", roles_dir): domains = domain_list.list_application_domains( - "infinito.example", + "infinito.test", include_aliases=True, include_www=True, ) @@ -117,10 +117,10 @@ class TestDomainList(unittest.TestCase): self.assertEqual( domains, [ - "dashboard.infinito.example", - "test.infinito.example", - "www.dashboard.infinito.example", - "www.test.infinito.example", + "dashboard.infinito.test", + "test.infinito.test", + "www.dashboard.infinito.test", + "www.test.infinito.test", ], ) @@ -130,9 +130,9 @@ class TestDomainList(unittest.TestCase): roles_dir.mkdir() with patch.object(domain_list, "ROLES_DIR", roles_dir): - domains = domain_list.list_application_domains("infinito.example") + domains = domain_list.list_application_domains("infinito.test") - self.assertEqual(domains, ["test.infinito.example"]) + self.assertEqual(domains, ["test.infinito.test"]) def test_list_application_domains_raises_on_collisions(self): with tempfile.TemporaryDirectory() as tmp: @@ -154,7 +154,7 @@ class TestDomainList(unittest.TestCase): patch.object(domain_list, "ROLES_DIR", roles_dir), self.assertRaises(AnsibleError), ): - domain_list.list_application_domains("infinito.example") + domain_list.list_application_domains("infinito.test") if __name__ == "__main__": diff --git a/tests/unit/python/utils/github/test_run_name.py b/tests/unit/python/utils/github/test_run_name.py index 6e61ba98c3..6813b4b976 100644 --- a/tests/unit/python/utils/github/test_run_name.py +++ b/tests/unit/python/utils/github/test_run_name.py @@ -128,7 +128,6 @@ class DeclaredTemplateTests(unittest.TestCase): dispatched = { "chunk_gate": "true", "workspace": "true", - "instructions": "false", "filesystem": "ext4", "distros": "debian arch", "lifecycles": "stable", diff --git a/tests/unit/python/utils/github/variant/test_instructions.py b/tests/unit/python/utils/github/variant/test_instructions.py new file mode 100644 index 0000000000..0b9b1bc462 --- /dev/null +++ b/tests/unit/python/utils/github/variant/test_instructions.py @@ -0,0 +1,102 @@ +"""The README replay rides on a row that runs in the guide's own mode. + +The replay is a second deploy on the same runner. On a swarm row that runner +would have to bring a compose stack up beside a swarm one, so the marker has to +land on a compose row for a role that ships a stack, and on a host row for one +installed onto the machine. + +The trap this guards is quiet: marking the wrong row still produces a ๐Ÿ“– in a +job title, so a run looks like it replayed the instructions either way. +""" + +from __future__ import annotations + +import unittest +from unittest.mock import patch + +from utils.github.variant import instructions + + +def _entry(app: str, variant: str, mode: str, **overrides: str) -> dict[str, str]: + entry = { + "apps": app, + "variant": variant, + "mode": mode, + "priority": "false", + "clone": "false", + "covered": "0", + "instructions": "", + "label": f"{app}#{variant}", + } + entry.update(overrides) + return entry + + +_VARIANTS = { + "web-app-x": [ + {"services": {"a": {"enabled": True}, "b": {"enabled": True}}}, + {"services": {"a": {"enabled": True}}}, + ] +} + + +def _mark(entries, mode="compose", variants=None): + """Mark with the guide's mode forced, leaving the variant search real. + + Both bindings are patched: ``mark`` resolved the name at import, while + ``guide_variant`` calls its own module's copy. + """ + with ( + patch.object(instructions, "guide_deployable", return_value=mode), + patch("utils.roles.guide.guide_deployable", return_value=mode), + ): + return instructions.mark( + entries, variants if variants is not None else _VARIANTS + ) + + +class TestInstructionsMode(unittest.TestCase): + def test_the_compose_row_of_the_smallest_variant_carries_it(self) -> None: + marked = _mark([_entry("web-app-x", "1", "compose")]) + self.assertEqual("compose", marked[0]["instructions"]) + + def test_a_swarm_row_never_carries_a_compose_replay(self) -> None: + marked = _mark([_entry("web-app-x", "1", "swarm")]) + self.assertEqual("", marked[0]["instructions"]) + + def test_the_swarm_row_is_skipped_and_the_compose_row_takes_it(self) -> None: + marked = _mark( + [_entry("web-app-x", "1", "swarm"), _entry("web-app-x", "1", "compose")] + ) + self.assertEqual(["", "compose"], [e["instructions"] for e in marked]) + + def test_a_variant_deployed_only_in_swarm_does_not_win_the_search(self) -> None: + marked = _mark( + [_entry("web-app-x", "1", "swarm"), _entry("web-app-x", "0", "compose")] + ) + self.assertEqual(["", "compose"], [e["instructions"] for e in marked]) + + def test_a_host_role_carries_it_on_its_host_row(self) -> None: + marked = _mark([_entry("web-app-x", "1", "host")], mode="host") + self.assertEqual("host", marked[0]["instructions"]) + + def test_a_redundant_row_carries_nothing(self) -> None: + marked = _mark([_entry("web-app-x", "1", "compose", covered="7")]) + self.assertEqual("", marked[0]["instructions"]) + + def test_only_one_row_per_role_is_marked(self) -> None: + marked = _mark( + [_entry("web-app-x", "1", "compose"), _entry("web-app-x", "1", "compose")] + ) + self.assertEqual(["compose", ""], [e["instructions"] for e in marked]) + + def test_the_label_gains_the_glyph_only_where_it_is_marked(self) -> None: + marked = _mark( + [_entry("web-app-x", "1", "swarm"), _entry("web-app-x", "1", "compose")] + ) + self.assertEqual("web-app-x#1", marked[0]["label"]) + self.assertNotEqual("web-app-x#1", marked[1]["label"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/install/test_collections.py b/tests/unit/python/utils/install/test_collections.py new file mode 100644 index 0000000000..8ff53e96cb --- /dev/null +++ b/tests/unit/python/utils/install/test_collections.py @@ -0,0 +1,260 @@ +import json +import re +import shutil +import subprocess +import sys +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory + +from utils import PROJECT_ROOT +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.install.collections import declared_pins, unsatisfied + +_DOCKERFILE = PROJECT_ROOT / "Dockerfile" +_COPY = re.compile(r"^COPY\s+(?P<source>\S+)\s+\$\{INFINITO_SRC_DIR\}/(?P<target>\S+)$") + + +def _materialise_image_slice(destination: Path) -> None: + """Reproduce what the image holds when it first runs the collection check. + + The Dockerfile copies a handful of paths, runs ``scripts/install/ansible.sh`` + against them, and only afterwards copies the rest of the tree. Anything + ``utils.install.collections`` imports beyond that slice is absent in the + layer that executes it, which no import inside a full checkout can show. + The list is read from the Dockerfile rather than restated here, so a COPY + added or dropped moves this probe with it. + + The caller must run the slice under ``python -S``. This repository installs + ``utils`` into site-packages, so without it the interpreter resolves every + submodule from the checkout however the slice is built, and the probe + passes on a module that cannot import inside the image. + + Args: + destination: an empty directory to build the slice in. + """ + for line in read_text(str(_DOCKERFILE)).splitlines(): + if line.startswith("COPY . "): + return + match = _COPY.match(line.strip()) + if not match: + continue + source = PROJECT_ROOT / match.group("source") + target = destination / match.group("target") + target.parent.mkdir(parents=True, exist_ok=True) + if source.is_dir(): + shutil.copytree(source, target, dirs_exist_ok=True) + else: + shutil.copy2(source, target) + + +_REQUIREMENTS = ( + PROJECT_ROOT / "requirements" / "requirements.galaxy.yml", + PROJECT_ROOT / "requirements" / "requirements.git.yml", +) + +_BOOTSTRAP_PROBE = """ +import sys + + +class _NoPyYAML: + def find_spec(self, fullname, path=None, target=None): + if fullname == "yaml" or fullname.startswith("yaml."): + raise ImportError("PyYAML is absent during the lint bootstrap") + return None + + +sys.meta_path.insert(0, _NoPyYAML()) + +from pathlib import Path + +from utils.install.lint.ansible import collections as lint_collections +from utils.install.collections import declared_pins + +for fqcn, version in declared_pins(Path("requirements/requirements.galaxy.yml")): + print(fqcn, version) +""" + +REQUIREMENTS = """--- +collections: + - name: community.general + version: 13.4.0 + - name: hetzner.hcloud + version: 7.0.1 +""" + + +def _write_requirements(root: Path, body: str = REQUIREMENTS) -> Path: + path = root / "requirements.galaxy.yml" + path.write_text(body, encoding="utf-8") + return path + + +def _install(collections_dir: Path, fqcn: str, version: str) -> None: + namespace, _, name = fqcn.partition(".") + target = collections_dir / "ansible_collections" / namespace / name + target.mkdir(parents=True) + (target / "MANIFEST.json").write_text( + json.dumps({"collection_info": {"version": version}}), encoding="utf-8" + ) + + +class TestAgainstPyYAML(unittest.TestCase): + def test_the_hand_parser_agrees_with_pyyaml(self): + for path in _REQUIREMENTS: + with self.subTest(requirements=path.name): + declared = load_yaml_any(str(path), default_if_missing={}) or {} + expected = [ + (str(entry.get("name")), entry.get("version")) + for entry in declared.get("collections") or [] + if isinstance(entry, dict) and entry.get("name") + ] + expected = [ + (name, None if version is None else str(version)) + for name, version in expected + ] + + self.assertEqual(declared_pins(path), expected) + + def test_the_parser_runs_with_pyyaml_unimportable(self): + result = subprocess.run( + [sys.executable, "-c", _BOOTSTRAP_PROBE], + cwd=str(PROJECT_ROOT), + capture_output=True, + text=True, + check=False, + ) + + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("community.general", result.stdout) + + def test_the_checker_runs_on_the_slice_the_dockerfile_copies(self): + tmp = TemporaryDirectory() + self.addCleanup(tmp.cleanup) + slice_root = Path(tmp.name) + _materialise_image_slice(slice_root) + requirements = slice_root / "requirements" / "requirements.galaxy.yml" + self.assertTrue( + requirements.is_file(), + "the Dockerfile stopped copying requirements/ before the ansible " + "install layer; this probe needs it to have something to check", + ) + + result = subprocess.run( + [ + sys.executable, + "-S", + "-m", + "utils.install.collections", + str(requirements), + str(slice_root / "collections"), + ], + cwd=str(slice_root), + capture_output=True, + text=True, + check=False, + ) + + self.assertNotIn( + "ModuleNotFoundError", + result.stderr, + "utils.install.collections reached for a module the image layer " + "that runs it does not hold; keep it on the standard library", + ) + self.assertEqual( + result.returncode, + 1, + f"an empty collections dir satisfies nothing, so the checker owes " + f"exit 1 and a list; stderr: {result.stderr}", + ) + self.assertIn("community.general", result.stdout) + + +class TestDeclaredPins(unittest.TestCase): + def test_a_quoted_version_is_read_without_its_quotes(self): + body = ( + "---\ncollections:\n" + ' - name: double.quoted\n version: "13.4.0"\n' + " - name: single.quoted\n version: '1.0.0'\n" + " - name: commented\n version: 2.2.2 # pinned\n" + ) + with TemporaryDirectory() as tmp: + root = Path(tmp) + requirements = _write_requirements(root, body) + + self.assertEqual( + declared_pins(requirements), + [ + ("double.quoted", "13.4.0"), + ("single.quoted", "1.0.0"), + ("commented", "2.2.2"), + ], + ) + + def test_an_entry_without_a_version_stays_unpinned(self): + body = "---\ncollections:\n - name: bare.entry\n" + with TemporaryDirectory() as tmp: + root = Path(tmp) + + self.assertEqual( + declared_pins(_write_requirements(root, body)), [("bare.entry", None)] + ) + + def test_a_missing_file_declares_nothing(self): + with TemporaryDirectory() as tmp: + self.assertEqual(declared_pins(Path(tmp) / "absent.yml"), []) + + +class TestUnsatisfied(unittest.TestCase): + def test_every_pin_installed_at_its_version_is_satisfied(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + requirements = _write_requirements(root) + _install(root, "community.general", "13.4.0") + _install(root, "hetzner.hcloud", "7.0.1") + + self.assertEqual(unsatisfied(requirements, root), []) + + def test_absent_collection_is_reported(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + requirements = _write_requirements(root) + _install(root, "community.general", "13.4.0") + + self.assertEqual(unsatisfied(requirements, root), ["hetzner.hcloud:7.0.1"]) + + def test_wrong_version_is_reported_although_the_directory_exists(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + requirements = _write_requirements(root) + _install(root, "community.general", "13.4.0") + _install(root, "hetzner.hcloud", "6.9.0") + + self.assertEqual(unsatisfied(requirements, root), ["hetzner.hcloud:7.0.1"]) + + def test_unpinned_entry_can_never_be_confirmed(self): + body = "---\ncollections:\n - name: community.general\n" + with TemporaryDirectory() as tmp: + root = Path(tmp) + requirements = _write_requirements(root, body) + _install(root, "community.general", "13.4.0") + + self.assertEqual(unsatisfied(requirements, root), ["community.general"]) + + def test_unreadable_manifest_is_reported(self): + with TemporaryDirectory() as tmp: + root = Path(tmp) + requirements = _write_requirements(root) + _install(root, "community.general", "13.4.0") + _install(root, "hetzner.hcloud", "7.0.1") + manifest = ( + root / "ansible_collections" / "hetzner" / "hcloud" / "MANIFEST.json" + ) + manifest.write_text("{not json", encoding="utf-8") + + self.assertEqual(unsatisfied(requirements, root), ["hetzner.hcloud:7.0.1"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/install/test_system_pkg.py b/tests/unit/python/utils/install/test_system_pkg.py index 4c9cda2901..d49299b9d3 100644 --- a/tests/unit/python/utils/install/test_system_pkg.py +++ b/tests/unit/python/utils/install/test_system_pkg.py @@ -41,6 +41,44 @@ class TestInstallPackageCandidates(unittest.TestCase): self.assertIn("DPkg::Lock::Timeout=600", commands[0]) self.assertIn("DPkg::Lock::Timeout=600", commands[1]) + def test_apt_refreshes_the_index_once_before_it_gives_up(self) -> None: + err = subprocess.CalledProcessError(returncode=1, cmd=["apt-get"]) + + def outcome(command: list[str]) -> None: + if "install" in command: + raise err + + with mock.patch.object(system_pkg, "run_privileged", side_effect=outcome): + self.assertRaises( + RuntimeError, + system_pkg.install_package_candidates, + "apt-get", + ["ruby"], + ) + commands = [ + c.args[0] + for c in system_pkg.run_privileged.call_args_list # type: ignore[attr-defined] + ] + self.assertEqual( + ["update", "install", "update", "install"], + [("update" if "update" in c else "install") for c in commands], + "a mirror mid-sync serves a pool file the fetched index disagrees " + "with, and apt's own Acquire::Retries re-fetches that same pair; " + "the install must be offered a fresh index once (run 34653542922, " + "Hugo#0: 'File has unexpected size ... Mirror sync in progress?')", + ) + + def test_a_manager_without_an_index_does_not_install_twice(self) -> None: + err = subprocess.CalledProcessError(returncode=1, cmd=["pacman"]) + with mock.patch.object(system_pkg, "run_privileged", side_effect=err) as priv: + self.assertRaises( + RuntimeError, + system_pkg.install_package_candidates, + "pacman", + ["ansible-core", "ansible"], + ) + self.assertEqual(2, len(priv.call_args_list)) + def test_raises_when_all_candidates_fail(self) -> None: err = subprocess.CalledProcessError(returncode=1, cmd=["pacman"]) with mock.patch.object(system_pkg, "run_privileged", side_effect=err): @@ -61,7 +99,25 @@ class TestInstallCommandViaPkg(unittest.TestCase): mock.patch.object(system_pkg, "install_package_candidates") as cand, ): system_pkg.install_command_via_pkg("ansible-playbook") - cand.assert_called_once_with("pacman", ["ansible-core", "ansible"]) + cand.assert_called_once_with( + "pacman", ["ansible-core", "ansible"], provides="ansible-playbook" + ) + + def test_a_candidate_that_installs_without_providing_the_command_fails( + self, + ) -> None: + with ( + mock.patch.object(system_pkg, "_prepare_manager"), + mock.patch.object( + system_pkg, "_install_one", side_effect=lambda m, p: p != "npm" + ), + mock.patch.object(system_pkg.shutil, "which", return_value=None), + self.assertRaises(RuntimeError) as caught, + ): + system_pkg.install_package_candidates( + "apt-get", ["npm", "nodejs"], provides="npm" + ) + self.assertIn("still not on PATH", str(caught.exception)) def test_unknown_command_raises(self) -> None: with mock.patch.object( diff --git a/tests/unit/python/utils/manager/test_inventory_manager.py b/tests/unit/python/utils/manager/test_inventory_manager.py index 5740a345a5..96a98c2b60 100644 --- a/tests/unit/python/utils/manager/test_inventory_manager.py +++ b/tests/unit/python/utils/manager/test_inventory_manager.py @@ -1,13 +1,16 @@ import base64 import tempfile from pathlib import Path +from typing import ClassVar from unittest import TestCase, main, mock from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any from utils.handler.vault import VaultScalar -from utils.manager.inventory import InventoryManager +from utils.manager.inventory import InventoryManager, validate_supplied_value from utils.manager.value_generator import ValueGenerator from utils.roles.mapping import ( ROLE_FILE_META_SECRETS, @@ -760,5 +763,104 @@ class TestInventoryManagerVariant(TestCase): self.assertEqual(cfg, {}) +class TestSuppliedValueValidation(TestCase): + """A schema that declares a shape must reject a value contradicting it. + + Without this the declaration is decoration: the 192 `validation:` blocks + already in the role schemas are enforced nowhere, and a `regex` would have + joined them. + """ + + SCHEMA: ClassVar[dict[str, str]] = { + "type": "string", + "regex": "sk-[A-Za-z0-9]{4,}", + } + + def test_a_matching_value_passes(self): + validate_supplied_value("credentials.api_key", "sk-abcd1234", self.SCHEMA) + + def test_an_empty_value_is_not_configured_and_passes(self): + validate_supplied_value("credentials.api_key", "", self.SCHEMA) + validate_supplied_value("credentials.api_key", None, self.SCHEMA) + + def test_a_value_failing_the_pattern_aborts(self): + with self.assertRaises(SystemExit): + validate_supplied_value("credentials.api_key", "nope", self.SCHEMA) + + def test_a_partial_match_is_not_enough(self): + with self.assertRaises(SystemExit): + validate_supplied_value("credentials.api_key", "sk-ab!!", self.SCHEMA) + + def test_a_value_of_the_wrong_type_aborts(self): + with self.assertRaises(SystemExit): + validate_supplied_value("credentials.port", 8080, {"type": "string"}) + + def test_an_unknown_declared_type_aborts(self): + with self.assertRaises(SystemExit): + validate_supplied_value("credentials.x", "v", {"type": "uuid"}) + + def test_a_schema_declaring_neither_accepts_anything(self): + validate_supplied_value("credentials.x", "anything", {"description": "free"}) + + def test_an_unrendered_template_is_not_a_value(self): + for value in ("{{ API.openai.api_key }}", "{% if x %}a{% endif %}"): + with self.subTest(value=value): + validate_supplied_value("credentials.api_key", value, self.SCHEMA) + + +class TestProviderKeyPattern(TestCase): + """The shipped provider-key pattern must outlive a vendor's format change. + + OpenAI moved from `sk-` to `sk-proj-` without notice. A schema that pinned + the prefix would reject a valid key and abort inventory creation, so the + pattern checks what a paste can get wrong instead. + """ + + ACCEPTED: ClassVar[tuple[str, ...]] = ( + "sk-proj-AbCdEfGh1234567890xyz", + "sk-ant-api03-AbCdEfGh1234567890", + "sk-or-v1-AbCdEfGh1234567890abc", + "sk-AbCdEfGh1234567890legacyKey", + "some-future-format-2099-abcdef", + ) + REJECTED: ClassVar[tuple[str, ...]] = ( + "sk-proj-AbCdEfGh1234567890xyz\n", + "sk-short", + "<your-key-here>", + "sk-proj-Ab Cd 1234567890 xyz", + ) + + def _credentials(self) -> dict: + path = PROJECT_ROOT / "roles/svc-ai-litellm" / ROLE_FILE_META_SECRETS + return load_yaml_any(str(path))["credentials"] + + def _schema(self) -> dict: + return self._credentials()["openai_api_key"] + + def test_every_declared_default_survives_its_own_schema(self): + """A default is written verbatim and read back as a supplied value. + + Run 34883491022 died in every job because the provider keys' own + `{{ API.<vendor>.api_key }}` reached the pattern on the second read. + """ + for key, schema in self._credentials().items(): + if "default" not in schema: + continue + with self.subTest(key=key): + validate_supplied_value(f"credentials.{key}", schema["default"], schema) + + def test_every_known_provider_form_is_accepted(self): + schema = self._schema() + for value in self.ACCEPTED: + with self.subTest(value=value): + validate_supplied_value("credentials.openai_api_key", value, schema) + + def test_a_broken_paste_is_rejected(self): + schema = self._schema() + for value in self.REJECTED: + with self.subTest(value=value), self.assertRaises(SystemExit): + validate_supplied_value("credentials.openai_api_key", value, schema) + + if __name__ == "__main__": main() diff --git a/tests/unit/python/utils/manager/test_value_generator.py b/tests/unit/python/utils/manager/test_value_generator.py index b35df9191e..46e2d08478 100644 --- a/tests/unit/python/utils/manager/test_value_generator.py +++ b/tests/unit/python/utils/manager/test_value_generator.py @@ -45,6 +45,11 @@ class TestValueGenerator(unittest.TestCase): v = self.vg.generate_value("sha1") self.assertTrue(re.fullmatch(r"[0-9a-f]{40}", v)) + def test_generate_value_sk_prefixed(self): + v = self.vg.generate_value("sk_prefixed") + self.assertTrue(v.startswith("sk-")) + self.assertTrue(re.fullmatch(r"[A-Za-z0-9]{48}", v.split("sk-", 1)[1])) + def test_generate_value_base64_prefixed_32(self): v = self.vg.generate_value("base64_prefixed_32") self.assertTrue(v.startswith("base64:")) diff --git a/tests/unit/python/utils/networks/_render_helpers.py b/tests/unit/python/utils/networks/_render_helpers.py new file mode 100644 index 0000000000..173cd5debf --- /dev/null +++ b/tests/unit/python/utils/networks/_render_helpers.py @@ -0,0 +1,48 @@ +from __future__ import annotations + + +def _entity_name(role: str) -> str: + return role.rsplit("-", 1)[-1] + + +def _const_lookup_config(**values): + def _lookup(_app, path, default): + return values.get(path, default) + + return _lookup + + +def _role_lookup_config(per_role, **values): + """Answer per (role, path) so a provider override is expressible. + + Args: + per_role: ``{role: {path: value}}`` consulted before the shared map. + values: paths every role answers identically. + + An unset path is answered the way utils.roles.applications.config.get does + it, which turns a ``None`` default into ``False``. + """ + + def _lookup(app, path, default): + scoped = per_role.get(app) or {} + if path in scoped: + return scoped[path] + if path in values: + return values[path] + return default if default is not None else False + + return _lookup + + +def _const_lookup_database(**values): + def _lookup(_app, key): + return values.get(key, "") + + return _lookup + + +def _database(local): + def _lookup(_app, key): + return {"local": local}.get(key, "") + + return _lookup diff --git a/tests/unit/python/utils/networks/test_render.py b/tests/unit/python/utils/networks/test_render.py index 6a707b7744..cfc075685f 100644 --- a/tests/unit/python/utils/networks/test_render.py +++ b/tests/unit/python/utils/networks/test_render.py @@ -11,458 +11,10 @@ regressions surface with a precise failure rather than a snapshot diff. from __future__ import annotations import unittest -from typing import ClassVar -from utils.networks.render import ( - _coerce_bool, - _compute_attachments, - _is_consumer, - _own_shared_net_provider, - _suppress_default, - compute_external_network_roles, - render_compose_networks, - render_container_networks, - shared_network_compose_key, -) +from utils.networks.render import render_compose_networks, render_container_networks - -def _entity_name(role: str) -> str: - return role.rsplit("-", 1)[-1] - - -def _const_lookup_config(**values): - def _lookup(_app, path, default): - return values.get(path, default) - - return _lookup - - -def _const_lookup_database(**values): - def _lookup(_app, key): - return values.get(key, "") - - return _lookup - - -class TestCoerceBool(unittest.TestCase): - def test_bool_passthrough(self): - self.assertTrue(_coerce_bool(True)) - self.assertFalse(_coerce_bool(False)) - - def test_string_truthy_set(self): - for v in ("true", "True", "TRUE", "1", "yes", "Yes"): - self.assertTrue(_coerce_bool(v), msg=v) - - def test_string_falsy_set(self): - for v in ("false", "no", "0", "", "anything-else"): - self.assertFalse(_coerce_bool(v), msg=v) - - def test_none_is_false(self): - self.assertFalse(_coerce_bool(None)) - - def test_other_truthy(self): - self.assertTrue(_coerce_bool(1)) - self.assertTrue(_coerce_bool([0])) - self.assertFalse(_coerce_bool(0)) - self.assertFalse(_coerce_bool([])) - - -class TestSuppressDefault(unittest.TestCase): - def test_svc_db_prefix_suppresses(self): - self.assertTrue(_suppress_default("svc-db-mariadb")) - self.assertTrue(_suppress_default("svc-db-postgres")) - - def test_svc_ai_prefix_suppresses(self): - self.assertTrue(_suppress_default("svc-ai-ollama")) - - def test_other_prefixes_do_not_suppress(self): - self.assertFalse(_suppress_default("svc-prx-openresty")) - self.assertFalse(_suppress_default("web-app-baserow")) - self.assertFalse(_suppress_default("web-svc-collabora")) - - -class TestIsConsumer(unittest.TestCase): - def test_database_kind_all_conditions(self): - entry = { - "role": "svc-db-postgres", - "overlay": {"consumer": {"kind": "database"}}, - } - lookup_db = _const_lookup_database( - enabled=True, shared=True, id="svc-db-postgres" - ) - self.assertTrue( - _is_consumer(entry, "web-app-baserow", _const_lookup_config(), lookup_db) - ) - - def test_database_kind_wrong_provider(self): - entry = { - "role": "svc-db-mariadb", - "overlay": {"consumer": {"kind": "database"}}, - } - lookup_db = _const_lookup_database( - enabled=True, shared=True, id="svc-db-postgres" - ) - self.assertFalse( - _is_consumer(entry, "web-app-baserow", _const_lookup_config(), lookup_db) - ) - - def test_database_kind_not_shared(self): - entry = { - "role": "svc-db-mariadb", - "overlay": {"consumer": {"kind": "database"}}, - } - lookup_db = _const_lookup_database( - enabled=True, shared=False, id="svc-db-mariadb" - ) - self.assertFalse( - _is_consumer(entry, "web-app-baserow", _const_lookup_config(), lookup_db) - ) - - def test_services_flags_explicit_key_and_flags(self): - entry = { - "role": "svc-prx-openresty", - "entity_name": "openresty", - "overlay": { - "consumer": { - "kind": "services_flags", - "key": "sso", - "flags": ["enabled"], - } - }, - } - cfg = _const_lookup_config(**{"services.sso.enabled": True}) - self.assertTrue( - _is_consumer(entry, "web-app-baserow", cfg, _const_lookup_database()) - ) - - def test_services_flags_default_key_from_provides(self): - entry = { - "role": "svc-db-openldap", - "entity_name": "openldap", - "provides": "ldap", - "overlay": {}, - } - cfg = _const_lookup_config( - **{"services.ldap.enabled": True, "services.ldap.shared": True} - ) - self.assertTrue( - _is_consumer(entry, "web-app-bookwyrm", cfg, _const_lookup_database()) - ) - - def test_services_flags_default_key_from_entity_name(self): - entry = { - "role": "svc-ai-ollama", - "entity_name": "ollama", - "overlay": {}, - } - cfg = _const_lookup_config( - **{"services.ollama.enabled": True, "services.ollama.shared": True} - ) - self.assertTrue( - _is_consumer(entry, "web-app-openwebui", cfg, _const_lookup_database()) - ) - - def test_services_flags_default_flags_require_enabled_and_shared(self): - entry = { - "role": "svc-db-openldap", - "entity_name": "openldap", - "provides": "ldap", - "overlay": {}, - } - cfg = _const_lookup_config(**{"services.ldap.enabled": True}) - self.assertFalse( - _is_consumer(entry, "web-app-x", cfg, _const_lookup_database()) - ) - - def test_unknown_kind_returns_false(self): - entry = {"role": "x", "overlay": {"consumer": {"kind": "future_thing"}}} - self.assertFalse( - _is_consumer( - entry, "web-app-x", _const_lookup_config(), _const_lookup_database() - ) - ) - - def test_web_facing_matches_web_app_and_web_svc(self): - entry = { - "role": "svc-prx-openresty", - "overlay": {"consumer": {"kind": "web_facing"}}, - } - for app in ("web-app-baserow", "web-svc-logout"): - self.assertTrue( - _is_consumer( - entry, app, _const_lookup_config(), _const_lookup_database() - ), - msg=app, - ) - - def test_web_facing_rejects_non_web_roles(self): - entry = { - "role": "svc-prx-openresty", - "overlay": {"consumer": {"kind": "web_facing"}}, - } - for app in ("svc-db-mariadb", "svc-ai-ollama", "sys-svc-x"): - self.assertFalse( - _is_consumer( - entry, app, _const_lookup_config(), _const_lookup_database() - ), - msg=app, - ) - - -class TestIsConsumerOnionSso(unittest.TestCase): - ENTRY: ClassVar[dict] = { - "role": "svc-net-tor", - "overlay": { - "consumer": { - "kind": "onion_sso", - "key": "sso", - "provider": "web-app-keycloak", - "provider_key": "tor", - } - }, - } - - @staticmethod - def _lookup(*, sso, provider_tor): - def _inner(app, path, default): - if app == "web-app-keycloak" and path == "services.tor.enabled": - return provider_tor - if path == "services.sso.enabled": - return sso - return default - - return _inner - - def _consumer(self, *, sso, provider_tor, entry=None): - return _is_consumer( - entry or self.ENTRY, - "web-app-nextcloud", - self._lookup(sso=sso, provider_tor=provider_tor), - _const_lookup_database(), - ) - - def test_attaches_only_when_sso_consumer_meets_onion_provider(self): - cases = [ - (True, True, True), - (True, False, False), - (False, True, False), - (False, False, False), - ] - for sso, provider_tor, expected in cases: - with self.subTest(sso=sso, provider_tor=provider_tor): - self.assertIs( - self._consumer(sso=sso, provider_tor=provider_tor), expected - ) - - def test_provider_is_mandatory(self): - entry = {"role": "svc-net-tor", "overlay": {"consumer": {"kind": "onion_sso"}}} - self.assertFalse(self._consumer(sso=True, provider_tor=True, entry=entry)) - - def test_provider_key_defaults_to_tor(self): - entry = { - "role": "svc-net-tor", - "overlay": { - "consumer": {"kind": "onion_sso", "provider": "web-app-keycloak"} - }, - } - self.assertTrue(self._consumer(sso=True, provider_tor=True, entry=entry)) - self.assertFalse(self._consumer(sso=True, provider_tor=False, entry=entry)) - - -class TestComputeAttachments(unittest.TestCase): - def test_skips_canonical_aliases(self): - registry = { - "css": { - "role": "web-svc-cdn", - "entity_name": "cdn", - "canonical": "cdn", - "overlay": { - "modes": ["swarm"], - "topology": "shared_net", - }, - }, - } - att, default_aliases = _compute_attachments( - registry, - "web-app-x", - "swarm", - _const_lookup_config(), - _const_lookup_database(), - ) - self.assertEqual(att, []) - self.assertEqual(default_aliases, []) - - def test_skips_mode_mismatch(self): - registry = { - "ldap": { - "role": "svc-db-openldap", - "entity_name": "openldap", - "provides": "ldap", - "overlay": { - "modes": ["compose"], - "topology": "shared_net", - }, - }, - } - att, _ = _compute_attachments( - registry, - "svc-db-openldap", - "swarm", - _const_lookup_config(), - _const_lookup_database(), - ) - self.assertEqual(att, []) - - def test_skips_beacon_entries_for_non_provider(self): - registry = { - "sso": { - "role": "web-app-keycloak", - "entity_name": "keycloak", - "provides": "sso", - "overlay": { - "modes": ["swarm"], - "proxy_resolvable": True, - "aliases": ["auth.example.com"], - }, - }, - } - att, default_aliases = _compute_attachments( - registry, - "web-app-baserow", - "swarm", - _const_lookup_config(**{"services.sso.enabled": True}), - _const_lookup_database(), - ) - self.assertEqual(att, []) - self.assertEqual(default_aliases, []) - - def test_provider_self_render_uses_default_alias_from_entity_name(self): - registry = { - "ldap": { - "role": "svc-db-openldap", - "entity_name": "openldap", - "provides": "ldap", - "overlay": { - "modes": ["swarm"], - "topology": "shared_net", - }, - }, - } - att, _ = _compute_attachments( - registry, - "svc-db-openldap", - "swarm", - _const_lookup_config(), - _const_lookup_database(), - ) - self.assertEqual(len(att), 1) - self.assertEqual(att[0]["aliases"], ["openldap"]) - - def test_proxy_aliases_override_topology_aliases_in_harvest(self): - """A shared_net beacon exposes only proxy_aliases to the harvest; its - own topology aliases (the entity name) must stay off the proxy.""" - registry = { - "openresty": { - "role": "svc-prx-openresty", - "entity_name": "openresty", - "overlay": { - "modes": ["swarm"], - "topology": "shared_net", - "collect_proxy_resolvable": True, - }, - }, - "seaweedfs": { - "role": "web-app-seaweedfs", - "entity_name": "seaweedfs", - "overlay": { - "modes": ["swarm"], - "topology": "shared_net", - "proxy_resolvable": True, - "proxy_aliases": ["api.s3.example.com"], - "aliases": ["seaweedfs"], - }, - }, - } - att, _ = _compute_attachments( - registry, - "svc-prx-openresty", - "swarm", - _const_lookup_config(), - _const_lookup_database(), - ) - provider = next(a for a in att if a["is_provider"]) - self.assertIn("api.s3.example.com", provider["aliases"]) - self.assertNotIn("seaweedfs", provider["aliases"]) - - def test_proxy_resolvable_sweep_skips_canonical_clones(self): - registry = { - "openresty": { - "role": "svc-prx-openresty", - "entity_name": "openresty", - "overlay": {"modes": ["swarm"], "topology": "default_net"}, - }, - "real_beacon": { - "role": "web-app-keycloak", - "entity_name": "keycloak", - "provides": "sso", - "overlay": { - "modes": ["swarm"], - "proxy_resolvable": True, - "aliases": ["auth.example.com"], - }, - }, - "clone_alias": { - "role": "web-app-keycloak", - "entity_name": "keycloak", - "canonical": "sso", - "overlay": { - "modes": ["swarm"], - "proxy_resolvable": True, - "aliases": ["auth.example.com"], - }, - }, - } - _, default_aliases = _compute_attachments( - registry, - "svc-prx-openresty", - "swarm", - _const_lookup_config(), - _const_lookup_database(), - ) - self.assertEqual(default_aliases, ["auth.example.com"]) - - def test_proxy_resolvable_sweep_skips_self_role(self): - registry = { - "openresty": { - "role": "svc-prx-openresty", - "entity_name": "openresty", - "overlay": { - "modes": ["swarm"], - "topology": "default_net", - "proxy_resolvable": True, - "aliases": ["self-mistake"], - }, - }, - "sso": { - "role": "web-app-keycloak", - "entity_name": "keycloak", - "provides": "sso", - "overlay": { - "modes": ["swarm"], - "proxy_resolvable": True, - "aliases": ["auth.example.com"], - }, - }, - } - _, default_aliases = _compute_attachments( - registry, - "svc-prx-openresty", - "swarm", - _const_lookup_config(), - _const_lookup_database(), - ) - self.assertEqual(default_aliases.count("self-mistake"), 1) - self.assertIn("auth.example.com", default_aliases) +from ._render_helpers import _const_lookup_config, _const_lookup_database, _entity_name class TestRenderComposeNetworks(unittest.TestCase): @@ -560,6 +112,94 @@ class TestRenderComposeNetworks(unittest.TestCase): ) self.assertEqual(rendered, expected) + def test_a_role_with_nothing_to_attach_emits_no_networks_key(self): + """A bare `networks:` parses as null, and compose refuses it as not an array.""" + for render in (render_container_networks, render_compose_networks): + for role in ("svc-ai-mcp-adapter", "svc-db-nothing"): + with self.subTest(render=render.__name__, role=role): + self.assertEqual( + "", + render( + application_id=role, + deployment_mode="compose", + registry={}, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + ), + ) + + def test_a_role_that_keeps_the_default_still_renders_it(self): + """The guard must not swallow the default attachment it sits behind.""" + for render in (render_container_networks, render_compose_networks): + with self.subTest(render=render.__name__): + self.assertIn( + "default:", + render( + application_id="web-app-anything", + deployment_mode="compose", + registry={}, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + ), + ) + + def test_own_network_only_drops_the_consumer_networks(self): + registry = { + "qdrant": { + "role": "svc-db-qdrant", + "entity_name": "qdrant", + "overlay": {"modes": ["compose"], "topology": "shared_net"}, + }, + "moodle": { + "role": "web-app-moodle", + "entity_name": "moodle", + "overlay": {"modes": ["compose"], "topology": "shared_net"}, + }, + } + lookup_config = _const_lookup_config( + **{"services.moodle.enabled": True, "services.moodle.shared": True} + ) + full = render_container_networks( + application_id="svc-db-qdrant", + deployment_mode="compose", + registry=registry, + get_entity_name=_entity_name, + lookup_config=lookup_config, + lookup_database=_const_lookup_database(), + ) + restricted = render_container_networks( + application_id="svc-db-qdrant", + deployment_mode="compose", + registry=registry, + get_entity_name=_entity_name, + lookup_config=lookup_config, + lookup_database=_const_lookup_database(), + own_network_only=True, + provider_self_alias=False, + ) + self.assertIn("moodle:", full) + self.assertIn("qdrant:", restricted) + self.assertNotIn("moodle:", restricted) + self.assertNotIn("aliases:", restricted) + + def test_own_network_only_emits_nothing_without_an_attachment(self): + rendered = render_container_networks( + application_id="web-app-prometheus", + deployment_mode="compose", + registry={}, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + own_network_only=True, + ) + self.assertEqual( + rendered, + "", + "a bare 'networks:' key is not a list and compose refuses the file", + ) + def test_node_local_swarm_renders_bridge(self): rendered = render_compose_networks( application_id="svc-runner", @@ -591,342 +231,5 @@ class TestRenderComposeNetworks(unittest.TestCase): self.assertNotIn("name:", rendered) -class TestComputeExternalNetworkRoles(unittest.TestCase): - def test_returns_consumer_provider_role(self): - registry = { - "redis": { - "role": "svc-db-redis", - "entity_name": "redis", - "overlay": { - "modes": ["swarm"], - "topology": "shared_net", - "consumer": {"kind": "services_flags", "key": "redis"}, - }, - }, - } - cfg = _const_lookup_config( - **{"services.redis.enabled": True, "services.redis.shared": True} - ) - roles = compute_external_network_roles( - application_id="web-app-gitea", - deployment_mode="swarm", - registry=registry, - lookup_config=cfg, - lookup_database=_const_lookup_database(), - ) - self.assertEqual(roles, ["svc-db-redis"]) - - def test_matches_external_true_entries_in_rendered_compose(self): - registry = { - "redis": { - "role": "svc-db-redis", - "entity_name": "redis", - "overlay": { - "modes": ["swarm"], - "topology": "shared_net", - "consumer": {"kind": "services_flags", "key": "redis"}, - }, - }, - } - cfg = _const_lookup_config( - **{"services.redis.enabled": True, "services.redis.shared": True} - ) - rendered = render_compose_networks( - application_id="web-app-gitea", - deployment_mode="swarm", - registry=registry, - get_entity_name=_entity_name, - lookup_config=cfg, - lookup_database=_const_lookup_database(), - ) - roles = compute_external_network_roles( - application_id="web-app-gitea", - deployment_mode="swarm", - registry=registry, - lookup_config=cfg, - lookup_database=_const_lookup_database(), - ) - self.assertIn("redis:\n external: true", rendered) - self.assertEqual([_entity_name(r) for r in roles], ["redis"]) - - def test_own_default_net_provider_not_returned(self): - registry = { - "openresty": { - "role": "svc-prx-openresty", - "entity_name": "openresty", - "overlay": {"modes": ["swarm"], "topology": "default_net"}, - }, - } - roles = compute_external_network_roles( - application_id="svc-prx-openresty", - deployment_mode="swarm", - registry=registry, - lookup_config=_const_lookup_config(), - lookup_database=_const_lookup_database(), - ) - self.assertEqual(roles, []) - - -class TestRenderContainerNetworks(unittest.TestCase): - def test_output_starts_with_leading_newline(self): - registry = { - "openresty": { - "role": "svc-prx-openresty", - "entity_name": "openresty", - "overlay": {"modes": ["swarm"], "topology": "default_net"}, - }, - } - rendered = render_container_networks( - application_id="svc-prx-openresty", - deployment_mode="swarm", - registry=registry, - get_entity_name=_entity_name, - lookup_config=_const_lookup_config(), - lookup_database=_const_lookup_database(), - ) - self.assertTrue(rendered.startswith("\n")) - self.assertIn("networks:", rendered) - - def test_consumer_attach_uses_dict_empty(self): - registry = { - "ldap": { - "role": "svc-db-openldap", - "entity_name": "openldap", - "provides": "ldap", - "overlay": {"modes": ["swarm"], "topology": "shared_net"}, - }, - } - rendered = render_container_networks( - application_id="web-app-bookwyrm", - deployment_mode="swarm", - registry=registry, - get_entity_name=_entity_name, - lookup_config=_const_lookup_config( - **{"services.ldap.enabled": True, "services.ldap.shared": True} - ), - lookup_database=_const_lookup_database(), - ) - self.assertIn("openldap:\n {}", rendered) - - def test_provider_default_net_skips_self_attach_emits_alias_block(self): - registry = { - "openresty": { - "role": "svc-prx-openresty", - "entity_name": "openresty", - "overlay": {"modes": ["swarm"], "topology": "default_net"}, - }, - "sso": { - "role": "web-app-keycloak", - "entity_name": "keycloak", - "provides": "sso", - "overlay": { - "modes": ["swarm"], - "proxy_resolvable": True, - "aliases": ["auth.example.com"], - }, - }, - } - rendered = render_container_networks( - application_id="svc-prx-openresty", - deployment_mode="swarm", - registry=registry, - get_entity_name=_entity_name, - lookup_config=_const_lookup_config(), - lookup_database=_const_lookup_database(), - ) - self.assertNotIn("openresty:\n", rendered) - self.assertIn("default:", rendered) - self.assertIn("- auth.example.com", rendered) - - def test_empty_registry_emits_only_default(self): - rendered = render_container_networks( - application_id="web-app-plain", - deployment_mode="swarm", - registry={}, - get_entity_name=_entity_name, - lookup_config=_const_lookup_config(), - lookup_database=_const_lookup_database(), - ) - self.assertEqual(rendered, "\nnetworks:\n default:") - - -class TestRenderEncryption(unittest.TestCase): - def test_swarm_encrypted_false_emits_lowercase_quoted_literal(self): - rendered = render_compose_networks( - application_id="web-app-x", - deployment_mode="swarm", - registry={}, - get_entity_name=_entity_name, - lookup_config=_const_lookup_config(), - lookup_database=_const_lookup_database(), - swarm_encrypted=False, - ) - self.assertIn('encrypted: "false"', rendered) - self.assertNotIn("encrypted: false\n", rendered) - self.assertNotIn('encrypted: "False"', rendered) - - -_PROVIDER_REGISTRY = { - "seaweedfs": { - "role": "web-app-seaweedfs", - "entity_name": "seaweedfs", - "overlay": {"modes": ["compose", "swarm"], "topology": "shared_net"}, - }, -} - - -class TestOwnSharedNetProvider(unittest.TestCase): - """A multi-service objstore provider (seaweedfs/minio) renders its own - ``<entity>`` net as external + a bare auto-IPAM project default (so the - role subnet, owned by the external net, is never re-requested), and its - sidecar services attach without the provider alias. Locks the - objstore-net-fix contract so a render edit cannot silently regress it.""" - - def test_helper_true_only_for_own_shared_net_provider(self): - own = [ - {"role": "web-app-seaweedfs", "topology": "shared_net", "is_provider": True} - ] - consumer = [ - { - "role": "web-app-seaweedfs", - "topology": "shared_net", - "is_provider": False, - } - ] - self.assertTrue(_own_shared_net_provider(own, "seaweedfs", _entity_name)) - self.assertFalse(_own_shared_net_provider(consumer, "baserow", _entity_name)) - self.assertFalse(_own_shared_net_provider([], "seaweedfs", _entity_name)) - - def test_compose_default_drops_name_and_subnet(self): - rendered = render_compose_networks( - application_id="web-app-seaweedfs", - deployment_mode="compose", - registry=_PROVIDER_REGISTRY, - get_entity_name=_entity_name, - lookup_config=_const_lookup_config( - **{"networks.local.subnet": "192.168.206.0/24"} - ), - lookup_database=_const_lookup_database(), - ) - self.assertIn(" seaweedfs:\n external: true", rendered) - self.assertIn(" default:\n driver: bridge", rendered) - self.assertNotIn("192.168.206", rendered) - self.assertNotIn("name: seaweedfs", rendered) - - def test_swarm_default_is_nameless_overlay(self): - rendered = render_compose_networks( - application_id="web-app-seaweedfs", - deployment_mode="swarm", - registry=_PROVIDER_REGISTRY, - get_entity_name=_entity_name, - lookup_config=_const_lookup_config(), - lookup_database=_const_lookup_database(), - ) - self.assertIn(" seaweedfs:\n external: true", rendered) - self.assertIn(" default:\n driver: overlay", rendered) - self.assertNotIn("name: seaweedfs", rendered) - - def test_main_publishes_alias_sidecar_does_not(self): - kwargs = { - "application_id": "web-app-seaweedfs", - "deployment_mode": "compose", - "registry": _PROVIDER_REGISTRY, - "get_entity_name": _entity_name, - "lookup_config": _const_lookup_config(), - "lookup_database": _const_lookup_database(), - } - main = render_container_networks(**kwargs) - sidecar = render_container_networks(provider_self_alias=False, **kwargs) - self.assertIn("seaweedfs:\n aliases:\n - seaweedfs", main) - self.assertIn("seaweedfs:\n {}", sidecar) - self.assertNotIn("- seaweedfs", sidecar) - - -class TestSharedNetworkComposeKey(unittest.TestCase): - """The key under which the pre-created ``<entity>`` network appears in the - rendered file. Callers stamp it into ``com.docker.compose.network``; docker - compose resolves a project's networks against that label, so a key that does - not match the rendered file makes compose adopt the wrong network and skip - creating the right one.""" - - def _key(self, application_id, registry, deployment_mode="compose"): - return shared_network_compose_key( - application_id=application_id, - deployment_mode=deployment_mode, - registry=registry, - get_entity_name=_entity_name, - lookup_config=_const_lookup_config(), - lookup_database=_const_lookup_database(), - ) - - def test_own_shared_net_provider_keys_on_its_entity(self): - for mode in ("compose", "swarm"): - with self.subTest(mode=mode): - self.assertEqual( - self._key("web-app-seaweedfs", _PROVIDER_REGISTRY, mode), - "seaweedfs", - ) - - def test_plain_app_keys_on_default(self): - for mode in ("compose", "swarm"): - with self.subTest(mode=mode): - self.assertEqual(self._key("web-app-baserow", {}, mode), "default") - - def test_consumer_of_a_foreign_provider_keys_on_default(self): - registry = { - "ldap": { - "role": "svc-db-openldap", - "entity_name": "openldap", - "provides": "ldap", - "overlay": {"modes": ["compose"], "topology": "shared_net"}, - }, - } - self.assertEqual(self._key("web-app-baserow", registry), "default") - - def test_node_local_forces_the_compose_answer(self): - self.assertEqual( - shared_network_compose_key( - application_id="web-app-seaweedfs", - deployment_mode="swarm", - registry=_PROVIDER_REGISTRY, - get_entity_name=_entity_name, - lookup_config=_const_lookup_config(), - lookup_database=_const_lookup_database(), - node_local=True, - ), - "seaweedfs", - ) - - def test_key_matches_the_key_the_renderer_emits(self): - """The contract that makes this a single source: whatever key the - function reports must be the key the rendered networks block actually - uses for the entity network.""" - cases = ( - ("web-app-seaweedfs", _PROVIDER_REGISTRY), - ("web-app-baserow", {}), - ) - for application_id, registry in cases: - for mode in ("compose", "swarm"): - with self.subTest(application_id=application_id, mode=mode): - key = self._key(application_id, registry, mode) - rendered = render_compose_networks( - application_id=application_id, - deployment_mode=mode, - registry=registry, - get_entity_name=_entity_name, - lookup_config=_const_lookup_config( - **{"networks.local.subnet": "192.168.206.0/24"} - ), - lookup_database=_const_lookup_database(), - ) - self.assertIn(f" {key}:", rendered) - entity = _entity_name(application_id) - if key == "default": - self.assertIn(f" name: {entity}", rendered) - else: - self.assertEqual(key, entity) - self.assertNotIn(f" name: {entity}", rendered) - - if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/networks/test_render_attachments.py b/tests/unit/python/utils/networks/test_render_attachments.py new file mode 100644 index 0000000000..f5fd9edb61 --- /dev/null +++ b/tests/unit/python/utils/networks/test_render_attachments.py @@ -0,0 +1,207 @@ +from __future__ import annotations + +import unittest + +from utils.networks.render import _compute_attachments + +from ._render_helpers import _const_lookup_config, _const_lookup_database + + +class TestComputeAttachments(unittest.TestCase): + def test_skips_canonical_aliases(self): + registry = { + "css": { + "role": "web-svc-cdn", + "entity_name": "cdn", + "canonical": "cdn", + "overlay": { + "modes": ["swarm"], + "topology": "shared_net", + }, + }, + } + att, default_aliases = _compute_attachments( + registry, + "web-app-x", + "swarm", + _const_lookup_config(), + _const_lookup_database(), + ) + self.assertEqual(att, []) + self.assertEqual(default_aliases, []) + + def test_skips_mode_mismatch(self): + registry = { + "ldap": { + "role": "svc-db-openldap", + "entity_name": "openldap", + "provides": "ldap", + "overlay": { + "modes": ["compose"], + "topology": "shared_net", + }, + }, + } + att, _ = _compute_attachments( + registry, + "svc-db-openldap", + "swarm", + _const_lookup_config(), + _const_lookup_database(), + ) + self.assertEqual(att, []) + + def test_skips_beacon_entries_for_non_provider(self): + registry = { + "sso": { + "role": "web-app-keycloak", + "entity_name": "keycloak", + "provides": "sso", + "overlay": { + "modes": ["swarm"], + "proxy_resolvable": True, + "aliases": ["auth.example.com"], + }, + }, + } + att, default_aliases = _compute_attachments( + registry, + "web-app-baserow", + "swarm", + _const_lookup_config(**{"services.sso.enabled": True}), + _const_lookup_database(), + ) + self.assertEqual(att, []) + self.assertEqual(default_aliases, []) + + def test_provider_self_render_uses_default_alias_from_entity_name(self): + registry = { + "ldap": { + "role": "svc-db-openldap", + "entity_name": "openldap", + "provides": "ldap", + "overlay": { + "modes": ["swarm"], + "topology": "shared_net", + }, + }, + } + att, _ = _compute_attachments( + registry, + "svc-db-openldap", + "swarm", + _const_lookup_config(), + _const_lookup_database(), + ) + self.assertEqual(len(att), 1) + self.assertEqual(att[0]["aliases"], ["openldap"]) + + def test_proxy_aliases_override_topology_aliases_in_harvest(self): + """A shared_net beacon exposes only proxy_aliases to the harvest; its + own topology aliases (the entity name) must stay off the proxy.""" + registry = { + "openresty": { + "role": "svc-prx-openresty", + "entity_name": "openresty", + "overlay": { + "modes": ["swarm"], + "topology": "shared_net", + "collect_proxy_resolvable": True, + }, + }, + "seaweedfs": { + "role": "web-app-seaweedfs", + "entity_name": "seaweedfs", + "overlay": { + "modes": ["swarm"], + "topology": "shared_net", + "proxy_resolvable": True, + "proxy_aliases": ["api.s3.example.com"], + "aliases": ["seaweedfs"], + }, + }, + } + att, _ = _compute_attachments( + registry, + "svc-prx-openresty", + "swarm", + _const_lookup_config(), + _const_lookup_database(), + ) + provider = next(a for a in att if a["is_provider"]) + self.assertIn("api.s3.example.com", provider["aliases"]) + self.assertNotIn("seaweedfs", provider["aliases"]) + + def test_proxy_resolvable_sweep_skips_canonical_clones(self): + registry = { + "openresty": { + "role": "svc-prx-openresty", + "entity_name": "openresty", + "overlay": {"modes": ["swarm"], "topology": "default_net"}, + }, + "real_beacon": { + "role": "web-app-keycloak", + "entity_name": "keycloak", + "provides": "sso", + "overlay": { + "modes": ["swarm"], + "proxy_resolvable": True, + "aliases": ["auth.example.com"], + }, + }, + "clone_alias": { + "role": "web-app-keycloak", + "entity_name": "keycloak", + "canonical": "sso", + "overlay": { + "modes": ["swarm"], + "proxy_resolvable": True, + "aliases": ["auth.example.com"], + }, + }, + } + _, default_aliases = _compute_attachments( + registry, + "svc-prx-openresty", + "swarm", + _const_lookup_config(), + _const_lookup_database(), + ) + self.assertEqual(default_aliases, ["auth.example.com"]) + + def test_proxy_resolvable_sweep_skips_self_role(self): + registry = { + "openresty": { + "role": "svc-prx-openresty", + "entity_name": "openresty", + "overlay": { + "modes": ["swarm"], + "topology": "default_net", + "proxy_resolvable": True, + "aliases": ["self-mistake"], + }, + }, + "sso": { + "role": "web-app-keycloak", + "entity_name": "keycloak", + "provides": "sso", + "overlay": { + "modes": ["swarm"], + "proxy_resolvable": True, + "aliases": ["auth.example.com"], + }, + }, + } + _, default_aliases = _compute_attachments( + registry, + "svc-prx-openresty", + "swarm", + _const_lookup_config(), + _const_lookup_database(), + ) + self.assertEqual(default_aliases.count("self-mistake"), 1) + self.assertIn("auth.example.com", default_aliases) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/networks/test_render_consumers.py b/tests/unit/python/utils/networks/test_render_consumers.py new file mode 100644 index 0000000000..53c7985d2f --- /dev/null +++ b/tests/unit/python/utils/networks/test_render_consumers.py @@ -0,0 +1,203 @@ +from __future__ import annotations + +import unittest +from typing import ClassVar + +from utils.networks.render import _coerce_bool, _is_consumer + +from ._render_helpers import ( + _const_lookup_config, + _const_lookup_database, + _role_lookup_config, +) + + +class TestCoerceBool(unittest.TestCase): + def test_bool_passthrough(self): + self.assertTrue(_coerce_bool(True)) + self.assertFalse(_coerce_bool(False)) + + def test_string_truthy_set(self): + for v in ("true", "True", "TRUE", "1", "yes", "Yes"): + self.assertTrue(_coerce_bool(v), msg=v) + + def test_string_falsy_set(self): + for v in ("false", "no", "0", "", "anything-else"): + self.assertFalse(_coerce_bool(v), msg=v) + + def test_none_is_false(self): + self.assertFalse(_coerce_bool(None)) + + def test_other_truthy(self): + self.assertTrue(_coerce_bool(1)) + self.assertTrue(_coerce_bool([0])) + self.assertFalse(_coerce_bool(0)) + self.assertFalse(_coerce_bool([])) + + +class TestMcpClientConsumer(unittest.TestCase): + """Only a client the provider admitted joins its network.""" + + ADMITTED: ClassVar[dict] = {"services.qdrant.mcp_consumer": True} + + def _consumer(self, **flags): + entry = { + "role": "web-app-homeassistant", + "overlay": {"consumer": {"kind": "mcp_client"}}, + } + return _is_consumer( + entry, + "svc-db-qdrant", + _const_lookup_config(**flags), + _const_lookup_database(), + ) + + def test_client_joins(self): + self.assertTrue( + self._consumer( + **{ + "mcp.enabled": True, + "mcp.shared": True, + "mcp.direction": "client", + **self.ADMITTED, + } + ) + ) + + def test_both_joins(self): + self.assertTrue( + self._consumer( + **{ + "mcp.enabled": True, + "mcp.shared": True, + "mcp.direction": "both", + **self.ADMITTED, + } + ) + ) + + def test_server_stays_out(self): + self.assertFalse( + self._consumer( + **{ + "mcp.enabled": True, + "mcp.shared": True, + "mcp.direction": "server", + } + ), + "a provider on another provider's network is the mesh this kind removes", + ) + + def test_disabled_stays_out(self): + self.assertFalse(self._consumer(**{"mcp.direction": "client"})) + + def test_a_client_that_never_declared_itself_stays_out(self): + self.assertFalse( + self._consumer( + **{ + "mcp.enabled": True, + "mcp.shared": True, + "mcp.direction": "client", + } + ), + "being a client is not an admission; the self-declaration decides", + ) + + def test_a_provider_that_states_nothing_admits_a_declared_client(self): + """Only an explicit false refuses; an unset flag inherits the client's + own declaration, and the accessor answers an unset path with false.""" + entry = { + "role": "web-app-gitlab", + "overlay": {"consumer": {"kind": "mcp_client"}}, + } + self.assertTrue( + _is_consumer( + entry, + "web-app-openwebui", + _role_lookup_config( + {"web-app-openwebui": {"services.openwebui.mcp_consumer": True}}, + **{ + "mcp.enabled": True, + "mcp.shared": True, + "mcp.direction": "client", + }, + ), + _const_lookup_database(), + ) + ) + + def test_a_provider_override_refuses_a_declared_client(self): + entry = { + "role": "web-app-homeassistant", + "overlay": {"consumer": {"kind": "mcp_client"}}, + } + self.assertFalse( + _is_consumer( + entry, + "svc-db-qdrant", + _role_lookup_config( + {"web-app-homeassistant": {"services.qdrant.mcp_consumer": False}}, + **{ + "mcp.enabled": True, + "mcp.shared": True, + "mcp.direction": "client", + "services.qdrant.mcp_consumer": True, + }, + ), + _const_lookup_database(), + ) + ) + + +class TestConsumerKindList(unittest.TestCase): + """A provider serving two kinds of consumer declares both on one overlay. + + Qdrant is the case: applications consume it as a vector database through the + services flags, and MCP clients must reach its adapter. One overlay per role + means a single `kind` cannot express both, and the second consumer silently + has no route. + """ + + ENTRY: ClassVar[dict] = { + "role": "svc-db-qdrant", + "entity_name": "qdrant", + "overlay": { + "consumer": {"kind": ["services_flags", "mcp_client"], "key": "qdrant"} + }, + } + + def _consumer(self, application_id, **flags): + return _is_consumer( + self.ENTRY, + application_id, + _const_lookup_config(**flags), + _const_lookup_database(), + ) + + def test_a_service_consumer_still_joins(self): + self.assertTrue( + self._consumer( + "web-app-openwebui", + **{"services.qdrant.enabled": True, "services.qdrant.shared": True}, + ) + ) + + def test_an_admitted_mcp_client_joins(self): + self.assertTrue( + self._consumer( + "web-app-hermes", + **{ + "mcp.enabled": True, + "mcp.shared": True, + "mcp.direction": "client", + "services.hermes.mcp_consumer": True, + }, + ) + ) + + def test_a_role_matching_neither_kind_stays_out(self): + self.assertFalse(self._consumer("web-app-unrelated")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/networks/test_render_container_networks.py b/tests/unit/python/utils/networks/test_render_container_networks.py new file mode 100644 index 0000000000..e2f729b1f8 --- /dev/null +++ b/tests/unit/python/utils/networks/test_render_container_networks.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import unittest + +from utils.networks.render import ( + compute_external_network_roles, + render_compose_networks, + render_container_networks, +) + +from ._render_helpers import _const_lookup_config, _const_lookup_database, _entity_name + + +class TestComputeExternalNetworkRoles(unittest.TestCase): + def test_returns_consumer_provider_role(self): + registry = { + "redis": { + "role": "svc-db-redis", + "entity_name": "redis", + "overlay": { + "modes": ["swarm"], + "topology": "shared_net", + "consumer": {"kind": "services_flags", "key": "redis"}, + }, + }, + } + cfg = _const_lookup_config( + **{"services.redis.enabled": True, "services.redis.shared": True} + ) + roles = compute_external_network_roles( + application_id="web-app-gitea", + deployment_mode="swarm", + registry=registry, + lookup_config=cfg, + lookup_database=_const_lookup_database(), + ) + self.assertEqual(roles, ["svc-db-redis"]) + + def test_matches_external_true_entries_in_rendered_compose(self): + registry = { + "redis": { + "role": "svc-db-redis", + "entity_name": "redis", + "overlay": { + "modes": ["swarm"], + "topology": "shared_net", + "consumer": {"kind": "services_flags", "key": "redis"}, + }, + }, + } + cfg = _const_lookup_config( + **{"services.redis.enabled": True, "services.redis.shared": True} + ) + rendered = render_compose_networks( + application_id="web-app-gitea", + deployment_mode="swarm", + registry=registry, + get_entity_name=_entity_name, + lookup_config=cfg, + lookup_database=_const_lookup_database(), + ) + roles = compute_external_network_roles( + application_id="web-app-gitea", + deployment_mode="swarm", + registry=registry, + lookup_config=cfg, + lookup_database=_const_lookup_database(), + ) + self.assertIn("redis:\n external: true", rendered) + self.assertEqual([_entity_name(r) for r in roles], ["redis"]) + + def test_own_default_net_provider_not_returned(self): + registry = { + "openresty": { + "role": "svc-prx-openresty", + "entity_name": "openresty", + "overlay": {"modes": ["swarm"], "topology": "default_net"}, + }, + } + roles = compute_external_network_roles( + application_id="svc-prx-openresty", + deployment_mode="swarm", + registry=registry, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + ) + self.assertEqual(roles, []) + + +class TestRenderContainerNetworks(unittest.TestCase): + def test_output_starts_with_leading_newline(self): + registry = { + "openresty": { + "role": "svc-prx-openresty", + "entity_name": "openresty", + "overlay": {"modes": ["swarm"], "topology": "default_net"}, + }, + } + rendered = render_container_networks( + application_id="svc-prx-openresty", + deployment_mode="swarm", + registry=registry, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + ) + self.assertTrue(rendered.startswith("\n")) + self.assertIn("networks:", rendered) + + def test_consumer_attach_uses_dict_empty(self): + registry = { + "ldap": { + "role": "svc-db-openldap", + "entity_name": "openldap", + "provides": "ldap", + "overlay": {"modes": ["swarm"], "topology": "shared_net"}, + }, + } + rendered = render_container_networks( + application_id="web-app-bookwyrm", + deployment_mode="swarm", + registry=registry, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config( + **{"services.ldap.enabled": True, "services.ldap.shared": True} + ), + lookup_database=_const_lookup_database(), + ) + self.assertIn("openldap:\n {}", rendered) + + def test_provider_default_net_skips_self_attach_emits_alias_block(self): + registry = { + "openresty": { + "role": "svc-prx-openresty", + "entity_name": "openresty", + "overlay": {"modes": ["swarm"], "topology": "default_net"}, + }, + "sso": { + "role": "web-app-keycloak", + "entity_name": "keycloak", + "provides": "sso", + "overlay": { + "modes": ["swarm"], + "proxy_resolvable": True, + "aliases": ["auth.example.com"], + }, + }, + } + rendered = render_container_networks( + application_id="svc-prx-openresty", + deployment_mode="swarm", + registry=registry, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + ) + self.assertNotIn("openresty:\n", rendered) + self.assertIn("default:", rendered) + self.assertIn("- auth.example.com", rendered) + + def test_empty_registry_emits_only_default(self): + rendered = render_container_networks( + application_id="web-app-plain", + deployment_mode="swarm", + registry={}, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + ) + self.assertEqual(rendered, "\nnetworks:\n default:") + + +class TestRenderEncryption(unittest.TestCase): + def test_swarm_encrypted_false_emits_lowercase_quoted_literal(self): + rendered = render_compose_networks( + application_id="web-app-x", + deployment_mode="swarm", + registry={}, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + swarm_encrypted=False, + ) + self.assertIn('encrypted: "false"', rendered) + self.assertNotIn("encrypted: false\n", rendered) + self.assertNotIn('encrypted: "False"', rendered) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/networks/test_render_is_consumer.py b/tests/unit/python/utils/networks/test_render_is_consumer.py new file mode 100644 index 0000000000..19b0ef297c --- /dev/null +++ b/tests/unit/python/utils/networks/test_render_is_consumer.py @@ -0,0 +1,200 @@ +from __future__ import annotations + +import unittest +from typing import ClassVar + +from utils.networks.render import _is_consumer + +from ._render_helpers import _const_lookup_config, _const_lookup_database + + +class TestIsConsumer(unittest.TestCase): + def test_database_kind_all_conditions(self): + entry = { + "role": "svc-db-postgres", + "overlay": {"consumer": {"kind": "database"}}, + } + lookup_db = _const_lookup_database( + enabled=True, shared=True, id="svc-db-postgres" + ) + self.assertTrue( + _is_consumer(entry, "web-app-baserow", _const_lookup_config(), lookup_db) + ) + + def test_database_kind_wrong_provider(self): + entry = { + "role": "svc-db-mariadb", + "overlay": {"consumer": {"kind": "database"}}, + } + lookup_db = _const_lookup_database( + enabled=True, shared=True, id="svc-db-postgres" + ) + self.assertFalse( + _is_consumer(entry, "web-app-baserow", _const_lookup_config(), lookup_db) + ) + + def test_database_kind_not_shared(self): + entry = { + "role": "svc-db-mariadb", + "overlay": {"consumer": {"kind": "database"}}, + } + lookup_db = _const_lookup_database( + enabled=True, shared=False, id="svc-db-mariadb" + ) + self.assertFalse( + _is_consumer(entry, "web-app-baserow", _const_lookup_config(), lookup_db) + ) + + def test_services_flags_explicit_key_and_flags(self): + entry = { + "role": "svc-prx-openresty", + "entity_name": "openresty", + "overlay": { + "consumer": { + "kind": "services_flags", + "key": "sso", + "flags": ["enabled"], + } + }, + } + cfg = _const_lookup_config(**{"services.sso.enabled": True}) + self.assertTrue( + _is_consumer(entry, "web-app-baserow", cfg, _const_lookup_database()) + ) + + def test_services_flags_default_key_from_provides(self): + entry = { + "role": "svc-db-openldap", + "entity_name": "openldap", + "provides": "ldap", + "overlay": {}, + } + cfg = _const_lookup_config( + **{"services.ldap.enabled": True, "services.ldap.shared": True} + ) + self.assertTrue( + _is_consumer(entry, "web-app-bookwyrm", cfg, _const_lookup_database()) + ) + + def test_services_flags_default_key_from_entity_name(self): + entry = { + "role": "svc-ai-ollama", + "entity_name": "ollama", + "overlay": {}, + } + cfg = _const_lookup_config( + **{"services.ollama.enabled": True, "services.ollama.shared": True} + ) + self.assertTrue( + _is_consumer(entry, "web-app-openwebui", cfg, _const_lookup_database()) + ) + + def test_services_flags_default_flags_require_enabled_and_shared(self): + entry = { + "role": "svc-db-openldap", + "entity_name": "openldap", + "provides": "ldap", + "overlay": {}, + } + cfg = _const_lookup_config(**{"services.ldap.enabled": True}) + self.assertFalse( + _is_consumer(entry, "web-app-x", cfg, _const_lookup_database()) + ) + + def test_unknown_kind_returns_false(self): + entry = {"role": "x", "overlay": {"consumer": {"kind": "future_thing"}}} + self.assertFalse( + _is_consumer( + entry, "web-app-x", _const_lookup_config(), _const_lookup_database() + ) + ) + + def test_web_facing_matches_web_app_and_web_svc(self): + entry = { + "role": "svc-prx-openresty", + "overlay": {"consumer": {"kind": "web_facing"}}, + } + for app in ("web-app-baserow", "web-svc-logout"): + self.assertTrue( + _is_consumer( + entry, app, _const_lookup_config(), _const_lookup_database() + ), + msg=app, + ) + + def test_web_facing_rejects_non_web_roles(self): + entry = { + "role": "svc-prx-openresty", + "overlay": {"consumer": {"kind": "web_facing"}}, + } + for app in ("svc-db-mariadb", "svc-ai-ollama", "sys-svc-x"): + self.assertFalse( + _is_consumer( + entry, app, _const_lookup_config(), _const_lookup_database() + ), + msg=app, + ) + + +class TestIsConsumerOnionSso(unittest.TestCase): + ENTRY: ClassVar[dict] = { + "role": "svc-net-tor", + "overlay": { + "consumer": { + "kind": "onion_sso", + "key": "sso", + "provider": "web-app-keycloak", + "provider_key": "tor", + } + }, + } + + @staticmethod + def _lookup(*, sso, provider_tor): + def _inner(app, path, default): + if app == "web-app-keycloak" and path == "services.tor.enabled": + return provider_tor + if path == "services.sso.enabled": + return sso + return default + + return _inner + + def _consumer(self, *, sso, provider_tor, entry=None): + return _is_consumer( + entry or self.ENTRY, + "web-app-nextcloud", + self._lookup(sso=sso, provider_tor=provider_tor), + _const_lookup_database(), + ) + + def test_attaches_only_when_sso_consumer_meets_onion_provider(self): + cases = [ + (True, True, True), + (True, False, False), + (False, True, False), + (False, False, False), + ] + for sso, provider_tor, expected in cases: + with self.subTest(sso=sso, provider_tor=provider_tor): + self.assertIs( + self._consumer(sso=sso, provider_tor=provider_tor), expected + ) + + def test_provider_is_mandatory(self): + entry = {"role": "svc-net-tor", "overlay": {"consumer": {"kind": "onion_sso"}}} + self.assertFalse(self._consumer(sso=True, provider_tor=True, entry=entry)) + + def test_provider_key_defaults_to_tor(self): + entry = { + "role": "svc-net-tor", + "overlay": { + "consumer": {"kind": "onion_sso", "provider": "web-app-keycloak"} + }, + } + self.assertTrue(self._consumer(sso=True, provider_tor=True, entry=entry)) + self.assertFalse(self._consumer(sso=True, provider_tor=False, entry=entry)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/networks/test_render_shared_net.py b/tests/unit/python/utils/networks/test_render_shared_net.py new file mode 100644 index 0000000000..a9e9b8dcec --- /dev/null +++ b/tests/unit/python/utils/networks/test_render_shared_net.py @@ -0,0 +1,200 @@ +from __future__ import annotations + +import unittest + +from utils.networks.render import ( + _own_shared_net_provider, + _suppress_default, + render_compose_networks, + render_container_networks, + shared_network_compose_key, +) + +from ._render_helpers import ( + _const_lookup_config, + _const_lookup_database, + _database, + _entity_name, +) + +_PROVIDER_REGISTRY = { + "seaweedfs": { + "role": "web-app-seaweedfs", + "entity_name": "seaweedfs", + "overlay": {"modes": ["compose", "swarm"], "topology": "shared_net"}, + }, +} + + +class TestSuppressDefault(unittest.TestCase): + def test_svc_db_prefix_suppresses(self): + self.assertTrue(_suppress_default("svc-db-mariadb", _database(False))) + self.assertTrue(_suppress_default("svc-db-postgres", _database(False))) + + def test_svc_ai_prefix_suppresses(self): + self.assertTrue(_suppress_default("svc-ai-ollama", _database(False))) + + def test_svc_ai_with_its_own_database_keeps_the_default_network(self): + self.assertFalse(_suppress_default("svc-ai-litellm", _database(True))) + + def test_other_prefixes_do_not_suppress(self): + self.assertFalse(_suppress_default("svc-prx-openresty", _database(False))) + self.assertFalse(_suppress_default("web-app-baserow", _database(False))) + self.assertFalse(_suppress_default("web-svc-collabora", _database(False))) + + +class TestOwnSharedNetProvider(unittest.TestCase): + """A multi-service objstore provider (seaweedfs/minio) renders its own + ``<entity>`` net as external + a bare auto-IPAM project default (so the + role subnet, owned by the external net, is never re-requested), and its + sidecar services attach without the provider alias. Locks the + objstore-net-fix contract so a render edit cannot silently regress it.""" + + def test_helper_true_only_for_own_shared_net_provider(self): + own = [ + {"role": "web-app-seaweedfs", "topology": "shared_net", "is_provider": True} + ] + consumer = [ + { + "role": "web-app-seaweedfs", + "topology": "shared_net", + "is_provider": False, + } + ] + self.assertTrue(_own_shared_net_provider(own, "seaweedfs", _entity_name)) + self.assertFalse(_own_shared_net_provider(consumer, "baserow", _entity_name)) + self.assertFalse(_own_shared_net_provider([], "seaweedfs", _entity_name)) + + def test_compose_default_drops_name_and_subnet(self): + rendered = render_compose_networks( + application_id="web-app-seaweedfs", + deployment_mode="compose", + registry=_PROVIDER_REGISTRY, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config( + **{"networks.local.subnet": "192.168.206.0/24"} + ), + lookup_database=_const_lookup_database(), + ) + self.assertIn(" seaweedfs:\n external: true", rendered) + self.assertIn(" default:\n driver: bridge", rendered) + self.assertNotIn("192.168.206", rendered) + self.assertNotIn("name: seaweedfs", rendered) + + def test_swarm_default_is_nameless_overlay(self): + rendered = render_compose_networks( + application_id="web-app-seaweedfs", + deployment_mode="swarm", + registry=_PROVIDER_REGISTRY, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + ) + self.assertIn(" seaweedfs:\n external: true", rendered) + self.assertIn(" default:\n driver: overlay", rendered) + self.assertNotIn("name: seaweedfs", rendered) + + def test_main_publishes_alias_sidecar_does_not(self): + kwargs = { + "application_id": "web-app-seaweedfs", + "deployment_mode": "compose", + "registry": _PROVIDER_REGISTRY, + "get_entity_name": _entity_name, + "lookup_config": _const_lookup_config(), + "lookup_database": _const_lookup_database(), + } + main = render_container_networks(**kwargs) + sidecar = render_container_networks(provider_self_alias=False, **kwargs) + self.assertIn("seaweedfs:\n aliases:\n - seaweedfs", main) + self.assertIn("seaweedfs:\n {}", sidecar) + self.assertNotIn("- seaweedfs", sidecar) + + +class TestSharedNetworkComposeKey(unittest.TestCase): + """The key under which the pre-created ``<entity>`` network appears in the + rendered file. Callers stamp it into ``com.docker.compose.network``; docker + compose resolves a project's networks against that label, so a key that does + not match the rendered file makes compose adopt the wrong network and skip + creating the right one.""" + + def _key(self, application_id, registry, deployment_mode="compose"): + return shared_network_compose_key( + application_id=application_id, + deployment_mode=deployment_mode, + registry=registry, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + ) + + def test_own_shared_net_provider_keys_on_its_entity(self): + for mode in ("compose", "swarm"): + with self.subTest(mode=mode): + self.assertEqual( + self._key("web-app-seaweedfs", _PROVIDER_REGISTRY, mode), + "seaweedfs", + ) + + def test_plain_app_keys_on_default(self): + for mode in ("compose", "swarm"): + with self.subTest(mode=mode): + self.assertEqual(self._key("web-app-baserow", {}, mode), "default") + + def test_consumer_of_a_foreign_provider_keys_on_default(self): + registry = { + "ldap": { + "role": "svc-db-openldap", + "entity_name": "openldap", + "provides": "ldap", + "overlay": {"modes": ["compose"], "topology": "shared_net"}, + }, + } + self.assertEqual(self._key("web-app-baserow", registry), "default") + + def test_node_local_forces_the_compose_answer(self): + self.assertEqual( + shared_network_compose_key( + application_id="web-app-seaweedfs", + deployment_mode="swarm", + registry=_PROVIDER_REGISTRY, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config(), + lookup_database=_const_lookup_database(), + node_local=True, + ), + "seaweedfs", + ) + + def test_key_matches_the_key_the_renderer_emits(self): + """The contract that makes this a single source: whatever key the + function reports must be the key the rendered networks block actually + uses for the entity network.""" + cases = ( + ("web-app-seaweedfs", _PROVIDER_REGISTRY), + ("web-app-baserow", {}), + ) + for application_id, registry in cases: + for mode in ("compose", "swarm"): + with self.subTest(application_id=application_id, mode=mode): + key = self._key(application_id, registry, mode) + rendered = render_compose_networks( + application_id=application_id, + deployment_mode=mode, + registry=registry, + get_entity_name=_entity_name, + lookup_config=_const_lookup_config( + **{"networks.local.subnet": "192.168.206.0/24"} + ), + lookup_database=_const_lookup_database(), + ) + self.assertIn(f" {key}:", rendered) + entity = _entity_name(application_id) + if key == "default": + self.assertIn(f" name: {entity}", rendered) + else: + self.assertEqual(key, entity) + self.assertNotIn(f" name: {entity}", rendered) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/roles/applications/services/test_registry.py b/tests/unit/python/utils/roles/applications/services/test_registry.py index ab7de60a13..f27085ea7c 100644 --- a/tests/unit/python/utils/roles/applications/services/test_registry.py +++ b/tests/unit/python/utils/roles/applications/services/test_registry.py @@ -4,12 +4,15 @@ import tempfile import unittest from pathlib import Path +from utils.cache.files import PROJECT_ROOT, read_text from utils.cache.yaml import dump_yaml_str from utils.roles.applications.services.registry import ( + GROUP_GATED_CONSTANTS, ServiceRegistryError, build_service_registry_from_applications, detect_service_bucket, detect_service_channel, + is_explicit_truth, ordered_primary_service_entries, resolve_service_dependency_roles_from_config, ) @@ -335,5 +338,40 @@ class TestServiceRegistryOrdering(unittest.TestCase): ordered_primary_service_entries(registry, roles_dir) +class TestExplicitTruth(unittest.TestCase): + """A flag may resolve a dependency through a group-gated constant. + + The substring rule reads the role id out of the flag itself, so a SPOT + constant hides it. Roles referencing one keep their provider only while + the constant is registered. + """ + + def test_a_literal_true_resolves(self): + self.assertTrue(is_explicit_truth(True)) + + def test_the_in_group_names_form_resolves(self): + self.assertTrue(is_explicit_truth("{{ 'web-app-keycloak' in group_names }}")) + + def test_every_registered_constant_resolves(self): + for constant in GROUP_GATED_CONSTANTS: + with self.subTest(constant=constant): + self.assertTrue(is_explicit_truth("{{ " + constant + " }}")) + + def test_an_unregistered_jinja_expression_does_not_resolve(self): + self.assertFalse( + is_explicit_truth("{{ lookup('config', 'web-app-gitea', 'mcp.enabled') }}") + ) + + def test_a_literal_false_does_not_resolve(self): + self.assertFalse(is_explicit_truth(False)) + + def test_every_registered_constant_is_defined_in_group_vars(self): + group_vars = PROJECT_ROOT / "group_vars" / "all" + defined = "".join(read_text(str(path)) for path in group_vars.glob("*.yml")) + for constant in GROUP_GATED_CONSTANTS: + with self.subTest(constant=constant): + self.assertIn(f"{constant}:", defined) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/roles/applications/services/test_sso.py b/tests/unit/python/utils/roles/applications/services/test_sso.py index b8a61742ca..6f83f0b25f 100644 --- a/tests/unit/python/utils/roles/applications/services/test_sso.py +++ b/tests/unit/python/utils/roles/applications/services/test_sso.py @@ -2,11 +2,16 @@ from __future__ import annotations import unittest +from jinja2.filters import do_urlencode + from utils.roles.applications.services.sso import ( get_sso_config, is_potentially_enabled, + logout_url, ) +KEYCLOAK_LOGOUT = "https://auth.example.org/realms/r/protocol/openid-connect/logout" + def _apps( *, @@ -203,5 +208,22 @@ class IsPotentiallyEnabledTests(unittest.TestCase): self.assertTrue(is_potentially_enabled("")) +class TestLogoutUrl(unittest.TestCase): + def test_an_app_without_the_proxy_logs_out_at_the_provider(self): + self.assertEqual(logout_url(KEYCLOAK_LOGOUT, False), KEYCLOAK_LOGOUT) + + def test_a_proxy_gated_app_signs_out_of_oauth2_proxy_first(self): + self.assertEqual( + logout_url(KEYCLOAK_LOGOUT, True), + "/oauth2/sign_out?rd=https%3A//auth.example.org/realms/r/protocol/openid-connect/logout", + ) + + def test_the_rd_encoding_matches_the_jinja_urlencode_filter(self): + self.assertEqual( + logout_url(KEYCLOAK_LOGOUT, True), + f"/oauth2/sign_out?rd={do_urlencode(KEYCLOAK_LOGOUT)}", + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/roles/applications/test_reachable_roles.py b/tests/unit/python/utils/roles/applications/test_reachable_roles.py new file mode 100644 index 0000000000..3ddb1f0dcd --- /dev/null +++ b/tests/unit/python/utils/roles/applications/test_reachable_roles.py @@ -0,0 +1,72 @@ +"""Unit tests for the whitelist-scoped dependency closure.""" + +from __future__ import annotations + +import unittest + +from utils.roles.applications import in_group_deps as deps_mod + +SERVICE_REGISTRY = { + "mariadb": {"role": "svc-db-mariadb"}, + "ldap": {"role": "svc-db-openldap"}, + "postgres": {"role": "svc-db-postgres"}, +} + + +def _uses(service_key): + return {"services": {service_key: {"enabled": True, "shared": True}}} + + +APPS = { + "web-app-alpha": _uses("mariadb"), + "web-app-beta": _uses("postgres"), + "web-app-solo": {}, + "svc-db-mariadb": _uses("ldap"), + "svc-db-openldap": {}, + "svc-db-postgres": {}, +} + + +def _resolver(mapping): + return lambda role, roles_dir: (mapping or {}).get(role, []) + + +class TestReachableRoles(unittest.TestCase): + def _closure(self, seeds, meta_deps=None): + return deps_mod.reachable_roles( + APPS, + seeds, + project_root="/unused", + roles_dir="/unused", + service_registry=SERVICE_REGISTRY, + meta_deps_resolver=_resolver(meta_deps), + ) + + def test_no_seed_reaches_nothing(self): + self.assertEqual(self._closure([]), set()) + + def test_an_app_without_dependencies_reaches_only_itself(self): + self.assertEqual(self._closure(["web-app-solo"]), {"web-app-solo"}) + + def test_service_edges_are_followed_transitively(self): + self.assertEqual( + self._closure(["web-app-alpha"]), + {"web-app-alpha", "svc-db-mariadb", "svc-db-openldap"}, + ) + + def test_an_unrelated_app_stays_outside_the_closure(self): + self.assertNotIn("web-app-beta", self._closure(["web-app-alpha"])) + self.assertNotIn("svc-db-postgres", self._closure(["web-app-alpha"])) + + def test_meta_dependencies_are_followed(self): + closure = self._closure( + ["web-app-solo"], meta_deps={"web-app-solo": ["svc-db-postgres"]} + ) + self.assertEqual(closure, {"web-app-solo", "svc-db-postgres"}) + + def test_seeding_every_app_reaches_every_app(self): + self.assertEqual(self._closure(sorted(APPS)), set(APPS)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/roles/applications/test_topics.py b/tests/unit/python/utils/roles/applications/test_topics.py new file mode 100644 index 0000000000..22a729ec8b --- /dev/null +++ b/tests/unit/python/utils/roles/applications/test_topics.py @@ -0,0 +1,107 @@ +"""Unit tests for ``utils/roles/applications/topics.py``. + +The three override shapes have to stay distinguishable: ``null`` empties, +``{}`` is a no-op, and a mapping changes the keys it names and nothing else. +""" + +from __future__ import annotations + +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory + +from utils.roles.applications.topics import ( + CONFIG_TOPICS, + apply_topic, + overridden_providers, +) + + +class TestApplyTopic(unittest.TestCase): + def test_null_empties_the_topic(self): + self.assertEqual({}, apply_topic({"a": {"enabled": True}}, None)) + + def test_an_empty_mapping_changes_nothing(self): + base = {"a": {"enabled": True}} + self.assertEqual(base, apply_topic(base, {})) + + def test_a_mapping_merges_the_named_keys_only(self): + base = {"a": {"enabled": True}, "b": {"enabled": True}} + self.assertEqual( + {"a": {"enabled": False}, "b": {"enabled": True}}, + apply_topic(base, {"a": {"enabled": False}}), + ) + + def test_a_missing_base_still_takes_the_override(self): + self.assertEqual({"a": 1}, apply_topic(None, {"a": 1})) + + def test_the_vocabulary_covers_the_topics_a_variant_can_name(self): + self.assertIn("services", CONFIG_TOPICS) + self.assertIn("addons", CONFIG_TOPICS) + self.assertNotIn("enabled", CONFIG_TOPICS) + + +class TestOverriddenProviders(unittest.TestCase): + """The scan runs against a synthetic tree. + + No variant in ``roles/`` dictates a provider's config today, so scanning + the real one would assert nothing and stay green however the function + breaks. + """ + + def setUp(self) -> None: + self._tmp = TemporaryDirectory() + self.roles = Path(self._tmp.name) + self.addCleanup(self._tmp.cleanup) + + def _role(self, name: str, services: str = "", variants: str = "") -> None: + """Write the minimum a role needs to reach the service registry. + + Args: + name: role directory name, also its ``application_id``. + services: body of ``meta/services.yml``. + variants: body of ``meta/variants.yml``, omitted when empty. + """ + meta = self.roles / name / "meta" + meta.mkdir(parents=True) + variables = self.roles / name / "vars" + variables.mkdir(parents=True) + (variables / "main.yml").write_text( + f"application_id: {name}\n", encoding="utf-8" + ) + (meta / "services.yml").write_text(services or "{}\n", encoding="utf-8") + if variants: + (meta / "variants.yml").write_text(variants, encoding="utf-8") + + def test_it_records_the_provider_a_variant_dictates(self) -> None: + self._role("svc-provider", "provider:\n shared: true\n") + self._role( + "web-app-consumer", + "provider:\n enabled: true\n", + "- services:\n provider:\n enabled: true\n services: null\n", + ) + self.assertEqual( + {("web-app-consumer", 0): {"svc-provider"}}, + overridden_providers(self.roles), + ) + + def test_a_plain_flag_is_not_an_override(self) -> None: + self._role("svc-provider", "provider:\n shared: true\n") + self._role( + "web-app-consumer", + "provider:\n enabled: true\n", + "- services:\n provider:\n enabled: true\n", + ) + self.assertEqual({}, overridden_providers(self.roles)) + + def test_a_role_never_records_itself(self) -> None: + self._role( + "svc-provider", + "provider:\n shared: true\n", + "- services:\n provider:\n services: null\n", + ) + self.assertEqual({}, overridden_providers(self.roles)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/roles/test_guide.py b/tests/unit/python/utils/roles/test_guide.py new file mode 100644 index 0000000000..49c3bcf1de --- /dev/null +++ b/tests/unit/python/utils/roles/test_guide.py @@ -0,0 +1,77 @@ +import unittest +from typing import ClassVar +from unittest import mock + +from utils.cache.applications import get_variants +from utils.roles.guide import guide_deployable, guide_variant, smallest_variant + + +def _variant(*enabled: str) -> dict: + return {"services": {name: {"enabled": True} for name in enabled}} + + +class TestSmallestVariant(unittest.TestCase): + def test_the_variant_with_the_fewest_enabled_services_wins(self) -> None: + variants = [_variant("a", "b", "c"), _variant("a"), _variant("a", "b")] + self.assertEqual(smallest_variant(variants), "1") + + def test_a_tie_goes_to_the_lower_index(self) -> None: + self.assertEqual(smallest_variant([_variant("a"), _variant("b")]), "0") + + def test_a_disabled_service_does_not_count(self) -> None: + variants = [ + {"services": {"a": {"enabled": True}, "b": {"enabled": False}}}, + _variant("a", "b"), + ] + self.assertEqual(smallest_variant(variants), "0") + + def test_a_variant_without_services_counts_as_empty(self) -> None: + self.assertEqual(smallest_variant([_variant("a"), {}]), "1") + + def test_a_variant_the_sweep_cuts_hands_the_replay_on(self) -> None: + """A row no sweep deploys would drop the role from the test entirely.""" + variants = [_variant("a"), _variant("a", "b"), _variant("a", "b", "c")] + self.assertEqual(smallest_variant(variants, {"1", "2"}), "1") + + def test_a_role_with_no_deployed_variant_carries_nothing(self) -> None: + self.assertEqual(smallest_variant([_variant("a")], set()), "") + + +class TestGuideVariant(unittest.TestCase): + _VARIANTS: ClassVar[dict] = {"web-app-x": [_variant("a", "b"), _variant("a")]} + _ALL: ClassVar[set] = {"0", "1"} + + def test_the_smallest_deployed_variant_carries_the_replay(self) -> None: + with mock.patch("utils.roles.guide.guide_deployable", return_value="compose"): + self.assertEqual( + guide_variant("web-app-x", self._VARIANTS, self._ALL), ("1", "compose") + ) + + def test_a_role_the_guide_cannot_deploy_carries_nothing(self) -> None: + with mock.patch("utils.roles.guide.guide_deployable", return_value=""): + self.assertEqual( + guide_variant("web-app-x", self._VARIANTS, self._ALL), ("", "") + ) + + def test_without_variant_data_no_row_is_the_smallest(self) -> None: + self.assertEqual(guide_variant("web-app-x", None, self._ALL), ("", "")) + self.assertEqual(guide_variant("web-app-x", {}, self._ALL), ("", "")) + + +class TestGuideDeployable(unittest.TestCase): + """Against the real roles, which is what the marker is computed over.""" + + def test_a_role_without_a_readme_production_block_is_excluded(self) -> None: + self.assertEqual(guide_deployable("does-not-exist"), "") + + def test_the_mode_follows_whether_the_role_ships_a_stack(self) -> None: + self.assertEqual(guide_deployable("web-app-nextcloud"), "compose") + + def test_the_replay_reaches_more_roles_than_the_single_random_pick(self) -> None: + """The job it replaced tested exactly one role per run.""" + marked = [app for app in get_variants() if guide_deployable(app)] + self.assertGreater(len(marked), 100) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/roles/test_rbac_scoped.py b/tests/unit/python/utils/roles/test_rbac_scoped.py new file mode 100644 index 0000000000..58b7320fba --- /dev/null +++ b/tests/unit/python/utils/roles/test_rbac_scoped.py @@ -0,0 +1,141 @@ +"""The application-scoped role boundary. + +``mcp`` grants reach whatever the deployment issued the provider's credentials +for, not the caller's own data, so holding it on one application must never +imply holding it on another. ``APPLICATION_SCOPED_ROLES`` is what keeps an +unscoped ``roles: [mcp]`` from becoming every deployed application at once, and +the Keycloak realm builder, the LDAP entry builder and the Open WebUI reconciler +all resolve membership through this one module. +""" + +from __future__ import annotations + +import unittest +from typing import ClassVar + +from utils.roles.rbac.scoped import ( + APPLICATION_SCOPED_ROLES, + granted_roles, + members_with_role, +) + + +class TestGrantedRoles(unittest.TestCase): + def test_a_scoped_grant_reaches_only_the_named_application(self) -> None: + user = {"application_roles": {"web-app-baserow": ["mcp"]}} + self.assertEqual({"mcp", "mcp-reader"}, granted_roles(user, "web-app-baserow")) + self.assertEqual(set(), granted_roles(user, "web-app-n8n")) + + def test_an_unscoped_scoped_role_grants_nothing_anywhere(self) -> None: + user = {"roles": ["mcp"]} + for application_id in ("web-app-baserow", "web-app-n8n"): + with self.subTest(application_id=application_id): + self.assertEqual(set(), granted_roles(user, application_id)) + + def test_an_unscoped_ordinary_role_reaches_every_application(self) -> None: + user = {"roles": ["administrator"]} + for application_id in ("web-app-baserow", "web-app-n8n"): + with self.subTest(application_id=application_id): + self.assertEqual({"administrator"}, granted_roles(user, application_id)) + + def test_scoped_and_unscoped_grants_combine_on_the_named_application(self) -> None: + user = { + "roles": ["administrator"], + "application_roles": {"web-app-baserow": ["mcp"]}, + } + self.assertEqual( + {"administrator", "mcp", "mcp-reader"}, + granted_roles(user, "web-app-baserow"), + ) + self.assertEqual({"administrator"}, granted_roles(user, "web-app-n8n")) + + def test_two_applications_carry_independent_scoped_grants(self) -> None: + user = { + "application_roles": { + "web-app-baserow": ["mcp"], + "web-app-n8n": ["administrator"], + } + } + self.assertEqual({"mcp", "mcp-reader"}, granted_roles(user, "web-app-baserow")) + self.assertEqual({"administrator"}, granted_roles(user, "web-app-n8n")) + + def test_a_user_without_any_declaration_holds_nothing(self) -> None: + self.assertEqual(set(), granted_roles({}, "web-app-baserow")) + + def test_null_declarations_are_treated_as_empty(self) -> None: + user = {"roles": None, "application_roles": None} + self.assertEqual(set(), granted_roles(user, "web-app-baserow")) + + def test_a_legacy_mcp_grant_confers_reading_not_writing(self) -> None: + user = {"application_roles": {"web-app-baserow": ["mcp"]}} + granted = granted_roles(user, "web-app-baserow") + self.assertIn("mcp-reader", granted) + self.assertNotIn("mcp-writer", granted) + + def test_an_explicit_writer_grant_is_kept(self) -> None: + user = {"application_roles": {"web-app-baserow": ["mcp-writer"]}} + self.assertEqual({"mcp-writer"}, granted_roles(user, "web-app-baserow")) + + def test_mcp_is_application_scoped(self) -> None: + self.assertIn("mcp", APPLICATION_SCOPED_ROLES) + + +class TestMembersWithRole(unittest.TestCase): + USERS: ClassVar[dict] = { + "biber": {"application_roles": {"web-app-baserow": ["mcp"]}}, + "otter": {"roles": ["mcp"]}, + "admin": {"roles": ["administrator"]}, + } + + def test_only_the_scoped_holder_is_a_member(self) -> None: + self.assertEqual( + ["biber"], members_with_role(self.USERS, "web-app-baserow", "mcp-reader") + ) + + def test_the_unscoped_holder_is_a_member_of_no_application(self) -> None: + self.assertEqual([], members_with_role(self.USERS, "web-app-n8n", "mcp")) + + def test_the_declared_username_wins_over_the_key(self) -> None: + users = { + "biber": { + "username": "biber@infinito.test", + "application_roles": {"web-app-baserow": ["mcp"]}, + } + } + self.assertEqual( + ["biber@infinito.test"], + members_with_role(users, "web-app-baserow", "mcp-reader"), + ) + + def test_members_are_sorted_so_the_grant_diff_is_stable(self) -> None: + users = { + name: {"application_roles": {"web-app-baserow": ["mcp"]}} + for name in ("otter", "biber", "adler") + } + self.assertEqual( + ["adler", "biber", "otter"], + members_with_role(users, "web-app-baserow", "mcp-reader"), + ) + + def test_no_users_yields_no_members(self) -> None: + self.assertEqual([], members_with_role(None, "web-app-baserow", "mcp")) + + def test_a_null_user_entry_does_not_abort_the_scan(self) -> None: + users = {"ghost": None, "biber": {"application_roles": {"app": ["mcp"]}}} + self.assertEqual(["biber"], members_with_role(users, "app", "mcp-reader")) + + +class TestMcpRoleVocabulary(unittest.TestCase): + def test_both_mcp_roles_are_application_scoped(self) -> None: + from utils.roles.rbac.scoped import APPLICATION_SCOPED_ROLES, MCP_ROLES + + for role in MCP_ROLES: + self.assertIn(role, APPLICATION_SCOPED_ROLES) + + def test_a_writer_grant_does_not_confer_the_reader_name(self) -> None: + user = {"application_roles": {"app": ["mcp-writer"]}} + self.assertEqual({"mcp-writer"}, granted_roles(user, "app")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/test_api.py b/tests/unit/python/utils/test_api.py new file mode 100644 index 0000000000..1a48d495b9 --- /dev/null +++ b/tests/unit/python/utils/test_api.py @@ -0,0 +1,51 @@ +import unittest + +from utils.api import declared_api, provider_enabled, resolve_api + + +class TestResolveApi(unittest.TestCase): + def test_a_partial_override_keeps_the_declared_providers(self) -> None: + declared = declared_api() + self.assertIn("github", declared) + + resolved = resolve_api({"API": {"openai": {"api_key": "sk-test"}}}) + + self.assertEqual(set(resolved), set(declared)) + self.assertEqual(resolved["openai"]["api_key"], "sk-test") + self.assertEqual(resolved["github"]["client_id"], "") + + def test_an_override_wins_per_key(self) -> None: + resolved = resolve_api({"API": {"github": {"client_id": "ID42"}}}) + + self.assertEqual(resolved["github"]["client_id"], "ID42") + self.assertEqual(resolved["github"]["client_secret"], "") + + def test_a_missing_api_falls_back_to_the_declaration(self) -> None: + self.assertEqual(resolve_api({}), declared_api()) + + def test_a_non_mapping_api_is_an_error(self) -> None: + with self.assertRaises(TypeError): + resolve_api({"API": "nope"}) + + +class TestProviderEnabled(unittest.TestCase): + def test_every_credential_must_carry_a_value(self) -> None: + api = {"github": {"client_id": "ID42", "client_secret": "SEC42"}} + + self.assertTrue(provider_enabled(api, "github")) + + def test_one_empty_credential_disables_the_provider(self) -> None: + api = {"github": {"client_id": "ID42", "client_secret": " "}} + + self.assertFalse(provider_enabled(api, "github")) + + def test_a_provider_without_credentials_is_disabled(self) -> None: + self.assertFalse(provider_enabled({"github": {}}, "github")) + + def test_an_undeclared_provider_is_an_error(self) -> None: + with self.assertRaises(KeyError): + provider_enabled({}, "github") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/tests/swarm/test_extend_inventory.py b/tests/unit/python/utils/tests/swarm/test_extend_inventory.py index a6ef01bc33..f2b9de2c34 100644 --- a/tests/unit/python/utils/tests/swarm/test_extend_inventory.py +++ b/tests/unit/python/utils/tests/swarm/test_extend_inventory.py @@ -57,5 +57,23 @@ class TestBackupLegGating(unittest.TestCase): self.assertNotIn("svc-bkp-volume-2-local", children) +class TestSandboxWorkerLabelling(unittest.TestCase): + def _workers(self, kata_enabled: object) -> tuple[str, ...]: + apps = {"an-app": {"services": {"kata": {"enabled": kata_enabled}}}} + with mock.patch.object(ei, "applications_for_round", return_value=apps): + return ei._sandbox_workers("an-app") + + def test_a_sandboxed_app_labels_every_worker(self): + self.assertEqual(self._workers(True), ei._WORKERS) + + def test_a_plain_app_leaves_one_worker_unlabelled(self): + self.assertEqual(self._workers(None), ei._WORKERS[-1:]) + self.assertEqual(self._workers(False), ei._WORKERS[-1:]) + + def test_an_app_without_a_kata_service_leaves_one_worker(self): + with mock.patch.object(ei, "applications_for_round", return_value={}): + self.assertEqual(ei._sandbox_workers("absent"), ei._WORKERS[-1:]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py b/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py new file mode 100644 index 0000000000..4f27992dcb --- /dev/null +++ b/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py @@ -0,0 +1,42 @@ +import contextlib +import io +import unittest +from unittest import mock + +from utils.tests.swarm import matrix + + +class TestRunReporting(unittest.TestCase): + """Every matrix phase must state what it cost. + + A phase that only announces its start leaves the reader subtracting + timestamps by hand, and a phase that produces no output of its own becomes + invisible: the credential rotation spent 17 minutes of a budget-killed job + with nothing but the 30-second sampler in between. + """ + + def _run_capturing(self, rc: int) -> tuple[int, str]: + buffer = io.StringIO() + with ( + mock.patch.object(matrix, "_run_watched", return_value=rc) as watched, + contextlib.redirect_stdout(buffer), + ): + returned = matrix._run(["true"], env={"A": "b"}, label="demo phase") + watched.assert_called_once_with(["true"], env={"A": "b"}) + return returned, buffer.getvalue() + + def test_the_exit_code_passes_through(self) -> None: + returned, _ = self._run_capturing(7) + self.assertEqual(returned, 7) + + def test_the_phase_announces_its_start(self) -> None: + _, output = self._run_capturing(0) + self.assertIn("=== swarm-matrix: demo phase ===", output) + + def test_the_phase_reports_its_duration_and_outcome(self) -> None: + _, output = self._run_capturing(124) + self.assertRegex(output, r"demo phase took \d+s \(rc=124\)") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/update/test_base_pin_families.py b/tests/unit/python/utils/update/test_base_pin_families.py new file mode 100644 index 0000000000..564fcab71a --- /dev/null +++ b/tests/unit/python/utils/update/test_base_pin_families.py @@ -0,0 +1,143 @@ +"""Immutable tags the updater could not order before. + +Two shapes reach the repository that name a fixed release yet failed the semver +gate, so the bump job skipped them and nothing could tell whether a newer one +existed: a vendor patch counter such as ``2.4.0p32`` and a five-component +version such as ``26.04.2.1.1``. +""" + +from __future__ import annotations + +import unittest + +from utils.update.base import ( + is_semver, + latest_semver, + version_depth, + version_flavor, + version_key, +) + + +def _latest(current: str, tags: list[str]) -> str | None: + return latest_semver(tags, version_depth(current), version_flavor(current)) + + +class TestPatchCounterTags(unittest.TestCase): + def test_a_patch_counter_is_orderable(self): + self.assertTrue(is_semver("2.4.0p32")) + + def test_it_bumps_within_its_own_counter(self): + self.assertEqual(_latest("2.4.0p32", ["2.4.0p32", "2.4.0p33"]), "2.4.0p33") + + def test_the_counter_orders_numerically_not_lexically(self): + self.assertEqual(_latest("2.4.0p9", ["2.4.0p9", "2.4.0p10"]), "2.4.0p10") + + def test_a_later_release_wins_over_a_later_counter(self): + self.assertEqual(_latest("2.4.0p32", ["2.4.0p99", "2.4.1p1"]), "2.4.1p1") + + def test_it_never_crosses_into_a_four_component_version(self): + self.assertEqual( + _latest("2.4.0p32", ["2.4.0p32", "2.4.0.99"]), + "2.4.0p32", + "2.4.0.99 is a different tag family and bumping into it would " + "silently change what the role deploys", + ) + + def test_the_counter_letter_keeps_families_apart(self): + self.assertEqual(version_flavor("2.4.0p32"), "p") + self.assertEqual(version_flavor("2.4.0.32"), "") + self.assertNotEqual(version_depth("2.4.0p32"), version_depth("2.4.0.32")) + + def test_a_plain_release_does_not_bump_into_a_counter(self): + self.assertEqual(_latest("2.4.0", ["2.4.0", "2.4.0p1"]), "2.4.0") + + +class TestFiveComponentTags(unittest.TestCase): + def test_five_components_are_orderable(self): + self.assertTrue(is_semver("26.04.2.1.1")) + self.assertEqual(version_depth("26.04.2.1.1"), 5) + + def test_it_bumps_within_its_own_depth(self): + self.assertEqual( + _latest("26.04.2.1.1", ["26.04.2.1.1", "26.04.2.1.2"]), "26.04.2.1.2" + ) + + def test_it_never_crosses_into_a_shorter_version(self): + self.assertEqual( + _latest("26.04.2.1.1", ["26.04.2.1.1", "27.0.0.0"]), "26.04.2.1.1" + ) + + +class TestNothingElseChanged(unittest.TestCase): + """The shapes the updater already handled must keep their family key.""" + + def test_known_shapes_keep_their_classification(self): + cases = { + "1.2.3": (True, 3, "", (1, 2, 3, 0)), + "v1.12.27": (True, 3, "", (1, 12, 27, 0)), + "16": (True, 1, "", (16, 0, 0, 0)), + "5.4.5-php8.3-apache": (True, 3, "-php8.3-apache", (5, 4, 5, 0)), + } + + for tag, (semver, depth, flavor, key) in cases.items(): + self.assertEqual(is_semver(tag), semver, tag) + self.assertEqual(version_depth(tag), depth, tag) + self.assertEqual(version_flavor(tag), flavor, tag) + self.assertEqual(version_key(tag), key, tag) + + def test_moving_names_are_still_refused(self): + for tag in ("latest", "stable", "lts", "alpine", "main"): + self.assertFalse(is_semver(tag), tag) + + def test_a_flavored_tag_still_refuses_a_different_runtime(self): + self.assertEqual( + _latest("5.4.5-php8.3-apache", ["5.4.6-php8.4-apache", "5.4.6"]), + None, + ) + + +class TestChannelPrefixedTags(unittest.TestCase): + """A release line written before the number is a family, not a version.""" + + def test_a_channel_prefixed_tag_is_orderable(self): + self.assertTrue(is_semver("main-v1.77.7-stable")) + self.assertEqual(version_depth("main-v1.77.7-stable"), 3) + self.assertEqual(version_key("main-v1.77.7-stable"), (1, 77, 7, 0)) + + def test_it_bumps_inside_its_own_channel(self): + tags = ["main-v1.77.7-stable", "main-v1.83.14-stable"] + self.assertEqual(_latest("main-v1.77.7-stable", tags), "main-v1.83.14-stable") + + def test_it_never_crosses_into_a_sibling_channel(self): + tags = ["main-v1.83.14-nightly", "main-v1.83.14-stable"] + self.assertEqual(_latest("main-v1.77.7-stable", tags), "main-v1.83.14-stable") + self.assertEqual(_latest("main-v1.77.7-nightly", tags), "main-v1.83.14-nightly") + + def test_a_bare_number_is_a_different_family_than_a_channelled_one(self): + self.assertNotEqual(version_flavor("stable-9646"), version_flavor("9646")) + self.assertEqual( + _latest("stable-9646", ["stable-9646", "9999"]), + "stable-9646", + "a bare build number leaves the stable channel and would change " + "what the role deploys", + ) + + def test_it_bumps_inside_the_stable_channel(self): + self.assertEqual( + _latest("stable-9646", ["stable-9646", "stable-9999"]), "stable-9999" + ) + + def test_a_channel_without_a_number_stays_refused(self): + for tag in ("act-latest", "bookworm-slim", "main-latest", "buildx-stable-1"): + self.assertFalse(is_semver(tag), tag) + + def test_a_date_stamped_tag_orders_as_one_number(self): + self.assertEqual(version_depth("20260917"), 1) + self.assertEqual( + _latest("20260702", ["20260702", "20260706", "20260917"]), "20260917" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/update/test_collection_source.py b/tests/unit/python/utils/update/test_collection_source.py new file mode 100644 index 0000000000..fa0075d497 --- /dev/null +++ b/tests/unit/python/utils/update/test_collection_source.py @@ -0,0 +1,114 @@ +import json +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory + +from utils.update.collection_source import ( + RATIO, + WINDOW, + append_sample, + decide, + load_history, +) + + +def _samples(galaxy, git, count=WINDOW): + return [{"galaxy": galaxy, "git": git} for _ in range(count)] + + +class TestAppendSample(unittest.TestCase): + def test_the_window_never_grows_past_its_size(self): + history = _samples(10.0, 10.0, WINDOW) + + grown = append_sample(history, {"galaxy": 99.0, "git": 1.0}) + + self.assertEqual(len(grown), WINDOW) + self.assertEqual(grown[-1], {"galaxy": 99.0, "git": 1.0}) + + def test_the_oldest_sample_is_the_one_dropped(self): + history = [{"galaxy": float(i), "git": 1.0} for i in range(WINDOW)] + + grown = append_sample(history, {"galaxy": 99.0, "git": 1.0}) + + self.assertEqual(grown[0]["galaxy"], 1.0) + + +class TestDecide(unittest.TestCase): + def test_below_a_full_window_the_default_is_left_alone(self): + history = _samples(300.0, 10.0, WINDOW - 1) + + verdict = decide(history, "galaxy") + + self.assertFalse(verdict.changed) + self.assertEqual(verdict.samples, WINDOW - 1) + + def test_exactly_the_ratio_swaps_the_preferred_source(self): + history = _samples(30.0, 10.0) + + verdict = decide(history, "galaxy") + + self.assertTrue(verdict.changed) + self.assertEqual(verdict.proposed, "git") + + def test_just_under_the_ratio_keeps_the_preferred_source(self): + history = _samples(10.0 * RATIO - 0.1, 10.0) + + self.assertFalse(decide(history, "galaxy").changed) + + def test_a_failed_install_ranks_worse_than_any_duration(self): + history = _samples(None, 10.0) + + verdict = decide(history, "galaxy") + + self.assertTrue(verdict.changed) + self.assertEqual(verdict.proposed, "git") + self.assertEqual(verdict.medians["galaxy"], float("inf")) + + def test_the_faster_source_is_never_swapped_away_from(self): + history = _samples(10.0, 300.0) + + self.assertFalse(decide(history, "galaxy").changed) + + def test_both_sources_failing_changes_nothing(self): + history = _samples(None, None) + + self.assertFalse(decide(history, "galaxy").changed) + + def test_a_single_outlier_does_not_move_the_median(self): + history = _samples(10.0, 10.0, WINDOW - 1) + history = append_sample(history, {"galaxy": 9000.0, "git": 10.0}) + + self.assertFalse(decide(history, "galaxy").changed) + + def test_the_verdict_is_taken_from_the_preferred_side(self): + history = _samples(10.0, 30.0) + + verdict = decide(history, "git") + + self.assertTrue(verdict.changed) + self.assertEqual(verdict.proposed, "galaxy") + + +class TestLoadHistory(unittest.TestCase): + def test_a_missing_file_reads_as_an_empty_history(self): + with TemporaryDirectory() as tmp: + self.assertEqual(load_history(Path(tmp) / "absent.json"), []) + + def test_a_corrupt_file_reads_as_an_empty_history(self): + with TemporaryDirectory() as tmp: + path = Path(tmp) / "history.json" + path.write_text("{not json", encoding="utf-8") + + self.assertEqual(load_history(path), []) + + def test_a_written_history_round_trips(self): + with TemporaryDirectory() as tmp: + path = Path(tmp) / "history.json" + history = _samples(1.0, 2.0, 3) + path.write_text(json.dumps(history), encoding="utf-8") + + self.assertEqual(load_history(path), history) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/update/test_docker_release_groups.py b/tests/unit/python/utils/update/test_docker_release_groups.py new file mode 100644 index 0000000000..72b6c22256 --- /dev/null +++ b/tests/unit/python/utils/update/test_docker_release_groups.py @@ -0,0 +1,112 @@ +"""Several images of one role at one version move together or not at all. + +Upstream does not push a release group atomically. Measured on Docker Hub: +``jitsi/prosody``, ``jitsi/jicofo`` and ``jitsi/jvb`` all publish +``stable-9457`` while ``jitsi/web`` does not, so a bump run landing in that +window would raise three components and leave the fourth behind. +""" + +from __future__ import annotations + +import unittest +from pathlib import Path + +from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.update.docker import ( + DockerImageVersionEntry, + DockerImageVersionUpdate, + _held_to_release_groups, +) + +JITSI = ("web", "prosody", "jicofo", "jvb") + + +def _entry(role: str, service: str, image: str, version: str): + return DockerImageVersionEntry( + role=role, + service=service, + image=image, + version=version, + config_path=Path(ROLE_FILE_META_SERVICES), + ) + + +def _jitsi_updates(version: str, latest: str): + return [ + DockerImageVersionUpdate( + entry=_entry("web-app-jitsi", name, f"jitsi/{name}", version), + latest=latest, + ) + for name in JITSI + ] + + +class TestReleaseGroupsMoveTogether(unittest.TestCase): + def test_a_partial_publish_holds_the_whole_group_back(self): + tags = { + "jitsi/web": ["stable-9400", "stable-9646"], + "jitsi/prosody": ["stable-9400", "stable-9646", "stable-9700"], + "jitsi/jicofo": ["stable-9400", "stable-9646", "stable-9700"], + "jitsi/jvb": ["stable-9400", "stable-9646", "stable-9700"], + } + updates = _jitsi_updates("stable-9400", "stable-9700") + + held = _held_to_release_groups(updates, tags) + + self.assertEqual({update.latest for update in held}, {"stable-9646"}) + self.assertEqual(len(held), 4) + + def test_a_group_all_publish_moves_to_the_head(self): + tags = {f"jitsi/{name}": ["stable-9400", "stable-9700"] for name in JITSI} + updates = _jitsi_updates("stable-9400", "stable-9700") + + held = _held_to_release_groups(updates, tags) + + self.assertEqual({update.latest for update in held}, {"stable-9700"}) + + def test_a_group_with_nothing_in_common_is_dropped(self): + tags = { + "jitsi/web": ["stable-9400", "stable-9701"], + "jitsi/prosody": ["stable-9400", "stable-9702"], + "jitsi/jicofo": ["stable-9400", "stable-9703"], + "jitsi/jvb": ["stable-9400", "stable-9704"], + } + updates = _jitsi_updates("stable-9400", "stable-9704") + + self.assertEqual(_held_to_release_groups(updates, tags), []) + + def test_a_lone_entry_is_untouched(self): + update = DockerImageVersionUpdate( + entry=_entry("web-app-fider", "fider", "getfider/fider", "v0.35.0"), + latest="v0.36.0", + ) + + held = _held_to_release_groups([update], {"getfider/fider": ["v0.36.0"]}) + + self.assertEqual(held, [update]) + + def test_two_roles_on_one_version_are_not_one_group(self): + tags = { + "jitsi/web": ["stable-9400", "stable-9700"], + "other/thing": ["stable-9400"], + } + updates = [ + DockerImageVersionUpdate( + entry=_entry("web-app-jitsi", "web", "jitsi/web", "stable-9400"), + latest="stable-9700", + ), + DockerImageVersionUpdate( + entry=_entry("web-app-other", "thing", "other/thing", "stable-9400"), + latest="stable-9400", + ), + ] + + held = _held_to_release_groups(updates, tags) + + self.assertEqual( + [update.latest for update in held], ["stable-9700", "stable-9400"] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/update/test_galaxy.py b/tests/unit/python/utils/update/test_galaxy.py new file mode 100644 index 0000000000..c05a02d292 --- /dev/null +++ b/tests/unit/python/utils/update/test_galaxy.py @@ -0,0 +1,127 @@ +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import patch + +from utils.update.galaxy import apply_updates, collect_pins, find_outdated_updates + +GALAXY = """--- +collections: + - name: community.general + version: 13.2.0 + - name: kewlfft.aur + version: 0.13.0 +""" + +GIT = """--- +collections: + - name: community.general + source: https://github.com/ansible-collections/community.general.git + type: git + version: 13.2.0 + + - name: kewlfft.aur + source: https://github.com/kewlfft/ansible-aur.git + type: git + version: master +""" + + +def _read(root: Path, name: str) -> str: + path = root / "requirements" / name + return path.read_text() # nocheck: cache-read -- rewritten by this test + + +def _repo(root: Path) -> Path: + (root / "requirements").mkdir() + (root / "requirements" / "requirements.galaxy.yml").write_text( + GALAXY, encoding="utf-8" + ) + (root / "requirements" / "requirements.git.yml").write_text(GIT, encoding="utf-8") + return root + + +class TestCollectPins(unittest.TestCase): + def test_only_collections_pinned_to_a_semver_in_both_files_are_collected(self): + with TemporaryDirectory() as tmp: + root = _repo(Path(tmp)) + + pins = collect_pins(root) + + self.assertEqual([pin.fqcn for pin in pins], ["community.general"]) + + def test_a_version_the_two_files_disagree_on_is_not_collected(self): + with TemporaryDirectory() as tmp: + root = _repo(Path(tmp)) + (root / "requirements" / "requirements.galaxy.yml").write_text( + GALAXY.replace("13.2.0", "13.4.0"), encoding="utf-8" + ) + + self.assertEqual(collect_pins(root), []) + + +class TestFindOutdatedUpdates(unittest.TestCase): + def test_a_higher_tag_of_the_same_depth_is_an_update(self): + with TemporaryDirectory() as tmp: + root = _repo(Path(tmp)) + with patch( + "utils.update.galaxy.git_ls_remote_tags", + return_value=["13.1.0", "13.2.0", "13.4.0"], + ): + updates = find_outdated_updates(root) + + self.assertEqual([u.latest for u in updates], ["13.4.0"]) + + def test_the_newest_tag_already_pinned_is_no_update(self): + with TemporaryDirectory() as tmp: + root = _repo(Path(tmp)) + with patch( + "utils.update.galaxy.git_ls_remote_tags", + return_value=["13.1.0", "13.2.0"], + ): + self.assertEqual(find_outdated_updates(root), []) + + def test_a_tag_of_a_different_depth_is_not_a_candidate(self): + with TemporaryDirectory() as tmp: + root = _repo(Path(tmp)) + with patch( + "utils.update.galaxy.git_ls_remote_tags", + return_value=["13.2.0", "14"], + ): + self.assertEqual(find_outdated_updates(root), []) + + +class TestApplyUpdates(unittest.TestCase): + def test_both_requirement_files_are_bumped_together(self): + with TemporaryDirectory() as tmp: + root = _repo(Path(tmp)) + with patch( + "utils.update.galaxy.git_ls_remote_tags", + return_value=["13.4.0"], + ): + updates = find_outdated_updates(root) + changed = apply_updates(root, updates) + + self.assertEqual(len(changed), 2) + galaxy_text = _read(root, "requirements.galaxy.yml") + git_text = _read(root, "requirements.git.yml") + self.assertIn("version: 13.4.0", galaxy_text) + self.assertIn("version: 13.4.0", git_text) + self.assertNotIn("13.2.0", galaxy_text) + self.assertNotIn("13.2.0", git_text) + + def test_an_entry_outside_the_update_keeps_its_version(self): + with TemporaryDirectory() as tmp: + root = _repo(Path(tmp)) + with patch( + "utils.update.galaxy.git_ls_remote_tags", + return_value=["13.4.0"], + ): + apply_updates(root, find_outdated_updates(root)) + + self.assertIn("version: master", _read(root, "requirements.git.yml")) + self.assertIn("version: 0.13.0", _read(root, "requirements.galaxy.yml")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/update/test_repository.py b/tests/unit/python/utils/update/test_repository.py index 28dfa766c2..a956b4354e 100644 --- a/tests/unit/python/utils/update/test_repository.py +++ b/tests/unit/python/utils/update/test_repository.py @@ -5,10 +5,12 @@ import unittest from pathlib import Path from utils.cache.files import read_text +from utils.roles.mapping import ROLE_DIR_META_ADDONS, ROLE_FILE_META_SERVICES from utils.update.repository import ( RepositoryRefEntry, RepositoryRefUpdate, apply_updates, + collect_entries, suppressed_ref_lines, update_config_refs, walk_repo_ref_pairs, @@ -216,5 +218,46 @@ class TestApplyUpdates(unittest.TestCase): self.assertEqual(read_text(str(config_b)), " ref: v2.1.0\n") +class TestCollectEntriesCoversAddons(unittest.TestCase): + def _role(self, root: Path) -> Path: + role = root / "roles" / "web-app-example" + (role / ROLE_DIR_META_ADDONS).mkdir(parents=True) + return role + + def test_addon_ref_is_collected_beside_the_service_ref(self) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + root = Path(tmpdir) + role = self._role(root) + (role / ROLE_FILE_META_SERVICES).write_text( + "app:\n repository: https://example.test/app.git\n ref: v1.0.0\n", + encoding="utf-8", + ) + (role / ROLE_DIR_META_ADDONS / "plug.yml").write_text( + "config:\n repository: https://example.test/plug.git\n ref: v2.0.0\n", + encoding="utf-8", + ) + + by_ref = {entry.ref: entry for entry in collect_entries(root)} + + self.assertEqual(set(by_ref), {"v1.0.0", "v2.0.0"}) + addon = by_ref["v2.0.0"] + self.assertEqual(addon.entity_path[:2], ("addons", "plug")) + self.assertEqual(addon.config_path.name, "plug.yml") + + def test_addon_ref_honours_its_own_suppression_marker(self) -> None: + with tempfile.TemporaryDirectory() as tmpdir: + root = Path(tmpdir) + role = self._role(root) + (role / ROLE_DIR_META_ADDONS / "plug.yml").write_text( + "config:\n" + " repository: https://example.test/plug.git\n" + " # nocheck: repository-version\n" + " ref: v2.0.0\n", + encoding="utf-8", + ) + + self.assertEqual(collect_entries(root), []) + + if __name__ == "__main__": unittest.main() diff --git a/utils/annotations/suppress.py b/utils/annotations/suppress.py index 51ce224c03..f6140a4d2c 100644 --- a/utils/annotations/suppress.py +++ b/utils/annotations/suppress.py @@ -134,6 +134,21 @@ def is_suppressed_anywhere(lines: Sequence[str], rule: str) -> bool: return any(line_has_rule(line, rule) for line in lines) +def is_suppressed_for_key(lines: Sequence[str], key: str, rule: str) -> bool: + """Whether the mapping line declaring *key* carries a marker for *rule*. + + Args: + lines: the file's lines. + key: the YAML key, matched as ``<key>:`` after stripping indentation. + rule: the rule to look for. + """ + number = next( + (n for n, line in enumerate(lines, 1) if line.strip().startswith(f"{key}:")), + None, + ) + return number is not None and is_suppressed_at(lines, number, rule) + + def suppressed_line_numbers(lines: Sequence[str], rule: str) -> set[int]: """Return the set of 1-based line numbers carrying a marker for *rule*.""" rule = rule.lower() diff --git a/utils/api.py b/utils/api.py new file mode 100644 index 0000000000..b7c0f95891 --- /dev/null +++ b/utils/api.py @@ -0,0 +1,112 @@ +"""Proprietary API credential SPOT, read from group_vars/all/18_api.yml. + +``API`` is a plain mapping, so an inventory that configures three providers +replaces the whole declaration instead of merging into it, and every provider it +does not name disappears. Resolving a hidden provider then raises, and a raising +lookup inside a value the applications renderer is templating leaves the raw +``{{ ... }}`` text in place: the consumer stores template text, and ``| bool`` +coerces it to False with a deprecation warning that fails the deploy on the +warning gate. + +Merging the scope's override over the declared defaults keeps every declared +provider resolvable, so an override narrows values, never the provider set. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import Any + +from utils import PROJECT_ROOT +from utils.cache.base import _deep_merge +from utils.cache.yaml import load_yaml_any + +_API_SPOT_FILE = str(PROJECT_ROOT / "group_vars" / "all" / "18_api.yml") + + +def declared_api() -> dict[str, Any]: + """The ``API`` mapping as declared in the group_vars SPOT. + + Returns: + Provider name to credential mapping, every value a plain string. + + Raises: + TypeError: the SPOT does not declare ``API`` as a mapping. + """ + document = load_yaml_any(_API_SPOT_FILE, default_if_missing={}) or {} + declared = document.get("API") if isinstance(document, Mapping) else None + if not isinstance(declared, Mapping): + raise TypeError(f"{_API_SPOT_FILE} does not declare 'API' as a mapping.") + return dict(declared) + + +def resolve_api( + variables: Mapping[str, Any] | None, templar: Any = None +) -> dict[str, Any]: + """The effective ``API`` mapping for a render scope. + + Args: + variables: the scope's variables; its ``API`` entry overrides the SPOT. + templar: optional templar; renders the override and the merged values, + so an inventory may source a credential from an env lookup. + + Returns: + The SPOT declaration with the scope's override merged over it. + + Raises: + TypeError: the scope's ``API`` is present but not a mapping. + """ + declared = declared_api() + override: Any = (variables or {}).get("API") + if override is not None and not isinstance(override, Mapping) and templar: + override = _templated(templar, override) + if override is None: + return declared + if not isinstance(override, Mapping): + raise TypeError("'API' is defined but is not a mapping.") + merged = _deep_merge(declared, dict(override)) + if templar is None: + return merged + rendered = _templated(templar, merged) + return dict(rendered) if isinstance(rendered, Mapping) else merged + + +def _templated(templar: Any, value: Any) -> Any: + from ansible.errors import AnsibleError + + try: + return templar.template(value, fail_on_undefined=False) + except TypeError: + pass + except (AnsibleError, ValueError): + return value + + try: + return templar.template(value) + except (AnsibleError, TypeError, ValueError): + return value + + +def provider_enabled(api: Mapping[str, Any], provider: str) -> bool: + """Whether every credential of a provider carries a value. + + Args: + api: an effective ``API`` mapping, as returned by ``resolve_api``. + provider: the provider name, e.g. ``github``. + + Returns: + True when the provider declares at least one credential and none of + them is empty. + + Raises: + KeyError: the provider is not declared in the SPOT. + """ + credentials = api.get(provider) + if not isinstance(credentials, Mapping): + raise KeyError( + f"unknown API provider {provider!r}; declare it under 'API' in " + f"{_API_SPOT_FILE}." + ) + if not credentials: + return False + return all(str(value).strip() for value in credentials.values()) diff --git a/utils/cache/README.md b/utils/cache/README.md index 95dffe8b55..a4d0080e34 100644 --- a/utils/cache/README.md +++ b/utils/cache/README.md @@ -10,8 +10,9 @@ This package contains the in-process cache layers Infinito.Nexus uses to keep CL | [files.py](files.py) | The project tree's full path list (one walk per process) and per-file UTF-8 contents (`read_text`). Used by lint/integration tests and CLI tools that scan the repo. | | [base.py](base.py) | Cross-cutting helpers: filesystem constants (`PROJECT_ROOT`, `ROLES_DIR`, `DEFAULT_TOKENS_FILE`), `_deep_merge`, cache-key + content-fingerprint signatures, the cross-domain re-entry guard, and the templar-render machinery. The only ansible-coupled symbol is `_render_with_templar`, which lazy-imports its dependency. | | [applications.py](applications.py) | Per-app variants + defaults + `get_merged_applications`. **Strictly ansible-free at import time** so the GitHub Actions runner-host CLI path (`cli.administration.deploy.development.init` โ†’ `plan_dev_inventory_matrix` โ†’ `get_variants`) keeps working without ansible installed. | +| [carrier.py](carrier.py) | The play-scoped carrier of the rendered applications payload: the fact name `_INFINITO_APPLICATIONS_RENDERED`, `merged_applications_cache_key`, and the reader `get_merged_applications` consults before it renders. | | [users/](users/) | User definitions, token store hydration, alias materialization, `get_user_defaults`, `get_merged_users` (package; `users/placeholders.py` substitutes `DOMAIN_PRIMARY` / `ORGANIZATION` / `SOFTWARE_NAME` ahead of the templar render pass). | -| [domains.py](domains.py) | Canonical-domains map derived from the merged applications view: `get_merged_domains`. | +| [domains.py](domains.py) | Canonical-domains map derived from the merged applications view: `get_merged_domains`. A read issued while the applications render is in progress (the re-entry guard is set) sees the unrendered view, so it is cached under its own key and never answers a later read. | | [`__init__.py`](__init__.py) | Owns the package-level `_reset_cache_for_tests()` orchestrator that clears every cache plus the shared fingerprint memo in one call. | ## When To Use Which ๐ŸŽฏ @@ -25,6 +26,8 @@ The layers are orthogonal: `yaml.py` caches "this file's parsed root", the `appl Both layers are process-wide in-process caches. They intentionally do NOT track on-disk file mtimes; CLI tools are short-lived and the assumption "the on-disk file does not change while my process runs" holds. The single exception is `utils.cache.yaml.dump_yaml`, which writes through and evicts the cached entry for the path it just wrote so a tool that edits a file mid-run sees the new content on the next read. +Inside a play the process boundary is the task: Ansible forks a fresh worker per task, so `_MERGED_APPLICATIONS_CACHE` starts empty in every worker. `get_merged_applications` therefore also accepts the play-scoped carrier fact `_INFINITO_APPLICATIONS_RENDERED` (payload plus cache key, parked once by the constructor stage) and serves it when the key matches. See [applications.md](../../docs/contributing/artefact/files/plugins/lookup/applications.md) for the contract. + ## Test-Only Helpers ๐Ÿงช Each module owns a private `_reset()` that clears its own cache dicts. The package-level `utils.cache._reset_cache_for_tests()` orchestrates all six (`base`, `applications`, `users`, `domains`, `yaml`, `files`) plus the shared fingerprint memo. Unit tests that exercise the cached paths MUST call it in `setUp` to guarantee clean state across test cases. @@ -52,3 +55,34 @@ from utils.cache.domains import get_merged_domains # Tests from utils.cache import _reset_cache_for_tests ``` + +## Schema ๐Ÿ—บ๏ธ + +```mermaid +flowchart TD + decl["meta/services.yml<br/>a flag reading group_names<br/>114 role files"] + ctor["01_constructor.yml:191<br/>applications_carrier"] + fact["_INFINITO_APPLICATIONS_RENDERED<br/>per-host fact"] + lookup["lookup('database', ...)<br/>and every applications consumer"] + key["base.py:103<br/>_stable_variables_signature"] + proc["_MERGED_APPLICATIONS_CACHE<br/>process-global dict"] + render["base.py:198<br/>_render_with_templar"] + consumer["database.py:121<br/>central_enabled = shared"] + name["postgres_postgres<br/>vs pretix_database"] + + decl -->|"read by"| render + ctor -->|"parks"| fact + lookup -->|"computes"| key + key -->|"1. looked up in"| proc + proc -->|"2. miss: falls back to"| fact + fact -->|"3. miss: renders"| render + render -->|"substitutes group_names,<br/>then stores under key"| proc + render --> consumer + consumer -->|"selects"| name + + proc -.->|"TRIP-WIRE: read BEFORE the<br/>host's own fact, so an inherited<br/>entry outranks it"| fact + render -.->|"TRIP-WIRE: main process renders<br/>task names for one host; forked<br/>workers inherit that entry"| proc + key -.->|"TRIP-WIRE: carrier.py:68 stringifies<br/>only one side, so a non-scalar key<br/>part silently never matches again"| fact +``` + +The key covers `group_names`. `domains.py` derives from the applications view and shares that dependency; `users` reads `group_names` nowhere. diff --git a/utils/cache/applications.py b/utils/cache/applications.py index b8f576b71c..68dc5e4823 100644 --- a/utils/cache/applications.py +++ b/utils/cache/applications.py @@ -15,7 +15,8 @@ from collections.abc import Mapping from typing import TYPE_CHECKING, Any from plugins.filter.merge.with_defaults import merge_with_defaults -from utils.roles.mapping import ROLE_FILE_META_VARIANTS +from utils.roles.applications.mcp import derive_mcp_presence +from utils.roles.mapping import ROLE_FILE_META_VARIANTS, ROLE_FILE_META_VOLUMES from .base import ( _RENDER_GUARD, @@ -24,8 +25,8 @@ from .base import ( _render_with_templar, _resolve_override_mapping, _resolve_roles_dir, - _stable_variables_signature, ) +from .carrier import _carried_applications, merged_applications_cache_key from .schema_credentials import extract_default_credentials from .yaml import load_yaml as _load_yaml_cached from .yaml import load_yaml_any as _load_yaml_any_cached @@ -281,10 +282,12 @@ def _build_variants(roles_dir: Path) -> dict[str, list[Any]]: behaviour. """ variants: dict[str, list[Any]] = {} + bases: dict[str, Any] = {} for role_dir in _iter_application_role_dirs(roles_dir): application_id = role_dir.name base_config = _build_role_base_config(role_dir, roles_dir) + bases[application_id] = base_config meta_path = role_dir / ROLE_FILE_META_VARIANTS override_list = _load_variants_overrides(meta_path) role_variants: list[Any] = [] @@ -295,6 +298,19 @@ def _build_variants(roles_dir: Path) -> dict[str, list[Any]]: role_variants.append(copy.deepcopy(override)) variants[application_id] = role_variants + derive_mcp_presence(bases) + for application_id, role_variants in variants.items(): + derived = (bases.get(application_id) or {}).get("mcp") + if not isinstance(derived, dict): + continue + for variant_config in role_variants: + block = ( + variant_config.get("mcp") if isinstance(variant_config, dict) else None + ) + if isinstance(block, dict): + block.setdefault("enabled", derived["enabled"]) + block.setdefault("shared", derived["shared"]) + return {key: variants[key] for key in sorted(variants)} @@ -306,6 +322,7 @@ def _build_application_defaults(roles_dir: Path) -> dict[str, Any]: defaults: dict[str, Any] = {} for role_dir in _iter_application_role_dirs(roles_dir): defaults[role_dir.name] = _build_role_base_config(role_dir, roles_dir) + derive_mcp_presence(defaults) return {key: defaults[key] for key in sorted(defaults)} @@ -379,14 +396,16 @@ def get_merged_applications( variables = variables or {} resolved_roles_dir = _resolve_roles_dir(roles_dir=roles_dir) - cache_key = ( - _cache_key(resolved_roles_dir), - _stable_variables_signature(variables), - ) + cache_key = merged_applications_cache_key(variables, roles_dir=resolved_roles_dir) cached = _MERGED_APPLICATIONS_CACHE.get(cache_key) if cached is not None: return cached + carried = _carried_applications(variables, cache_key) + if carried is not None: + _MERGED_APPLICATIONS_CACHE[cache_key] = carried + return carried + defaults = get_application_defaults(roles_dir=resolved_roles_dir) overrides = _resolve_override_mapping(variables, "applications", templar=templar) @@ -431,10 +450,21 @@ def get_canonical_volumes(application_id: str) -> dict[str, Any]: Lives outside the applications payload so its embedded Jinja `source:` strings stay raw โ€” see the `_CANONICAL_VOLUMES_BY_ROLE` doc-comment. + + An empty result is cached under its id too, or a role without the file + would re-stat it on every call. """ - if not _CANONICAL_VOLUMES_BY_ROLE: - _build_application_defaults(_resolve_roles_dir(roles_dir=None)) - return _CANONICAL_VOLUMES_BY_ROLE.get(application_id, {}) + cached = _CANONICAL_VOLUMES_BY_ROLE.get(application_id) + if cached is not None: + return cached + + data = _load_yaml_any_cached( + _resolve_roles_dir(roles_dir=None) / application_id / ROLE_FILE_META_VOLUMES, + default_if_missing={}, + ) + volumes = data if isinstance(data, dict) else {} + _CANONICAL_VOLUMES_BY_ROLE[application_id] = volumes + return volumes def _reset() -> None: diff --git a/utils/cache/base.py b/utils/cache/base.py index 9986e7fe63..f9c2d23276 100644 --- a/utils/cache/base.py +++ b/utils/cache/base.py @@ -104,15 +104,24 @@ def _stable_variables_signature(variables: Mapping[str, Any] | None) -> tuple: """Build a content-based cache signature from the subset of `variables` that influences the merged applications/users payload. + `group_names` belongs in the key because a service flag may be written as + `{{ '<role>' in group_names }}`, so two hosts of one play render different + payloads from identical host_vars. Ansible forks its workers, so a payload + rendered in the strategy's main process for one host is inherited by every + later worker; without this component that payload answers for hosts whose + groups say otherwise. + See `_fingerprint_mapping` for why id()-only keys don't work reliably. """ if not variables: - return ("0", "0", "", "") + return ("0", "0", "", "", "") + groups = variables.get("group_names") return ( _fingerprint_mapping(variables.get("applications")), _fingerprint_mapping(variables.get("users")), str(variables.get("DOMAIN_PRIMARY") or ""), str(variables.get("SYSTEM_EMAIL_DOMAIN") or ""), + ",".join(sorted(str(group) for group in groups)) if groups else "", ) diff --git a/utils/cache/carrier.py b/utils/cache/carrier.py new file mode 100644 index 0000000000..08c4e786a2 --- /dev/null +++ b/utils/cache/carrier.py @@ -0,0 +1,73 @@ +"""Play-scoped carrier of the rendered applications payload. + +Ansible forks a fresh worker process per task, so the in-process +`_MERGED_APPLICATIONS_CACHE` starts empty in every worker. The constructor +stage renders once and parks the payload plus its cache key in the host fact +named by `APPLICATIONS_RENDERED_FACT`; every later worker inherits that fact +at fork time and `get_merged_applications` serves it instead of rendering. +Ansible-free at import time like the rest of the package. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any + +from .base import _cache_key, _resolve_roles_dir, _stable_variables_signature + +if TYPE_CHECKING: + import os + +APPLICATIONS_RENDERED_FACT = "_INFINITO_APPLICATIONS_RENDERED" + + +def merged_applications_cache_key( + variables: Mapping[str, Any] | None, + *, + roles_dir: str | os.PathLike[str] | None = None, +) -> tuple[str, tuple]: + """Key under which one rendered applications payload stays valid. + + Args: + variables: The play's variable scope. Only the subset that + `_stable_variables_signature` reads influences the key. + roles_dir: Roles tree the payload is built from; defaults to the + repository's `roles/`. + + Returns: + ``(resolved roles dir, stable variables signature)``. + """ + return ( + _cache_key(_resolve_roles_dir(roles_dir=roles_dir)), + _stable_variables_signature(variables), + ) + + +def _carried_applications( + variables: Mapping[str, Any], cache_key: tuple[str, tuple] +) -> dict[str, Any] | None: + """Return the payload carried in `APPLICATIONS_RENDERED_FACT` when its + key equals *cache_key*, else ``None``. + + Args: + variables: The play's variable scope, read for the carrier fact. + cache_key: The key the caller would render under. + """ + carrier = variables.get(APPLICATIONS_RENDERED_FACT) + if not isinstance(carrier, Mapping): + return None + key = carrier.get("key") + payload = carrier.get("applications") + if ( + not isinstance(payload, Mapping) + or not isinstance(key, (list, tuple)) + or len(key) != 2 + or not isinstance(key[1], (list, tuple)) + ): + return None + if [str(key[0]), [str(part) for part in key[1]]] != [ + cache_key[0], + list(cache_key[1]), + ]: + return None + return payload diff --git a/utils/cache/domains.py b/utils/cache/domains.py index cc7f7f2eeb..ee4bd569a4 100644 --- a/utils/cache/domains.py +++ b/utils/cache/domains.py @@ -12,6 +12,7 @@ from __future__ import annotations from typing import TYPE_CHECKING, Any from .base import ( + _RENDER_GUARD, _cache_key, _resolve_roles_dir, _stable_variables_signature, @@ -31,6 +32,54 @@ def _as_bool(value: Any) -> bool: return bool(value) +def _resolved_flag( + value: Any, + *, + app: str, + name: str, + templar: Any, + variables: Any, + apps: Any, +) -> bool: + """A tor service flag as a boolean, never as the text of its own template. + + ``services.tor.*`` is declared as Jinja in 99 of the 105 roles that carry + it. When this map is built from an applications tree that is still being + rendered (``utils.cache.applications`` returns the raw tree while its own + render is in flight) the flag arrives as its source text, which every + boolean coercion reads as False. The onion injection would then silently + not happen and the clearnet domain would be frozen into whatever value the + render was producing. + + Args: + value: the declared flag, rendered or not. + app: application id, for the error message. + name: flag name under ``services.tor``, for the error message. + templar: templar to render with; ``None`` renders nothing. + variables: scope the template resolves against. + apps: applications tree seeded into the nested render. + + Returns: + The flag as a boolean. + + Raises: + ValueError: the flag still carries template text after rendering. + """ + if isinstance(value, str) and ("{{" in value or "{%" in value): + from utils.cache.base import _render_with_templar + + value = _render_with_templar( + value, templar=templar, variables=variables, raw_applications=apps + ) + if isinstance(value, str) and ("{{" in value or "{%" in value): + raise ValueError( + f"get_merged_domains: '{app}' services.tor.{name} stayed template " + f"text ({value!r}). Reading it as a boolean would drop the onion " + "domains without saying so." + ) + return _as_bool(value) + + def _onion_of(domain: str, primary: str, node_onion: str) -> str | None: """Return ``domain`` with the clearnet ``primary`` suffix swapped for the node onion, or None when the domain is not under ``primary``.""" @@ -47,6 +96,9 @@ def _inject_onion_domains( apps: dict[str, Any], primary: str, node_onion: str, + *, + templar: Any = None, + variables: Any = None, ) -> dict[str, Any]: """Add ``<sub>.<node-onion>`` domains for apps opting into onion routing. @@ -62,21 +114,38 @@ def _inject_onion_domains( ) registry = build_service_registry_from_applications(apps) + + def _flag(value: Any, app: str, name: str) -> bool: + return _resolved_flag( + value, + app=app, + name=name, + templar=templar, + variables=variables, + apps=apps, + ) + out: dict[str, Any] = {} for app, domains in merged.items(): tor = ((apps.get(app) or {}).get("services") or {}).get("tor") or {} - if not isinstance(domains, (list, dict)) or not _as_bool(tor.get("enabled")): + if not isinstance(domains, (list, dict)) or not _flag( + tor.get("enabled"), app, "enabled" + ): out[app] = domains continue - exclusive = _as_bool( + exclusive = _flag( resolve_service_config( apps, app, "tor", "exclusive", default=False, service_registry=registry - ) + ), + app, + "exclusive", ) - is_primary = _as_bool( + is_primary = _flag( resolve_service_config( apps, app, "tor", "primary", default=False, service_registry=registry - ) + ), + app, + "primary", ) if isinstance(domains, dict): out[app] = _inject_onion_into_dict( @@ -136,7 +205,13 @@ def get_merged_domains( (canonical/aliases) and flow through the regular applications-merge pipeline. - Cached keyed on (roles_dir, variables_signature). + Cached keyed on (roles_dir, variables_signature, render_state). A read + issued while the applications render is in progress sees the unrendered + tree, whose service flags are still Jinja strings; its map is cached under + its own key so the render's own call sites reuse it without it ever being + served as the finished map. The tor flags are rendered before they are + read (``_resolved_flag``), so that mid-render map carries the same onion + domains the finished one does. """ from plugins.filter.canonical_domains_map import ( FilterModule as _CanonicalDomainsFilter, @@ -150,6 +225,7 @@ def get_merged_domains( cache_key = ( _cache_key(resolved_roles_dir), _stable_variables_signature(variables), + bool(getattr(_RENDER_GUARD, "applications", False)), ) cached = _MERGED_DOMAINS_CACHE.get(cache_key) if cached is not None: @@ -194,7 +270,14 @@ def get_merged_domains( node_onion = str(_render_raw(node_raw or "", "services.tor.node") or "").strip() group_names = variables.get("group_names") or [] if node_onion and "svc-net-tor" in group_names: - merged = _inject_onion_domains(merged, apps, str(primary_domain), node_onion) + merged = _inject_onion_domains( + merged, + apps, + str(primary_domain), + node_onion, + templar=templar, + variables=variables, + ) _MERGED_DOMAINS_CACHE[cache_key] = merged return merged diff --git a/utils/cache/files.py b/utils/cache/files.py index f871884b9b..8f310c21e7 100644 --- a/utils/cache/files.py +++ b/utils/cache/files.py @@ -79,16 +79,15 @@ def _local_exclude_dirs() -> frozenset[str]: return frozenset(names) -@lru_cache(maxsize=1) -def _all_project_files() -> tuple[str, ...]: - """One-shot filesystem walk from PROJECT_ROOT. +@lru_cache(maxsize=4) +def _all_project_files(root_str: str) -> tuple[str, ...]: + """One-shot filesystem walk from *root_str*. Returns absolute paths as a tuple (immutable โ†’ safe to cache). Pruned at walk-time by `_DEFAULT_SKIP_DIRS` plus git's local exclude file, since those dirs are never relevant for any project-tree test and descending into them is pure waste. """ - root_str = str(PROJECT_ROOT) skip_dirs = _DEFAULT_SKIP_DIRS | _local_exclude_dirs() paths: list[str] = [] for dirpath, dirnames, filenames in os.walk(root_str, topdown=True): @@ -114,7 +113,7 @@ def iter_project_files( ``exclude_dirs=("docs",)`` skips any file whose path contains a ``docs`` segment. """ - all_files = _all_project_files() + all_files = _all_project_files(str(PROJECT_ROOT)) tests_prefix = str(Path(str(PROJECT_ROOT)) / "tests") + os.sep ext_lower = tuple(e.lower() for e in extensions) if extensions else None exclude_dirs_set = set(exclude_dirs) if exclude_dirs else None diff --git a/utils/cache/users/__init__.py b/utils/cache/users/__init__.py index da97804f2c..46dded5320 100644 --- a/utils/cache/users/__init__.py +++ b/utils/cache/users/__init__.py @@ -102,12 +102,25 @@ def _load_user_defs(roles_dir: Path) -> OrderedDict[str, dict[str, Any]]: existing = merged[key] for field, value in overrides.items(): - if field in existing and existing[field] != value: + if field not in existing: + existing[field] = copy.deepcopy(value) + continue + current = existing[field] + if isinstance(current, dict) and isinstance(value, dict): + for sub_key, sub_value in value.items(): + if sub_key in current and current[sub_key] != sub_value: + raise ValueError( + f"Conflict for user '{key}': field '{field}.{sub_key}' has " + f"existing value '{current[sub_key]}', tried to set " + f"'{sub_value}' in {filepath}" + ) + current[sub_key] = copy.deepcopy(sub_value) + continue + if current != value: raise ValueError( f"Conflict for user '{key}': field '{field}' has existing value " - f"'{existing[field]}', tried to set '{value}' in {filepath}" + f"'{current}', tried to set '{value}' in {filepath}" ) - existing.update(copy.deepcopy(overrides)) return merged @@ -148,7 +161,11 @@ def _build_users( "description", f"Created by Infinito.Nexus Ansible for {primary_domain}" ) roles = overrides.get("roles", []) - password = overrides.get("password", become_pwd) + application_roles = overrides.get("application_roles", {}) + declared_password = overrides.get("password", become_pwd) + password = ( + become_pwd if isinstance(declared_password, dict) else declared_password + ) accounts = overrides.get("accounts") if accounts is None: accounts = _derive_accounts(roles) @@ -168,6 +185,7 @@ def _build_users( "uid": uid, "gid": gid, "roles": roles, + "application_roles": application_roles, "tokens": tokens, "authorized_keys": authorized_keys, "accounts": accounts, diff --git a/utils/cache/yaml.py b/utils/cache/yaml.py index 6e39faf8e5..7666265ec6 100644 --- a/utils/cache/yaml.py +++ b/utils/cache/yaml.py @@ -59,6 +59,7 @@ def _construct_vault_tag(loader, node): yaml.SafeLoader.add_constructor("!vault", _construct_vault_tag) +_Loader.add_constructor("!vault", _construct_vault_tag) _MISSING = object() _CACHE: dict[tuple[str, int, int], list[Any]] = {} diff --git a/utils/diagnostics/container.py b/utils/diagnostics/container.py index 57562773c7..60695c8a1a 100755 --- a/utils/diagnostics/container.py +++ b/utils/diagnostics/container.py @@ -40,8 +40,12 @@ _NESTED_TIMEOUT = 600 _TAR_TIMEOUT = 300 _SELF_IN_CONTAINER = "/tmp/rescue-self.py" # noqa: S108 - fixed staging path inside the inspected container _LOCAL_DUMPS_ENV = "INFINITO_RESCUE_LOCAL_DUMPS_DIR" +_APP_LOG_TAIL = "find /var/log /var/www /opt /srv -xdev -type f -name '*.log' -size -20971520c -mmin -360 -exec sh -c 'echo \"===== $1\"; tail -n 400 \"$1\"' _ {} ';'" _PROBE_HOSTS = ("deb.debian.org", "ghcr.io", "repo.packagist.org") -_INZONE_PROBE = "getent hosts rescue-probe.$(awk -F/ '/^address=/{print $2;exit}' /etc/dnsmasq.conf)" +_DNSMASQ_DIRS = ( + "$(sed -n 's|^ *conf-dir=\\([^,[:space:]]*\\).*|\\1|p' /etc/dnsmasq.conf)" +) +_INZONE_PROBE = f"getent hosts rescue-probe.$(grep -rhs '^ *address=/' /etc/dnsmasq.conf {_DNSMASQ_DIRS} | awk -F/ '{{print $2;exit}}')" def runtime_bin() -> str | None: @@ -330,23 +334,22 @@ def collect_runtime(out: Path, rt: str) -> tuple[list[str], list[str]]: safe = sanitize(name) capture(out / "containers", f"{safe}.log", [rt, "logs", name]) capture(out / "containers", f"{safe}.inspect.json", [rt, "inspect", name]) - capture( - out / "containers", - f"{safe}.resolv-conf.txt", - [rt, "exec", name, "cat", "/etc/resolv.conf"], - timeout=_PROBE_TIMEOUT, - ) - capture( - out / "containers", - f"{safe}.systemctl.txt", - [rt, "exec", name, "systemctl", "status", "--all", "--no-pager"], - timeout=_PROBE_TIMEOUT, - ) - capture( - out / "containers", - f"{safe}.journal.txt", - [rt, "exec", name, "journalctl", "-b", "--no-pager"], - ) + for suffix, argv, probe_timeout in ( + ("resolv-conf.txt", ["cat", "/etc/resolv.conf"], _PROBE_TIMEOUT), + ( + "systemctl.txt", + ["systemctl", "status", "--all", "--no-pager"], + _PROBE_TIMEOUT, + ), + ("journal.txt", ["journalctl", "-b", "--no-pager"], _EXEC_TIMEOUT), + ("app-logs.txt", ["sh", "-c", _APP_LOG_TAIL], _PROBE_TIMEOUT), + ): + capture( + out / "containers", + f"{safe}.{suffix}", + [rt, "exec", name, *argv], + timeout=probe_timeout, + ) if "postgres" in name: capture( out / "containers", @@ -366,14 +369,11 @@ def collect_runtime(out: Path, rt: str) -> tuple[list[str], list[str]]: services = list_lines([rt, "service", "ls", "--format", "{{.Name}}"]) for svc in services: safe = sanitize(svc) - capture( - out / "services", f"{safe}.ps.txt", [rt, "service", "ps", "--no-trunc", svc] - ) - capture( - out / "services", - f"{safe}.log", - [rt, "service", "logs", "--no-task-ids", svc], - ) + for suffix, argv in ( + ("ps.txt", ["service", "ps", "--no-trunc", svc]), + ("log", ["service", "logs", "--no-task-ids", svc]), + ): + capture(out / "services", f"{safe}.{suffix}", [rt, *argv]) return containers, services diff --git a/utils/docker/healthcheck/probes.py b/utils/docker/healthcheck/probes.py index a8f185905c..837878bbf8 100644 --- a/utils/docker/healthcheck/probes.py +++ b/utils/docker/healthcheck/probes.py @@ -12,6 +12,20 @@ from typing import Any, ClassVar CURL = ("curl",) CURL_NO_PROXY = ("--noproxy", "*") +DEFAULT_INTERVAL = "2m" +DEFAULT_TIMEOUT = "5s" +DEFAULT_RETRIES = 3 +DEFAULT_START_PERIOD = "10m" +DEFAULT_START_INTERVAL = "5s" + +TIMING_DEFAULTS: dict[str, object] = { + "interval": DEFAULT_INTERVAL, + "timeout": DEFAULT_TIMEOUT, + "retries": DEFAULT_RETRIES, + "start_period": DEFAULT_START_PERIOD, + "start_interval": DEFAULT_START_INTERVAL, +} + _HTTP_REQUEST = ( "echo -e 'GET /{path} HTTP/1.1\\r\\nHost: localhost\\r\\n" "Connection: close\\r\\n\\r\\n' >&3" @@ -53,10 +67,11 @@ class Probe: """Base for every flavor: timings plus the argv docker executes.""" flavor: ClassVar[str] = "" - interval: ClassVar[str] = "30s" - timeout: ClassVar[str] = "5s" - retries: ClassVar[int] = 3 - start_period: ClassVar[str] = "30s" + interval: ClassVar[str] = DEFAULT_INTERVAL + timeout: ClassVar[str] = DEFAULT_TIMEOUT + retries: ClassVar[int] = DEFAULT_RETRIES + start_period: ClassVar[str] = DEFAULT_START_PERIOD + start_interval: ClassVar[str] = DEFAULT_START_INTERVAL def __init__(self, **context: Any) -> None: self.port = context.get("port", "") @@ -86,11 +101,24 @@ class Probe: def block(self, overrides: dict[str, Any]) -> dict[str, Any]: """Assemble the healthcheck mapping. + `start_interval` is the cadence while `start_period` is still running. + Without it a probe only fires every `interval`, so a service ready after + three seconds is reported healthy at the next tick -- 30s, or a minute + for the curl flavors -- and a stack converges no faster than its slowest + quantisation. It changes when the same probe runs, never what it tests. + + `start_period` therefore bounds it: once the window closes the cadence + falls back to `interval`, so a service that becomes ready just after the + window pays a full tick anyway. The window has to outlast a realistic + boot, not merely a fast one, which is why it is measured in minutes + rather than sized to `interval`. It costs nothing while the container + works, only the time until a broken one is called unhealthy. + Args: overrides: service level values that win over the flavor defaults. """ block: dict[str, Any] = {"test": self.test()} - for key in ("interval", "timeout", "retries", "start_period"): + for key in ("interval", "timeout", "retries", "start_period", "start_interval"): block[key] = overrides.get(key, getattr(self, key)) return block @@ -116,7 +144,6 @@ class Curl(Probe): """ flavor = "curl" - interval = "1m" timeout = "10s" def test(self) -> list[str]: @@ -128,7 +155,6 @@ class Curl(Probe): class Wget(Probe): flavor = "wget" - interval = "1m" timeout = "10s" def test(self) -> list[str]: @@ -145,7 +171,6 @@ class Http(Probe): flavor = "http" retries = 5 - start_period = "20s" def test(self) -> list[str]: return [ @@ -197,7 +222,6 @@ class HttpStatus(Tcp): class Nc(Probe): flavor = "nc" timeout = "3s" - start_period = "10s" def test(self) -> list[str]: return ["CMD-SHELL", f"nc -z localhost {self.port} || exit 1"] @@ -212,7 +236,6 @@ class Connect(Probe): """ flavor = "connect" - interval = "1m" timeout = "20s" retries = 5 start_period = "15m" diff --git a/utils/docker/image/discovery.py b/utils/docker/image/discovery.py index c569aed7c1..559003e0e7 100644 --- a/utils/docker/image/discovery.py +++ b/utils/docker/image/discovery.py @@ -4,6 +4,7 @@ from dataclasses import dataclass from typing import TYPE_CHECKING from utils.cache.yaml import load_yaml_any as _load_yaml_cached +from utils.docker.image.pin import pull_reference from utils.roles.mapping import ROLE_FILE_META_SERVICES if TYPE_CHECKING: @@ -146,7 +147,7 @@ def docker_hub_source(image: str, version: str) -> str: if "/" not in base: base = f"library/{base}" - return f"docker.io/{base}:{version}" + return pull_reference(f"docker.io/{base}", version) def image_source(image: str, version: str) -> str: @@ -166,7 +167,7 @@ def image_source(image: str, version: str) -> str: if registry == "docker.io" and "/" not in base: base = f"library/{base}" - return f"{registry}/{base}:{version}" + return pull_reference(f"{registry}/{base}", version) def canonical_image_name(image: str) -> str: diff --git a/utils/docker/image/pin.py b/utils/docker/image/pin.py new file mode 100644 index 0000000000..11b4ec7e41 --- /dev/null +++ b/utils/docker/image/pin.py @@ -0,0 +1,58 @@ +from utils.update.base import version_depth + +DIGEST_PREFIX = "sha256:" + +SEMVER = "semver" +DIGEST = "digest" +REF = "ref" + +RULE_BY_CLASS = { + DIGEST: "docker-digest", + REF: "docker-version", +} + + +def is_digest(version: str) -> bool: + """Whether ``version`` pins by content rather than by name. + + Args: + version: the ``version:`` value a role declares for an image. + """ + return str(version).strip().startswith(DIGEST_PREFIX) + + +def pin_class(version: str) -> str: + """Classify a pin as ``semver``, ``digest`` or ``ref``. + + Args: + version: the ``version:`` value a role declares for an image. + + Returns: + The class name. ``ref`` is the residue: a tag that names no version + the registry can order, so nothing can tell whether it moved. + """ + stripped = str(version).strip() + if is_digest(stripped): + return DIGEST + if version_depth(stripped) > 0: + return SEMVER + return REF + + +def reference_separator(version: str) -> str: + """The character that joins an image name to ``version`` in a pull ref. + + Args: + version: the ``version:`` value a role declares for an image. + """ + return "@" if is_digest(version) else ":" + + +def pull_reference(name: str, version: str) -> str: + """Join an image name and a pin into the reference a registry accepts. + + Args: + name: image name, with or without a registry prefix. + version: the ``version:`` value a role declares for an image. + """ + return f"{name}{reference_separator(version)}{str(version).strip()}" diff --git a/utils/docker/registry.py b/utils/docker/registry.py index dcc4f2cce3..7827e546e0 100644 --- a/utils/docker/registry.py +++ b/utils/docker/registry.py @@ -93,7 +93,7 @@ def _request(url: str, repo: str, method: str, accept: str | None): unreachable (connection/timeout). """ token: str | None = None - for _attempt in (0, 1): + for _ in (0, 1): headers = {"User-Agent": _UA} if accept: headers["Accept"] = accept diff --git a/utils/env/handlers/passthrough.py b/utils/env/handlers/passthrough.py index 1616c7d233..a16fe548c3 100644 --- a/utils/env/handlers/passthrough.py +++ b/utils/env/handlers/passthrough.py @@ -12,6 +12,7 @@ if TYPE_CHECKING: STATIC_KEYS = ( "INFINITO_SRC_DIR", "INFINITO_VENV_DIR", + "INFINITO_ANSIBLE_COLLECTIONS_SOURCE", "INFINITO_BIND_IP", "INFINITO_BUILD", "INFINITO_SUBNET", @@ -21,7 +22,6 @@ STATIC_KEYS = ( "INFINITO_DNS_HOSTS_FILE", "INFINITO_DNS_IP", "INFINITO_DOMAIN", - "INFINITO_DOMAIN_RE", "INFINITO_TOR_SOCKS_PORT", "INFINITO_CONTAINER", "INFINITO_CONTAINER_CA_ENABLED", @@ -44,6 +44,7 @@ STATIC_KEYS = ( "INFINITO_SWARM_TEST_LABEL", "INFINITO_SWARM_MGR_NAME", "INFINITO_SWARM_STEP_TIMEOUT_MINUTES", + "INFINITO_SWARM_TEARDOWN_RESERVE_SECONDS", "INFINITO_SWARM_WRK1_NAME", "INFINITO_SWARM_WRK2_NAME", "INFINITO_SWARM_NFS_NAME", @@ -70,7 +71,11 @@ STATIC_KEYS = ( "INFINITO_FILESYSTEM_INSTALL_SCRIPT", "INFINITO_INTERPRETERS_INSTALL_SCRIPT", "INFINITO_ALIAS_REPOSITORY", + "INFINITO_APT_UBUNTU_MIRRORS", "INFINITO_FORK_REPOSITORY_NAME", + "INFINITO_API_ANTHROPIC_KEY", + "INFINITO_API_OPENAI_KEY", + "INFINITO_API_OPENROUTER_KEY", "INFINITO_PLAYWRIGHT_KEEP", "INFINITO_INVENTORY_EXTRA_VARS", "INFINITO_PUBLISH_PORTS", @@ -95,6 +100,7 @@ STATIC_KEYS = ( "INFINITO_BLACKLIST", "INFINITO_PRIORITY", "INFINITO_CI_CHUNK", + "INFINITO_CI_CHUNK_SIZE", "INFINITO_CI_CONCURRENCY", "INFINITO_CI_DISTRO_BUDGET_SECONDS", "INFINITO_CI_JOB_LIMIT", @@ -127,6 +133,7 @@ STATIC_KEYS = ( "INFINITO_CACHE_PACKAGE_FRONTEND_CERTS_DIR", "INFINITO_CACHE_PACKAGE_FRONTEND_IP", "INFINITO_CACHE_PACKAGE_FRONTEND_INIT_IMAGE", + "INFINITO_CACHE_PACKAGE_IP", "INFINITO_CACHE_PACKAGE_MAX_AGE_MIN", "INFINITO_CACHE_PACKAGE_METADATA_MAX_AGE_MIN", "INFINITO_CACHE_PACKAGE_NPMRC", diff --git a/utils/github/variant/axes.py b/utils/github/variant/axes.py index 8caafe11c2..f00940b12d 100644 --- a/utils/github/variant/axes.py +++ b/utils/github/variant/axes.py @@ -42,6 +42,7 @@ import os import re from typing import TYPE_CHECKING, NamedTuple +from utils.github.variant import instructions from utils.github.variant.pools import DISTROS, FILESYSTEMS, rotate from utils.github.variant.tor import ( TOR_DEPLOY_MODES, @@ -63,7 +64,8 @@ MODES = ("compose", "swarm", "host") LOCAL_GLYPH = to_emoji("test_host") _AXIS_GLYPHS = ( - "".join(to_emoji(word) for word in ("tor", "clearnet", "priority")) + LOCAL_GLYPH + "".join(to_emoji(word) for word in ("tor", "clearnet", "priority", "instructions")) + + LOCAL_GLYPH ) @@ -393,7 +395,7 @@ def assign( else "false", "disable": "" if enabled else "tor", "priority": "true" if priority else "false", - "weight": str(row.get("weight", 0)), + "instructions": "", "id": str(row.get("id", 0)), "covered": str(row.get("covered_by", 0)), "clone": "true" if row.get("clone") else "false", @@ -404,7 +406,7 @@ def assign( + (f" {to_emoji('priority')}" if priority else ""), } ) - return _one_per_deploy(entries) + return instructions.mark(_one_per_deploy(entries), variants_per_app) def _one_per_deploy(entries: list[dict[str, str]]) -> list[dict[str, str]]: diff --git a/utils/github/variant/instructions.py b/utils/github/variant/instructions.py new file mode 100644 index 0000000000..89adaaa508 --- /dev/null +++ b/utils/github/variant/instructions.py @@ -0,0 +1,68 @@ +"""Which matrix entry replays its role's README instructions. + +The replay used to be a job of its own, picking one random role per run. It +rides on a deploy row instead: the role's smallest variant among the rows this +sweep actually deploys, marked with ``instructions`` (the mode the replay runs +in) and a ๐Ÿ“– in the job title. :mod:`utils.roles.guide` decides which variant +that is; this module is what turns the decision into matrix entries. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from utils.roles.guide import guide_deployable, guide_variant +from utils.symbol_glossary import to_emoji + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + from typing import Any + + +def redundant(entry: Mapping[str, str]) -> bool: + """Whether the sweep drops this row as coverage an earlier row already has.""" + if entry["priority"] == "true": + return False + return entry["clone"] == "true" or entry["covered"] != "0" + + +def mark( + entries: list[dict[str, str]], + variants_per_app: Mapping[str, Sequence[Mapping[str, Any]]] | None, +) -> list[dict[str, str]]: + """Hand one entry per role the replay, and give its label the ๐Ÿ“–. + + Only the first entry of the chosen variant: a priority row runs every mode + and onion state it offers, and replaying the same README block in each of + them proves nothing the first replay did not. The glyph goes between the + variant number and the โญ of a priority row, with no space between the two: + they are one marker block, not two axes. + + The row has to run in the guide's own mode. The replay is a second deploy + on the same runner, so hanging it on a swarm row would ask that runner to + bring a compose stack up beside a swarm one. Only rows in that mode count + as deployed here either, so the variant search cannot settle on one that + this sweep runs in swarm alone. + """ + star = f" {to_emoji('priority')}" + deployed: dict[str, set[str]] = {} + for entry in entries: + app = entry["apps"] + if not redundant(entry) and entry["mode"] == guide_deployable(app): + deployed.setdefault(app, set()).add(entry["variant"]) + marked: set[str] = set() + for entry in entries: + app = entry["apps"] + if app in marked or redundant(entry): + continue + variant, mode = guide_variant(app, variants_per_app, deployed.get(app, set())) + if not mode or entry["variant"] != variant or entry["mode"] != mode: + continue + entry["instructions"] = mode + entry["label"] = ( + entry["label"].removesuffix(star) + + f" {to_emoji('instructions')}" + + (to_emoji("priority") if entry["priority"] == "true" else "") + ) + marked.add(app) + return entries diff --git a/utils/handler/vault.py b/utils/handler/vault.py index c9e61d5b91..30a6805b0a 100644 --- a/utils/handler/vault.py +++ b/utils/handler/vault.py @@ -1,10 +1,15 @@ -import subprocess -from typing import Any +from __future__ import annotations + +from functools import cached_property +from typing import TYPE_CHECKING, Any import yaml from yaml.dumper import SafeDumper from yaml.loader import SafeLoader +if TYPE_CHECKING: + from ansible.parsing.vault import VaultLib + class VaultScalar(str): """A subclass of str to represent vault-encrypted strings.""" @@ -31,22 +36,25 @@ class VaultHandler: def __init__(self, vault_password_file: str): self.vault_password_file = vault_password_file + @cached_property + def _vault(self) -> VaultLib: + from ansible.parsing.dataloader import DataLoader + from ansible.parsing.vault import FileVaultSecret, VaultLib + + secret = FileVaultSecret(filename=self.vault_password_file, loader=DataLoader()) + secret.load() + return VaultLib([("default", secret)]) + def encrypt_string(self, value: str, name: str) -> str: - """Encrypt a string using ansible-vault.""" - cmd = [ - "ansible-vault", - "encrypt_string", - "--stdin-name", - name, - "--vault-password-file", - self.vault_password_file, - ] - proc = subprocess.run( - cmd, input=value, capture_output=True, text=True, check=False - ) - if proc.returncode != 0: - raise RuntimeError(f"ansible-vault encrypt_string failed:\n{proc.stderr}") - return proc.stdout + """Return the ``name: !vault |`` snippet as ``ansible-vault`` lays it out. + + Args: + value: plaintext to encrypt. + name: key the snippet is emitted under. + """ + body = self._vault.encrypt(value).decode() + indented = "\n".join(f" {line}" for line in body.splitlines()) + return f"{name}: !vault |\n{indented}\n" def encrypt_leaves(self, branch: dict[str, Any], vault_pw: str): """Recursively encrypt all leaves (plain text values) under the credentials section.""" diff --git a/utils/install/collections.py b/utils/install/collections.py new file mode 100644 index 0000000000..60c2031eb8 --- /dev/null +++ b/utils/install/collections.py @@ -0,0 +1,109 @@ +"""Compare the pinned Galaxy requirements against what is on disk. + +Imported by the lint bootstrap, which runs on a bare interpreter before any +dependency is installed, so this module stays on the standard library. It also +stays inside its own package: the Dockerfile copies it into the image beside +``utils/__init__.py`` and ``utils/install/__init__.py`` and nothing else, so +importing any other ``utils`` submodule raises ``ModuleNotFoundError`` in the +layer that runs it. The +requirements files it reads are this repository's own and hold one shape: +a ``collections:`` list of ``- name:`` entries with an optional ``version:``. +A line that does not match that shape leaves the entry unpinned, which the +caller treats as unsatisfied and installs. +""" + +from __future__ import annotations + +import json +import re +import sys +from pathlib import Path + +_NAME = re.compile(r"^\s*-\s+name:\s*(?P<name>[A-Za-z0-9_.]+)\s*(?:#.*)?$") +_VERSION = re.compile( + r"^\s*version:\s*(?P<quote>[\"']?)(?P<version>[^\s#\"']+)(?P=quote)\s*(?:#.*)?$" +) + + +def declared_pins(requirements_file: Path) -> list[tuple[str, str | None]]: + """The ``(fqcn, version)`` pairs a requirements file declares, in order. + + Args: + requirements_file: the requirements.galaxy.yml to read. + """ + pins: list[tuple[str, str | None]] = [] + try: + raw = requirements_file.read_text(encoding="utf-8") # nocheck: cache-read + except OSError: + return pins + lines = raw.splitlines() + + for line in lines: + name_match = _NAME.match(line) + if name_match: + pins.append((name_match.group("name"), None)) + continue + version_match = _VERSION.match(line) + if version_match and pins: + fqcn, _ = pins[-1] + pins[-1] = (fqcn, version_match.group("version")) + return pins + + +def _installed_version(collections_dir: Path, namespace: str, name: str) -> str | None: + """The version recorded in a collection's manifest, or None when absent. + + Args: + collections_dir: the ``-p`` target ansible-galaxy installs into. + namespace: collection namespace, the part before the dot. + name: collection name, the part after the dot. + """ + manifest = ( + collections_dir / "ansible_collections" / namespace / name / "MANIFEST.json" + ) + try: + raw = manifest.read_text(encoding="utf-8") # nocheck: cache-read + payload = json.loads(raw) + except (OSError, ValueError): + return None + version = payload.get("collection_info", {}).get("version") + return str(version) if version else None + + +def unsatisfied(requirements_file: Path, collections_dir: Path) -> list[str]: + """Requirements that COLLECTIONS_DIR does not already hold at the pinned version. + + An entry without a pinned version can never be confirmed from disk and is + always reported, so the caller falls through to a real install. + + Args: + requirements_file: the requirements.galaxy.yml to read. + collections_dir: the ``-p`` target ansible-galaxy installs into. + """ + missing: list[str] = [] + for fqcn, pinned in declared_pins(requirements_file): + if "." not in fqcn or not pinned: + missing.append(fqcn) + continue + namespace, _, name = fqcn.partition(".") + if _installed_version(collections_dir, namespace, name) != pinned: + missing.append(f"{fqcn}:{pinned}") + return missing + + +def main() -> int: + """Exit 0 when every pinned collection is present at its pinned version. + + Args: + argv[1]: path to requirements.galaxy.yml. + argv[2]: path to the collections directory. + """ + missing = unsatisfied(Path(sys.argv[1]), Path(sys.argv[2])) + if missing: + print(" ".join(missing)) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/utils/install/lint/__main__.py b/utils/install/lint/__main__.py index dc7b97c90c..11fb1fc56a 100644 --- a/utils/install/lint/__main__.py +++ b/utils/install/lint/__main__.py @@ -52,6 +52,8 @@ _STAMP_TOOLS = ( "hadolint", "markdownlint-cli2", "mbake", + "php", + "ruby", "ruff", "shellcheck", "shfmt", @@ -73,6 +75,14 @@ def _install_python_tools() -> None: ruff.ensure() +def _install_php_tools() -> None: + php.ensure() + + +def _install_ruby_tools() -> None: + ruby.ensure() + + def _install_shellcheck_tools() -> None: shellcheck.ensure() @@ -125,6 +135,8 @@ _GROUP_FN_NAMES = { "action": "_install_action_tools", "ansible": "_install_ansible_tools", "python": "_install_python_tools", + "php": "_install_php_tools", + "ruby": "_install_ruby_tools", "shellcheck": "_install_shellcheck_tools", "dockerfile": "_install_dockerfile_tools", "markdown": "_install_markdown_tools", @@ -133,8 +145,6 @@ _GROUP_FN_NAMES = { "javascript": "_install_javascript_tools", "playwright": "_install_playwright_tools", "packages": "_install_packages_tools", - "php": "_install_php_tools", - "ruby": "_install_ruby_tools", "sql": "_install_sql_tools", "css": "_install_css_tools", } @@ -144,6 +154,8 @@ def _install_all() -> None: _install_action_tools() _install_ansible_tools() _install_python_tools() + _install_php_tools() + _install_ruby_tools() _install_shellcheck_tools() _install_dockerfile_tools() _install_markdown_tools() diff --git a/utils/install/lint/ansible/collections.py b/utils/install/lint/ansible/collections.py index 1edd2f83e2..17a2dfec9a 100644 --- a/utils/install/lint/ansible/collections.py +++ b/utils/install/lint/ansible/collections.py @@ -8,16 +8,13 @@ import time from pathlib import Path from utils.cache import PROJECT_ROOT +from utils.install.collections import unsatisfied from utils.install.primitives import log, warn _MAX_ATTEMPTS = 5 -def _collection_present(base_dir: Path, namespace: str, name: str) -> bool: - return (base_dir / "ansible_collections" / namespace / name).is_dir() - - -def _galaxy_install(requirements_file: str, base_dir: Path) -> bool: +def _galaxy_install(requirements_file: Path, base_dir: Path) -> bool: try: subprocess.run( [ @@ -25,7 +22,7 @@ def _galaxy_install(requirements_file: str, base_dir: Path) -> bool: "collection", "install", "-r", - requirements_file, + str(requirements_file), "-p", str(base_dir), "--force-with-deps", @@ -39,22 +36,14 @@ def _galaxy_install(requirements_file: str, base_dir: Path) -> bool: def ensure() -> None: collections_base_dir = Path("~/.ansible/collections").expanduser() - missing: list[str] = [] - - if not _collection_present(collections_base_dir, "community", "general"): - missing.append("community.general") - if not _collection_present(collections_base_dir, "hetzner", "hcloud"): - missing.append("hetzner.hcloud") - if not _collection_present(collections_base_dir, "kewlfft", "aur"): - missing.append("kewlfft.aur") + repo_root = Path(PROJECT_ROOT) + req_galaxy = repo_root / "requirements" / "requirements.galaxy.yml" + req_git = repo_root / "requirements" / "requirements.git.yml" + missing = unsatisfied(req_galaxy, collections_base_dir) if not missing: return - repo_root = Path(PROJECT_ROOT) - req_galaxy = str(repo_root / "requirements" / "requirements.galaxy.yml") - req_git = str(repo_root / "requirements" / "requirements.git.yml") - attempt = 1 while True: log( diff --git a/utils/install/php.py b/utils/install/php.py index 3bb2414f29..c7fdd71147 100644 --- a/utils/install/php.py +++ b/utils/install/php.py @@ -19,7 +19,7 @@ _PHPUNIT_EXTENSIONS = ("dom", "mbstring", "xmlwriter") def ensure_php_toolchain() -> None: """Install the PHP interpreter, Composer and the extensions PHPUnit needs. - ``phpunit/phpunit ^11`` declares ``_PHPUNIT_EXTENSIONS`` as platform + ``phpunit/phpunit`` declares ``_PHPUNIT_EXTENSIONS`` as platform requirements and Composer refuses to resolve the vendor tree without them, so they are part of the toolchain rather than of the suite consuming it. A distro ships them as packages separate from the interpreter, which is why diff --git a/utils/install/system_pkg.py b/utils/install/system_pkg.py index 3f82afc8eb..bf625e35a2 100644 --- a/utils/install/system_pkg.py +++ b/utils/install/system_pkg.py @@ -75,12 +75,53 @@ def _install_one(manager: str, package: str) -> bool: return True -def install_package_candidates(manager: str, packages: list[str]) -> None: - _prepare_manager(manager) +def _try_candidates( + manager: str, packages: list[str], provides: str | None +) -> tuple[bool, bool]: + """Install candidates until ``provides`` is callable. + + Args: + manager: the detected package manager. + packages: candidate package names, most specific first. + provides: the command the caller needs. + + Returns: + whether the caller's command is now callable, and whether any + candidate installed at all. + """ + installed_any = False for package in packages: if _install_one(manager, package): - return - raise RuntimeError(f"All package candidates failed via {manager}: {packages}") + installed_any = True + if provides is None or shutil.which(provides) is not None: + return True, installed_any + return False, installed_any + + +def install_package_candidates( + manager: str, packages: list[str], provides: str | None = None +) -> None: + """Install packages until ``provides`` is callable, or all candidates fail. + + Args: + manager: the detected package manager. + packages: candidate package names, most specific first. + provides: the command the caller needs. + """ + _prepare_manager(manager) + done, installed_any = _try_candidates(manager, packages, provides) + if not done and not installed_any and manager == "apt-get": + _prepare_manager(manager) + done, installed_any = _try_candidates(manager, packages, provides) + if done: + return + if installed_any and provides is not None: + raise RuntimeError( + f"Installed {packages} via {manager} but {provides!r} is still not on " + f"PATH; the candidate list does not cover this distribution." + ) + if not installed_any: + raise RuntimeError(f"All package candidates failed via {manager}: {packages}") _COMMAND_PACKAGES: dict[str, dict[str, list[str]]] = { @@ -225,7 +266,7 @@ def install_command_via_pkg(command_name: str) -> None: ) log(f"Missing command '{command_name}'. Attempting installation via {manager}.") - install_package_candidates(manager, mapping[manager]) + install_package_candidates(manager, mapping[manager], provides=command_name) __all__ = [ diff --git a/utils/manager/inventory.py b/utils/manager/inventory.py index ac3463d36d..2c7379d022 100644 --- a/utils/manager/inventory.py +++ b/utils/manager/inventory.py @@ -1,5 +1,6 @@ from __future__ import annotations +import re import sys from typing import TYPE_CHECKING, Any @@ -19,7 +20,22 @@ from utils.roles.mapping import ROLE_FILE_META_SECRETS, ROLE_FILE_VARS_MAIN if TYPE_CHECKING: from pathlib import Path -_CREDENTIAL_LEAF_MARKERS = ("description", "algorithm", "validation", "default") +_CREDENTIAL_LEAF_MARKERS = ( + "description", + "algorithm", + "validation", + "default", + "type", + "regex", +) + +_SCHEMA_TYPES: dict[str, type | tuple[type, ...]] = { + "string": str, + "integer": int, + "boolean": bool, +} + +_UNRENDERED_TEMPLATE = re.compile(r"\{\{|\{%") def _is_credential_leaf(node: Any) -> bool: @@ -28,6 +44,59 @@ def _is_credential_leaf(node: Any) -> bool: ) +def validate_supplied_value(full_key: str, value: Any, meta: dict[str, Any]) -> None: + """Hold an operator-supplied credential to the schema it declares. + + Only supplied values are checked: a generated one comes from the algorithm + the same schema names, and the generators take no schema argument. + + Args: + full_key: dotted schema path, used in the failure message. + value: the value the operator supplied, empty meaning "not configured". + meta: the schema leaf, read for `type` and `regex`. + + Raises: + SystemExit: the value contradicts the declared type or pattern. + + Exception: a `default:` is written into the inventory verbatim, so on the + next read it arrives here as if an operator had typed it. Every default in + the repository is a Jinja reference, and a pattern describes the rendered + secret, not the template text that will produce it. + """ + if value in ("", None): + return + + if isinstance(value, str) and _UNRENDERED_TEMPLATE.search(value): + return + + declared = meta.get("type") + if declared: + expected = _SCHEMA_TYPES.get(str(declared)) + if expected is None: + print( + f"ERROR: '{full_key}' declares unknown type '{declared}'; " + f"known types are {', '.join(sorted(_SCHEMA_TYPES))}", + file=sys.stderr, + ) + sys.exit(1) + if not isinstance(value, expected): + print( + f"ERROR: '{full_key}' is declared {declared} but the supplied " + f"value is {type(value).__name__}", + file=sys.stderr, + ) + sys.exit(1) + + pattern = meta.get("regex") + if pattern and not re.fullmatch(str(pattern), str(value)): + print( + f"ERROR: the value supplied for '{full_key}' does not match the " + f"pattern its schema declares: {pattern}", + file=sys.stderr, + ) + sys.exit(1) + + def _meta_role_config(role_path: Path) -> dict[str, Any]: """Assemble the view of a role's config from its meta files. @@ -251,6 +320,9 @@ class InventoryManager: * `default:` (Jinja literal) is written verbatim and short-circuits algorithm-based generation. `validation:` is ignored for default-bearing entries. + * `type:` and `regex:` hold an operator-supplied value to the + shape the schema declares; a generated one is exempt because + the algorithm that produced it is named by the same schema. * Existing inventory values are preserved (no double-encryption, no overwrite of operator-supplied secrets). """ @@ -295,6 +367,7 @@ class InventoryManager: if "default" in meta: if isinstance(existing_value, str) and existing_value != "": + validate_supplied_value(full_key, existing_value, meta) return dest[key] = meta["default"] return @@ -306,7 +379,9 @@ class InventoryManager: if algorithm == "plain": if set_key in self.overrides: plain = self.overrides[set_key] + validate_supplied_value(full_key, plain, meta) elif isinstance(existing_value, str) and existing_value != "": + validate_supplied_value(full_key, existing_value, meta) return elif self.allow_empty_plain: plain = "" diff --git a/utils/manager/value_generator.py b/utils/manager/value_generator.py index 118f826cb8..d797dd7a0e 100644 --- a/utils/manager/value_generator.py +++ b/utils/manager/value_generator.py @@ -76,6 +76,7 @@ class ValueGenerator: โ€ข "strong_password" โ€ข "bcrypt" โ€ข "alphanumeric" + โ€ข "sk_prefixed" โ€ข "base64_prefixed_32" โ€ข "vapid_private" โ€ข "vapid_public" @@ -105,6 +106,8 @@ class ValueGenerator: ) if algorithm == "alphanumeric": return self.generate_secure_alphanumeric(64) + if algorithm == "sk_prefixed": + return "sk-" + self.generate_secure_alphanumeric(48) if algorithm == "base64_prefixed_32": return "base64:" + base64.b64encode(secrets.token_bytes(32)).decode() if algorithm == "vapid_private": diff --git a/utils/networks/attachments.py b/utils/networks/attachments.py index 89dd1971ce..bbaacadda9 100644 --- a/utils/networks/attachments.py +++ b/utils/networks/attachments.py @@ -10,6 +10,8 @@ from __future__ import annotations from typing import TYPE_CHECKING, Any +from utils.roles.entity.name import get_entity_name + if TYPE_CHECKING: from collections.abc import Callable @@ -22,7 +24,24 @@ def _is_consumer( ) -> bool: overlay = entry.get("overlay") or {} consumer = overlay.get("consumer") or {} - kind = consumer.get("kind") or "services_flags" + declared = consumer.get("kind") or "services_flags" + kinds = declared if isinstance(declared, list) else [declared] + return any( + _matches_kind( + str(kind), entry, consumer, application_id, lookup_config, lookup_database + ) + for kind in kinds + ) + + +def _matches_kind( + kind: str, + entry: dict[str, Any], + consumer: dict[str, Any], + application_id: str, + lookup_config: Callable[[str, str, Any], Any], + lookup_database: Callable[[str, str], Any], +) -> bool: if kind == "database": if not _coerce_bool(lookup_database(application_id, "enabled")): return False @@ -38,6 +57,26 @@ def _is_consumer( ): return False return True + if kind == "mcp_client": + if not _coerce_bool(lookup_config(application_id, "mcp.enabled", False)): + return False + if not _coerce_bool(lookup_config(application_id, "mcp.shared", False)): + return False + direction = str( + lookup_config(application_id, "mcp.direction", "") or "" + ).strip() + if direction not in ("client", "both"): + return False + consumer_key = get_entity_name(application_id) + if ( + lookup_config(application_id, f"services.{consumer_key}.mcp_consumer", None) + is not True + ): + return False + refusal = lookup_config( + entry.get("role") or "", f"services.{consumer_key}.mcp_consumer", True + ) + return refusal is not False if kind == "onion_sso": provider = consumer.get("provider") if not provider: @@ -152,3 +191,34 @@ def _compute_attachments( ) return attachments, default_aliases + + +def _suppress_default( + application_id: str, lookup_database: Callable[[str, str], Any] +) -> bool: + if not application_id.startswith(("svc-db-", "svc-ai-")): + return False + return not bool(lookup_database(application_id, "local")) + + +def _own_shared_net_provider( + attachments: list[dict[str, Any]], + own_entity: str, + get_entity_name: Callable[[str], str], +) -> bool: + return any( + att["is_provider"] + and att["topology"] == "shared_net" + and get_entity_name(att["role"]) == own_entity + for att in attachments + ) + + +def _shared_network_key( + attachments: list[dict[str, Any]], + own_entity: str, + get_entity_name: Callable[[str], str], +) -> str: + if _own_shared_net_provider(attachments, own_entity, get_entity_name): + return own_entity + return "default" diff --git a/utils/networks/render.py b/utils/networks/render.py index a399aaae6e..10fc049197 100644 --- a/utils/networks/render.py +++ b/utils/networks/render.py @@ -13,8 +13,15 @@ discovered into the service_registry by ``discover_role_services``. Keys: * ``topology``: ``shared_net`` | ``default_net``. Absent = beacon-only (no attachment) * ``aliases``: list of DNS aliases. Default: ``[entity_name]`` for shared_net, ``[]`` for default_net * ``consumer``: optional override - * ``kind``: ``services_flags`` (default) | ``database`` | ``web_facing`` | - ``onion_sso`` + * ``kind``: ``services_flags`` (default) | ``database`` | ``mcp_client`` + | ``web_facing`` | ``onion_sso``. ``mcp_client`` admits a role only when + its ``mcp.direction`` is ``client`` or ``both`` AND it declares + ``services.<own-entity>.mcp_consumer: true`` without the provider + refusing it through ``mcp_consumer: false`` on that same entry, so a + provider's network carries the clients + it admitted rather than every client in the deployment. Being a client is + not an admission: without the second condition one admission anywhere + reaches every provider that opens its overlay. * ``key``: services.<key>.* lookup base. Default: provides or entity_name * ``flags``: list of flags to AND. Default: ``[enabled, shared]`` (``services_flags`` only) @@ -41,12 +48,17 @@ from utils.networks.attachments import ( _coerce_bool, _compute_attachments, _is_consumer, + _own_shared_net_provider, + _shared_network_key, + _suppress_default, ) __all__ = [ "_coerce_bool", "_compute_attachments", "_is_consumer", + "_own_shared_net_provider", + "_suppress_default", "compute_external_network_roles", "render_compose_networks", "render_container_networks", @@ -54,33 +66,6 @@ __all__ = [ ] -def _suppress_default(application_id: str) -> bool: - return application_id.startswith(("svc-db-", "svc-ai-")) - - -def _own_shared_net_provider( - attachments: list[dict[str, Any]], - own_entity: str, - get_entity_name: Callable[[str], str], -) -> bool: - return any( - att["is_provider"] - and att["topology"] == "shared_net" - and get_entity_name(att["role"]) == own_entity - for att in attachments - ) - - -def _shared_network_key( - attachments: list[dict[str, Any]], - own_entity: str, - get_entity_name: Callable[[str], str], -) -> str: - if _own_shared_net_provider(attachments, own_entity, get_entity_name): - return own_entity - return "default" - - def shared_network_compose_key( *, application_id: str, @@ -174,7 +159,7 @@ def render_compose_networks( is_own_shared_net_provider = ( _shared_network_key(attachments, own_entity, get_entity_name) == own_entity ) - if not _suppress_default(application_id): + if not _suppress_default(application_id, lookup_database): lines.append(" default:") if deployment_mode == "swarm": if not is_own_shared_net_provider and own_entity: @@ -203,6 +188,9 @@ def render_compose_networks( lines.append(" config:") lines.append(f" - subnet: {subnet}") + if len(lines) == 1: + return "" + return "\n".join(lines) + "\n" @@ -216,6 +204,7 @@ def render_container_networks( lookup_database: Callable[[str, str], Any], provider_self_alias: bool = True, node_local: bool = False, + own_network_only: bool = False, ) -> str: if node_local: deployment_mode = "compose" @@ -226,6 +215,8 @@ def render_container_networks( for att in attachments: if att["is_provider"] and att["topology"] == "default_net": continue + if own_network_only and not att["is_provider"]: + continue lines.append(f" {get_entity_name(att['role'])}:") aliases = att["aliases"] if att["is_provider"] and not provider_self_alias: @@ -236,7 +227,12 @@ def render_container_networks( else: lines.append(" {}") - if not _suppress_default(application_id): + if own_network_only: + if len(lines) == 1: + return "" + return "\n" + "\n".join(lines) + + if not _suppress_default(application_id, lookup_database): if default_aliases: lines.append(" default:") lines.append(" aliases:") @@ -244,4 +240,7 @@ def render_container_networks( else: lines.append(" default:") + if len(lines) == 1: + return "" + return "\n" + "\n".join(lines) diff --git a/utils/roles/applications/in_group_deps.py b/utils/roles/applications/in_group_deps.py index 74cbdbdb4a..448f856bc2 100644 --- a/utils/roles/applications/in_group_deps.py +++ b/utils/roles/applications/in_group_deps.py @@ -94,20 +94,31 @@ def _collect_reachable_roles( ) -def applications_if_group_and_all_deps( +def reachable_roles( applications: dict[str, Any], - group_names: list[str], + seeds: list[str], *, project_root: str | None = None, roles_dir: str | None = None, service_registry: dict[str, Any] | None = None, meta_deps_resolver: MetaDepsResolver | None = None, blocked: frozenset[str] | set[str] | None = None, -) -> dict[str, Any]: +) -> set[str]: + """Return every role reachable from ``seeds`` through meta and service edges. + + Args: + applications: the merged applications map. + seeds: role ids to start the traversal from. + project_root: repository root, used to derive ``roles_dir`` and registry. + roles_dir: roles directory, when it is not derived from ``project_root``. + service_registry: prebuilt registry, otherwise built from the inputs. + meta_deps_resolver: reads a role's ``meta/main.yml`` dependencies. + blocked: roles the traversal must not enter. + """ if not isinstance(applications, dict): raise TypeError("'applications' must be a mapping") - if not isinstance(group_names, list): - raise TypeError("'group_names' must be a list") + if not isinstance(seeds, list): + raise TypeError("'seeds' must be a list") if not project_root and not roles_dir: raise ValueError("'project_root' or 'roles_dir' must be provided") @@ -126,21 +137,42 @@ def applications_if_group_and_all_deps( elif not isinstance(service_registry, dict): raise ValueError("'service_registry' must be a mapping") - meta_deps_resolver = meta_deps_resolver or meta_deps_from_disk + resolver = meta_deps_resolver or meta_deps_from_disk blocked_roles = frozenset(blocked or ()) included: set[str] = set() - for group in group_names: + for seed in seeds: _collect_reachable_roles( - group, + seed, applications, service_registry, roles_dir, included, - meta_deps_resolver, + resolver, blocked_roles, ) + return included + +def applications_if_group_and_all_deps( + applications: dict[str, Any], + group_names: list[str], + *, + project_root: str | None = None, + roles_dir: str | None = None, + service_registry: dict[str, Any] | None = None, + meta_deps_resolver: MetaDepsResolver | None = None, + blocked: frozenset[str] | set[str] | None = None, +) -> dict[str, Any]: + included = reachable_roles( + applications, + group_names, + project_root=project_root, + roles_dir=roles_dir, + service_registry=service_registry, + meta_deps_resolver=meta_deps_resolver, + blocked=blocked, + ) return { key: cfg for key, cfg in applications.items() diff --git a/utils/roles/applications/mcp.py b/utils/roles/applications/mcp.py new file mode 100644 index 0000000000..a9cb32f1a8 --- /dev/null +++ b/utils/roles/applications/mcp.py @@ -0,0 +1,462 @@ +"""Vocabulary of the ``mcp`` block in ``meta/services.yml``. + +Every role with an ``application_id`` declares exactly one ``mcp:`` entry. +The block is an audit disposition first and a deployable surface second: +``classification`` states what the role is, and only a deployable +classification may also carry ``enabled``/``shared`` and a served contract. + +Field vocabulary (see ``docs/contributing/design/role/services/mcp.md``): + +* ``classification``: what this role is in the MCP audit. Required. +* ``reason``: why a non-deployable classification cannot serve. +* ``direction``: whether the role exposes MCP, consumes it, or both. +* ``transport``: wire protocol of the endpoint. +* ``exposure``: who may reach the endpoint. +* ``auth``: authentication scheme guarding the endpoint. +* ``auth_subject``: identity MCP calls execute as. ``user`` and ``oidc`` + additionally require a ``delegation`` block, because a rendered deployment + bearer is a service account no matter what the metadata claims. +* ``delegation``: recorded proof, at one exact upstream version, that + per-user token acquisition, refresh, audience binding and revocation exist. +* ``implementation``: how the surface is provided, ordered by precedence. +* ``credential``: which principal the provider authenticates as, and + where its secret is read from. Replaces the administrator token path. +Admission is not declared here. A client marks itself once, in its own +``meta/services.yml`` self-entry, as ``mcp_consumer: true``; a provider +deviates by carrying ``mcp_consumer: false`` on that client's entry in its +own ``meta/services.yml``. ``derive_allowed_consumers`` resolves the pair. + +* ``supported_transports`` / ``supported_auths``: what a client can present. +* ``endpoint``: connection metadata for clients (server roles only). +* ``adapter``: immutable source contract of a repository-owned adapter. + ``category_allowlist`` suits an upstream that switches whole categories and + offers no per-tool filter, where a tool allowlist would be unenforceable; + ``mcp_passthrough`` fronts an upstream that already speaks MCP instead of + translating REST. ``upstream_path`` names that upstream where it lives on the + application's own vhost, so the proxy can hide it: reaching it directly walks + past the allowlist the adapter exists to enforce. A provider whose upstream is + a separate sidecar declares ``upstream_network`` instead and has nothing to + hide there. +* ``limits``: the request, response, timeout, concurrency, pagination + and stream ceilings the surface enforces. +* ``tools``: ``allowlist`` is what a reader may reach and + ``writer_allowlist`` what a writer may reach; the deployment renders one + contract per role, each with its own bearer, because the gateway tells + callers apart by credential and by nothing else. ``allowlist`` is policy, + what the platform lets a consumer + reach, and is only a constraint where a gateway enforces it. ``upstream_serves`` + is the observation: every tool the upstream offers at the deployed version. + State it only where it DIFFERS from the allowlist; absence means the two are + identical, which is the normal case for a provider that serves exactly what is + allowed. The difference between them measures unenforced exposure, and a + provider whose difference is non-empty needs a gateway in front. Plus schema + hash and mutation policy. +* ``mutating_proofs``: required once ``tools.mutating_tools_enabled`` is true. + Names the artifact proving each of confirmation, authorization, idempotency, + audit and reversal for the mutating variant, separately from the read-only + one. +* ``source_url``: upstream documentation or source of the MCP surface. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from utils.roles.entity.name import get_entity_name + +if TYPE_CHECKING: + from collections.abc import Mapping + +MCP_DIRECTIONS = frozenset({"server", "client", "both"}) +MCP_TRANSPORTS = frozenset({"streamable_http", "sse"}) +MCP_EXPOSURES = frozenset({"internal", "public"}) +MCP_AUTHS = frozenset( + {"oidc", "app_password", "basic_auth", "bearer_token", "upstream_session", "none"} +) +MCP_AUTH_SUBJECTS = frozenset({"user", "service_account", "administrator", "none"}) +MCP_IMPLEMENTATIONS = frozenset({"native", "plugin", "sidecar", "adapter", "external"}) + +MCP_CLASSIFICATIONS = frozenset( + { + "native_server", + "native_client", + "native_both", + "plugin_server", + "sidecar_server", + "adapter_server", + "adapter_candidate", + "blocked", + "enabler", + "subordinate", + "no_surface", + } +) + +MCP_DEPLOYABLE_CLASSIFICATIONS = frozenset( + { + "native_server", + "native_client", + "native_both", + "plugin_server", + "sidecar_server", + "adapter_server", + } +) + +MCP_AUDIT_ONLY_CLASSIFICATIONS = MCP_CLASSIFICATIONS - MCP_DEPLOYABLE_CLASSIFICATIONS + +MCP_CLIENT_CLASSIFICATIONS = frozenset({"native_client", "native_both"}) + +MCP_REASONS = frozenset( + { + "no_remote_surface", + "host_execution_boundary", + "privileged_control_plane", + "shared_engine_isolation", + "administrative_surface", + "duplicate_owner", + "version_unverified", + "licence", + "hosted_only", + "stdio_only", + "interactive_browser_session", + "unreviewed_third_party", + "missing_dependency", + } +) + +MCP_ADAPTER_TYPES = frozenset( + { + "openapi_allowlist", + "graphql_allowlist", + "named_query", + "s3_prefix", + "prometheus_readonly", + "n8n_workflow", + "resource_readonly", + "category_allowlist", + "mcp_passthrough", + } +) + +MCP_UPSTREAM_MCP_ADAPTER_TYPES = frozenset({"mcp_passthrough"}) + +MCP_SCOPED_ADAPTER_TYPES = frozenset( + {"graphql_allowlist", "named_query", "s3_prefix", "resource_readonly"} +) + +MCP_SPECIFICATION_ADAPTER_TYPES = frozenset({"openapi_allowlist", "graphql_allowlist"}) + +MCP_CREDENTIAL_SOURCES = frozenset({"token_store", "credentials"}) +MCP_SOURCE_TOKEN_STORE = "token_store" # noqa: S105 - a source name, not a secret +MCP_SOURCE_CREDENTIALS = "credentials" +MCP_FORBIDDEN_CREDENTIAL_OWNER = "administrator" + +MCP_KEYS = frozenset( + { + "enabled", + "shared", + "classification", + "reason", + "direction", + "transport", + "exposure", + "auth", + "auth_subject", + "delegation", + "implementation", + "credential", + "supported_transports", + "supported_auths", + "endpoint", + "adapter", + "limits", + "tools", + "mutating_proofs", + "source_url", + } +) + +MCP_ENDPOINT_KEYS = frozenset( + { + "service_key", + "path", + "port_key", + "host_header", + } +) + +MCP_CREDENTIAL_KEYS = frozenset({"owner", "source", "key"}) + +MCP_DELEGATION_KEYS = frozenset( + { + "verified_version", + "source_url", + "refresh", + "revocation", + "audience_binding", + } +) + +MCP_DELEGATION_PROOF_KEYS = frozenset({"refresh", "revocation", "audience_binding"}) + +MCP_ADAPTER_KEYS = frozenset( + { + "type", + "upstream_api_version", + "upstream_network", + "specification_path", + "specification_sha256", + "scope", + "upstream_transport", + "upstream_path", + } +) + +MCP_ADAPTER_REQUIRED_KEYS = frozenset({"type"}) + +MCP_LIMITS_KEYS = frozenset( + { + "request_bytes", + "response_bytes", + "timeout_seconds", + "concurrent_requests", + "page_size", + "result_items", + "stream_seconds", + } +) + +MCP_TOOLS_KEYS = frozenset( + { + "allowlist", + "mutating", + "writer_allowlist", + "upstream_serves", + "categories", + "schema_sha256", + "read_only_default", + "mutating_tools_enabled", + "read_probe", + } +) + +MCP_READ_PROBE_KEYS = frozenset({"tool", "arguments"}) + +MCP_TOOLS_BOOLEAN_KEYS = frozenset({"read_only_default", "mutating_tools_enabled"}) + +MCP_SERVER_DIRECTIONS = frozenset({"server", "both"}) +MCP_CLIENT_DIRECTIONS = frozenset({"client", "both"}) +MCP_REQUIRED_ENDPOINT_KEYS = frozenset({"service_key", "path", "port_key"}) +MCP_PRIVILEGED_AUTH_SUBJECTS = frozenset({"service_account", "administrator"}) +MCP_DELEGATED_AUTH_SUBJECTS = frozenset({"user"}) +MCP_DELEGATED_AUTHS = frozenset({"oidc"}) + +MCP_FORBIDDEN_SURFACE_MARKERS = ( + "docker.sock", + "/var/run/", + "unix:", + "file://", + "sh -c", + "bash -c", + "${", + "*", +) + +MCP_SHA256_PREFIX = "sha256:" + +DEFAULT_MCP_TRANSPORT = "streamable_http" + + +MCP_CONSUMER_FLAG = "mcp_consumer" + + +def value_is_templated(value: object) -> bool: + return isinstance(value, str) and "{{" in value + + +def declares_mcp_consumer(role_id: str, services: object) -> bool: + """Return whether a role marks itself an MCP client in its own services. + + Args: + role_id: the role's ``application_id``. + services: that role's ``services`` mapping, or anything else. + """ + if not isinstance(services, dict): + return False + entry = services.get(get_entity_name(role_id)) + return isinstance(entry, dict) and entry.get(MCP_CONSUMER_FLAG) is True + + +def admits_mcp_consumer(provider_services: object, consumer_id: str) -> bool: + """Return whether a provider admits one client. + + An omitted flag inherits the client's own declaration; only an explicit + ``mcp_consumer: false`` excludes, so a deliberate exclusion is + distinguishable from a forgotten entry. + + Args: + provider_services: the provider's ``services`` mapping. + consumer_id: the client's ``application_id``. + """ + if not isinstance(provider_services, dict): + return True + entry = provider_services.get(get_entity_name(consumer_id)) + if isinstance(entry, dict) and MCP_CONSUMER_FLAG in entry: + return entry[MCP_CONSUMER_FLAG] is True + return True + + +def derive_allowed_consumers( + provider_id: str, services_by_role: dict[str, object] +) -> list[str]: + """Return the client application ids a provider admits, sorted. + + Args: + provider_id: the provider's ``application_id``. + services_by_role: every role's ``services`` mapping, keyed by role id. + """ + provider_services = services_by_role.get(provider_id) + return sorted( + role_id + for role_id, services in services_by_role.items() + if role_id != provider_id + and declares_mcp_consumer(role_id, services) + and admits_mcp_consumer(provider_services, role_id) + ) + + +def derive_mcp_presence(applications: dict[str, Any]) -> dict[str, Any]: + """Materialise every ``mcp`` topic's enable state from its declared peers. + + Args: + applications: ``{application_id: config}``, mutated in place. + + Returns: + The same mapping. + + A surface is reachable only while a peer that uses it is deployed, so both + keys resolve to the ``in group_names`` form the rest of the tree uses, and + to ``False`` when a role has no peer at all. An explicitly configured + ``enabled``/``shared`` always wins, so config stays the override channel. + Keying on peer PRESENCE rather than on a peer's own value is required: a + re-entrant read under ``_RENDER_GUARD`` returns the unrendered dict. + + The resolved block replaces the mapping rather than being written into it. + ``_build_role_base_config`` parks the YAML cache's own object under ``mcp``, + so an in-place write would inject these keys into every later raw read of + ``meta/mcp.yml``. + """ + blocks = { + role_id: config["mcp"] + for role_id, config in applications.items() + if isinstance(config, dict) and isinstance(config.get("mcp"), dict) + } + services_by_role = { + role_id: (config or {}).get("services") + for role_id, config in applications.items() + if isinstance(config, dict) + } + for role_id, block in blocks.items(): + direction = str(block.get("direction") or "").lower() + peers: set[str] = set() + if direction in ("server", "both"): + peers |= set(derive_allowed_consumers(role_id, services_by_role)) + if direction in ("client", "both") and declares_mcp_consumer( + role_id, services_by_role.get(role_id) + ): + peers |= { + peer + for peer, peer_block in blocks.items() + if peer != role_id + and str(peer_block.get("direction") or "").lower() in ("server", "both") + and admits_mcp_consumer(services_by_role.get(peer), role_id) + } + value: Any = ( + "{{ " + " or ".join(f"'{p}' in group_names" for p in sorted(peers)) + " }}" + if peers + else False + ) + resolved = dict(block) + resolved.setdefault("enabled", value) + resolved.setdefault("shared", value) + applications[role_id]["mcp"] = resolved + return applications + + +def is_deployable(mcp: object) -> bool: + """Return whether this block may carry a served surface and be discovered. + + Args: + mcp: the role's ``mcp`` mapping, or anything else. + """ + if not isinstance(mcp, dict): + return False + return mcp.get("classification") in MCP_DEPLOYABLE_CLASSIFICATIONS + + +def declares_delegation(mcp: object) -> bool: + """Return whether this block claims to act as the requesting end user. + + Args: + mcp: the role's ``mcp`` mapping, or anything else. + """ + if not isinstance(mcp, dict): + return False + return ( + mcp.get("auth_subject") in MCP_DELEGATED_AUTH_SUBJECTS + or mcp.get("auth") in MCP_DELEGATED_AUTHS + ) + + +def delegation_is_proven(mcp: object) -> bool: + """Return whether a recorded per-version audit backs the delegation claim. + + Args: + mcp: the role's ``mcp`` mapping, or anything else. + """ + if not isinstance(mcp, dict): + return False + delegation = mcp.get("delegation") + if not isinstance(delegation, dict): + return False + if not str(delegation.get("verified_version") or "").strip(): + return False + if not str(delegation.get("source_url") or "").strip(): + return False + return all(delegation.get(key) is True for key in MCP_DELEGATION_PROOF_KEYS) + + +def resolve_credential( + server: Mapping[str, Any], + users: Mapping[str, Any], + role_credentials: Mapping[str, Any], +) -> tuple[str, str]: + """Return the provider's declared secret and the owner it belongs to. + + Args: + server: a discovered ``direction=server`` entry. + users: the merged users mapping, carrying each principal's tokens. + role_credentials: the provider role's own ``secrets.credentials`` + mapping, which is where every other consumer addresses them. + + Returns an empty token when the declaration is incomplete or the principal + holds nothing; the caller turns that into ``credential_missing``. + """ + credential = server.get("credential") or {} + owner = str(credential.get("owner") or "").strip() + source = str(credential.get("source") or "").strip() + key = str(credential.get("key") or "").strip() + if not owner or not source or not key or owner == MCP_FORBIDDEN_CREDENTIAL_OWNER: + return "", owner + + if source == MCP_SOURCE_TOKEN_STORE: + principal = users.get(owner) + tokens = principal.get("tokens") if isinstance(principal, dict) else None + value = (tokens or {}).get(key) if isinstance(tokens, dict) else None + return str(value or "").strip(), owner + + if source == MCP_SOURCE_CREDENTIALS: + return str(role_credentials.get(key) or "").strip(), owner + + return "", owner diff --git a/utils/roles/applications/mounts.py b/utils/roles/applications/mounts.py index dcb6b46182..1f33dd9d35 100644 --- a/utils/roles/applications/mounts.py +++ b/utils/roles/applications/mounts.py @@ -22,6 +22,13 @@ Canonical shape (dict-of-dicts; the YAML key is the semantic short name): - service: synapse target: /etc/synapse/config + scratch: + type: tmpfs + mounts: + - service: synapse + target: /var/run/synapse + size: 64m # per-mount tmpfs size + The legacy list-of-dicts shape is no longer accepted. """ @@ -45,6 +52,13 @@ class VolumesSchemaError(ValueError): """Raised when a meta/volumes.yml fails schema validation.""" +def _is_octal_mode(value: Any) -> bool: + """True when ``value`` is a leading-zero octal permission string.""" + return ( + isinstance(value, str) and value.startswith("0") and value.lstrip("0").isdigit() + ) + + def normalize_volumes_meta( meta_volumes: Any, ) -> dict[str, dict[str, Any]]: @@ -120,16 +134,15 @@ def validate_volumes_meta( violations.append( f"{prefix}: 'mode' is only valid for type config/secret (got type={vtype!r})" ) - if "mode" in entry and vtype in _TYPE_HAS_MODE: - mode = entry["mode"] - if not ( - isinstance(mode, str) - and mode.startswith("0") - and mode.lstrip("0").isdigit() - ): - violations.append( - f"{prefix}: 'mode' must be an octal string like \"0440\", got {mode!r}" - ) + if ( + "mode" in entry + and vtype in _TYPE_HAS_MODE + and not _is_octal_mode(entry["mode"]) + ): + violations.append( + f"{prefix}: 'mode' must be an octal string like \"0440\", " + f"got {entry['mode']!r}" + ) if "read_only" in entry and vtype not in _TYPE_HAS_READ_ONLY: violations.append( @@ -176,6 +189,12 @@ def validate_volumes_meta( for mount in (entry.get("mounts") or []) if "size" in mount and not isinstance(mount["size"], (str, int)) ) + violations.extend( + f"{prefix}: tmpfs 'mode' must be an octal string or int, got " + f"{type(mount['mode']).__name__}" + for mount in (entry.get("mounts") or []) + if "mode" in mount and not isinstance(mount["mode"], (str, int)) + ) mounts = entry.get("mounts") if mounts is None: diff --git a/utils/roles/applications/services/config.py b/utils/roles/applications/services/config.py index cd34fcf540..3bb3d85dbd 100644 --- a/utils/roles/applications/services/config.py +++ b/utils/roles/applications/services/config.py @@ -17,8 +17,6 @@ from utils.roles.applications.services.registry import ( build_service_registry_from_applications, ) -_MISSING = object() - def _service_entry( applications: dict[str, Any], diff --git a/utils/roles/applications/services/database.py b/utils/roles/applications/services/database.py index 2025e52775..8ebd461fa5 100644 --- a/utils/roles/applications/services/database.py +++ b/utils/roles/applications/services/database.py @@ -7,6 +7,9 @@ if TYPE_CHECKING: RDBMS_SERVICE_KEYS = ("mariadb", "postgres") +REALIGN_CONFIG_KEY = "database_realign" +REALIGN_TARGET = "/etc/mysql/realign.sql" + def _as_mapping(value: Any) -> dict[str, Any]: return value if isinstance(value, dict) else {} diff --git a/utils/roles/applications/services/registry.py b/utils/roles/applications/services/registry.py index 561ce13652..484bf2ada3 100644 --- a/utils/roles/applications/services/registry.py +++ b/utils/roles/applications/services/registry.py @@ -28,10 +28,21 @@ def _normalized_name(value: Any) -> str: return value.strip() +GROUP_GATED_CONSTANTS: tuple[str, ...] = ("LITELLM_USABLE",) +"""Group_vars constants whose own definition carries an ``in group_names`` +gate, so a flag referencing one is dynamic even though its own text is not. + +A constant hides the role id the substring rule looks for, so every SPOT of +this kind MUST be listed here or the roles referencing it silently drop their +provider from the static closure. +""" + + def is_explicit_truth(value: Any) -> bool: """A services.<key> flag (``enabled`` / ``shared``) MAY be true if it - is the literal Python ``True`` OR any string containing the substring - ``in group_names``. Negated and compound predicates + is the literal Python ``True``, any string containing the substring + ``in group_names``, or a string referencing a `GROUP_GATED_CONSTANTS` + entry. Negated and compound predicates (``"{{ 'X' not in group_names }}"``) match on purpose: they are true on some node shape, and the static closure is the co-deploy superset. Mirrors the substring test at @@ -47,7 +58,11 @@ def is_explicit_truth(value: Any) -> bool: """ if value is True: return True - return bool(isinstance(value, str) and "in group_names" in value) + if not isinstance(value, str): + return False + return "in group_names" in value or any( + constant in value for constant in GROUP_GATED_CONSTANTS + ) def detect_service_channel(role_name: str) -> str: diff --git a/utils/roles/applications/services/resources.py b/utils/roles/applications/services/resources.py index a3da6b8ee2..e6e61978bf 100644 --- a/utils/roles/applications/services/resources.py +++ b/utils/roles/applications/services/resources.py @@ -15,6 +15,7 @@ from typing import Any from humanfriendly import parse_size +from utils.roles.applications.topics import apply_topic from utils.roles.entity.name import get_entity_name _RESOURCE_KEYS = ("mem_reservation", "mem_limit", "pids_limit", "cpus") @@ -166,6 +167,7 @@ def collect_role_resources( ) shared_dependencies: list[str] = [] + nested_maps: dict[str, dict[str, Any]] = {} for service_key, raw_service_conf in services.items(): if service_key == entity_name: continue @@ -185,6 +187,8 @@ def collect_role_resources( add(service_key, service_conf) elif provider_role and provider_role != role_name: shared_dependencies.append(provider_role) + if "services" in service_conf: + nested_maps[provider_role] = service_conf["services"] elif _is_shared(service_conf): warnings.append( f"{role_name}: shared service '{service_key}' has no registered provider" @@ -196,9 +200,18 @@ def collect_role_resources( return for provider_role in shared_dependencies: + scoped = applications + if provider_role in nested_maps: + demanded = nested_maps[provider_role] + provider_conf = dict(_as_mapping(applications.get(provider_role))) + provider_conf["services"] = apply_topic( + provider_conf.get("services"), demanded + ) + scoped = dict(applications) + scoped[provider_role] = provider_conf collect_role_resources( provider_role, - applications, + scoped, service_registry, visited, rows, diff --git a/utils/roles/applications/services/sso.py b/utils/roles/applications/services/sso.py index d447352bc7..e4dd220e9f 100644 --- a/utils/roles/applications/services/sso.py +++ b/utils/roles/applications/services/sso.py @@ -19,6 +19,7 @@ literal-protocol-lookup and lookup-config-path static-scan guards). from __future__ import annotations from typing import TYPE_CHECKING, Any +from urllib.parse import quote from utils.roles.applications.config import get @@ -28,6 +29,7 @@ if TYPE_CHECKING: _DEFAULT_FLAVOR = "oidc" _VALID_FLAVORS = frozenset({"oidc", "oauth2", "saml"}) +OAUTH2_SIGN_OUT_PATH = "/oauth2/sign_out" def is_potentially_enabled(value: Any) -> bool: @@ -52,6 +54,20 @@ def is_potentially_enabled(value: Any) -> bool: return not (isinstance(value, str) and value.strip().lower() == "false") +def _as_bool(value: Any) -> bool: + """Coerce a merged-payload flag to bool. + + Args: + value: the raw value, which may still be the string a template rendered. + + Returns: + True only for a literal True or a string spelling an affirmative. + """ + if isinstance(value, str): + return value.strip().lower() in ("true", "1", "yes", "on") + return bool(value) + + def _get(applications: Mapping[str, Any], app_id: str, path: str, default: Any) -> Any: """Thin wrapper around ``get`` with the lenient flags this module uses.""" return get( @@ -82,6 +98,9 @@ def get_sso_config( oauth2_origin_port str โ€” ``services.sso.oauth2.origin.port`` or '' oauth2_acl dict โ€” ``services.sso.oauth2.acl`` or {} oauth2_allowed_groups list โ€” ``services.sso.oauth2.allowed_groups`` or [] + oauth2_pass_access_token bool โ€” ``services.sso.oauth2.pass_access_token``, + default False: the gate hands the upstream a + bearer token only where the app decodes one The compound predicates are the documented call surface โ€” call sites should prefer ``is_proxy_gated`` over manually combining @@ -106,6 +125,9 @@ def get_sso_config( raw_allowed_groups = _get( applications, application_id, "services.sso.oauth2.allowed_groups", [] ) + raw_pass_access_token = _get( + applications, application_id, "services.sso.oauth2.pass_access_token", False + ) return { "enabled": enabled, @@ -123,4 +145,17 @@ def get_sso_config( if isinstance(raw_allowed_groups, (list, tuple)) else [] ), + "oauth2_pass_access_token": _as_bool(raw_pass_access_token), } + + +def logout_url(oidc_logout_url: str, is_proxy_gated: bool) -> str: + """Return the logout target of an application's own logout control. + + Args: + oidc_logout_url: the identity provider's end-session endpoint. + is_proxy_gated: whether oauth2-proxy fronts the application. + """ + if not is_proxy_gated: + return oidc_logout_url + return f"{OAUTH2_SIGN_OUT_PATH}?rd={quote(oidc_logout_url, safe='/')}" diff --git a/utils/roles/applications/status_codes.py b/utils/roles/applications/status_codes.py new file mode 100644 index 0000000000..79aae9e57a --- /dev/null +++ b/utils/roles/applications/status_codes.py @@ -0,0 +1,119 @@ +"""HTTP status codes for a deployed domain. + +``roles/<app>/meta/server.yml`` declares ``status_codes`` keyed like +``domains.canonical``; it is the single source of truth for every prober. +""" + +from __future__ import annotations + +from collections.abc import Mapping + +from utils.roles.applications.config import get + +DEFAULT_OK = [200, 302, 301] + + +def normalize_codes(value) -> list[int]: + """Return *value* as a list of plausible HTTP status codes. + + Args: + value: a scalar, list or mapping straight out of the declaration. + + Returns: + The codes as de-duplicated integers, dropping anything outside 100-599. + """ + if value is None: + return [] + candidates = value if isinstance(value, (list, tuple, set)) else [value] + codes: list[int] = [] + for candidate in candidates: + if isinstance(candidate, bool): + continue + try: + code = int(candidate) + except (TypeError, ValueError): + continue + if 100 <= code <= 599 and code not in codes: + codes.append(code) + return codes + + +def codes_by_key(raw) -> dict[str, list[int]]: + """Normalize a raw ``server.status_codes`` declaration. + + Args: + raw: the declaration as read from the app config. + + Returns: + The declared keys mapped to their codes, dropping keys that declare + nothing usable. + """ + if not isinstance(raw, Mapping): + return {} + resolved: dict[str, list[int]] = {} + for key, value in raw.items(): + codes = normalize_codes(value) + if codes: + resolved[str(key)] = codes + return resolved + + +def declared_status_codes(applications, app_id: str, domain: str) -> list[int]: + """Return what *app_id* declares for *domain*, or an empty list. + + The vhost is identified by the ``domains.canonical`` key that carries the + domain, which is the same key ``server.status_codes`` uses. A domain that + is not canonical, or a key that declares nothing, falls back to the + declared ``default``. + + Args: + applications: the applications SPOT. + app_id: the role the domain belongs to. + domain: the fully qualified domain being probed. + + Returns: + The declared codes, empty when the app declares none for this domain. + """ + declared = codes_by_key( + get(applications, app_id, "server.status_codes", strict=False, default={}) + ) + if not declared: + return [] + + wanted = str(domain or "").strip() + canonical = get(applications, app_id, "domains.canonical", strict=False, default=[]) + if wanted and isinstance(canonical, Mapping): + for key, domains in canonical.items(): + entries = domains if isinstance(domains, (list, tuple, set)) else [domains] + if wanted in {str(entry).strip() for entry in entries if entry}: + codes = declared.get(str(key)) + if codes: + return list(codes) + break + + return list(declared.get("default") or []) + + +def accepted_status_codes(applications, app_id: str, domain: str) -> list[int]: + """Return the codes that prove *domain* is being served at all. + + Most declarations are narrower than :data:`DEFAULT_OK`, so this gate adds + to the default instead of replacing it; narrowing it would escalate vhosts + that answer perfectly well. Contract checking is a different question and + belongs to ``sys-ctl-hlth-webserver``. + + Args: + applications: the applications SPOT. + app_id: the role the domain belongs to. + domain: the fully qualified domain being probed. + + Returns: + :data:`DEFAULT_OK` plus whatever the app declares for this domain. + """ + accepted = list(DEFAULT_OK) + accepted.extend( + code + for code in declared_status_codes(applications, app_id, domain) + if code not in accepted + ) + return accepted diff --git a/utils/roles/applications/topics.py b/utils/roles/applications/topics.py new file mode 100644 index 0000000000..3603e29efd --- /dev/null +++ b/utils/roles/applications/topics.py @@ -0,0 +1,115 @@ +"""The config topics a variant may dictate for the providers it pulls in. + +A round deploys a provider once, so the role that pulls it in is the only +place that can say how lean it has to be. A variant entry may therefore carry +any application config topic under the service it depends on: + + services: + openwebui: + enabled: true + shared: true + services: null # brings nothing along + addons: + whisper: + enabled: false # everything else in addons survives + +A mapping deep-merges, so naming one key changes that key and nothing else. +``null`` empties the topic, which is the only way to say "bring nothing": +merged, an empty mapping is a no-op and would leave exactly the services the +round was trying to shed. + +YAML writes null three ways - ``null``, ``~``, and a key with nothing after +it - so a half-typed line empties a topic rather than being ignored. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +from utils.cache.base import _deep_merge +from utils.cache.yaml import load_yaml_any +from utils.roles.applications.services.registry import ( + build_service_registry_from_roles_dir, +) +from utils.roles.mapping import ROLE_FILE_META_VARIANTS + +CONFIG_TOPICS = frozenset( + { + "addons", + "csp", + "domains", + "group_id", + "info", + "mcp", + "networks", + "packages", + "rbac", + "secrets", + "server", + "services", + "tests", + "users", + } +) + + +def apply_topic(base_value: Any, override_value: Any) -> Any: + """Return a provider's topic after one override is applied. + + Args: + base_value: what the provider declares for the topic today. + override_value: what the pulling role demands. + + ``None`` empties the topic and is normalised to ``{}``: the closure + resolver skips a non-mapping payload, so leaving the bare ``None`` would + silently keep the services it was meant to drop. + """ + if override_value is None: + return {} + return _deep_merge(base_value, override_value) + + +def provider_of(service_key: str, service_registry: Mapping) -> str: + """Return the role providing ``service_key``, or "" when unregistered. + + Args: + service_key: a first-level key of a role's services map. + service_registry: the project-wide service registry. + """ + entry = service_registry.get(service_key) + if not isinstance(entry, Mapping): + return "" + role = entry.get("role") + return str(role).strip() if role else "" + + +def overridden_providers(roles_dir: str | Path) -> dict[tuple[str, int], set[str]]: + """Return ``{(role, variant index): {provider role, ...}}`` across every variant. + + Args: + roles_dir: roles directory the variants and service registry are read from. + + A variant that dictates a provider's config does not deploy that provider as + the provider declares it, so nothing about that run states what the provider + does on its own. Callers that reason about coverage need to know which pairs + those are before they credit one role's deploy to another. + """ + roles_root = Path(roles_dir) + registry = build_service_registry_from_roles_dir(roles_root) + found: dict[tuple[str, int], set[str]] = {} + for path in sorted(roles_root.glob(f"*/{ROLE_FILE_META_VARIANTS}")): + role = path.parent.parent.name + variants = load_yaml_any(str(path), default_if_missing=[]) or [] + for index, variant in enumerate(variants): + services = (variant or {}).get("services") or {} + if not isinstance(services, Mapping): + continue + for service_key, entry in services.items(): + if not isinstance(entry, Mapping) or not CONFIG_TOPICS & set(entry): + continue + target = provider_of(str(service_key), registry) + if target and target != role: + found.setdefault((role, index), set()).add(target) + return found diff --git a/utils/roles/credits.py b/utils/roles/credits.py new file mode 100644 index 0000000000..170509078e --- /dev/null +++ b/utils/roles/credits.py @@ -0,0 +1,118 @@ +"""Attribution recorded in markdown ``## Credits`` sections. + +The link that belongs to a credited person lives nowhere but the Credits +lines themselves: ``galaxy_info.author`` carries the name without a URL, and +``galaxy_info.company`` names the project owner rather than the role's +author, so neither can supply it. This module derives the name -> URL map +from the linked mentions already present in the repository, which keeps the +README generator and the ``credits-attribution`` lint reading the same +source instead of a hand-maintained list. + +Adding a contributor therefore needs no code change: one linked credit +anywhere makes the generator emit that link for every role they author. + +Patterns exported here: + +* ``LINKED_RE`` ``[Name](https://url)`` plus the bold markers a Credits + line wraps it in. +* ``BARE_BOLD_RE`` ``**Name**`` that is not itself a link's text. +* ``PERSON_RE`` a multi-word proper name whose parts carry no dot. The + dot is what separates people from the products and + projects that also appear in Credits lines + ("Infinito.Nexus Project"). A person written with an + initial ("J. Smith") therefore falls out of enforcement + rather than into a false positive, which is the safe + direction for a lint. +""" + +from __future__ import annotations + +import re +from functools import lru_cache +from typing import TYPE_CHECKING + +from utils.cache.files import iter_non_ignored_files, read_text + +if TYPE_CHECKING: + from collections.abc import Iterator + +CREDITS_HEADING_RE = re.compile(r"^##+\s+Credits\s*$", re.IGNORECASE) +ANY_HEADING_RE = re.compile(r"^##+\s+") + +LINKED_RE = re.compile(r"\*{0,2}\[([^\]\[]+)\]\((https?://[^)\s]+)\)\*{0,2}") + +BARE_BOLD_RE = re.compile(r"(?<!\])\*\*([^*\]]+)\*\*(?!\()") + +PERSON_RE = re.compile(r"^[A-Z][\w'-]*(?:\s+[A-Z][\w'-]*)+$") + + +def is_person(name: str) -> bool: + return bool(PERSON_RE.match(name.strip())) + + +def credits_lines(lines: list[str]) -> list[tuple[int, str]]: + """``(1-based line number, text)`` for every line inside a ``## Credits`` + section, ending at the next heading of any level. + + Args: + lines: the file's lines, without trailing newlines. + """ + out: list[tuple[int, str]] = [] + inside = False + for idx, raw in enumerate(lines, start=1): + if CREDITS_HEADING_RE.match(raw): + inside = True + continue + if inside and ANY_HEADING_RE.match(raw): + inside = False + continue + if inside: + out.append((idx, raw)) + return out + + +def collect_author_urls(documents: list[list[str]]) -> dict[str, set[str]]: + """Map every credited person to the set of URLs they are linked with. + + A name with more than one URL is a conflict the caller decides about; + this function reports rather than resolves it. + + Args: + documents: one entry per file, each the file's lines. + """ + urls: dict[str, set[str]] = {} + for lines in documents: + for _line_no, text in credits_lines(lines): + for name, url in LINKED_RE.findall(text): + if is_person(name): + urls.setdefault(name.strip(), set()).add(url) + return urls + + +def iter_markdown_documents() -> Iterator[tuple[str, list[str]]]: + """Yield ``(path, lines)`` for every tracked markdown file. + + Files the process cannot read are skipped rather than raised: this walk + backs the README build, and an unreadable agent scratch file such as + ``.claude/loop.md`` must not abort generating documentation. + """ + for path in iter_non_ignored_files(extensions=(".md",)): + try: + yield path, read_text(path).splitlines() + except OSError: + continue + + +@lru_cache(maxsize=1) +def author_urls() -> dict[str, str]: + """Name -> URL for every person credited with exactly one URL repo-wide. + + Names linked to conflicting URLs are omitted, so an ambiguous mapping + never silently picks a winner. + """ + documents = [lines for _path, lines in iter_markdown_documents()] + return { + name: next(iter(seen)) + for name, seen in collect_author_urls(documents).items() + if len(seen) == 1 + } diff --git a/utils/roles/guide.py b/utils/roles/guide.py new file mode 100644 index 0000000000..94cc49b84b --- /dev/null +++ b/utils/roles/guide.py @@ -0,0 +1,111 @@ +"""Which deploy row replays the role's README instructions, and in what mode. + +The instructions test used to be a job of its own that picked one random role +per run. Riding along on a deploy row instead costs no extra runner and covers +every role the sweep touches. The row it rides on is the role's smallest +variant -- the one enabling the fewest services -- because that is the shape +the README's Production block describes: the bare role, with the optional +providers switched off. + +The replay is a second deploy on the same runner, so the row it picks must be +one the guide can actually deploy: the README has to carry a Production block, +and the guide's own mode (``compose`` for a role that ships a stack, ``host`` +for one installed onto the machine) has to be a mode the role runs and tests. +""" + +from __future__ import annotations + +from functools import cache +from typing import TYPE_CHECKING + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.roles.deploy import role_has_stack +from utils.roles.meta_lookup import get_role_mode_enabled, get_role_test_skips + +if TYPE_CHECKING: + from collections.abc import Collection, Mapping, Sequence + from typing import Any + +PRODUCTION_HEADING = "### Production" +"""The README section :file:`scripts/github/guide/compose_deploy.sh` replays. +A role without it has no instructions to test.""" + + +def _enabled_services(variant: Mapping[str, Any]) -> int: + services = variant.get("services") or {} + return sum( + 1 + for config in services.values() + if isinstance(config, dict) and config.get("enabled") + ) + + +def smallest_variant( + variants: Sequence[Mapping[str, Any]], allowed: Collection[str] | None = None +) -> str: + """The variant that enables the fewest services, as the matrix writes it; + the lowest index wins a tie, and ``''`` means none qualifies. + + Args: + variants: the role's rendered variant configs, in index order. + allowed: the variants this sweep actually deploys. A variant the sweep + cuts as redundant coverage never reaches a runner, so hanging the + replay on it would silently drop the role from the instructions + test; the next-smallest deployed variant carries it instead. + """ + candidates = [ + index + for index in range(len(variants)) + if allowed is None or str(index) in allowed + ] + if not candidates: + return "" + return str( + min(candidates, key=lambda index: (_enabled_services(variants[index]), index)) + ) + + +@cache +def guide_deployable(app: str) -> str: + """The mode the guide would replay *app* in, or ``''`` when it cannot. + + Independent of the variant, and cached: the answer is a property of the + role's files, and :func:`utils.github.variant.axes.assign` asks it once per + row of every chunk. + """ + role_dir = PROJECT_ROOT / "roles" / app + readme = role_dir / "README.md" + if not readme.is_file() or PRODUCTION_HEADING not in read_text(str(readme)): + return "" + mode = "compose" if role_has_stack(role_dir) else "host" + if mode in get_role_test_skips(role_dir, role_name=app): + return "" + if not get_role_mode_enabled(role_dir, mode=mode, role_name=app): + return "" + return mode + + +def guide_variant( + app: str, + variants_per_app: Mapping[str, Sequence[Mapping[str, Any]]] | None, + allowed: Collection[str], +) -> tuple[str, str]: + """The variant of *app* that carries the replay, and the mode it runs in. + + ``('', '')`` when the role has no instructions to replay or this sweep + deploys no variant that could carry them. + + Args: + app: the role. + variants_per_app: rendered variant configs per app; without them no + variant can be told to be the smallest one. + allowed: the variants this sweep deploys, as the matrix writes them. + """ + variants = (variants_per_app or {}).get(app) + if not variants: + return "", "" + mode = guide_deployable(app) + if not mode: + return "", "" + variant = smallest_variant(variants, allowed) + return (variant, mode) if variant else ("", "") diff --git a/utils/roles/mapping.py b/utils/roles/mapping.py index b3ce96a5e9..64ad1b4934 100644 --- a/utils/roles/mapping.py +++ b/utils/roles/mapping.py @@ -142,6 +142,7 @@ def _all( ROLE_FILE_DEFAULTS_MAIN = "defaults/main.yml" ROLE_FILE_HANDLERS_MAIN = "handlers/main.yml" ROLE_FILE_TASKS_MAIN = "tasks/main.yml" +ROLE_FILE_TASKS_MCP = "tasks/utils/mcp.yml" ROLE_FILE_VARS_MAIN = "vars/main.yml" ROLE_FILE_README = "README.md" ROLE_FILE_TEMPL_COMPOSE = "templates/compose.yml.j2" @@ -177,6 +178,7 @@ ROLE_FILE_META_SERVER = "meta/server.yml" ROLE_FILE_META_CSP = "meta/csp.yml" ROLE_FILE_META_DOMAINS = "meta/domains.yml" ROLE_FILE_META_NETWORKS = "meta/networks.yml" +ROLE_FILE_META_MCP = "meta/mcp.yml" ROLE_FILE_META_RBAC = "meta/rbac.yml" ROLE_FILE_META_VOLUMES = "meta/volumes.yml" ROLE_FILE_META_SECRETS = "meta/secrets.yml" @@ -353,6 +355,17 @@ ROLE_FILES: dict[str, dict[str, object]] = { "description": ("Optional dashboard / UI metadata (logo, label) for the role."), "types": _all(mandatory=False), }, + ROLE_FILE_META_MCP: { + "description": ( + "Model Context Protocol capability of the role: direction, transport, " + "auth, credential, tool surface and admitted counterparts. Not a " + "service entry, because no single role provides MCP." + ), + "types": [ + {"type": ROLE_TYPE_APPLICATION, "mandatory": False, "entries": []}, + *_all(allowed=False), + ], + }, ROLE_FILE_META_USERS: { "description": ( "Reserved-username declarations consumed by the user-management layer." diff --git a/utils/roles/rbac/__init__.py b/utils/roles/rbac/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/utils/roles/rbac/scoped.py b/utils/roles/rbac/scoped.py new file mode 100644 index 0000000000..4fdc9b587f --- /dev/null +++ b/utils/roles/rbac/scoped.py @@ -0,0 +1,77 @@ +"""Which role names a user holds on one application. + +Most role names are global: ``roles: [administrator]`` means administrator +everywhere it is declared. ``APPLICATION_SCOPED_ROLES`` are the exception. +Those carry a distinct grant per application, so reading them from the +unscoped list would hand a user every deployed application's copy at once. +They come only from ``application_roles``:: + + users: + alice: + application_roles: + web-app-baserow: [mcp] + +This module is the single source of truth for that rule. The Keycloak realm +group builder, the LDAP role entry builder and the Open WebUI group reconciler +all resolve membership through it, so the three paths cannot drift. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Mapping + +MCP_READER_ROLE = "mcp-reader" +MCP_WRITER_ROLE = "mcp-writer" +MCP_LEGACY_ROLE = "mcp" + +MCP_ROLES = (MCP_READER_ROLE, MCP_WRITER_ROLE) + +APPLICATION_SCOPED_ROLES = frozenset({MCP_LEGACY_ROLE, *MCP_ROLES}) + + +def expand_mcp_role(role_name: str) -> str: + """Return the role a grant confers, resolving the pre-split name. + + Args: + role_name: a role as written in a user's grants. + """ + return MCP_READER_ROLE if role_name == MCP_LEGACY_ROLE else role_name + + +def granted_roles(user_config: Mapping[str, object], application_id: str) -> set[str]: + """Return the role names this user holds on one application. + + Args: + user_config: the user's merged configuration. + application_id: the application whose grants are being resolved. + """ + scoped = (user_config.get("application_roles") or {}).get(application_id) or [] + unscoped = [ + role + for role in (user_config.get("roles") or []) + if role not in APPLICATION_SCOPED_ROLES + ] + return set(unscoped) | set(scoped) | {expand_mcp_role(r) for r in scoped} + + +def members_with_role( + users: Mapping[str, Mapping[str, object]] | None, + application_id: str, + role_name: str, +) -> list[str]: + """Return the usernames holding ``role_name`` on ``application_id``. + + Args: + users: the merged users mapping. + application_id: the application whose grants are being resolved. + role_name: the role to filter by. + """ + members = [] + for username, user_config in (users or {}).items(): + cfg = user_config or {} + if role_name in granted_roles(cfg, application_id): + members.append(str(cfg.get("username", username))) + return sorted(members) diff --git a/utils/symbol_glossary.py b/utils/symbol_glossary.py index eff690c4a3..004cc846b4 100644 --- a/utils/symbol_glossary.py +++ b/utils/symbol_glossary.py @@ -16,6 +16,7 @@ SYMBOLS: dict[str, str] = { "disabled": "โŒ", "skip": "โญ๏ธ", "priority": "โญ", + "instructions": "๐Ÿ“–", "distros": "๐Ÿง", "arch": "๐Ÿน", "debian": "๐ŸŒ€", diff --git a/utils/templating/ansible.py b/utils/templating/ansible.py index bcc7624766..ccf1666673 100644 --- a/utils/templating/ansible.py +++ b/utils/templating/ansible.py @@ -4,6 +4,7 @@ import contextlib import os import posixpath import re +from collections.abc import Mapping, Sequence from typing import Any from ansible.errors import AnsibleError @@ -22,6 +23,33 @@ except Exception: TrustedAsTemplate = None +def to_plain(obj: Any) -> Any: + """Convert Ansible/Jinja proxy types into plain Python so PyYAML can serialize.""" + + if obj is None: + return None + + if isinstance(obj, str): + return str(obj) + + if isinstance(obj, bool): + return bool(obj) + + if isinstance(obj, int): + return int(obj) + + if isinstance(obj, float): + return float(obj) + + if isinstance(obj, Mapping): + return {str(to_plain(k)): to_plain(v) for k, v in obj.items()} + + if isinstance(obj, Sequence) and not isinstance(obj, (str, bytes, bytearray)): + return [to_plain(x) for x in obj] + + return str(obj) + + def _trust_as_template(s: str) -> Any: """Tag a string as trusted for Jinja templating in Ansible 2.19+. diff --git a/utils/tests/swarm/derive_includes.py b/utils/tests/swarm/derive_includes.py index 03cb58e5e7..c2b7cd5e2e 100755 --- a/utils/tests/swarm/derive_includes.py +++ b/utils/tests/swarm/derive_includes.py @@ -141,6 +141,23 @@ def _force_shared_db_view(applications: dict[str, Any]) -> dict[str, Any]: return result +def applications_for_round( + variants: dict[str, int] | None = None, +) -> dict[str, Any]: + """Return the round's application configs with its variants applied. + + Args: + variants: active ``{app_id: variant_index}`` map; ``None`` falls back + to ``INFINITO_APP_VARIANTS``. + + Returns: + Application id to its config for this round. + """ + return _applications_for_active_variants( + get_merged_applications(roles_dir=str(_ROLES_DIR)), variants + ) + + def derive_includes( app_id: str, *, variants: dict[str, int] | None = None ) -> list[str]: @@ -176,6 +193,21 @@ def derive_includes( return sorted(found) +def variant_scope(app_id: str, *, variants: dict[str, int] | None = None) -> list[str]: + """Deployed roles for APP_ID that must carry their own variant config. + + Args: + app_id: role whose closure is resolved. + variants: active ``{app_id: variant_index}`` map, as ``derive_includes``. + """ + explicit = set(_EXPLICIT_INCLUDES) - {app_id} + return [ + role + for role in derive_includes(app_id, variants=variants) + if role not in explicit + ] + + def _disabled_provider_roles(service_registry: dict[str, Any]) -> set[str]: """Provider roles the ``disable`` env removes from the closure, so the swarm include set matches what the provision-time services_disabler diff --git a/utils/tests/swarm/extend_inventory.py b/utils/tests/swarm/extend_inventory.py index a9a634858d..71bd35949c 100755 --- a/utils/tests/swarm/extend_inventory.py +++ b/utils/tests/swarm/extend_inventory.py @@ -32,7 +32,7 @@ from utils.cache.yaml import dump_yaml, load_yaml_any from utils.env.parser import parse_static_env from utils.roles.meta_lookup import get_role_placement from utils.tests.swarm.backup_repos import repo_placements -from utils.tests.swarm.derive_includes import derive_includes +from utils.tests.swarm.derive_includes import applications_for_round, derive_includes _DOCKER_VARS: dict[str, str] = { "ansible_connection": "docker", @@ -77,6 +77,23 @@ def _placement_dep_groups(app_id: str) -> list[tuple[str, str]]: ] +def _sandbox_workers(app_id: str) -> tuple[str, ...]: + """Return the workers that may carry the kata-capable label. + + Args: + app_id: the round's primary application. + + Returns: + Every worker when the app itself is sandboxed, otherwise one. + """ + services = (applications_for_round().get(app_id) or {}).get("services") or {} + return ( + _WORKERS + if ((services.get("kata") or {}).get("enabled")) is True + else _WORKERS[-1:] + ) + + def main() -> int: if not os.environ.get("SWARM_NAME"): raise SystemExit("extend_inventory: SWARM_NAME is required (cluster id)") @@ -85,6 +102,10 @@ def main() -> int: closure = derive_includes(app_id) group_hosts = _host_topology(app_id) + _placement_dep_groups(app_id) + if "svc-virt-kata" in closure: + group_hosts.extend( + ("svc-virt-kata", host) for host in (_MANAGER, *_sandbox_workers(app_id)) + ) group_hosts.extend( repo_placements( app_closure=closure, diff --git a/utils/tests/swarm/matrix.py b/utils/tests/swarm/matrix.py index 49cd36b5f6..dcc1dccc7d 100644 --- a/utils/tests/swarm/matrix.py +++ b/utils/tests/swarm/matrix.py @@ -24,10 +24,13 @@ import os import shutil import subprocess import sys +import time from utils import PROJECT_ROOT from utils.env.runtime import mem_available_mb, mem_stall_pct, mem_total_mb from utils.storage.constrained import host_storage_constrained +from utils.tests.swarm.derive_includes import derive_includes, variant_scope +from utils.tests.swarm.write.extras import ensure_swarm_keypairs _SWARM_DIR = PROJECT_ROOT / "scripts" / "tests" / "deploy" / "swarm" _SWARM_SCRIPTS = _SWARM_DIR / "routine" @@ -51,13 +54,40 @@ def _abort(proc: subprocess.Popen[bytes], banner: str, probe: list[str]) -> int: def _run(cmd: list[str], *, env: dict[str, str], label: str) -> int: - """Run a matrix step, aborting visibly before the runner disk or RAM fills. + """Announce a matrix step, run it, and report what it cost. + + Args: + cmd: argv of the step. + env: environment the step runs with. + label: phase name for the banners. + + Returns: + The step's exit code. + """ + print(f"=== swarm-matrix: {label} ===", flush=True) + started = time.monotonic() + rc = _run_watched(cmd, env=env) + print( + f"=== swarm-matrix: {label} took {time.monotonic() - started:.0f}s (rc={rc}) ===", + flush=True, + ) + return rc + + +def _run_watched(cmd: list[str], *, env: dict[str, str]) -> int: + """Run a step, aborting visibly before the runner disk or RAM fills. The Actions Worker dies silently on ENOSPC while writing its own logs, so a full disk truncates the job without diagnostics; terminating the step at DISK_FLOOR_MB keeps enough room for rescue artifacts and the log upload. + + Args: + cmd: argv of the step. + env: environment the step runs with. + + Returns: + The step's exit code, or the abort code when a floor was hit. """ - print(f"=== swarm-matrix: {label} ===", flush=True) proc = subprocess.Popen(cmd, cwd=str(PROJECT_ROOT), env=env) while True: try: @@ -138,6 +168,46 @@ def _write_extras(*, extras_path: str) -> int: ) +def _reset_credentials( + *, app_id: str, inv_dir: str, round_variants: dict[str, int] +) -> int: + """Regenerate the round's credentials so the update pass has to carry them. + + `administrator` stays exempt: its password is `ansible_become_password`, + and rotating it would lock the deploy out of the nodes it manages. + + The credential scope is `derive_includes`, the same source + `02_provision_inventory.sh` feeds provision's `--include`, so the gate + rotates the ids the round provisioned. A matrix host_vars file also holds + an application block per mirror artefact, and rotating those costs one + subprocess each for credentials provision never generated. Every declared + user password still rotates, so PASS 2 has to carry all of them. + """ + return _run( + [ + "python3", + "-m", + "cli.administration.inventory.credentials.reset", + "--inventory-dir", + inv_dir, + "--host", + os.environ["MGR"], + "--schema", + "--users", + "--include", + *derive_includes(app_id, variants=round_variants), + "--app-variants", + json.dumps(round_variants, sort_keys=True), + "--mirror", + "--backup", + "--except", + "administrator", + ], + env=os.environ.copy(), + label="reset credentials (rotation gate before the async pass)", + ) + + def _deploy( *, app_id: str, @@ -317,7 +387,7 @@ def main(argv: list[str] | None = None) -> int: round_index, inv_dir, round_variants, - round_include, + _round_include, round_purge_set, ) in enumerate(plan): inv_root = inv_dir.rstrip("/") @@ -329,7 +399,7 @@ def main(argv: list[str] | None = None) -> int: variant_payloads = _resolve_variant_payloads( roles_dir=_ROLES_DIR, - include=round_include, + include=variant_scope(app_id, variants=round_variants), active_variants=round_variants, ) from utils.tests.swarm.backup_repos import backup_provider_ips @@ -346,9 +416,13 @@ def main(argv: list[str] | None = None) -> int: f"(round {round_index}): {', '.join(providers)} ===", flush=True, ) + pubkeys = ensure_swarm_keypairs() vars_payload = _bake_overrides( base_overrides={ "applications": backup_applications_overrides(providers), + "users": { + name: {"authorized_keys": [key]} for name, key in pubkeys.items() + }, "STORAGE_CONSTRAINED": host_storage_constrained( [app_id], round_variants, local_vantage="/" ), @@ -391,6 +465,10 @@ def main(argv: list[str] | None = None) -> int: rc = _backup_restore_drill( app_id=app_id, inv_dir=inv_root, extras_path=extras_path ) + if rc == 0: + rc = _reset_credentials( + app_id=app_id, inv_dir=inv_root, round_variants=round_variants + ) if rc == 0: rc = _deploy( app_id=app_id, diff --git a/utils/tests/swarm/write/extras.py b/utils/tests/swarm/write/extras.py index b018b5ca75..c37ddf7f9f 100755 --- a/utils/tests/swarm/write/extras.py +++ b/utils/tests/swarm/write/extras.py @@ -18,9 +18,10 @@ overrides, including ``remote-2-local.backup_providers`` (derived per round from ``utils.tests.swarm.backup_repos``), are baked by the matrix orchestrator into the provisioner's host_vars merge (INFINITO_VARS_PAYLOAD), NOT into the extras file: extra-vars replace the whole inventory -``applications`` dict and would strip every generated credential. The -deploy-facing twin ``<OUT_PATH stem>.deploy.yml`` therefore carries -everything except ``applications``. +``applications`` dict and would strip every generated credential. ``users`` +carries the same hazard for the same reason, and its authorized_keys travel +the same merge channel. The deploy-facing twin ``<OUT_PATH stem>.deploy.yml`` +therefore carries everything except ``applications`` and ``users``. """ from __future__ import annotations @@ -104,29 +105,45 @@ def _ensure_keypair(key_path: Path) -> str: return pub.strip() +def ensure_swarm_keypairs() -> dict[str, str]: + """Create the swarm-test keypairs if they are absent and return the public keys. + + Returns: + Public key per user name, for ``administrator`` and ``backup``. + + The matrix orchestrator needs these before it provisions, so that the + authorized_keys reach host_vars through the merging ``--vars`` channel + rather than through the replacing extra-vars file. + """ + static_env = parse_static_env(PROJECT_ROOT / "default.env") + admin_key = Path(os.environ.get("KEY_PATH", "/tmp/swarm-nfs-admin.key")) # noqa: S108 - ephemeral swarm-test path, overridable via KEY_PATH + backup_key = Path( + os.environ.get("INFINITO_SWARM_BACKUP_KEY") + or static_env["INFINITO_SWARM_BACKUP_KEY"] + ) + return { + "administrator": _ensure_keypair(admin_key), + "backup": _ensure_keypair(backup_key), + } + + def main() -> int: nfs_ip = os.environ["NFS_IP"] mgr_ip = os.environ["MGR_IP"] mgr = os.environ["MGR"] out_path = Path(os.environ.get("OUT_PATH", "/tmp/swarm-nfs-extras.yml")) # noqa: S108 - ephemeral swarm-test path, overridable via OUT_PATH - key_path = Path(os.environ.get("KEY_PATH", "/tmp/swarm-nfs-admin.key")) # noqa: S108 - ephemeral swarm-test path, overridable via KEY_PATH - admin_pubkey = _ensure_keypair(key_path) + pubkeys = ensure_swarm_keypairs() static_env = parse_static_env(PROJECT_ROOT / "default.env") default_users = copy.deepcopy(load_yaml(str(_DEFAULT_INVENTORY)).get("users", {})) admin = dict(default_users.get("administrator", {})) - admin["authorized_keys"] = [admin_pubkey] + admin["authorized_keys"] = [pubkeys["administrator"]] default_users["administrator"] = admin - backup_key_path = Path( - os.environ.get("INFINITO_SWARM_BACKUP_KEY") - or static_env["INFINITO_SWARM_BACKUP_KEY"] - ) - backup_pubkey = _ensure_keypair(backup_key_path) backup = dict(default_users.get("backup", {"accounts": ["host"]})) - backup["authorized_keys"] = [backup_pubkey] + backup["authorized_keys"] = [pubkeys["backup"]] default_users["backup"] = backup extras = { @@ -150,7 +167,9 @@ def main() -> int: } dump_yaml(str(out_path), extras) - deploy_extras = {k: v for k, v in extras.items() if k != "applications"} + deploy_extras = { + k: v for k, v in extras.items() if k not in ("applications", "users") + } deploy_path = out_path.with_suffix(".deploy.yml") dump_yaml(str(deploy_path), deploy_extras) print(out_path.read_text()) # nocheck: cache-read โ€” re-reads the file just written diff --git a/utils/update/base.py b/utils/update/base.py index 2900d2eaa7..161664e813 100644 --- a/utils/update/base.py +++ b/utils/update/base.py @@ -1,15 +1,24 @@ """Semver primitives shared by every version-bump backend. -A "version" here is a tag of the shape ``v?<numeric-semver>(-<flavor>)?``, -where the numeric part has 1 to 4 dot-separated components and the -optional ``-<flavor>`` suffix is an opaque discriminator (e.g. the -Docker Official Image tag ``5.4.5-php8.3-apache`` or the npm-style -``1.2.3-alpha``). +A "version" here is a tag of the shape +``(<channel>-)?v?<numeric-semver><patch>?(-<flavor>)?``, where the numeric part +has 1 to 5 dot-separated components, the optional leading ``<channel>-`` is a +release line written before the number (e.g. the LiteLLM tag +``main-v1.77.7-stable`` or the Jitsi tag ``stable-9646``), the optional +``<patch>`` is a vendor counter written as a letter and a number (e.g. the +Checkmk tag ``2.4.0p32``), and the optional ``-<flavor>`` suffix is an opaque +discriminator (e.g. the Docker Official Image tag ``5.4.5-php8.3-apache`` or +the npm-style ``1.2.3-alpha``). -Upgrade candidates MUST share the same depth (1, 2, 3 or 4 components) -AND the same flavor as the current tag, so that ``5.4.5-php8.3-apache`` -never silently bumps to ``5.4.6-php8.4-apache`` (different runtime) or -to ``5.4.6`` (different depth). +Upgrade candidates MUST share the same depth (1 to 5 components) AND the same +flavor as the current tag, so that ``5.4.5-php8.3-apache`` never silently bumps +to ``5.4.6-php8.4-apache`` (different runtime) or to ``5.4.6`` (different +depth). Everything that is not the number folds into the flavor: the leading +channel, the trailing suffix and the patch letter. That is what keeps +``main-v1.77.7-stable`` away from ``main-v1.77.7-nightly``, ``stable-9646`` +away from a bare ``9646``, and ``2.4.0p32`` ordering against ``2.4.0p33`` +rather than against the four-component ``2.4.0.32``. Only the patch number +joins the ordering key, so ``p9`` sorts below ``p10``. """ from __future__ import annotations @@ -17,15 +26,24 @@ from __future__ import annotations import os import re -_SEMVER_CORE = r"v?\d+(?:\.\d+){0,3}" -_VERSIONED_TAG_RE = re.compile(rf"^(?P<semver>{_SEMVER_CORE})(?P<flavor>-\S+)?$") +_SEMVER_CORE = r"v?\d+(?:\.\d+){0,4}" +_VERSIONED_TAG_RE = re.compile( + rf"^(?P<channel>[A-Za-z][A-Za-z0-9]*-)?(?P<semver>{_SEMVER_CORE})" + rf"(?P<patch>[A-Za-z]\d+)?(?P<flavor>-\S+)?$" +) -def _parse_versioned_tag(tag: str) -> tuple[str, str] | None: +def _parse_versioned_tag(tag: str) -> tuple[str, str, int | None] | None: match = _VERSIONED_TAG_RE.match(str(tag).strip()) if match is None: return None - return match.group("semver"), match.group("flavor") or "" + patch = match.group("patch") + flavor = ( + (match.group("channel") or "") + + (match.group("flavor") or "") + + (patch[0] if patch else "") + ) + return match.group("semver"), flavor, int(patch[1:]) if patch else None def is_semver(value: str) -> bool: @@ -36,16 +54,17 @@ def version_key(tag: str) -> tuple[int, ...]: parsed = _parse_versioned_tag(tag) if parsed is None: return (0,) * 4 - semver, _flavor = parsed + semver, _flavor, patch = parsed parts = tuple(int(part) for part in semver.lstrip("v").split(".")) - return parts + (0,) * (4 - len(parts)) + padded = parts + (0,) * (4 - len(parts)) + return padded if patch is None else (*padded, patch) def version_depth(tag: str) -> int: parsed = _parse_versioned_tag(tag) if parsed is None: return 0 - semver, _flavor = parsed + semver, _flavor, _patch = parsed return len(semver.lstrip("v").split(".")) diff --git a/utils/update/collection_source.py b/utils/update/collection_source.py new file mode 100644 index 0000000000..546ed3488e --- /dev/null +++ b/utils/update/collection_source.py @@ -0,0 +1,115 @@ +"""Which requirements source ``scripts/install/ansible.sh`` should try first. + +Both sources carry the same pinned collections, so the only thing separating +them is how long they take and whether they answer at all. A single slow day +says nothing: galaxy.ansible.com degrades and recovers, and a git clone can +stall on one runner. The default is therefore retuned only when a rolling +window of daily samples shows one source durably behind the other. + +A sample whose install failed is recorded as ``None`` and ranks worse than +any duration, so an outage counts fully rather than being dropped. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from statistics import median +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from pathlib import Path + +SOURCES = ("galaxy", "git") +WINDOW = 12 +"""Samples the median is taken over; below this the default is left alone.""" + +RATIO = 3.0 +"""How many times slower the preferred source must be before it is swapped.""" + + +@dataclass(frozen=True) +class Verdict: + """The outcome of comparing the two sources. + + Args: + preferred: the source in force when the comparison ran. + proposed: the source the samples favour, equal to preferred when + nothing should change. + medians: median seconds per source, infinite when every sample failed. + samples: how many samples the medians were taken over. + """ + + preferred: str + proposed: str + medians: dict[str, float] + samples: int + + @property + def changed(self) -> bool: + return self.proposed != self.preferred + + +def load_history(path: Path) -> list[dict[str, float | None]]: + """Samples recorded so far, oldest first, or an empty list. + + Args: + path: JSON file holding the rolling window. + """ + try: + raw = path.read_text() # nocheck: cache-read -- rewritten every run + payload = json.loads(raw) + except (OSError, ValueError): + return [] + return payload if isinstance(payload, list) else [] + + +def append_sample( + history: list[dict[str, float | None]], sample: dict[str, float | None] +) -> list[dict[str, float | None]]: + """The history with SAMPLE appended, truncated to the newest WINDOW entries. + + Args: + history: samples recorded so far, oldest first. + sample: seconds per source for this run, None where the install failed. + """ + return [*history, sample][-WINDOW:] + + +def _median_seconds(history: list[dict[str, float | None]], source: str) -> float: + values = [ + float("inf") if entry.get(source) is None else float(entry[source]) + for entry in history + ] + return median(values) if values else float("inf") + + +def decide(history: list[dict[str, float | None]], preferred: str) -> Verdict: + """Whether the samples justify swapping the preferred source. + + Args: + history: samples recorded so far, oldest first. + preferred: the source currently tried first. + """ + medians = {source: _median_seconds(history, source) for source in SOURCES} + verdict = Verdict( + preferred=preferred, + proposed=preferred, + medians=medians, + samples=len(history), + ) + if len(history) < WINDOW: + return verdict + + other = next(source for source in SOURCES if source != preferred) + mine, theirs = medians[preferred], medians[other] + if theirs == float("inf") or theirs <= 0: + return verdict + if mine >= theirs * RATIO: + return Verdict( + preferred=preferred, + proposed=other, + medians=medians, + samples=len(history), + ) + return verdict diff --git a/utils/update/docker.py b/utils/update/docker.py index 0c96b20cd4..53bf9561f8 100644 --- a/utils/update/docker.py +++ b/utils/update/docker.py @@ -19,6 +19,7 @@ import re import time import urllib.error import urllib.request +from collections import defaultdict from dataclasses import dataclass from typing import TYPE_CHECKING from urllib.parse import quote, urlencode @@ -342,7 +343,53 @@ def find_outdated_updates(repo_root: Path) -> list[DockerImageVersionUpdate]: if latest and version_key(entry.version) < version_key(latest): updates.append(DockerImageVersionUpdate(entry=entry, latest=latest)) - return updates + return _held_to_release_groups(updates, image_tags) + + +def _held_to_release_groups( + updates: list[DockerImageVersionUpdate], image_tags: dict[str, list[str]] +) -> list[DockerImageVersionUpdate]: + """Hold every member of a release group to the newest tag all of them + publish. + + Several images of one role that currently sit on the same version are one + product released together (the four Jitsi components, the six GitLab CNG + images). Upstream does not push them atomically, so a run that lands in the + window between the first and the last push would raise the ones already + there and leave the rest behind, deploying a mixed set. + + Args: + updates: the per-entry candidates, before grouping. + image_tags: every tag fetched per image, keyed as in the caller. + + Returns: + The updates, each group lowered to its common newest tag, and dropped + entirely where the group shares no newer tag at all. + """ + groups: dict[tuple[str, str], list[DockerImageVersionUpdate]] = defaultdict(list) + for update in updates: + groups[(update.entry.role, update.entry.version)].append(update) + + held: list[DockerImageVersionUpdate] = [] + for group in groups.values(): + if len(group) == 1: + held.extend(group) + continue + shared = set.intersection( + *(set(image_tags.get(update.entry.image, [])) for update in group) + ) + current = group[0].entry.version + common = latest_semver( + sorted(shared), version_depth(current), version_flavor(current) + ) + if not common or version_key(current) >= version_key(common): + continue + held.extend( + DockerImageVersionUpdate(entry=update.entry, latest=common) + for update in group + ) + + return held def update_config_versions(config_path: Path, service_versions: dict[str, str]) -> bool: diff --git a/utils/update/galaxy.py b/utils/update/galaxy.py new file mode 100644 index 0000000000..a29a3edf1c --- /dev/null +++ b/utils/update/galaxy.py @@ -0,0 +1,136 @@ +"""Pinned Ansible collection versions in ``requirements/``. + +Both requirement files name the same collections at the same versions: the +Galaxy file is the normal source, the git file the fallback used when +galaxy.ansible.com is unreachable. A bump that touches only one of them +would make the fallback install something the pin does not describe, so an +update is applied to both or to neither. + +Upstream releases are resolved from the git file's own ``source:`` URL via +``git ls-remote --tags``, not from the Galaxy API, because the collections +are tagged in the repository the fallback already clones. + +An entry whose ``version:`` is not a semver (a branch name, say) states an +intent this cannot second-guess and is skipped. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from pathlib import Path + +from utils.cache.yaml import load_yaml_any +from utils.update.base import is_semver, version_key +from utils.update.repository import git_ls_remote_tags + +GALAXY_REQUIREMENTS = Path("requirements/requirements.galaxy.yml") +GIT_REQUIREMENTS = Path("requirements/requirements.git.yml") + + +@dataclass(frozen=True) +class CollectionPin: + """One collection pinned in both requirement files. + + Args: + fqcn: fully qualified collection name, namespace and name. + version: the version both files pin today. + source: upstream git URL taken from the git requirements file. + """ + + fqcn: str + version: str + source: str + + +@dataclass(frozen=True) +class CollectionPinUpdate: + pin: CollectionPin + latest: str + + +def _entries(path: Path) -> list[dict]: + declared = load_yaml_any(str(path), default_if_missing={}) or {} + return [e for e in (declared.get("collections") or []) if isinstance(e, dict)] + + +def collect_pins(repo_root: Path) -> list[CollectionPin]: + """Collections pinned to the same semver in both requirement files. + + Args: + repo_root: repository root holding the ``requirements`` directory. + """ + galaxy = { + str(e.get("name")): str(e.get("version")) + for e in _entries(repo_root / GALAXY_REQUIREMENTS) + if e.get("name") and e.get("version") + } + pins: list[CollectionPin] = [] + for entry in _entries(repo_root / GIT_REQUIREMENTS): + fqcn = str(entry.get("name", "")) + version = str(entry.get("version", "")) + source = str(entry.get("source", "")) + if not (fqcn and source and is_semver(version)): + continue + if galaxy.get(fqcn) != version: + continue + pins.append(CollectionPin(fqcn=fqcn, version=version, source=source)) + return pins + + +def _highest_release(source: str, current: str) -> str | None: + candidates = [ + tag + for tag in git_ls_remote_tags(source) + if is_semver(tag) and tag.lstrip("v").count(".") == current.count(".") + ] + if not candidates: + return None + newest = max(candidates, key=version_key) + if version_key(newest) <= version_key(current): + return None + return newest.lstrip("v") + + +def find_outdated_updates(repo_root: Path) -> list[CollectionPinUpdate]: + """Pins whose upstream carries a higher release tag. + + Args: + repo_root: repository root holding the ``requirements`` directory. + """ + updates: list[CollectionPinUpdate] = [] + for pin in collect_pins(repo_root): + latest = _highest_release(pin.source, pin.version) + if latest: + updates.append(CollectionPinUpdate(pin=pin, latest=latest)) + return updates + + +def _rewrite(path: Path, fqcn: str, old: str, new: str) -> bool: + text = path.read_text( + encoding="utf-8" + ) # nocheck: cache-read -- rewritten below, a cached copy would go stale mid-run + pattern = re.compile( + rf"(name:\s*{re.escape(fqcn)}\b(?:\n(?!\s*-\s).*)*?\n\s*version:\s*){re.escape(old)}\b" + ) + replaced, count = pattern.subn(rf"\g<1>{new}", text) + if not count: + return False + path.write_text(replaced, encoding="utf-8") + return True + + +def apply_updates(repo_root: Path, updates: list[CollectionPinUpdate]) -> list[Path]: + """Write every update into both requirement files. + + Args: + repo_root: repository root holding the ``requirements`` directory. + updates: the bumps to apply, as returned by :func:`find_outdated_updates`. + """ + changed: set[Path] = set() + for update in updates: + for relative in (GALAXY_REQUIREMENTS, GIT_REQUIREMENTS): + path = repo_root / relative + if _rewrite(path, update.pin.fqcn, update.pin.version, update.latest): + changed.add(path) + return sorted(changed) diff --git a/utils/update/pip.py b/utils/update/pip.py new file mode 100644 index 0000000000..0be2636398 --- /dev/null +++ b/utils/update/pip.py @@ -0,0 +1,191 @@ +"""Pinned pip requirements in ``roles/**/*.yml``. + +A role that hands ``sys-pip-install`` a bare package name follows whatever pip +resolves; one that pins ``name==version`` freezes it, and nothing thaws it +again. The docker updater keeps image tags current and dependabot reads +``pyproject.toml``; neither sees a version inside an Ansible task variable, so +a pin set once ages silently. + +Only exact ``==`` pins are collected. A range or a VCS reference states an +intent this cannot second-guess. + +Suppress a package by placing ``# nocheck: pip-version`` on the line directly +above the ``package_name:`` key, or on the key itself: + + # nocheck: pip-version + package_name: "automtu==1.1.1" +""" + +from __future__ import annotations + +import http.client +import json +import re +import urllib.error +import urllib.request +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import read_text +from utils.update.base import is_semver, version_key + +if TYPE_CHECKING: + from pathlib import Path + +PIN_PATTERN = re.compile( + r"^(?P<indent>\s*)package_name:\s*" + r"(?P<quote>[\"']?)(?P<package>[A-Za-z0-9][A-Za-z0-9._-]*)==" + r"(?P<version>[0-9][0-9A-Za-z.+-]*)(?P=quote)" + r"(?P<suffix>\s*(?:#.*)?)$" +) + +MARKER = "pip-version" + + +@dataclass(frozen=True) +class PipPinEntry: + """One ``package_name: "<name>==<version>"`` line. + + Args: + role: the role directory the pin lives in. + package: the distribution name on PyPI. + version: the pinned version. + config_path: the task file holding the pin. + line_number: 1-indexed line of the pin. + """ + + role: str + package: str + version: str + config_path: Path + line_number: int + + +@dataclass(frozen=True) +class PipPinUpdate: + entry: PipPinEntry + latest: str + + +def collect_entries(repo_root: Path) -> list[PipPinEntry]: + """Return every exact pip pin under ``roles/``. + + Args: + repo_root: repository root to scan. + """ + entries: list[PipPinEntry] = [] + for path in sorted((repo_root / "roles").rglob("*.yml")): + text = read_text(str(path)) + if "package_name:" not in text: + continue + lines = text.splitlines() + for index, line in enumerate(lines): + match = PIN_PATTERN.match(line) + if not match: + continue + if is_suppressed_at(lines, index + 1, MARKER) or MARKER in line: + continue + entries.append( + PipPinEntry( + role=path.relative_to(repo_root / "roles").parts[0], + package=match.group("package"), + version=match.group("version"), + config_path=path, + line_number=index + 1, + ) + ) + return entries + + +def fetch_pypi_versions(package: str) -> list[str]: + """Return every released version of ``package``, empty when PyPI is unreachable. + + Args: + package: distribution name. + """ + url = f"https://pypi.org/pypi/{package}/json" + req = urllib.request.Request( + url, headers={"User-Agent": "infinito-nexus-version-updater"} + ) + try: + with urllib.request.urlopen(req, timeout=15) as resp: # noqa: S310 - fixed https PyPI origin, package name matched against PIN_PATTERN + body = json.loads(resp.read().decode()) + except ( + urllib.error.URLError, + OSError, + http.client.HTTPException, + json.JSONDecodeError, + ): + return [] + releases = body.get("releases") or {} + return [ + version + for version, files in releases.items() + if is_semver(version) and any(not f.get("yanked") for f in files) + ] + + +def latest_release(package: str) -> str | None: + """Return the highest released version of ``package``, or None. + + Args: + package: distribution name. + """ + versions = fetch_pypi_versions(package) + return max(versions, key=version_key) if versions else None + + +def find_outdated_updates(repo_root: Path) -> list[PipPinUpdate]: + """Return one update per pin that PyPI has moved past. + + Args: + repo_root: repository root to scan. + """ + updates: list[PipPinUpdate] = [] + latest_by_package: dict[str, str | None] = {} + for entry in collect_entries(repo_root): + if not is_semver(entry.version): + continue + if entry.package not in latest_by_package: + latest_by_package[entry.package] = latest_release(entry.package) + latest = latest_by_package[entry.package] + if latest and version_key(latest) > version_key(entry.version): + updates.append(PipPinUpdate(entry=entry, latest=latest)) + return updates + + +def apply_updates(updates: list[PipPinUpdate]) -> list[Path]: + """Rewrite each pin to its latest version and return the files changed. + + Args: + updates: the updates to apply. + """ + by_path: dict[Path, dict[int, str]] = {} + for update in updates: + by_path.setdefault(update.entry.config_path, {})[update.entry.line_number] = ( + update.latest + ) + + changed: list[Path] = [] + for path, line_versions in sorted(by_path.items()): + lines = read_text(str(path)).splitlines(keepends=True) + touched = False + for line_number, latest in line_versions.items(): + original = lines[line_number - 1] + match = PIN_PATTERN.match(original.rstrip("\n")) + if not match: + continue + quote = match.group("quote") + replacement = ( + f"{match.group('indent')}package_name: " + f"{quote}{match.group('package')}=={latest}{quote}" + f"{match.group('suffix')}\n" + ) + if replacement != original: + lines[line_number - 1] = replacement + touched = True + if touched: + path.write_text("".join(lines), encoding="utf-8") + changed.append(path) + return changed diff --git a/utils/update/repository.py b/utils/update/repository.py index ac5561fb22..c43f446461 100644 --- a/utils/update/repository.py +++ b/utils/update/repository.py @@ -30,7 +30,7 @@ from typing import TYPE_CHECKING from utils.annotations.suppress import is_suppressed_at from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any -from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.roles.mapping import ROLE_DIR_META_ADDONS, ROLE_FILE_META_SERVICES from utils.update.base import ( is_semver, latest_semver, @@ -148,43 +148,67 @@ def suppressed_ref_lines(config_path: Path) -> set[int]: return suppressed +def _entries_of_file( + role_name: str, config_path: Path, entity_prefix: tuple[str, ...] +) -> list[RepositoryRefEntry]: + """Return the unsuppressed semver ``(repository, ref)`` entries of one + declaration file. + + Args: + role_name: role the file belongs to, carried into each entry. + config_path: YAML file to read. + entity_prefix: path segments prepended to the entity path, so an + addon's entries stay distinguishable from a service's. + """ + data = load_yaml_any(str(config_path), default_if_missing=None) + if not isinstance(data, dict): + return [] + + ref_line_index: dict[str, list[int]] = {} + for line_no, ref_value in _ref_lines(read_text(str(config_path)).splitlines()): + ref_line_index.setdefault(ref_value, []).append(line_no) + + suppressed = suppressed_ref_lines(config_path) + entries: list[RepositoryRefEntry] = [] + for entity_path, repo, ref in walk_repo_ref_pairs(data, entity_prefix): + if not is_semver(ref): + continue + candidates = ref_line_index.get(ref) or [] + if not candidates: + continue + line_no = candidates.pop(0) + if line_no in suppressed: + continue + entries.append( + RepositoryRefEntry( + role=role_name, + entity_path=entity_path, + repository=repo, + ref=ref, + config_path=config_path, + line=line_no, + ) + ) + return entries + + def collect_entries(repo_root: Path) -> list[RepositoryRefEntry]: """Return every semver-checkable ``(repository, ref)`` declaration - under ``roles/*/meta/services.yml`` whose ref is not suppressed.""" + under ``roles/*/meta/services.yml`` and ``roles/*/meta/addons/*.yml`` + whose ref is not suppressed.""" roles_root = repo_root / "roles" entries: list[RepositoryRefEntry] = [] for role_dir in sorted(p for p in roles_root.iterdir() if p.is_dir()): services_path = role_dir / ROLE_FILE_META_SERVICES - if not services_path.is_file(): - continue - data = load_yaml_any(str(services_path), default_if_missing=None) - if not isinstance(data, dict): - continue + if services_path.is_file(): + entries += _entries_of_file(role_dir.name, services_path, ()) - raw = read_text(str(services_path)) - ref_line_index: dict[str, list[int]] = {} - for line_no, ref_value in _ref_lines(raw.splitlines()): - ref_line_index.setdefault(ref_value, []).append(line_no) - - suppressed = suppressed_ref_lines(services_path) - for entity_path, repo, ref in walk_repo_ref_pairs(data, ()): - if not is_semver(ref): - continue - candidates = ref_line_index.get(ref) or [] - if not candidates: - continue - line_no = candidates.pop(0) - if line_no in suppressed: - continue - entries.append( - RepositoryRefEntry( - role=role_dir.name, - entity_path=entity_path, - repository=repo, - ref=ref, - config_path=services_path, - line=line_no, - ) + addons_dir = role_dir / ROLE_DIR_META_ADDONS + if not addons_dir.is_dir(): + continue + for addon_path in sorted(addons_dir.glob("*.yml")): + entries += _entries_of_file( + role_dir.name, addon_path, ("addons", addon_path.stem) ) return entries