diff --git a/.dockerignore b/.dockerignore index 3b93cecead..a5fe05a732 100644 --- a/.dockerignore +++ b/.dockerignore @@ -14,6 +14,7 @@ venv *tree.json roles/list.json roles/importer_result.json +roles/web-app-cst-* *.pyc *.egg-info build/* diff --git a/.github/workflows/README.md b/.github/workflows/README.md index e8a1738899..92afdb673f 100644 --- a/.github/workflows/README.md +++ b/.github/workflows/README.md @@ -23,7 +23,7 @@ flowchart TB subgraph orchestrator["call-orchestrator.yml jobs"] waitfork["wait-fork-prereq-run"] --> forkready["fork-prereqs-ready"] - lintwf["call-lint.yml: make lint + hadolint"] + lintwf["call-lint.yml: make lint"] testwf["call-test.yml: make test"] codeql["cron-security-codeql.yml"] buildci["build-ci-images: call-images-build-ci.yml"] --> dns["call-test-dns.yml"] diff --git a/.github/workflows/entry-push-latest.yml b/.github/workflows/entry-push-latest.yml index 59070de57b..72c1ca9e52 100644 --- a/.github/workflows/entry-push-latest.yml +++ b/.github/workflows/entry-push-latest.yml @@ -19,6 +19,27 @@ permissions: contents: read jobs: + sync-main: + name: 🔄 Sync main + runs-on: ubuntu-26.04 + permissions: + contents: read + steps: + - name: ⬇️ Checkout repository + uses: actions/checkout@v7.0.0 + with: + fetch-depth: 0 + persist-credentials: false + + - name: 🔄 Sync main from source repository + shell: bash + env: + CI_SYNC_MAIN_TOKEN: ${{ secrets.CI_SYNC_MAIN_TOKEN }} + CI_SYNC_MAIN_SOURCE_REPOSITORY_DEFAULT: infinito-nexus/core + CI_SYNC_MAIN_SOURCE_REPOSITORY: ${{ vars.CI_SYNC_MAIN_SOURCE_REPOSITORY }} + CI_SYNC_MAIN_SOURCE_REPOSITORY_IS_SET: ${{ contains(toJSON(vars), '"CI_SYNC_MAIN_SOURCE_REPOSITORY"') }} + run: bash scripts/github/sync/main_from_repository.sh + run-policy: name: 🧭 Decide CI policy runs-on: ubuntu-26.04 diff --git a/.gitignore b/.gitignore index 3b93cecead..a5fe05a732 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ venv *tree.json roles/list.json roles/importer_result.json +roles/web-app-cst-* *.pyc *.egg-info build/* diff --git a/Makefile b/Makefile index 2e24d3848e..21511f61c8 100644 --- a/Makefile +++ b/Makefile @@ -699,6 +699,20 @@ quality: # Full gate: quality (autoformat + test) followed by every lint check. quality-high: quality lint +.PHONY: roles-clean +# Remove every custom role (roles/web-app-cst-*) a pull placed in this checkout and nothing else. +roles-clean: + @"$${PYTHON}" -m cli.administration.roles.clean + +.PHONY: roles-pull +# Pull the custom roles (web-app-cst-*) an inventory declares into roles/ without deploying, removing the ones it no longer declares. +# Usage: make roles-pull inventory= +# Example: make roles-pull inventory=inventories/production/devices.yml +# Param inventory: inventory file whose group_vars/host_vars declare applications..custom and .source (required). +roles-pull: + @test -n '$(inventory)' || { echo 'usage: make roles-pull inventory='; exit 2; } + @"$${PYTHON}" -m cli.administration.roles.pull '$(inventory)' + .PHONY: roundtrip # Validate one or more roles through every deploy mode in order (compose, then swarm), stopping at the first failure. # Param apps: space-separated role ids; default = one role per base cluster, most-complex first (complexity --unique). @@ -1020,4 +1034,4 @@ wsl2-systemd-check: .PHONY: wsl2-trust-windows # Trust Windows certificates in WSL2. wsl2-trust-windows: - @bash scripts/system/tls/trust/wsl2.sh \ No newline at end of file + @bash scripts/system/tls/trust/wsl2.sh diff --git a/aliases b/aliases index b7746f6bc0..a4cf47699a 100644 --- a/aliases +++ b/aliases @@ -133,6 +133,8 @@ alias i8puwl='__i8puwl(){ [ -z "${1:-}" ] && { echo "usage: i8puwl >> Deploy command inside container:") diff --git a/cli/administration/deploy/dedicated/command.py b/cli/administration/deploy/dedicated/command.py index 3e2a4cfdee..24adfba58e 100644 --- a/cli/administration/deploy/dedicated/command.py +++ b/cli/administration/deploy/dedicated/command.py @@ -4,6 +4,8 @@ import argparse import subprocess from typing import Any +from cli.administration.roles.pull import pull_or_exit + from .apps import validate_application_ids from .modes import add_dynamic_mode_args, build_modes_from_args, load_modes_from_yaml from .paths import INVENTORY_VALIDATOR_PATH, MODES_FILE, PLAYBOOK_PATH, PROJECT_ROOT @@ -117,6 +119,14 @@ def build_parser() -> argparse.ArgumentParser: parser.add_argument( "-B", "--skip-build", action="store_true", help="Skip build phase." ) + parser.add_argument( + "--skip-pull", + action="store_true", + help=( + "Deploy the custom roles already under roles/ instead of pulling " + "the ones the inventory declares (generated test inventories)." + ), + ) parser.add_argument( "--id", nargs="+", @@ -185,6 +195,16 @@ def parse_args( return args, passthrough, modes_spec +def pull_custom_roles(args: Any) -> None: + """Place the custom roles the inventory declares before anything reads roles/. + + Args: + args: parsed wrapper args; ``skip_pull`` keeps roles/ as it is. + """ + if not args.skip_pull: + pull_or_exit(args.inventory) + + def run_from_args( args: Any, passthrough: list[str], @@ -221,4 +241,5 @@ def main(argv: list[str] | None = None) -> int: ``cli.administration.deploy.swarm``. """ args, passthrough, modes_spec = parse_args(argv) + pull_custom_roles(args) return run_from_args(args, passthrough, modes_spec) diff --git a/cli/administration/deploy/development/deploy/run.py b/cli/administration/deploy/development/deploy/run.py index aada71cb71..ed3b51a279 100644 --- a/cli/administration/deploy/development/deploy/run.py +++ b/cli/administration/deploy/development/deploy/run.py @@ -53,6 +53,7 @@ def _run_deploy( "--assert", "true", "--diff", + "--skip-pull", "--id", *deploy_ids, ] diff --git a/cli/administration/deploy/development/env.py b/cli/administration/deploy/development/env.py index 23d467b9b5..49943f9739 100644 --- a/cli/administration/deploy/development/env.py +++ b/cli/administration/deploy/development/env.py @@ -23,6 +23,7 @@ def compose_file_args() -> list[str]: stack outright, so a checkout that was never handed a shared git dir or cache network simply does not layer that file in. """ + from .extra_mounts import parse_mounts, write_mounts_override from .profile import Profile profile = Profile() @@ -46,6 +47,11 @@ def compose_file_args() -> list[str]: from .runner_mirror import write_override out += ["-f", write_override(PROJECT_ROOT, out[1::2])] + mounts = parse_mounts(os.environ.get("INFINITO_EXTRA_MOUNTS") or "") + if mounts: + from utils.cache.files import PROJECT_ROOT + + out += ["-f", write_mounts_override(PROJECT_ROOT, mounts)] return out diff --git a/cli/administration/deploy/development/extra_mounts.py b/cli/administration/deploy/development/extra_mounts.py new file mode 100644 index 0000000000..794dabdc2e --- /dev/null +++ b/cli/administration/deploy/development/extra_mounts.py @@ -0,0 +1,47 @@ +"""Mount extra host directories read-only into the infinito container.""" + +from __future__ import annotations + +from pathlib import Path + +from utils.cache.yaml import dump_yaml + +OVERRIDE = "build/compose/extra-mounts.override.yml" + + +def parse_mounts(raw: str) -> list[Path]: + """Return the directories of a comma-separated ``INFINITO_EXTRA_MOUNTS`` value. + + Args: + raw: comma-separated absolute host directories. + + Raises: + SystemExit: an entry is not an existing absolute directory. + """ + directories: list[Path] = [] + for item in filter(None, (part.strip() for part in raw.split(","))): + directory = Path(item) + if not directory.is_absolute() or not directory.is_dir(): + raise SystemExit( + f"INFINITO_EXTRA_MOUNTS: {item} is not an existing absolute directory" + ) + directories.append(directory) + return directories + + +def write_mounts_override(repo_root: Path, directories: list[Path]) -> str: + """Write the compose override that mounts ``directories`` into the container. + + Args: + repo_root: repository root the compose files are relative to. + directories: host directories, each mounted read-only at its own path. + + Returns: + The override path relative to ``repo_root``. + """ + volumes = [ + {"type": "bind", "source": str(path), "target": str(path), "read_only": True} + for path in directories + ] + dump_yaml(repo_root / OVERRIDE, {"services": {"infinito": {"volumes": volumes}}}) + return OVERRIDE diff --git a/cli/administration/deploy/swarm/command.py b/cli/administration/deploy/swarm/command.py index 9fb76ebe47..c152223003 100644 --- a/cli/administration/deploy/swarm/command.py +++ b/cli/administration/deploy/swarm/command.py @@ -1,17 +1,23 @@ """Swarm-aware deploy CLI command. -Re-uses ``dedicated.command.parse_args`` verbatim, then rewrites -``args.id`` via the swarm closure between parse and dispatch. +Re-uses ``dedicated.command.parse_args`` verbatim, pulls the custom roles +first because the swarm closure reads roles/, then rewrites ``args.id`` +via that closure between parse and dispatch. """ from __future__ import annotations -from cli.administration.deploy.dedicated.command import parse_args, run_from_args +from cli.administration.deploy.dedicated.command import ( + parse_args, + pull_custom_roles, + run_from_args, +) from .closure import swarm_deploy_targets def main(argv: list[str] | None = None) -> int: args, passthrough, modes_spec = parse_args(argv) + pull_custom_roles(args) args.id = swarm_deploy_targets(args.id, args.inventory) return run_from_args(args, passthrough, modes_spec) diff --git a/cli/administration/inventory/provision/cli.py b/cli/administration/inventory/provision/cli.py index 01e127bc6d..45fc613058 100644 --- a/cli/administration/inventory/provision/cli.py +++ b/cli/administration/inventory/provision/cli.py @@ -247,7 +247,7 @@ def main(argv: list[str] | None = None) -> int: print( f"[INFO] Pinning a password for every user the {len(application_ids)} " - "resolved applications declare..." + "resolved applications declare and every catalogue user holding an account..." ) pinned = generate_user_passwords( roles_dir=roles_dir, diff --git a/cli/administration/inventory/provision/reset.py b/cli/administration/inventory/provision/reset.py index 54e5bfba82..ea0f570aa5 100644 --- a/cli/administration/inventory/provision/reset.py +++ b/cli/administration/inventory/provision/reset.py @@ -160,7 +160,7 @@ def _drop_user_passwords( application_ids: list[str], exclude: set[str], ) -> int: - """Remove the pinned password of every user the resolved roles declare. + """Remove the pinned password of every user the deployment needs pinned. Args: document: the host_vars document. @@ -171,9 +171,9 @@ def _drop_user_passwords( 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. + Only the users ``required_user_policies`` names 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): diff --git a/cli/administration/inventory/provision/users_generator.py b/cli/administration/inventory/provision/users_generator.py index 07f557ecb6..1164eb9eb6 100644 --- a/cli/administration/inventory/provision/users_generator.py +++ b/cli/administration/inventory/provision/users_generator.py @@ -1,4 +1,4 @@ -"""Pin a password on every user the resolved role set needs. +"""Pin a password on every user a deployment creates or authenticates. A user definition that declares no password falls back to ``{{ 42 | strong_password }}``. That is a template, not a value: it is @@ -10,8 +10,9 @@ that are already generated there. from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any +from utils.cache.users import get_user_defaults from utils.cache.yaml import load_yaml_any from utils.roles.mapping import ROLE_FILE_META_USERS @@ -21,28 +22,19 @@ from .ruamel_io import dump_document, ensure_map, load_document, vault_value if TYPE_CHECKING: from pathlib import Path +BOT_ROLE = "bot" -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. + +def _declarations( + roles_dir: Path, +) -> dict[str, list[tuple[Path, dict[str, Any]]]]: + """Return every role's declaration of every user, keyed by username. 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 + declarations: dict[str, list[tuple[Path, dict[str, Any]]]] = {} + for users_file in sorted(roles_dir.glob(f"*/{ROLE_FILE_META_USERS}")): declared = load_yaml_any(users_file) if not isinstance(declared, dict): continue @@ -51,26 +43,94 @@ def required_user_policies( 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} + declarations.setdefault(str(username), []).append((users_file, overrides)) + return declarations + + +def _policy( + username: str, declarations: list[tuple[Path, dict[str, Any]]] +) -> dict[str, str | None]: + """Return the password policy the declarations of one user agree on. + + Args: + username: the user the declarations belong to. + declarations: every role's declaration of that user. + + 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. A declaration without a policy agrees + with any. + """ + policy: dict[str, str | None] = {"algorithm": None, "validation": None} + source: Path | None = None + for users_file, overrides in declarations: + declared = overrides.get("password") + if not isinstance(declared, dict): + continue + candidate = { + "algorithm": declared.get("algorithm"), + "validation": declared.get("validation"), + } + if not any(candidate.values()): + continue + if source is not None and candidate != policy: + raise SystemExit( + f"user {username!r} carries conflicting password policies: " + f"{source} asks for {policy}, {users_file} for {candidate}" ) - 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())) + policy, source = candidate, users_file + return policy + + +def _provisioned_users(roles_dir: Path) -> set[str]: + """Return every user that holds an account or is a bot, deployed role or not. + + Args: + roles_dir: directory the roles live in. + + The directory and the mail providers iterate ``lookup('users')``, the + catalogue of every role, so a bot whose declaring role this inventory never + deploys still gets a mailbox and a submission token. + """ + return { + username + for username, user in get_user_defaults(roles_dir=roles_dir).items() + if user["accounts"] or BOT_ROLE in user["roles"] + } + + +def required_user_policies( + roles_dir: Path, application_ids: list[str] +) -> dict[str, dict[str, str | None]]: + """Return every username the deployment needs pinned, with its policy. + + Args: + roles_dir: directory the roles live in. + application_ids: the roles resolved into this inventory. + + A user is needed when a resolved role declares it, or when it holds an + account or is a bot and no role states its password outright. + """ + resolved = { + roles_dir / application_id / ROLE_FILE_META_USERS + for application_id in application_ids + } + declarations = _declarations(roles_dir) + policies = { + username: _policy(username, declared) + for username, declared in declarations.items() + } + provisioned = _provisioned_users(roles_dir) + + required: dict[str, dict[str, str | None]] = {} + for username, declared in declarations.items(): + by_resolved_role = any(users_file in resolved for users_file, _ in declared) + stated = any( + isinstance(overrides.get("password"), str) for _, overrides in declared + ) + if by_resolved_role or (username in provisioned and not stated): + required[username] = policies[username] + return dict(sorted(required.items())) def generate_user_passwords( diff --git a/cli/administration/inventory/validate/applications.py b/cli/administration/inventory/validate/applications.py index 99498dcd96..8d3a3d1ed6 100644 --- a/cli/administration/inventory/validate/applications.py +++ b/cli/administration/inventory/validate/applications.py @@ -3,17 +3,26 @@ from __future__ import annotations from utils.manager.credential_key import OVERRIDE_SECTION, SECRETS_KEY +from utils.roles.custom import CUSTOM_KEY, SOURCE_KEY, is_custom from .keys import recursive_keys +def _declares_custom_role(app_id: str, key: str) -> bool: + return is_custom(app_id) and key.split(".", 1)[0] in (CUSTOM_KEY, SOURCE_KEY) + + def compare_application_keys(applications, application_defaults, source, variants=None): """Variants.yml is part of the role contract: a variant overlay may legitimately introduce service-keys absent from meta/services.yml (e.g. roles/web-opt-rdr-www declares services.dashboard only in meta/variants.yml). Widen the allow-set to defaults ∪ union(variant overlays) so host_vars baked by matrix-deploy from variants.yml - aren't flagged as "Missing default".""" + aren't flagged as "Missing default". + + ``custom`` and ``source`` of a custom role are the inventory's + declaration of where the role comes from, not role settings, so no + role default carries them.""" variants = variants or {} errs: list[str] = [] for app_id, conf in applications.items(): @@ -26,6 +35,8 @@ def compare_application_keys(applications, application_defaults, source, variant for key in recursive_keys(conf): if key == SECRETS_KEY or key.startswith(OVERRIDE_SECTION): continue + if _declares_custom_role(app_id, key): + continue if key not in legal_keys: errs.append(f"{source}: Missing default for {app_id}: {key}") return errs diff --git a/cli/administration/inventory/validate/loaders.py b/cli/administration/inventory/validate/loaders.py index 7305f49747..6f695a8f21 100644 --- a/cli/administration/inventory/validate/loaders.py +++ b/cli/administration/inventory/validate/loaders.py @@ -1,49 +1,54 @@ -"""Inventory file I/O — YAML parsing with vault stripping + directory scans.""" +"""Inventory file I/O — YAML parsing + directory scans.""" from __future__ import annotations -import re import sys from pathlib import Path from utils.cache.files import read_text from utils.cache.yaml import load_yaml_str -_VAULT_BLOCK_RE = re.compile(r"(?m)^([ \t]*[^\s:]+):\s*!vault[\s\S]+?(?=^\S|\Z)") - def load_yaml_file(path): - """Parse a YAML file, replacing ``!vault`` scalars with a placeholder. + """Parse a YAML file; a ``!vault`` scalar loads as its ciphertext string. - The cache's path-keyed loader is bypassed on purpose — the caller - mutates content per call, so each parse is intentionally fresh. + Args: + path: the YAML file. + + Returns: + the parsed document, or ``None`` after a warning when the file is + missing or not valid YAML. """ try: - content = read_text(str(path)) - content = _VAULT_BLOCK_RE.sub(r'\1: ""\n', content) - return load_yaml_str(content) + return load_yaml_str(read_text(str(path))) except Exception as e: print(f"Warning: Could not parse {path}: {e}", file=sys.stderr) return None +def inventory_files(inv_dir) -> list[Path]: + """Return the YAML files of an inventory directory that may set ``applications``. + + Args: + inv_dir: the inventory directory; its ``*.yml`` and every ``*.yml`` + under its ``*_vars`` directories are listed. + """ + p = Path(inv_dir) + files = list(p.glob("*.yml")) + for d in p.glob("*_vars"): + if d.is_dir(): + files.extend(d.rglob("*.yml")) + return files + + def load_inventory_files(inv_dir) -> dict[str, dict]: """Walk the inventory directory and collect every ``applications:`` block keyed by its source file path.""" all_data: dict[str, dict] = {} - p = Path(inv_dir) - for f in p.glob("*.yml"): + for f in inventory_files(inv_dir): data = load_yaml_file(f) if isinstance(data, dict): apps = data.get("applications") if apps: all_data[str(f)] = apps - for d in p.glob("*_vars"): - if d.is_dir(): - for f in d.rglob("*.yml"): - data = load_yaml_file(f) - if isinstance(data, dict): - apps = data.get("applications") - if apps: - all_data[str(f)] = apps return all_data diff --git a/cli/administration/inventory/validate/users.py b/cli/administration/inventory/validate/users.py index 401b4acd07..7e2de2fd1e 100644 --- a/cli/administration/inventory/validate/users.py +++ b/cli/administration/inventory/validate/users.py @@ -9,7 +9,8 @@ def compare_user_keys(users, user_defaults, source) -> list[str]: errs: list[str] = [] for user, conf in users.items(): if user not in user_defaults: - print(f"Warning: {source}: Unknown user '{user}'", file=sys.stderr) + if not (isinstance(conf, dict) and conf.get("username")): + print(f"Warning: {source}: Unknown user '{user}'", file=sys.stderr) continue def_conf = user_defaults[user] for key in conf: diff --git a/cli/administration/roles/README.md b/cli/administration/roles/README.md new file mode 100644 index 0000000000..4e1ad83c7b --- /dev/null +++ b/cli/administration/roles/README.md @@ -0,0 +1,3 @@ +# Roles 🧩 + +Custom roles (`web-app-cst-*`) an inventory declares, pulled from their own repositories into the role search path of this checkout, listed and removed again. diff --git a/cli/administration/roles/__init__.py b/cli/administration/roles/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/cli/administration/roles/clean/__init__.py b/cli/administration/roles/clean/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/cli/administration/roles/clean/__main__.py b/cli/administration/roles/clean/__main__.py new file mode 100644 index 0000000000..2e95391b10 --- /dev/null +++ b/cli/administration/roles/clean/__main__.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +import argparse + +from cli.administration.roles.paths import WORK_DIR +from cli.administration.roles.placement import clean +from utils.cache import ROLES_DIR + + +def main(argv: list[str] | None = None) -> int: + argparse.ArgumentParser( + description=( + "Remove every custom role (roles/web-app-cst-*) a pull placed in this " + "checkout and nothing else; report every other roles/web-app-cst-* entry." + ) + ).parse_args(argv) + try: + lines = clean(ROLES_DIR, WORK_DIR) + except OSError as exc: + raise SystemExit(f"[ERROR] {exc}") from exc + for line in lines: + print(f"custom role {line}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cli/administration/roles/declaration.py b/cli/administration/roles/declaration.py new file mode 100644 index 0000000000..fe81a16ce9 --- /dev/null +++ b/cli/administration/roles/declaration.py @@ -0,0 +1,248 @@ +"""Custom-role declarations of an inventory, validated before anything is pulled. + +``custom`` and ``source`` are read from the raw inventory files and are +never rendered: a templated or tagged value could otherwise make the +controller fetch code chosen at render time. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from pathlib import Path, PurePosixPath +from urllib.parse import urlsplit + +from utils.cache.yaml import TaggedValue +from utils.roles.custom import CUSTOM_KEY, PREFIX, SOURCE_KEY, is_custom +from utils.roles.entity.name import get_entity_name + +from .inventory import read_inventory + +SOURCE_FIELDS: tuple[str, ...] = ("url", "version", "path") + +_JINJA = re.compile(r"{{|{%|{#") +_FULL_SHA = re.compile(r"^(?:[0-9a-f]{40}|[0-9a-f]{64})$") +_GIT_URL = re.compile(r"^(?:(?:https|ssh)://\S+|(?:[\w.-]+@)?[\w.-]+:(?!//)\S+)$") +_CONFLICT = object() + + +@dataclass(frozen=True) +class Source: + """Where a custom role comes from. + + Args: + url: Git URL over HTTPS or SSH, or an absolute local directory. + version: tag or full commit SHA; ``None`` copies the working tree + of a local directory. + path: the role directory inside the repository. + """ + + url: str + version: str | None + path: str + + @property + def local(self) -> bool: + return Path(self.url).is_absolute() + + @property + def commit(self) -> bool: + return self.version is not None and bool(_FULL_SHA.match(self.version)) + + def describe(self) -> str: + """Return the source as the pull reports it, without the resolved commit.""" + if self.version is None: + return f"{self.url} {self.path} (working tree)" + return f"{self.url} {self.path} @ {self.version}" + + +def read_declarations( + inventory: Path, roles_dir: Path +) -> tuple[dict[str, Source], list[str]]: + """Return the declared custom roles and every declaration error. + + Args: + inventory: the inventory file, whose directory holds the + ``group_vars``/``host_vars`` that set application values, or + an inventory directory. + roles_dir: the core ``roles/`` the custom roles are placed in. + + Returns: + ``({group: Source}, errors)``; each error names its group, or the + inventory file that cannot be read, which declares nothing. + """ + documents, groups, errors = read_inventory(inventory) + if errors: + return {}, errors + marked: set[str] = set() + declared: dict[str, Source] = {} + for group, by_key in sorted(_collect(documents).items()): + values = { + key: _agreed(group, key, by_file, errors) for key, by_file in by_key.items() + } + if any(value is _CONFLICT for value in values.values()): + continue + custom = values.get(CUSTOM_KEY) + if reason := _unrendered(custom): + errors.append( + f"{group}: applications.{group}.{CUSTOM_KEY} {reason}; the pull never renders it" + ) + continue + if custom is not True: + continue + marked.add(group) + if not is_custom(group): + errors.append( + f"{group}: {CUSTOM_KEY}: true marks a group outside the {PREFIX} prefix" + ) + continue + source = _source(group, values.get(SOURCE_KEY), errors) + if source is not None: + declared[group] = source + errors.extend( + f"{group}: inventory group without applications.{group}.{CUSTOM_KEY}: true" + for group in sorted(groups) + if is_custom(group) and group not in marked + ) + errors.extend(_entity_collisions(declared, roles_dir)) + return declared, errors + + +def _collect(documents: dict[str, object]) -> dict[str, dict[str, dict[str, object]]]: + found: dict[str, dict[str, dict[str, object]]] = {} + for src, data in documents.items(): + apps = data.get("applications") if isinstance(data, dict) else None + if not isinstance(apps, dict): + continue + for group, conf in apps.items(): + if not isinstance(conf, dict): + continue + for key in (CUSTOM_KEY, SOURCE_KEY): + if key in conf: + found.setdefault(str(group), {}).setdefault(key, {})[src] = conf[ + key + ] + return found + + +def _agreed( + group: str, key: str, by_file: dict[str, object], errors: list[str] +) -> object: + values = list(by_file.values()) + if all(value == values[0] for value in values[1:]): + return values[0] + errors.append( + f"{group}: applications.{group}.{key} differs between {', '.join(sorted(by_file))}" + ) + return _CONFLICT + + +def _unrendered(value: object) -> str | None: + if isinstance(value, TaggedValue): + return f"holds a {value.tag} value" + if isinstance(value, str): + return "holds a Jinja expression" if _JINJA.search(value) else None + if isinstance(value, dict): + value = list(value.values()) + if isinstance(value, list): + return next(filter(None, map(_unrendered, value)), None) + return None + + +def _source(group: str, raw: object, errors: list[str]) -> Source | None: + prefix = f"{group}: applications.{group}.{SOURCE_KEY}" + if raw is None: + errors.append(f"{prefix} is missing") + return None + if isinstance(raw, TaggedValue): + errors.append(f"{prefix} holds a {raw.tag} value; the pull never renders it") + return None + if not isinstance(raw, dict): + errors.append(f"{prefix} must be a mapping of {', '.join(SOURCE_FIELDS)}") + return None + before = len(errors) + errors.extend( + f"{prefix}.{name} is not a source field" + for name in sorted(set(raw) - set(SOURCE_FIELDS)) + ) + fields: dict[str, str] = {} + for name in SOURCE_FIELDS: + value = raw.get(name) + if value is None: + continue + if reason := _unrendered(value): + errors.append(f"{prefix}.{name} {reason}; the pull never renders it") + elif not isinstance(value, str) or not value.strip(): + errors.append(f"{prefix}.{name} must be a non-empty string") + else: + fields[name] = value + url, version, path = (fields.get(name) for name in SOURCE_FIELDS) + if url is None and "url" not in raw: + errors.append(f"{prefix}.url is missing") + if url is not None: + errors.extend(_url_errors(prefix, url)) + if ( + version is None + and "version" not in raw + and not (url is not None and Path(url).is_absolute()) + ): + errors.append(f"{prefix}.version is missing") + if path is None and "path" not in raw: + errors.append(f"{prefix}.path is missing") + if path is not None: + errors.extend(_path_errors(group, prefix, PurePosixPath(path))) + if len(errors) > before or url is None or path is None: + return None + return Source(url=url, version=version, path=path) + + +def _url_errors(prefix: str, url: str) -> list[str]: + if _embeds_credentials(url): + return [ + ( + f"{prefix}.url embeds credentials; authenticate through the SSH " + "agent or SSH configuration of the controller instead" + ) + ] + if not (Path(url).is_absolute() or _GIT_URL.match(url)): + return [ + f"{prefix}.url is neither a Git URL over HTTPS or SSH nor an absolute local directory" + ] + return [] + + +def _embeds_credentials(url: str) -> bool: + if "://" not in url: + return False + try: + parts = urlsplit(url) + password = parts.password + except ValueError: + return True + return password is not None or ( + parts.scheme != "ssh" and parts.username is not None + ) + + +def _path_errors(group: str, prefix: str, path: PurePosixPath) -> list[str]: + # nocheck: project-root-import -- refuses a source.path that climbs out of its repository + if path.is_absolute() or ".." in path.parts: + return [f"{prefix}.path must be a relative path inside the repository"] + if path.name != group: + return [ + f"{prefix}.path names the role directory '{path.name}', but the group is '{group}'; core never renames a role" + ] + return [] + + +def _entity_collisions(declared: dict[str, Source], roles_dir: Path) -> list[str]: + in_tree = { + get_entity_name(role.name): role.name + for role in sorted(roles_dir.iterdir()) + if role.is_dir() and not is_custom(role.name) + } + return [ + f"{group}: entity name '{entity}' collides with the in-tree role {in_tree[entity]}" + for group in sorted(declared) + if (entity := get_entity_name(group)) in in_tree + ] diff --git a/cli/administration/roles/inventory.py b/cli/administration/roles/inventory.py new file mode 100644 index 0000000000..e6f56991e0 --- /dev/null +++ b/cli/administration/roles/inventory.py @@ -0,0 +1,105 @@ +"""The inventory files a custom-role pull reads, picked the way Ansible picks them. + +A pull stops while any of these files cannot be read: a declaration it +cannot see would make it remove the role as no longer declared. +""" + +from __future__ import annotations + +import re +from typing import TYPE_CHECKING + +from yaml import MarkedYAMLError, YAMLError + +from cli.administration.inventory.validate.loaders import inventory_files +from utils.cache.yaml import load_yaml_tagged +from utils.inventory.groups import inventory_groups + +if TYPE_CHECKING: + from pathlib import Path + +_SKIPPED_NAMES = re.compile(r"^\.|^(?:host_vars|group_vars|vars_plugins)$") +_SKIPPED_SUFFIXES = ( + ".pyc", + ".pyo", + ".swp", + ".bak", + "~", + ".rpm", + ".md", + ".txt", + ".rst", + ".orig", + ".cfg", + ".retry", +) +_UNREADABLE = (OSError, ValueError, YAMLError) + + +def is_host_list(inventory: Path) -> bool: + """Return whether *inventory* is an inline host list such as ``localhost,``. + + Args: + inventory: the ``-i`` value; Ansible reads it as a host list when + no such path exists and it holds a comma. + """ + return "," in str(inventory) and not inventory.exists() + + +def read_inventory(inventory: Path) -> tuple[dict[str, object], set[str], list[str]]: + """Read every file of *inventory* the pull takes declarations and groups from. + + Args: + inventory: an inventory file, or a directory Ansible reads as one: + its host files, skipped the way Ansible skips them, and the + ``group_vars``/``host_vars`` beside them. + + Returns: + ``({file: document}, groups, errors)``; each error names a file + that cannot be read. Tagged values load as opaque + :class:`~utils.cache.yaml.TaggedValue` objects. + """ + if inventory.is_dir(): + base, hosts = inventory, _host_files(inventory) + else: + base, hosts = inventory.parent, [inventory] + documents: dict[str, object] = {} + errors: list[str] = [] + for path in inventory_files(base): + try: + documents[str(path)] = load_yaml_tagged(path) + except _UNREADABLE as exc: + errors.append(_unreadable(path, exc)) + groups: set[str] = set() + for path in hosts: + try: + groups |= inventory_groups(str(path)) + except _UNREADABLE as exc: + if (message := _unreadable(path, exc)) not in errors: + errors.append(message) + return documents, groups, errors + + +def _host_files(directory: Path) -> list[Path]: + files: list[Path] = [] + for entry in sorted(directory.iterdir()): + if _SKIPPED_NAMES.search(entry.name) or entry.name.endswith(_SKIPPED_SUFFIXES): + continue + if entry.is_dir(): + files.extend(_host_files(entry)) + elif entry.is_file(): + files.append(entry) + return files + + +def _unreadable(path: Path, exc: Exception) -> str: + if isinstance(exc, UnicodeDecodeError): + reason = "it is not UTF-8" + elif isinstance(exc, MarkedYAMLError) and exc.problem_mark is not None: + reason = f"{exc.problem} at line {exc.problem_mark.line + 1}" + else: + reason = str(exc) + return ( + f"{path}: cannot read the inventory file ({reason}); the pull changes " + "nothing while an inventory file is unreadable" + ) diff --git a/cli/administration/roles/list/__init__.py b/cli/administration/roles/list/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/cli/administration/roles/list/__main__.py b/cli/administration/roles/list/__main__.py new file mode 100644 index 0000000000..1f0200c5e6 --- /dev/null +++ b/cli/administration/roles/list/__main__.py @@ -0,0 +1,22 @@ +from __future__ import annotations + +import argparse + +from cli.administration.roles.marker import placed_roles, provenance +from utils.cache import ROLES_DIR + + +def main(argv: list[str] | None = None) -> int: + argparse.ArgumentParser( + description=( + "Print the custom roles a pull placed under roles/ of this checkout, " + "one per line with its source and resolved commit." + ) + ).parse_args(argv) + for role in placed_roles(ROLES_DIR): + print(f"{role.name}: {provenance(role)}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cli/administration/roles/marker.py b/cli/administration/roles/marker.py new file mode 100644 index 0000000000..3dbf05163c --- /dev/null +++ b/cli/administration/roles/marker.py @@ -0,0 +1,118 @@ +"""The marker that identifies a custom role the pull placed under ``roles/``. + +The marker names the directory it was placed as, so a copy of a placed +role under another name, which carries the same file, never counts as +placed. It is written and read without following a symbolic link. +""" + +from __future__ import annotations + +import os +import shutil +import stat +from typing import TYPE_CHECKING + +from utils.roles.custom import PREFIX + +if TYPE_CHECKING: + from pathlib import Path + +MARKER_FILE = ".infinito-custom-role" +MARKER_HEADER = "# infinito-nexus custom role" +_MARKER_LIMIT = 4096 + + +def marker_text(directory: str, group: str, provenance: str) -> str: + """Return the content of the marker file. + + Args: + directory: the name the role directory is placed as under ``roles/``. + group: the inventory group the role was pulled for. + provenance: the source and resolved commit the role was placed from. + """ + return ( + f"{MARKER_HEADER}\ndirectory: {directory}\ngroup: {group}\n" + f"source: {provenance}\n" + ) + + +def write_marker(role: Path, group: str, provenance: str) -> None: + """Write the marker into a staged role, replacing whatever entry holds its name. + + The entry is removed without following it and the marker is created + exclusively, so a symbolic link shipped under that name never + redirects the write. + + Args: + role: the staged role directory, named as it is placed. + group: the inventory group the role was pulled for. + provenance: the source and resolved commit the role was placed from. + """ + marker = role / MARKER_FILE + try: + mode = marker.lstat().st_mode + except FileNotFoundError: + mode = None + if mode is not None and stat.S_ISDIR(mode): + shutil.rmtree(marker) + elif mode is not None: + marker.unlink() + descriptor = os.open( + marker, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644 + ) + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + handle.write(marker_text(role.name, group, provenance)) + + +def is_placed(path: Path) -> bool: + """Return whether the pull placed ``path``: its marker names ``path`` itself. + + Args: + path: an entry of the role search directory. + """ + return not path.is_symlink() and _fields(path).get("directory") == path.name + + +def provenance(path: Path) -> str: + """Return the source and resolved commit recorded for a placed role. + + Args: + path: a role directory :func:`is_placed` accepts. + """ + return _fields(path).get("source", "") + + +def custom_entries(roles_dir: Path) -> list[Path]: + """Return every ``roles/web-app-cst-*`` entry, placed or not, sorted. + + Args: + roles_dir: the role search directory. + """ + return sorted(roles_dir.glob(f"{PREFIX}*")) + + +def placed_roles(roles_dir: Path) -> list[Path]: + """Return the custom roles the pull placed under ``roles_dir``, sorted. + + Args: + roles_dir: the role search directory. + """ + return [entry for entry in custom_entries(roles_dir) if is_placed(entry)] + + +def _fields(role: Path) -> dict[str, str]: + # Exception: O_NONBLOCK keeps a FIFO planted under the marker name from + # blocking the open; the fstat below refuses it. + try: + descriptor = os.open( + role / MARKER_FILE, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK + ) + except OSError: + return {} + with os.fdopen(descriptor, encoding="utf-8", errors="replace") as handle: + if not stat.S_ISREG(os.fstat(descriptor).st_mode): + return {} + lines = handle.read(_MARKER_LIMIT).splitlines() + if not lines or lines[0] != MARKER_HEADER: + return {} + return dict(line.split(": ", 1) for line in lines[1:] if ": " in line) diff --git a/cli/administration/roles/paths.py b/cli/administration/roles/paths.py new file mode 100644 index 0000000000..17d4362eec --- /dev/null +++ b/cli/administration/roles/paths.py @@ -0,0 +1,7 @@ +"""Where custom roles are staged before the pull moves them under ``roles/``.""" + +from __future__ import annotations + +from utils.cache import PROJECT_ROOT + +WORK_DIR = PROJECT_ROOT / "build" / "custom-roles" diff --git a/cli/administration/roles/placement.py b/cli/administration/roles/placement.py new file mode 100644 index 0000000000..631cfc6064 --- /dev/null +++ b/cli/administration/roles/placement.py @@ -0,0 +1,233 @@ +"""Place the custom roles an inventory declares under ``roles/`` and remove them again. + +A pull stages every declared role in a work directory outside ``roles/`` +and checks it before the first entry of ``roles/`` changes, so a refused +pull leaves ``roles/`` as it was. A pull or clean only ever replaces or +removes the directories the pull placed itself, whose marker names them. + +Both hold an exclusive lock under the work directory, so two of them on +one checkout never interleave, and clear what an interrupted run left +there. They swap entries by rename and delete the old copies only after +the swap, so an interrupt never leaves a declared role missing. +""" + +from __future__ import annotations + +import contextlib +import fcntl +import os +import shutil +import sys +import tempfile +from pathlib import Path +from typing import TYPE_CHECKING + +from yaml import YAMLError + +from utils.cache.yaml import load_yaml_tagged +from utils.roles.custom import CustomRoleError +from utils.roles.mapping import ROLE_FILE_META_MAIN, ROLE_FILE_VARS_MAIN + +from .declaration import read_declarations +from .inventory import is_host_list +from .marker import MARKER_FILE, custom_entries, is_placed, write_marker +from .source import check, stage + +if TYPE_CHECKING: + from collections.abc import Iterator + + from .declaration import Source + +LOCK_FILE = ".lock" +_LEFT = "left in place, the pull did not place it" + + +def pull(inventory: Path, roles_dir: Path, work_dir: Path) -> list[str]: + """Place the custom roles *inventory* declares and remove the ones it dropped. + + Args: + inventory: the inventory file or directory; an inline host list + such as ``localhost,`` declares nothing and changes nothing. + roles_dir: the ``roles/`` of the core checkout that runs the deploy. + work_dir: staging directory outside ``roles_dir`` on its filesystem. + + Returns: + One line per placed or removed role, naming its source and + resolved commit, and one per ``roles/web-app-cst-*`` entry the + pull left alone. + + Raises: + CustomRoleError: naming the group, or the file, that stops the run. + """ + if is_host_list(inventory): + return [] + if not inventory.exists(): + raise CustomRoleError( + f"inventory {inventory} is neither a file nor a directory" + ) + declared, errors = read_declarations(inventory, roles_dir) + if errors: + raise CustomRoleError("\n".join(errors)) + if not declared and not custom_entries(roles_dir): + return [] + with _locked(work_dir): + return _place(declared, roles_dir, work_dir) + + +def clean(roles_dir: Path, work_dir: Path) -> list[str]: + """Remove every ``roles/web-app-cst-*`` directory the pull placed and nothing else. + + Args: + roles_dir: the role search directory. + work_dir: staging directory outside ``roles_dir`` on its filesystem. + + Returns: + One line per ``roles/web-app-cst-*`` entry: removed, or left in + place because the pull did not place it. + """ + with _locked(work_dir): + entries = custom_entries(roles_dir) + placed = [entry for entry in entries if is_placed(entry)] + holders: list[Path] = [] + try: + _rename_all( + [(entry, _retired(entry, work_dir, holders)) for entry in placed] + ) + finally: + _discard(holders) + return [ + f"{entry.name}: removed" if entry in placed else f"{entry.name}: {_LEFT}" + for entry in entries + ] + + +def _place(declared: dict[str, Source], roles_dir: Path, work_dir: Path) -> list[str]: + entries = custom_entries(roles_dir) + for group, source in sorted(declared.items()): + check(group, source, entries, roles_dir) + _check_target(roles_dir / group) + undeclared = [entry for entry in entries if entry.name not in declared] + lines: list[str] = [] + staged: list[tuple[Path, Path]] = [] + holders: list[Path] = [] + try: + for group, source in sorted(declared.items()): + staging = _holder(work_dir, group, holders) / group + origin = stage(group, source, staging) + _check_role(group, staging) + write_marker(staging, group, origin) + staged.append((staging, roles_dir / group)) + lines.append(f"{group}: {origin}") + for _staging, target in staged: + _check_target(target) + dropped = [entry for entry in undeclared if is_placed(entry)] + moves = [(entry, _retired(entry, work_dir, holders)) for entry in dropped] + for staging, target in staged: + if os.path.lexists(target): + moves.append((target, _retired(target, work_dir, holders))) + moves.append((staging, target)) + _rename_all(moves) + finally: + _discard(holders) + lines.extend( + f"{entry.name}: removed, the inventory no longer declares it" + if entry in dropped + else f"{entry.name}: {_LEFT}" + for entry in undeclared + ) + return sorted(lines) + + +def _check_target(target: Path) -> None: + if target.is_symlink(): + raise CustomRoleError( + f"{target.name}: {target} is a symbolic link to {target.readlink()}, " + f"not a role the pull placed; remove the link (rm {target}) and pull again" + ) + if target.exists() and not is_placed(target): + raise CustomRoleError( + f"{target.name}: {target} was not placed by a pull (its {MARKER_FILE} " + "does not name it); the pull never replaces it, remove it by hand" + ) + + +def _check_role(group: str, staged: Path) -> None: + if (staged / MARKER_FILE).is_symlink(): + raise CustomRoleError( + f"{group}: source.path {MARKER_FILE} is a symbolic link; the pull " + "refuses a source that could redirect the marker it writes" + ) + if not (staged / ROLE_FILE_META_MAIN).is_file(): + raise CustomRoleError( + f"{group}: source.path holds no {ROLE_FILE_META_MAIN}, so it is no role directory" + ) + variables = staged / ROLE_FILE_VARS_MAIN + try: + data = load_yaml_tagged(variables) if variables.is_file() else None + except (ValueError, YAMLError) as exc: + raise CustomRoleError( + f"{group}: {ROLE_FILE_VARS_MAIN} cannot be read: {exc}" + ) from exc + application_id = data.get("application_id") if isinstance(data, dict) else None + if application_id != group: + raise CustomRoleError( + f"{group}: {ROLE_FILE_VARS_MAIN} application_id is {application_id!r}, but the group is '{group}'; core never renames a role" + ) + + +@contextlib.contextmanager +def _locked(work_dir: Path) -> Iterator[None]: + work_dir.mkdir(parents=True, exist_ok=True) + lock = work_dir / LOCK_FILE + descriptor = os.open(lock, os.O_RDONLY | os.O_CREAT | os.O_NOFOLLOW, 0o644) + try: + try: + fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + print( + f"[INFO] waiting for another custom-role pull or clean of this checkout ({lock})", + file=sys.stderr, + flush=True, + ) + fcntl.flock(descriptor, fcntl.LOCK_EX) + _discard([entry for entry in work_dir.iterdir() if entry.name != LOCK_FILE]) + yield + finally: + os.close(descriptor) + + +def _holder(work_dir: Path, prefix: str, holders: list[Path]) -> Path: + holder = Path(tempfile.mkdtemp(prefix=f"{prefix}.", dir=work_dir)) + holders.append(holder) + return holder + + +def _retired(entry: Path, work_dir: Path, holders: list[Path]) -> Path: + return _holder(work_dir, f"{entry.name}.retired", holders) / entry.name + + +def _rename_all(moves: list[tuple[Path, Path]]) -> None: + done: list[tuple[Path, Path]] = [] + try: + for old, new in moves: + old.rename(new) + done.append((old, new)) + except BaseException: + for old, new in reversed(done): + new.rename(old) + raise + + +def _discard(entries: list[Path]) -> None: + for entry in entries: + try: + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + except OSError as exc: + print( + f"[WARN] cannot remove {entry} ({exc}); container-owned leftovers " + "go with make clean-container-owned", + file=sys.stderr, + ) diff --git a/cli/administration/roles/pull/__init__.py b/cli/administration/roles/pull/__init__.py new file mode 100644 index 0000000000..a50a1bac8c --- /dev/null +++ b/cli/administration/roles/pull/__init__.py @@ -0,0 +1,5 @@ +from __future__ import annotations + +from .command import main, pull_or_exit + +__all__ = ["main", "pull_or_exit"] diff --git a/cli/administration/roles/pull/__main__.py b/cli/administration/roles/pull/__main__.py new file mode 100644 index 0000000000..32f6bc12c4 --- /dev/null +++ b/cli/administration/roles/pull/__main__.py @@ -0,0 +1,6 @@ +from __future__ import annotations + +from .command import main + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/cli/administration/roles/pull/command.py b/cli/administration/roles/pull/command.py new file mode 100644 index 0000000000..b04cb5386e --- /dev/null +++ b/cli/administration/roles/pull/command.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +import argparse +import re +import sys +import tarfile +from pathlib import Path + +from yaml import YAMLError + +from cli.administration.roles.paths import WORK_DIR +from cli.administration.roles.placement import pull +from utils.cache import ROLES_DIR +from utils.roles.custom import CustomRoleError + +_URL_USERINFO = re.compile(r"(?<=://)[^/\s@'\"]+@") + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description=( + "Pull the custom roles (web-app-cst-*) an inventory declares into " + "roles/, replace the ones an earlier pull placed and remove the ones " + "it no longer declares, without deploying." + ), + ) + parser.add_argument( + "inventory", + help="Inventory file or directory, or an inline host list such as 'localhost,'.", + ) + return parser + + +def pull_or_exit(inventory: str) -> list[str]: + """Pull the custom roles of *inventory*; exit 1 when the pull is refused. + + The reason never carries the credentials of a URL. + + Args: + inventory: the inventory file or directory, or an inline host list. + + Returns: + One line per placed, removed or untouched custom role; none and + no output when nothing is declared or placed. + """ + try: + lines = pull(Path(inventory), ROLES_DIR, WORK_DIR) + except (CustomRoleError, OSError, tarfile.TarError, YAMLError) as exc: + reason = _URL_USERINFO.sub("***@", str(exc)) + print(f"\n[ERROR] Custom roles refused:\n{reason}\n", file=sys.stderr) + sys.exit(1) + for line in lines: + print(f"custom role {line}", flush=True) + return lines + + +def main(argv: list[str] | None = None) -> int: + args = build_parser().parse_args(argv) + pull_or_exit(args.inventory) + return 0 diff --git a/cli/administration/roles/source.py b/cli/administration/roles/source.py new file mode 100644 index 0000000000..cdeba91acb --- /dev/null +++ b/cli/administration/roles/source.py @@ -0,0 +1,177 @@ +"""Check the source of a custom role and stage its content.""" + +from __future__ import annotations + +import io +import os +import shutil +import subprocess +import tarfile +import tempfile +from pathlib import Path +from typing import TYPE_CHECKING + +from utils.roles.custom import CustomRoleError + +if TYPE_CHECKING: + from .declaration import Source + +_COPY_IGNORE = shutil.ignore_patterns(".git", "__pycache__") +_DROPPED_ENV = frozenset( + { + "GIT_ALTERNATE_OBJECT_DIRECTORIES", + "GIT_ASKPASS", + "GIT_COMMON_DIR", + "GIT_DIR", + "GIT_INDEX_FILE", + "GIT_OBJECT_DIRECTORY", + "GIT_WORK_TREE", + "SSH_ASKPASS", + } +) + + +def check(group: str, source: Source, placements: list[Path], roles_dir: Path) -> None: + """Refuse a source before anything is fetched. + + Args: + group: the custom role's inventory group. + source: its validated declaration. + placements: every ``roles/web-app-cst-*`` entry that exists now. + roles_dir: the core ``roles/`` the role is placed in. + + Raises: + CustomRoleError: for a missing local directory, a local source the + pull would delete, or a version that is no tag or full commit SHA. + """ + if source.local: + _check_local(group, source, [roles_dir / group, *placements], roles_dir) + if source.version is None or source.commit: + return + refs = { + line.split("\t", 1)[1] + for line in _git( + None, ["ls-remote", "--", source.url], f"{group}: git ls-remote failed" + ) + .decode(errors="replace") + .splitlines() + if "\t" in line + } + if f"refs/heads/{source.version}" in refs: + raise CustomRoleError( + f"{group}: source.version '{source.version}' names a branch; pin a tag or a full commit SHA" + ) + if f"refs/tags/{source.version}" not in refs: + raise CustomRoleError( + f"{group}: source.version '{source.version}' is neither a tag nor a full commit SHA" + ) + + +def stage(group: str, source: Source, target: Path) -> str: + """Copy the role of ``source`` into ``target`` and describe what was copied. + + Args: + group: the custom role's inventory group. + source: a checked declaration. + target: a path that does not exist yet; it becomes the role directory. + + Returns: + The source and, for a pinned version, the resolved commit. + + Raises: + CustomRoleError: the source cannot be read, or it holds an entry, + such as a link to an absolute path, the pull refuses to unpack. + """ + if source.version is None: + content = Path(source.url) / source.path + if not content.is_dir(): + raise CustomRoleError( + f"{group}: source.path is not a directory in the source" + ) + shutil.copytree(content, target, symlinks=True, ignore=_COPY_IGNORE) + return source.describe() + with tempfile.TemporaryDirectory(prefix="infinito-custom-role-") as scratch: + _git(scratch, ["init", "--quiet", "--bare"], f"{group}: git init failed") + _git( + scratch, + [ + "fetch", + "--quiet", + "--depth", + "1", + "--no-tags", + "--", + source.url, + source.version, + ], + f"{group}: git fetch of {source.version} failed", + ) + commit = ( + _git( + scratch, + ["rev-parse", "--verify", "FETCH_HEAD^{commit}"], + f"{group}: {source.version} names no commit", + ) + .decode() + .strip() + ) + tree = f"{commit}:{source.path}" + kind = _git( + scratch, + ["cat-file", "-t", tree], + f"{group}: source.path is not a directory in the source", + ) + if kind.decode().strip() != "tree": + raise CustomRoleError( + f"{group}: source.path is not a directory in the source" + ) + archive = _git( + scratch, + ["archive", "--format=tar", tree], + f"{group}: git archive of source.path failed", + ) + target.mkdir() + try: + with tarfile.open(fileobj=io.BytesIO(archive)) as tar: + tar.extractall(target, filter="data") + except tarfile.TarError as exc: + raise CustomRoleError( + f"{group}: source.path holds an entry the pull refuses to unpack: {exc}" + ) from exc + return f"{source.describe()} (commit {commit})" + + +def _check_local( + group: str, source: Source, placements: list[Path], roles_dir: Path +) -> None: + if not Path(source.url).is_dir(): + raise CustomRoleError(f"{group}: source.url {source.url} is not a directory") + role = (Path(source.url) / source.path).resolve() + for placement in placements: + resolved = placement.resolve() + if role == resolved or role.is_relative_to(resolved): + raise CustomRoleError( + f"{group}: local source {role} lies in the placement directory {placement} under {roles_dir}; a pull never deletes its own source" + ) + + +def _git(cwd: str | None, arguments: list[str], failure: str) -> bytes: + # Exception: a git hook exports GIT_DIR, GIT_INDEX_FILE and friends, which + # would point the scratch repository at the core checkout; the askpass + # helpers and the detached session keep a fetch that needs credentials + # from prompting. + env = {key: value for key, value in os.environ.items() if key not in _DROPPED_ENV} + env.update(GIT_TERMINAL_PROMPT="0", SSH_ASKPASS_REQUIRE="never") + result = subprocess.run( + ["git", *arguments], + cwd=cwd, + env=env, + stdin=subprocess.DEVNULL, + capture_output=True, + start_new_session=True, + check=False, + ) + if result.returncode != 0: + detail = result.stderr.decode(errors="replace").strip() + raise CustomRoleError(f"{failure}: {detail}") + return result.stdout diff --git a/cli/build/docs/readme/cosmos.py b/cli/build/docs/readme/cosmos.py index 5153901765..e55277af6f 100644 --- a/cli/build/docs/readme/cosmos.py +++ b/cli/build/docs/readme/cosmos.py @@ -11,6 +11,9 @@ The role box lists EVERY service the role declares. Around it: above: another role names this one, or declares a service keyed by this role's ``provides`` name (e.g. web-app-keycloak ``provides: sso`` and every role with an ``sso`` service). + An in-tree role never lists a custom role (``web-app-cst-*``) + here: Git ignores custom roles, so a tracked README never + names one. ``provides`` matching runs in both directions, so a provider (e.g. openldap ``provides: ldap``) is picked up even when the consuming flag uses a @@ -44,6 +47,7 @@ from utils.roles.applications.services.registry import ( build_service_registry_from_roles_dir, is_explicit_truth, ) +from utils.roles.custom import is_custom from utils.roles.deploy import role_deploy_modes from utils.roles.mapping import ROLE_FILE_META_MAIN, ROLE_FILE_META_SERVICES from utils.symbol_glossary import to_emoji @@ -298,7 +302,7 @@ def derive_cosmos_mermaid(role_dir: Path, role_name: str) -> str: dpt_kind: dict[str, str] = {} gear_dependents: set[str] = set() for other, other_services in meta.items(): - if other == role_name: + if other == role_name or (is_custom(other) and not is_custom(role_name)): continue kind = _consumption_kind(other_services, role_name, my_provides, my_primary_key) if role_name in ansible_deps.get(other, set()): diff --git a/cli/build/docs/readme/overview.py b/cli/build/docs/readme/overview.py index f3df36aacd..ced98e4bd1 100644 --- a/cli/build/docs/readme/overview.py +++ b/cli/build/docs/readme/overview.py @@ -10,7 +10,8 @@ run; every other section stays untouched. Rows are the invokable roles, sorted ascending by the Entity column. Rows are the invokable roles inside the tested lifecycle envelope, sorted -ascending by name. +ascending by name. Custom roles (``web-app-cst-*``) are left out: Git ignores +them, so the tracked README never names one. Columns:: @@ -34,6 +35,7 @@ from pathlib import Path from cli.meta.roles.applications.complexity.model import compute_complexity_rows from utils.cache.files import PROJECT_ROOT, read_text from utils.cache.yaml import load_yaml_any +from utils.roles.custom import is_custom from utils.roles.entity.name import entity_name from utils.roles.lifecycle import tested_lifecycles from utils.roles.mapping import ( @@ -111,7 +113,9 @@ def build_table(roles_dir: Path) -> str: roles = sorted( p.name for p in roles_dir.iterdir() - if p.is_dir() and _is_role_invokable(p.name, invokable_paths) + if p.is_dir() + and not is_custom(p.name) + and _is_role_invokable(p.name, invokable_paths) ) complexity = {row.name: row for row in compute_complexity_rows(roles_dir)} roles = [ diff --git a/default.env b/default.env index ef2007bab6..310e6e6e38 100644 --- a/default.env +++ b/default.env @@ -205,6 +205,9 @@ INFINITO_DOCKER_VOLUME=docker # Stack domain for vhosts, certs and fixtures; a CI/dev default a real deploy overrides; a worktree gets .INFINITO_DNS_DOMAIN. INFINITO_DOMAIN=main.infinito.test +# Comma-separated absolute host directories mounted read-only at the same path into the infinito container; empty mounts none. +INFINITO_EXTRA_MOUNTS= + # Repo-relative path of the filesystem userland install script (ext4, btrfs, zfs). INFINITO_FILESYSTEM_INSTALL_SCRIPT=scripts/install/filesystem.sh @@ -259,6 +262,9 @@ INFINITO_LIFECYCLES="alpha beta rc stable maintenance" # Ansible limit pattern for local deploys. INFINITO_LIMIT_HOST=localhost +# Git ref whose merge-base with HEAD bounds local file lints to the files changed since; empty, a missing ref or CI lints every file. +INFINITO_LINT_DIFF_BASE=origin/main + # Where scripts/lint/wrapper.sh executes 'make lint*' / 'make autoformat': host | docker. INFINITO_LINT_RUNNER=docker diff --git a/docs/administration/deploy.md b/docs/administration/deploy.md index 94b56fea01..07a13a237f 100644 --- a/docs/administration/deploy.md +++ b/docs/administration/deploy.md @@ -40,5 +40,56 @@ When you need to redeploy after changes, repeat the same two `infinito` commands - Update `--include` whenever the target app set changes. - Use a `--vars-file` that matches the target environment. Production deploys MUST NOT point at the development sample file. +## Custom Roles 🧩 + +An inventory MAY deploy application roles that live in their own, possibly private, repositories. + +### Declare 📝 + +A custom role is an inventory group named `web-app-cst-`; a host joins it like any `web-app-*` group. Its application values mark it and name its source: + +```yaml +applications: + web-app-cst-security-check: + custom: true + source: + url: git@github.com:infinitonexus/php-landingpage.git + version: v1.4.0 + path: ansible/roles/web-app-cst-security-check +``` + +- `url` is a Git URL over HTTPS or SSH. During development an absolute local directory MAY stand in for it; without `version` its working tree is copied, uncommitted changes included. +- `version` is a tag or a full commit SHA. A branch is refused. +- `path` is the role directory inside the repository. Its name and the `application_id` in its `vars/main.yml` MUST equal the group. +- Values MUST be literal strings; Jinja is not rendered. + +### Pull 🔄 + +`infinito administration deploy dedicated` and `infinito administration deploy swarm` pull the declared roles into `roles/` of the controller's checkout before they read any role. Pass `--skip-pull` to deploy the roles already placed. The same steps run on their own: + +```bash +make roles-pull inventory=/etc/infinito.nexus/inventories/production/devices.yml +infinito administration roles list +make roles-clean +``` + +A pull stages every role outside `roles/` and changes `roles/` only when all of them passed, so a refused pull leaves it as it was. It replaces or removes only the directories it placed itself, whose marker names them, and refuses a declared name that meets a symbolic link, a hand-placed directory or a copy of a placed role. `make roles-clean` removes every `roles/web-app-cst-*` directory the pull placed and reports every other one it leaves in place. Git ignores `roles/web-app-cst-*`, so a pulled role never enters a core commit. + +For the local compose stack, `INFINITO_EXTRA_MOUNTS=[,]` mounts each directory read-only at the same path into the `infinito` container, so a local `url` resolves inside it. + +### Private Repositories 🔐 + +Git fetches with the SSH agent or the SSH configuration of the controller, so a deploy key goes into the agent or into `~/.ssh/config`: + +```text +Host github-landingpage + HostName github.com + User git + IdentityFile ~/.ssh/landingpage-deploy-key + IdentitiesOnly yes +``` + +The declaration then uses `url: github-landingpage:infinitonexus/php-landingpage.git`. A `url` that embeds a password or token is refused without being echoed, and a fetch that would ask for credentials fails instead of prompting. + For CLI installation prerequisites, see the [Installation Guide](installation.md). For the local development deploy flow (make targets, matrix variants, single-variant pinning), see [Local Deploy](../contributing/actions/deploy.md). diff --git a/docs/contributing/actions/testing/playwright.md b/docs/contributing/actions/testing/playwright.md index 48e6d59124..fecd3a54f3 100644 --- a/docs/contributing/actions/testing/playwright.md +++ b/docs/contributing/actions/testing/playwright.md @@ -30,7 +30,7 @@ Every Playwright-enabled role MUST provide exactly these two files: `playwright.config.js` MUST remain centralized in `roles/test-e2e-playwright/files/` and `package.json` in `roles/test-e2e-playwright/templates/package.json.j2` (rendered per-deploy into the staging dir). You MUST NOT duplicate or override either per role. -The `@playwright/test` version pinned into the rendered `package.json` comes from `playwright.version` in `roles/test-e2e-playwright/meta/services.yml` via the `image_version` filter. That YAML value is the single source of truth for the Playwright version. +The `@playwright/test` version pinned into the rendered `package.json` comes from `playwright.version` in `roles/test-e2e-playwright/meta/services.yml` via the `image_version` filter. That YAML value is the single source of truth for the Playwright version. The rendered `package.json` also installs `@axe-core/playwright` at `playwright.axe_version` from the same file, so a spec MAY run WCAG checks with `const { default: AxeBuilder } = require("@axe-core/playwright");`. ## CI Image Source 🪞 diff --git a/docs/contributing/artefact/files/plugins/lookup/applications.md b/docs/contributing/artefact/files/plugins/lookup/applications.md index 46577fc3d7..a2963acfe5 100644 --- a/docs/contributing/artefact/files/plugins/lookup/applications.md +++ b/docs/contributing/artefact/files/plugins/lookup/applications.md @@ -33,12 +33,12 @@ No other source is consulted. 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`, `SYSTEM_EMAIL_DOMAIN` or `group_names`, or a changed path or content of the tokens file). +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`, `SYSTEM_EMAIL_DOMAIN` or `group_names`, or changed tokens in the store the users are hydrated from). - The stage-wide task sits in `tasks/stages/01_constructor.yml` after the `networks` 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 carrier is parked again after every role in `tasks/utils/setup/role.yml`, after every nested application load in `tasks/utils/load/app.yml`, and after every persisted token in `roles/sys-token-store/tasks/write.yml`. The first two run on every host of the include, also on hosts the loaded role skips. A re-park whose key still matches serves the carried payload without rendering. +- The carrier is parked again after every role in `tasks/utils/setup/role.yml`, after every nested application load in `tasks/utils/load/app.yml`, and after every store write in `roles/sys-token-store/tasks/write_many.yml`, which `write.yml` runs for a single token. The first two run on every host of the include, also on hosts the loaded role skips. A re-park whose key still matches serves the carried payload without rendering. - The action renders with `application_id` removed from its variables, so the carried tree holds the play-scope result of every consumer-aligned `lookup('tls', ...)`, whichever role parks it. -- The tokens file enters the key as the SHA-256 of its content, memoised per inode, mtime and size, so a touch keeps the key. The carrier action opens the file before it computes the key, so an NFS client keys on revalidated attributes. +- The token store enters the key as the SHA-256 of exactly the tokens the users are hydrated from: the controller's tokens file until `sys-token-store` loads, the `sys_token_store_users` fact after. Both sources key alike when they hold the same tokens, so loading an unchanged store keeps the carrier, and a touch keeps the key. The carrier action opens the file before it computes the key, so an NFS client keys on revalidated attributes. - 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. diff --git a/docs/contributing/artefact/files/role/readme_md.md b/docs/contributing/artefact/files/role/readme_md.md index 1735a476df..239213c841 100644 --- a/docs/contributing/artefact/files/role/readme_md.md +++ b/docs/contributing/artefact/files/role/readme_md.md @@ -92,6 +92,8 @@ Link text MUST be a descriptive label or the domain name. Never use the full URL CI replays the Production block off the published page rather than off this file, so the instructions that are tested are the ones a reader sees. See [instructions.md](../../../tools/github/actions/instructions.md). +A custom role (`roles/web-app-cst-*`, pulled from its own repository) is exempt from the `Licensed under …` line above and states its own licence there instead; the rest of the format stays the same. + ## Formatting Rules 📏 - Role README files MUST NOT use emojis in headings. diff --git a/docs/contributing/artefact/git/branch.md b/docs/contributing/artefact/git/branch.md index 020cded368..895427d72a 100644 --- a/docs/contributing/artefact/git/branch.md +++ b/docs/contributing/artefact/git/branch.md @@ -17,7 +17,7 @@ The branch prefix MUST match the type of change. The [PR workflow](pull-request. ## Enforcement 🔒 -All rules in this document are actively enforced on `main` via GitHub branch protection. See [branch.md](../../tools/github/branch/security.md) for the full enforcement policy. +The [PR workflow](pull-request.md) fails its validation run when the branch prefix does not match the PR scope. The ruleset on `main` does not require that run to pass, see [branch.md](../../tools/github/branch/security.md) for the rules it enforces. The naming conventions below are additionally checked locally by the lint test [test_branch_name.py](../../../../tests/lint/repository/naming/test_branch_name.py), which fails `make test-lint` when the checked-out branch uses an unknown prefix (e.g. `feat/` instead of `feature/`) or a non-kebab-case description. diff --git a/docs/contributing/artefact/git/pipeline.md b/docs/contributing/artefact/git/pipeline.md index e0e923d34e..e69ee1385d 100644 --- a/docs/contributing/artefact/git/pipeline.md +++ b/docs/contributing/artefact/git/pipeline.md @@ -40,7 +40,7 @@ The `security-codeql` job runs the CodeQL scan (catalogued in the `Security and ### 3. Linting 🧹 -The `lint` job runs [call-lint.yml](../../../../.github/workflows/call-lint.yml): `make lint` fans every lint check out in parallel, plus a hadolint SARIF job. It MUST pass before the pipeline continues. +The `lint` job runs [call-lint.yml](../../../../.github/workflows/call-lint.yml): `make lint` fans every lint check out in parallel, hadolint on `Dockerfile` included. It MUST pass before the pipeline continues. ### 4. CI Image Build 🐳 diff --git a/docs/contributing/tools/github/actions/secrets.md b/docs/contributing/tools/github/actions/secrets.md index 54cefb8974..25a0d0398a 100644 --- a/docs/contributing/tools/github/actions/secrets.md +++ b/docs/contributing/tools/github/actions/secrets.md @@ -15,6 +15,27 @@ Repository secrets MUST be set under **Settings → Secrets and variables → Ac | `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. | +| `CI_SYNC_MAIN_TOKEN` | [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml) | Fine-grained token the `🔄 Sync main` job pushes the source repository's `main` with. | In every repository whose `CI_SYNC_MAIN_SOURCE_REPOSITORY` names another repository, which a fork does by default. | + +## `CI_SYNC_MAIN_TOKEN` 🔄 + +### How to create the token 🛠️ + +1. Open **Settings → Developer settings → Personal access tokens → Fine-grained tokens → Generate new token** on the account that owns the fork. +2. Set **Resource owner** to that account and **Repository access** to **Only select repositories**, selecting the fork alone. +3. Grant these repository permissions and nothing else: + - `Contents`: **Read and write** (force-push of `main`). + - `Workflows`: **Read and write** (the pushed `main` carries `.github/workflows/**`). + - `Metadata`: **Read** (default, cannot be removed). +4. Choose an expiration date and note it; an expired token fails the job like a missing one. +5. In the fork, add it under **Settings → Secrets and variables → Actions → Secrets → New repository secret** as `CI_SYNC_MAIN_TOKEN`. + +### Failure mode when the secret is missing 💥 + +| Repository | Behaviour | +|---|---| +| `infinito-nexus/core`, or a repository with the sync disabled through `CI_SYNC_MAIN_SOURCE_REPOSITORY` | The job prints that the sync is skipped and succeeds. The secret is not read. | +| Any other repository | [main_from_repository.sh](../../../../../scripts/github/sync/main_from_repository.sh) fails before any fetch or push and names the secret. The run is marked failed; the other jobs of the run are unaffected. | ## `API_OPENAI_KEY`, `API_ANTHROPIC_KEY`, `API_OPENROUTER_KEY` 🤖 diff --git a/docs/contributing/tools/github/actions/workflows.md b/docs/contributing/tools/github/actions/workflows.md index a1c390b4f1..5a826a3a23 100644 --- a/docs/contributing/tools/github/actions/workflows.md +++ b/docs/contributing/tools/github/actions/workflows.md @@ -44,7 +44,7 @@ Trigger column legend: **auto** = fires automatically (push, pull_request, sched |---|---|---|---| | [cron-security-codeql.yml](../../../../../.github/workflows/cron-security-codeql.yml): `🔐 Scan with CodeQL` | CodeQL static analysis. Invoked by [call-orchestrator.yml](../../../../../.github/workflows/call-orchestrator.yml) so every CI run produces a single scan; additionally runs on a weekly cron so coverage does not drop when no pushes land on `main`. See [pipeline.md](../../../artefact/git/pipeline.md) for the gating behaviour. | reusable, auto (`schedule`: weekly Mon 00:00 UTC) | none | | [cron-security-fuzz.yml](../../../../../.github/workflows/cron-security-fuzz.yml): `🧬 Fuzz parsers` | Runs the [atheris](https://github.com/google/atheris) harness [_yaml_bootstrap.py](../../../../../tests/fuzz/_yaml_bootstrap.py) for 15 minutes and uploads every crashing input as the `fuzz-crashes` artifact. Reproduce one locally with `pip install -e ".[fuzz]"` and `python3 tests/fuzz/_yaml_bootstrap.py `. | auto (`schedule`: weekly Sun 04:00 UTC), manual | none | -| [call-lint.yml](../../../../../.github/workflows/call-lint.yml): `🧹 Lint` | Runs `make lint` (every lint check in parallel: action, ansible, javascript, makefile, markdown, mermaid, packages, playwright, python, shellcheck) plus a hadolint SARIF job on `Dockerfile`. | reusable, manual | none | +| [call-lint.yml](../../../../../.github/workflows/call-lint.yml): `🧹 Lint` | Runs `make lint` (every lint check in parallel: action, ansible, css, dockerfile, javascript, makefile, markdown, mermaid, packages, php, playwright, python, ruby, shellcheck, sql). Hadolint checks `Dockerfile` as `lint-dockerfile` and uploads no SARIF. | reusable, manual | none | ### CI images 🐳 diff --git a/docs/contributing/tools/github/branch/security.md b/docs/contributing/tools/github/branch/security.md index 594c8331bc..c38e15dd47 100644 --- a/docs/contributing/tools/github/branch/security.md +++ b/docs/contributing/tools/github/branch/security.md @@ -4,11 +4,12 @@ See also [repository.md](../repository.md) for repository-wide security settings ## Enforcement 🔒 -- Ruleset is **Enabled (Enforced)** +- Ruleset `Main` is **Enabled (Enforced)** 👉 **Meaning for contributors:** -- All rules in this document are **actively enforced** on the default branch (`main`). +- Every rule marked ✅ in this document is **actively enforced** on the default branch (`main`). +- Rules marked ❌ are not part of the ruleset and block nothing. - Contributors MUST comply; violations will block pushes/merges. --- @@ -168,45 +169,34 @@ See also [repository.md](../repository.md) for repository-wide security settings --- -## Status Checks (CI/CD) ✅ +## Status Checks (CI/CD) ❌ -### Require Status Checks to Pass ✅ +### Require Status Checks to Pass ❌ 👉 **Contributor impact:** -- Your PR MUST pass CI before merging +- The ruleset names no required check, so a failing or missing CI run does not block the merge. +- CI in your fork still MUST be green before you open the PR, see [pull-request.md](../../../artefact/git/pull-request.md). --- -### Required Checks: NONE ⚠️ +### Require Branch to Be Up-To-Date ❌ 👉 **Contributor impact:** -- Currently, no checks are enforced -- Effectively: nothing blocks merge here - ---- - -### Require Branch to Be Up-To-Date ✅ - -👉 **Contributor impact:** - -- You MUST update your branch before merging -- Typically via: - - - merge `main` - - or rebase +- The ruleset does not block merging a branch that is behind `main`. +- Your branch still MUST be up to date with `main`, see [pull-request.md](../../../artefact/git/pull-request.md). --- ## Security 🔐 -### Require Signed Commits ✅ +### Require Signed Commits ❌ 👉 **Contributor impact:** -- All commits MUST be signed (GPG/SSH) -- Unsigned commits will be rejected +- The ruleset `Main` does not reject unsigned commits. +- The ruleset `Signed`, which requires signed commits on `main`, is disabled. --- @@ -228,6 +218,8 @@ Configured tools: - CodeQL (High severity) - Hadolint (High severity) +No workflow uploads Hadolint results to code scanning. Hadolint checks `Dockerfile` as `lint-dockerfile` inside `make lint` and writes no SARIF. + 👉 **Contributor impact:** - PR MUST NOT introduce high-severity issues diff --git a/docs/contributing/tools/github/repository.md b/docs/contributing/tools/github/repository.md index 9f69e43799..e202ea0f11 100644 --- a/docs/contributing/tools/github/repository.md +++ b/docs/contributing/tools/github/repository.md @@ -4,21 +4,21 @@ See also [branch.md](branch/security.md) for branch protection rules. ## Dependency Management 📦 -### Dependency Graph ❌ +### Dependency Graph ✅ -👉 Contributors may not have access to full dependency insights +👉 Dependency insights are available under Insights → Dependency graph -### Dependabot Alerts ❌ +### Dependabot Alerts ✅ -👉 Vulnerabilities may go unnoticed +👉 Known vulnerabilities in dependencies are reported as Dependabot alerts -### Dependabot Security Updates ❌ +### Dependabot Security Updates ✅ -👉 Contributors MUST update dependencies manually +👉 Dependabot opens PRs that bump vulnerable dependencies to a fixed release -### Dependabot Version Updates ❌ +### Dependabot Version Updates ✅ -👉 No automatic upgrade PRs +👉 Dependabot opens upgrade PRs for the ecosystems listed in [dependabot.yml](../../../../.github/dependabot.yml) --- @@ -38,27 +38,25 @@ See also [branch.md](branch/security.md) for branch protection rules. For GHCR authentication configuration see [authentication.md](../ghcr/authentication.md). -### Secret Scanning ❌ +### Secret Scanning ✅ -👉 Secrets may accidentally be committed +👉 Committed secrets are detected and reported as secret scanning alerts -### Push Protection ❌ +### Push Protection ✅ -👉 Commits with secrets are NOT blocked +👉 Pushes that contain a detected secret are blocked --- ## Summary for Contributors 📋 -Once enabled, you MUST: +You MUST: - Create a PR (no direct push) - Get 2 approvals - Get CODEOWNER approval (if applicable) - Resolve all comments - Re-approve after changes -- Keep branch up-to-date -- Use signed commits - Pass code scanning & quality checks You MUST NOT: diff --git a/docs/requirements/025-mcp-role-integration.md b/docs/requirements/025-mcp-role-integration.md index bb01d34e5b..492ef880d1 100644 --- a/docs/requirements/025-mcp-role-integration.md +++ b/docs/requirements/025-mcp-role-integration.md @@ -178,7 +178,7 @@ Direction gates the wiring: a `server` role only exposes `/mcp`, a `client` role 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. Each `blocked` role carries a row naming its reason token and the concrete obstacle, drawn from the per-role guidance the requirement already held. A lint enforced the three halves of that — a blocked role without a row, a token outside the documented vocabulary, and a blocked role shipping an enabled surface — by parsing the audit; it was removed together with the other two document-parsing lints, so the rows are now held by review rather than by a test. +- [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. Each `blocked` role carries a row naming its reason token and the concrete obstacle, drawn from the per-role guidance the requirement already held. A lint enforced the three halves of that (a blocked role without a row, a token outside the documented vocabulary, and a blocked role shipping an enabled surface) by parsing the audit; it was removed together with the other two document-parsing lints, so the rows are now held by review rather than by a test. - [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. diff --git a/docs/requirements/046-custom-roles.md b/docs/requirements/046-custom-roles.md new file mode 100644 index 0000000000..1506dfc159 --- /dev/null +++ b/docs/requirements/046-custom-roles.md @@ -0,0 +1,54 @@ +# 046 - Custom Roles from Inventory-Declared Sources + +## User Story + +As an operator, I want to declare application roles that live in their own repositories, such as the landing page and the store GUI, as ordinary inventory groups that Infinito.Nexus pulls into `roles/web-app-cst-*` and verifies like every in-tree role, so that these projects ship their role from their own repository without a fork of core and without a second, weaker set of checks. + +## Acceptance Criteria + +### Declaration + +- [x] A custom role is an ordinary inventory group named `web-app-cst-`; a host joins it the same way it joins any `web-app-*` group. +- [x] `applications.web-app-cst-.custom: true`, set in `host_vars` or anywhere else the inventory sets application values, marks the group as a custom role. +- [x] `applications.web-app-cst-.source` holds `url` (a Git URL over HTTPS or SSH), `version` (a tag or a full commit SHA) and `path` (the role directory inside that repository). +- [x] A custom role whose `source.version` names a branch, or whose `source` misses `url`, `version` or `path`, stops the run before anything is pulled, and the message names the group and the missing or rejected field. +- [x] A group named `web-app-cst-*` without `custom: true`, or `custom: true` on a group outside the `web-app-cst-` prefix, stops the run with a message naming the group. +- [x] The pull reads `custom` and `source` from the raw inventory and never renders them as templates: a value that holds a Jinja expression stops the run with a message naming the group and the field, so no templated value can trigger a fetch. +- [x] A `source.url` that embeds credentials stops the run without echoing the URL. + +### Authentication + +- [x] A private repository is fetched through the SSH agent or SSH configuration of the controller. +- [x] A fetch that needs interactive credentials fails instead of prompting. +- [x] No credential reaches the inventory, the `ansible-playbook` command line, Ansible variables or the deploy log. + +### Pull and placement + +- [x] Before the playbook starts, and so before the applications SPOT reads `roles/*/meta/`, the deploy pulls every custom role declared for the target hosts at its `source.version` and places `source.path` as `roles/web-app-cst-` in the core checkout that runs the deploy. +- [x] A `make` target pulls the custom roles an inventory declares into the local core checkout without deploying, so every other `make` target can run against them. +- [x] A local directory may stand in for `source.url` during development, so a role checkout is verified and deployed without a tag. +- [x] A local source that resolves to its own placement directory `roles/web-app-cst-` stops the run with a message naming the path, so a pull never deletes its own source. +- [x] A placed role whose directory name or `vars/main.yml` `application_id` differs from its group name stops the run with a message naming both values; core never renames a role. +- [x] Pulling again replaces each `roles/web-app-cst-*` directory with the pinned content, and removes the directory of a custom role the inventory no longer declares. +- [x] A pull that stops leaves `roles/` unchanged, and no staging or leftover directory of a pull appears under `roles/`. +- [x] A declared name that meets a symbolic link under `roles/`, or a directory the pull did not place, stops the run with a message naming it, and the pull never replaces or removes such a directory. +- [x] A command lists the placed custom roles with their source and resolved commit, and a `make` target removes every `roles/web-app-cst-*` directory the pull placed and nothing else. +- [ ] `INFINITO_EXTRA_MOUNTS=[,]` mounts each directory read-only at the same path into the `infinito` container when the stack is created, so a local `source.url` resolves inside the container; an entry that is not an existing absolute directory stops the stack start with an error naming it. +- [x] `roles/web-app-cst-*` is ignored by Git in core, so a pulled role never enters a core commit. +- [x] The `web-app-cst-` prefix is reserved: a lint fails on an in-tree role whose name starts with it. +- [x] `meta/categories.yml` declares `web-app-cst` as a category, so the entity name of `web-app-cst-` is `` and the container, database and volume names a custom role derives stay what they were before its rename. +- [x] A custom role whose entity name equals the entity name of an in-tree role stops the run with a message naming both roles. +- [ ] A swarm or Act run (`make swarm-*`, `make act-*`) carries the pulled custom roles into the copy of the core checkout its nodes use. + +### Verification + +- [ ] A pulled custom role is scanned by `make test`, `make lint` and `make quality-high` exactly like an in-tree role: no lint, unit or integration check skips `roles/web-app-cst-*`, and no check exists only for custom roles. The one exception is the licence: a custom role is exempt from the Infinito.Nexus licence wording the role README lint demands in Credits, and states its own licence instead. +- [ ] `make compose-deploy` deploys a pulled custom role through the same path as an in-tree role, including its Playwright specs. +- [ ] The README of `php-landingpage` and of `infinito-nexus-gui` documents the inventory format above for their role. +- [ ] `php-landingpage` names its role `web-app-cst-` in directory and `application_id`, and its CI pulls the role into a core checkout and runs core's `make test` and `make lint` against it. +- [ ] `infinito-nexus-gui` names its store role `web-app-cst-` in directory and `application_id`, and its CI pulls the role into a core checkout and runs core's `make test` and `make lint` against it. + +### Quality + +- [x] The pull, placement, validation and cleanup logic has unit tests, including a branch name refused as `source.version`, a role whose `application_id` differs from its group, and the removal of a role the inventory no longer declares. +- [ ] `make test` passes. diff --git a/docs/requirements/047-openbao-audit-device.md b/docs/requirements/047-openbao-audit-device.md new file mode 100644 index 0000000000..edda635639 --- /dev/null +++ b/docs/requirements/047-openbao-audit-device.md @@ -0,0 +1,19 @@ +# 047 - OpenBao Audit Device + +## User Story + +As an operator of applications that keep customer credentials in [`web-app-openbao`](../../roles/web-app-openbao/), I want every request to OpenBao recorded with the accessing identity and a timestamp, so that each read of a stored secret can be traced to the person or machine that made it. + +## Background + +OpenBao writes nothing about who read which secret unless an audit device is enabled. OpenBao 2.7 refuses to create audit devices through the API (`cannot enable audit device via API; use declarative, config-based audit device management instead`), so the device is declared in the server configuration. Once any audit device is enabled, OpenBao refuses requests it cannot log. The device therefore writes to the server's stdout, which cannot block. That output reaches the same container log as the rest of the server output. By default OpenBao replaces secret values in audit entries with salted HMACs, so the audit trail does not contain credentials. + +## Acceptance Criteria + +- [ ] The server configuration declares `audit "file" "stdout"` with `file_path = "stdout"`. +- [ ] The `ansible-admin` policy grants `read` and `sudo` on `sys/audit` to list audit devices, and no other policy of the role gains access to `sys/audit`. +- [ ] Every deploy fails unless `bao audit list` reports `stdout/` of type `file`; the check never reports changed. +- [ ] The deploy reads a probe secret with its AppRole session and fails unless the container log then holds an audit response entry for that read, carrying the request path, the `read` operation, a `display_name` and a `time`. +- [ ] Audit entries carry no plaintext secret value: the probe secret's value does not appear in the container log. +- [ ] The role README documents the audit device, its stdout destination and the deploy probe. +- [ ] `make compose-deploy` of `web-app-openbao` is green on a fresh stack and on a re-run. diff --git a/group_vars/all/11_oidc.yml b/group_vars/all/11_oidc.yml index 06ec4f0468..90f5d7a045 100644 --- a/group_vars/all/11_oidc.yml +++ b/group_vars/all/11_oidc.yml @@ -14,8 +14,7 @@ # Helper Variables: _oidc_client_realm: "{{ OIDC_OVERRIDE.CLIENT.REALM if OIDC_OVERRIDE is defined and OIDC_OVERRIDE.CLIENT is defined and OIDC_OVERRIDE.CLIENT.REALM is defined else SOFTWARE_DOMAIN }}" -_oidc_url: "{{ ( OIDC_OVERRIDE.URL if (OIDC_OVERRIDE is defined and OIDC_OVERRIDE.URL is defined) else (lookup('tls', 'web-app-keycloak', 'url.base')) ).rstrip('/') - }}" +_oidc_url: "{{ OIDC_OVERRIDE.URL.rstrip('/') if (OIDC_OVERRIDE is defined and OIDC_OVERRIDE.URL is defined) else lookup('tls', 'web-app-keycloak', 'url.origin') }}" _oidc_client_issuer_url: "{{ _oidc_url ~ '/realms/' ~ _oidc_client_realm }}" _oidc_client_id: "{{ OIDC_OVERRIDE.CLIENT.ID if OIDC_OVERRIDE is defined and OIDC_OVERRIDE.CLIENT is defined and OIDC_OVERRIDE.CLIENT.ID is defined else SOFTWARE_DOMAIN }}" diff --git a/group_vars/all/18_swarm.yml b/group_vars/all/18_swarm.yml index cf14e5924e..f179d71867 100644 --- a/group_vars/all/18_swarm.yml +++ b/group_vars/all/18_swarm.yml @@ -22,6 +22,9 @@ SWARM_INGRESS_GUARDED: "{{ swarm_ingress_endpoints.stdout_lines | swarm_ingress_ SWARM_INGRESS_PEERS: "{{ swarm_ingress_nodes.stdout_lines | swarm_node_addresses }}" +SWARM_MANAGER_PORT: 2377 +SWARM_LISTEN_ADDR: "0.0.0.0:{{ SWARM_MANAGER_PORT }}" + swarm: manager: advertise_addr: >- diff --git a/meta/categories.yml b/meta/categories.yml index b0bb9712e6..c2545db7e2 100644 --- a/meta/categories.yml +++ b/meta/categories.yml @@ -188,6 +188,13 @@ roles: run_after: [web-svc] invokable: true + cst: + title: "Custom Applications" + hanzi: "定制" # Means "custom-made" or "tailored". + description: "Application roles an inventory pulls from their own repositories into roles/; core never tracks them." + icon: "fas fa-puzzle-piece" + run_after: [web-app] + opt: title: "Webserver Optimation" glyph: "𓅱" diff --git a/meta/packages.yml b/meta/packages.yml index 0b35ae1cf2..8f265adfe8 100644 --- a/meta/packages.yml +++ b/meta/packages.yml @@ -150,6 +150,7 @@ iproute: - iproute2 RedHat: - iproute + batch: false iputils-ping: Archlinux: @@ -158,6 +159,7 @@ iputils-ping: - iputils-ping RedHat: - iputils + batch: false java-jdk: Archlinux: @@ -214,6 +216,7 @@ nfs-client: - nfs-common RedHat: - nfs-utils + batch: false npm: Archlinux: @@ -243,6 +246,7 @@ postfix: RedHat: - postfix - postfix-lmdb + batch: false retext: Archlinux: diff --git a/plugins/action/applications_carrier.py b/plugins/action/applications_carrier.py index b57393630b..d7da126d30 100644 --- a/plugins/action/applications_carrier.py +++ b/plugins/action/applications_carrier.py @@ -13,9 +13,11 @@ instead of rendering:: ``tasks/stages/01_constructor.yml`` parks three of them: a block-scoped one for the merge block, which it drops again at the block's end, one after the ``add_host`` tasks for the swarm bootstrap roles, parked only when -``DEPLOYMENT_MODE`` is ``swarm``, and the stage-wide one after the token store. ``merged_applications_cache_key`` reads ``group_names`` and the -tokens file's path and content digest, so a carrier whose groups or tokens no -longer match is rejected and the reader renders afresh:: +``DEPLOYMENT_MODE`` is ``swarm``, and the stage-wide one after the token store. ``merged_applications_cache_key`` reads ``group_names`` and a +digest of the tokens the users are hydrated from (the tokens file, or the +``sys_token_store_users`` fact once the token store loaded; both key alike for +the same tokens), so a carrier whose groups or tokens no longer match is +rejected and the reader renders afresh:: - name: 🧊 Drop the merge-block carrier so later stages re-render applications_carrier: @@ -23,7 +25,7 @@ longer match is rejected and the reader renders afresh:: ``tasks/utils/setup/role.yml`` parks one after every role, ``tasks/utils/load/app.yml`` one after every nested application load and -``roles/sys-token-store/tasks/write.yml`` one after every persisted token; +``roles/sys-token-store/tasks/write_many.yml`` one after every store write; where the key still matches they serve the carried payload without rendering. The result is masked by the action itself: the fact is the whole rendered diff --git a/plugins/action/package_install.py b/plugins/action/package_install.py index ea7fe211c1..60012326f1 100755 --- a/plugins/action/package_install.py +++ b/plugins/action/package_install.py @@ -17,7 +17,10 @@ role states what it needs and never how to get it:: Distribution repositories, the AUR, COPR, PPA and source builds all run through here, including the unprivileged build environment the AUR needs. :mod:`utils.packages.plan` decides which module calls that takes; this -plugin only executes them. +plugin only executes them. Ids whose plans only call the host's package +manager share one call, so a long list costs one transaction, and +:mod:`utils.packages.installed` skips that call when the host's package +database already shows every name in the requested state. Args: id: logical package id, or a list of ids, each declared either in the @@ -31,7 +34,7 @@ from __future__ import annotations import time from typing import Any -from ansible.errors import AnsibleActionFail +from ansible.errors import AnsibleActionFail, AnsibleError from ansible.plugins.action import ActionBase from utils.packages.calls import ( @@ -42,8 +45,9 @@ from utils.packages.calls import ( ModuleCall, ) from utils.packages.facts import distribution_and_family, read_fact +from utils.packages.installed import query_argv, state_holds from utils.packages.outcome import aggregate -from utils.packages.plan import build_plan +from utils.packages.plan import build_plan, merge_plans from utils.packages.registry import build_registry, project_root_from_env, resolve from utils.packages.schema import ROLE_FILE_META_PACKAGES, PackagesShapeError @@ -68,7 +72,7 @@ class ActionModule(ActionBase): registry = self._registry() role = self._role() - results: list[dict[str, Any]] = [] + plans: list[list[ModuleCall]] = [] skipped: list[str] = [] for package_id in package_ids: @@ -77,6 +81,10 @@ class ActionModule(ActionBase): if not plan: skipped.append(package_id) continue + plans.append(plan) + + results: list[dict[str, Any]] = [] + for plan in merge_plans(plans): results.extend(self._run_plan(plan, task_vars, facts)) return aggregate(results, skipped, distribution) @@ -106,7 +114,14 @@ class ActionModule(ActionBase): ) -> dict[str, Any]: """Run *call* once, or up to its retry policy while it keeps failing. Returns the last result, tagged with the module that - produced it.""" + produced it. A call whose state the host already holds does not + run at all.""" + if self._state_holds(call, task_vars, facts): + return { + "changed": False, + "msg": f"{', '.join(call.args['name'])} already {call.args['state']}", + "module": call.module, + } if call.retry is None: return self._tagged(call, task_vars, facts) result: dict[str, Any] = {} @@ -118,6 +133,23 @@ class ActionModule(ActionBase): time.sleep(call.retry.seconds) return result + def _state_holds( + self, call: ModuleCall, task_vars: dict[str, Any], facts: dict[str, Any] + ) -> bool: + pkg_mgr = read_fact(facts, "pkg_mgr") + argv = query_argv(call, pkg_mgr) + if argv is None: + return False + try: + result = self._execute_module( + module_name="ansible.builtin.command", + module_args={"argv": argv, "expand_argument_vars": False}, + task_vars=task_vars, + ) + except AnsibleError: + return False + return state_holds(call, pkg_mgr, result) + def _tagged( self, call: ModuleCall, task_vars: dict[str, Any], facts: dict[str, Any] ) -> dict[str, Any]: diff --git a/plugins/filter/seaweedfs.py b/plugins/filter/seaweedfs.py index f1029c6ece..bd5440616a 100644 --- a/plugins/filter/seaweedfs.py +++ b/plugins/filter/seaweedfs.py @@ -1,8 +1,17 @@ from __future__ import annotations +import json +import re + +from ansible.errors import AnsibleFilterError + VOLUME_GROW_BATCH = 7 VOLUME_SIZE_LIMIT_MB = 1024 MIN_FREE_SPACE_VOLUMES = 2 +POLICY_VERSION = "2012-10-17" +ANONYMOUS_DENY_SID = "DenyAnonymousRead" +NO_SUCH_BUCKET_POLICY = "NoSuchBucketPolicy" +_BUCKET_LIST_ENTRY = re.compile(r"(\S+)\tsize:") def min_free_space(): @@ -107,9 +116,106 @@ def seaweedfs_sidecar_script(bucket, s3_port, access_key, secret_key): ) +def seaweedfs_anonymous_deny_policy(bucket): + """Build the bucket policy that denies every unsigned read of *bucket*. + + SeaweedFS honours a public-read object or bucket ACL on an unsigned read + unless a bucket policy explicitly denies it first. A bare + ``Principal: "*"`` deny would also hit the consumer's own signed and + presigned requests; the ``Null`` condition on ``aws:username`` limits it to + unsigned ones, because SeaweedFS derives that key from a signed caller's + IAM user ARN and evaluates an unsigned request as principal ``*`` without + it. + + Args: + bucket: bucket the policy is attached to; scopes both the bucket ARN + (listings) and its object ARNs (GET/HEAD). + """ + return { + "Version": POLICY_VERSION, + "Statement": [ + { + "Sid": ANONYMOUS_DENY_SID, + "Effect": "Deny", + "Principal": "*", + "Action": ["s3:Get*", "s3:List*"], + "Resource": [f"arn:aws:s3:::{bucket}", f"arn:aws:s3:::{bucket}/*"], + "Condition": {"Null": {"aws:username": "true"}}, + } + ], + } + + +def seaweedfs_bucket_names(output): + """Return the bucket names a ``weed shell`` ``s3.bucket.list`` printed. + + Args: + output: stdout of the shell; every bucket line carries the name + followed by a tab and its ``size:`` column, and the first one may + follow the shell prompt on the same line. + """ + return _BUCKET_LIST_ENTRY.findall(str(output)) + + +def seaweedfs_stored_bucket_policy(output): + """Return the policy SeaweedFS reports for a bucket. + + Args: + output: stdout of the admin curl ``GET /?policy`` run with + ``-w '\\n%{http_code}'``: the response body, a newline, and the + HTTP status. + + Returns: + The stored policy document on HTTP 200, an empty dict on HTTP 404 + ``NoSuchBucketPolicy``, and ``None`` on every other answer, a missing + bucket (``NoSuchBucket``) included. + """ + body, _, status = str(output).rpartition("\n") + if status == "200": + return json.loads(body) + if status == "404" and NO_SUCH_BUCKET_POLICY in body: + return {} + return None + + +def seaweedfs_bucket_policy_target(stored, bucket, public): + """Return the policy *bucket* converges to. + + Every statement except ``DenyAnonymousRead`` is kept as stored; that one + is replaced by the current :func:`seaweedfs_anonymous_deny_policy` + statement on a private bucket and dropped on a public one. + + Args: + stored: policy document the bucket carries, an empty dict for none. + bucket: bucket the deny statement scopes. + public: whether the consumer is marked public; must be a bool. + + Returns: + The target policy document, or an empty dict when no statement + remains and the bucket must carry no policy. + """ + if not isinstance(public, bool): + raise AnsibleFilterError( + f"seaweedfs_bucket_policy_target: public must be a bool, got {public!r}" + ) + statements = [ + statement + for statement in stored.get("Statement", []) + if statement.get("Sid") != ANONYMOUS_DENY_SID + ] + if not public: + statements.extend(seaweedfs_anonymous_deny_policy(bucket)["Statement"]) + if not statements: + return {} + return {"Version": POLICY_VERSION, "Statement": statements} + + class FilterModule: def filters(self): return { + "seaweedfs_bucket_names": seaweedfs_bucket_names, + "seaweedfs_bucket_policy_target": seaweedfs_bucket_policy_target, "seaweedfs_command": seaweedfs_command, "seaweedfs_sidecar_script": seaweedfs_sidecar_script, + "seaweedfs_stored_bucket_policy": seaweedfs_stored_bucket_policy, } diff --git a/plugins/lookup/nginx.py b/plugins/lookup/nginx.py index c833e1348d..c00ad7037c 100644 --- a/plugins/lookup/nginx.py +++ b/plugins/lookup/nginx.py @@ -1,6 +1,9 @@ """Resolve nginx path configuration and an optional domain-specific server config path under ``//.conf``. +``files.lua`` is the body-filter Lua file of one vhost, +``/.lua``; it needs the domain term. + The ``want=`` kwarg is intentionally ignored: want-path is ALWAYS the first positional argument so callers can't accidentally pass it both ways. @@ -89,6 +92,8 @@ class LookupModule(LookupBase): raise AnsibleError("nginx: want_path is empty") domain = as_str(terms[1]).strip() if len(terms) == 2 else "" + if want == "files.lua" and not domain: + raise AnsibleError("nginx: files.lua requires a domain") applications = lookup_loader.get( "applications", loader=self._loader, templar=getattr(self, "_templar", None) @@ -201,5 +206,6 @@ class LookupModule(LookupBase): "protocol_overridden": bool(protocol_override), } resolved["files"]["domain"] = _join(servers_dir, protocol, f"{domain}.conf") + resolved["files"]["lua"] = _join(lua_dir, f"{domain}.lua") return [want_get(resolved, want)] diff --git a/plugins/lookup/package_batch.py b/plugins/lookup/package_batch.py new file mode 100644 index 0000000000..108bdc76a2 --- /dev/null +++ b/plugins/lookup/package_batch.py @@ -0,0 +1,58 @@ +"""Lookup ``package_batch``: the package ids a host installs in one run at +deploy start. + + {{ lookup('package_batch', group_names) }} + +The terms are every group of the host, after the swarm auto-placement, so a +role the service loader reaches on this host through any whitelist is covered. They are widened to +every role the deploy may run on the host +(:func:`utils.roles.invocations.deploy_closure`), and the sorted ids the +batch installs for those roles (:func:`utils.packages.batch.batch_ids`) are +returned. +""" + +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.packages.batch import batch_ids +from utils.packages.schema import PackagesShapeError +from utils.roles.invocations import deploy_closure +from utils.roles.validation.invokable import types_from_group_names + + +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)) + + vars_ = variables or getattr(self._templar, "available_variables", {}) or {} + group_names = [str(group) for group in vars_["group_names"]] + applications = lookup_loader.get( + "applications", loader=self._loader, templar=getattr(self, "_templar", None) + ).run([], variables=vars_)[0] + try: + roles = deploy_closure( + applications, + seeds, + project_root=PROJECT_ROOT, + host_types=types_from_group_names(group_names), + group_names=group_names, + ) + return [batch_ids(roles, PROJECT_ROOT)] + except (PackagesShapeError, TypeError, ValueError) as exc: + raise AnsibleError(f"package_batch: {exc}") from exc diff --git a/plugins/lookup/rbac_group_path.py b/plugins/lookup/rbac_group_path.py index 2b4bd66fd8..398b085740 100644 --- a/plugins/lookup/rbac_group_path.py +++ b/plugins/lookup/rbac_group_path.py @@ -36,7 +36,7 @@ Contract: The Keycloak group tree behind these paths is materialised by a per-application group-ldap-mapper -(roles/web-app-keycloak/tasks/update/05_per_app_mappers.yml), anchored at +(roles/web-app-keycloak/tasks/update/03_per_app_mappers.yml), anchored at `//` with `group.name.ldap.attribute=description`. """ diff --git a/plugins/lookup/tls.py b/plugins/lookup/tls.py index c585917372..fab23c0ed5 100644 --- a/plugins/lookup/tls.py +++ b/plugins/lookup/tls.py @@ -103,7 +103,8 @@ class LookupModule(LookupBase): web_protocol = "https" if enabled else "http" websocket_protocol = "wss" if enabled else "ws" web_port = 443 if enabled else 80 - base_url = f"{web_protocol}://{primary_domain}/" + origin = f"{web_protocol}://{primary_domain}" + base_url = f"{origin}/" resolved: dict[str, Any] = { "application_id": app_id, @@ -113,7 +114,7 @@ class LookupModule(LookupBase): "domains": {"primary": primary_domain, "all": all_domains}, "protocols": {"web": web_protocol, "websocket": websocket_protocol}, "ports": {"web": web_port}, - "url": {"base": base_url}, + "url": {"base": base_url, "origin": origin}, } if want: diff --git a/requirements/requirements.galaxy.yml b/requirements/requirements.galaxy.yml index ef98c31538..ac83f6ac7b 100644 --- a/requirements/requirements.galaxy.yml +++ b/requirements/requirements.galaxy.yml @@ -2,8 +2,8 @@ collections: - name: ansible.posix version: 2.2.2 - - name: ansible.mysql - version: 5.2.0 + - name: ansible.mariadb + version: 6.0.2 - name: kewlfft.aur version: 0.13.0 - name: community.general diff --git a/requirements/requirements.git.yml b/requirements/requirements.git.yml index 58808ee14c..a84faf36fc 100644 --- a/requirements/requirements.git.yml +++ b/requirements/requirements.git.yml @@ -5,10 +5,10 @@ collections: type: git version: 2.2.2 - - name: ansible.mysql - source: https://github.com/ansible-collections/ansible.mysql.git + - name: ansible.mariadb + source: https://github.com/ansible-collections/ansible.mariadb.git type: git - version: 5.2.0 + version: 6.0.2 - name: kewlfft.aur source: https://github.com/kewlfft/ansible-aur.git diff --git a/roles/dev-arduino/tasks/main.yml b/roles/dev-arduino/tasks/main.yml index 014a08da9a..071019fc53 100644 --- a/roles/dev-arduino/tasks/main.yml +++ b/roles/dev-arduino/tasks/main.yml @@ -1,8 +1,4 @@ --- -- name: 📦 install arduino developer tools - package_install: - id: arduino-ide - - name: "🔧 Add user {{ lookup('users', WORKSTATION_USER).username }} to arduino groups" ansible.builtin.user: name: "{{ lookup('users', WORKSTATION_USER).username }}" diff --git a/roles/dev-gcc/meta/packages.yml b/roles/dev-gcc/meta/packages.yml index 48d2291f03..cb7af00134 100644 --- a/roles/dev-gcc/meta/packages.yml +++ b/roles/dev-gcc/meta/packages.yml @@ -9,3 +9,4 @@ gcc: RedHat: - gcc - libstdc++ + batch: false diff --git a/roles/dev-gcc/tasks/main.yml b/roles/dev-gcc/tasks/main.yml index 63f36b1dd5..7e1011fe1e 100644 --- a/roles/dev-gcc/tasks/main.yml +++ b/roles/dev-gcc/tasks/main.yml @@ -1,7 +1,7 @@ --- - block: - name: 📦 Install GCC compiler and runtime (cross-distro) - package_install: + package_install: # nocheck: package-install sys-pip builds on gcc before the update role and the batch run id: gcc - ansible.builtin.set_fact: diff --git a/roles/dev-git/meta/packages.yml b/roles/dev-git/meta/packages.yml new file mode 100644 index 0000000000..2844b63173 --- /dev/null +++ b/roles/dev-git/meta/packages.yml @@ -0,0 +1,3 @@ +--- +git: + shared: true diff --git a/roles/dev-git/tasks/main.yml b/roles/dev-git/tasks/main.yml index 2785241996..0fd1085f6a 100644 --- a/roles/dev-git/tasks/main.yml +++ b/roles/dev-git/tasks/main.yml @@ -1,8 +1,4 @@ --- - block: - - name: "📦 Install git" - package_install: - id: git - - include_tasks: utils/once/flag.yml when: run_once_dev_git is not defined diff --git a/roles/dev-java/meta/packages.yml b/roles/dev-java/meta/packages.yml new file mode 100644 index 0000000000..53b5125418 --- /dev/null +++ b/roles/dev-java/meta/packages.yml @@ -0,0 +1,3 @@ +--- +java-jdk: + shared: true diff --git a/roles/dev-java/tasks/main.yml b/roles/dev-java/tasks/main.yml index 699f16e551..ed97d539c0 100644 --- a/roles/dev-java/tasks/main.yml +++ b/roles/dev-java/tasks/main.yml @@ -1,4 +1 @@ --- -- name: 📦 install java - package_install: - id: java-jdk diff --git a/roles/dev-make/tasks/main.yml b/roles/dev-make/tasks/main.yml index dbdec40ac3..ed97d539c0 100644 --- a/roles/dev-make/tasks/main.yml +++ b/roles/dev-make/tasks/main.yml @@ -1,4 +1 @@ --- -- name: 📦 install make - package_install: - id: make diff --git a/roles/dev-nix/meta/packages.yml b/roles/dev-nix/meta/packages.yml index 5bb467bd28..d4bad2f9fd 100644 --- a/roles/dev-nix/meta/packages.yml +++ b/roles/dev-nix/meta/packages.yml @@ -1,6 +1,10 @@ --- +ca-certificates: + shared: true + nix: Archlinux: - nix Debian: [] # nocheck: empty - the role installs nix from the official releases.nixos.org installer on this family RedHat: [] # nocheck: empty - the role installs nix from the official releases.nixos.org installer on this family + batch: false diff --git a/roles/dev-nix/tasks/00_core.yml b/roles/dev-nix/tasks/00_core.yml index bcd81755ae..f7c6f60536 100644 --- a/roles/dev-nix/tasks/00_core.yml +++ b/roles/dev-nix/tasks/00_core.yml @@ -3,12 +3,6 @@ # - Arch-based systems: install via package manager # - Non-Arch systems: use the official installer with SHA256 verification -# 0) Ensure CA trust is present and discover CA bundle path for Nix TLS -- name: "📦 Install the CA trust store" - package_install: - id: ca-certificates - become: true - - name: 🔍 Probe CA bundle candidate paths ansible.builtin.stat: path: "{{ item }}" @@ -30,7 +24,7 @@ }} - name: 📦 Install Nix via package manager on Arch-based systems - package_install: + package_install: # nocheck: package-install Arch only, other distros take the installer path id: nix become: true when: diff --git a/roles/dev-nodejs/tasks/main.yml b/roles/dev-nodejs/tasks/main.yml index bdd31754a1..ed97d539c0 100644 --- a/roles/dev-nodejs/tasks/main.yml +++ b/roles/dev-nodejs/tasks/main.yml @@ -1,4 +1 @@ --- -- name: ✅ Ensure Node.js is installed - package_install: - id: nodejs diff --git a/roles/dev-npm/meta/packages.yml b/roles/dev-npm/meta/packages.yml new file mode 100644 index 0000000000..4b2b21bc8c --- /dev/null +++ b/roles/dev-npm/meta/packages.yml @@ -0,0 +1,3 @@ +--- +npm: + shared: true diff --git a/roles/dev-npm/tasks/main.yml b/roles/dev-npm/tasks/main.yml index f1e13976ba..1d05f75cca 100644 --- a/roles/dev-npm/tasks/main.yml +++ b/roles/dev-npm/tasks/main.yml @@ -1,8 +1,4 @@ --- -- name: ✅ Ensure npm is installed - package_install: - id: npm - - name: ▶️ Run 'npm ci' command: npm ci args: diff --git a/roles/drv-epson-multiprinter/tasks/00_core.yml b/roles/drv-epson-multiprinter/tasks/00_core.yml index 5f304ab01c..70042adc45 100644 --- a/roles/drv-epson-multiprinter/tasks/00_core.yml +++ b/roles/drv-epson-multiprinter/tasks/00_core.yml @@ -1,6 +1,2 @@ --- -- name: 📦 install epson printer and scanner drivers - package_install: - id: epson-multiprinter - - include_tasks: utils/once/flag.yml diff --git a/roles/drv-intel/tasks/main.yml b/roles/drv-intel/tasks/main.yml index ef0be3870e..ed97d539c0 100644 --- a/roles/drv-intel/tasks/main.yml +++ b/roles/drv-intel/tasks/main.yml @@ -1,4 +1 @@ --- -- name: 📦 Install Intel media driver package(s) - package_install: - id: intel-media-driver diff --git a/roles/drv-non-free/tasks/main.yml b/roles/drv-non-free/tasks/main.yml index 1b5e6b3313..f34f13471f 100644 --- a/roles/drv-non-free/tasks/main.yml +++ b/roles/drv-non-free/tasks/main.yml @@ -3,11 +3,6 @@ ansible.builtin.setup: when: ansible_facts is not defined -- name: ✅ Ensure mhwd is installed on Manjaro - package_install: - id: mhwd - become: true - - name: 🔍 Detect mhwd command ansible.builtin.stat: path: /usr/bin/mhwd diff --git a/roles/dsk-blender/meta/packages.yml b/roles/dsk-blender/meta/packages.yml index a0b72d0759..5696e19381 100644 --- a/roles/dsk-blender/meta/packages.yml +++ b/roles/dsk-blender/meta/packages.yml @@ -1,4 +1,7 @@ --- +blender: + shared: true + pipx: Archlinux: - python-pipx @@ -6,6 +9,7 @@ pipx: - pipx RedHat: - pipx + batch: false centos: names: - pipx diff --git a/roles/dsk-blender/tasks/00_core.yml b/roles/dsk-blender/tasks/00_core.yml index eac534fabc..9f038f066f 100644 --- a/roles/dsk-blender/tasks/00_core.yml +++ b/roles/dsk-blender/tasks/00_core.yml @@ -1,10 +1,6 @@ --- - include_tasks: utils/once/flag.yml -- name: 📦 install blender - package_install: - id: blender - - name: 🧩 Bind Blender to the agents on this workstation ansible.builtin.include_tasks: file: addons/mcp-for-blender.yml diff --git a/roles/dsk-blender/tasks/addons/mcp-for-blender.yml b/roles/dsk-blender/tasks/addons/mcp-for-blender.yml index 91e0ec05fa..6b5b4118c5 100644 --- a/roles/dsk-blender/tasks/addons/mcp-for-blender.yml +++ b/roles/dsk-blender/tasks/addons/mcp-for-blender.yml @@ -1,6 +1,6 @@ --- - name: ✅ Ensure pipx is installed - package_install: + package_install: # nocheck: package-install only when the MCP for Blender addon is enabled, which gates the include of this file id: pipx become: true become_user: root diff --git a/roles/dsk-bluray-player/tasks/main.yml b/roles/dsk-bluray-player/tasks/main.yml index 6ecbb33cec..ed97d539c0 100644 --- a/roles/dsk-bluray-player/tasks/main.yml +++ b/roles/dsk-bluray-player/tasks/main.yml @@ -1,4 +1 @@ --- -- name: 📦 install vlc and blu ray software - package_install: - id: vlc-bluray diff --git a/roles/dsk-chromium/tasks/main.yml b/roles/dsk-chromium/tasks/main.yml index b012d714b7..a8a016fc2e 100644 --- a/roles/dsk-chromium/tasks/main.yml +++ b/roles/dsk-chromium/tasks/main.yml @@ -1,8 +1,4 @@ --- -- name: 📦 Install Chromium browser - package_install: - id: chromium - - name: 📂 Include dependency 'dsk-keepassxc' include_role: name: dsk-keepassxc diff --git a/roles/dsk-code/meta/packages.yml b/roles/dsk-code/meta/packages.yml index 73ad796b44..2e08094ee2 100644 --- a/roles/dsk-code/meta/packages.yml +++ b/roles/dsk-code/meta/packages.yml @@ -4,6 +4,7 @@ code-oss: - code Debian: [] # nocheck: empty - Code - OSS has no upstream build of its own here, and VSCodium is that build, installed through the vscodium id RedHat: [] # nocheck: empty - Code - OSS has no upstream build of its own here, and VSCodium is that build, installed through the vscodium id + batch: false vscode: Archlinux: @@ -22,6 +23,7 @@ vscode: - com.visualstudio.code flatpak: command: code + batch: false vscodium: Archlinux: @@ -40,3 +42,4 @@ vscodium: - com.vscodium.codium flatpak: command: codium + batch: false diff --git a/roles/dsk-code/tasks/00_core.yml b/roles/dsk-code/tasks/00_core.yml index b7096408ac..18fa730694 100644 --- a/roles/dsk-code/tasks/00_core.yml +++ b/roles/dsk-code/tasks/00_core.yml @@ -9,13 +9,13 @@ quiet: true - name: "🧹 Remove the flavors that conflict with {{ code_flavor }}" - package_install: + package_install: # nocheck: package-install removes the flavors other than the configured one, the batch only installs id: "{{ item }}" state: absent loop: "{{ code_conflicting_flavors }}" - name: "📦 install {{ code_flavor }}" - package_install: + package_install: # nocheck: package-install installs only the configured flavor, the role removes the others id: "{{ code_flavor }}" register: code_install diff --git a/roles/dsk-copyq/tasks/main.yml b/roles/dsk-copyq/tasks/main.yml index 3423d40ffe..cdb589cb65 100644 --- a/roles/dsk-copyq/tasks/main.yml +++ b/roles/dsk-copyq/tasks/main.yml @@ -1,8 +1,4 @@ --- -- name: 📦 Install CopyQ clipboard manager - package_install: - id: copyq - - name: ✅ Ensure autostart directory exists file: path: "{{ ansible_facts['env']['HOME'] }}/.config/autostart" diff --git a/roles/dsk-firefox/tasks/main.yml b/roles/dsk-firefox/tasks/main.yml index 7d80f2529d..fb7d61fc7e 100644 --- a/roles/dsk-firefox/tasks/main.yml +++ b/roles/dsk-firefox/tasks/main.yml @@ -1,8 +1,4 @@ --- -- name: 📦 Install Firefox - package_install: - id: firefox - - name: ✅ Ensure Firefox distribution policies directory exists file: path: "{{ firefox_policy_dir }}" diff --git a/roles/dsk-git/meta/packages.yml b/roles/dsk-git/meta/packages.yml new file mode 100644 index 0000000000..2844b63173 --- /dev/null +++ b/roles/dsk-git/meta/packages.yml @@ -0,0 +1,3 @@ +--- +git: + shared: true diff --git a/roles/dsk-git/tasks/main.yml b/roles/dsk-git/tasks/main.yml index 1cc468972f..fe4b36c00e 100644 --- a/roles/dsk-git/tasks/main.yml +++ b/roles/dsk-git/tasks/main.yml @@ -1,8 +1,4 @@ --- -- name: "📦 Install git" - package_install: - id: git - - name: 📦 Install gitcon CLI system-wide via pip include_role: name: sys-pip-install diff --git a/roles/dsk-gnome-caffeine/tasks/00_core.yml b/roles/dsk-gnome-caffeine/tasks/00_core.yml index c53e3f519f..71b0601a88 100644 --- a/roles/dsk-gnome-caffeine/tasks/00_core.yml +++ b/roles/dsk-gnome-caffeine/tasks/00_core.yml @@ -1,8 +1,4 @@ --- -- name: 📦 Install caffeine - package_install: - id: caffeine - - name: 🔍 Probe for the caffeine binary ansible.builtin.stat: path: "{{ caffeine_binary }}" diff --git a/roles/dsk-gnome-terminal/tasks/00_core.yml b/roles/dsk-gnome-terminal/tasks/00_core.yml index 9cd48ebb07..398994cfa3 100644 --- a/roles/dsk-gnome-terminal/tasks/00_core.yml +++ b/roles/dsk-gnome-terminal/tasks/00_core.yml @@ -1,8 +1,4 @@ --- -- name: 📦 Install Gnome Terminal - package_install: - id: gnome-terminal - - name: "🔧 Set zsh as default shell for {{ lookup('users', WORKSTATION_USER).username }}" user: name: "{{ lookup('users', WORKSTATION_USER).username }}" diff --git a/roles/dsk-gnome/tasks/00_core.yml b/roles/dsk-gnome/tasks/00_core.yml index 9f87984cfb..a7faba5cf3 100644 --- a/roles/dsk-gnome/tasks/00_core.yml +++ b/roles/dsk-gnome/tasks/00_core.yml @@ -1,9 +1,4 @@ --- -- name: 📦 Install GNOME GSettings schemas + GNOME Shell (cross-distro) - become: true - package_install: - id: gnome-shell - - name: 📂 Include dependencies include_role: name: "{{ desk_gnome_dependency }}" diff --git a/roles/dsk-gnt-claude/meta/packages.yml b/roles/dsk-gnt-claude/meta/packages.yml new file mode 100644 index 0000000000..4b2b21bc8c --- /dev/null +++ b/roles/dsk-gnt-claude/meta/packages.yml @@ -0,0 +1,3 @@ +--- +npm: + shared: true diff --git a/roles/dsk-gnt-claude/tasks/00_core.yml b/roles/dsk-gnt-claude/tasks/00_core.yml index 72f6be7f3c..6b68f79ef6 100644 --- a/roles/dsk-gnt-claude/tasks/00_core.yml +++ b/roles/dsk-gnt-claude/tasks/00_core.yml @@ -1,10 +1,6 @@ --- - include_tasks: utils/once/flag.yml -- name: ✅ Ensure npm is installed - package_install: - id: npm - - name: 📦 install the claude coding agent ansible.builtin.command: cmd: npm install -g {{ agnt_claude_package }} diff --git a/roles/dsk-gnt-codex/meta/packages.yml b/roles/dsk-gnt-codex/meta/packages.yml new file mode 100644 index 0000000000..4b2b21bc8c --- /dev/null +++ b/roles/dsk-gnt-codex/meta/packages.yml @@ -0,0 +1,3 @@ +--- +npm: + shared: true diff --git a/roles/dsk-gnt-codex/tasks/00_core.yml b/roles/dsk-gnt-codex/tasks/00_core.yml index 4fe24cbfc6..ab403047d7 100644 --- a/roles/dsk-gnt-codex/tasks/00_core.yml +++ b/roles/dsk-gnt-codex/tasks/00_core.yml @@ -1,10 +1,6 @@ --- - include_tasks: utils/once/flag.yml -- name: ✅ Ensure npm is installed - package_install: - id: npm - - name: 📦 install the codex coding agent ansible.builtin.command: cmd: npm install -g {{ agnt_codex_package }} diff --git a/roles/dsk-gnt-cursor/tasks/main.yml b/roles/dsk-gnt-cursor/tasks/main.yml index 4c87f36676..99408a67d7 100644 --- a/roles/dsk-gnt-cursor/tasks/main.yml +++ b/roles/dsk-gnt-cursor/tasks/main.yml @@ -1,8 +1,4 @@ --- - block: - - name: 📦 install cursor - package_install: - id: cursor - - include_tasks: utils/once/flag.yml when: run_once_dsk_gnt_cursor is not defined diff --git a/roles/dsk-gnt-pi/meta/packages.yml b/roles/dsk-gnt-pi/meta/packages.yml new file mode 100644 index 0000000000..4b2b21bc8c --- /dev/null +++ b/roles/dsk-gnt-pi/meta/packages.yml @@ -0,0 +1,3 @@ +--- +npm: + shared: true diff --git a/roles/dsk-gnt-pi/tasks/00_core.yml b/roles/dsk-gnt-pi/tasks/00_core.yml index aa2b86732e..e252eb2158 100644 --- a/roles/dsk-gnt-pi/tasks/00_core.yml +++ b/roles/dsk-gnt-pi/tasks/00_core.yml @@ -1,8 +1,4 @@ --- -- name: ✅ Ensure npm is installed - package_install: - id: npm - - name: 📦 install the pi coding agent ansible.builtin.command: cmd: npm install -g --ignore-scripts {{ agnt_pi_package }} diff --git a/roles/dsk-gnucash/tasks/main.yml b/roles/dsk-gnucash/tasks/main.yml index 2823e94977..ed97d539c0 100644 --- a/roles/dsk-gnucash/tasks/main.yml +++ b/roles/dsk-gnucash/tasks/main.yml @@ -1,4 +1 @@ --- -- name: 📦 Install GnuCash - package_install: - id: gnucash diff --git a/roles/dsk-jrnl/meta/packages.yml b/roles/dsk-jrnl/meta/packages.yml index bebfb3282a..cc34420503 100644 --- a/roles/dsk-jrnl/meta/packages.yml +++ b/roles/dsk-jrnl/meta/packages.yml @@ -5,4 +5,5 @@ jrnl: Debian: [] # nocheck: empty - jrnl is packaged in no Debian or Ubuntu suite, so the role installs it from PyPI through sys-pip-install RedHat: - jrnl + batch: false centos: [] # nocheck: empty - jrnl ships only in the Fedora repositories and EPEL 10 does not carry it, so the role installs it from PyPI through sys-pip-install diff --git a/roles/dsk-jrnl/tasks/main.yml b/roles/dsk-jrnl/tasks/main.yml index da5bce401e..69c048251e 100644 --- a/roles/dsk-jrnl/tasks/main.yml +++ b/roles/dsk-jrnl/tasks/main.yml @@ -1,6 +1,6 @@ --- - name: 📦 install jrnl - package_install: + package_install: # nocheck: package-install its skipped result picks the PyPI fallback below id: jrnl register: jrnl_package diff --git a/roles/dsk-keepassxc/tasks/main.yml b/roles/dsk-keepassxc/tasks/main.yml index 7bda10646d..95e3431e7d 100644 --- a/roles/dsk-keepassxc/tasks/main.yml +++ b/roles/dsk-keepassxc/tasks/main.yml @@ -1,8 +1,4 @@ --- - block: - - name: "📦 Install keepassxc" - package_install: - id: keepassxc - - include_tasks: utils/once/flag.yml when: run_once_dsk_keepassxc is not defined diff --git a/roles/dsk-libreoffice/tasks/main.yml b/roles/dsk-libreoffice/tasks/main.yml index 9e2fd86237..dd7704375a 100644 --- a/roles/dsk-libreoffice/tasks/main.yml +++ b/roles/dsk-libreoffice/tasks/main.yml @@ -1,8 +1,4 @@ --- -- name: 📦 install libreoffice - package_install: - id: libreoffice - - name: 📦 install libreoffice language packages package: # nocheck: dynamic-package (the language pack name is built from the configured flavor and the loop variable) name: "libreoffice-{{ lookup('applications', 'dsk-libreoffice').flavor }}-{{ item }}" diff --git a/roles/dsk-micro/tasks/main.yml b/roles/dsk-micro/tasks/main.yml index 5dbeb2ccf2..ed97d539c0 100644 --- a/roles/dsk-micro/tasks/main.yml +++ b/roles/dsk-micro/tasks/main.yml @@ -1,4 +1 @@ --- -- name: 📦 install micro - package_install: - id: micro diff --git a/roles/dsk-neovim/tasks/main.yml b/roles/dsk-neovim/tasks/main.yml index 19e6d6c1a3..ed97d539c0 100644 --- a/roles/dsk-neovim/tasks/main.yml +++ b/roles/dsk-neovim/tasks/main.yml @@ -1,4 +1 @@ --- -- name: 📦 install neovim - package_install: - id: neovim diff --git a/roles/dsk-nextcloud/tasks/main.yml b/roles/dsk-nextcloud/tasks/main.yml index 2e0bb69682..e1be8e8240 100644 --- a/roles/dsk-nextcloud/tasks/main.yml +++ b/roles/dsk-nextcloud/tasks/main.yml @@ -1,8 +1,4 @@ --- -- name: 📦 Install nextcloud-client - package_install: - id: nextcloud-desktop - - name: 🎬 Initialize dotlinker mapping list ansible.builtin.set_fact: nextcloud_dotlinker_mappings: [] diff --git a/roles/dsk-obs/tasks/main.yml b/roles/dsk-obs/tasks/main.yml index 53f464a646..ed97d539c0 100644 --- a/roles/dsk-obs/tasks/main.yml +++ b/roles/dsk-obs/tasks/main.yml @@ -1,4 +1 @@ --- -- name: 📦 install streaming - package_install: - id: obs-studio diff --git a/roles/dsk-qbittorrent/README.md b/roles/dsk-qbittorrent/README.md index f7b7911be2..4fa0577ab8 100644 --- a/roles/dsk-qbittorrent/README.md +++ b/roles/dsk-qbittorrent/README.md @@ -17,7 +17,7 @@ This README is for the `dsk-qbittorrent` role within the `infinito` repository. The `main.yml` file in the `dsk-qbittorrent` role includes the following task: 1. **Install Torrent Software**: - - This task calls `package_install` with the `qbittorrent` id; the per-distribution names are declared in [`meta/packages.yml`](meta/packages.yml). + - The package batch the constructor runs at deploy start installs the `qbittorrent` id; the per-distribution names are declared in [`meta/packages.yml`](meta/packages.yml). ## Purpose and Usage diff --git a/roles/dsk-qbittorrent/tasks/main.yml b/roles/dsk-qbittorrent/tasks/main.yml index 98656b4643..8626ced237 100644 --- a/roles/dsk-qbittorrent/tasks/main.yml +++ b/roles/dsk-qbittorrent/tasks/main.yml @@ -1,8 +1,4 @@ --- - block: - - name: 📦 install torrent software - package_install: - id: qbittorrent - - include_tasks: utils/once/flag.yml when: run_once_dsk_qbittorrent is not defined diff --git a/roles/dsk-retroarch/tasks/main.yml b/roles/dsk-retroarch/tasks/main.yml index 161f60f2c8..ed97d539c0 100644 --- a/roles/dsk-retroarch/tasks/main.yml +++ b/roles/dsk-retroarch/tasks/main.yml @@ -1,4 +1 @@ --- -- name: 📦 Install RetroArch and assets - package_install: - id: retroarch diff --git a/roles/dsk-spotify/README.md b/roles/dsk-spotify/README.md index 30a5593bcc..2261343ac9 100644 --- a/roles/dsk-spotify/README.md +++ b/roles/dsk-spotify/README.md @@ -6,7 +6,7 @@ This Ansible role installs the [Spotify](https://www.spotify.com/) desktop clien ## Overview -Spotify is a digital music streaming service that gives you access to millions of songs and podcasts. The role calls `package_install` with the `spotify` id; [`meta/packages.yml`](meta/packages.yml) declares it as an AUR package on Arch Linux and as a deliberate no-op on the Debian and RedHat families, which do not archive the proprietary client. +Spotify is a digital music streaming service that gives you access to millions of songs and podcasts. The package batch the constructor runs at deploy start installs the `spotify` id; [`meta/packages.yml`](meta/packages.yml) declares it as an AUR package on Arch Linux and as a deliberate no-op on the Debian and RedHat families, which do not archive the proprietary client. ## Purpose diff --git a/roles/dsk-spotify/tasks/main.yml b/roles/dsk-spotify/tasks/main.yml index 6fa170f1e1..03cbe92b98 100644 --- a/roles/dsk-spotify/tasks/main.yml +++ b/roles/dsk-spotify/tasks/main.yml @@ -1,8 +1,4 @@ --- - block: - - name: 📦 install spotify - package_install: - id: spotify - - include_tasks: utils/once/flag.yml when: run_once_dsk_spotify is not defined diff --git a/roles/dsk-torbrowser/tasks/main.yml b/roles/dsk-torbrowser/tasks/main.yml index 413f664817..ed97d539c0 100644 --- a/roles/dsk-torbrowser/tasks/main.yml +++ b/roles/dsk-torbrowser/tasks/main.yml @@ -1,4 +1 @@ --- -- name: 📦 Install torbrowser - package_install: - id: torbrowser diff --git a/roles/dsk-zoom/README.md b/roles/dsk-zoom/README.md index bf157bc2a1..face26ff95 100644 --- a/roles/dsk-zoom/README.md +++ b/roles/dsk-zoom/README.md @@ -6,7 +6,7 @@ ## Overview -This role installs Zoom through `package_install` with the `zoom` id. [`meta/packages.yml`](meta/packages.yml) declares it as an AUR package on Arch Linux and as a deliberate no-op on the Debian and RedHat families, which do not archive the proprietary client. +The package batch the constructor runs at deploy start installs Zoom through the `zoom` id. [`meta/packages.yml`](meta/packages.yml) declares it as an AUR package on Arch Linux and as a deliberate no-op on the Debian and RedHat families, which do not archive the proprietary client. ## Features diff --git a/roles/dsk-zoom/tasks/main.yml b/roles/dsk-zoom/tasks/main.yml index 7370f9fe29..a6446de530 100644 --- a/roles/dsk-zoom/tasks/main.yml +++ b/roles/dsk-zoom/tasks/main.yml @@ -1,8 +1,4 @@ --- - block: - - name: 📦 install video conference software - package_install: - id: zoom - - include_tasks: utils/once/flag.yml when: run_once_dsk_zoom is not defined diff --git a/roles/gen-hunspell/tasks/main.yml b/roles/gen-hunspell/tasks/main.yml index 1024aff1ad..daf9331192 100644 --- a/roles/gen-hunspell/tasks/main.yml +++ b/roles/gen-hunspell/tasks/main.yml @@ -1,8 +1,4 @@ --- -- name: 📦 install hunspell - package_install: - id: hunspell - - name: 📦 install hunspell language packages package: # nocheck: dynamic-package name: "hunspell-{{ item }}" diff --git a/roles/svc-bkp-volume-2-local/meta/packages.yml b/roles/svc-bkp-volume-2-local/meta/packages.yml index 420cd30850..3cc18c9b93 100644 --- a/roles/svc-bkp-volume-2-local/meta/packages.yml +++ b/roles/svc-bkp-volume-2-local/meta/packages.yml @@ -6,6 +6,7 @@ btrfs-tools: - btrfs-progs RedHat: - btrfs-progs + batch: false centos: names: - btrfs-progs diff --git a/roles/svc-bkp-volume-2-local/tasks/00_core.yml b/roles/svc-bkp-volume-2-local/tasks/00_core.yml index 2230c11636..c1f8817949 100644 --- a/roles/svc-bkp-volume-2-local/tasks/00_core.yml +++ b/roles/svc-bkp-volume-2-local/tasks/00_core.yml @@ -27,14 +27,13 @@ owner: root group: root mode: "0600" + modification_time: preserve + access_time: preserve - name: ✅ Ensure compositions dir exists (baudolo scans it; absent on fresh host) ansible.builtin.file: path: "{{ DIR_COMPOSITIONS }}" state: directory - owner: root - group: root - mode: "0755" - name: ✅ Assert the configured snapshot_mode names a snapshot mode ansible.builtin.assert: @@ -49,7 +48,7 @@ - name: 📦 Install the btrfs tools the snapshot launcher shells out to become: true - package_install: + package_install: # nocheck: package-install only on hosts with a btrfs mount id: btrfs-tools when: ansible_facts.mounts | selectattr('fstype', 'equalto', 'btrfs') | list | length > 0 diff --git a/roles/svc-bkp-volume-2-local/tasks/01_install.yml b/roles/svc-bkp-volume-2-local/tasks/01_install.yml index 1be7cbf0b4..910489bbd9 100644 --- a/roles/svc-bkp-volume-2-local/tasks/01_install.yml +++ b/roles/svc-bkp-volume-2-local/tasks/01_install.yml @@ -18,7 +18,7 @@ when: MODE_ASSERT | bool - name: ✅ Ensure secrets directory exists (root only) - ansible.builtin.file: + ansible.builtin.file: # nocheck: path-single-owner sys-token-store sets the same root 0700 on STACK_HOST only, every other host needs it here path: "{{ DIR_SECRETS }}" state: directory owner: root diff --git a/roles/svc-db-elasticsearch/templates/compose.yml.j2 b/roles/svc-db-elasticsearch/templates/compose.yml.j2 index bb788436e4..20762820a1 100644 --- a/roles/svc-db-elasticsearch/templates/compose.yml.j2 +++ b/roles/svc-db-elasticsearch/templates/compose.yml.j2 @@ -17,7 +17,7 @@ healthcheck: test: - "CMD-SHELL" - - "curl -fsS -u elastic:{{ ELASTICSEARCH_PASSWORD }} http://127.0.0.1:{{ ELASTICSEARCH_INTERNAL_PORT }}/_cluster/health || exit 1" + - 'printf ''user = "elastic:%s"\n'' "$$ELASTIC_PASSWORD" | curl -fsS -K - http://127.0.0.1:{{ ELASTICSEARCH_INTERNAL_PORT }}/_cluster/health || exit 1' interval: 2m timeout: 5s retries: 18 diff --git a/roles/svc-db-mariadb/tasks/00_core.yml b/roles/svc-db-mariadb/tasks/00_core.yml index 76c883e173..4c582b2f84 100644 --- a/roles/svc-db-mariadb/tasks/00_core.yml +++ b/roles/svc-db-mariadb/tasks/00_core.yml @@ -69,8 +69,8 @@ delay: 5 until: mariadb_cli.rc == 0 -- name: "⏳ Wait until MariaDB accepts root credentials (via mysql_db)" - ansible.mysql.mysql_db: +- name: "⏳ Wait until MariaDB accepts root credentials (via mariadb_db)" + ansible.mariadb.mariadb_db: name: "{{ MARIADB_HEALTHCHECK_DB }}" state: present login_user: root diff --git a/roles/svc-db-mariadb/tasks/01_init.yml b/roles/svc-db-mariadb/tasks/01_init.yml index bdb97c6b71..c28cf4ffcb 100644 --- a/roles/svc-db-mariadb/tasks/01_init.yml +++ b/roles/svc-db-mariadb/tasks/01_init.yml @@ -1,7 +1,7 @@ --- - block: - - name: "📁 Create database: {{ database_name }} (host via mysql_db)" - ansible.mysql.mysql_db: + - name: "📁 Create database: {{ database_name }} (host via mariadb_db)" + ansible.mariadb.mariadb_db: name: "{{ database_name }}" state: present login_user: root @@ -12,8 +12,8 @@ collation: "{{ MARIADB_COLLATION }}" config_file: "" - - name: "📁 Create database user: {{ database_username }} (host via mysql_user)" - ansible.mysql.mysql_user: + - name: "📁 Create database user: {{ database_username }} (host via mariadb_user)" + ansible.mariadb.mariadb_user: name: "{{ database_username }}" password: "{{ database_password }}" host: "%" diff --git a/roles/svc-db-openldap/tasks/_python_ldap_prerequisites.yml b/roles/svc-db-openldap/tasks/_python_ldap_prerequisites.yml index a0be0a467a..150185b83c 100644 --- a/roles/svc-db-openldap/tasks/_python_ldap_prerequisites.yml +++ b/roles/svc-db-openldap/tasks/_python_ldap_prerequisites.yml @@ -1,8 +1,4 @@ --- -- name: 📦 Install python-ldap native library build dependencies - package_install: - id: openldap-dev - - name: 🔍 Resolve Python include directory for active interpreter ansible.builtin.command: argv: diff --git a/roles/svc-db-openldap/tasks/schemas/moodle.yml b/roles/svc-db-openldap/tasks/schemas/moodle.yml index bfe5cf53b6..b91fb9816d 100644 --- a/roles/svc-db-openldap/tasks/schemas/moodle.yml +++ b/roles/svc-db-openldap/tasks/schemas/moodle.yml @@ -16,18 +16,19 @@ objectclass_defs: - "( 1.3.6.1.4.1.99999.13 NAME 'infinitoMoodleUser' DESC 'Auxiliary class for Moodle-only user attributes' AUXILIARY MAY ( infinitoNamePhoneticGiven $ infinitoNamePhoneticFamily $ infinitoTimezone ) )" - command: > - ldapsm - -s {{ OPENLDAP_SERVER_URI }} - -D '{{ OPENLDAP_BIND_DN }}' - -W '{{ OPENLDAP_BIND_PW }}' - -n {{ schema_name }} - {% for at in attribute_defs %} - -a "{{ at }}" - {% endfor %} - {% for oc in objectclass_defs %} - -c "{{ oc }}" - {% endfor %} + command: + cmd: > + {{ OPENLDAP_LDAPSM_COMMAND }} + -s {{ OPENLDAP_SERVER_URI }} + -D '{{ OPENLDAP_BIND_DN }}' + -n {{ schema_name }} + {% for at in attribute_defs %} + -a "{{ at }}" + {% endfor %} + {% for oc in objectclass_defs %} + -c "{{ oc }}" + {% endfor %} + stdin: "{{ OPENLDAP_BIND_PW }}" register: ldapsm_moodle_result changed_when: "'Created schema entry' in ldapsm_moodle_result.stdout" check_mode: false diff --git a/roles/svc-db-openldap/tasks/schemas/nextcloud.yml b/roles/svc-db-openldap/tasks/schemas/nextcloud.yml index afd814f361..12c89f86de 100644 --- a/roles/svc-db-openldap/tasks/schemas/nextcloud.yml +++ b/roles/svc-db-openldap/tasks/schemas/nextcloud.yml @@ -8,18 +8,19 @@ objectclass_defs: - "( 1.3.6.1.4.1.99999.2 NAME '{{ LDAP.USER.OBJECTS.AUXILIARY.NEXTCLOUD_USER }}' DESC 'Auxiliary class for Nextcloud attributes' AUXILIARY MAY ( {{ LDAP.USER.ATTRIBUTES.NEXTCLOUD_QUOTA }} ) )" - command: > - ldapsm - -s {{ OPENLDAP_SERVER_URI }} - -D '{{ OPENLDAP_BIND_DN }}' - -W '{{ OPENLDAP_BIND_PW }}' - -n {{ schema_name }} - {% for at in attribute_defs %} - -a "{{ at }}" - {% endfor %} - {% for oc in objectclass_defs %} - -c "{{ oc }}" - {% endfor %} + command: + cmd: > + {{ OPENLDAP_LDAPSM_COMMAND }} + -s {{ OPENLDAP_SERVER_URI }} + -D '{{ OPENLDAP_BIND_DN }}' + -n {{ schema_name }} + {% for at in attribute_defs %} + -a "{{ at }}" + {% endfor %} + {% for oc in objectclass_defs %} + -c "{{ oc }}" + {% endfor %} + stdin: "{{ OPENLDAP_BIND_PW }}" register: ldapsm_result changed_when: "'Created schema entry' in ldapsm_result.stdout" check_mode: false diff --git a/roles/svc-db-openldap/tasks/schemas/openssh_lpk.yml b/roles/svc-db-openldap/tasks/schemas/openssh_lpk.yml index 4ad8992d49..046e7e2be2 100644 --- a/roles/svc-db-openldap/tasks/schemas/openssh_lpk.yml +++ b/roles/svc-db-openldap/tasks/schemas/openssh_lpk.yml @@ -14,18 +14,19 @@ SUP top AUXILIARY MAY ( {{ LDAP.USER.ATTRIBUTES.SSH_PUBLIC_KEY }} $ sshFingerprint ) ) - command: > - ldapsm - -s {{ OPENLDAP_SERVER_URI }} - -D '{{ OPENLDAP_BIND_DN }}' - -W '{{ OPENLDAP_BIND_PW }}' - -n {{ schema_name }} - {% for at in attribute_defs %} - -a "{{ at }}" - {% endfor %} - {% for oc in objectclass_defs %} - -c "{{ oc }}" - {% endfor %} + command: + cmd: > + {{ OPENLDAP_LDAPSM_COMMAND }} + -s {{ OPENLDAP_SERVER_URI }} + -D '{{ OPENLDAP_BIND_DN }}' + -n {{ schema_name }} + {% for at in attribute_defs %} + -a "{{ at }}" + {% endfor %} + {% for oc in objectclass_defs %} + -c "{{ oc }}" + {% endfor %} + stdin: "{{ OPENLDAP_BIND_PW }}" register: opensshlpk_ldapsm changed_when: "'Created schema entry' in opensshlpk_ldapsm.stdout" check_mode: false diff --git a/roles/svc-db-openldap/vars/main.yml b/roles/svc-db-openldap/vars/main.yml index e897583808..5cddb47f13 100644 --- a/roles/svc-db-openldap/vars/main.yml +++ b/roles/svc-db-openldap/vars/main.yml @@ -20,6 +20,8 @@ OPENLDAP_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name OPENLDAP_SERVICE: "{{ entity_name }}" OPENLDAP_BIND_DN: "{{ LDAP.DN.ADMINISTRATOR.DATA }}" OPENLDAP_BIND_PW: "{{ LDAP.BIND_CREDENTIAL }}" +OPENLDAP_LDAPSM_COMMAND: |- + {{ ansible_python_interpreter }} -c 'import sys; from ldapsm.__main__ import main; sys.argv = ["ldapsm", *sys.argv[1:], "-W", sys.stdin.readline().rstrip("\n")]; sys.exit(main())' OPENLDAP_NETWORK_SWITCH_PUBLIC: "{{ lookup('config', application_id, 'services.openldap.network.public') }}" OPENLDAP_NETWORK_SWITCH_LOCAL: "{{ lookup('config', application_id, 'services.openldap.network.local') }}" 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 d3a3c49a82..56bee95f78 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,10 +2,8 @@ set -euo pipefail # Usage: -# set_postgres_superuser_password.sh -# POSTGRES_SUPERUSER_PASSWORD: the password to write, read from the -# environment only, so it reaches neither this script's argv nor that of the -# container exec calls it makes. +# set_postgres_superuser_password.sh < password +# stdin: the password to write. # # 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 @@ -15,15 +13,16 @@ set -euo pipefail container_raw="${1:-}" role="${2:-}" -new_pw="${POSTGRES_SUPERUSER_PASSWORD:-}" if [[ -z "$container_raw" || -z "$role" ]]; then - echo "Usage: $0 " >&2 + echo "Usage: $0 < password" >&2 exit 2 fi +new_pw="$(cat)" + if [[ -z "$new_pw" ]]; then - echo "[FAIL] POSTGRES_SUPERUSER_PASSWORD is empty; refusing to set an empty password." >&2 + echo "[FAIL] no password on stdin; refusing to set an empty password." >&2 exit 1 fi @@ -38,12 +37,17 @@ pg_exec() { "psql -U \"\$PG_ROLE\" -d postgres -Atc '$1'" 2>/dev/null } +# Returns 0 when TCP auth over 127.0.0.1 accepts the new password. +auth_once() { + # shellcheck disable=SC2016 + container exec -e PGPASSWORD -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' +} + # Retry TCP auth up to 15 times (30s) to handle HBA reload delay auth_test() { for _ in {1..15}; do - # shellcheck disable=SC2016 - if container exec -e PGPASSWORD -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 + if auth_once; then return 0 fi sleep 2 @@ -101,11 +105,12 @@ for _ in {1..30}; do fi pre_ok=0 - if auth_test; then pre_ok=1; fi + if auth_once; then pre_ok=1; fi # shellcheck disable=SC2016 if ! container exec -e NEW_POSTGRES_PASSWORD -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'"'"' + psql -U "$PG_ROLE" -d postgres -v ON_ERROR_STOP=1 -v role="$PG_ROLE" <<'"'"'SQL'"'"' +\set password `printenv NEW_POSTGRES_PASSWORD` ALTER USER :"role" WITH PASSWORD :'"'"'password'"'"'; SQL ' 2>/dev/null; then diff --git a/roles/svc-db-postgres/tasks/00_core.yml b/roles/svc-db-postgres/tasks/00_core.yml index 4b24499880..2d48f0ebc9 100644 --- a/roles/svc-db-postgres/tasks/00_core.yml +++ b/roles/svc-db-postgres/tasks/00_core.yml @@ -44,10 +44,16 @@ changed_when: false - 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 - environment: - POSTGRES_SUPERUSER_PASSWORD: "{{ POSTGRES_PASSWORD }}" + ansible.builtin.command: + argv: + - bash + - -c + - "{{ lookup('file', 'shell/set_postgres_superuser_password.sh') }}" + - set_postgres_superuser_password.sh + - "{{ POSTGRES_CONTAINER_ADDRESS }}" + - postgres + stdin: "{{ POSTGRES_PASSWORD }}" + expand_argument_vars: false register: postgres_pw_result delegate_to: "{{ STACK_HOST }}" run_once: true diff --git a/roles/svc-db-redis/templates/compose.yml.j2 b/roles/svc-db-redis/templates/compose.yml.j2 index dca7f58969..ae375c341e 100644 --- a/roles/svc-db-redis/templates/compose.yml.j2 +++ b/roles/svc-db-redis/templates/compose.yml.j2 @@ -8,7 +8,7 @@ - "-c" - >- exec redis-server - --requirepass {{ REDIS_PASSWORD | quote }} + --requirepass "$$REDIS_PASSWORD" --appendonly yes --maxmemory {{ lookup('service_memory_mb', application_id, service_name, 0.8) }}mb --maxmemory-policy allkeys-lru diff --git a/roles/svc-db-typesense/templates/compose.yml.j2 b/roles/svc-db-typesense/templates/compose.yml.j2 index 90b6350447..ac1efdb403 100644 --- a/roles/svc-db-typesense/templates/compose.yml.j2 +++ b/roles/svc-db-typesense/templates/compose.yml.j2 @@ -9,8 +9,6 @@ - "/data" - "--enable-cors" - "--reset-peers-on-error" - - "--api-key" - - "{{ TYPESENSE_API_KEY }}" {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {% if TYPESENSE_EXPOSE_LOCAL %} diff --git a/roles/svc-net-firewall/tasks/01_host.yml b/roles/svc-net-firewall/tasks/01_host.yml index 9474747829..b8a08ae231 100644 --- a/roles/svc-net-firewall/tasks/01_host.yml +++ b/roles/svc-net-firewall/tasks/01_host.yml @@ -1,9 +1,4 @@ --- -- name: "📦 Firewall | Install nftables" - become: true - package_install: - id: nftables - - name: "📁 Firewall | Ensure the fragment directory exists" become: true ansible.builtin.file: diff --git a/roles/svc-net-tor/meta/packages.yml b/roles/svc-net-tor/meta/packages.yml index b5bdbd8924..349a9a6e91 100644 --- a/roles/svc-net-tor/meta/packages.yml +++ b/roles/svc-net-tor/meta/packages.yml @@ -6,3 +6,4 @@ dnsmasq: - dnsmasq RedHat: - dnsmasq + batch: false diff --git a/roles/svc-net-tor/tasks/router.yml b/roles/svc-net-tor/tasks/router.yml index 08f4119e8e..cf665d8721 100644 --- a/roles/svc-net-tor/tasks/router.yml +++ b/roles/svc-net-tor/tasks/router.yml @@ -7,7 +7,7 @@ no-resolv and would answer .onion only. - name: "📦 Egress router | Install dnsmasq (host split-DNS forwarder)" become: true - package_install: + package_install: # nocheck: package-install only on the egress router this file is included for id: dnsmasq - name: "📁 Egress router | Ensure the dnsmasq drop-in directory exists" ansible.builtin.file: diff --git a/roles/svc-net-wireguard/meta/packages.yml b/roles/svc-net-wireguard/meta/packages.yml index ca3794afe1..996f701343 100644 --- a/roles/svc-net-wireguard/meta/packages.yml +++ b/roles/svc-net-wireguard/meta/packages.yml @@ -9,3 +9,4 @@ wireguard: RedHat: - procps-ng - wireguard-tools + batch: false diff --git a/roles/svc-net-wireguard/tasks/00_core.yml b/roles/svc-net-wireguard/tasks/00_core.yml index b0f89c0f8b..c99c74b524 100644 --- a/roles/svc-net-wireguard/tasks/00_core.yml +++ b/roles/svc-net-wireguard/tasks/00_core.yml @@ -18,7 +18,7 @@ when: WIREGUARD_MESH_NAMES | length == 0 - name: "📦 Install the WireGuard tooling" - package_install: + package_install: # nocheck: package-install the mesh bootstrap runs before the update role and the batch run id: - wireguard - iproute diff --git a/roles/svc-opt-keyboard-color/meta/packages.yml b/roles/svc-opt-keyboard-color/meta/packages.yml index 1236ef128e..927f272f53 100644 --- a/roles/svc-opt-keyboard-color/meta/packages.yml +++ b/roles/svc-opt-keyboard-color/meta/packages.yml @@ -6,3 +6,4 @@ msi-perkeyrgb: - msi-perkeyrgb Debian: [] # nocheck: empty - msi-perkeyrgb is published upstream on GitHub and PyPI only, so the role installs it from PyPI through sys-pip-install RedHat: [] # nocheck: empty - msi-perkeyrgb is carried by no RedHat-family repository, so the role installs it from PyPI through sys-pip-install + batch: false diff --git a/roles/svc-opt-keyboard-color/tasks/00_core.yml b/roles/svc-opt-keyboard-color/tasks/00_core.yml index f0eeb6ed4e..e5214e029b 100644 --- a/roles/svc-opt-keyboard-color/tasks/00_core.yml +++ b/roles/svc-opt-keyboard-color/tasks/00_core.yml @@ -3,7 +3,7 @@ name: sys-ctl-alm-compose - name: 📦 Install MSI packages - package_install: + package_install: # nocheck: package-install its skipped result picks the PyPI fallback below id: msi-perkeyrgb register: msi_perkeyrgb_package diff --git a/roles/svc-prx-openresty/meta/services.yml b/roles/svc-prx-openresty/meta/services.yml index a806151ccc..7b318b9bf2 100644 --- a/roles/svc-prx-openresty/meta/services.yml +++ b/roles/svc-prx-openresty/meta/services.yml @@ -31,7 +31,7 @@ openresty: mem_reservation: 1g mem_limit: 2g image: openresty/openresty - version: 1.31.1.1-alpine + version: 1.31.8.1-alpine custom: true lifecycle: beta pids_limit: 256 diff --git a/roles/svc-storage-nfs-client/tasks/main.yml b/roles/svc-storage-nfs-client/tasks/main.yml index 68241b326d..c99e7e9b17 100644 --- a/roles/svc-storage-nfs-client/tasks/main.yml +++ b/roles/svc-storage-nfs-client/tasks/main.yml @@ -10,7 +10,7 @@ server IP/hostname is mandatory. - name: "📦 Install the NFS client" - package_install: + package_install: # nocheck: package-install the controller installs it too, by delegation from the NFS server role id: nfs-client - name: "🔧 Match NFSv4 idmap to the ganesha test server" diff --git a/roles/svc-storage-nfs-server/meta/packages.yml b/roles/svc-storage-nfs-server/meta/packages.yml index 7c744471d1..510887e4ae 100644 --- a/roles/svc-storage-nfs-server/meta/packages.yml +++ b/roles/svc-storage-nfs-server/meta/packages.yml @@ -6,11 +6,13 @@ e2fsprogs: - e2fsprogs RedHat: - e2fsprogs + batch: false libntirpc: Archlinux: [] # nocheck: empty - the AUR build compiles its own ntirpc submodule Debian: [] # nocheck: empty - the packaged nfs-ganesha links against a matching libntirpc, only Fedora ships a broken pair RedHat: [] # nocheck: empty - only the Fedora override needs the upgrade, the CentOS SIG build is self-consistent + batch: false fedora: names: - libntirpc @@ -29,6 +31,7 @@ nfs-ganesha: RedHat: - nfs-ganesha - nfs-ganesha-vfs + batch: false centos: names: - nfs-ganesha @@ -41,9 +44,11 @@ nfs-kernel-server: Debian: - nfs-kernel-server RedHat: [] # nocheck: empty - the kernel server ships inside nfs-utils, installed through the nfs-client id + batch: false selinux-python-binding: Archlinux: [] # nocheck: empty - SELinux is not the mandatory access control on this family Debian: [] # nocheck: empty - SELinux is not the mandatory access control on this family RedHat: - python3-libselinux + batch: false diff --git a/roles/svc-storage-nfs-server/tasks/02_overlay_backing/ext4_loop.yml b/roles/svc-storage-nfs-server/tasks/02_overlay_backing/ext4_loop.yml index 8a7f474e3c..989d8705d0 100644 --- a/roles/svc-storage-nfs-server/tasks/02_overlay_backing/ext4_loop.yml +++ b/roles/svc-storage-nfs-server/tasks/02_overlay_backing/ext4_loop.yml @@ -1,6 +1,6 @@ --- - name: "📦 Ensure e2fsprogs is installed for mkfs.ext4" - package_install: + package_install: # nocheck: package-install only the ext4 loop overlay backing includes this file id: e2fsprogs - name: "✅ Refuse to mount over a non-empty export base" diff --git a/roles/svc-storage-nfs-server/tasks/03_controller_mount.yml b/roles/svc-storage-nfs-server/tasks/03_controller_mount.yml index 62e83c01e4..640a36689d 100644 --- a/roles/svc-storage-nfs-server/tasks/03_controller_mount.yml +++ b/roles/svc-storage-nfs-server/tasks/03_controller_mount.yml @@ -24,12 +24,9 @@ ansible.builtin.file: path: "{{ DIR_VAR_LIB }}" state: directory - owner: root - group: root - mode: "0755" - name: "📦 Install the NFS client" - package_install: + package_install: # nocheck: package-install runs on the controller by delegation, outside any host's batch id: nfs-client - name: "🔎 Read current mount source at controller {{ DIR_VAR_LIB }}" diff --git a/roles/svc-storage-nfs-server/tasks/flavor/ganesha/main.yml b/roles/svc-storage-nfs-server/tasks/flavor/ganesha/main.yml index 2bed32571d..683d316343 100644 --- a/roles/svc-storage-nfs-server/tasks/flavor/ganesha/main.yml +++ b/roles/svc-storage-nfs-server/tasks/flavor/ganesha/main.yml @@ -1,6 +1,6 @@ --- - name: "📦 Install the userspace nfs-ganesha server" - package_install: + package_install: # nocheck: package-install only the ganesha NFS flavor includes this file id: - nfs-ganesha - libntirpc diff --git a/roles/svc-storage-nfs-server/tasks/flavor/kernel/main.yml b/roles/svc-storage-nfs-server/tasks/flavor/kernel/main.yml index 4e58e90b49..e9efa80de0 100644 --- a/roles/svc-storage-nfs-server/tasks/flavor/kernel/main.yml +++ b/roles/svc-storage-nfs-server/tasks/flavor/kernel/main.yml @@ -1,12 +1,12 @@ --- - name: "📦 Install the kernel NFS server" - package_install: + package_install: # nocheck: package-install only the kernel NFS flavor includes this file id: - nfs-client - nfs-kernel-server - name: "📦 Install the SELinux python binding (seboolean module + selinux fact)" - package_install: + package_install: # nocheck: package-install only the kernel NFS flavor includes this file id: selinux-python-binding - name: "📊 Re-gather the SELinux fact now the binding is present" diff --git a/roles/svc-swarm-node/tasks/01_manager.yml b/roles/svc-swarm-node/tasks/01_manager.yml index 8b8c2fb70e..8df62372f6 100644 --- a/roles/svc-swarm-node/tasks/01_manager.yml +++ b/roles/svc-swarm-node/tasks/01_manager.yml @@ -26,7 +26,7 @@ changed_when: false - name: "⬇️ Fetch manager swarm-advertise address" - ansible.builtin.command: container info --format '{{ "{{" }}.Swarm.NodeAddr{{ "}}" }}:2377' + ansible.builtin.command: container info --format '{{ "{{" }}.Swarm.NodeAddr{{ "}}" }}:{{ SWARM_MANAGER_PORT }}' register: docker_swarm_manager_addr changed_when: false diff --git a/roles/svc-swarm-node/tasks/02_manager_join.yml b/roles/svc-swarm-node/tasks/02_manager_join.yml index 515f797297..2e89de9d5b 100644 --- a/roles/svc-swarm-node/tasks/02_manager_join.yml +++ b/roles/svc-swarm-node/tasks/02_manager_join.yml @@ -7,9 +7,17 @@ - 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 }} - {{ svc_swarm_manager_addr }} + uri_retry: + url: http://localhost/swarm/join + unix_socket: /var/run/docker.sock + method: POST + body_format: json + body: + ListenAddr: "{{ SWARM_LISTEN_ADDR }}" + RemoteAddrs: + - "{{ svc_swarm_manager_addr }}" + JoinToken: "{{ svc_swarm_manager_token }}" + status_code: 200 + timeout: "{{ lookup('timeout', 120) | int }}" when: docker_swarm_local_state.stdout != 'active' changed_when: true diff --git a/roles/svc-swarm-node/tasks/03_worker.yml b/roles/svc-swarm-node/tasks/03_worker.yml index 997df31374..356ab82f46 100644 --- a/roles/svc-swarm-node/tasks/03_worker.yml +++ b/roles/svc-swarm-node/tasks/03_worker.yml @@ -7,9 +7,17 @@ - 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 }} - {{ svc_swarm_manager_addr }} + uri_retry: + url: http://localhost/swarm/join + unix_socket: /var/run/docker.sock + method: POST + body_format: json + body: + ListenAddr: "{{ SWARM_LISTEN_ADDR }}" + RemoteAddrs: + - "{{ svc_swarm_manager_addr }}" + JoinToken: "{{ svc_swarm_worker_token }}" + status_code: 200 + timeout: "{{ lookup('timeout', 120) | int }}" when: docker_swarm_local_state.stdout != 'active' changed_when: true diff --git a/roles/sys-ca-selfsigned/files/shell/build-trust-bundle.sh b/roles/sys-ca-selfsigned/files/shell/build-trust-bundle.sh new file mode 100644 index 0000000000..b7a3b5562a --- /dev/null +++ b/roles/sys-ca-selfsigned/files/shell/build-trust-bundle.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env sh +# Usage: build-trust-bundle.sh ... +# bundle file to hold the concatenated sources; rewritten in place, keeping its inode for +# containers that bind-mount it, and only when its content differs +# source certificate files, concatenated in the given order +# Prints "bundle-rewritten" when the bundle was replaced. +set -eu + +bundle="$1" +shift + +staged="$(mktemp "${bundle}.XXXXXX")" +trap 'rm -f "$staged"' EXIT + +cat "$@" >"$staged" +if ! cmp -s "$staged" "$bundle"; then + cat "$staged" >"$bundle" + echo "bundle-rewritten" +fi diff --git a/roles/sys-ca-selfsigned/tasks/00_core.yml b/roles/sys-ca-selfsigned/tasks/00_core.yml index 8daaadaefd..5f8a2223b5 100644 --- a/roles/sys-ca-selfsigned/tasks/00_core.yml +++ b/roles/sys-ca-selfsigned/tasks/00_core.yml @@ -4,7 +4,7 @@ ansible.builtin.file: path: "{{ CA_ROOT.base_dir }}" state: directory - mode: "0750" + mode: "0755" owner: root group: root @@ -73,6 +73,10 @@ loop: "{{ CA_BUNDLE_CANDIDATES }}" register: _ca_public_bundle_candidates +- name: "📌 CA | keep the first public CA bundle the host ships" + ansible.builtin.set_fact: + _ca_public_bundle: "{{ (_ca_public_bundle_candidates.results | selectattr('stat.exists') | map(attribute='item') | list)[:1] }}" + - name: "🔎 CA | stat host CA-trust bind-mount sources" become: true ansible.builtin.stat: @@ -97,11 +101,12 @@ - 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 + ansible.builtin.script: + cmd: >- + {{ role_path }}/files/shell/build-trust-bundle.sh + {{ ([CA_TRUST.bundle_host, CA_ROOT.cert_host] + _ca_public_bundle) | map('quote') | join(' ') }} + register: _ca_trust_bundle_build + changed_when: "'bundle-rewritten' in _ca_trust_bundle_build.stdout" - name: "🔐 CA | enforce permissions (trust bundle)" become: true @@ -119,6 +124,7 @@ owner: root group: root mode: "0755" + register: _ca_trust_wrapper - name: "📦 CA | install PHP CA-trust ini (SPOT) on host" become: true @@ -129,6 +135,21 @@ group: root mode: "0644" +- name: "🔎 CA | check whether the host trust store already trusts the Root CA" + become: true + ansible.builtin.command: + argv: + - openssl + - verify + - -no-CApath + - -CAfile + - "{{ _ca_public_bundle | first }}" + - "{{ CA_ROOT.cert_host }}" + register: _ca_trusted_by_host + changed_when: false + failed_when: _ca_trusted_by_host.rc not in [0, 2] + when: _ca_public_bundle | length > 0 + - name: "📦 CA | Install Root CA into host trust store" become: true ansible.builtin.command: @@ -140,6 +161,10 @@ CA_TRUST_CERT: "{{ CA_ROOT.cert_host }}" CA_TRUST_NAME: "{{ DOMAIN_PRIMARY | lower }}" changed_when: true + when: >- + _ca_trust_wrapper is changed + or _ca_trusted_by_host is skipped + or _ca_trusted_by_host.rc != 0 - name: "✅ TLS | (self_signed) ensure CA trust env vars in {{ FILE_ENVIRONMENT }}" become: true diff --git a/roles/sys-ctl-alm-telegram/meta/packages.yml b/roles/sys-ctl-alm-telegram/meta/packages.yml index 04726d4501..f09f817ef7 100644 --- a/roles/sys-ctl-alm-telegram/meta/packages.yml +++ b/roles/sys-ctl-alm-telegram/meta/packages.yml @@ -6,3 +6,4 @@ curl: - curl RedHat: - curl + batch: false diff --git a/roles/sys-ctl-alm-telegram/tasks/00_core.yml b/roles/sys-ctl-alm-telegram/tasks/00_core.yml index 223ded00c6..bab16cd491 100644 --- a/roles/sys-ctl-alm-telegram/tasks/00_core.yml +++ b/roles/sys-ctl-alm-telegram/tasks/00_core.yml @@ -17,7 +17,7 @@ system_service_tpl_on_failure: "{{ lookup('unit_name','sys-ctl-alm-email@', suffix=False) }}%i.service" - name: 📦 install curl - package_install: + package_install: # nocheck: package-install only hosts with Telegram alerts run this role id: curl - include_tasks: utils/once/flag.yml diff --git a/roles/sys-ctl-cln-bkps/meta/packages.yml b/roles/sys-ctl-cln-bkps/meta/packages.yml index 1a477501b1..f269a69d0e 100644 --- a/roles/sys-ctl-cln-bkps/meta/packages.yml +++ b/roles/sys-ctl-cln-bkps/meta/packages.yml @@ -6,3 +6,4 @@ lsof: - lsof RedHat: - lsof + batch: false diff --git a/roles/sys-ctl-cln-bkps/tasks/00_core.yml b/roles/sys-ctl-cln-bkps/tasks/00_core.yml index e78287d157..a749081a19 100644 --- a/roles/sys-ctl-cln-bkps/tasks/00_core.yml +++ b/roles/sys-ctl-cln-bkps/tasks/00_core.yml @@ -9,7 +9,7 @@ loop_var: sys_ctl_cln_bkps_dependency - name: 📦 install lsof - package_install: + package_install: # nocheck: package-install only hosts that clean backups run this role id: lsof - name: 📦 install psutil via pip @@ -24,9 +24,6 @@ ansible.builtin.file: path: "{{ DIR_BACKUPS }}" state: directory - owner: root - group: root - mode: "0755" - include_role: name: sys-service diff --git a/roles/sys-ctl-cln-faild-bkps/tasks/00_core.yml b/roles/sys-ctl-cln-faild-bkps/tasks/00_core.yml index 8affbd23bc..fb467e107e 100644 --- a/roles/sys-ctl-cln-faild-bkps/tasks/00_core.yml +++ b/roles/sys-ctl-cln-faild-bkps/tasks/00_core.yml @@ -23,9 +23,6 @@ ansible.builtin.file: path: "{{ DIR_BACKUPS }}" state: directory - owner: root - group: root - mode: "0755" - include_role: name: sys-service diff --git a/roles/sys-ctl-mtn-cert-renew/meta/packages.yml b/roles/sys-ctl-mtn-cert-renew/meta/packages.yml index f1ab745a72..8831fb925b 100644 --- a/roles/sys-ctl-mtn-cert-renew/meta/packages.yml +++ b/roles/sys-ctl-mtn-cert-renew/meta/packages.yml @@ -6,6 +6,7 @@ certbot-nginx: - python3-certbot-nginx RedHat: - python3-certbot-nginx + batch: false centos: names: - python3-certbot-nginx diff --git a/roles/sys-ctl-mtn-cert-renew/tasks/00_core.yml b/roles/sys-ctl-mtn-cert-renew/tasks/00_core.yml index be196bcaa1..0effd422c4 100644 --- a/roles/sys-ctl-mtn-cert-renew/tasks/00_core.yml +++ b/roles/sys-ctl-mtn-cert-renew/tasks/00_core.yml @@ -10,7 +10,7 @@ loop_var: sys_ctl_mtn_cert_renew_dependency - name: 📦 install certbot - package_install: + package_install: # nocheck: package-install only hosts with Let's Encrypt certificates run this role id: certbot-nginx - include_role: diff --git a/roles/sys-daemon/tasks/00_core.yml b/roles/sys-daemon/tasks/00_core.yml index 88e6d4b0c9..924b698a5d 100644 --- a/roles/sys-daemon/tasks/00_core.yml +++ b/roles/sys-daemon/tasks/00_core.yml @@ -1,9 +1,4 @@ --- -- name: 📦 Install systemd tools (provides systemd-analyze) - package_install: - id: systemd-tools - become: true - - name: "♻️ reset (if enabled) for {{ role_name}}" include_tasks: 01_reset.yml when: MODE_RESET | bool and run_once_sys_daemon is not defined diff --git a/roles/sys-front-inj-all/tasks/main.yml b/roles/sys-front-inj-all/tasks/main.yml index f810d3a2cb..d0562fae3d 100644 --- a/roles/sys-front-inj-all/tasks/main.yml +++ b/roles/sys-front-inj-all/tasks/main.yml @@ -47,6 +47,6 @@ - name: "📄 Render body_filter Lua for '{{ domain }}'" stack_host_template: src: body_filter.lua.j2 - dest: "{{ lookup('nginx', 'directories.configuration.lua') }}{{ domain }}.lua" + dest: "{{ lookup('nginx', 'files.lua', domain) }}" mode: "0644" notify: reload-openresty 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 c07da70c54..42ca823183 100644 --- a/roles/sys-front-inj-all/templates/body_filter.lua.j2 +++ b/roles/sys-front-inj-all/templates/body_filter.lua.j2 @@ -89,7 +89,7 @@ end {% if (lookup('config', application_id, 'services.tor.enabled', False) | bool) and (domain | network_of) == 'tor' %} {% set _mirror_origins = lookup('applications') | external_asset_origins(application_id, DOMAIN_PRIMARY) %} -{% set _mirror_base = lookup('tls', 'web-svc-mirror', 'url.base') | regex_replace('/+$', '') %} +{% set _mirror_base = lookup('tls', 'web-svc-mirror', 'url.origin') %} {% for origin in _mirror_origins %} do local pat = ([=[https://{{ origin }}]=]):gsub("([^%w])", "%%%1") @@ -102,7 +102,7 @@ if ngx.ctx.is_css then return end -{% set _cdn_base = lookup('tls', 'web-svc-cdn', 'url.base') | regex_replace('/+$', '') %} +{% set _cdn_base = lookup('tls', 'web-svc-cdn', 'url.origin') %} {% set _tor_node = lookup('config', 'svc-net-tor', 'services.tor.node', '') %} {% set _cdn_onion = (lookup('network_urls', _cdn_base) | select('search', '\\.onion') | list | first) | default(_cdn_base, true) %} local function onionize(s) diff --git a/roles/sys-front-inj-all/templates/location.lua.j2 b/roles/sys-front-inj-all/templates/location.lua.j2 index 55b9a78d39..7a76f072da 100644 --- a/roles/sys-front-inj-all/templates/location.lua.j2 +++ b/roles/sys-front-inj-all/templates/location.lua.j2 @@ -1,4 +1,4 @@ lua_need_request_body on; set_by_lua_block $inj_inflate { ngx.ctx.inj_inflate = true return "1" } -body_filter_by_lua_file {{ lookup('nginx', 'directories.configuration.lua') }}{{ domain }}.lua; +body_filter_by_lua_file {{ lookup('nginx', 'files.lua', domain) }}; diff --git a/roles/sys-front-tls-selfsigned/tasks/00_core.yml b/roles/sys-front-tls-selfsigned/tasks/00_core.yml index 021c23d3db..67c478632a 100644 --- a/roles/sys-front-tls-selfsigned/tasks/00_core.yml +++ b/roles/sys-front-tls-selfsigned/tasks/00_core.yml @@ -88,7 +88,7 @@ subjectAltName = @alt_names [ alt_names ] - {% for d in _ss_san %} + {% for d in _ss_san | unique | sort %} DNS.{{ loop.index }} = {{ d }} {% endfor %} diff --git a/roles/sys-hostname/meta/packages.yml b/roles/sys-hostname/meta/packages.yml index 4ab1f2083e..0a09d6a8b3 100644 --- a/roles/sys-hostname/meta/packages.yml +++ b/roles/sys-hostname/meta/packages.yml @@ -6,3 +6,4 @@ hostname-tool: - hostname RedHat: - hostname + batch: false diff --git a/roles/sys-hostname/tasks/00_core.yml b/roles/sys-hostname/tasks/00_core.yml index 97d3c1bfac..d593022acc 100644 --- a/roles/sys-hostname/tasks/00_core.yml +++ b/roles/sys-hostname/tasks/00_core.yml @@ -4,7 +4,7 @@ block: - name: ✅ Ensure hostname package is installed become: true - package_install: + package_install: # nocheck: package-install skipped inside containers id: hostname-tool - name: 🔧 Set system hostname to inventory_hostname (FQDN recommended) diff --git a/roles/sys-openssl/tasks/00_core.yml b/roles/sys-openssl/tasks/00_core.yml index a326b83c1c..70042adc45 100644 --- a/roles/sys-openssl/tasks/00_core.yml +++ b/roles/sys-openssl/tasks/00_core.yml @@ -1,7 +1,2 @@ --- -- name: 📦 Install OpenSSL - become: true - package_install: - id: openssl - - include_tasks: utils/once/flag.yml diff --git a/roles/sys-pip/meta/packages.yml b/roles/sys-pip/meta/packages.yml index 08e3191531..5f70c3c5a1 100644 --- a/roles/sys-pip/meta/packages.yml +++ b/roles/sys-pip/meta/packages.yml @@ -6,6 +6,8 @@ python-dev: - python3-dev RedHat: - python3-devel + batch: false + python-pip: Archlinux: - python-pip @@ -13,3 +15,4 @@ python-pip: - python3-pip RedHat: - python3-pip + batch: false diff --git a/roles/sys-pip/tasks/00_core.yml b/roles/sys-pip/tasks/00_core.yml index 8baa742b04..9accbf492b 100644 --- a/roles/sys-pip/tasks/00_core.yml +++ b/roles/sys-pip/tasks/00_core.yml @@ -5,11 +5,11 @@ when: run_once_dev_gcc is not defined - name: 🐍 python pip install - package_install: + package_install: # nocheck: package-install needed before the update role and the batch run id: python-pip - name: 🧱 python headers for the sdists pip is asked to build - package_install: + package_install: # nocheck: package-install needed before the update role and the batch run id: python-dev - include_tasks: utils/once/flag.yml diff --git a/roles/sys-service/handlers/main.yml b/roles/sys-service/handlers/main.yml index 8048212663..8af583adc5 100644 --- a/roles/sys-service/handlers/main.yml +++ b/roles/sys-service/handlers/main.yml @@ -1,4 +1,60 @@ --- -- name: 🔄 refresh systemctl service +- name: "🔧 Enable systemctl service" listen: refresh-systemctl-service - ansible.builtin.include_tasks: refresh_systemctl_service.yml + systemd: + name: "{{ system_service_name }}" + scope: "{{ system_service_scope }}" + enabled: true + daemon_reload: 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 }}" + +- name: "🔧 Set systemctl service state" + listen: refresh-systemctl-service + systemd: + name: "{{ system_service_name }}" + scope: "{{ system_service_scope }}" + state: "{{ system_service_state }}" + 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 }}" + when: not (system_service_suppress_flush | bool) + register: systemd_set_state + failed_when: false + +- name: 🔍 sys-service | Read unit Result and ExecMainStatus (oneshot-safe) + listen: refresh-systemctl-service + ansible.builtin.command: + argv: "{{ system_service_systemctl_show + [system_service_name] }}" + register: system_service_show + changed_when: false + failed_when: false + when: not (system_service_suppress_flush | bool) + +- name: 🐛 sys-service | Show diagnostics on failure + listen: refresh-systemctl-service + ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/debug.yml" + vars: + system_service_unit_result: >- + {{ system_service_show.stdout_lines | default([]) | select('match', '^Result=') | map('regex_replace', '^Result=', '') | first | default('') | trim }} + system_service_unit_exec_status: >- + {{ system_service_show.stdout_lines | default([]) | select('match', '^ExecMainStatus=') | map('regex_replace', '^ExecMainStatus=', '') | first | default('') + | trim }} + system_service_debug_unit: "{{ system_service_name }}" + system_service_debug_context_lines: + - "system_service_id={{ system_service_id }}" + - "system_service_name={{ system_service_name }}" + - "system_service_state={{ system_service_state | default('') }}" + - "system_service_result={{ system_service_unit_result }}" + - "system_service_exec_status={{ system_service_unit_exec_status }}" + - "systemd_set_state={{ systemd_set_state | to_nice_json }}" + system_service_debug_fail: true + system_service_debug_fail_message: >- + Unable to start service {{ system_service_name }}. See shared service diagnostics above. + when: + - not (system_service_suppress_flush | bool) + - (systemd_set_state.failed | default(false) | bool) or (system_service_state != omit and (system_service_unit_result not in ['success', ''] or + system_service_unit_exec_status not in ['0', ''])) diff --git a/roles/sys-service/handlers/refresh_systemctl_service.yml b/roles/sys-service/handlers/refresh_systemctl_service.yml deleted file mode 100644 index 111fcf6bdf..0000000000 --- a/roles/sys-service/handlers/refresh_systemctl_service.yml +++ /dev/null @@ -1,57 +0,0 @@ ---- -- name: "🔧 Enable systemctl service" - systemd: - name: "{{ system_service_name }}" - scope: "{{ system_service_scope }}" - enabled: true - daemon_reload: 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 }}" - -- name: "🔧 Set systemctl service state" - systemd: - name: "{{ system_service_name }}" - scope: "{{ system_service_scope }}" - state: "{{ system_service_state }}" - 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 }}" - when: not (system_service_suppress_flush | bool) - register: systemd_set_state - failed_when: false - -- name: 🔍 sys-service | Read unit Result (oneshot-safe) - ansible.builtin.command: - 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: "{{ system_service_systemctl_show + ['ExecMainStatus', system_service_name] }}" - register: system_service_exec_status - changed_when: false - failed_when: false - -- name: 🐛 sys-service | Show diagnostics on failure - ansible.builtin.include_tasks: "{{ role_path }}/tasks/utils/debug.yml" - vars: - system_service_debug_unit: "{{ system_service_name }}" - system_service_debug_context_lines: - - "system_service_id={{ system_service_id }}" - - "system_service_name={{ system_service_name }}" - - "system_service_state={{ system_service_state | default('') }}" - - "system_service_result={{ system_service_result.stdout | default('') | trim }}" - - "system_service_exec_status={{ system_service_exec_status.stdout | default('') | trim }}" - - "systemd_set_state={{ systemd_set_state | to_nice_json }}" - system_service_debug_fail: true - system_service_debug_fail_message: >- - Unable to start service {{ system_service_name }}. See shared service diagnostics above. - when: - - not (system_service_suppress_flush | bool) - - (systemd_set_state.failed | default(false) | bool) or (system_service_state != omit and ( (system_service_result.stdout | default('') | trim) not in - ['success', ''] or (system_service_exec_status.stdout | default('') | trim) not in ['0', ''])) diff --git a/roles/sys-service/tasks/04_base.yml b/roles/sys-service/tasks/04_base.yml index 6aa9180b46..e0e504c0f9 100644 --- a/roles/sys-service/tasks/04_base.yml +++ b/roles/sys-service/tasks/04_base.yml @@ -1,32 +1,15 @@ --- -- name: "📂 Copy the service files for '{{ system_service_id }}'" - when: system_service_copy_files | bool - block: - - name: "🔍 find best matching source for service script" - set_fact: - system_service_script_src: >- - {{ lookup('first_found', - { - 'files': [ - 'templates/script.sh.j2', - 'templates/script.py.j2', - 'files/shell/script.sh', - 'files/python/script.py' - ], - 'paths': [ system_service_role_dir ] - }, - errors='strict' - ) }} - - - name: "📂 Load file logic for '{{ system_service_id }}'" - include_tasks: 05_files.yml - when: system_service_script_src | default('') | length > 0 +- name: "📂 Load file logic for '{{ system_service_id }}'" + import_tasks: 05_files.yml + when: + - system_service_copy_files | bool + - system_service_script_src | length > 0 - name: "📂 Load systemctl logic for '{{ system_service_id }}'" - include_tasks: 06_service.yml + import_tasks: 06_service.yml - name: "📂 Load timer logic for '{{ system_service_id }}'" - include_tasks: 07_timer.yml + import_tasks: 07_timer.yml when: system_service_timer_enabled | bool - name: "➕ sys-service | Add '{{ system_service_name }}' to final run list" diff --git a/roles/sys-service/tasks/05_files.yml b/roles/sys-service/tasks/05_files.yml index 9eeaaf5fa8..494392faec 100644 --- a/roles/sys-service/tasks/05_files.yml +++ b/roles/sys-service/tasks/05_files.yml @@ -5,21 +5,18 @@ state: directory mode: "0755" -- name: "📄 template or copy script" - block: - - name: "📄 render template" - template: # nocheck: stack-host-template (per-host script for per-host systemd service) - src: "{{ system_service_script_src }}" - dest: "{{ [system_service_script_dir, (system_service_script_src | basename | regex_replace('\\.j2$', ''))] | path_join }}" - mode: "0755" - notify: "{{ 'reload-system-daemon' if system_service_is_template | bool else 'refresh-systemctl-service' }}" - when: system_service_script_src.endswith('.j2') +- name: "📄 render template" + template: # nocheck: stack-host-template (per-host script for per-host systemd service) + src: "{{ system_service_script_src }}" + dest: "{{ [system_service_script_dir, (system_service_script_src | basename | regex_replace('\\.j2$', ''))] | path_join }}" + mode: "0755" + notify: "{{ 'reload-system-daemon' if system_service_is_template | bool else 'refresh-systemctl-service' }}" + when: system_service_script_src.endswith('.j2') - - name: "📋 copy raw file" - copy: - src: "{{ system_service_script_src }}" - dest: "{{ [system_service_script_dir, (system_service_script_src | basename)] | path_join }}" - mode: "0755" - when: not system_service_script_src.endswith('.j2') - notify: "{{ 'reload-system-daemon' if system_service_is_template | bool else 'refresh-systemctl-service' }}" - when: system_service_copy_files | bool +- name: "📋 copy raw file" + copy: + src: "{{ system_service_script_src }}" + dest: "{{ [system_service_script_dir, (system_service_script_src | basename)] | path_join }}" + mode: "0755" + when: not system_service_script_src.endswith('.j2') + notify: "{{ 'reload-system-daemon' if system_service_is_template | bool else 'refresh-systemctl-service' }}" diff --git a/roles/sys-service/tasks/06_service.yml b/roles/sys-service/tasks/06_service.yml index a89a63ad6d..eb243fa929 100644 --- a/roles/sys-service/tasks/06_service.yml +++ b/roles/sys-service/tasks/06_service.yml @@ -1,30 +1,4 @@ --- -- name: 🔍 Resolve systemctl template source - set_fact: - system_service_template_src: >- - {{ lookup( - 'first_found', - { - 'files': [ - 'templates/systemctl@.service.j2', - 'templates/systemctl.service.j2' - ], - 'paths': [ - system_service_role_dir, - role_path - ] - }, - errors='strict' - ) }} - -- name: ✅ Ensure a systemctl template was found - assert: - that: system_service_template_src | length > 0 - fail_msg: >- - Could not resolve any systemctl template. Looked in: - {{ system_service_role_dir }}/templates/ and {{ role_path }}/templates/. - when: MODE_ASSERT | bool - - name: "🔧 setup systemctl '{{ system_service_id }}'" template: # nocheck: stack-host-template (per-host systemd service unit) src: "{{ system_service_template_src }}" @@ -35,13 +9,9 @@ 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 - block: - - name: 🔄 reload system daemon - command: /bin/true - notify: reload-system-daemon - - name: 🔄 refresh systemctl service - command: /bin/true - notify: refresh-systemctl-service - when: not system_service_is_template | bool +- name: "🔄 Force the handlers of '{{ system_service_id }}' to run" + ansible.builtin.debug: + msg: "system_service_force_flush_instant runs the handlers of {{ system_service_name }}." + changed_when: true + notify: "{{ ['reload-system-daemon'] + ([] if system_service_is_template | bool else ['refresh-systemctl-service']) }}" when: system_service_force_flush_instant | bool diff --git a/roles/sys-service/tasks/07_timer.yml b/roles/sys-service/tasks/07_timer.yml index 4814d6ad92..81caa1fada 100644 --- a/roles/sys-service/tasks/07_timer.yml +++ b/roles/sys-service/tasks/07_timer.yml @@ -1,25 +1,20 @@ --- -- name: 🛑 Fail if a timer is asked for outside the system scope +- name: 🛑 Fail if the timer of '{{ system_service_id }}' cannot drive its service assert: that: - system_service_scope == 'system' - fail_msg: >- + - not (MODE_ASSERT | bool) or '@' not in system_service_id + fail_msg: "{{ system_service_timer_scope_msg if system_service_scope != 'system' else system_service_timer_id_msg }}" + vars: + system_service_timer_scope_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. + system_service_timer_id_msg: "Invalid system_service_id '{{ system_service_id }}' → must not contain '@'." -- name: 🛑 Fail if system_service_id contains "@" - assert: - that: - - "'@' not in system_service_id" - fail_msg: "Invalid system_service_id '{{ system_service_id }}' → must not contain '@'." - when: MODE_ASSERT | bool - -- name: "🔨 Make '{{ system_service_id }}' available for sys-timer" - set_fact: - system_service_timer_service: "{{ system_service_id }}" - -- name: "📂 include role for sys-timer for {{ system_service_timer_service }}" +- name: "📂 include role for sys-timer for {{ system_service_id }}" include_role: name: sys-timer + vars: + system_service_timer_service: "{{ system_service_id }}" diff --git a/roles/sys-service/tasks/main.yml b/roles/sys-service/tasks/main.yml index c759025647..530b5875c2 100644 --- a/roles/sys-service/tasks/main.yml +++ b/roles/sys-service/tasks/main.yml @@ -13,7 +13,7 @@ - name: "▶️ Execute service routines for '{{ system_service_id }}'" block: - name: "🧩 Load base routine for '{{ system_service_id }}'" - include_tasks: 04_base.yml + import_tasks: 04_base.yml - name: "🚿 Flush system service handlers for '{{ system_service_id }}'" meta: flush_handlers when: system_service_id is defined diff --git a/roles/sys-service/vars/main.yml b/roles/sys-service/vars/main.yml index 24b8e3fae9..ad89c55845 100644 --- a/roles/sys-service/vars/main.yml +++ b/roles/sys-service/vars/main.yml @@ -8,11 +8,40 @@ system_service_scope: "system" # 'system' for root units, 'user' for per-login u 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_systemctl_show: "{{ ['systemctl'] + (['--user'] if system_service_scope == 'user' else []) + ['--no-pager', 'show', '-p', 'Result', '-p', 'ExecMainStatus'] + }}" 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 }}" +system_service_script_src: >- + {{ lookup('first_found', + { + 'files': [ + 'templates/script.sh.j2', + 'templates/script.py.j2', + 'files/shell/script.sh', + 'files/python/script.py' + ], + 'paths': [ system_service_role_dir ] + }, + errors='strict' + ) }} +system_service_template_src: >- + {{ lookup( + 'first_found', + { + 'files': [ + 'templates/systemctl@.service.j2', + 'templates/systemctl.service.j2' + ], + 'paths': [ + system_service_role_dir, + role_path + ] + }, + errors='strict' + ) }} system_service_force_linear_sync: "{{ system_service_name in SYS_SERVICE_GROUP_MANIPULATION }}" # Disables automatic async system_service_force_flush_instant: "{{ (SYS_SERVICE_ALL_ENABLED | bool) and not system_service_force_flush_final }}" # When set to true it activates the flushing of services. defaults to SYS_SERVICE_ALL_ENABLED diff --git a/roles/sys-sudo/meta/packages.yml b/roles/sys-sudo/meta/packages.yml index a717eb47e5..60c3110a7b 100644 --- a/roles/sys-sudo/meta/packages.yml +++ b/roles/sys-sudo/meta/packages.yml @@ -6,3 +6,4 @@ sudo: - sudo RedHat: - sudo + batch: false diff --git a/roles/sys-sudo/tasks/main.yml b/roles/sys-sudo/tasks/main.yml index b34252b8be..2028134c6b 100644 --- a/roles/sys-sudo/tasks/main.yml +++ b/roles/sys-sudo/tasks/main.yml @@ -1,7 +1,7 @@ --- - block: - name: 📦 Install sudo (Arch/Manjaro) - package_install: + package_install: # nocheck: package-install user-root needs sudo before the update role and the batch run id: sudo - name: ▶️ run the sudo tasks once set_fact: diff --git a/roles/sys-svc-certbot/meta/packages.yml b/roles/sys-svc-certbot/meta/packages.yml index 97831723f1..709f9f52a3 100644 --- a/roles/sys-svc-certbot/meta/packages.yml +++ b/roles/sys-svc-certbot/meta/packages.yml @@ -6,6 +6,7 @@ certbot: - certbot RedHat: - certbot + batch: false centos: names: - certbot diff --git a/roles/sys-svc-certbot/tasks/00_core.yml b/roles/sys-svc-certbot/tasks/00_core.yml index d2f3c3b154..ffd26939b2 100644 --- a/roles/sys-svc-certbot/tasks/00_core.yml +++ b/roles/sys-svc-certbot/tasks/00_core.yml @@ -1,6 +1,6 @@ --- - name: 📦 install certbot - package_install: + package_install: # nocheck: package-install only hosts with Let's Encrypt certificates run this role id: certbot - name: "📂 Include tasks for 'No-Webroot-ACME-CHALLENGE-METHOD'" 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 7cec376626..becd8e1ba5 100755 --- a/roles/sys-svc-compose-ca/files/python/compose_ca.py +++ b/roles/sys-svc-compose-ca/files/python/compose_ca.py @@ -211,8 +211,9 @@ def escape_compose_vars(argv: list[str]) -> list[str]: Compose escaping rule: - $$ => literal $ (no interpolation) - Therefore: replace every "$" with "$$" in exec-form argv strings that we write into - compose override YAML (entrypoint/command). + Therefore: replace every "$" with "$$" in the image's exec-form argv before it is + written into compose override YAML; a service's own argv comes from `compose config`, + which already prints a literal "$" as "$$". """ return [s.replace("$", "$$") for s in argv] @@ -582,7 +583,7 @@ def render_override( IMPORTANT: Docker Compose interpolates $VARS in YAML strings on the host. - We escape any $ in the command argv with $$ so container-side expansion works. + We escape any $ in the image's argv with $$ so container-side expansion works. """ out_services: dict[str, Any] = {} extra_ca_host = _cache_frontend_ca_host() @@ -678,8 +679,8 @@ def render_override( img_ep = normalize_entrypoint(raw_ep) img_cmd = normalize_cmd(raw_cmd) - final_ep = svc_ep or img_ep - final_cmd = svc_cmd or img_cmd + final_ep = svc_ep or escape_compose_vars(img_ep) + final_cmd = svc_cmd or escape_compose_vars(img_cmd) if _is_shell_form(final_ep): final_cmd = [_shell_payload(final_cmd)] @@ -688,7 +689,7 @@ def render_override( if has_sh and effective_cmd: override_svc["entrypoint"] = [wrapper_container] - override_svc["command"] = escape_compose_vars(effective_cmd) + override_svc["command"] = effective_cmd out_services[name] = override_svc diff --git a/roles/sys-svc-compose/handlers/compose.yml b/roles/sys-svc-compose/handlers/compose.yml index 85af7fe5dd..c332676728 100644 --- a/roles/sys-svc-compose/handlers/compose.yml +++ b/roles/sys-svc-compose/handlers/compose.yml @@ -8,36 +8,6 @@ - container-recreate - compose-service-up -- name: 📝 Generate CA trust override - ansible.builtin.shell: | - set -euo pipefail - {{ lookup('compose_ca_inject_cmd', application_id) }} - args: - chdir: "{{ lookup('container', application_id, 'directories.instance') }}" - executable: /bin/bash - register: compose_ca_override - timeout: "{{ lookup('timeout', 1200) | int }}" - retries: 7 - delay: 20 - until: compose_ca_override is succeeded - listen: - - compose-up - when: lookup('ca_injected', application_id) - -- name: ✅ Validate Docker Compose configuration - ansible.builtin.shell: | - set -euo pipefail - compose config --quiet - args: - chdir: "{{ lookup('container', application_id, 'directories.instance') }}" - executable: /bin/bash - register: dc_validate - changed_when: false - failed_when: dc_validate.rc != 0 - listen: - - compose-up - when: MODE_ASSERT_LOCAL | bool - - name: 📥 compose pull ansible.builtin.script: cmd: >- @@ -92,6 +62,36 @@ listen: - compose-build +- name: 📝 Generate CA trust override + ansible.builtin.shell: | + set -euo pipefail + {{ lookup('compose_ca_inject_cmd', application_id) }} + args: + chdir: "{{ lookup('container', application_id, 'directories.instance') }}" + executable: /bin/bash + register: compose_ca_override + timeout: "{{ lookup('timeout', 1200) | int }}" + retries: 7 + delay: 20 + until: compose_ca_override is succeeded + listen: + - compose-up + when: lookup('ca_injected', application_id) + +- name: ✅ Validate Docker Compose configuration + ansible.builtin.shell: | + set -euo pipefail + compose config --quiet + args: + chdir: "{{ lookup('container', application_id, 'directories.instance') }}" + executable: /bin/bash + register: dc_validate + changed_when: false + failed_when: dc_validate.rc != 0 + listen: + - compose-up + when: MODE_ASSERT_LOCAL | bool + - 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: diff --git a/roles/sys-svc-compose/tasks/00_core.yml b/roles/sys-svc-compose/tasks/00_core.yml index ab5af6efaa..35e8555721 100644 --- a/roles/sys-svc-compose/tasks/00_core.yml +++ b/roles/sys-svc-compose/tasks/00_core.yml @@ -1,10 +1,6 @@ --- - include_tasks: utils/once/flag.yml -- name: "✅ Ensure compose wrapper system deps (PyYAML)" - package_install: - id: python-yaml - - name: 📦 Install compose wrapper become: true ansible.builtin.copy: diff --git a/roles/sys-svc-container/README.md b/roles/sys-svc-container/README.md index 02672ecc48..15e326cba6 100644 --- a/roles/sys-svc-container/README.md +++ b/roles/sys-svc-container/README.md @@ -28,7 +28,7 @@ When enabled via `MODE_CLEANUP` or `MODE_RESET`, it will automatically prune unu - **Image Pre-Pull** [start.yml](tasks/utils/prepull/start.yml) pulls the images the deploy of the host runs, as listed by the `update_pull_images` filter, that the host does not hold yet under the pinned reference ([pull.yml](tasks/utils/prepull/pull.yml)), three at a time in a background job right before the shared services load; with nothing missing no job starts. - It runs when `ASYNC_ENABLED` is true, `STORAGE_CONSTRAINED` and `MODE_RESET` are false, and the host is a stack host, so never on a swarm worker. + It runs whatever `ASYNC_ENABLED` says, when `STORAGE_CONSTRAINED` and `MODE_RESET` are false and the host is a stack host, so never on a swarm worker. [reap.yml](tasks/utils/prepull/reap.yml) collects the job before the E2E run, or at the start of the destructor on a host without a server stage, and prints the pulls that failed. A failed pull or the time limit of `SYS_SVC_CONTAINER_PREPULL_ASYNC_TIME` does not fail the deploy, and each app still pulls its images itself. diff --git a/roles/sys-svc-container/handlers/main.yml b/roles/sys-svc-container/handlers/main.yml index 245328adaa..ad3996b457 100644 --- a/roles/sys-svc-container/handlers/main.yml +++ b/roles/sys-svc-container/handlers/main.yml @@ -22,3 +22,4 @@ NODE_IMAGE: "{{ '' if IS_SWARM_MODE else lookup('config', 'sys-svc-container', 'services.node.image') ~ ':' ~ lookup('config', 'sys-svc-container', 'services.node.version') }}" DOMAIN: "{{ DOMAIN_PRIMARY }}" + CA_CONTAINER_ENABLED: "0" diff --git a/roles/sys-svc-container/meta/packages.yml b/roles/sys-svc-container/meta/packages.yml index b936706079..4a1bd9b06b 100644 --- a/roles/sys-svc-container/meta/packages.yml +++ b/roles/sys-svc-container/meta/packages.yml @@ -23,6 +23,7 @@ docker-cli: - iptables-nft repo: managed_externally: sys-svc-container configures the download.docker.com repository per distro before installing + batch: false nvidia-container-toolkit: Archlinux: @@ -37,3 +38,4 @@ nvidia-container-toolkit: - nvidia-container-toolkit repo: managed_externally: sys-svc-container configures the nvidia.github.io repository before installing + batch: false diff --git a/roles/sys-svc-container/tasks/00_core.yml b/roles/sys-svc-container/tasks/00_core.yml index 0bf93dafab..1933c06e7b 100644 --- a/roles/sys-svc-container/tasks/00_core.yml +++ b/roles/sys-svc-container/tasks/00_core.yml @@ -22,7 +22,7 @@ when: ansible_facts['os_family'] == 'RedHat' - name: 📦 Install Docker packages - package_install: + package_install: # nocheck: package-install needs the Docker repository the role adds first id: docker-cli register: sys_svc_container_packages_install retries: 5 diff --git a/roles/sys-svc-container/tasks/00_core/debian.yml b/roles/sys-svc-container/tasks/00_core/debian.yml index c78ca6ce76..42dddaa826 100644 --- a/roles/sys-svc-container/tasks/00_core/debian.yml +++ b/roles/sys-svc-container/tasks/00_core/debian.yml @@ -13,7 +13,7 @@ - name: 🔧 Configure Docker apt repository ansible.builtin.copy: dest: /etc/apt/sources.list.d/docker.list - content: >- + content: > deb [arch={{ SYS_SVC_CONTAINER_DPKG_ARCH_BY_ANSIBLE_ARCH.get(ansible_facts['architecture'], ansible_facts['architecture']) }} signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/{{ SYS_SVC_CONTAINER_DOCKER_REPO_DISTRO_BY_DISTRIBUTION[ansible_facts['distribution']] }} diff --git a/roles/sys-svc-container/tasks/00_core/nvidia.yml b/roles/sys-svc-container/tasks/00_core/nvidia.yml index 306dc12373..799f62dc7a 100644 --- a/roles/sys-svc-container/tasks/00_core/nvidia.yml +++ b/roles/sys-svc-container/tasks/00_core/nvidia.yml @@ -8,7 +8,7 @@ when: ansible_facts['os_family'] == 'RedHat' - name: "📦 Install the NVIDIA container toolkit" - package_install: + package_install: # nocheck: package-install needs the nvidia.github.io repository configured above, only on hosts with an NVIDIA device id: nvidia-container-toolkit register: sys_svc_container_nvidia_install until: sys_svc_container_nvidia_install is succeeded diff --git a/roles/sys-svc-container/tasks/_mtu.yml b/roles/sys-svc-container/tasks/_mtu.yml index f7972ff789..8561a7ade5 100644 --- a/roles/sys-svc-container/tasks/_mtu.yml +++ b/roles/sys-svc-container/tasks/_mtu.yml @@ -7,11 +7,22 @@ global_install: true - name: ✅ Ensure 'ip' and 'ping' commands are available for automtu - package_install: + package_install: # nocheck: package-install only for the automtu measurement this file is included for id: - iproute - iputils-ping +- name: 📏 Read the egress MTU automtu measures against + ansible.builtin.command: + argv: + - "{{ ansible_python_interpreter }}" + - -m + - automtu + - --print-mtu + - egress + register: automtu_egress + changed_when: false + - name: 🔍 Detect safe Docker MTU ansible.builtin.command: argv: @@ -20,20 +31,29 @@ - automtu - --pmtu-target - "{{ SYS_SVC_DOCKER_AUTOMTU_TARGETS | join(',') }}" + - --pmtu-min-payload + - "{{ automtu_probe_payload }}" + - --pmtu-max-payload + - "{{ automtu_probe_payload }}" - --pmtu-policy - - min + - max - --print-mtu - effective + vars: + automtu_probe_payload: >- + {{ (([SYS_SVC_DOCKER_AUTOMTU_MTU_CEILING, automtu_egress.stdout | int] | min) + - SYS_SVC_DOCKER_AUTOMTU_ICMP_HEADER_BYTES) | string }} register: automtu_mtu changed_when: false - name: ✅ Assert automtu returned an integer MTU ansible.builtin.assert: that: + - automtu_egress.stdout is match('^[0-9]+$') - automtu_mtu.stdout is match('^[0-9]+$') - (automtu_mtu.stdout | int) >= 576 - (automtu_mtu.stdout | int) <= 9000 - fail_msg: "automtu returned unexpected MTU output: '{{ automtu_mtu.stdout | default('') }}'" + fail_msg: "automtu returned unexpected MTU output: egress '{{ automtu_egress.stdout }}', effective '{{ automtu_mtu.stdout }}'" - name: 🔧 Set docker daemon MTU fact ansible.builtin.set_fact: diff --git a/roles/sys-svc-container/tasks/utils/prepull/start.yml b/roles/sys-svc-container/tasks/utils/prepull/start.yml index 4e1fd048fa..ac5ca7f09f 100644 --- a/roles/sys-svc-container/tasks/utils/prepull/start.yml +++ b/roles/sys-svc-container/tasks/utils/prepull/start.yml @@ -1,7 +1,6 @@ --- - name: "📥 Pre-pull the images of this deploy in the background" when: - - ASYNC_ENABLED | bool - not (STORAGE_CONSTRAINED | bool) - not (MODE_RESET | bool) - IS_STACK_HOST | bool diff --git a/roles/sys-svc-container/vars/main.yml b/roles/sys-svc-container/vars/main.yml index 608918bb5b..088c223611 100644 --- a/roles/sys-svc-container/vars/main.yml +++ b/roles/sys-svc-container/vars/main.yml @@ -3,7 +3,9 @@ SYS_SVC_DOCKER_DIR: "/etc/docker/" SYS_SVC_DOCKER_DAEMON: "{{ [SYS_SVC_DOCKER_DIR, 'daemon.json' ] | path_join }}" SYS_SVC_DOCKER_AUTOMTU_TARGETS: >- - {{ ['registry-1.docker.io', 'github.com'] + NETWORK_PUBLIC_DNS_RESOLVERS }} + {{ ['github.com'] + NETWORK_PUBLIC_DNS_RESOLVERS }} +SYS_SVC_DOCKER_AUTOMTU_MTU_CEILING: 1500 +SYS_SVC_DOCKER_AUTOMTU_ICMP_HEADER_BYTES: 28 SYS_SVC_CONTAINER_DOCKER_REPO_DISTRO_BY_DISTRIBUTION: Debian: debian diff --git a/roles/sys-svc-mail-msmtp/meta/packages.yml b/roles/sys-svc-mail-msmtp/meta/packages.yml index feb15e0940..3c6dfddf61 100644 --- a/roles/sys-svc-mail-msmtp/meta/packages.yml +++ b/roles/sys-svc-mail-msmtp/meta/packages.yml @@ -1,4 +1,7 @@ --- +ca-certificates: + shared: true + msmtp: Archlinux: - msmtp @@ -18,3 +21,4 @@ msmtp-mta: Debian: - msmtp-mta RedHat: [] # nocheck: empty - neither the EL base repositories nor EPEL ship msmtp-mta, so the role links /usr/bin/sendmail to msmtp instead + batch: false diff --git a/roles/sys-svc-mail-msmtp/tasks/disable.yml b/roles/sys-svc-mail-msmtp/tasks/disable.yml index 19d1e27086..1b86ea7956 100644 --- a/roles/sys-svc-mail-msmtp/tasks/disable.yml +++ b/roles/sys-svc-mail-msmtp/tasks/disable.yml @@ -1,6 +1,6 @@ --- - name: "✅ Ensure msmtp-mta is absent (conflicts with postfix smtp-forwarder)" - package_install: + package_install: # nocheck: package-install removes msmtp-mta, the batch only installs id: msmtp-mta state: absent diff --git a/roles/sys-svc-mail-msmtp/tasks/enable.yml b/roles/sys-svc-mail-msmtp/tasks/enable.yml index 20848be3b8..d332b9eed7 100644 --- a/roles/sys-svc-mail-msmtp/tasks/enable.yml +++ b/roles/sys-svc-mail-msmtp/tasks/enable.yml @@ -12,14 +12,6 @@ is the dedicated NFS server (svc-storage-nfs-server). Hosts outside the swarm (svc-swarm-node) keep a local {{ DIR_VAR_LIB }}. -- name: 📦 Install msmtp base package - package_install: - id: msmtp - -- name: "📦 Install the CA trust store" - package_install: - id: ca-certificates - - name: ✅ Ensure the shared Root CA is trusted for the TLS mail relay include_role: name: sys-ca-selfsigned @@ -33,7 +25,7 @@ - when: lookup('email').external | bool block: - name: 📦 Install msmtp-mta when Mailu is used and package exists on distro - package_install: + package_install: # nocheck: package-install only inside the Mailu block and only where the distro ships msmtp-mta id: msmtp-mta register: sys_svc_mail_msmtp_mta @@ -49,7 +41,7 @@ template: # nocheck: stack-host-template (per-host /root/.msmtprc, not stack-host-only) src: "msmtprc.conf.j2" dest: "/root/.msmtprc" - mode: 600 + mode: "0600" vars: sys_svc_mail_msmtp_in_container: false diff --git a/roles/sys-svc-mail-smtp/tasks/disable.yml b/roles/sys-svc-mail-smtp/tasks/disable.yml index 9a394142f1..7a89c2cbbb 100644 --- a/roles/sys-svc-mail-smtp/tasks/disable.yml +++ b/roles/sys-svc-mail-smtp/tasks/disable.yml @@ -1,14 +1,19 @@ --- - block: - - name: ⏹️ Stop and disable postfix if present (avoid port 25 conflicts) + - name: 🔎 Check whether postfix is installed + ansible.builtin.stat: + path: /usr/sbin/postfix + register: sys_svc_mail_smtp_postfix_binary + + - name: ⏹️ Stop and disable postfix (avoid port 25 conflicts) service: name: postfix state: stopped enabled: false - failed_when: false + when: sys_svc_mail_smtp_postfix_binary.stat.exists - name: 🗑️ Remove postfix when external SMTP is used (conflicts with msmtp-mta) - package_install: + package_install: # nocheck: package-install removes postfix, the batch only installs id: postfix state: absent when: lookup('email').external | bool diff --git a/roles/sys-svc-mail-smtp/tasks/enable.yml b/roles/sys-svc-mail-smtp/tasks/enable.yml index 05f7bb5ef5..439fd04a83 100644 --- a/roles/sys-svc-mail-smtp/tasks/enable.yml +++ b/roles/sys-svc-mail-smtp/tasks/enable.yml @@ -12,7 +12,7 @@ when: run_once_sys_daemon is not defined - name: "📦 Install local SMTP relay (Postfix)" - package_install: + package_install: # nocheck: package-install only when the email relay is not external id: postfix - name: "🔧 Configure Postfix as localhost-only relay" diff --git a/roles/sys-svc-nss/tasks/00_core.yml b/roles/sys-svc-nss/tasks/00_core.yml index 1a883ff42f..f32335ca2d 100644 --- a/roles/sys-svc-nss/tasks/00_core.yml +++ b/roles/sys-svc-nss/tasks/00_core.yml @@ -1,9 +1,4 @@ --- -- name: ✅ Ensure nss-myhostname is installed so *.localhost resolves to loopback - become: true - package_install: - id: nss-myhostname - - name: ✅ Ensure nsswitch resolves hosts via myhostname become: true ansible.builtin.lineinfile: 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 8bf5b19b36..9b06bac3c7 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 @@ -22,7 +22,7 @@ header_filter_by_lua_block { ngx.ctx.is_html = true ngx.header.content_length = nil {% if _network == 'clearnet' and _onion.host and domain != (OIDC.URL | urlsplit('hostname')) and not lookup('config', application_id, 'networks.reachability.handover', False) %} - ngx.header["Onion-Location"] = "{{ lookup('tls', _onion.host, 'url.base') | regex_replace('/+$', '') }}" .. ngx.var.request_uri + ngx.header["Onion-Location"] = "{{ lookup('tls', _onion.host, 'url.origin') }}" .. ngx.var.request_uri {% endif %} else ngx.ctx.is_html = false diff --git a/roles/sys-svc-proxy/templates/headers/forwarded_base.conf.j2 b/roles/sys-svc-proxy/templates/headers/forwarded_base.conf.j2 new file mode 100644 index 0000000000..8590f9bb9b --- /dev/null +++ b/roles/sys-svc-proxy/templates/headers/forwarded_base.conf.j2 @@ -0,0 +1,4 @@ +proxy_set_header Host $host; +proxy_set_header X-Real-IP $remote_addr; +proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; +proxy_set_header X-Forwarded-Proto {{ proxy_x_forwarded_proto | default('$scheme') }}; diff --git a/roles/sys-svc-proxy/templates/location/sso_acl.conf.j2 b/roles/sys-svc-proxy/templates/location/sso_acl.conf.j2 new file mode 100644 index 0000000000..5b4219dbfd --- /dev/null +++ b/roles/sys-svc-proxy/templates/location/sso_acl.conf.j2 @@ -0,0 +1,41 @@ +{# Param sso_gated_location_extra_configuration: directives appended to every SSO-gated location. #} +{# Param sso_open_location_extra_configuration: directives appended to every location the ACL leaves ungated. #} +{% if lookup('sso', application_id, 'is_proxy_gated') %} + {% set _base_extra = webserver_location_extra_configuration | default('') %} + {% set _gated_extra = _base_extra ~ (sso_gated_location_extra_configuration | default('')) %} + {% set _open_extra = _base_extra ~ (sso_open_location_extra_configuration | default('')) %} + {% set acl = lookup('sso', application_id, 'oauth2_acl') %} + + {% if acl.blacklist is defined %} + {% with sso_proxy_enabled = false, location = "/", webserver_location_extra_configuration = _open_extra %} + {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} + {% endwith %} + + {% for loc in acl.blacklist %} + {% with sso_proxy_enabled = true, location = loc, webserver_location_extra_configuration = _gated_extra %} + {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} + {% endwith %} + {% endfor %} + + {% elif acl.whitelist is defined %} + {% with sso_proxy_enabled = true, location = "/", webserver_location_extra_configuration = _gated_extra %} + {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} + {% endwith %} + + {% for loc in acl.whitelist %} + {% with sso_proxy_enabled = false, location = loc, webserver_location_extra_configuration = _open_extra %} + {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} + {% endwith %} + {% endfor %} + + {% else %} + {% with sso_proxy_enabled = true, location = "/", webserver_location_extra_configuration = _gated_extra %} + {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} + {% endwith %} + {% endif %} + +{% else %} + {% set sso_proxy_enabled = false %} + {% set location = "/" %} + {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} +{% endif %} diff --git a/roles/sys-svc-proxy/templates/vhost/basic.conf.j2 b/roles/sys-svc-proxy/templates/vhost/basic.conf.j2 index 709975e8e0..6572386ce3 100644 --- a/roles/sys-svc-proxy/templates/vhost/basic.conf.j2 +++ b/roles/sys-svc-proxy/templates/vhost/basic.conf.j2 @@ -27,41 +27,8 @@ server {% elif lookup('network_handover', application_id, domain) %} {% include 'roles/sys-svc-proxy/templates/location/handover.conf.j2' %} - {% elif lookup('sso', application_id, 'is_proxy_gated') %} - {% set acl = lookup('sso', application_id, 'oauth2_acl') %} - - {% if acl.blacklist is defined %} - {% set sso_proxy_enabled = false %} - {% set location = "/" %} - {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} - - {% for loc in acl.blacklist %} - {% set sso_proxy_enabled = true %} - {% set location = loc %} - {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} - {% endfor %} - - {% elif acl.whitelist is defined %} - {% set sso_proxy_enabled = true %} - {% set location = "/" %} - {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} - - {% for loc in acl.whitelist %} - {% set sso_proxy_enabled = false %} - {% set location = loc %} - {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} - {% endfor %} - - {% else %} - {% set sso_proxy_enabled = true %} - {% set location = "/" %} - {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} - {% endif %} - {% else %} - {% set sso_proxy_enabled = false %} - {% set location = "/" %} - {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} + {% include 'roles/sys-svc-proxy/templates/location/sso_acl.conf.j2' %} {% endif %} {% include 'roles/web-app-prometheus/templates/nginx/locations.conf.j2' %} diff --git a/roles/sys-svc-rdbms/tasks/utils/realign_dedicated_db.yml b/roles/sys-svc-rdbms/tasks/utils/realign_dedicated_db.yml index 4471d193fb..28939894e4 100644 --- a/roles/sys-svc-rdbms/tasks/utils/realign_dedicated_db.yml +++ b/roles/sys-svc-rdbms/tasks/utils/realign_dedicated_db.yml @@ -26,12 +26,16 @@ 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, 'username') | quote }} - environment: - POSTGRES_SUPERUSER_PASSWORD: "{{ lookup('database', application_id, 'password') }}" + ansible.builtin.command: + argv: + - bash + - -c + - "{{ lookup('file', lookup('path_absolute', 'roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh')) }}" + - set_postgres_superuser_password.sh + - "{{ lookup('database', application_id, 'container') }}" + - "{{ lookup('database', application_id, 'username') }}" + stdin: "{{ lookup('database', application_id, 'password') }}" + expand_argument_vars: false register: _app_db_realign no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" changed_when: _app_db_realign.stdout is search('\\[CHANGED\\]') diff --git a/roles/sys-svc-ssh/meta/packages.yml b/roles/sys-svc-ssh/meta/packages.yml index 1784d762f9..672cd80498 100644 --- a/roles/sys-svc-ssh/meta/packages.yml +++ b/roles/sys-svc-ssh/meta/packages.yml @@ -6,3 +6,4 @@ openssh-client: - openssh-client RedHat: - openssh-clients + batch: false diff --git a/roles/sys-svc-ssh/tasks/00_core.yml b/roles/sys-svc-ssh/tasks/00_core.yml index 211e926920..942ec697bf 100644 --- a/roles/sys-svc-ssh/tasks/00_core.yml +++ b/roles/sys-svc-ssh/tasks/00_core.yml @@ -12,7 +12,7 @@ when: ansible_facts['os_family'] == 'Debian' - name: 📦 Install OpenSSH client - package_install: + package_install: # nocheck: package-install user-root and the mesh bootstrap need it before the update role and the batch run id: openssh-client - include_tasks: utils/once/flag.yml diff --git a/roles/sys-timer/tasks/main.yml b/roles/sys-timer/tasks/main.yml index 0d661f7f72..3e4d425122 100644 --- a/roles/sys-timer/tasks/main.yml +++ b/roles/sys-timer/tasks/main.yml @@ -9,7 +9,7 @@ - name: "🚀 deploy timer" systemd: - daemon_reload: true + daemon_reload: "{{ dummy_timer is changed }}" name: "{{ sys_timer_file }}" state: stopped enabled: false diff --git a/roles/sys-token-store/README.md b/roles/sys-token-store/README.md index 73b9ea6427..75eaa0dca1 100644 --- a/roles/sys-token-store/README.md +++ b/roles/sys-token-store/README.md @@ -85,9 +85,21 @@ This is the **canonical way** to store tokens. - Updates the token store file (idempotent) - Makes the token available via `lookup('users', '').tokens['']` -- Exports `sys_token_store_token` -Empty tokens are rejected explicitly. +Empty tokens are rejected explicitly. `write.yml` hands its token to `write_many.yml` as a one-entry list. + +### `write_many.yml` + +Persists several tokens with one store write and at most one re-render of the applications SPOT. + +**Input** + +- `sys_token_store_entries`: list of `{user_key, app, token}`; every `token` must be non-empty + +**Effects** + +- Merges every entry into the store in list order, so a later entry for the same user and app wins +- Writes the store file and re-renders the applications SPOT once, and only when the merged store differs from the loaded one --- @@ -111,6 +123,22 @@ After this, the token is available as: lookup('users', 'administrator').tokens['web-app-matomo'] ``` +### Persist several tokens at once + +```yaml +- include_role: + name: sys-token-store + tasks_from: write_many.yml + vars: + sys_token_store_entries: + - user_key: administrator + app: web-app-matomo + token: "{{ matomo_token_value }}" + - user_key: no-reply + app: web-app-stalwart + token: "{{ stalwart_bot_secret }}" +``` + --- ## What This Role Does *Not* Do diff --git a/roles/sys-token-store/tasks/write.yml b/roles/sys-token-store/tasks/write.yml index 0dd70db756..fc51fe4ca0 100644 --- a/roles/sys-token-store/tasks/write.yml +++ b/roles/sys-token-store/tasks/write.yml @@ -4,73 +4,10 @@ # sys_token_store_app # sys_token_store_token # must be non-empty -- name: "✅ Ensure store exists" - ansible.builtin.import_tasks: 00_core.yml - -- name: "📐 Normalize incoming token" - ansible.builtin.set_fact: - sys_token_store_token_effective: "{{ sys_token_store_token | string | trim }}" - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - -- name: "🛑 Abort if token is empty (do not persist empties)" - ansible.builtin.assert: - that: - - sys_token_store_token_effective != '' - fail_msg: "sys_token_store_token is empty – refusing to persist empty token." - -- name: "🔨 Build merged structure" - ansible.builtin.set_fact: - sys_token_store_users_merged: >- - {{ - sys_token_store_users - | combine({ - sys_token_store_user_key: ( - sys_token_store_users.get(sys_token_store_user_key, {}) - | combine({ - 'tokens': ( - sys_token_store_users.get(sys_token_store_user_key, {}).get('tokens', {}) - | combine({ sys_token_store_app: sys_token_store_token_effective }) - ) - }, recursive=True - ) - ) - }, recursive=True - ) - }} - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - -- name: "💾 Write the token store when the merge changed it" - when: sys_token_store_users_merged != sys_token_store_users - block: - - name: "💾 Persist store (idempotent, single-writer via STACK_HOST)" - ansible.builtin.copy: - dest: "{{ FILE_TOKENS }}" - owner: "{{ SYS_TOKEN_STORE_OWNER }}" - group: "{{ SYS_TOKEN_STORE_GROUP }}" - mode: "{{ SYS_TOKEN_STORE_FILE_MODE }}" - content: "{{ {'users': sys_token_store_users_merged} | to_nice_yaml(indent=2, width=9999) }}" - delegate_to: "{{ STACK_HOST }}" - run_once: true - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - become: true - register: sys_token_store_persisted - - - 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: IS_SWARM_MODE - delegate_to: localhost # nocheck: localhost-become FILE_TOKENS sits below the root-owned DIR_SECRETS - run_once: true - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - register: sys_token_store_mirrored - - - name: "🔄 Hand the written store to the lookups of the rest of the play" - ansible.builtin.set_fact: - sys_token_store_users: "{{ sys_token_store_users_merged }}" - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - -- name: "🧊 Re-render the applications SPOT the new token invalidated" - applications_carrier: {} - when: sys_token_store_persisted is changed or sys_token_store_mirrored is changed +- name: "💾 Persist the token as a one-entry batch" + ansible.builtin.import_tasks: write_many.yml + vars: + sys_token_store_entries: + - user_key: "{{ sys_token_store_user_key }}" + app: "{{ sys_token_store_app }}" + token: "{{ sys_token_store_token }}" diff --git a/roles/sys-token-store/tasks/write_many.yml b/roles/sys-token-store/tasks/write_many.yml new file mode 100644 index 0000000000..2f2862ab65 --- /dev/null +++ b/roles/sys-token-store/tasks/write_many.yml @@ -0,0 +1,65 @@ +--- +# REQUIRED: +# sys_token_store_entries # list of {user_key, app, token}; every token must be non-empty + +- name: "✅ Ensure store exists" + ansible.builtin.import_tasks: 00_core.yml + +- name: "🛑 Abort if a token is empty (do not persist empties)" + ansible.builtin.assert: + that: + - sys_token_store_empty | length == 0 + fail_msg: "Refusing to persist the empty tokens of {{ sys_token_store_empty }}." + vars: + sys_token_store_empty: >- + {%- set empty = [] -%} + {%- for entry in sys_token_store_entries if (entry.token | string | trim) == '' -%} + {%- set _ = empty.append(entry.user_key ~ '/' ~ entry.app) -%} + {%- endfor -%} + {{ empty }} + +- name: "🔨 Build merged structure" + ansible.builtin.set_fact: + sys_token_store_users_merged: >- + {%- set layers = [] -%} + {%- for entry in sys_token_store_entries -%} + {%- set _ = layers.append({entry.user_key: {'tokens': {entry.app: entry.token | string | trim}}}) -%} + {%- endfor -%} + {{ sys_token_store_users | combine(layers, recursive=True) }} + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "💾 Write the token store when the merge changed it" + when: sys_token_store_users_merged != sys_token_store_users + block: + - name: "💾 Persist store (idempotent, single-writer via STACK_HOST)" + ansible.builtin.copy: + dest: "{{ FILE_TOKENS }}" + owner: "{{ SYS_TOKEN_STORE_OWNER }}" + group: "{{ SYS_TOKEN_STORE_GROUP }}" + mode: "{{ SYS_TOKEN_STORE_FILE_MODE }}" + content: "{{ {'users': sys_token_store_users_merged} | to_nice_yaml(indent=2, width=9999) }}" + delegate_to: "{{ STACK_HOST }}" + run_once: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + become: true + register: sys_token_store_persisted + + - 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: IS_SWARM_MODE + delegate_to: localhost # nocheck: localhost-become FILE_TOKENS sits below the root-owned DIR_SECRETS + run_once: true + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: sys_token_store_mirrored + + - name: "🔄 Hand the written store to the lookups of the rest of the play" + ansible.builtin.set_fact: + sys_token_store_users: "{{ sys_token_store_users_merged }}" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "🧊 Re-render the applications SPOT the new tokens invalidated" + applications_carrier: {} + when: sys_token_store_persisted is changed or sys_token_store_mirrored is changed diff --git a/roles/test-e2e-playwright/README.md b/roles/test-e2e-playwright/README.md index b840e563b3..8cf2deea67 100644 --- a/roles/test-e2e-playwright/README.md +++ b/roles/test-e2e-playwright/README.md @@ -68,7 +68,7 @@ For the file-level contract, use [Contributing `playwright.env.j2`](../../docs/a This role ships central Playwright defaults: -- `templates/package.json.j2`: `@playwright/test` version derived from `meta/services.yml.playwright.version` +- `templates/package.json.j2`: `@playwright/test` version derived from `meta/services.yml.playwright.version`, and `@axe-core/playwright` (WCAG checks through `AxeBuilder`) pinned by `meta/services.yml.playwright.axe_version` - `files/playwright.config.js`: shared Playwright configuration - `files/network-leak.spec.js`: guest persona and cross-network leak check, staged next to every role spec and skipped unless `PLAYWRIGHT_NETWORK_LEAK=true`, which the runner sets when the role is served on more than one network diff --git a/roles/test-e2e-playwright/meta/services.yml b/roles/test-e2e-playwright/meta/services.yml index b152ccb34d..b27c095e13 100644 --- a/roles/test-e2e-playwright/meta/services.yml +++ b/roles/test-e2e-playwright/meta/services.yml @@ -6,3 +6,8 @@ test-e2e-playwright: playwright: image: mcr.microsoft.com/playwright version: "v1.64.1-noble" + axe_version: 4.14.0 + update: + - key: axe_version + type: npm + package: "@axe-core/playwright" diff --git a/roles/test-e2e-playwright/tasks/01_setup.yml b/roles/test-e2e-playwright/tasks/01_setup.yml index 0a3d34651b..fc67383f36 100644 --- a/roles/test-e2e-playwright/tasks/01_setup.yml +++ b/roles/test-e2e-playwright/tasks/01_setup.yml @@ -20,6 +20,18 @@ become: false changed_when: false +- name: 📦 Pack the shared Playwright helpers for a single transfer per role + ansible.builtin.command: + argv: >- + {{ + ['tar', '-cf', TEST_E2E_PLAYWRIGHT_HELPERS_ARCHIVE, '-C', TEST_E2E_PLAYWRIGHT_HELPERS_DIR] + + (query('fileglob', TEST_E2E_PLAYWRIGHT_HELPERS_DIR ~ '/*.js') + | map('basename') | reject('equalto', 'playwright.config.js') | list) + }} + delegate_to: localhost + become: false + changed_when: false + - name: ✅ Ensure the shared personas dir exists ansible.builtin.file: path: "{{ TEST_E2E_PLAYWRIGHT_SHARED_PERSONAS }}" @@ -48,7 +60,7 @@ {{ (not _playwright_shared_stamp_stat.stat.exists) or ((_playwright_shared_stamp_content.content | default('') | b64decode | trim) - != TEST_E2E_PLAYWRIGHT_VERSION) + != TEST_E2E_PLAYWRIGHT_INSTALL_STAMP) }} - name: ⬇️ Pull the Playwright image once for every role of this run @@ -71,7 +83,7 @@ - name: 🔧 Provision the shared Playwright install (npm install + stamp) when: _playwright_shared_install_needed | bool block: - - name: 📦 Install @playwright/test into the shared dir (once per host per version) + - name: 📦 Install @playwright/test and @axe-core/playwright into the shared dir ansible.builtin.command: argv: - container @@ -98,5 +110,5 @@ - name: ✏️ Write shared install stamp ansible.builtin.copy: dest: "{{ TEST_E2E_PLAYWRIGHT_SHARED_STAMP }}" - content: "{{ TEST_E2E_PLAYWRIGHT_VERSION }}" + content: "{{ TEST_E2E_PLAYWRIGHT_INSTALL_STAMP }}" mode: "0644" diff --git a/roles/test-e2e-playwright/tasks/02_run_one.yml b/roles/test-e2e-playwright/tasks/02_run_one.yml index b45c78a9fb..4d85cdc6fb 100644 --- a/roles/test-e2e-playwright/tasks/02_run_one.yml +++ b/roles/test-e2e-playwright/tasks/02_run_one.yml @@ -6,6 +6,7 @@ _playwright_spec_src: "{{ lookup('path_absolute', 'roles', application_id, 'files/playwright/playwright.spec.js') }}" _playwright_stage_dir: "{{ TEST_E2E_PLAYWRIGHT_STAGE_BASE_DIR }}/{{ application_id }}" _playwright_stage_tests_dir: "{{ TEST_E2E_PLAYWRIGHT_STAGE_BASE_DIR }}/{{ application_id }}/tests" + _playwright_tree_archive: "/tmp/infinito-playwright-{{ application_id }}.tar" _playwright_reports_dir: "{{ TEST_E2E_PLAYWRIGHT_REPORTS_BASE_DIR }}/{{ application_id }}" _playwright_default_package_template: "{{ lookup('path_absolute', 'roles/test-e2e-playwright/templates/package.json.j2') }}" _playwright_default_config_js: "{{ lookup('path_absolute', 'roles/test-e2e-playwright/files/playwright.config.js') }}" @@ -143,21 +144,23 @@ dest: "{{ _playwright_stage_dir }}/playwright.config.js" mode: "0644" -- name: 📋 Copy Playwright tree (spec + companions + addons/ + fixtures/) to staging - ansible.builtin.copy: - src: "{{ _playwright_files_dir }}/" - dest: "{{ _playwright_stage_tests_dir }}/" - mode: "0644" - directory_mode: "0755" +- name: 📦 Pack the role's Playwright tree for a single transfer + ansible.builtin.command: + argv: [tar, -cf, "{{ _playwright_tree_archive }}", -C, "{{ _playwright_files_dir }}", .] + delegate_to: localhost + become: false + changed_when: false -- name: 📋 Copy shared Playwright helpers into staging tests directory - ansible.builtin.copy: - src: "{{ item }}" - dest: "{{ _playwright_stage_tests_dir }}/{{ item | basename }}" - mode: "0644" - when: (item | basename) != 'playwright.config.js' - with_fileglob: - - "{{ lookup('path_absolute', 'roles/test-e2e-playwright/files') }}/*.js" +- name: 📋 Stage the Playwright tree and the shared helpers + ansible.builtin.unarchive: + src: "{{ playwright_archive }}" + dest: "{{ _playwright_stage_tests_dir }}/" + extra_opts: [--no-same-owner] + loop: + - "{{ _playwright_tree_archive }}" + - "{{ TEST_E2E_PLAYWRIGHT_HELPERS_ARCHIVE }}" + loop_control: + loop_var: playwright_archive - name: ✅ Ensure staging volume directory exists ansible.builtin.file: diff --git a/roles/test-e2e-playwright/templates/package.json.j2 b/roles/test-e2e-playwright/templates/package.json.j2 index b420bb03ea..3ffbacf5ab 100644 --- a/roles/test-e2e-playwright/templates/package.json.j2 +++ b/roles/test-e2e-playwright/templates/package.json.j2 @@ -5,6 +5,7 @@ "test": "playwright test" }, "devDependencies": { + "@axe-core/playwright": "{{ TEST_E2E_PLAYWRIGHT_AXE_VERSION }}", "@playwright/test": "{{ TEST_E2E_PLAYWRIGHT_VERSION }}" } } diff --git a/roles/test-e2e-playwright/vars/main.yml b/roles/test-e2e-playwright/vars/main.yml index 0abfd65243..0c254f659d 100644 --- a/roles/test-e2e-playwright/vars/main.yml +++ b/roles/test-e2e-playwright/vars/main.yml @@ -2,6 +2,8 @@ TEST_E2E_PLAYWRIGHT_IMAGE: "{{ lookup('config', 'test-e2e-playwright', 'services.playwright.image') }}:{{ lookup('config', 'test-e2e-playwright', 'services.playwright.version') }}" TEST_E2E_PLAYWRIGHT_VERSION: "{{ lookup('config', 'test-e2e-playwright', 'services.playwright.version') | image_version }}" +TEST_E2E_PLAYWRIGHT_AXE_VERSION: "{{ lookup('config', 'test-e2e-playwright', 'services.playwright.axe_version') }}" +TEST_E2E_PLAYWRIGHT_INSTALL_STAMP: "{{ TEST_E2E_PLAYWRIGHT_VERSION }} axe-{{ TEST_E2E_PLAYWRIGHT_AXE_VERSION }}" TEST_E2E_PLAYWRIGHT_STAGE_BASE_DIR: "/tmp/test-e2e-playwright" @@ -24,6 +26,8 @@ TEST_E2E_PLAYWRIGHT_SHARED_DIR: "{{ TEST_E2E_PLAYWRIGHT_STAGE_BASE_DIR }}/_share TEST_E2E_PLAYWRIGHT_SHARED_NODE_MODULES: "{{ TEST_E2E_PLAYWRIGHT_SHARED_DIR }}/node_modules" TEST_E2E_PLAYWRIGHT_SHARED_PERSONAS: "{{ TEST_E2E_PLAYWRIGHT_SHARED_DIR }}/personas" TEST_E2E_PLAYWRIGHT_PERSONAS_ARCHIVE: "/tmp/infinito-playwright-personas.tar" +TEST_E2E_PLAYWRIGHT_HELPERS_DIR: "{{ lookup('path_absolute', 'roles/test-e2e-playwright/files') }}" +TEST_E2E_PLAYWRIGHT_HELPERS_ARCHIVE: "/tmp/infinito-playwright-helpers.tar" TEST_E2E_PLAYWRIGHT_SHARED_STAMP: "{{ TEST_E2E_PLAYWRIGHT_SHARED_DIR }}/.installed-version" TEST_E2E_PLAYWRIGHT_IS_ONION: "{{ (_playwright_pass_domain | network_of) == 'tor' }}" diff --git a/roles/user-administrator/tasks/00_core.yml b/roles/user-administrator/tasks/00_core.yml index ea1087ea90..eda788307e 100644 --- a/roles/user-administrator/tasks/00_core.yml +++ b/roles/user-administrator/tasks/00_core.yml @@ -10,13 +10,18 @@ name: sys-sudo when: run_once_sys_sudo is not defined +- name: "🔎 Check whether {{ USER_ADMINISTRATOR_NAME }} already holds an SSH key" + ansible.builtin.stat: + path: "{{ DIR_HOME_ADMINISTRATOR }}.ssh/id_rsa" + register: user_administrator_ssh_key + - name: "📁 create {{ USER_ADMINISTRATOR_NAME }}" user: name: "{{ USER_ADMINISTRATOR_NAME }}" update_password: on_create password: "{{ lookup('users', USER_ADMINISTRATOR_NAME).password | password_hash('sha512') }}" create_home: true - generate_ssh_key: true + generate_ssh_key: "{{ not user_administrator_ssh_key.stat.exists }}" ssh_key_type: rsa ssh_key_bits: 8192 no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/user-backup/meta/packages.yml b/roles/user-backup/meta/packages.yml index 41f7ad032a..f240de6bf7 100644 --- a/roles/user-backup/meta/packages.yml +++ b/roles/user-backup/meta/packages.yml @@ -6,3 +6,4 @@ acl: - acl RedHat: - acl + batch: false diff --git a/roles/user-backup/tasks/02_permissions_folders.yml b/roles/user-backup/tasks/02_permissions_folders.yml index 0e6a6c1c74..bd4bb0d16e 100644 --- a/roles/user-backup/tasks/02_permissions_folders.yml +++ b/roles/user-backup/tasks/02_permissions_folders.yml @@ -1,6 +1,6 @@ --- - name: 📦 Install ACL utilities - package_install: + package_install: # nocheck: package-install only the permissions step this file is included for needs setfacl id: acl - name: ✅ Ensure backups root exists and owned by backup diff --git a/roles/web-app-akaunting/tasks/01_setup.yml b/roles/web-app-akaunting/tasks/01_setup.yml index 8fb187c597..c96d7c0640 100644 --- a/roles/web-app-akaunting/tasks/01_setup.yml +++ b/roles/web-app-akaunting/tasks/01_setup.yml @@ -24,6 +24,8 @@ path: "{{ AKAUNTING_SETUP_MARKER }}" state: touch mode: "0644" + modification_time: preserve + access_time: preserve - 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') }}" diff --git a/roles/web-app-akaunting/tasks/setup/swarm.yml b/roles/web-app-akaunting/tasks/setup/swarm.yml index 48fe1ab334..c7531fa02b 100644 --- a/roles/web-app-akaunting/tasks/setup/swarm.yml +++ b/roles/web-app-akaunting/tasks/setup/swarm.yml @@ -16,6 +16,15 @@ delay: 5 until: akaunting_swarm_drained.rc == 0 +# Exception: the service runs the image built from the akaunting/docker repository, whose code lands in the shared volume; the upstream tag carries an older PHP that cannot run that code. +- name: "🔍 Akaunting setup | Read the image the akaunting service runs" + ansible.builtin.command: >- + container service inspect {{ AKAUNTING_SERVICE }} + --format {{ '{{.Spec.TaskTemplate.ContainerSpec.Image}}' }} + register: akaunting_service_image + changed_when: false + failed_when: akaunting_service_image.rc != 0 or (akaunting_service_image.stdout | trim | length == 0) + - name: "▶️ Akaunting setup | Run one-shot install" ansible.builtin.shell: | set -euo pipefail @@ -28,7 +37,7 @@ --mount type=volume,source={{ AKAUNTING_VOLUME | quote }},target={{ lookup('volume', 'web-app-akaunting', 'data').target }} \ --network {{ application_id | entity_name | quote }} \ {% if lookup('database', application_id, 'shared') | bool %}--network {{ lookup('database', application_id, 'network') | quote }} {% endif %}\ - {{ AKAUNTING_IMAGE }}:{{ AKAUNTING_VERSION }} \ + {{ akaunting_service_image.stdout | trim | quote }} \ {{ AKAUNTING_ENTRYPOINT }} changed_when: true diff --git a/roles/web-app-akaunting/vars/main.yml b/roles/web-app-akaunting/vars/main.yml index 36e30f9256..769e00d2d7 100644 --- a/roles/web-app-akaunting/vars/main.yml +++ b/roles/web-app-akaunting/vars/main.yml @@ -4,8 +4,6 @@ application_id: "web-app-akaunting" database_password: "{{ lookup('config', application_id, 'secrets.credentials.database_password') }}" # nocheck: lookup-config-path 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', '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') }}" diff --git a/roles/web-app-baserow/vars/main.yml b/roles/web-app-baserow/vars/main.yml index 1bd3573d1d..b3dad2e36f 100644 --- a/roles/web-app-baserow/vars/main.yml +++ b/roles/web-app-baserow/vars/main.yml @@ -3,7 +3,7 @@ application_id: "web-app-baserow" entity_name: "{{ application_id | entity_name }}" database_password: "{{ lookup('config', application_id, 'secrets.credentials.database_password') }}" # nocheck: lookup-config-path -BASEROW_PUBLIC_URL: "{{ lookup('tls', application_id, 'url.base') | regex_replace('/+$', '') }}" +BASEROW_PUBLIC_URL: "{{ lookup('tls', application_id, 'url.origin') }}" BASEROW_VERSION: "{{ lookup('config', application_id, 'services.baserow.version') }}" BASEROW_IMAGE: "{{ lookup('config', application_id, 'services.baserow.image') }}" BASEROW_CONTAINER: "{{ lookup('config', application_id, 'services.baserow.name') }}" diff --git a/roles/web-app-checkmk/templates/proxy.conf.j2 b/roles/web-app-checkmk/templates/proxy.conf.j2 index 92e9ac9241..cdb3284131 100644 --- a/roles/web-app-checkmk/templates/proxy.conf.j2 +++ b/roles/web-app-checkmk/templates/proxy.conf.j2 @@ -14,20 +14,13 @@ server {% include 'roles/sys-front-tls/templates/nginx_ssl_header.j2' %} - {% if lookup('sso', application_id, 'is_proxy_gated') %} - {% set sso_proxy_enabled = true %} - {% set webserver_location_extra_configuration %} + {% set sso_gated_location_extra_configuration %} proxy_set_header X-Remote-User "${authrequest_username}"; - {% endset %} - {% set location = '/' %} - {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} - {% set webserver_location_extra_configuration = '' %} - {% else %} - {% set sso_proxy_enabled = false %} - {% set webserver_location_extra_configuration = '' %} - {% set location = '/' %} - {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} - {% endif %} + {% endset %} + {% set sso_open_location_extra_configuration %} + proxy_set_header X-Remote-User ""; + {% endset %} + {% include 'roles/sys-svc-proxy/templates/location/sso_acl.conf.j2' %} {% include 'roles/web-app-prometheus/templates/nginx/locations.conf.j2' %} diff --git a/roles/web-app-dashboard/templates/javascript/oidc.js.j2 b/roles/web-app-dashboard/templates/javascript/oidc.js.j2 index a7b44ee780..bcf54dd766 100644 --- a/roles/web-app-dashboard/templates/javascript/oidc.js.j2 +++ b/roles/web-app-dashboard/templates/javascript/oidc.js.j2 @@ -12,11 +12,11 @@ const KC_CONFIG = { realm: "{{ OIDC.CLIENT.REALM }}", // e.g. cymais.cloud clientId: "{{ OIDC.CLIENT.ID }}", // e.g. cymais.cloud redirectUri: "{{ DASHBOARD_APP_BASE_URL }}", // canonical app URL for login/logout round-trips - silentCheckSsoRedirectUri: "{{ (DASHBOARD_APP_BASE_URL | regex_replace('/+$', '')) ~ DASHBOARD_LOCATION_SILENT_CHECK }}" + silentCheckSsoRedirectUri: "{{ lookup('tls', DASHBOARD_APPLICATION_ID, 'url.origin') ~ DASHBOARD_LOCATION_SILENT_CHECK }}" }; {% if (lookup('config', application_id, 'services.tor.enabled', False) | bool) and (domain | network_of) == 'tor' %} -const KC_MIRROR_BASE = "{{ lookup('tls', 'web-svc-mirror', 'url.base') | regex_replace('/+$', '') }}"; +const KC_MIRROR_BASE = "{{ lookup('tls', 'web-svc-mirror', 'url.origin') }}"; {% else %} const KC_MIRROR_BASE = null; {% endif %} diff --git a/roles/web-app-dashboard/vars/main.yml b/roles/web-app-dashboard/vars/main.yml index a365f718ca..7e7828c2ea 100644 --- a/roles/web-app-dashboard/vars/main.yml +++ b/roles/web-app-dashboard/vars/main.yml @@ -18,13 +18,12 @@ DASHBOARD_SIMPLEICONS_PROBE_URLS: >- | map('regex_replace', '^', DASHBOARD_SIMPLEICONS_SYNC_URL_BASE) | map('regex_replace', '$', '.svg'))) }} -DASHBOARD_JS_CDN_URL: "{{ lookup('tls', 'web-svc-cdn', 'url.base') }}" DASHBOARD_JS_FILES: >- {{ ['iframe.js'] + (['oidc.js'] if (DASHBOARD_OIDC_ENABLED | bool) else []) }} DASHBOARD_JS_BASE_PATH: "{{ DASHBOARD_APPLICATION_ID | entity_name }}/{{ 'js' | labelled(DASHBOARD_NETWORK_LABEL, '-') }}" DASHBOARD_JS_SERVER_DIR: "{{ [ lookup('nginx','directories.data.cdn'), DASHBOARD_JS_BASE_PATH ] | path_join }}" -DASHBOARD_JS_BASE_URL: "{{ (DASHBOARD_JS_CDN_URL | trim('/')) ~ '/' ~ (DASHBOARD_JS_BASE_PATH | trim('/')) }}" +DASHBOARD_JS_BASE_URL: "{{ lookup('tls', 'web-svc-cdn', 'url.origin') ~ '/' ~ (DASHBOARD_JS_BASE_PATH | trim('/')) }}" DASHBOARD_LOCATION_SILENT_CHECK: "/silent-check-sso.html" @@ -36,7 +35,7 @@ DASHBOARD_I18N_CONTENT_DIR: "{{ [ lookup('container', DASHBOARD_APPLICATION_ID, DASHBOARD_IMAGE: "{{ lookup('config', DASHBOARD_APPLICATION_ID, 'services.dashboard.image') }}" DASHBOARD_VERSION: "{{ lookup('config', DASHBOARD_APPLICATION_ID, 'services.dashboard.version') }}" -DASHBOARD_APP_BASE_URL: "{{ lookup('tls', DASHBOARD_APPLICATION_ID, 'url.base') | regex_replace('/+$', '') }}/" +DASHBOARD_APP_BASE_URL: "{{ lookup('tls', DASHBOARD_APPLICATION_ID, 'url.base') }}" DASHBOARD_KEYCLOAK_LOGIN_URL: >- {{ OIDC.CLIENT.AUTHORIZE_URL ~ '?client_id=' ~ OIDC.CLIENT.ID diff --git a/roles/web-app-decidim/templates/playwright.env.j2 b/roles/web-app-decidim/templates/playwright.env.j2 index b611a7f0c2..dee18e647c 100644 --- a/roles/web-app-decidim/templates/playwright.env.j2 +++ b/roles/web-app-decidim/templates/playwright.env.j2 @@ -2,7 +2,7 @@ ADMIN_EMAIL={{ lookup('users', 'platform_administrator').email | dotenv_quote }} ADMIN_PASSWORD={{ lookup('users', 'platform_administrator').password | dotenv_quote }} -APP_BASE_URL={{ lookup('tls', application_id, 'url.base') | regex_replace('/+$', '') | dotenv_quote }} +APP_BASE_URL={{ lookup('tls', application_id, 'url.origin') | dotenv_quote }} BIBER_EMAIL={{ lookup('users', 'biber').email | dotenv_quote }} @@ -12,7 +12,7 @@ BIBER_USERNAME={{ lookup('users', 'biber').username | dotenv_quote }} CANONICAL_DOMAIN={{ lookup('domain', application_id) | dotenv_quote }} -DECIDIM_BASE_URL={{ lookup('tls', application_id, 'url.base') | regex_replace('/+$', '') | dotenv_quote }} +DECIDIM_BASE_URL={{ lookup('tls', application_id, 'url.origin') | dotenv_quote }} DESIGN_LOGO_ENABLED={{ DECIDIM_DESIGN_LOGO_ENABLED | string | lower }} diff --git a/roles/web-app-discourse/meta/services.yml b/roles/web-app-discourse/meta/services.yml index ae49f9b908..a8f46da76a 100644 --- a/roles/web-app-discourse/meta/services.yml +++ b/roles/web-app-discourse/meta/services.yml @@ -71,7 +71,7 @@ discourse: repository: https://github.com/discourse/discourse_docker.git application: repository: https://github.com/discourse/discourse.git - ref: v2026.9.1 + ref: v2026.10.0 ports: local: http: 8020 diff --git a/roles/web-app-discourse/tasks/02_docker.yml b/roles/web-app-discourse/tasks/02_docker.yml index acb7801e9a..c6cbe7a537 100644 --- a/roles/web-app-discourse/tasks/02_docker.yml +++ b/roles/web-app-discourse/tasks/02_docker.yml @@ -1,8 +1,4 @@ --- -- name: 📦 install which - package_install: - id: which - - name: "🧩 load docker, db and proxy for {{ application_id }}" include_role: name: sys-stk-full diff --git a/roles/web-app-discourse/templates/ai_gateway/register.rb.j2 b/roles/web-app-discourse/templates/ai_gateway/register.rb.j2 index b059ab8437..e815ee0141 100644 --- a/roles/web-app-discourse/templates/ai_gateway/register.rb.j2 +++ b/roles/web-app-discourse/templates/ai_gateway/register.rb.j2 @@ -15,4 +15,3 @@ SiteSetting.ai_helper_enabled = true SiteSetting.ai_summarization_enabled = true SiteSetting.ai_bot_enabled = true SiteSetting.ai_bot_enabled_llms = llm.id.to_s -llm.reload.toggle_companion_user diff --git a/roles/web-app-erpnext/meta/services.yml b/roles/web-app-erpnext/meta/services.yml index 7a2178be9a..d5b6a3b5e4 100644 --- a/roles/web-app-erpnext/meta/services.yml +++ b/roles/web-app-erpnext/meta/services.yml @@ -68,7 +68,7 @@ erpnext: enabled: true shared: true image: frappe/erpnext - version: "v16.52.1" + version: "v16.53.0" name: erpnext min_storage: 1017MB ports: diff --git a/roles/web-app-erpnext/templates/compose.yml.j2 b/roles/web-app-erpnext/templates/compose.yml.j2 index 3edb77576a..2015935cac 100644 --- a/roles/web-app-erpnext/templates/compose.yml.j2 +++ b/roles/web-app-erpnext/templates/compose.yml.j2 @@ -89,7 +89,7 @@ bench set-config -g redis_queue "{{ ERPNEXT_REDIS_URL }}/1"; bench set-config -g redis_socketio "{{ ERPNEXT_REDIS_URL }}/2"; bench set-config -gp socketio_port {{ ERPNEXT_WEBSOCKET_PORT }}; - bench set-config -g host_name "{{ lookup('tls', application_id, 'url.base') | regex_replace('/+$', '') }}"; + bench set-config -g host_name "{{ lookup('tls', application_id, 'url.origin') }}"; {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_depends_on', application_id) | indent(4) }} {{ lookup('container_extra_hosts') | indent(4) }} diff --git a/roles/web-app-friendica/vars/main.yml b/roles/web-app-friendica/vars/main.yml index 8271924254..6f2ecfffaf 100644 --- a/roles/web-app-friendica/vars/main.yml +++ b/roles/web-app-friendica/vars/main.yml @@ -8,7 +8,7 @@ FRIENDICA_IMAGE: "{{ lookup('config', application_id, 'services.' ~ FRIENDICA_SE FRIENDICA_VERSION: "{{ lookup('config', application_id, 'services.' ~ FRIENDICA_SERVICE ~ '.version') }}" FRIENDICA_INIT_GATE_FILE: "friendica-init-gate.sh" FRIENDICA_INIT_GATE_HOST: "{{ [lookup('container', application_id, 'directories.instance'), FRIENDICA_INIT_GATE_FILE] | path_join }}" -FRIENDICA_BASE_URL: "{{ lookup('tls', application_id, 'url.base') | regex_replace('/+$', '') }}" +FRIENDICA_BASE_URL: "{{ lookup('tls', application_id, 'url.origin') }}" FRIENDICA_APPLICATION_DIR: "{{ lookup('volume', 'web-app-friendica', 'html').target }}" FRIENDICA_CONFIG_DIR: "{{ [ FRIENDICA_APPLICATION_DIR, 'config' ] | path_join }}" diff --git a/roles/web-app-funkwhale/templates/compose.yml.j2 b/roles/web-app-funkwhale/templates/compose.yml.j2 index 30352d3871..2ad494bb4f 100644 --- a/roles/web-app-funkwhale/templates/compose.yml.j2 +++ b/roles/web-app-funkwhale/templates/compose.yml.j2 @@ -56,7 +56,9 @@ {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {{ lookup('container_image', application_id, 'typesense') }} {{ lookup('container_volumes', service_name) | indent(4) }} - command: --data-dir /data --enable-cors --api-key {{ FUNKWHALE_TYPESENSE_API_KEY }} + command: --data-dir /data --enable-cors + environment: # nocheck: compose-environment-from-env-file typesense-only key kept out of argv; the role's single env.j2 is also the env_file of api, celeryworker, celerybeat and migrate, which must not receive it + TYPESENSE_API_KEY: "{{ FUNKWHALE_TYPESENSE_API_KEY }}" {% if IS_COMPOSE_MODE %} profiles: - typesense diff --git a/roles/web-app-fusiondirectory/vars/main.yml b/roles/web-app-fusiondirectory/vars/main.yml index f7c3ef2a8a..74273f13b9 100644 --- a/roles/web-app-fusiondirectory/vars/main.yml +++ b/roles/web-app-fusiondirectory/vars/main.yml @@ -3,7 +3,7 @@ application_id: web-app-fusiondirectory entity_name: "{{ application_id | entity_name }}" FUSIONDIRECTORY_CONTAINER: "{{ lookup('config', application_id, 'services.fusiondirectory.name') }}" -FUSIONDIRECTORY_URL: "{{ lookup('tls', application_id, 'url.base') | regex_replace('/+$', '') }}" +FUSIONDIRECTORY_URL: "{{ lookup('tls', application_id, 'url.origin') }}" FUSIONDIRECTORY_DESIGN_ENABLED: "{{ lookup('config', application_id, 'services.design.enabled') }}" FUSIONDIRECTORY_THEME_CSS_HOST: "{{ [lookup('container', application_id, 'directories.volumes'), 'theme.css'] | path_join }}" FUSIONDIRECTORY_DESIGN_TITLE: "{{ lookup('design', application_id).title if (FUSIONDIRECTORY_DESIGN_ENABLED | bool and lookup('design', application_id).title is string) diff --git a/roles/web-app-gitlab/meta/addons/jira.yml b/roles/web-app-gitlab/meta/addons/jira.yml index 55720897d8..423e6c9f75 100644 --- a/roles/web-app-gitlab/meta/addons/jira.yml +++ b/roles/web-app-gitlab/meta/addons/jira.yml @@ -6,4 +6,4 @@ source: bundled bridges: - jira config: - url: "{{ lookup('tls', 'web-app-jira', 'url.base') }}" + url: "{{ lookup('tls', 'web-app-jira', 'url.origin') }}" diff --git a/roles/web-app-gitlab/vars/main.yml b/roles/web-app-gitlab/vars/main.yml index 1375e4b14b..d1de381261 100644 --- a/roles/web-app-gitlab/vars/main.yml +++ b/roles/web-app-gitlab/vars/main.yml @@ -4,7 +4,6 @@ entity_name: "{{ application_id | entity_name }}" swarm_stack_converge_retries: 600 -GITLAB_URL: "{{ lookup('tls', application_id, 'url.base') }}" GITLAB_HOSTNAME: "{{ lookup('container_hostname', application_id) }}" GITLAB_TLS_ENABLED: "{{ lookup('tls', application_id, 'enabled') | bool }}" GITLAB_WEB_PORT: "{{ lookup('tls', application_id, 'ports.web') }}" diff --git a/roles/web-app-jenkins/meta/services.yml b/roles/web-app-jenkins/meta/services.yml index df1a6b3807..377c25fe1a 100644 --- a/roles/web-app-jenkins/meta/services.yml +++ b/roles/web-app-jenkins/meta/services.yml @@ -63,7 +63,7 @@ jenkins: # nocheck: single-replica replicas: 1 image: jenkins/jenkins - version: 2.580.1-lts + version: 2.580.2-lts custom: true name: jenkins ports: diff --git a/roles/web-app-jenkins/templates/casc.yaml.j2 b/roles/web-app-jenkins/templates/casc.yaml.j2 index 4ed79d0c6a..12f7a35ca4 100644 --- a/roles/web-app-jenkins/templates/casc.yaml.j2 +++ b/roles/web-app-jenkins/templates/casc.yaml.j2 @@ -54,4 +54,4 @@ jenkins: - group: "authenticated" unclassified: location: - url: "{{ lookup('tls', application_id, 'url.base') | regex_replace('/+$', '') }}/" + url: "{{ lookup('tls', application_id, 'url.base') }}" diff --git a/roles/web-app-joomla/meta/addons/plg_system_keycloak.yml b/roles/web-app-joomla/meta/addons/plg_system_keycloak.yml index 217db5e036..803b04af25 100644 --- a/roles/web-app-joomla/meta/addons/plg_system_keycloak.yml +++ b/roles/web-app-joomla/meta/addons/plg_system_keycloak.yml @@ -11,7 +11,7 @@ config: issuer_url: "{{ OIDC.CLIENT.ISSUER_URL }}" client_id: "{{ OIDC.CLIENT.ID }}" client_secret: "{{ OIDC.CLIENT.SECRET }}" - redirect_uri: "{{ lookup('tls', 'web-app-joomla', 'url.base') }}/index.php?option=keycloak&task=callback" + redirect_uri: "{{ lookup('tls', 'web-app-joomla', 'url.base') }}index.php?option=keycloak&task=callback" end_session_url: "{{ OIDC.CLIENT.LOGOUT_URL }}" fallback_enabled: "{{ lookup('config', 'web-app-joomla', 'services.sso.oidc.fallback_enabled') | string | lower }}" group_admin: "/{{ lookup('rbac_group_path', application_id='web-app-joomla', role='administrator') }}" diff --git a/roles/web-app-keycloak/files/python/keycloak_admin.py b/roles/web-app-keycloak/files/python/keycloak_admin.py index 5966d048f1..ada56f3150 100644 --- a/roles/web-app-keycloak/files/python/keycloak_admin.py +++ b/roles/web-app-keycloak/files/python/keycloak_admin.py @@ -3,7 +3,7 @@ Exports: KeycloakError: an HTTP error status, naming method, path and status but never the body. container_credentials: the permanent admin read from ``/proc//environ`` of the Keycloak container. - Keycloak: client whose ``call`` paths are relative to ``/admin/realms//``. + Keycloak: client whose ``call`` paths are relative to ``/admin/realms//`` and ``admin`` paths to ``/admin/realms/``. ADMIN_ENV_KEYS: container environment keys of the permanent admin user and password. PAGE: page size of every paged listing. TOKEN_MARGIN: seconds before expiry at which the master realm token is renewed. @@ -96,9 +96,22 @@ class Keycloak: payload: JSON body, or None for none. timeout: seconds the request may take. """ + return self.admin(method, f"{self.realm}/{path}", payload, timeout) + + def admin( + self, method: str, path: str, payload: object = None, timeout: int = 60 + ) -> tuple[object, str]: + """Return the decoded body and the id the ``Location`` header names. + + Args: + method: HTTP method. + path: path below ``/admin/realms/``, starting with a realm name. + payload: JSON body, or None for none. + timeout: seconds the request may take. + """ data = b"" if payload is None else json.dumps(payload).encode() request = urllib.request.Request( # noqa: S310 fixed local Keycloak origin - f"{self.url}/admin/realms/{self.realm}/{path}", + f"{self.url}/admin/realms/{path}", data=data if method in ("POST", "PUT") else None, headers={ "Authorization": self._bearer(), diff --git a/roles/web-app-keycloak/files/python/realm_settings.py b/roles/web-app-keycloak/files/python/realm_settings.py new file mode 100755 index 0000000000..64b0c0d69a --- /dev/null +++ b/roles/web-app-keycloak/files/python/realm_settings.py @@ -0,0 +1,264 @@ +#!/usr/bin/env python3 +"""Converge Keycloak client scopes, clients and realm settings over the admin REST API. + +Env: + KC_URL: Keycloak base URL reachable from the network namespace the script runs in. + KC_PID: host PID of the Keycloak container, whose environment holds the admin credentials. + KC_REALM: realm holding the client scopes and clients. + +Stdin: JSON object with + clientScopes: client scopes the realm gets when it has none of that name. + clients: clients created when absent, updated when they drifted, their scope lists converged. + realms: ``{"realm": , "desired": }`` objects deep-merged into their realm. + +Output: one `` `` line per object, then one ``summary`` line. +Exit: 0 every object converged, 1 otherwise. +""" + +from __future__ import annotations + +import json +import os +import sys +import urllib.parse +from copy import deepcopy +from pathlib import Path + +from keycloak_admin import Keycloak, KeycloakError, container_credentials + +OUTCOMES = ("created", "updated", "unchanged", "failed") +SCOPE_LISTS = ( + ("defaultClientScopes", "default-client-scopes"), + ("optionalClientScopes", "optional-client-scopes"), +) +CLIENT_KEYS = ("id", "clientId") +EMPTY = (None, "", [], {}) +ERRORS = (KeycloakError, OSError, KeyError, TypeError, ValueError) + + +class RefusalError(Exception): + pass + + +def deep_merge(base: dict, overlay: dict) -> dict: + """Return ``base`` with ``overlay`` merged in: nested dicts merge, every other value is replaced. + + Args: + base: the object as Keycloak holds it. + overlay: the values to set. + """ + merged = deepcopy(base) + for key, value in overlay.items(): + if isinstance(merged.get(key), dict) and isinstance(value, dict): + merged[key] = deep_merge(merged[key], value) + else: + merged[key] = deepcopy(value) + return merged + + +def matches(desired: object, current: object) -> bool: + """True when writing ``desired`` leaves ``current`` as Keycloak shows it. + + Args: + desired: value to write. An empty value matches a key Keycloak omits. + current: value Keycloak returned. Dict keys ``desired`` lacks are ignored, list order is not compared. + """ + if isinstance(desired, dict): + return isinstance(current, dict) and all( + matches(value, current[key]) if key in current else value in EMPTY + for key, value in desired.items() + ) + if isinstance(desired, list): + if not isinstance(current, list) or len(desired) != len(current): + return False + remaining = list(current) + for item in desired: + index = next( + (i for i, have in enumerate(remaining) if matches(item, have)), -1 + ) + if index < 0: + return False + del remaining[index] + return True + return desired == current + + +def comparable(client: dict) -> dict: + """Return the client fields a client PUT writes and Keycloak shows back. + + Args: + client: client representation. Keycloak never shows the secret of a public or + bearer-only client, and a client PUT ignores the scope lists. + """ + hidden = {field for field, _ in SCOPE_LISTS} + if client.get("publicClient") or client.get("bearerOnly"): + hidden.add("secret") + return {key: value for key, value in client.items() if key not in hidden} + + +def find_client(kc: Keycloak, client_id: str) -> dict | None: + """Return the client whose clientId equals ``client_id``, or None. + + Args: + kc: client. + client_id: the clientId. + """ + query = urllib.parse.urlencode({"clientId": client_id, "search": "false"}) + found, _ = kc.call("GET", f"clients?{query}") + return next((c for c in found if c["clientId"] == client_id), None) + + +def create_scope(kc: Keycloak, scope: dict, catalog: dict[str, str]) -> str: + """Return ``created`` or ``unchanged`` for a client scope; existing scopes stay as they are. + + Args: + kc: client. + scope: client scope representation. + catalog: client scope ids by name, extended by the created scope. + """ + if scope["name"] in catalog: + return "unchanged" + _, scope_id = kc.call("POST", "client-scopes", scope) + if not scope_id: + raise KeycloakError("created client scope carries no id") + catalog[scope["name"]] = scope_id + return "created" + + +def converge_scope_lists( + kc: Keycloak, client_id: str, desired: dict, catalog: dict[str, str] +) -> bool: + """Unassign and assign client scopes until the client's scope lists equal the desired ones. + + Args: + kc: client. + client_id: id of the client. + desired: client representation naming the wanted scopes. + catalog: client scope ids by name. + + Returns: + True when a scope was unassigned or assigned. + """ + plans = [] + for field, kind in SCOPE_LISTS: + if field in desired: + found, _ = kc.call("GET", f"clients/{client_id}/{kind}") + current = {scope["name"]: scope["id"] for scope in found} + plans.append((kind, set(desired[field]), current)) + unknown = sorted( + name + for _, wanted, current in plans + for name in wanted - set(current) + if name not in catalog + ) + if unknown: + raise RefusalError(f"client scopes missing in the realm: {', '.join(unknown)}") + changed = False + for kind, wanted, current in plans: + for name in sorted(set(current) - wanted): + kc.call("DELETE", f"clients/{client_id}/{kind}/{current[name]}") + changed = True + for kind, wanted, current in plans: + for name in sorted(wanted - set(current)): + kc.call("PUT", f"clients/{client_id}/{kind}/{catalog[name]}") + changed = True + return changed + + +def converge_client( + kc: Keycloak, desired: dict, existing: dict | None, catalog: dict[str, str] +) -> str: + """Return ``created``, ``updated`` or ``unchanged`` for a client. + + Args: + kc: client. + desired: client representation from the realm dictionary. + existing: the client as Keycloak holds it, or None when it is absent. + catalog: client scope ids by name. + """ + if existing is None: + try: + kc.call("POST", "clients", desired) + except KeycloakError: + existing = find_client(kc, desired["clientId"]) + if existing is None: + raise + else: + return "created" + merged = { + **deep_merge(existing, desired), + **{key: existing[key] for key in CLIENT_KEYS}, + } + written = not matches(comparable(merged), comparable(existing)) + if written: + kc.call("PUT", f"clients/{existing['id']}", merged) + scopes_changed = converge_scope_lists(kc, existing["id"], desired, catalog) + return "updated" if written or scopes_changed else "unchanged" + + +def converge_realm(kc: Keycloak, realm: str, desired: dict) -> str: + """Return ``updated`` or ``unchanged`` for a realm. + + Args: + kc: client. + realm: realm name. + desired: realm fields deep-merged into the realm. Secrets Keycloak masks never + match, so a desired secret is written on every run. + """ + path = urllib.parse.quote(realm, safe="") + current, _ = kc.admin("GET", path) + merged = deep_merge(current, desired) + if matches(merged, current): + return "unchanged" + kc.admin("PUT", path, merged) + return "updated" + + +def main() -> int: + env = os.environ + try: + kc = Keycloak( + env["KC_URL"], + env["KC_REALM"], + *container_credentials(Path("/proc") / env["KC_PID"] / "environ"), + ) + spec = json.load(sys.stdin) + wanted_scopes, wanted_clients, wanted_realms = ( + spec["clientScopes"], + spec["clients"], + spec["realms"], + ) + scopes, _ = kc.call("GET", "client-scopes") + catalog = {scope["name"]: scope["id"] for scope in scopes} + clients, _ = kc.call("GET", "clients") + existing = {client["clientId"]: client for client in clients} + except ERRORS as error: + print(f"listing-failed {error}") + return 1 + + outcomes = [] + + def record(kind: str, name: str, action, *args) -> None: + try: + outcome = action(*args) + except (RefusalError, *ERRORS) as error: + print(f"{kind} {name}: {error}", file=sys.stderr) + outcome = "failed" + print(f"{outcome} {kind} {name}") + outcomes.append(outcome) + + for scope in wanted_scopes: + record("client-scope", scope["name"], create_scope, kc, scope, catalog) + for client in wanted_clients: + name = client["clientId"] + record("client", name, converge_client, kc, client, existing.get(name), catalog) + for realm in wanted_realms: + name = realm["realm"] + record("realm", name, converge_realm, kc, name, realm["desired"]) + + print("summary " + " ".join(f"{key}={outcomes.count(key)}" for key in OUTCOMES)) + return 1 if "failed" in outcomes else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/roles/web-app-keycloak/files/shell/rbac_realm/ensure_group_path_members.sh b/roles/web-app-keycloak/files/shell/rbac_realm/ensure_group_path_members.sh index 430876e238..201503f035 100755 --- a/roles/web-app-keycloak/files/shell/rbac_realm/ensure_group_path_members.sh +++ b/roles/web-app-keycloak/files/shell/rbac_realm/ensure_group_path_members.sh @@ -64,7 +64,7 @@ for username in ${MEMBERS:-}; do --fields id --format csv --noquotes 2>/dev/null)" uid="$(printf '%s\n' "$raw" | grep -Eio "$_uuid_re" | head -n1 | tr -d '\r')" if [ -z "$uid" ]; then - echo "[keycloak][rbac] member '$username' not found in realm (expected: seeded by 08_users_realm before this runs)" >&2 + echo "[keycloak][rbac] member '$username' not found in realm (expected: seeded by update/06_users/realm.yml before this runs)" >&2 exit 1 fi if ! kc update "users/$uid/groups/$leaf_id" -r "$KC_REALM" \ diff --git a/roles/web-app-keycloak/filter_plugins/build_realm_rbac_groups.py b/roles/web-app-keycloak/filter_plugins/build_realm_rbac_groups.py index 7a5993dbaa..0516655300 100644 --- a/roles/web-app-keycloak/filter_plugins/build_realm_rbac_groups.py +++ b/roles/web-app-keycloak/filter_plugins/build_realm_rbac_groups.py @@ -9,7 +9,7 @@ the realm when no LDAP federation exists to import it from: Membership uses the same rule as the LDAP path: a user joins a role group iff that role name appears in the user's ``roles`` list. Members are restricted to -the users 08_users_realm actually seeds (non-reserved, non-empty password) and +the users update/06_users/realm.yml actually seeds (non-reserved, non-empty password) and are emitted by their ``username`` attribute (dict key fallback) so the realm lookup in ensure_group_path_members.sh matches the created accounts. The implicit ``administrator`` role is auto-added for every RBAC application, diff --git a/roles/web-app-keycloak/filter_plugins/ldap_filters.py b/roles/web-app-keycloak/filter_plugins/ldap_filters.py index 12b46718d6..41fe4e3801 100644 --- a/roles/web-app-keycloak/filter_plugins/ldap_filters.py +++ b/roles/web-app-keycloak/filter_plugins/ldap_filters.py @@ -1,6 +1,5 @@ import json from collections.abc import Iterable -from copy import deepcopy class FilterModule: @@ -70,7 +69,7 @@ class FilterModule: if not isinstance(ldap_cmp_id, str): raise TypeError("ldap_roles_mapper_payload: 'ldap_cmp_id' must be a string") - payload = deepcopy(desired_group_mapper) + payload = dict(desired_group_mapper) payload.update( { "name": "ldap-roles", diff --git a/roles/web-app-keycloak/tasks/03_manager_ops/update_routines.yml b/roles/web-app-keycloak/tasks/03_manager_ops/update_routines.yml index 3483a7f08d..399c82e85f 100644 --- a/roles/web-app-keycloak/tasks/03_manager_ops/update_routines.yml +++ b/roles/web-app-keycloak/tasks/03_manager_ops/update_routines.yml @@ -1,42 +1,29 @@ --- -- name: "📂 Load Client Update routines for '{{ application_id }}'" - include_tasks: "{{ role_path }}/tasks/update/01_client.yml" - -- name: "📂 Load Mail Update routines for '{{ application_id }} - {{ KEYCLOAK_REALM }}'" - include_tasks: "{{ role_path }}/tasks/update/02_mail_realm.yml" - -- name: "📂 Load Mail Update routines for '{{ application_id }} - master'" - include_tasks: "{{ role_path }}/tasks/update/03_mail_master.yml" - -- name: "⏳ Reap the client update job" - ansible.builtin.include_tasks: utils/async/reap.yml - vars: - async_reap_jobs: "{{ kc_client_update.results | default([kc_client_update]) }}" - async_reap_label: "Keycloak client settings" - async_reap_tolerate: [] +- name: "📂 Load client and mail settings routines for '{{ application_id }}'" + include_tasks: "{{ role_path }}/tasks/update/01_settings.yml" - name: "📂 Load RBAC Update routines for '{{ application_id }}'" - include_tasks: "{{ role_path }}/tasks/update/04_rbac_client_scope.yml" + include_tasks: "{{ role_path }}/tasks/update/02_rbac_client_scope.yml" - name: "📂 Load web-origins claim routines for '{{ application_id }}'" - include_tasks: "{{ role_path }}/tasks/update/09_web_origins_claim.yml" + include_tasks: "{{ role_path }}/tasks/update/07_web_origins_claim.yml" - name: "📂 Load LDAP shared-federation routines for '{{ application_id }}'" - include_tasks: "{{ role_path }}/tasks/update/05_ldap/shared.yml" + include_tasks: "{{ role_path }}/tasks/update/03_ldap/shared.yml" when: - KEYCLOAK_LDAP_ENABLED | bool - KEYCLOAK_LDAP_SHARED | bool - name: "🧹 Remove LDAP federation routines for '{{ application_id }}' when LDAP disabled" - include_tasks: "{{ role_path }}/tasks/update/05_ldap/disabled.yml" + include_tasks: "{{ role_path }}/tasks/update/03_ldap/disabled.yml" when: not KEYCLOAK_LDAP_ENABLED | bool - name: "📂 Load reCAPTCHA Update routines for '{{ application_id }}'" - include_tasks: "{{ role_path }}/tasks/update/06_recaptcha.yml" + include_tasks: "{{ role_path }}/tasks/update/04_recaptcha.yml" when: KEYCLOAK_RECAPTCHA_ENABLED | bool - name: "📂 Load UserProfile (declarative) Update routines for '{{ application_id }}'" - include_tasks: "{{ role_path }}/tasks/update/07_userprofile.yml" + include_tasks: "{{ role_path }}/tasks/update/05_userprofile.yml" - name: "📂 Load corporate theme selection routines for '{{ application_id }}'" include_tasks: "{{ role_path }}/tasks/update/11_design.yml" @@ -45,26 +32,11 @@ when: not KEYCLOAK_LDAP_ENABLED | bool block: - name: "📂 Load Realm User provisioning routines for '{{ application_id }}'" - include_tasks: "{{ role_path }}/tasks/update/08_users/realm.yml" + include_tasks: "{{ role_path }}/tasks/update/06_users/realm.yml" - name: "📂 Load RBAC realm group provisioning routines for '{{ application_id }}'" - include_tasks: "{{ role_path }}/tasks/update/08_rbac_groups_realm.yml" + include_tasks: "{{ role_path }}/tasks/update/06_rbac_groups_realm.yml" - name: "📂 Load Users Update routines for '{{ application_id }}' (emailVerified)" - include_tasks: "{{ role_path }}/tasks/update/08_users/email_verified.yml" + include_tasks: "{{ role_path }}/tasks/update/06_users/email_verified.yml" when: KEYCLOAK_USER_EMAILS_VERIFIED | bool - -- name: "📂 Ensure application-declared and SAML clients (existing realms)" - include_tasks: "{{ role_path }}/tasks/update/10_declared_client.yml" - vars: - kc_declared_client_id: "{{ declared_client }}" - loop: "{{ KEYCLOAK_DECLARED_CLIENT_IDS + KEYCLOAK_SAML_CLIENT_IDS }}" - loop_control: - loop_var: declared_client - -- name: "⏳ Reap the remaining Keycloak update jobs" - ansible.builtin.include_tasks: utils/async/reap.yml - vars: - async_reap_jobs: "{{ kc_declared_client_jobs | default([]) }}" - async_reap_label: "Keycloak realm updates" - async_reap_tolerate: [] diff --git a/roles/web-app-keycloak/tasks/update/01_client.yml b/roles/web-app-keycloak/tasks/update/01_client.yml deleted file mode 100644 index 4555b4ca40..0000000000 --- a/roles/web-app-keycloak/tasks/update/01_client.yml +++ /dev/null @@ -1,75 +0,0 @@ ---- -- name: ⬇️ Read the client scopes of the realm - shell: "{{ KEYCLOAK_EXEC_KCADM }} get client-scopes -r {{ KEYCLOAK_REALM }} --format json" - register: kc_realm_client_scopes - changed_when: false - -- name: ✅ Create the client scopes the realm dictionary declares and the realm lacks - shell: | - cat <<'JSON' | {{ KEYCLOAK_EXEC_KCADM }} create client-scopes -r {{ KEYCLOAK_REALM }} -f - - {{ kc_client_scope | to_json }} - JSON - loop: >- - {{ KEYCLOAK_DICTIONARY_REALM.clientScopes - | rejectattr('name', 'in', kc_realm_client_scopes.stdout | kcadm_json | map(attribute='name') | list) - | list }} - loop_control: - loop_var: kc_client_scope - label: "{{ kc_client_scope.name }}" - changed_when: true - -- name: "🔄 Update Client settings" - vars: - kc_object_kind: "client" - kc_lookup_value: "{{ KEYCLOAK_CLIENT_ID }}" - kc_desired: >- - {{ - KEYCLOAK_DICTIONARY_REALM.clients - | selectattr('clientId','equalto', KEYCLOAK_CLIENT_ID) - | list | first - }} - kc_force_attrs: - publicClient: >- - {{ - (KEYCLOAK_DICTIONARY_REALM.clients - | selectattr('clientId','equalto', KEYCLOAK_CLIENT_ID) - | map(attribute='publicClient') - | first) - }} - serviceAccountsEnabled: >- - {{ - (KEYCLOAK_DICTIONARY_REALM.clients - | selectattr('clientId','equalto', KEYCLOAK_CLIENT_ID) - | map(attribute='serviceAccountsEnabled') - | first ) - }} - frontchannelLogout: >- - {{ - (KEYCLOAK_DICTIONARY_REALM.clients - | selectattr('clientId','equalto', KEYCLOAK_CLIENT_ID) - | map(attribute='frontchannelLogout') - | first) - }} - attributes: >- - {{ - ( (KEYCLOAK_DICTIONARY_REALM.clients - | selectattr('clientId','equalto', KEYCLOAK_CLIENT_ID) - | list | first | default({}) ).attributes | default({}) ) - | combine({'frontchannel.logout.url': KEYCLOAK_FRONTCHANNEL_LOGOUT_URL}, recursive=True) - }} - keycloak_kcadm_update: - object_kind: "{{ kc_object_kind }}" - lookup_value: "{{ kc_lookup_value }}" - desired: "{{ kc_desired }}" - force_attrs: "{{ kc_force_attrs }}" - kcadm_exec: "{{ KEYCLOAK_EXEC_KCADM }}" - realm: "{{ KEYCLOAK_REALM }}" - assert_mode: "{{ MODE_ASSERT }}" - cid_resolve_cmd: "{{ KEYCLOAK_CID_RESOLVE_CMD if IS_SWARM_MODE else omit }}" - current_cid: "{{ KEYCLOAK_LOCAL_CID if IS_SWARM_MODE else omit }}" - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - register: kc_client_update - changed_when: false - # rationale: async; reaped in update_routines.yml before 04_rbac reads the client back - async: "{{ ASYNC_TIME if ASYNC_ENABLED | bool else omit }}" - poll: "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}" diff --git a/roles/web-app-keycloak/tasks/update/01_settings.yml b/roles/web-app-keycloak/tasks/update/01_settings.yml new file mode 100644 index 0000000000..fec9bf34f8 --- /dev/null +++ b/roles/web-app-keycloak/tasks/update/01_settings.yml @@ -0,0 +1,28 @@ +--- +- name: "🛑 Refuse clients the realm dictionary of '{{ KEYCLOAK_REALM }}' lacks" + ansible.builtin.assert: + that: KEYCLOAK_SETTINGS_MISSING_CLIENT_IDS | length == 0 + fail_msg: "The realm dictionary of '{{ KEYCLOAK_REALM }}' declares no client {{ KEYCLOAK_SETTINGS_MISSING_CLIENT_IDS | join(', ') }}" + quiet: true + +- name: "🔄 Converge client scopes, clients and realm mail settings over REST" + ansible.builtin.include_tasks: + file: "{{ role_path }}/tasks/utils/rest_script.yml" + apply: + delegate_to: "{{ KEYCLOAK_HOST_NODE }}" + vars: + rest_script: realm_settings.py + rest_script_env: {} + rest_script_stdin: "{{ KEYCLOAK_SETTINGS_SPEC | to_json }}" + rest_script_ok_rcs: [0, 1] + rest_script_changed: "(created|updated)=[1-9]" + rest_script_register: kc_settings + +- name: "📊 Report how many client scopes, clients and realms changed" + ansible.builtin.debug: + msg: "{{ kc_settings.stdout_lines | select('match', '^summary ') | list }}" + +- name: "⚠️ Report the client scopes, clients and realms that failed" + ansible.builtin.fail: + msg: "{{ (kc_settings.stdout_lines | select('match', '^(failed|listing-failed) ') | list) + kc_settings.stderr_lines }}" + when: kc_settings.rc != 0 diff --git a/roles/web-app-keycloak/tasks/update/02_mail_realm.yml b/roles/web-app-keycloak/tasks/update/02_mail_realm.yml deleted file mode 100644 index 073fa710df..0000000000 --- a/roles/web-app-keycloak/tasks/update/02_mail_realm.yml +++ /dev/null @@ -1,12 +0,0 @@ ---- -- name: "🔄 Update {{ KEYCLOAK_REALM }} REALM mail settings from realm dictionary" - keycloak_kcadm_update: - object_kind: "realm" - lookup_field: "id" - lookup_value: "{{ KEYCLOAK_REALM }}" - desired: - smtpServer: "{{ KEYCLOAK_DICTIONARY_REALM.smtpServer }}" - merge_path: "smtpServer" - kcadm_exec: "{{ KEYCLOAK_EXEC_KCADM }}" - assert_mode: "{{ MODE_ASSERT }}" - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-keycloak/tasks/update/04_rbac_client_scope.yml b/roles/web-app-keycloak/tasks/update/02_rbac_client_scope.yml similarity index 100% rename from roles/web-app-keycloak/tasks/update/04_rbac_client_scope.yml rename to roles/web-app-keycloak/tasks/update/02_rbac_client_scope.yml diff --git a/roles/web-app-keycloak/tasks/update/05_ldap/disabled.yml b/roles/web-app-keycloak/tasks/update/03_ldap/disabled.yml similarity index 100% rename from roles/web-app-keycloak/tasks/update/05_ldap/disabled.yml rename to roles/web-app-keycloak/tasks/update/03_ldap/disabled.yml diff --git a/roles/web-app-keycloak/tasks/update/05_ldap/main.yml b/roles/web-app-keycloak/tasks/update/03_ldap/main.yml similarity index 100% rename from roles/web-app-keycloak/tasks/update/05_ldap/main.yml rename to roles/web-app-keycloak/tasks/update/03_ldap/main.yml diff --git a/roles/web-app-keycloak/tasks/update/05_ldap/shared.yml b/roles/web-app-keycloak/tasks/update/03_ldap/shared.yml similarity index 70% rename from roles/web-app-keycloak/tasks/update/05_ldap/shared.yml rename to roles/web-app-keycloak/tasks/update/03_ldap/shared.yml index ac9e308e35..d0cb42014e 100644 --- a/roles/web-app-keycloak/tasks/update/05_ldap/shared.yml +++ b/roles/web-app-keycloak/tasks/update/03_ldap/shared.yml @@ -1,10 +1,10 @@ --- - name: "📂 Load LDAP Update routines for '{{ application_id }}'" - include_tasks: "{{ role_path }}/tasks/update/05_ldap/main.yml" + include_tasks: "{{ role_path }}/tasks/update/03_ldap/main.yml" - name: ✅ Assert Keycloak LDAP configuration include_tasks: "{{ role_path }}/tasks/assert/01_ldap.yml" when: MODE_ASSERT_LOCAL | bool - name: "📂 Load per-app group-ldap-mapper routines for '{{ application_id }}'" - include_tasks: "{{ role_path }}/tasks/update/05_per_app_mappers.yml" + include_tasks: "{{ role_path }}/tasks/update/03_per_app_mappers.yml" diff --git a/roles/web-app-keycloak/tasks/update/03_mail_master.yml b/roles/web-app-keycloak/tasks/update/03_mail_master.yml deleted file mode 100644 index 7340996078..0000000000 --- a/roles/web-app-keycloak/tasks/update/03_mail_master.yml +++ /dev/null @@ -1,12 +0,0 @@ ---- -- name: "🔄 Update Master REALM mail settings from realm dictionary" - keycloak_kcadm_update: - object_kind: "realm" - lookup_field: "id" - lookup_value: "master" - desired: - smtpServer: "{{ KEYCLOAK_DICTIONARY_REALM.smtpServer }}" - merge_path: "smtpServer" - kcadm_exec: "{{ KEYCLOAK_EXEC_KCADM }}" - assert_mode: "{{ MODE_ASSERT }}" - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-keycloak/tasks/update/05_per_app_mappers.yml b/roles/web-app-keycloak/tasks/update/03_per_app_mappers.yml similarity index 97% rename from roles/web-app-keycloak/tasks/update/05_per_app_mappers.yml rename to roles/web-app-keycloak/tasks/update/03_per_app_mappers.yml index 9757d711b3..a01d3fe6cf 100644 --- a/roles/web-app-keycloak/tasks/update/05_per_app_mappers.yml +++ b/roles/web-app-keycloak/tasks/update/03_per_app_mappers.yml @@ -21,7 +21,7 @@ # `preserve.group.inheritance=false` suffices per mapper because the # anchor is per-app — no collisions between apps exist within a mapper. # -# The shared default `ldap-roles` mapper (created by update/05_ldap/main.yml) +# The shared default `ldap-roles` mapper (created by update/03_ldap/main.yml) # is removed here so it does not shadow the per-app mappers, and any # Keycloak groups it had imported flat under /roles are pruned. @@ -59,6 +59,7 @@ SYNC_ATTEMPTS: "3" SYNC_DELAY: "20" SYNC_TIMEOUT: "{{ lookup('timeout', 60) | int }}" + rest_script_stdin: "" rest_script_ok_rcs: [0, 1, 2] rest_script_changed: "synced=[1-9]" rest_script_register: per_app_reconcile diff --git a/roles/web-app-keycloak/tasks/update/06_recaptcha.yml b/roles/web-app-keycloak/tasks/update/04_recaptcha.yml similarity index 100% rename from roles/web-app-keycloak/tasks/update/06_recaptcha.yml rename to roles/web-app-keycloak/tasks/update/04_recaptcha.yml diff --git a/roles/web-app-keycloak/tasks/update/07_userprofile.yml b/roles/web-app-keycloak/tasks/update/05_userprofile.yml similarity index 100% rename from roles/web-app-keycloak/tasks/update/07_userprofile.yml rename to roles/web-app-keycloak/tasks/update/05_userprofile.yml diff --git a/roles/web-app-keycloak/tasks/update/08_rbac_groups_realm.yml b/roles/web-app-keycloak/tasks/update/06_rbac_groups_realm.yml similarity index 100% rename from roles/web-app-keycloak/tasks/update/08_rbac_groups_realm.yml rename to roles/web-app-keycloak/tasks/update/06_rbac_groups_realm.yml diff --git a/roles/web-app-keycloak/tasks/update/08_users/email_verified.yml b/roles/web-app-keycloak/tasks/update/06_users/email_verified.yml similarity index 96% rename from roles/web-app-keycloak/tasks/update/08_users/email_verified.yml rename to roles/web-app-keycloak/tasks/update/06_users/email_verified.yml index f092932e5c..797a3ab3c6 100644 --- a/roles/web-app-keycloak/tasks/update/08_users/email_verified.yml +++ b/roles/web-app-keycloak/tasks/update/06_users/email_verified.yml @@ -8,6 +8,7 @@ rest_script: email_verified.py rest_script_env: USERNAMES: "{{ lookup('users_non_reserved') | dict2items | map(attribute='value.username') | join(' ') }}" + rest_script_stdin: "" rest_script_ok_rcs: [0] rest_script_changed: "updated=[1-9]" rest_script_register: kc_email_verified diff --git a/roles/web-app-keycloak/tasks/update/08_users/realm.yml b/roles/web-app-keycloak/tasks/update/06_users/realm.yml similarity index 96% rename from roles/web-app-keycloak/tasks/update/08_users/realm.yml rename to roles/web-app-keycloak/tasks/update/06_users/realm.yml index 61a986f4da..361ce9024c 100644 --- a/roles/web-app-keycloak/tasks/update/08_users/realm.yml +++ b/roles/web-app-keycloak/tasks/update/06_users/realm.yml @@ -3,7 +3,7 @@ # disabled. Without an LDAP federation this is the only path that seeds real # end-user accounts (administrator, biber, ...); seeding only administrator left # their SSO logins failing with user_not_found. Group memberships are applied -# afterwards by update/08_rbac_groups_realm.yml. +# afterwards by update/06_rbac_groups_realm.yml. - name: "✅ Ensure non-reserved users exist in realm '{{ KEYCLOAK_REALM }}'" ansible.builtin.script: shell/ensure_realm_user.sh diff --git a/roles/web-app-keycloak/tasks/update/09_web_origins_claim.yml b/roles/web-app-keycloak/tasks/update/07_web_origins_claim.yml similarity index 100% rename from roles/web-app-keycloak/tasks/update/09_web_origins_claim.yml rename to roles/web-app-keycloak/tasks/update/07_web_origins_claim.yml diff --git a/roles/web-app-keycloak/tasks/update/10_declared_client.yml b/roles/web-app-keycloak/tasks/update/10_declared_client.yml deleted file mode 100644 index bd44321fef..0000000000 --- a/roles/web-app-keycloak/tasks/update/10_declared_client.yml +++ /dev/null @@ -1,29 +0,0 @@ ---- -# Realm import only runs for a MISSING realm; this kcadm create-or-update brings -# application-declared and SAML clients to existing realms too. Desired state is the -# import's own client object, so the realm template stays the one SPOT. -- name: "✅ Ensure the '{{ kc_declared_client_id }}' client" - vars: - kc_desired: >- - {{ - KEYCLOAK_DICTIONARY_REALM.clients - | selectattr('clientId', 'equalto', kc_declared_client_id) - | list | first - }} - keycloak_kcadm_update: - object_kind: "client" - lookup_value: "{{ kc_declared_client_id }}" - desired: "{{ kc_desired }}" - kcadm_exec: "{{ KEYCLOAK_EXEC_KCADM }}" - realm: "{{ KEYCLOAK_REALM }}" - assert_mode: "{{ MODE_ASSERT }}" - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - register: kc_declared_client - # rationale: async; nothing reads the client back in this chain, reaped at the end of update_routines.yml - async: "{{ ASYNC_TIME if ASYNC_ENABLED | bool else omit }}" - poll: "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}" - -# rationale: looped include — each iteration overwrites the register, so the job handle is banked here for the reap. -- name: "🧾 Queue the '{{ kc_declared_client_id }}' client job for the reap" - ansible.builtin.set_fact: - kc_declared_client_jobs: "{{ (kc_declared_client_jobs | default([])) + [kc_declared_client] }}" diff --git a/roles/web-app-keycloak/tasks/utils/rest_script.yml b/roles/web-app-keycloak/tasks/utils/rest_script.yml index 60c6e99885..2f3099f5d4 100644 --- a/roles/web-app-keycloak/tasks/utils/rest_script.yml +++ b/roles/web-app-keycloak/tasks/utils/rest_script.yml @@ -1,6 +1,7 @@ --- # Param: rest_script - script under files/python/ that imports keycloak_admin.py # Param: rest_script_env - script environment besides KC_URL, KC_PID, KC_REALM and PYTHONPATH +# Param: rest_script_stdin - text the script reads on stdin, the only channel for secrets # Param: rest_script_ok_rcs - exit codes that do not fail the run # Param: rest_script_changed - regex on stdout that marks the run changed # Param: rest_script_register - fact the command result is stored under @@ -48,6 +49,7 @@ - -- - python3 - "{{ kc_rest_script_dir.path }}/{{ rest_script }}" + stdin: "{{ rest_script_stdin }}" environment: "{{ rest_script_env | combine(kc_rest_script_base_env) }}" vars: kc_rest_script_base_env: diff --git a/roles/web-app-keycloak/templates/logout-panel.js.j2 b/roles/web-app-keycloak/templates/logout-panel.js.j2 index ea01d97e07..1b680da5d6 100644 --- a/roles/web-app-keycloak/templates/logout-panel.js.j2 +++ b/roles/web-app-keycloak/templates/logout-panel.js.j2 @@ -1,5 +1,5 @@ window.__INFINITO_LOGOUT__ = { - origin: {{ lookup('tls', 'web-svc-logout', 'url.base') | regex_replace('/$', '') | to_json }}, + origin: {{ lookup('tls', 'web-svc-logout', 'url.origin') | to_json }}, i18n: {{ lookup('i18n_catalogue', 'logout', 'roles/web-app-keycloak/files/logout_i18n.yml') | to_json }} }; {{ lookup('file', application_id | abs_role_path_by_application_id ~ '/files/javascript/logout-panel.js') }} diff --git a/roles/web-app-keycloak/templates/sso_proxy/endpoint.conf.j2 b/roles/web-app-keycloak/templates/sso_proxy/endpoint.conf.j2 index 5ae6402c67..08495f9578 100644 --- a/roles/web-app-keycloak/templates/sso_proxy/endpoint.conf.j2 +++ b/roles/web-app-keycloak/templates/sso_proxy/endpoint.conf.j2 @@ -5,10 +5,28 @@ location /oauth2/ { {% include 'roles/sys-svc-proxy/templates/headers/upstream_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; - proxy_set_header X-Forwarded-Proto $scheme; + {% include 'roles/sys-svc-proxy/templates/headers/forwarded_base.conf.j2' %} + + proxy_pass_request_body off; + proxy_set_header Content-Length ""; +} + +location @oauth2_start { + {{ lookup('proxy_pass', application_id, 'sso-proxy', 'http', tail='oauth2', local_port=lookup('config', application_id, 'services.' ~ (application_id | get_entity_name) ~ '.ports.local.sso'), internal_port=lookup('config', 'web-app-keycloak', 'services.sso_proxy.ports.internal.http')) }} + + {% include 'roles/sys-svc-proxy/templates/headers/upstream_strips.conf.j2' %} + + {% include 'roles/sys-svc-proxy/templates/headers/forwarded_base.conf.j2' %} + + set $oauth2_start_redirect $request_uri; + if ($request_method !~ ^(GET|HEAD)$) { + set $oauth2_start_redirect ""; + } + if ($request_uri ~ "^.{3500}") { + set $oauth2_start_redirect ""; + } + rewrite ^ /oauth2/start? break; + proxy_set_header X-Auth-Request-Redirect $oauth2_start_redirect; proxy_pass_request_body off; proxy_set_header Content-Length ""; diff --git a/roles/web-app-keycloak/templates/sso_proxy/following_directives.conf.j2 b/roles/web-app-keycloak/templates/sso_proxy/following_directives.conf.j2 index efc9d94049..b6d3ecd1aa 100644 --- a/roles/web-app-keycloak/templates/sso_proxy/following_directives.conf.j2 +++ b/roles/web-app-keycloak/templates/sso_proxy/following_directives.conf.j2 @@ -2,7 +2,7 @@ auth_request /oauth2/auth; -error_page 401 = /oauth2/start; +error_page 401 = @oauth2_start; auth_request_set $authrequest_user $upstream_http_x_auth_request_user; auth_request_set $authrequest_username $upstream_http_x_auth_request_preferred_username; diff --git a/roles/web-app-keycloak/vars/main.yml b/roles/web-app-keycloak/vars/main.yml index 5c04ac2603..d5139f9184 100644 --- a/roles/web-app-keycloak/vars/main.yml +++ b/roles/web-app-keycloak/vars/main.yml @@ -5,7 +5,7 @@ domain: "{{ lookup('domain',application_id) }}" KEYCLOAK_CONTAINER_HOSTNAME: "{{ entity_name }}" KEYCLOAK_REALM: "{{ OIDC.CLIENT.REALM }}" -KEYCLOAK_URL: "{{ lookup('tls', application_id, 'url.base') | regex_replace('/+$', '') }}" +KEYCLOAK_URL: "{{ lookup('tls', application_id, 'url.origin') }}" KEYCLOAK_REALM_URL: "{{ KEYCLOAK_URL }}/realms/{{ KEYCLOAK_REALM }}" KEYCLOAK_DEBUG_ENABLED: "{{ MODE_DEBUG }}" KEYCLOAK_CLIENT_ID: "{{ OIDC.CLIENT.ID }}" @@ -95,11 +95,6 @@ KEYCLOAK_TARGET_CONTAINER: "{{ KEYCLOAK_LOCAL_CID | default(KEYCLOAK_CONTAINER_A KEYCLOAK_EXEC_CONTAINER: "container exec -i {{ KEYCLOAK_TARGET_CONTAINER }}" # nocheck: container-exec-resolver # nocheck: container-var-name-lookup references the consumer's container, not this role's service KEYCLOAK_KCADM: "/opt/keycloak/bin/kcadm.sh" KEYCLOAK_EXEC_KCADM: "{{ KEYCLOAK_EXEC_CONTAINER }} {{ KEYCLOAK_KCADM }}" -KEYCLOAK_CID_RESOLVE_CMD: >- - container ps - --filter "label=com.docker.swarm.service.name={{ lookup('container_service', application_id, entity_name) }}" - --filter status=running - --format '{{ "{{.ID}}" }}' | head -1 KEYCLOAK_IMAGE: "{{ lookup('config', application_id, 'services.keycloak.image') }}" KEYCLOAK_VERSION: "{{ lookup('config', application_id, 'services.keycloak.version') }}" KEYCLOAK_REPLICAS: "{{ groups[application_id] | length }}" @@ -153,6 +148,19 @@ KEYCLOAK_MOODLE_ENABLED: "{{ 'web-app-moodle' in group_names }}" KEYCLOAK_DECLARED_CLIENT_APPS: "{{ lookup('applications') | kc_declared_client_apps(lookup('deployment').groups) }}" KEYCLOAK_DECLARED_CLIENT_IDS: "{{ lookup('applications') | kc_declared_client_ids(lookup('deployment').groups) }}" KEYCLOAK_SAML_CLIENT_IDS: "{{ KEYCLOAK_DICTIONARY_REALM.clients | selectattr('protocol', 'equalto', 'saml') | map(attribute='clientId') | list }}" +KEYCLOAK_SETTINGS_CLIENT_IDS: "{{ ([KEYCLOAK_CLIENT_ID] + KEYCLOAK_DECLARED_CLIENT_IDS + KEYCLOAK_SAML_CLIENT_IDS) | unique | list }}" +KEYCLOAK_SETTINGS_MISSING_CLIENT_IDS: "{{ KEYCLOAK_SETTINGS_CLIENT_IDS | reject('in', KEYCLOAK_DICTIONARY_REALM.clients | map(attribute='clientId') | list) | list + }}" +KEYCLOAK_SETTINGS_SPEC: + clientScopes: "{{ KEYCLOAK_DICTIONARY_REALM.clientScopes }}" + clients: "{{ KEYCLOAK_DICTIONARY_REALM.clients | selectattr('clientId', 'in', KEYCLOAK_SETTINGS_CLIENT_IDS) | list }}" + realms: + - realm: "{{ KEYCLOAK_REALM }}" + desired: + smtpServer: "{{ KEYCLOAK_DICTIONARY_REALM.smtpServer }}" + - realm: master + desired: + smtpServer: "{{ KEYCLOAK_DICTIONARY_REALM.smtpServer }}" KEYCLOAK_RECAPTCHA_ENABLED: "{{ lookup('config', application_id, 'services.recaptcha.enabled') }}" KEYCLOAK_RECAPTCHA_KEY: "{{ lookup('config', application_id, 'secrets.credentials.recaptcha.key') }}" diff --git a/roles/web-app-kix/templates/kix-proxy.default.conf.j2 b/roles/web-app-kix/templates/kix-proxy.default.conf.j2 index 781f73ea14..11c9a7e453 100644 --- a/roles/web-app-kix/templates/kix-proxy.default.conf.j2 +++ b/roles/web-app-kix/templates/kix-proxy.default.conf.j2 @@ -23,10 +23,7 @@ server { proxy_send_timeout 300s; location / { - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; + {% include 'roles/sys-svc-proxy/templates/headers/forwarded_base.conf.j2' %} proxy_set_header X-Forwarded-User $http_x_forwarded_user; proxy_set_header Remote-User $http_x_forwarded_user; proxy_set_header Upgrade $http_upgrade; diff --git a/roles/web-app-magento/templates/style.css.j2 b/roles/web-app-magento/templates/style.css.j2 index ac35acdccd..f939375568 100644 --- a/roles/web-app-magento/templates/style.css.j2 +++ b/roles/web-app-magento/templates/style.css.j2 @@ -1,5 +1,5 @@ {% set design = lookup('design', application_id) %} -{% set static = MAGENTO_URL | regex_replace('/+$', '') ~ '/static' %} +{% set static = lookup('tls', application_id, 'url.origin') ~ '/static' %} {% set admin = ':where(html:has(> head > link[href*="/adminhtml/"]))' %} :where(html:not(:has(> head > link[href*="/adminhtml/"]))) { & body { diff --git a/roles/web-app-matomo/tasks/08_reinject_consumers.yml b/roles/web-app-matomo/tasks/08_reinject_consumers.yml index 27f46377d9..97e76888e6 100644 --- a/roles/web-app-matomo/tasks/08_reinject_consumers.yml +++ b/roles/web-app-matomo/tasks/08_reinject_consumers.yml @@ -1,7 +1,7 @@ --- - name: "🔎 Matomo | Stat rendered body_filter Lua of candidate web-svc matomo consumers" ansible.builtin.stat: - path: "{{ lookup('nginx', 'directories.configuration.lua') }}{{ lookup('domain', matomo_inj_consumer.id) }}.lua" + path: "{{ lookup('nginx', 'files.lua', lookup('domain', matomo_inj_consumer.id)) }}" loop: "{{ lookup('roles_with_service', 'matomo', scope='all') | selectattr('id', 'match', '^web-svc-') | list }}" loop_control: loop_var: matomo_inj_consumer diff --git a/roles/web-app-matrix/meta/services.yml b/roles/web-app-matrix/meta/services.yml index 7022c9600b..d0f317ec8c 100644 --- a/roles/web-app-matrix/meta/services.yml +++ b/roles/web-app-matrix/meta/services.yml @@ -94,7 +94,7 @@ postgres: synapse: healthcheck: flavor: curl - version: v1.164.0 + version: v1.164.1 image: matrixdotorg/synapse name: matrix-synapse backup: diff --git a/roles/web-app-mattermost/meta/addons/mattermost-plugin-agents.yml b/roles/web-app-mattermost/meta/addons/mattermost-plugin-agents.yml index 874d5d52c3..52e60512d6 100644 --- a/roles/web-app-mattermost/meta/addons/mattermost-plugin-agents.yml +++ b/roles/web-app-mattermost/meta/addons/mattermost-plugin-agents.yml @@ -7,4 +7,4 @@ bridges: - openwebui config: plugin_id: mattermost-ai - partner_url: "{{ lookup('tls', 'web-app-openwebui', 'url.base') | regex_replace('/+$', '') ~ '/api' }}" + partner_url: "{{ lookup('tls', 'web-app-openwebui', 'url.origin') ~ '/api' }}" diff --git a/roles/web-app-mediawiki/files/install/or_update.sh b/roles/web-app-mediawiki/files/install/or_update.sh index 248e4143f4..4ef14c0f8f 100755 --- a/roles/web-app-mediawiki/files/install/or_update.sh +++ b/roles/web-app-mediawiki/files/install/or_update.sh @@ -5,10 +5,17 @@ set -euo pipefail NETWORK="$1"; MARIADB_VERSION="$2" -DB_HOST="$3"; DB_PORT="$4"; DB_USER="$5"; DB_PASSWORD="$6"; DB_NAME="$7" -MW_USER="$8"; MW_IMAGE="$9"; MW_VERSION="${10}"; MW_HTML_DIR="${11}" -MW_URL="${12}"; MW_SITENAME="${13}"; ADMIN_NAME="${14}"; ADMIN_PASSWORD="${15}" +DB_HOST="$3"; DB_PORT="$4"; DB_USER="$5"; DB_NAME="$6" +MW_USER="$7"; MW_IMAGE="$8"; MW_VERSION="$9"; MW_HTML_DIR="${10}" +MW_URL="${11}"; MW_SITENAME="${12}"; ADMIN_NAME="${13}" +{ IFS= read -r MW_DB_PASSWORD && IFS= read -r MW_ADMIN_PASSWORD; } || { + echo "the database and the admin password must arrive on stdin, one per line" >&2 + exit 1 +} +: "${MW_DB_PASSWORD:?the database password must be the first line on stdin}" +: "${MW_ADMIN_PASSWORD:?the admin password must be the second line on stdin}" +export MW_DB_PASSWORD MW_ADMIN_PASSWORD : "${MW_CUSTOM_IMAGE:?MW_CUSTOM_IMAGE env var required for update}" : "${MW_LOCALSETTINGS_HOST_PATH:?MW_LOCALSETTINGS_HOST_PATH env var required for update}" : "${MW_LOCALSETTINGS_CONTAINER_PATH:?MW_LOCALSETTINGS_CONTAINER_PATH env var required for update}" @@ -24,8 +31,9 @@ if [ -n "$MW_NETWORK_OBJSTORE" ] && [ "$MW_NETWORK_OBJSTORE" != "$NETWORK" ]; th fi has_tables=0 -if container run --rm --network "$NETWORK" "mariadb:${MARIADB_VERSION:-latest}" \ - mariadb -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASSWORD" \ +if MYSQL_PWD="$MW_DB_PASSWORD" container run --rm --network "$NETWORK" -e MYSQL_PWD \ + "mariadb:${MARIADB_VERSION:-latest}" \ + mariadb -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" \ -N -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$DB_NAME';" \ 2>/dev/null | grep -q -v '^0$'; then has_tables=1 @@ -33,22 +41,24 @@ fi if [ "$has_tables" -eq 0 ]; then echo "[mw] Fresh DB detected -> running install (one-shot)" + # shellcheck disable=SC2016 container run --rm \ --network "$NETWORK" \ -u "$MW_USER" \ + -e MW_DB_PASSWORD \ + -e MW_ADMIN_PASSWORD \ "$MW_IMAGE:$MW_VERSION" \ - php "$MW_HTML_DIR/maintenance/run.php" install \ + bash -c 'umask 077 && printf "%s" "$MW_DB_PASSWORD" > /tmp/dbpass && printf "%s" "$MW_ADMIN_PASSWORD" > /tmp/pass && exec php "$@" --dbpassfile /tmp/dbpass --passfile /tmp/pass' _ \ + "$MW_HTML_DIR/maintenance/run.php" install \ --confpath /tmp \ --dbtype mysql \ --dbserver "$DB_HOST:$DB_PORT" \ --dbname "$DB_NAME" \ --dbuser "$DB_USER" \ - --dbpass "$DB_PASSWORD" \ --server "$MW_URL" \ --scriptpath "" \ "$MW_SITENAME" \ - "$ADMIN_NAME" \ - --pass "$ADMIN_PASSWORD" + "$ADMIN_NAME" else echo "[mw] DB already initialized -> skipping install" fi diff --git a/roles/web-app-mediawiki/tasks/03_install.yml b/roles/web-app-mediawiki/tasks/03_install.yml index d32c7a0511..bb93a6697b 100644 --- a/roles/web-app-mediawiki/tasks/03_install.yml +++ b/roles/web-app-mediawiki/tasks/03_install.yml @@ -1,14 +1,28 @@ --- - name: "🥾 MEDIAWIKI | Bootstrap DB (install if empty) then update" - ansible.builtin.script: >- - install/or_update.sh - "{{ MEDIAWIKI_NETWORK_DATABASE }}" "{{ lookup('database', application_id, 'version') | default('latest') }}" - "{{ lookup('database', application_id, 'host') }}" "{{ lookup('database', application_id, 'port') }}" - "{{ lookup('database', application_id, 'username') }}" "{{ lookup('database', application_id, 'password') }}" - "{{ lookup('database', application_id, 'name') }}" - "{{ MEDIAWIKI_USER }}" "{{ MEDIAWIKI_IMAGE }}" "{{ MEDIAWIKI_VERSION }}" "{{ MEDIAWIKI_HTML_DIR }}" - "{{ MEDIAWIKI_URL }}" "{{ MEDIAWIKI_SITENAME }}" - "{{ MEDIAWIKI_ADMINISTRATOR_NAME }}" "{{ MEDIAWIKI_ADMINISTRATOR_PASSWORD }}" + ansible.builtin.command: + argv: + - bash + - -c + - "{{ lookup('file', 'install/or_update.sh') }}" + - or_update.sh + - "{{ MEDIAWIKI_NETWORK_DATABASE }}" + - "{{ lookup('database', application_id, 'version') | default('latest') }}" + - "{{ lookup('database', application_id, 'host') }}" + - "{{ lookup('database', application_id, 'port') }}" + - "{{ lookup('database', application_id, 'username') }}" + - "{{ lookup('database', application_id, 'name') }}" + - "{{ MEDIAWIKI_USER }}" + - "{{ MEDIAWIKI_IMAGE }}" + - "{{ MEDIAWIKI_VERSION }}" + - "{{ MEDIAWIKI_HTML_DIR }}" + - "{{ MEDIAWIKI_URL }}" + - "{{ MEDIAWIKI_SITENAME }}" + - "{{ MEDIAWIKI_ADMINISTRATOR_NAME }}" + stdin: |- + {{ lookup('database', application_id, 'password') }} + {{ MEDIAWIKI_ADMINISTRATOR_PASSWORD }} + expand_argument_vars: false environment: MW_CUSTOM_IMAGE: "{{ MEDIAWIKI_CUSTOM_IMAGE_REF }}" MW_LOCALSETTINGS_HOST_PATH: "{{ MEDIAWIKI_LOCALSETTINGS_HOST_PATH }}" diff --git a/roles/web-app-mediawiki/templates/LocalSettings.php.j2 b/roles/web-app-mediawiki/templates/LocalSettings.php.j2 index 6f8f162b37..baf70e0c50 100644 --- a/roles/web-app-mediawiki/templates/LocalSettings.php.j2 +++ b/roles/web-app-mediawiki/templates/LocalSettings.php.j2 @@ -32,10 +32,10 @@ $wgScriptPath = ""; ## The protocol and server name to use in fully-qualified URLs {% set mediawiki_hosts = lookup('network_siblings', lookup('domain', application_id)) %} -$wgCanonicalServer = "{{ MEDIAWIKI_URL | regex_replace('/+$', '') }}"; +$wgCanonicalServer = "{{ lookup('tls', application_id, 'url.origin') }}"; $infinito_servers = [ {% for host in mediawiki_hosts %} - '{{ host }}' => "{{ lookup('tls', host, 'url.base') | regex_replace('/+$', '') }}", + '{{ host }}' => "{{ lookup('tls', host, 'url.origin') }}", {% endfor %} ]; $infinito_request_host = strtolower( (string)parse_url( \MediaWiki\Request\WebRequest::detectServer(), PHP_URL_HOST ) ); diff --git a/roles/web-app-moodle/templates/env.j2 b/roles/web-app-moodle/templates/env.j2 index c0fe827eae..160d3faa99 100644 --- a/roles/web-app-moodle/templates/env.j2 +++ b/roles/web-app-moodle/templates/env.j2 @@ -1,6 +1,6 @@ {% include 'roles/sys-svc-container/templates/env.j2' %} -MOODLE_WWWROOT={{ lookup('tls', application_id, 'url.base') | regex_replace('/$', '') }} +MOODLE_WWWROOT={{ lookup('tls', application_id, 'url.origin') }} MOODLE_INTERNAL_HOST={{ MOODLE_MCP_SERVICE_KEY }} MOODLE_DATAROOT={{ MOODLE_DATA_DIR }} MOODLE_LOCALCACHEDIR={{ MOODLE_LOCAL_CACHE_DIR }} diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index 2f7e95c213..88ac69dacd 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -75,7 +75,7 @@ n8n: backup: stop_required: true image: docker.n8n.io/n8nio/n8n - version: "3.0.0" + version: "3.0.1" update: type: registry_tags image: docker.n8n.io/n8nio/n8n diff --git a/roles/web-app-nextcloud/files/php/addons/openproject/ensure_nc_client.php b/roles/web-app-nextcloud/files/php/addons/openproject/ensure_nc_client.php new file mode 100644 index 0000000000..28e9d8eddf --- /dev/null +++ b/roles/web-app-nextcloud/files/php/addons/openproject/ensure_nc_client.php @@ -0,0 +1,50 @@ +loadApp("oauth2"); +$apps->loadApp("integration_openproject"); + +$oauth =\OCP\Server::get(\OCA\OpenProject\Service\OauthService::class); +$clients = \OCP\Server::get(\OCA\OAuth2\Service\ClientService::class); +$mapper = \OCP\Server::get(\OCA\OAuth2\Db\ClientMapper::class); + +$openProjectUrl = rtrim($openProjectUrl, "/"); +$current = ctype_digit($storedId) ? $oauth->getClientInfo((int) $storedId) : null; + +if ($current === null) { + $created = $oauth->createNcOauthClient($clientName, $openProjectUrl . "/oauth_clients/%s/callback"); + $state = [ + "action" => "created", + "id" => (int) $created["id"], + "client_id" => $created["nextcloud_client_id"], + "client_secret" => $created["nextcloud_client_secret"], + ]; +} else { + $expected = $openProjectUrl . "/oauth_clients/" . $current["nextcloud_client_id"] . "/callback"; + $state = [ + "action" => $current["openproject_redirect_uri"] === $expected ? "unchanged" : "redirect_fixed", + "id" => (int) $current["id"], + "client_id" => $current["nextcloud_client_id"], + ]; + if ($state["action"] === "redirect_fixed") { + $oauth->setClientRedirectUri($state["id"], $openProjectUrl); + } +} + +$removed = 0; +foreach ($mapper->getClients() as $client) { + if ($client->getName() === $clientName && (int) $client->getId() !== $state["id"]) { + $clients->deleteClient((int) $client->getId()); + $removed++; + } +} +$state["removed"] = $removed; + +echo "NC_OAUTH_CLIENT " . json_encode($state) . "\n"; diff --git a/roles/web-app-nextcloud/files/php/utils/migration_state.php b/roles/web-app-nextcloud/files/php/utils/migration_state.php new file mode 100644 index 0000000000..05c6aad745 --- /dev/null +++ b/roles/web-app-nextcloud/files/php/utils/migration_state.php @@ -0,0 +1,15 @@ + $migrations->getMigratedVersions(), + "available" => $migrations->getAvailableVersions(), +]) . "\n"; diff --git a/roles/web-app-nextcloud/files/playwright/addons/bbb.spec.js b/roles/web-app-nextcloud/files/playwright/addons/bbb.spec.js index 4fa76378af..4239f5e629 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/bbb.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/bbb.spec.js @@ -63,8 +63,8 @@ test("bbb addon: cloud_bbb app route renders its own UI and is coupled to the pa expect( configuredUrl, - "the bbb api.url must be a valid https URL pointing at the BigBlueButton API mount (the partner base URL + '/bigbluebutton/' API suffix)" - ).toMatch(/^https:\/\/.+\/bigbluebutton\/?$/); + "the bbb api.url must be the partner base URL + '/bigbluebutton/' with exactly one slash on each side; the BigBlueButton client appends 'api/' directly, so a missing trailing slash yields '/bigbluebuttonapi/'" + ).toMatch(/^https:\/\/[^/]+\/bigbluebutton\/$/); const apiSecretField = bbbSection.locator("#bbb-api input[name='api.secret'], input[name='api.secret']"); await expect( diff --git a/roles/web-app-nextcloud/files/playwright/addons/integration_openproject.spec.js b/roles/web-app-nextcloud/files/playwright/addons/integration_openproject.spec.js index abbae4906d..bb6b5874ad 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/integration_openproject.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/integration_openproject.spec.js @@ -2,7 +2,8 @@ const { test, expect } = require("@playwright/test"); const { resolveTimeout } = require("../timeouts"); const { skipUnlessAddonEnabled } = require("../addon-gating"); const shared = require("../_shared"); -const { gotoOnion } = require("../personas"); +const { gotoOnion, performKeycloakLoginForm } = require("../personas"); +const { decodeDotenvQuotedValue } = require("../personas/utils/dotenv"); test("integration integration_openproject: two-way OAuth coupling provisioned and connectable to partner OpenProject", async ({ browser }) => { skipUnlessAddonEnabled("integration_openproject"); @@ -92,3 +93,172 @@ test("integration integration_openproject: two-way OAuth coupling provisioned an await context.close().catch(() => {}); } }); + +const OAUTH_REDIRECT_PATH = "integration_openproject/oauth-redirect"; + +function connectButton(page) { + return page.getByRole("button", { name: /connect to openproject|mit openproject verbinden/i }).first(); +} + +function disconnectButton(page) { + return page.getByRole("button", { name: /disconnect from openproject|von openproject trennen/i }).first(); +} + +async function openOpenProjectPersonalSettings(page) { + await gotoOnion(page, + new URL("index.php/settings/user/openproject", shared.env.nextcloudBaseUrl).toString(), + { waitUntil: "domcontentloaded", timeout: resolveTimeout(60_000) } + ); + await shared.dismissBlockingNextcloudModals(page, page); + await expect( + connectButton(page).or(disconnectButton(page)).first(), + "the integration_openproject personal settings must offer 'Connect to OpenProject' or 'Disconnect from OpenProject'; anything else means the user-side OAuth configuration (admin_config_ok) is broken" + ).toBeVisible({ timeout: resolveTimeout(60_000) }); +} + +async function disconnectFromOpenProjectIfConnected(page) { + const disconnect = disconnectButton(page); + if (!(await disconnect.isVisible().catch(() => false))) return; + await Promise.all([ + page.waitForResponse( + (response) => + response.request().method() === "PUT" && + new URL(response.url()).pathname.includes("integration_openproject/config"), + { timeout: resolveTimeout(30_000) } + ), + shared.clickWithModalRetry(page, page, disconnect), + ]); + await expect( + connectButton(page), + "after 'Disconnect from OpenProject' the personal settings must offer 'Connect to OpenProject' again" + ).toBeVisible({ timeout: resolveTimeout(30_000) }); +} + +async function ensureOpenProjectSession(page) { + const openProjectUrl = decodeDotenvQuotedValue(process.env.OPENPROJECT_BASE_URL || ""); + expect( + openProjectUrl, + "OPENPROJECT_BASE_URL must name the partner OpenProject while integration_openproject is enabled" + ).not.toBe(""); + const openProjectHost = new URL(openProjectUrl).host; + const loginForm = page + .locator("form") + .filter({ has: page.locator("input[type='password']:visible") }) + .first(); + await gotoOnion(page, openProjectUrl, { waitUntil: "domcontentloaded", timeout: resolveTimeout(60_000) }); + const deadline = Date.now() + resolveTimeout(90_000); + while (Date.now() < deadline) { + const current = new URL(page.url()); + if (current.host === openProjectHost && !/login|two_factor|oauth2\/callback/.test(current.pathname)) { + return; + } + if (await loginForm.isVisible().catch(() => false)) { + await performKeycloakLoginForm(loginForm, shared.env.loginUsername, shared.env.loginPassword); + } + await page.waitForTimeout(resolveTimeout(500)); + } + const stoppedAt = new URL(page.url()); + throw new Error(`no OpenProject session after the SSO login; the browser stopped at ${stoppedAt.host}${stoppedAt.pathname}`); +} + +async function authorizeOnOpenProject(page, oauthRedirectReached) { + const loginForm = page + .locator("form") + .filter({ has: page.locator("input[type='password']:visible") }) + .first(); + const authorizeButton = page + .locator("form[action*='/oauth/authorize']:not(:has(input[name='_method'])) [type='submit']") + .or(page.getByRole("button", { name: /^\s*(authori[sz]e|autorisieren)\s*$/i })) + .first(); + const deadline = Date.now() + resolveTimeout(120_000); + let loginSubmitted = false; + + while (!oauthRedirectReached() && Date.now() < deadline) { + if (await authorizeButton.isVisible().catch(() => false)) { + await authorizeButton.click({ timeout: resolveTimeout(30_000) }); + return; + } + if (!loginSubmitted && (await loginForm.isVisible().catch(() => false))) { + await performKeycloakLoginForm(loginForm, shared.env.loginUsername, shared.env.loginPassword); + loginSubmitted = true; + } + await page.waitForTimeout(resolveTimeout(500)); + } +} + +test("integration integration_openproject: a user connects to OpenProject via OAuth and Nextcloud redeems the code at /oauth/token", async ({ browser }) => { + skipUnlessAddonEnabled("integration_openproject"); + test.setTimeout(resolveTimeout(300_000)); + + const context = await browser.newContext({ ignoreHTTPSErrors: true }); + const page = await context.newPage(); + let connectStarted = false; + + try { + await shared.loginToStandaloneNextcloud(page); + await ensureOpenProjectSession(page); + await openOpenProjectPersonalSettings(page); + await disconnectFromOpenProjectIfConnected(page); + + const connect = connectButton(page); + await expect( + connect, + "the 'Connect to OpenProject' control must render for an unconnected user once the OAuth client is provisioned" + ).toBeVisible({ timeout: resolveTimeout(30_000) }); + + let oauthRedirectReached = false; + const oauthRedirect = page + .waitForResponse( + (response) => new URL(response.url()).pathname.includes(OAUTH_REDIRECT_PATH), + { timeout: resolveTimeout(180_000) } + ) + .then( + (response) => { + oauthRedirectReached = true; + return { response }; + }, + (error) => { + oauthRedirectReached = true; + return { error }; + } + ); + + connectStarted = true; + await shared.clickWithModalRetry(page, page, connect); + await authorizeOnOpenProject(page, () => oauthRedirectReached); + + const { response, error } = await oauthRedirect; + const stoppedAt = new URL(page.url()); + expect( + error, + `the OpenProject OAuth round trip must return the browser to Nextcloud's ${OAUTH_REDIRECT_PATH}; it stopped at ${stoppedAt.host}${stoppedAt.pathname}` + ).toBeUndefined(); + const status = response.status(); + expect( + status, + `Nextcloud's ${OAUTH_REDIRECT_PATH} answered HTTP ${status}: redeeming the authorization code at OpenProject's /oauth/token failed (e.g. a trailing slash in openproject_instance_url makes the app request //oauth/token)` + ).toBeLessThan(500); + + await page.waitForURL(/\/settings\/user\/openproject/, { + waitUntil: "domcontentloaded", + timeout: resolveTimeout(60_000), + }); + await shared.dismissBlockingNextcloudModals(page, page); + await expect( + page.getByText(/connected as|verbunden als/i).first(), + "after the OAuth round trip the personal settings must show 'Connected as '; without it Nextcloud stored no usable OpenProject access token" + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + await expect( + disconnectButton(page), + "a connected user must be offered 'Disconnect from OpenProject'" + ).toBeVisible({ timeout: resolveTimeout(30_000) }); + } finally { + if (connectStarted) { + await openOpenProjectPersonalSettings(page) + .then(() => disconnectFromOpenProjectIfConnected(page)) + .catch(() => {}); + } + await page.close().catch(() => {}); + await context.close().catch(() => {}); + } +}); diff --git a/roles/web-app-nextcloud/files/ruby/addons/openproject/ensure_nextcloud_storage.rb b/roles/web-app-nextcloud/files/ruby/addons/openproject/ensure_nextcloud_storage.rb index 0d61e3887c..858d7f3ccd 100644 --- a/roles/web-app-nextcloud/files/ruby/addons/openproject/ensure_nextcloud_storage.rb +++ b/roles/web-app-nextcloud/files/ruby/addons/openproject/ensure_nextcloud_storage.rb @@ -1,12 +1,16 @@ # nocheck: mirrored-unit-test - runs in the OpenProject console against # Storages::NextcloudStorage; the model only exists once OpenProject has booted +# Param PROVISION_INPUT: defined ahead of this script on the same stdin, with the keys +# nextcloud_host, storage_name, nc_op_client_secret, rotate_op_secret, +# nc_oauth_client_id and nc_oauth_client_secret. require "json" -host = ENV.fetch("NEXTCLOUD_HOST").sub(%r{/+\z}, "") -name = ENV.fetch("STORAGE_NAME") -nc_client_id = ENV["NC_OAUTH_CLIENT_ID"].to_s.strip -nc_client_secret = ENV["NC_OAUTH_CLIENT_SECRET"].to_s.strip -nc_has_op_secret = ENV["NC_HAS_OP_SECRET"].to_s.strip +host = PROVISION_INPUT.fetch("nextcloud_host").sub(%r{/+\z}, "") +name = PROVISION_INPUT.fetch("storage_name") +nc_client_id = PROVISION_INPUT.fetch("nc_oauth_client_id").to_s.strip +nc_client_secret = PROVISION_INPUT.fetch("nc_oauth_client_secret").to_s.strip +nc_op_client_secret = PROVISION_INPUT.fetch("nc_op_client_secret").to_s.strip +rotate_op_secret = PROVISION_INPUT.fetch("rotate_op_secret") == true admins = User.where(admin: true) creator = @@ -34,7 +38,7 @@ end application = storage.oauth_application op_client_secret = nil -if application && nc_client_id.empty? && nc_has_op_secret.empty? +if application && nc_client_id.empty? && nc_op_client_secret.empty? application.destroy storage.reload application = nil @@ -63,8 +67,15 @@ if application.nil? application = result.is_a?(ServiceResult) ? result.result : result op_client_secret = application.plaintext_secret if application.respond_to?(:plaintext_secret) storage.reload +elsif rotate_op_secret || nc_op_client_secret.empty? || !application.secret_matches?(nc_op_client_secret) + application.renew_secret + application.save! + op_client_secret = application.plaintext_secret || application.secret + storage.reload end +application.update!(redirect_uri: redirect_uri) if application.redirect_uri != redirect_uri + if nc_client_id.present? && nc_client_secret.present? client = storage.oauth_client if client.nil? || client.client_id != nc_client_id @@ -84,5 +95,5 @@ puts JSON.generate( openproject_client_id: storage.oauth_application&.uid, openproject_client_secret: op_client_secret, nc_oauth_client_id: storage.oauth_client&.client_id, - oauth_application_created: !op_client_secret.nil? + oauth_application_secret_issued: !op_client_secret.nil? ) diff --git a/roles/web-app-nextcloud/files/sql/addons/openproject/coupling.sql b/roles/web-app-nextcloud/files/sql/addons/openproject/coupling.sql new file mode 100644 index 0000000000..1896301d43 --- /dev/null +++ b/roles/web-app-nextcloud/files/sql/addons/openproject/coupling.sql @@ -0,0 +1,22 @@ +SELECT + storage.id, + storage.created_at, + storage.name, + storage.host, + application.uid, + application.updated_at, + client.client_id, + client.updated_at +FROM storages AS storage +LEFT JOIN oauth_applications AS application + ON + storage.id = application.integration_id + AND application.integration_type LIKE 'Storages::%' +LEFT JOIN oauth_clients AS client + ON + storage.id = client.integration_id + AND client.integration_type LIKE 'Storages::%' +WHERE + storage.provider_type = 'Storages::NextcloudStorage' + AND (rtrim(storage.host, '/') = %(host)s OR storage.name = %(name)s) +ORDER BY storage.id, application.id, client.id; diff --git a/roles/web-app-nextcloud/filter_plugins/nextcloud_install.py b/roles/web-app-nextcloud/filter_plugins/nextcloud_install.py index 80d1830799..2426fecd6f 100644 --- a/roles/web-app-nextcloud/filter_plugins/nextcloud_install.py +++ b/roles/web-app-nextcloud/filter_plugins/nextcloud_install.py @@ -1,11 +1,18 @@ """Classify the result of `occ app:install` so the playbook can treat -version-incompatible plugins as warnings instead of failures. +version-incompatible plugins as warnings instead of failures, and gate and +join an `occ app:install` that runs in the background. """ +import json + _INCOMPAT_MARKER = "is not compatible with this version of the server" _ALREADY_MARKER = "already installed" _UNAVAILABLE_MARKER = "was not found on the appstore" _TRANSPORT_MARKERS = ("cURL error", "ConnectException") +_TIMEOUT_RC = 124 +_SIGNAL_RCS = range(129, 193) +_MIGRATION_STATE_MARKER = "MIGRATION_STATE " +_JOB_FILE_GRACE_ATTEMPTS = 15 def nextcloud_install_status(install_result): @@ -51,6 +58,85 @@ def nextcloud_install_status(install_result): } +def nextcloud_background_gate(gate_result): + """Decide whether other occ calls may run next to a background `occ app:install`. + + Args: + gate_result: registered result of the gate shell, polled in an + ``until`` loop so it carries ``attempts``. Its first stdout line is + the async job file of the install (one JSON object, holding + ``started`` while the job runs and the module result once it ended, + empty until async_wrapper wrote it); a later line holds the + ``MIGRATION_STATE`` JSON that files/php/utils/migration_state.php + prints with the ``migrated`` and ``available`` versions of the app. + + Returns: + 'open' - the job ended with an occ exit code, or the schema of the app + is in place: at least one migration lies on disk and the + versions on disk are exactly the versions recorded in + oc_migrations + 'killed' - the job ended without an occ exit code (see + ``nextcloud_background_lost``), or its job file is still + missing after the grace attempts + 'wait' - neither yet + """ + if not isinstance(gate_result, dict): + raise TypeError( + "nextcloud_background_gate expects a registered shell/command result dict" + ) + + lines = (gate_result.get("stdout") or "").splitlines() + if not lines or not lines[0].strip(): + return ( + "wait" if gate_result["attempts"] <= _JOB_FILE_GRACE_ATTEMPTS else "killed" + ) + job = json.loads(lines[0]) + if not isinstance(job, dict): + raise TypeError( + "nextcloud_background_gate expects the async job file on the first stdout line" + ) + if "started" not in job: + return "killed" if nextcloud_background_lost(job) else "open" + + if gate_result.get("rc") != 0: + return "wait" + states = [ + json.loads(line[len(_MIGRATION_STATE_MARKER) :]) + for line in lines[1:] + if line.startswith(_MIGRATION_STATE_MARKER) + ] + if len(states) != 1: + return "wait" + available = set(states[0]["available"]) + settled = bool(available) and available == set(states[0]["migrated"]) + return "open" if settled else "wait" + + +def nextcloud_background_lost(job_result): + """Tell whether a background `occ app:install` ended without an occ exit code. + + Args: + job_result: `async_status` result or async job file content of the + background install. + + Returns: + True when the job carries no exit code (still running, killed by the + async timeout, crashed), a signal killed its shell (negative code), a + timeout killed its exec (124) or a signal ended the exec (129-192, 137 + for the KILL after the timeout). + """ + if not isinstance(job_result, dict): + raise TypeError( + "nextcloud_background_lost expects a registered async_status result dict" + ) + rc = job_result.get("rc") + return rc is None or rc < 0 or rc == _TIMEOUT_RC or rc in _SIGNAL_RCS + + class FilterModule: def filters(self): - return {"nextcloud_install_status": nextcloud_install_status} + return { + "nextcloud_install_status": nextcloud_install_status, + "nextcloud_background_gate": nextcloud_background_gate, + "nextcloud_background_lost": nextcloud_background_lost, + } diff --git a/roles/web-app-nextcloud/filter_plugins/nextcloud_oauth_client.py b/roles/web-app-nextcloud/filter_plugins/nextcloud_oauth_client.py new file mode 100644 index 0000000000..9bc3415a2b --- /dev/null +++ b/roles/web-app-nextcloud/filter_plugins/nextcloud_oauth_client.py @@ -0,0 +1,44 @@ +import json + +from ansible.errors import AnsibleFilterError + +_MARKER = "NC_OAUTH_CLIENT " +_ACTIONS = ("created", "redirect_fixed", "unchanged") + + +def nextcloud_oauth_client_state(stdout): + """Read the state files/php/addons/openproject/ensure_nc_client.php prints. + + Args: + stdout: the helper's stdout; PHP notices may surround its marker line. + + Returns: + the marker's JSON object (action, id, client_id, removed, and + client_secret when the client was created) plus ``changed``, true + unless the client was left as it was and no stale client was removed. + + Raises: + AnsibleFilterError: when the stdout holds no or several marker lines, + or an action the helper does not print. + """ + states = [ + json.loads(line[len(_MARKER) :]) + for line in str(stdout).splitlines() + if line.startswith(_MARKER) + ] + if len(states) != 1: + raise AnsibleFilterError( + f"nextcloud_oauth_client_state expects one {_MARKER.strip()} line, got {len(states)}" + ) + state = states[0] + if state.get("action") not in _ACTIONS: + raise AnsibleFilterError( + f"nextcloud_oauth_client_state: unknown action {state.get('action')!r}" + ) + state["changed"] = state["action"] != "unchanged" or state.get("removed", 0) > 0 + return state + + +class FilterModule: + def filters(self): + return {"nextcloud_oauth_client_state": nextcloud_oauth_client_state} diff --git a/roles/web-app-nextcloud/filter_plugins/nextcloud_plugin_plan.py b/roles/web-app-nextcloud/filter_plugins/nextcloud_plugin_plan.py index 125cdb1985..9e1811f162 100644 --- a/roles/web-app-nextcloud/filter_plugins/nextcloud_plugin_plan.py +++ b/roles/web-app-nextcloud/filter_plugins/nextcloud_plugin_plan.py @@ -25,10 +25,12 @@ def nextcloud_plugin_plan(plugin_items, app_list): Returns: dict of app ids: - disable - wanted off and enabled right now - install - wanted on and not installed, or shipped as a pinned archive - enable - wanted on, installed, not enabled - configure - wanted on and already enabled + disable - wanted off and enabled right now + install - wanted on and not installed, or shipped as a pinned archive + background - wanted on, not installed, marked ``background_install``, + neither pinned nor mandatory; disjoint from ``install`` + enable - wanted on, installed, not enabled + configure - wanted on and already enabled """ enabled_now = set((app_list or {}).get("enabled") or {}) installed = enabled_now | set((app_list or {}).get("disabled") or {}) @@ -46,15 +48,23 @@ def nextcloud_plugin_plan(plugin_items, app_list): plan = { "disable": [app for app, on in wanted.items() if not on and app in enabled_now], "install": [], + "background": [], "enable": [], "configure": [], } for item in plugin_items: key = item["key"] + plugin = item["value"] if not wanted.get(key): continue - if key not in installed or _setting(item["value"], "archive", ""): + if _setting(plugin, "archive", ""): plan["install"].append(key) + elif key not in installed: + background = _flag(_setting(plugin, "background_install", False)) + mandatory = _flag(_setting(plugin, "mandatory", False)) + plan["background" if background and not mandatory else "install"].append( + key + ) elif key not in enabled_now: plan["enable"].append(key) else: diff --git a/roles/web-app-nextcloud/meta/addons/bbb.yml b/roles/web-app-nextcloud/meta/addons/bbb.yml index cf8956fa91..662805ccf5 100644 --- a/roles/web-app-nextcloud/meta/addons/bbb.yml +++ b/roles/web-app-nextcloud/meta/addons/bbb.yml @@ -16,4 +16,5 @@ config: configvalue: "{{ lookup('config','web-app-bigbluebutton', 'secrets.credentials.shared_secret', '') }}" - appid: "bbb" configkey: "api.url" - configvalue: "{{ lookup('tls', 'web-app-bigbluebutton', 'url.base') }}{{ lookup('config', 'web-app-bigbluebutton', 'services.bigbluebutton.api_suffix','') }}" + configvalue: "{{ ([lookup('tls', 'web-app-bigbluebutton', 'url.base'), lookup('config', 'web-app-bigbluebutton', 'services.bigbluebutton.api_suffix', '')] | + url_join) ~ '/' }}" diff --git a/roles/web-app-nextcloud/meta/addons/integration_discourse.yml b/roles/web-app-nextcloud/meta/addons/integration_discourse.yml index f9f5bf5f2a..b551a19148 100644 --- a/roles/web-app-nextcloud/meta/addons/integration_discourse.yml +++ b/roles/web-app-nextcloud/meta/addons/integration_discourse.yml @@ -9,4 +9,4 @@ config: plugin_configuration: - appid: "integration_discourse" configkey: "url" - configvalue: "{{ lookup('tls', 'web-app-discourse', 'url.base') }}" + configvalue: "{{ lookup('tls', 'web-app-discourse', 'url.origin') }}" diff --git a/roles/web-app-nextcloud/meta/addons/integration_gitlab.yml b/roles/web-app-nextcloud/meta/addons/integration_gitlab.yml index 39bde68818..1f12b37537 100644 --- a/roles/web-app-nextcloud/meta/addons/integration_gitlab.yml +++ b/roles/web-app-nextcloud/meta/addons/integration_gitlab.yml @@ -9,4 +9,4 @@ config: plugin_configuration: - appid: "integration_gitlab" configkey: "oauth_instance_url" - configvalue: "{{ lookup('tls', 'web-app-gitlab', 'url.base') }}" + configvalue: "{{ lookup('tls', 'web-app-gitlab', 'url.origin') }}" diff --git a/roles/web-app-nextcloud/meta/addons/integration_mastodon.yml b/roles/web-app-nextcloud/meta/addons/integration_mastodon.yml index 50aa6a16f1..531babaff0 100644 --- a/roles/web-app-nextcloud/meta/addons/integration_mastodon.yml +++ b/roles/web-app-nextcloud/meta/addons/integration_mastodon.yml @@ -9,4 +9,4 @@ config: plugin_configuration: - appid: "integration_mastodon" configkey: "oauth_instance_url" - configvalue: "{{ lookup('tls', 'web-app-mastodon', 'url.base') }}" + configvalue: "{{ lookup('tls', 'web-app-mastodon', 'url.origin') }}" diff --git a/roles/web-app-nextcloud/meta/addons/integration_mattermost.yml b/roles/web-app-nextcloud/meta/addons/integration_mattermost.yml index a48a906c21..d640499771 100644 --- a/roles/web-app-nextcloud/meta/addons/integration_mattermost.yml +++ b/roles/web-app-nextcloud/meta/addons/integration_mattermost.yml @@ -9,4 +9,4 @@ config: plugin_configuration: - appid: "integration_mattermost" configkey: "url" - configvalue: "{{ lookup('tls', 'web-app-mattermost', 'url.base') }}" + configvalue: "{{ lookup('tls', 'web-app-mattermost', 'url.origin') }}" diff --git a/roles/web-app-nextcloud/meta/addons/integration_moodle.yml b/roles/web-app-nextcloud/meta/addons/integration_moodle.yml index 3d9f258de4..b8af1249e3 100644 --- a/roles/web-app-nextcloud/meta/addons/integration_moodle.yml +++ b/roles/web-app-nextcloud/meta/addons/integration_moodle.yml @@ -9,4 +9,4 @@ config: plugin_configuration: - appid: "integration_moodle" configkey: "url" - configvalue: "{{ lookup('tls', 'web-app-moodle', 'url.base') }}" + configvalue: "{{ lookup('tls', 'web-app-moodle', 'url.origin') }}" diff --git a/roles/web-app-nextcloud/meta/addons/integration_openai.yml b/roles/web-app-nextcloud/meta/addons/integration_openai.yml index ebca903814..b676256acf 100644 --- a/roles/web-app-nextcloud/meta/addons/integration_openai.yml +++ b/roles/web-app-nextcloud/meta/addons/integration_openai.yml @@ -12,5 +12,4 @@ 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 (LITELLM_BASE_LOCAL_URL - ~ '/v1') }}" + configvalue: "{{ (lookup('tls', 'web-app-openwebui', 'url.origin') ~ '/api') if ('web-app-openwebui' in group_names) else (LITELLM_BASE_LOCAL_URL ~ '/v1') }}" diff --git a/roles/web-app-nextcloud/meta/addons/integration_openproject.yml b/roles/web-app-nextcloud/meta/addons/integration_openproject.yml index 348c601c12..05fa6ad404 100644 --- a/roles/web-app-nextcloud/meta/addons/integration_openproject.yml +++ b/roles/web-app-nextcloud/meta/addons/integration_openproject.yml @@ -6,7 +6,11 @@ source: upstream bridges: - openproject config: + rotate_oauth_client: false plugin_configuration: - appid: "integration_openproject" configkey: "openproject_instance_url" - configvalue: "{{ lookup('tls', 'web-app-openproject', 'url.base') }}" + configvalue: "{{ NEXTCLOUD_OPENPROJECT_URL }}" + - appid: "integration_openproject" + configkey: "fresh_project_folder_setup" + configvalue: "0" diff --git a/roles/web-app-nextcloud/meta/addons/integration_suitecrm.yml b/roles/web-app-nextcloud/meta/addons/integration_suitecrm.yml index 3c0f4ad3db..f768daed2d 100644 --- a/roles/web-app-nextcloud/meta/addons/integration_suitecrm.yml +++ b/roles/web-app-nextcloud/meta/addons/integration_suitecrm.yml @@ -9,4 +9,4 @@ config: plugin_configuration: - appid: "integration_suitecrm" configkey: "url" - configvalue: "{{ lookup('tls', 'web-app-suitecrm', 'url.base') }}" + configvalue: "{{ lookup('tls', 'web-app-suitecrm', 'url.origin') }}" diff --git a/roles/web-app-nextcloud/meta/addons/integration_zammad.yml b/roles/web-app-nextcloud/meta/addons/integration_zammad.yml index d28691d0cf..368cf43a26 100644 --- a/roles/web-app-nextcloud/meta/addons/integration_zammad.yml +++ b/roles/web-app-nextcloud/meta/addons/integration_zammad.yml @@ -9,4 +9,4 @@ config: plugin_configuration: - appid: "integration_zammad" configkey: "oauth_instance_url" - configvalue: "{{ lookup('tls', 'web-app-zammad', 'url.base') }}" + configvalue: "{{ lookup('tls', 'web-app-zammad', 'url.origin') }}" diff --git a/roles/web-app-nextcloud/meta/addons/recognize.yml b/roles/web-app-nextcloud/meta/addons/recognize.yml index 352ca2a594..a559169355 100644 --- a/roles/web-app-nextcloud/meta/addons/recognize.yml +++ b/roles/web-app-nextcloud/meta/addons/recognize.yml @@ -3,3 +3,5 @@ enabled: true required: false mechanism: plugin source: upstream +config: + background_install: true diff --git a/roles/web-app-nextcloud/meta/addons/richdocuments.yml b/roles/web-app-nextcloud/meta/addons/richdocuments.yml index 9ee7d15b9b..9bc079f5a8 100644 --- a/roles/web-app-nextcloud/meta/addons/richdocuments.yml +++ b/roles/web-app-nextcloud/meta/addons/richdocuments.yml @@ -16,7 +16,7 @@ config: configvalue: "{{ NEXTCLOUD_COLLABORA_URL }}" - appid: "richdocuments" configkey: "public_wopi_url" - configvalue: "{{ NEXTCLOUD_COLLABORA_URL }}" + configvalue: "{{ lookup('tls', 'web-svc-collabora', 'url.origin') }}" - appid: "richdocuments" configkey: "disable_certificate_verification" configvalue: 0 diff --git a/roles/web-app-nextcloud/meta/addons/xwiki.yml b/roles/web-app-nextcloud/meta/addons/xwiki.yml index d72abe33e3..efd7dbf572 100644 --- a/roles/web-app-nextcloud/meta/addons/xwiki.yml +++ b/roles/web-app-nextcloud/meta/addons/xwiki.yml @@ -15,4 +15,4 @@ config: configkey: "instances" configvalue: - name: "XWiki" - url: "{{ lookup('tls', 'web-app-xwiki', 'url.base') }}" + url: "{{ lookup('tls', 'web-app-xwiki', 'url.origin') }}" diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin.yml index 8fcaff427d..2a12650297 100644 --- a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin.yml +++ b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin.yml @@ -9,6 +9,7 @@ ansible.builtin.set_fact: nextcloud_plugin_plan: "{{ NEXTCLOUD_PLUGIN_ITEMS | nextcloud_plugin_plan(nextcloud_app_list.stdout | from_json) }}" nextcloud_plugin_configure_keys: [] + nextcloud_plugin_background_jobs: [] - name: "🔴 Disable the plugins that end up disabled" ansible.builtin.command: @@ -16,9 +17,44 @@ when: nextcloud_plugin_plan.disable | length > 0 changed_when: true -- name: "📦 Install and enable the plugins Nextcloud lacks" - ansible.builtin.include_tasks: 06_plugin/01_install.yml - loop: "{{ NEXTCLOUD_PLUGIN_ITEMS | selectattr('key', 'in', nextcloud_plugin_plan.install) | list }}" +- name: "📦 Install the plugins Nextcloud lacks, the background ones beside the loop" + block: + - name: "🛫 Start the installs that run beside the install loop" + ansible.builtin.include_tasks: 06_plugin/01_background.yml + loop: "{{ NEXTCLOUD_PLUGIN_ITEMS | selectattr('key', 'in', nextcloud_plugin_plan.background) | list }}" + loop_control: + loop_var: plugin_item + label: "{{ plugin_item.key }}" + vars: + plugin_key: "{{ plugin_item.key }}" + + - name: "📦 Install and enable the plugins Nextcloud lacks" + ansible.builtin.include_tasks: 06_plugin/02_install.yml + loop: "{{ NEXTCLOUD_PLUGIN_ITEMS | selectattr('key', 'in', nextcloud_plugin_plan.install) | list }}" + 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 }}" + always: + - name: "⏳ Join the background installs" + ansible.builtin.async_status: + jid: "{{ item.jid }}" + loop: "{{ nextcloud_plugin_background_jobs }}" + loop_control: + label: "{{ item.key }}" + register: nextcloud_plugin_background_result + until: nextcloud_plugin_background_result is finished + retries: "{{ ((NEXTCLOUD_PLUGIN_BACKGROUND_ASYNC_TIME | int) / 5) | round(0, 'ceil') | int }}" + delay: 5 + changed_when: (nextcloud_plugin_background_result | nextcloud_install_status).changed + failed_when: nextcloud_plugin_background_result | nextcloud_background_lost + +- name: "📦 Enable and configure the plugins installed in the background" + ansible.builtin.include_tasks: 06_plugin/02_install.yml + loop: "{{ NEXTCLOUD_PLUGIN_ITEMS | selectattr('key', 'in', nextcloud_plugin_plan.background) | list }}" loop_control: loop_var: plugin_item label: "{{ plugin_item.key }}" @@ -28,7 +64,7 @@ plugin_value: "{{ plugin_item.value }}" - name: "🟢 Enable the installed plugins Nextcloud keeps disabled" - ansible.builtin.include_tasks: 06_plugin/02_enable.yml + ansible.builtin.include_tasks: 06_plugin/03_enable.yml loop: "{{ NEXTCLOUD_PLUGIN_ITEMS | selectattr('key', 'in', nextcloud_plugin_plan.enable) | list }}" loop_control: loop_var: plugin_item @@ -43,5 +79,5 @@ nextcloud_plugin_configure_keys: "{{ nextcloud_plugin_configure_keys + nextcloud_plugin_plan.configure }}" - name: "🔧 Configure every queued plugin in one batch" - ansible.builtin.include_tasks: 06_plugin/03_configure.yml + ansible.builtin.include_tasks: 06_plugin/04_configure.yml when: nextcloud_plugin_configure_keys | length > 0 diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/01_background.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/01_background.yml new file mode 100644 index 0000000000..f318c75ac1 --- /dev/null +++ b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/01_background.yml @@ -0,0 +1,35 @@ +--- +- name: "📦 Install {{ plugin_key }} nextcloud plugin in the background" + ansible.builtin.shell: | + {{ NEXTCLOUD_DOCKER_EXEC_OCC }} config:app:delete settings appstore-fetcher-lastFailure >/dev/null 2>&1 || true + {{ NEXTCLOUD_DOCKER_EXEC_OCC }} app:install {{ plugin_key | quote }} + args: + executable: /bin/bash + register: nextcloud_plugin_background_job + changed_when: false + # rationale: async; the gate below holds every later occ call until this install has applied its schema, and 06_plugin.yml joins the job before 02_install.yml enables and configures the plugin + async: "{{ NEXTCLOUD_PLUGIN_BACKGROUND_ASYNC_TIME }}" + poll: 0 + +- name: "🧮 Queue {{ plugin_key }} for the join after the install loop" + ansible.builtin.set_fact: + nextcloud_plugin_background_jobs: >- + {{ nextcloud_plugin_background_jobs + + [{'key': plugin_key, 'jid': nextcloud_plugin_background_job.ansible_job_id}] }} + +- name: "⏳ Hold the other installs until {{ plugin_key }} has applied its schema" + ansible.builtin.shell: + cmd: | + cat {{ nextcloud_plugin_background_job.results_file | quote }} + echo + {{ NEXTCLOUD_DOCKER_EXEC_INTERACTIVE }} php -- {{ NEXTCLOUD_DOCKER_WORK_DIRECTORY | quote }} {{ plugin_key | quote }} + stdin: "{{ lookup('file', 'php/utils/migration_state.php') }}" + executable: /bin/bash + environment: + CONTAINER_EXEC_TIMEOUT: "{{ lookup('timeout', 60) | int }}" + register: nextcloud_plugin_background_gate + until: (nextcloud_plugin_background_gate | nextcloud_background_gate) != 'wait' + retries: "{{ ((NEXTCLOUD_PLUGIN_BACKGROUND_ASYNC_TIME | int) / 2) | round(0, 'ceil') | int }}" + delay: 2 + changed_when: false + failed_when: (nextcloud_plugin_background_gate | nextcloud_background_gate) != 'open' 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/02_install.yml similarity index 99% rename from roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/01_install.yml rename to roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/02_install.yml index db1785ee09..9f7f8222d0 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/02_install.yml @@ -79,5 +79,5 @@ (install_result | nextcloud_install_status).incompatible or (install_result | nextcloud_install_status).unavailable -- include_tasks: 02_enable.yml +- include_tasks: 03_enable.yml when: (install_result | nextcloud_install_status).runnable diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/02_enable.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/03_enable.yml similarity index 100% rename from roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/02_enable.yml rename to roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/03_enable.yml diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/03_configure.yml b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/04_configure.yml similarity index 100% rename from roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/03_configure.yml rename to roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/04_configure.yml diff --git a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md index ef90610062..5844edeffb 100644 --- a/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md +++ b/roles/web-app-nextcloud/tasks/02_manager_ops/06_plugin/README.md @@ -15,25 +15,46 @@ The pipeline owns three responsibilities for one Nextcloud plugin (app): | Plan list | Plugins | Entered at | |---|---|---| | `disable` | wanted off and enabled right now | one `occ app:disable` for all of them | -| `install` | wanted on and not installed, or pinned through `archive` | [01_install.yml](./01_install.yml) | -| `enable` | wanted on, installed, not enabled | [02_enable.yml](./02_enable.yml) | -| `configure` | wanted on and already enabled | [03_configure.yml](./03_configure.yml) | +| `install` | wanted on and not installed, or pinned through `archive` | [02_install.yml](./02_install.yml) | +| `background` | wanted on, not installed, marked `background_install`, neither pinned nor `mandatory` | [01_background.yml](./01_background.yml), then [02_install.yml](./02_install.yml) after the join | +| `enable` | wanted on, installed, not enabled | [03_enable.yml](./03_enable.yml) | +| `configure` | wanted on and already enabled | [04_configure.yml](./04_configure.yml) | The wanted state replays the addons in order: an enabled plugin turns its `incompatible_plugins` off and itself on, a plugin marked `enabled: false` turns itself off, and a later entry wins. +## Background installs + +An addon MAY set `config.background_install: true`. `recognize` sets it. + +1. After the `disable` step, [01_background.yml](./01_background.yml) starts `occ app:install` for each such plugin as an async job, one plugin at a time. +2. The gate prints the async job file (`results_file` of the job) and runs [files/php/utils/migration_state.php](../../../files/php/utils/migration_state.php) in the container, which prints the versions `oc_migrations` records for the app and the versions its migration folder holds. The filter `nextcloud_background_gate` maps each poll to a state: + + | State | Poll result | Gate | + |---|---|---| + | `open` | the job ended with an occ exit code, or the folder holds at least one version and exactly the recorded ones | the play continues | + | `killed` | the job ended without an occ exit code, with a negative one, with `124` or with `129`-`192`, or its job file is still missing after 15 polls | the task fails | + | `wait` | anything else, including a probe that fails or that `CONTAINER_EXEC_TIMEOUT` (60 s for this task) cuts off | the task polls again, and fails after `NEXTCLOUD_PLUGIN_BACKGROUND_ASYNC_TIME` | + + The gate does not use `occ migrations:status`: Nextcloud registers it only with `debug` on. +3. The install loop runs while the job finishes. +4. The `always` section of the install block joins every job with `async_status`. The filter `nextcloud_background_lost` fails the join on the exit codes of the `killed` state. +5. Each joined plugin runs [02_install.yml](./02_install.yml): `occ app:install` answers `already installed` once the job placed the app, so the stage enables and configures it. When the job failed before it placed the app, the stage installs it with its own retries. + +The job runs in every mode, `ASYNC_ENABLED` included. Its limit `NEXTCLOUD_PLUGIN_BACKGROUND_ASYNC_TIME` in [vars/main.yml](../../../vars/main.yml) is 7 days, the default of `SYS_TIMEOUT_CONTAINER_EXEC`. + ## Pipeline stages Each `tasks/02_manager_ops/06_plugin/.yml` file owns exactly one OCC stage and one decision about whether to continue. | File | Stage | OCC command | Continues to next stage when | |---|---|---|---| -| [01_install.yml](./01_install.yml) | install | `occ app:install` | install result is `runnable` (success or already installed) | -| [02_enable.yml](./02_enable.yml) | enable | `occ app:enable` | enable result is not flagged `incompatible`; the plugin is then queued for the configure stage | -| [03_configure.yml](./03_configure.yml) | configure | one `occ config:list`, then `occ config:app:set` for the values that differ, plus optional hook | (terminal stage) | +| [02_install.yml](./02_install.yml) | install | `occ app:install` | install result is `runnable` (success or already installed) | +| [03_enable.yml](./03_enable.yml) | enable | `occ app:enable` | enable result is not flagged `incompatible`; the plugin is then queued for the configure stage | +| [04_configure.yml](./04_configure.yml) | configure | one `occ config:list`, then `occ config:app:set` for the values that differ, plus optional hook | (terminal stage) | ## Configure stage -[03_configure.yml](./03_configure.yml) runs once for every queued plugin: first the plugins the install loop enabled, then those the enable loop enabled, then those of the `configure` plan list. +[04_configure.yml](./04_configure.yml) runs once for every queued plugin: first the plugins the install loop enabled, then the background installs, then those the enable loop enabled, then those of the `configure` plan list. 1. It loads the addon spec of every queued plugin. 2. It reads `occ config:list` once and keeps an entry only when Nextcloud does not already hold the exact value `occ config:app:set` would store. Entries with a `type`, sensitive values that `config:list` masks, booleans, floats and structured values are always kept. @@ -51,27 +72,27 @@ A plugin MAY ship an appstore release that lags the pinned Nextcloud server majo In that case OCC emits the marker string `is not compatible with this version of the server` and exits non-zero. The pipeline MUST treat this as a non-fatal condition: -- `01_install.yml` accepts the install as terminal so the retry loop ends immediately. -- `01_install.yml` and `02_enable.yml` each emit a `debug` warning that the plugin will be skipped for this run. +- `02_install.yml` accepts the install as terminal so the retry loop ends immediately. +- `02_install.yml` and `03_enable.yml` each emit a `debug` warning that the plugin will be skipped for this run. - The next stage in the pipeline MUST NOT execute when the previous stage classified the plugin as `incompatible`. Once a compatible release ships, the next deploy run will install + enable + configure the plugin automatically without operator intervention. ## Mandatory plugins -A plugin entry MAY set `mandatory: true`. This inverts the tolerance above: when the plugin is `enabled` for the current deployment but its install result is not `runnable` (incompatible with the pinned server major, or unavailable on the appstore), [01_install.yml](./01_install.yml) aborts the deployment with `ansible.builtin.fail` instead of emitting the skip warning. +A plugin entry MAY set `mandatory: true`. This inverts the tolerance above: when the plugin is `enabled` for the current deployment but its install result is not `runnable` (incompatible with the pinned server major, or unavailable on the appstore), [02_install.yml](./02_install.yml) aborts the deployment with `ansible.builtin.fail` instead of emitting the skip warning. The OIDC login entry points (`oidc_login`, `sociallogin`, `user_oidc`) are mandatory because they gate SSO login: when one of them is the selected flavor and the system hides the native login form, an un-installed OIDC app leaves the instance with no usable login path. Failing at install time surfaces the version-pin mismatch immediately rather than as a downstream login timeout in the Playwright e2e suite. ## Adding configuration for a plugin -Per-plugin configuration is keyed by the addon id and rendered by [03_configure.yml](./03_configure.yml). +Per-plugin configuration is keyed by the addon id and rendered by [04_configure.yml](./04_configure.yml). A new plugin requires no changes here when its addon spec and optional hook file are present at the conventional paths. - **Configuration keys (optional).** Add a `config.plugin_configuration` list to `meta/addons/.yml`. Each list item MUST contain `appid`, `configkey`, and `configvalue`. - `03_configure.yml` loads the addon spec and invokes `occ config:app:set` for every entry whose value Nextcloud does not hold yet. + `04_configure.yml` loads the addon spec and invokes `occ config:app:set` for every entry whose value Nextcloud does not hold yet. - **Custom logic (optional).** Create `tasks/addons/.yml`. The hook runs after the configuration of every queued plugin and MAY perform plugin-specific provisioning such as LDAP wiring or REST calls against the live container. @@ -82,10 +103,10 @@ Missing files MUST be tolerated; the corresponding step skips cleanly. ## Mutually exclusive plugins An addon under `meta/addons/` MAY declare an `incompatible_plugins` list in its `config:`. -The plan's `disable` list carries every listed plugin that ends up off and still runs, and [01_install.yml](./01_install.yml) disables the listed plugins again before an install attempt. +The plan's `disable` list carries every listed plugin that ends up off and still runs, and [02_install.yml](./02_install.yml) disables the listed plugins again before an install attempt. This guarantees that mutually exclusive integrations such as the OIDC entry points (`oidc_login`, `sociallogin`, `user_oidc`) and the document-editing surfaces (`onlyoffice`, `richdocuments`, `fileslibreofficeedit`) cannot accidentally coexist on the same instance. ## Entry point [02_manager_ops.yml](../../02_manager_ops.yml) includes [06_plugin.yml](../06_plugin.yml) once. -It loops over the `NEXTCLOUD_PLUGIN_ITEMS` of the `install` and `enable` plan lists and unpacks the loop variable `plugin_item` into `plugin_key` (the OCC app name) and `plugin_value` (its meta entry), then includes the configure stage once for the queue `nextcloud_plugin_configure_keys`. +It loops over the `NEXTCLOUD_PLUGIN_ITEMS` of the `background`, `install` and `enable` plan lists and unpacks the loop variable `plugin_item` into `plugin_key` (the OCC app name) and `plugin_value` (its meta entry), then includes the configure stage once for the queue `nextcloud_plugin_configure_keys`. diff --git a/roles/web-app-nextcloud/tasks/addons/integration_gitlab.yml b/roles/web-app-nextcloud/tasks/addons/integration_gitlab.yml index 3bec48c98f..fbb1e629d8 100644 --- a/roles/web-app-nextcloud/tasks/addons/integration_gitlab.yml +++ b/roles/web-app-nextcloud/tasks/addons/integration_gitlab.yml @@ -1,7 +1,7 @@ --- - name: 🔍 Resolve GitLab integration provisioning facts set_fact: - nextcloud_gl_nc_base_url: "{{ lookup('tls', 'web-app-nextcloud', 'url.base') | regex_replace('/$', '') }}" + nextcloud_gl_nc_base_url: "{{ lookup('tls', 'web-app-nextcloud', 'url.origin') }}" changed_when: false - name: 📖 Read persisted integration_gitlab OAuth client id diff --git a/roles/web-app-nextcloud/tasks/addons/integration_mattermost.yml b/roles/web-app-nextcloud/tasks/addons/integration_mattermost.yml index d617e9cf48..28ab01e6e0 100644 --- a/roles/web-app-nextcloud/tasks/addons/integration_mattermost.yml +++ b/roles/web-app-nextcloud/tasks/addons/integration_mattermost.yml @@ -5,7 +5,7 @@ # partner and wires the returned credentials into Nextcloud. - name: 🔍 Resolve Mattermost partner coupling facts set_fact: - nextcloud_mm_base_url: "{{ lookup('tls', 'web-app-mattermost', 'url.base') }}" + nextcloud_mm_base_url: "{{ lookup('tls', 'web-app-mattermost', 'url.origin') }}" nextcloud_mm_local_url: "http://{{ DOCKER_REACH_HOST }}:{{ lookup('config', 'web-app-mattermost', 'services.mattermost.ports.local.http') }}" nextcloud_mm_redirect_path: "/apps/integration_mattermost/oauth-redirect" nextcloud_mm_exec_chdir: "{{ lookup('container', 'web-app-mattermost', 'directories.instance') if IS_COMPOSE_MODE else omit }}" diff --git a/roles/web-app-nextcloud/tasks/addons/integration_openproject.yml b/roles/web-app-nextcloud/tasks/addons/integration_openproject.yml index 9043c6e26c..825ac7154c 100644 --- a/roles/web-app-nextcloud/tasks/addons/integration_openproject.yml +++ b/roles/web-app-nextcloud/tasks/addons/integration_openproject.yml @@ -1,37 +1,51 @@ --- -- name: 🔍 Resolve expected OpenProject base URL for the integration +- name: 🔍 Resolve the name of the Nextcloud storage in OpenProject set_fact: - nextcloud_op_expected_url: "{{ lookup('tls', 'web-app-openproject', 'url.base') | trim }}" nextcloud_op_storage_name: "Nextcloud ({{ lookup('domain', 'web-app-nextcloud') }})" changed_when: false -- name: 📖 Read persisted integration_openproject OpenProject OAuth client id - shell: > - {{ NEXTCLOUD_DOCKER_EXEC_OCC }} config:app:get integration_openproject openproject_client_id - register: nextcloud_op_client_id_current - changed_when: false - failed_when: false +- name: 📖 Read the OpenProject coupling state of both sides + include_tasks: integration_openproject_state.yml -- name: 📖 Read persisted integration_openproject Nextcloud OAuth client id - shell: > - {{ NEXTCLOUD_DOCKER_EXEC_OCC }} config:app:get integration_openproject nc_oauth_client_id - register: nextcloud_op_nc_client_current - changed_when: false - failed_when: false +- name: 🔍 Find the stamp of the last OpenProject provisioning + ansible.builtin.stat: + path: "{{ NEXTCLOUD_OPENPROJECT_STAMP_FILE }}" + register: nextcloud_op_stamp_file + when: IS_STACK_HOST | bool -- name: 📖 Read persisted integration_openproject OpenProject OAuth client secret - shell: > - {{ NEXTCLOUD_DOCKER_EXEC_OCC }} config:app:get integration_openproject openproject_client_secret - register: nextcloud_op_client_secret_current - changed_when: false - failed_when: false - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" +- name: 📖 Read the stamp of the last OpenProject provisioning + ansible.builtin.slurp: + src: "{{ NEXTCLOUD_OPENPROJECT_STAMP_FILE }}" + register: nextcloud_op_stamp + when: + - IS_STACK_HOST | bool + - nextcloud_op_stamp_file.stat.exists -- name: 🔧 Provision the bidirectional OpenProject <-> Nextcloud OAuth coupling +- name: 🧮 Decide whether the OpenProject coupling needs a provisioning run + set_fact: + nextcloud_op_provision_due: >- + {{ (lookup('config', 'web-app-nextcloud', 'addons.integration_openproject.config.rotate_oauth_client') | bool) + or nextcloud_op_stamp is skipped + or (nextcloud_op_stamp.content | b64decode | trim) != nextcloud_op_digest }} + when: IS_STACK_HOST | bool + +- name: 🔧 Converge the bidirectional OpenProject <-> Nextcloud OAuth coupling include_tasks: integration_openproject_provision.yml - when: >- - IS_STACK_HOST | bool - and ( - (nextcloud_op_client_id_current.stdout | trim) | length == 0 - or (nextcloud_op_nc_client_current.stdout | trim) | length == 0 - ) + when: + - IS_STACK_HOST | bool + - nextcloud_op_provision_due | bool + +- name: 📖 Read the OpenProject coupling state the provisioning left + include_tasks: integration_openproject_state.yml + when: + - IS_STACK_HOST | bool + - nextcloud_op_provision_due | bool + +- name: 📝 Stamp the OpenProject coupling state the provisioning left + stack_host_copy: + content: "{{ nextcloud_op_digest }}\n" + dest: "{{ NEXTCLOUD_OPENPROJECT_STAMP_FILE }}" + mode: "0600" + when: + - IS_STACK_HOST | bool + - nextcloud_op_provision_due | bool diff --git a/roles/web-app-nextcloud/tasks/addons/integration_openproject_provision.yml b/roles/web-app-nextcloud/tasks/addons/integration_openproject_provision.yml index 5994a4a73f..47bedad88c 100644 --- a/roles/web-app-nextcloud/tasks/addons/integration_openproject_provision.yml +++ b/roles/web-app-nextcloud/tasks/addons/integration_openproject_provision.yml @@ -16,23 +16,59 @@ delay: 5 timeout: "{{ lookup('timeout', 600) | int }}" -- name: 📁 Create the Nextcloud storage + OpenProject OAuth application +- name: 🔑 Ensure the Nextcloud OAuth2 client OpenProject signs in with + ansible.builtin.shell: + cmd: >- + {{ NEXTCLOUD_DOCKER_EXEC_INTERACTIVE }} php -- + {{ NEXTCLOUD_DOCKER_WORK_DIRECTORY | quote }} + {{ NEXTCLOUD_OPENPROJECT_URL | quote }} + {{ NEXTCLOUD_OPENPROJECT_CLIENT_NAME | quote }} + {{ nextcloud_op_nc_client_current.stdout | trim | quote }} + stdin: "{{ lookup('file', 'php/addons/openproject/ensure_nc_client.php') }}" + register: nextcloud_op_ncclient_ensure + changed_when: (nextcloud_op_ncclient_ensure.stdout | nextcloud_oauth_client_state).changed + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: 🔎 Build the OpenProject provisioning input + set_fact: + nextcloud_op_ncclient: "{{ nextcloud_op_ncclient_ensure.stdout | nextcloud_oauth_client_state }}" + nextcloud_op_provision_input: | + PROVISION_INPUT = JSON.parse(<<~'INPUT') + {{ { + 'nextcloud_host': NEXTCLOUD_URL, + 'storage_name': nextcloud_op_storage_name, + 'nc_op_client_secret': nextcloud_op_client_secret_current.stdout | trim, + 'rotate_op_secret': lookup('config', 'web-app-nextcloud', 'addons.integration_openproject.config.rotate_oauth_client') | bool, + 'nc_oauth_client_id': (nextcloud_op_ncclient_ensure.stdout | nextcloud_oauth_client_state).client_id + if (nextcloud_op_ncclient_ensure.stdout | nextcloud_oauth_client_state).action == 'created' else '', + 'nc_oauth_client_secret': (nextcloud_op_ncclient_ensure.stdout | nextcloud_oauth_client_state).client_secret + if (nextcloud_op_ncclient_ensure.stdout | nextcloud_oauth_client_state).action == 'created' else '' + } | to_json }} + INPUT + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: 📁 Ensure the OpenProject storage, OAuth application and Nextcloud client ansible.builtin.shell: cmd: >- # nocheck: container-exec-resolver NEXTCLOUD_OPENPROJECT_LOCAL_CID resolved at delegate_to runtime; container_address would return a manager-only subshell container exec -i - -e NEXTCLOUD_HOST={{ lookup('tls', 'web-app-nextcloud', 'url.base') | quote }} - -e STORAGE_NAME={{ nextcloud_op_storage_name | quote }} - -e NC_HAS_OP_SECRET {{ NEXTCLOUD_OPENPROJECT_LOCAL_CID | quote }} bash -lc 'cd /app && bundle exec rails runner -' - stdin: "{{ lookup('file', 'ruby/utils/doorkeeper_allow_onion_redirect.rb') ~ '\n' ~ lookup('file', 'ruby/addons/openproject/ensure_nextcloud_storage.rb') }}" - environment: - NC_HAS_OP_SECRET: "{{ nextcloud_op_client_secret_current.stdout | trim }}" + stdin: "{{ 'require \"json\"\n' ~ nextcloud_op_provision_input ~ lookup('file', 'ruby/utils/doorkeeper_allow_onion_redirect.rb') ~ '\n' ~ lookup('file', 'ruby/addons/openproject/ensure_nextcloud_storage.rb') + }}" delegate_to: "{{ NEXTCLOUD_OPENPROJECT_HOST_NODE }}" register: nextcloud_op_storage_create - changed_when: "'\"oauth_application_created\":true' in nextcloud_op_storage_create.stdout" + changed_when: >- + '"oauth_application_secret_issued":true' in nextcloud_op_storage_create.stdout + or nextcloud_op_ncclient.action == 'created' no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" +- name: ⬆️ Push a newly created Nextcloud OAuth2 client into integration_openproject + shell: > + {{ NEXTCLOUD_DOCKER_EXEC_OCC }} config:app:set integration_openproject nc_oauth_client_id + --value={{ nextcloud_op_ncclient.id | string | quote }} + when: nextcloud_op_ncclient.action == 'created' + changed_when: true + - name: 🔎 Parse the OpenProject OAuth application credentials set_fact: nextcloud_op_oauth: "{{ nextcloud_op_storage_create.stdout | regex_search('{.*}') | from_json }}" @@ -52,9 +88,8 @@ - (nextcloud_op_client_secret | default('') | trim) | length > 0 fail_msg: >- OpenProject did not return a usable OAuth application and no client secret is persisted in - Nextcloud. A freshly generated client secret is only available the first time the application - is created; reset the integration_openproject app config (openproject_client_id, - openproject_client_secret, nc_oauth_client_id) and the OpenProject storage to re-provision. + Nextcloud. Set addons.integration_openproject.config.rotate_oauth_client to true for one + deploy to issue a new secret. - name: ⬆️ Push the OpenProject OAuth application credentials into Nextcloud ansible.builtin.shell: @@ -64,49 +99,7 @@ {{ NEXTCLOUD_INTERNAL_OCC_COMMAND | quote }} config:app:set integration_openproject authorization_method --value=oauth2 {{ NEXTCLOUD_INTERNAL_OCC_COMMAND | quote }} config:app:set integration_openproject openproject_client_id --value={{ nextcloud_op_oauth.openproject_client_id | quote }} {{ NEXTCLOUD_INTERNAL_OCC_COMMAND | quote }} config:app:set integration_openproject openproject_client_secret --value={{ nextcloud_op_client_secret | quote }} + when: >- + nextcloud_op_oauth.oauth_application_secret_issued + or (nextcloud_op_client_id_current.stdout | trim) != nextcloud_op_oauth.openproject_client_id no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - -- name: 📝 Register a Nextcloud OAuth2 client for OpenProject - shell: > - {{ NEXTCLOUD_DOCKER_EXEC_OCC }} oauth2:add-client - "OpenProject client" - "{{ nextcloud_op_expected_url }}/oauth_clients/%s/callback" - --output=json - register: nextcloud_op_ncclient_create - changed_when: nextcloud_op_ncclient_create.rc == 0 - failed_when: false - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - -- name: 🔌 Wire the Nextcloud OAuth2 client into both sides when it was created - when: (nextcloud_op_ncclient_create.rc | default(1)) == 0 - block: - - name: 🔎 Parse the Nextcloud OAuth2 client credentials - set_fact: - nextcloud_op_ncclient: "{{ nextcloud_op_ncclient_create.stdout | trim | from_json }}" - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - - - name: ⬆️ Push the Nextcloud OAuth2 client id into integration_openproject - shell: > - {{ NEXTCLOUD_DOCKER_EXEC_OCC }} config:app:set integration_openproject nc_oauth_client_id - --value={{ nextcloud_op_ncclient.clientId | quote }} - changed_when: true - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - - - name: 📝 Register the Nextcloud OAuth2 client back on the OpenProject storage - ansible.builtin.shell: - cmd: >- # nocheck: container-exec-resolver NEXTCLOUD_OPENPROJECT_LOCAL_CID resolved at delegate_to runtime; container_address would return a manager-only subshell - container exec -i - -e NEXTCLOUD_HOST={{ lookup('tls', 'web-app-nextcloud', 'url.base') | quote }} - -e STORAGE_NAME={{ nextcloud_op_storage_name | quote }} - -e NC_OAUTH_CLIENT_ID={{ nextcloud_op_ncclient.clientId | quote }} - -e NC_OAUTH_CLIENT_SECRET - {{ NEXTCLOUD_OPENPROJECT_LOCAL_CID | quote }} - bash -lc 'cd /app && bundle exec rails runner -' - stdin: "{{ lookup('file', 'ruby/utils/doorkeeper_allow_onion_redirect.rb') ~ '\n' ~ lookup('file', 'ruby/addons/openproject/ensure_nextcloud_storage.rb') - }}" - environment: - NC_OAUTH_CLIENT_SECRET: "{{ nextcloud_op_ncclient.clientSecret }}" - delegate_to: "{{ NEXTCLOUD_OPENPROJECT_HOST_NODE }}" - register: nextcloud_op_client_store - changed_when: true - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-nextcloud/tasks/addons/integration_openproject_state.yml b/roles/web-app-nextcloud/tasks/addons/integration_openproject_state.yml new file mode 100644 index 0000000000..fe34d08cc9 --- /dev/null +++ b/roles/web-app-nextcloud/tasks/addons/integration_openproject_state.yml @@ -0,0 +1,57 @@ +--- +- name: 📖 Read persisted integration_openproject OpenProject OAuth client id + shell: > + {{ NEXTCLOUD_DOCKER_EXEC_OCC }} config:app:get integration_openproject openproject_client_id + register: nextcloud_op_client_id_current + changed_when: false + failed_when: false + +- name: 📖 Read persisted integration_openproject Nextcloud OAuth client id + shell: > + {{ NEXTCLOUD_DOCKER_EXEC_OCC }} config:app:get integration_openproject nc_oauth_client_id + register: nextcloud_op_nc_client_current + changed_when: false + failed_when: false + +- name: 📖 Read persisted integration_openproject OpenProject OAuth client secret + shell: > + {{ NEXTCLOUD_DOCKER_EXEC_OCC }} config:app:get integration_openproject openproject_client_secret + register: nextcloud_op_client_secret_current + changed_when: false + failed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: 🔍 Read the Nextcloud storage and its OAuth pair OpenProject holds + database_query: + config: "{{ lookup('database', 'web-app-openproject') }}" + query_file: "{{ [role_path, 'files/sql/addons/openproject/coupling.sql'] | path_join }}" + named_args: + host: "{{ lookup('tls', application_id, 'url.origin') }}" + name: "{{ nextcloud_op_storage_name }}" + expect_rows: true + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: nextcloud_op_coupling + until: nextcloud_op_coupling is succeeded + retries: 6 + delay: 5 + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + when: IS_STACK_HOST | bool + +- name: 🧮 Digest the provisioning sources, inputs and coupling state + set_fact: + nextcloud_op_digest: >- + {{ { + 'sources': query('file', *NEXTCLOUD_OPENPROJECT_PROVISION_SOURCES) | map('hash', 'sha256') | list, + 'nextcloud_url': NEXTCLOUD_URL, + 'openproject_url': NEXTCLOUD_OPENPROJECT_URL, + 'storage_name': nextcloud_op_storage_name, + 'client_name': NEXTCLOUD_OPENPROJECT_CLIENT_NAME, + 'work_directory': NEXTCLOUD_DOCKER_WORK_DIRECTORY, + 'openproject_client_id': nextcloud_op_client_id_current.stdout | trim, + 'nc_oauth_client_id': nextcloud_op_nc_client_current.stdout | trim, + 'openproject_client_secret': nextcloud_op_client_secret_current.stdout | trim | hash('sha256'), + 'openproject': nextcloud_op_coupling.rows + } | to_json(sort_keys=true) | hash('sha256') }} + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + when: IS_STACK_HOST | bool diff --git a/roles/web-app-nextcloud/tasks/addons/integration_suitecrm.yml b/roles/web-app-nextcloud/tasks/addons/integration_suitecrm.yml index 6cb2397108..47330a4604 100644 --- a/roles/web-app-nextcloud/tasks/addons/integration_suitecrm.yml +++ b/roles/web-app-nextcloud/tasks/addons/integration_suitecrm.yml @@ -3,7 +3,7 @@ set_fact: nextcloud_crm_container: "{{ lookup('config', 'web-app-suitecrm', 'services.suitecrm.name') }}" nextcloud_crm_instance_dir: "{{ lookup('container', 'web-app-suitecrm', 'directories.instance') }}" - nextcloud_crm_base_url: "{{ lookup('tls', 'web-app-suitecrm', 'url.base') | trim }}" + nextcloud_crm_base_url: "{{ lookup('tls', 'web-app-suitecrm', 'url.origin') }}" nextcloud_crm_client_name: "Nextcloud ({{ lookup('domain', 'web-app-nextcloud') }})" nextcloud_crm_client_secret: "{{ lookup('config', application_id, 'secrets.credentials.integration_suitecrm_client_secret') }}" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-nextcloud/tasks/addons/integration_zammad.yml b/roles/web-app-nextcloud/tasks/addons/integration_zammad.yml index da66d43ec1..e8257cc7ec 100644 --- a/roles/web-app-nextcloud/tasks/addons/integration_zammad.yml +++ b/roles/web-app-nextcloud/tasks/addons/integration_zammad.yml @@ -6,8 +6,8 @@ # integration_gitlab coupling does. - name: 🔍 Resolve Zammad integration provisioning facts set_fact: - nextcloud_zammad_base_url: "{{ lookup('tls', 'web-app-zammad', 'url.base') | regex_replace('/$', '') }}" - nextcloud_zammad_nc_base_url: "{{ lookup('tls', 'web-app-nextcloud', 'url.base') | regex_replace('/$', '') }}" + nextcloud_zammad_base_url: "{{ lookup('tls', 'web-app-zammad', 'url.origin') }}" + nextcloud_zammad_nc_base_url: "{{ lookup('tls', 'web-app-nextcloud', 'url.origin') }}" changed_when: false - name: 📖 Read persisted integration_zammad OAuth client id diff --git a/roles/web-app-nextcloud/tasks/addons/richdocuments.yml b/roles/web-app-nextcloud/tasks/addons/richdocuments.yml index ed97d539c0..e771bf8995 100644 --- a/roles/web-app-nextcloud/tasks/addons/richdocuments.yml +++ b/roles/web-app-nextcloud/tasks/addons/richdocuments.yml @@ -1 +1,15 @@ --- +- name: "⏱️ Set the deadline for the Collabora check" + set_fact: + nextcloud_richdocuments_check_deadline: "{{ now(utc=true).timestamp() + (lookup('timeout', 300) | int) }}" + +- name: "🔎 Activate the Collabora connector and cache its capabilities" + shell: > + {{ NEXTCLOUD_DOCKER_EXEC_OCC }} richdocuments:activate-config + register: nextcloud_richdocuments_check + until: >- + nextcloud_richdocuments_check.rc == 0 + or now(utc=true).timestamp() > nextcloud_richdocuments_check_deadline | float + retries: 30 + delay: 10 + changed_when: false diff --git a/roles/web-app-nextcloud/templates/env.j2 b/roles/web-app-nextcloud/templates/env.j2 index d1b8d64053..6177bc5260 100644 --- a/roles/web-app-nextcloud/templates/env.j2 +++ b/roles/web-app-nextcloud/templates/env.j2 @@ -55,7 +55,7 @@ OBJECTSTORE_S3_AUTOCREATE=false {% if NEXTCLOUD_HPB_PLUGIN_ENABLED %} NC_DOMAIN={{ NEXTCLOUD_DOMAIN }} -TALK_NETWORK_BACKEND_URLS={{ lookup('network_urls', NEXTCLOUD_URL | regex_replace('/+$', ''))[1:] | join(',') }} +TALK_NETWORK_BACKEND_URLS={{ lookup('network_urls', lookup('tls', application_id, 'url.origin'))[1:] | join(',') }} TALK_HOST={{ NEXTCLOUD_HPB_DOMAIN }} SIGNALING_SECRET={{ NEXTCLOUD_HPB_SIGNALING_SECRET }} INTERNAL_SECRET={{ NEXTCLOUD_HPB_INTERNAL_SECRET }} diff --git a/roles/web-app-nextcloud/templates/playwright.env.j2 b/roles/web-app-nextcloud/templates/playwright.env.j2 index 6ffd0638d2..e9a91558f5 100644 --- a/roles/web-app-nextcloud/templates/playwright.env.j2 +++ b/roles/web-app-nextcloud/templates/playwright.env.j2 @@ -71,6 +71,8 @@ NEXTCLOUD_TALK_UNEXPECTED_TURN_SERVER={{ (NEXTCLOUD_HPB_TURN_ONBOARD_CONFIG.serv OIDC_ISSUER_URL={{ OIDC.CLIENT.ISSUER_URL | dotenv_quote }} +OPENPROJECT_BASE_URL={{ (lookup('landing_url', 'web-app-openproject') if (lookup('config', application_id, 'services.openproject.enabled') | bool) else '') | dotenv_quote }} + PEERTUBE_BASE_URL={{ (lookup('landing_url', 'web-app-peertube') if (lookup('config', application_id, 'services.peertube.enabled') | bool) else '') | dotenv_quote }} # nocheck: persona-block-rationale — the native Nextcloud administrator signs in through NEXTCLOUD_DIRECT_LOGIN_PASSWORD above, so this role renders LOGIN_USERNAME / LOGIN_PASSWORD instead of the ADMIN_USERNAME / ADMIN_PASSWORD pair the shared helper reads (roles/test-e2e-playwright/files/personas/admin.js:29-30) and the helper has nothing to type; the admin chain is driven by files/playwright/test-login-admin-native.js and test-login-admin-oidc.js (see README "Persona contract opt-outs"). diff --git a/roles/web-app-nextcloud/vars/main.yml b/roles/web-app-nextcloud/vars/main.yml index 3d1e5b7193..aa2ad5da7e 100644 --- a/roles/web-app-nextcloud/vars/main.yml +++ b/roles/web-app-nextcloud/vars/main.yml @@ -24,6 +24,7 @@ NEXTCLOUD_PINNED_PLUGINS: >- | map(attribute='key') | list }} NEXTCLOUD_PLUGINS_PINNED: "{{ NEXTCLOUD_PINNED_PLUGINS | length > 0 }}" NEXTCLOUD_PLUGINS_ENABLED: "{{ lookup('config', application_id, 'services.nextcloud.plugins_enabled') }}" +NEXTCLOUD_PLUGIN_BACKGROUND_ASYNC_TIME: "{{ lookup('timeout', 604800) | int }}" NEXTCLOUD_DESIGN_ENABLED: "{{ lookup('config', application_id, 'services.design.enabled') | bool }}" NEXTCLOUD_DESIGN_DIR: "{{ [lookup('container', application_id, 'directories.config'), 'design'] | path_join }}" NEXTCLOUD_DESIGN_PRIMARY: "{{ lookup('design_palette', lookup('config', 'web-svc-design', 'services.design.colors.base')).light['--design-primary'] }}" @@ -264,6 +265,16 @@ NEXTCLOUD_ONLYOFFICE_URL: "{{ lookup('tls', 'web-svc-onlyoffice', 'url.base') }} NEXTCLOUD_ONLYOFFICE_ENABLED: "{{ lookup('config', application_id, 'addons.onlyoffice.enabled') }}" NEXTCLOUD_ONLYOFFICE_LOCATION: "/ds-vpath/" +NEXTCLOUD_OPENPROJECT_URL: "{{ lookup('tls', 'web-app-openproject', 'url.origin') }}" +NEXTCLOUD_OPENPROJECT_CLIENT_NAME: "OpenProject client" +NEXTCLOUD_OPENPROJECT_STAMP_FILE: "{{ [lookup('container', application_id, 'directories.instance'), 'openproject-provision.sha256'] | path_join }}" +NEXTCLOUD_OPENPROJECT_PROVISION_SOURCES: + - "{{ [role_path, 'tasks/addons/integration_openproject_provision.yml'] | path_join }}" + - "{{ [role_path, 'files/php/addons/openproject/ensure_nc_client.php'] | path_join }}" + - "{{ [role_path, 'files/ruby/utils/doorkeeper_allow_onion_redirect.rb'] | path_join }}" + - "{{ [role_path, 'files/ruby/addons/openproject/ensure_nextcloud_storage.rb'] | path_join }}" + - "{{ [role_path, 'filter_plugins/nextcloud_oauth_client.py'] | path_join }}" + NEXTCLOUD_DOCKER_USER_ID: 82 NEXTCLOUD_DOCKER_USER: "www-data" diff --git a/roles/web-app-openbao/README.md b/roles/web-app-openbao/README.md index 875224ab78..0668531b0d 100644 --- a/roles/web-app-openbao/README.md +++ b/roles/web-app-openbao/README.md @@ -17,6 +17,7 @@ This role deploys OpenBao as an Infinito.Nexus application at `openbao.` - **Automatic unsealing:** A `static` seal reads a 32-byte key from the encrypted inventory, so the node unseals itself on every container restart. - **Machine identity:** AppRole is configured independently of human login, so services and automation use their own identities and short-lived tokens instead of a shared administrator token. - **Optional internal PKI:** A service flag mounts the `pki` engine with an internal root CA and an issuing role. +- **Audit trail:** A `file` audit device at `stdout/`, declared in the server config, writes every request, with the accessing identity and a timestamp, to the server's stdout and so to the container log. Secret values appear only as salted HMACs. Every deploy reads a probe secret and fails unless the log shows that read with its identity and time. - **Monitoring:** Prometheus scrapes `/v1/sys/metrics` on the role-local network. A sealed node is detected from `/v1/sys/health`, which answers 503 while sealed and 200 once unsealed. - **Automated provisioning:** Configured by Ansible without manual steps; no Keycloak client or OpenBao path has to be created by hand. diff --git a/roles/web-app-openbao/meta/services.yml b/roles/web-app-openbao/meta/services.yml index 4deb4b4edf..2835707517 100644 --- a/roles/web-app-openbao/meta/services.yml +++ b/roles/web-app-openbao/meta/services.yml @@ -42,6 +42,7 @@ prometheus: native_metrics: enabled: true port: 8200 +# nocheck: playwright-service-flag self-provider openbao: # nocheck: default-placement-manager raft keeps its BoltDB store mmap'd with fsync durability, so it cannot live on NFS; the node is pinned in swarm to stay with its volume placement: manager @@ -50,6 +51,9 @@ openbao: enabled: true swarm: enabled: true + bond: 1 + enabled: true # nocheck: dynamic-flag + shared: true cpus: 0.5 mem_reservation: 128m mem_limit: 512m diff --git a/roles/web-app-openbao/tasks/03_policies.yml b/roles/web-app-openbao/tasks/03_policies.yml index 84c28ad92a..a716d8ced8 100644 --- a/roles/web-app-openbao/tasks/03_policies.yml +++ b/roles/web-app-openbao/tasks/03_policies.yml @@ -27,3 +27,42 @@ [ "$before" = "$after" ] || echo OPENBAO_CHANGED' register: openbao_admin_policy_write changed_when: "'OPENBAO_CHANGED' in openbao_admin_policy_write.stdout" + +- name: "📝 Fail unless the declared stdout audit device is active" + ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec {{ OPENBAO_LOCAL_CID | quote }} + bao audit list -format=json + register: openbao_audit_devices + changed_when: false + failed_when: >- + openbao_audit_devices.rc != 0 + or (openbao_audit_devices.stdout | from_json).get(OPENBAO_AUDIT_PATH ~ '/', {}).get('type') != 'file' + +- name: "🔎 Read the audit probe secret through the AppRole session" + ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container exec {{ OPENBAO_LOCAL_CID | quote }} + sh -c 'bao kv get -mount={{ OPENBAO_KV_MOUNT | quote }} -field=value {{ OPENBAO_AUDIT_PROBE | quote }} 2>/dev/null || + { bao kv put -mount={{ OPENBAO_KV_MOUNT | quote }} {{ OPENBAO_AUDIT_PROBE | quote }} value="probe-$(date +%s)-$$" >/dev/null && + bao kv get -mount={{ OPENBAO_KV_MOUNT | quote }} -field=value {{ OPENBAO_AUDIT_PROBE | quote }}; }' + register: openbao_audit_probe + changed_when: false + +- name: "🧾 Fail unless the audit log recorded the probe read with identity and time" + ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container logs --since 10m {{ OPENBAO_LOCAL_CID | quote }} 2>&1 + | grep -F '"type":"response"' + | grep -F '"path":"{{ OPENBAO_KV_MOUNT }}/data/{{ OPENBAO_AUDIT_PROBE }}"' + | grep -F '"operation":"read"' + | grep -F '"display_name":' + | grep -cF '"time":' + register: openbao_audit_entries + changed_when: false + failed_when: openbao_audit_entries.stdout | trim | int < 1 + +- name: "🙈 Fail if the audit log holds the probe secret in plaintext" + ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node + container logs --since 10m {{ OPENBAO_LOCAL_CID | quote }} 2>&1 + | grep -cF {{ openbao_audit_probe.stdout | trim | quote }} + register: openbao_audit_leak + changed_when: false + failed_when: openbao_audit_leak.stdout | trim | int > 0 diff --git a/roles/web-app-openbao/templates/openbao.hcl.j2 b/roles/web-app-openbao/templates/openbao.hcl.j2 index 9fc02c3bbc..acba58a60f 100644 --- a/roles/web-app-openbao/templates/openbao.hcl.j2 +++ b/roles/web-app-openbao/templates/openbao.hcl.j2 @@ -27,6 +27,12 @@ seal "static" { {% endif %} } +audit "file" "{{ OPENBAO_AUDIT_PATH }}" { + options { + file_path = "stdout" + } +} + telemetry { prometheus_retention_time = "24h" disable_hostname = true diff --git a/roles/web-app-openbao/templates/policies/ansible-admin.hcl.j2 b/roles/web-app-openbao/templates/policies/ansible-admin.hcl.j2 index c96fe76e97..1497fe5ad7 100644 --- a/roles/web-app-openbao/templates/policies/ansible-admin.hcl.j2 +++ b/roles/web-app-openbao/templates/policies/ansible-admin.hcl.j2 @@ -18,6 +18,10 @@ path "sys/mounts/*" { capabilities = ["create", "read", "update", "delete", "sudo"] } +path "sys/audit" { + capabilities = ["read", "sudo"] +} + path "sys/plugins/reload/backend" { capabilities = ["update"] } diff --git a/roles/web-app-openbao/vars/main.yml b/roles/web-app-openbao/vars/main.yml index 6441f6b93e..789f4cc773 100644 --- a/roles/web-app-openbao/vars/main.yml +++ b/roles/web-app-openbao/vars/main.yml @@ -17,7 +17,7 @@ OPENBAO_LDAP_ENABLED: "{{ lookup('config', application_id, 'services.ldap.enable OPENBAO_PKI_ENABLED: "{{ lookup('config', application_id, 'services.openbao.pki.enabled') }}" OPENBAO_LOG_LEVEL: "{{ lookup('config', application_id, 'services.openbao.log_level') }}" -OPENBAO_BASE_URL: "{{ lookup('tls', application_id, 'url.base') | regex_replace('/+$', '') }}" +OPENBAO_BASE_URL: "{{ lookup('tls', application_id, 'url.origin') }}" OPENBAO_CONFIG_HOST: "{{ [lookup('container', application_id, 'directories.config'), 'openbao.hcl'] | path_join }}" OPENBAO_PLUGINS_CONFIG_HOST: "{{ [lookup('container', application_id, 'directories.config'), 'plugins.hcl'] | path_join }}" @@ -47,6 +47,8 @@ OPENBAO_RECOVERY_KEY: >- OPENBAO_SECRET_ID_REGISTERED: "{{ openbao_secret_id_registered | default('', true) }}" OPENBAO_SECRET_ID_ROTATING: "{{ (OPENBAO_SECRET_ID_REGISTERED | length > 0) and (OPENBAO_SECRET_ID_REGISTERED != OPENBAO_APPROLE_SECRET_ID) }}" OPENBAO_KV_MOUNT: "infinito" +OPENBAO_AUDIT_PATH: "stdout" +OPENBAO_AUDIT_PROBE: "audit-probe" OPENBAO_ANSIBLE_APPROLE: "ansible" OPENBAO_PKI_MOUNT: "pki" OPENBAO_PKI_ISSUING_ROLE: "internal" diff --git a/roles/web-app-openclaw/vars/main.yml b/roles/web-app-openclaw/vars/main.yml index 134a790905..4634ae6bee 100644 --- a/roles/web-app-openclaw/vars/main.yml +++ b/roles/web-app-openclaw/vars/main.yml @@ -6,7 +6,7 @@ http_port: "{{ lookup('config', application_id, 'services.openclaw.ports.local.h 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') | regex_replace('/+$', '') }}" +OPENCLAW_URL: "{{ lookup('tls', application_id, 'url.origin') }}" OPENCLAW_CONTROL_UI_ORIGINS: "{{ lookup('network_urls', OPENCLAW_URL) }}" 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 [] }}" diff --git a/roles/web-app-opencloud/vars/main.yml b/roles/web-app-opencloud/vars/main.yml index dc6d965294..d09d9e665c 100644 --- a/roles/web-app-opencloud/vars/main.yml +++ b/roles/web-app-opencloud/vars/main.yml @@ -7,7 +7,7 @@ proxy_x_forwarded_proto: "https" OPENCLOUD_CONTAINER: "{{ lookup('config', application_id, 'services.opencloud.name') }}" OPENCLOUD_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, entity_name) }}" -OPENCLOUD_URL: "{{ lookup('tls', application_id, 'url.base') | regex_replace('/+$', '') }}" +OPENCLOUD_URL: "{{ lookup('tls', application_id, 'url.origin') }}" OPENCLOUD_DOMAIN: "{{ lookup('domain', application_id) }}" OPENCLOUD_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') }}" diff --git a/roles/web-app-openproject/README.md b/roles/web-app-openproject/README.md index 1cd2392a2d..9aca5e078f 100644 --- a/roles/web-app-openproject/README.md +++ b/roles/web-app-openproject/README.md @@ -62,6 +62,12 @@ Each addon's spec lives under `files/playwright/addons/`. To inspect and modify live settings inside the container, open a shell and use the Rails console for full LDAP and SMTP configuration. +[tasks/04_admin.yml](./tasks/04_admin.yml) applies the settings, the administrator and its LDAP link only when the digest of its sources, its inputs and the state OpenProject holds differs from the stamp `admin-provision.sha256` in the instance directory. Set `services.openproject.admin.force` to `true` to run it regardless. + +## Database migrations + +A deploy runs `bin/rails db:migrate` in the web container only while the comment on `schema_migrations` names another image than the one the web container runs, and writes the running image id there once the run succeeds. `COMMENT ON TABLE schema_migrations IS NULL` makes the next deploy migrate again. + ## Major Upgrades A compose deploy reads `schema_migrations` of an existing database before the pinned image starts. The newest aggregated migration `1000NNN` marks a schema migrated by major NNN + 1; without one, `20241015081341` marks 15 and anything older counts as 14. For every major between that stage and the pinned `services.web.version`, the deploy stops the old app containers, runs the seeder of `openproject/openproject:` and works off the queued GoodJob jobs with [drain_jobs.rb](./files/ruby/drain_jobs.rb), then starts the pinned major. A database migrated by a newer major than the pinned one stops the deploy. Swarm deploys skip the stepping, so the pinned seeder reports an incompatible schema itself. diff --git a/roles/web-app-openproject/files/playwright/test-oidc-security.js b/roles/web-app-openproject/files/playwright/test-oidc-security.js index 266cf8da90..e27169ca32 100644 --- a/roles/web-app-openproject/files/playwright/test-oidc-security.js +++ b/roles/web-app-openproject/files/playwright/test-oidc-security.js @@ -75,9 +75,14 @@ test("oidc-security: a forged identity header cannot authenticate through the tr `the trusted-header bridge must never authenticate an un-proxied request (got ${response.status()}: ${body.slice(0, 200)})`, ).toBeFalsy(); expect( - response.url(), - "the bridge surface must sit behind the oauth2-proxy gate", - ).toContain("openid-connect/auth"); + response.status(), + "the SSO ACL whitelists /api/ for the bearer-token API, so a forged header must meet OpenProject's own 401", + ).toBe(401); + const sessionCookies = await context.cookies(expectedBase); + expect( + sessionCookies.some((cookie) => cookie.name === "_open_project_session"), + "no OpenProject session cookie may be minted from a forged header on the whitelisted API", + ).toBe(false); } finally { await context.close(); } diff --git a/roles/web-app-openproject/files/sql/migration-stamp/read.sql b/roles/web-app-openproject/files/sql/migration-stamp/read.sql new file mode 100644 index 0000000000..22da9c8e5a --- /dev/null +++ b/roles/web-app-openproject/files/sql/migration-stamp/read.sql @@ -0,0 +1 @@ +SELECT obj_description(to_regclass('public.schema_migrations'), 'pg_class'); diff --git a/roles/web-app-openproject/files/sql/migration-stamp/write.sql b/roles/web-app-openproject/files/sql/migration-stamp/write.sql new file mode 100644 index 0000000000..40c3f0dc46 --- /dev/null +++ b/roles/web-app-openproject/files/sql/migration-stamp/write.sql @@ -0,0 +1,7 @@ +DO $$ +BEGIN + EXECUTE format( + 'COMMENT ON TABLE public.schema_migrations IS %L', %(image)s + ); +END +$$; diff --git a/roles/web-app-openproject/files/sql/select/admin-state.sql b/roles/web-app-openproject/files/sql/select/admin-state.sql new file mode 100644 index 0000000000..907f2fd0de --- /dev/null +++ b/roles/web-app-openproject/files/sql/select/admin-state.sql @@ -0,0 +1,54 @@ +SELECT + account.id AS account_id, + account.admin AS account_admin, + account.status AS account_status, + account.force_password_change AS account_force_password_change, + account.ldap_auth_source_id AS account_ldap_auth_source_id, + latest_password.id AS password_id, + md5(latest_password.hashed_password) AS password_digest, + ldap_source.id AS ldap_source_id, + stored_settings.state AS settings_state, + seeded_admin.state AS seeded_admin_state +FROM ( + SELECT + %(login)s AS wanted_login, + %(ldap_name)s AS wanted_ldap_name +) AS wanted +LEFT JOIN users AS account + ON + account.type = 'User' + AND wanted.wanted_login = account.login +LEFT JOIN LATERAL ( + SELECT + candidate.id, + candidate.hashed_password + FROM user_passwords AS candidate + WHERE candidate.user_id = account.id + ORDER BY candidate.id DESC + LIMIT 1 +) AS latest_password ON TRUE +LEFT JOIN ldap_auth_sources AS ldap_source + ON wanted.wanted_ldap_name = ldap_source.name +CROSS JOIN LATERAL ( + SELECT + string_agg( + concat(setting.name, '=', md5(setting.value)), + ',' ORDER BY setting.name, setting.id + ) AS state + FROM settings AS setting + WHERE setting.name IN ( + SELECT json_array_elements_text(%(settings)s::json) + ) +) AS stored_settings +CROSS JOIN LATERAL ( + SELECT + string_agg( + concat(seeded.id, '=', seeded.status), + ',' ORDER BY seeded.id + ) AS state + FROM users AS seeded + WHERE + seeded.type = 'User' + AND seeded.login = 'admin' +) AS seeded_admin +ORDER BY account_id, ldap_source_id; diff --git a/roles/web-app-openproject/files/sql/select-ldap-auth-source-exists.sql b/roles/web-app-openproject/files/sql/select/ldap-auth-source-exists.sql similarity index 100% rename from roles/web-app-openproject/files/sql/select-ldap-auth-source-exists.sql rename to roles/web-app-openproject/files/sql/select/ldap-auth-source-exists.sql diff --git a/roles/web-app-openproject/filter_plugins/openproject_migrate.py b/roles/web-app-openproject/filter_plugins/openproject_migrate.py new file mode 100644 index 0000000000..5d9d5a0835 --- /dev/null +++ b/roles/web-app-openproject/filter_plugins/openproject_migrate.py @@ -0,0 +1,29 @@ +from ansible.errors import AnsibleFilterError + + +def openproject_migrations_pending(stamp, image): + """Tell whether ``db:migrate`` must run in the web container. + + Args: + stamp: the image id on ``schema_migrations``, written only after + ``db:migrate`` succeeded; empty when no run succeeded yet. + image: the image id of the running web container. + + Returns: + ``False`` only when ``stamp`` names ``image``. + + Raises: + AnsibleFilterError: ``image`` is empty, which would let an empty + stamp pass for current. + """ + current = str(image).strip() + if not current: + raise AnsibleFilterError( + "openproject_migrations_pending: the web container reported no image id" + ) + return str(stamp).strip() != current + + +class FilterModule: + def filters(self): + return {"openproject_migrations_pending": openproject_migrations_pending} diff --git a/roles/web-app-openproject/meta/services.yml b/roles/web-app-openproject/meta/services.yml index 0df9e5301e..4bb26e35dd 100644 --- a/roles/web-app-openproject/meta/services.yml +++ b/roles/web-app-openproject/meta/services.yml @@ -147,6 +147,8 @@ openproject: filters: administrators: false users: false + admin: + force: false ports: local: sso: 16483 diff --git a/roles/web-app-openproject/tasks/02_migrate.yml b/roles/web-app-openproject/tasks/02_migrate.yml index d9b318f4af..fd47cffb68 100644 --- a/roles/web-app-openproject/tasks/02_migrate.yml +++ b/roles/web-app-openproject/tasks/02_migrate.yml @@ -25,28 +25,29 @@ resolve_converge_retries: 120 resolve_converge_delay: 5 -- name: ▶️ Run database migrations - shell: >- # nocheck: container-exec-resolver OPENPROJECT_WEB_LOCAL_CID resolved at delegate_to runtime; container_address would return a manager-only subshell - container exec -i {{ OPENPROJECT_WEB_LOCAL_CID | quote }} bash -lc - "cd /app && bin/rails db:migrate RAILS_ENV=production" +- name: 🔍 Read the image of the OpenProject web container + ansible.builtin.command: + argv: + - container + - inspect + - --type + - container + - --format + - "{{ '{{.Image}}' }}" + - "{{ OPENPROJECT_WEB_LOCAL_CID }}" # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node delegate_to: "{{ OPENPROJECT_WEB_HOST_NODE }}" - register: openproject_migrate - retries: 30 - delay: 10 - until: openproject_migrate.rc == 0 - -- name: ⏳ Wait until OpenProject web container is running (after migrations, compose) - shell: > - container inspect --type container - -f '{{"{{"}}.State.Status{{"}}"}}' {{ OPENPROJECT_WEB_CONTAINER_ADDRESS }} - register: openproject_web_state_after_migrate - retries: 60 - delay: 5 - until: openproject_web_state_after_migrate.stdout.strip() == "running" + register: openproject_web_image changed_when: false - when: IS_COMPOSE_MODE -- name: ⏳ Wait until OpenProject web service converged (after migrations, swarm) - ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/wait_converged.yml') }}" - vars: - wait_service_key: "{{ OPENPROJECT_WEB_SERVICE }}" +- name: 🔍 Read the image that last migrated the schema + database_query: + mask_values: false + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/migration-stamp/read.sql" + expect_rows: true + register: openproject_migration_stamp + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: ▶️ Migrate the schema for an image that has not migrated it yet + include_tasks: 02_migrate/run.yml + when: openproject_migration_stamp.stdout | openproject_migrations_pending(openproject_web_image.stdout) diff --git a/roles/web-app-openproject/tasks/02_migrate/run.yml b/roles/web-app-openproject/tasks/02_migrate/run.yml new file mode 100644 index 0000000000..f09f96b938 --- /dev/null +++ b/roles/web-app-openproject/tasks/02_migrate/run.yml @@ -0,0 +1,34 @@ +--- +- name: ▶️ Run database migrations + shell: >- # nocheck: container-exec-resolver OPENPROJECT_WEB_LOCAL_CID resolved at delegate_to runtime; container_address would return a manager-only subshell + container exec -i {{ OPENPROJECT_WEB_LOCAL_CID | quote }} bash -lc + "cd /app && bin/rails db:migrate RAILS_ENV=production" + delegate_to: "{{ OPENPROJECT_WEB_HOST_NODE }}" + register: openproject_migrate + retries: 30 + delay: 10 + until: openproject_migrate.rc == 0 + +- name: 🏷️ Stamp the schema with the image that migrated it + database_query: + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/migration-stamp/write.sql" + named_args: + image: "{{ openproject_web_image.stdout | trim }}" + +- name: ⏳ Wait until OpenProject web container is running (after migrations, compose) + shell: > + container inspect --type container + -f '{{"{{"}}.State.Status{{"}}"}}' {{ OPENPROJECT_WEB_CONTAINER_ADDRESS }} + register: openproject_web_state_after_migrate + retries: 60 + delay: 5 + until: openproject_web_state_after_migrate.stdout.strip() == "running" + changed_when: false + when: IS_COMPOSE_MODE + +- name: ⏳ Wait until OpenProject web service converged (after migrations, swarm) + ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/wait_converged.yml') }}" + vars: + wait_service_key: "{{ OPENPROJECT_WEB_SERVICE }}" diff --git a/roles/web-app-openproject/tasks/03_ldap.yml b/roles/web-app-openproject/tasks/03_ldap.yml index 581e23823b..61ee7224f7 100644 --- a/roles/web-app-openproject/tasks/03_ldap.yml +++ b/roles/web-app-openproject/tasks/03_ldap.yml @@ -7,7 +7,7 @@ database_query: mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" config: "{{ lookup('database', application_id) }}" - query_file: "{{ role_path }}/files/sql/select-ldap-auth-source-exists.sql" + query_file: "{{ role_path }}/files/sql/select/ldap-auth-source-exists.sql" named_args: name: "{{ OPENPROJECT_LDAP.name }}" expect_rows: true diff --git a/roles/web-app-openproject/tasks/04_admin.yml b/roles/web-app-openproject/tasks/04_admin.yml index 93f7242daf..799dc2b9a0 100644 --- a/roles/web-app-openproject/tasks/04_admin.yml +++ b/roles/web-app-openproject/tasks/04_admin.yml @@ -1,31 +1,42 @@ --- -- name: "🔍 Resolve openproject web 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: web - resolve_output_prefix: OPENPROJECT_WEB - resolve_compose_cid: "{{ OPENPROJECT_WEB_CONTAINER_ADDRESS }}" +- name: 📖 Read the settings, administrator and LDAP link OpenProject holds + include_tasks: + file: 04_admin/state.yml + apply: + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" -- name: 🔧 Apply settings, ensure the administrator, lock the seeded admin, link LDAP - ansible.builtin.shell: - cmd: >- # nocheck: container-exec-resolver CID resolved at delegate_to runtime; container_address targets a manager-only subshell - container exec -i - -e {{ ('OPENPROJECT_ADMIN_LOGIN=' ~ OPENPROJECT_ADMINISTRATOR_USERNAME) | quote }} - -e {{ ('OPENPROJECT_ADMIN_EMAIL=' ~ OPENPROJECT_ADMINISTRATOR_EMAIL) | quote }} - {% if OPENPROJECT_HEADER_SSO_ENABLED | bool %}-e {{ ('OPENPROJECT_LDAP_NAME=' ~ OPENPROJECT_LDAP.name) | quote }}{% endif %} - {{ OPENPROJECT_WEB_LOCAL_CID | quote }} - sh -c 'IFS= read -r OPENPROJECT_ADMIN_PASSWORD; IFS= read -r OPENPROJECT_RAILS_SETTINGS; export OPENPROJECT_ADMIN_PASSWORD OPENPROJECT_RAILS_SETTINGS; exec - "$@"' sh bash -lc 'cd /app && bundle exec rails runner -' - stdin: |- - {{ OPENPROJECT_ADMINISTRATOR_PASSWORD }} - {{ OPENPROJECT_RAILS_SETTINGS | to_json }} - {{ lookup('file', 'ruby/apply_settings.rb') }} - {{ lookup('file', 'ruby/ensure_admin_user.rb') }} - {{ lookup('file', 'ruby/lock_seeded_admin.rb') }} - {% if OPENPROJECT_HEADER_SSO_ENABLED | bool %}{{ lookup('file', 'ruby/link_admin_to_ldap.rb') }}{% endif %} - delegate_to: "{{ OPENPROJECT_WEB_HOST_NODE }}" - register: openproject_rails_runner - retries: 30 - delay: 5 - until: openproject_rails_runner.rc == 0 - no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" +- name: 🔍 Find the stamp of the last settings and administrator run + ansible.builtin.stat: + path: "{{ OPENPROJECT_ADMIN_STAMP_FILE }}" + register: openproject_admin_stamp_file + +- name: 📖 Read the stamp of the last settings and administrator run + ansible.builtin.slurp: + src: "{{ OPENPROJECT_ADMIN_STAMP_FILE }}" + register: openproject_admin_stamp + when: openproject_admin_stamp_file.stat.exists + +- name: 🧮 Decide whether the settings and administrator need a run + ansible.builtin.set_fact: + openproject_admin_due: >- + {{ (OPENPROJECT_ADMIN_FORCE | bool) + or openproject_admin_stamp is skipped + or (openproject_admin_stamp.content | b64decode | trim) != openproject_admin_digest }} + +- name: 🔧 Run the settings and administrator step and stamp what it left + when: openproject_admin_due | bool + block: + - name: 🔧 Apply settings, ensure the administrator and link it to LDAP + include_tasks: 04_admin/provision.yml + + - name: 📖 Read the settings, administrator and LDAP link the run left + include_tasks: + file: 04_admin/state.yml + apply: + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + + - name: 📝 Stamp the settings, administrator and LDAP link the run left + stack_host_copy: + content: "{{ openproject_admin_digest }}\n" + dest: "{{ OPENPROJECT_ADMIN_STAMP_FILE }}" + mode: "0600" diff --git a/roles/web-app-openproject/tasks/04_admin/provision.yml b/roles/web-app-openproject/tasks/04_admin/provision.yml new file mode 100644 index 0000000000..713e4c094a --- /dev/null +++ b/roles/web-app-openproject/tasks/04_admin/provision.yml @@ -0,0 +1,31 @@ +--- +- name: "🔍 Resolve openproject web 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: web + resolve_output_prefix: OPENPROJECT_WEB + resolve_compose_cid: "{{ OPENPROJECT_WEB_CONTAINER_ADDRESS }}" + +- name: 🔧 Apply settings, ensure the administrator, lock the seeded admin, link LDAP + ansible.builtin.shell: + cmd: >- # nocheck: container-exec-resolver CID resolved at delegate_to runtime; container_address targets a manager-only subshell + container exec -i + -e {{ ('OPENPROJECT_ADMIN_LOGIN=' ~ OPENPROJECT_ADMINISTRATOR_USERNAME) | quote }} + -e {{ ('OPENPROJECT_ADMIN_EMAIL=' ~ OPENPROJECT_ADMINISTRATOR_EMAIL) | quote }} + {% if OPENPROJECT_HEADER_SSO_ENABLED | bool %}-e {{ ('OPENPROJECT_LDAP_NAME=' ~ OPENPROJECT_ADMIN_LDAP_NAME) | quote }}{% endif %} + {{ OPENPROJECT_WEB_LOCAL_CID | quote }} + sh -c 'IFS= read -r OPENPROJECT_ADMIN_PASSWORD; IFS= read -r OPENPROJECT_RAILS_SETTINGS; export OPENPROJECT_ADMIN_PASSWORD OPENPROJECT_RAILS_SETTINGS; exec + "$@"' sh bash -lc 'cd /app && bundle exec rails runner -' + stdin: |- + {{ OPENPROJECT_ADMINISTRATOR_PASSWORD }} + {{ OPENPROJECT_RAILS_SETTINGS | to_json }} + {{ lookup('file', 'ruby/apply_settings.rb') }} + {{ lookup('file', 'ruby/ensure_admin_user.rb') }} + {{ lookup('file', 'ruby/lock_seeded_admin.rb') }} + {% if OPENPROJECT_HEADER_SSO_ENABLED | bool %}{{ lookup('file', 'ruby/link_admin_to_ldap.rb') }}{% endif %} + delegate_to: "{{ OPENPROJECT_WEB_HOST_NODE }}" + register: openproject_rails_runner + retries: 30 + delay: 5 + until: openproject_rails_runner.rc == 0 + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-openproject/tasks/04_admin/state.yml b/roles/web-app-openproject/tasks/04_admin/state.yml new file mode 100644 index 0000000000..2ed91cda4b --- /dev/null +++ b/roles/web-app-openproject/tasks/04_admin/state.yml @@ -0,0 +1,30 @@ +--- +- name: 🔍 Read the settings, administrator and LDAP link OpenProject holds + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ [role_path, 'files/sql/select/admin-state.sql'] | path_join }}" + named_args: + login: "{{ OPENPROJECT_ADMINISTRATOR_USERNAME }}" + ldap_name: "{{ OPENPROJECT_ADMIN_LDAP_NAME }}" + settings: "{{ OPENPROJECT_RAILS_SETTINGS | list | to_json }}" + expect_rows: true + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: openproject_admin_state + until: openproject_admin_state is succeeded + retries: 6 + delay: 5 + changed_when: false + +- name: 🧮 Digest the run's sources, inputs and the state OpenProject holds + ansible.builtin.set_fact: + openproject_admin_digest: >- + {{ { + 'sources': query('file', *OPENPROJECT_ADMIN_SOURCES) | map('hash', 'sha256') | list, + 'version': OPENPROJECT_VERSION, + 'login': OPENPROJECT_ADMINISTRATOR_USERNAME, + 'email': OPENPROJECT_ADMINISTRATOR_EMAIL, + 'password': OPENPROJECT_ADMINISTRATOR_PASSWORD | hash('sha256'), + 'settings': OPENPROJECT_RAILS_SETTINGS | to_json(sort_keys=true) | hash('sha256'), + 'ldap_name': OPENPROJECT_ADMIN_LDAP_NAME, + 'state': openproject_admin_state.rows + } | to_json(sort_keys=true) | hash('sha256') }} diff --git a/roles/web-app-openproject/tasks/addons/gitlab_integration.yml b/roles/web-app-openproject/tasks/addons/gitlab_integration.yml index ff1ce71d07..2f35d87c66 100644 --- a/roles/web-app-openproject/tasks/addons/gitlab_integration.yml +++ b/roles/web-app-openproject/tasks/addons/gitlab_integration.yml @@ -59,6 +59,6 @@ msg: >- {{ application_id }}: the OpenProject side is configured. No GitLab webhook exists - register one against - {{ lookup('tls', application_id, 'url.base') | regex_replace('/$', '') }}{{ openproject_addon.value.config.webhook_path }}?key= + {{ lookup('tls', application_id, 'url.origin') }}{{ openproject_addon.value.config.webhook_path }}?key= with the X-Gitlab-Token header set to the webhook secret, triggers push/comments/issues/merge_request/pipeline. diff --git a/roles/web-app-openproject/templates/proxy.conf.j2 b/roles/web-app-openproject/templates/proxy.conf.j2 index 7b9b4c16f9..e8671bd2dc 100644 --- a/roles/web-app-openproject/templates/proxy.conf.j2 +++ b/roles/web-app-openproject/templates/proxy.conf.j2 @@ -16,19 +16,14 @@ server {% if lookup('network_handover', application_id, domain) %} {% include 'roles/sys-svc-proxy/templates/location/handover.conf.j2' %} - {% elif lookup('sso', application_id, 'is_proxy_gated') %} - {% set sso_proxy_enabled = true %} - {% set webserver_location_extra_configuration %} + {% else %} + {% set sso_gated_location_extra_configuration %} proxy_set_header X-Remote-User "${authrequest_username}:{{ lookup('config', application_id, 'secrets.credentials.auth_source_sso_secret') }}"; {% endset %} - {% set location = '/' %} - {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} - {% set webserver_location_extra_configuration = '' %} - {% else %} - {% set sso_proxy_enabled = false %} - {% set webserver_location_extra_configuration = '' %} - {% set location = '/' %} - {% include 'roles/sys-svc-proxy/templates/location/html.conf.j2' %} + {% set sso_open_location_extra_configuration %} + proxy_set_header X-Remote-User ""; + {% endset %} + {% include 'roles/sys-svc-proxy/templates/location/sso_acl.conf.j2' %} {% endif %} {% include 'roles/web-app-prometheus/templates/nginx/locations.conf.j2' %} diff --git a/roles/web-app-openproject/vars/main.yml b/roles/web-app-openproject/vars/main.yml index 621800589f..db1865ee15 100644 --- a/roles/web-app-openproject/vars/main.yml +++ b/roles/web-app-openproject/vars/main.yml @@ -51,6 +51,15 @@ OPENPROJECT_UPGRADE_RUN: OPENPROJECT_ADMINISTRATOR_USERNAME: "{{ lookup('users', 'platform_administrator').username }}" OPENPROJECT_ADMINISTRATOR_PASSWORD: "{{ lookup('users', 'platform_administrator').password }}" OPENPROJECT_ADMINISTRATOR_EMAIL: "{{ lookup('users', 'platform_administrator').email }}" +OPENPROJECT_ADMIN_FORCE: "{{ lookup('config', application_id, 'services.openproject.admin.force') }}" +OPENPROJECT_ADMIN_LDAP_NAME: "{{ OPENPROJECT_LDAP.name if (OPENPROJECT_HEADER_SSO_ENABLED | bool) else '' }}" +OPENPROJECT_ADMIN_STAMP_FILE: "{{ [lookup('container', application_id, 'directories.instance'), 'admin-provision.sha256'] | path_join }}" +OPENPROJECT_ADMIN_SOURCES: + - "{{ [role_path, 'tasks/04_admin/provision.yml'] | path_join }}" + - "{{ [role_path, 'files/ruby/apply_settings.rb'] | path_join }}" + - "{{ [role_path, 'files/ruby/ensure_admin_user.rb'] | path_join }}" + - "{{ [role_path, 'files/ruby/lock_seeded_admin.rb'] | path_join }}" + - "{{ [role_path, 'files/ruby/link_admin_to_ldap.rb'] | path_join }}" OPENPROJECT_CACHE_CONTAINER: "{{ lookup('config', application_id, 'services.cache.name') }}" diff --git a/roles/web-app-opentalk/tasks/02_keycloak_client.yml b/roles/web-app-opentalk/tasks/02_keycloak_client.yml index e081ce8dab..2afebe388d 100644 --- a/roles/web-app-opentalk/tasks/02_keycloak_client.yml +++ b/roles/web-app-opentalk/tasks/02_keycloak_client.yml @@ -76,7 +76,7 @@ - name: "📝 Upsert dedicated public Keycloak client for the OpenTalk frontend" vars: - opentalk_frontend_origin: "{{ OPENTALK_URL | regex_replace('/+$', '') }}" + opentalk_frontend_origin: "{{ lookup('tls', application_id, 'url.origin') }}" keycloak_kcadm_update: object_kind: "client" lookup_value: "{{ OPENTALK_FRONTEND_OIDC_CLIENT_ID }}" diff --git a/roles/web-app-opentalk/templates/nginx/extra.conf.j2 b/roles/web-app-opentalk/templates/nginx/extra.conf.j2 index 6d1bcc5e73..60bccc4f9c 100644 --- a/roles/web-app-opentalk/templates/nginx/extra.conf.j2 +++ b/roles/web-app-opentalk/templates/nginx/extra.conf.j2 @@ -4,10 +4,7 @@ location /v1/ { {{ opentalk_controller_backend }} {% include 'roles/sys-svc-proxy/templates/headers/upstream_strips.conf.j2' %} proxy_http_version 1.1; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; + {% include 'roles/sys-svc-proxy/templates/headers/forwarded_base.conf.j2' %} proxy_buffering off; proxy_request_buffering off; client_max_body_size 0; @@ -19,10 +16,7 @@ location /v1/signaling/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; + {% include 'roles/sys-svc-proxy/templates/headers/forwarded_base.conf.j2' %} proxy_read_timeout 86400; proxy_buffering off; } @@ -33,10 +27,7 @@ location ~ ^/livekit/(?.*)$ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; + {% include 'roles/sys-svc-proxy/templates/headers/forwarded_base.conf.j2' %} proxy_read_timeout 86400; proxy_buffering off; } diff --git a/roles/web-app-opentalk/vars/main.yml b/roles/web-app-opentalk/vars/main.yml index cfa2bd79b5..d3aeff48da 100644 --- a/roles/web-app-opentalk/vars/main.yml +++ b/roles/web-app-opentalk/vars/main.yml @@ -41,7 +41,7 @@ OPENTALK_RECORDER_HTTP_PORT: "{{ lookup('config', application_id, 'services.reco OPENTALK_RECORDER_API_KEY_ID: "recorder" OPENTALK_RECORDER_API_SECRET: "{{ lookup('config', application_id, 'secrets.credentials.recorder_api_secret') }}" -OPENTALK_KEYCLOAK_BASE_URL: "{{ lookup('tls', 'web-app-keycloak', 'url.base') | regex_replace('/+$','') }}" +OPENTALK_KEYCLOAK_BASE_URL: "{{ lookup('tls', 'web-app-keycloak', 'url.origin') }}" OPENTALK_KEYCLOAK_CONTAINER_ADDRESS: "{{ lookup('container_address', 'web-app-keycloak', 'keycloak') }}" OPENTALK_KEYCLOAK_REALM: "{{ OIDC.CLIENT.REALM }}" diff --git a/roles/web-app-pixelfed/vars/main.yml b/roles/web-app-pixelfed/vars/main.yml index ad126cf192..f423b9cf58 100644 --- a/roles/web-app-pixelfed/vars/main.yml +++ b/roles/web-app-pixelfed/vars/main.yml @@ -6,7 +6,7 @@ swarm_stack_converge_retries: 600 PIXELFED_CONTAINER: "{{ lookup('config', application_id, 'services.pixelfed.name') }}" PIXELFED_WORKER_CONTAINER: "{{ lookup('config', application_id, 'services.worker.name') }}" PIXELFED_TITLE: "{{ lookup('design', application_id).label }}" -PIXELFED_URL: "{{ lookup('tls', application_id, 'url.base') | regex_replace('/+$', '') }}" +PIXELFED_URL: "{{ lookup('tls', application_id, 'url.origin') }}" PIXELFED_OIDC_ENABLED: "{{ lookup('config', application_id, 'services.sso.enabled') }}" PIXELFED_OIDC_ONION_ISSUER: "{{ lookup('tls', 'web-app-keycloak', 'domain').endswith('.onion') }}" PIXELFED_OIDC_SOCKS_PROXY: "{{ lookup('tor_socks_proxy') if PIXELFED_OIDC_ONION_ISSUER | bool else '' }}" diff --git a/roles/web-app-pretix/meta/services.yml b/roles/web-app-pretix/meta/services.yml index d826646453..f5be2ee08b 100644 --- a/roles/web-app-pretix/meta/services.yml +++ b/roles/web-app-pretix/meta/services.yml @@ -56,7 +56,7 @@ pretix: # nocheck: docker-version runtime base of the source build, not the served application version: "3.13" source_repository: https://github.com/pretix/pretix.git - source_version: v2026.8.0 + source_version: v2026.8.1 update: - key: source_version type: git_tags diff --git a/roles/web-app-roulette-wheel/templates/style.css.j2 b/roles/web-app-roulette-wheel/templates/style.css.j2 index 978f9ce046..62d1cae250 100644 --- a/roles/web-app-roulette-wheel/templates/style.css.j2 +++ b/roles/web-app-roulette-wheel/templates/style.css.j2 @@ -1,4 +1,4 @@ -{% set base = lookup('tls', application_id, 'url.base') | regex_replace('/+$', '') %} +{% set base = lookup('tls', application_id, 'url.origin') %} body { background-color: var(--design-surface-1); color: var(--design-text); diff --git a/roles/web-app-seaweedfs/templates/nginx.conf.j2 b/roles/web-app-seaweedfs/templates/nginx.conf.j2 index 1476ad43d0..f8602f0b7a 100644 --- a/roles/web-app-seaweedfs/templates/nginx.conf.j2 +++ b/roles/web-app-seaweedfs/templates/nginx.conf.j2 @@ -7,10 +7,7 @@ server { location / { proxy_pass http://{{ SEAWEEDFS_ENGINE_HOST }}:{{ SEAWEEDFS_ENGINE_FILER_PORT }}; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; + {% include 'roles/sys-svc-proxy/templates/headers/forwarded_base.conf.j2' %} } } @@ -20,10 +17,7 @@ server { location / { proxy_pass http://{{ SEAWEEDFS_ENGINE_HOST }}:{{ SEAWEEDFS_ENGINE_MASTER_PORT }}; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; + {% include 'roles/sys-svc-proxy/templates/headers/forwarded_base.conf.j2' %} } } diff --git a/roles/web-app-snipe-it/templates/env.j2 b/roles/web-app-snipe-it/templates/env.j2 index 89db7775a6..e15d62bc8b 100644 --- a/roles/web-app-snipe-it/templates/env.j2 +++ b/roles/web-app-snipe-it/templates/env.j2 @@ -4,7 +4,7 @@ APP_ENV={{ ENVIRONMENT | lower }} APP_DEBUG={{MODE_DEBUG | string | lower }} APP_KEY={{ lookup('config', application_id, 'secrets.credentials.app_key')}} -APP_URL={{ SNIPE_IT_URL | regex_replace('/$', '') }} +APP_URL={{ lookup('tls', application_id, 'url.origin') }} APP_TIMEZONE={{ HOST_TIMEZONE | dotenv_quote }} APP_LOCALE={{ HOST_LL_CC }} MAX_RESULTS=500 diff --git a/roles/web-app-stalwart/README.md b/roles/web-app-stalwart/README.md index 90017b3e81..fe09675c9a 100644 --- a/roles/web-app-stalwart/README.md +++ b/roles/web-app-stalwart/README.md @@ -72,6 +72,10 @@ delegates **interactive** authentication to Keycloak: (a claim that already holds an `@` is taken as is), creating it on first login. - **Roundcube** logs users in over OAuth2 and talks to Stalwart with **XOAUTH2** (`templates/roundcube-oauth.inc.php.j2`). +- The OIDC directory skips the audience check and gives Keycloak tokens without + Stalwart scopes access to mail, contacts, calendars and files + (`STALWART_OIDC_TOKEN_VALIDATION`). Tokens of the `stalwart-webui` client get + full access, because the WebUI Application names it as its `oauthClientId`. **Design constraint (validated against the live JMAP schema):** Stalwart's authentication directory is *Internal XOR one external directory* — there is no @@ -99,6 +103,22 @@ authenticated sessions in both modes (`STALWART_RELAY_RULE`). With SSO disabled the role uses the Internal directory and the bot's derived account password. +## WebUI sign-in + +The WebUI Application always names `stalwart-webui` (`STALWART_WEBUI_OAUTH_CLIENT_ID`) as its `oauthClientId`, with and without SSO. +Where the WebUI sends a login depends on the account: + +| Account | Authorization server | Client `stalwart-webui` | +|---|---|---| +| Account in a domain bound to the Keycloak OIDC directory | Keycloak | Keycloak client from `templates/keycloak/clients.json.j2` | +| Recovery admin (`STALWART_ADMIN_USER`), and every account while SSO is off | Stalwart | OAuth client the role registers in Stalwart (`tasks/02_webadmin.yml`) | + +The role registers that Stalwart client over JMAP (`templates/jmap/oauth_client/`) as a public first-party client, with one redirect URI `//oauth/callback` and one post-logout URI `//login` per URL prefix of the WebUI Application. +`` is the role's canonical WebUI URL (`STALWART_WEBUI_BASE_URL`), so a Tor deployment registers its `http://` onion origin. +Every deploy compares the registered client with that target and updates it when they differ. +A deployment that serves the WebUI on a further origin MUST add that origin's URIs to [`templates/jmap/oauth_client/webui.json.j2`](templates/jmap/oauth_client/webui.json.j2), because a URI added in Stalwart alone is removed by the next deploy. +Stalwart's login page asks for consent before the password form for every registered client, so a native WebUI login shows an **Allow** step. + ## Calendar & Contacts (CalDAV / CardDAV / WebDAV) Stalwart serves DAV natively on the mail HTTP listener — no extra container @@ -118,7 +138,7 @@ account (or the Keycloak SSO token when SSO is enabled). instance dir, and per-round downloads hit GitHub rate limits) and bind-mounts it read-only. The `update:` block next to `webui_version` in `meta/services.yml` names the upstream tags, so the version-source updater - bumps the bundle on its own. + bumps the bundle on its own, within the `v2.` line that server 1.x serves. - **The embedded PostgreSQL pins the plain `postgres` image** — the platform's postgis default defeats baudolo's substring database detection and would degrade backups to torn live-file snapshots. `backup.project_hard_restart` @@ -131,12 +151,13 @@ account (or the Keycloak SSO token when SSO is enabled). (`templates/jmap/*.json.j2`). - **Only authenticated sessions relay, with or without SSO.** Under SSO a bot authenticates with an app password. -- **Accounts and app passwords are provisioned in batches.** Each phase - (create, password update, app password list, mint, retire, drop) is one JMAP - request for all accounts. A phase on the bots' app passwords carries one - method call per bot, at most `STALWART_JMAP_MAX_METHOD_CALLS` (Stalwart's - default `maxMethodCalls`) per request, and a refusal names the account it - hit. +- **Accounts, app passwords and forwards are provisioned in batches.** Each + phase (create, password update, app password list, mint, retire, drop, + forward script list, read, upload, activate) is one JMAP request for all + accounts. A phase on the bots' app passwords or the forward scripts carries + one method call per account, addressed through its `accountId` by the + recovery admin, at most `STALWART_JMAP_MAX_METHOD_CALLS` (Stalwart's default + `maxMethodCalls`) per request, and a refusal names the account it hit. - **Address bans expire after `services.stalwart.ban_period_seconds`** (one hour by default). Without a period Stalwart keeps a ban forever, and the reverse proxy, the published ports, Tor and the swarm ingress hand many @@ -147,8 +168,8 @@ account (or the Keycloak SSO token when SSO is enabled). - **HTTP clients are rate-limited and banned by their own address.** The vhost sets `proxy_forwarded_client_address`, so OpenResty sends `Forwarded: for=$remote_addr` on every location and replaces any - client-supplied value, and Stalwart reads it (`STALWART_HTTP_SETTINGS`, - `useXForwarded`). + client-supplied value, and Stalwart reads it (`STALWART_HTTP_SETTINGS`: + `clientIpSource: forwarded` with one trusted hop, `forwardedHops: 1`). - **Bans and failed logins also go to the container output** (`STALWART_BAN_TRACER`, `tasks/tracing.yml`), next to the daily log file in the data volume. @@ -249,6 +270,78 @@ applications: - The source is not served by Stalwart and gets no DKIM key; it receives mail but sends none. - Removing every alias domain leaves the last rewrite in Stalwart; set the RCPT stage's rewrite back to `false` in WebAdmin. +## Upgrading from 0.16 + +Stalwart 1.x refuses to open a 0.16 store and has no in-place upgrade. Every deploy checks the store in the role's database before it starts Stalwart, whatever state the running server is in, and stops when the store predates 1.0 ([`tasks/store_guard.yml`](tasks/store_guard.yml)). A store from before 1.0 keeps a `bigint` column `v` in table `u`, a 1.x store a `bytea` one, and a database without that column holds no store yet. + +A deploy that has brought Stalwart 1.x up on the store and finished its provisioning writes the marker `store.layout`, holding the store layout version `1`, into the role's instance directory on the stack host (`STALWART_STORE_MARKER_FILE`, written last in [`tasks/manager_ops.yml`](tasks/manager_ops.yml)). +A failed deploy writes no marker. +A deploy that finds the marker passes without reading the store. +A deploy without the marker reads the store: + +| Database | No store yet | Store to read | +|---|---|---| +| Shared PostgreSQL | the `postgres` superuser finds no database `stalwart` in the catalog | read as the role's database user | +| Dedicated PostgreSQL | the volume `stalwart_database` does not exist | read inside the dedicated database container; when that container is not running, the deploy stops and names the database service to start | + +Migrate the store with [`stalwart-migrate`](https://github.com/stalwartlabs/stalwart-migrate) into a new database and swap it in under the role's database name. That name is fixed to `stalwart` ([`plugins/lookup/database.py`](../../plugins/lookup/database.py) derives it from the entity name), so the migration targets a second database that later takes over the name. + +A deploy whose store guard finds a 0.16 store migrates it on its own ([`tasks/store_guard/migrate.yml`](tasks/store_guard/migrate.yml)): it stages `migrate-v016/migrate.sh` in the role's instance directory (`STALWART_MIGRATE_SCRIPT`, a copy of [`files/shell/migrate_v016.sh`](files/shell/migrate_v016.sh)), the values it reads in `migrate.env` ([`templates/migrate.env.j2`](templates/migrate.env.j2)) and the target configuration, runs the phases below from `upgrade` to `final`, reads the store layout again and deploys Stalwart 1.x on the migrated store. Mail is down from the stop in `final` until the deploy starts 1.x. A failing phase stops the deploy with the 0.16 store and server back in place. The phases also run by hand, as root: + +| Phase | Steps below | +|---|---| +| `upgrade` | 1: pulls the floating tag of the source series the `stalwart_migrate` image names in its `--help` banner (`v0.16`, the last 0.16 release) and recreates Stalwart on it when the running image differs (compose: `compose -f compose.upgrade.yml up -d`, swarm: `service update --image`) | +| `check` | 1: the running Stalwart must be that exact image and the role's `version` must belong to the banner's target series; plus the guard's own conditions: 0.16 store, no swap yet, no marker | +| `backup` | 2, the database dump only | +| `target` | 3 | +| `prepare` | 5, interactive on a terminal; without one it accepts the recommended answer of every question `stalwart-migrate` marks as not answered in `migrate-v016/state/answers.toml` | +| `sync` | 5, repeatable while 0.16 serves | +| `final` | 6 and 7 | +| `status` | the progress `stalwart-migrate status` reports | +| `all` | `upgrade` to `final` in order | + +Then deploy again (step 8). The steps by hand: + +1. Make sure the server runs Stalwart `v0.16.27`; `stalwart-migrate` reads no other release. Upgrade an older 0.16 server with the previous revision of this role first. +2. Back up the database `stalwart` (for example `pg_dump -Fc -d stalwart -f stalwart-v016.dump`) and the role's volumes. +3. As a PostgreSQL superuser, create the empty target database, owned by the role's database user: + + ```sql + CREATE DATABASE stalwart_v1 OWNER stalwart; + ``` + +4. Copy the rendered `config.json` (`STALWART_CONFIG_FILE`, `etc/config.json` in the role's volumes directory) into a new directory and set its `"database"` to `"stalwart_v1"`. This file is the `--target`. +5. Answer the conversion questions and copy the data while 0.16 keeps serving. Run the tool on the network the `stalwart` container reaches its database on (`docker inspect stalwart`), so the hosts in both files resolve: + + ```sh + docker run --rm -it --network \ + -v /etc:/etc/stalwart:ro \ + -v :/etc/stalwart-v1 \ + -v :/var/lib/stalwart-migrate \ + stalwartlabs/stalwart-migrate:1.0.0 prepare \ + --source /etc/stalwart/config.json \ + --state /var/lib/stalwart-migrate + ``` + + Then run the same container with `run --source /etc/stalwart/config.json --target /etc/stalwart-v1/config.json --state /var/lib/stalwart-migrate`. `run` copies only what changed since the previous run and may be repeated. +6. Stop the Stalwart server (`docker stop stalwart` in compose, `docker service scale _stalwart=0` in swarm) and run the same container with `run --final` and the same options. It verifies the copy and writes `final-report.txt` into the state directory. +7. Swap the databases, as a PostgreSQL superuser connected to the `postgres` database: + + ```sql + ALTER DATABASE stalwart RENAME TO stalwart_v016; + ALTER DATABASE stalwart_v1 RENAME TO stalwart; + ``` + +8. Deploy this role. The store guard finds the migrated 1.x store under the role's database name and lets Stalwart 1.x start on it. +9. Keep `stalwart_v016`, the dump and the state directory until 1.x is verified. `stalwart-migrate rollback` reads the state directory to copy the 1.x store back into a new 0.16 store. + +### Restore and redeploy + +The marker lives outside the stack and its volumes, so it survives `docker stack rm`, `docker compose down`, a crashed database and the stop and start cycle of `backup.project_hard_restart`. +A host that carries the marker therefore redeploys while its dedicated database is down, as in the restore of [`svc-bkp-nfs-2-local`](../svc-bkp-nfs-2-local/README.md) (`docker stack rm`, restore, redeploy). +A dedicated store on a host without the marker, such as a 0.16 host or a host whose instance directory was lost, needs its database running before the deploy: start the database service of the stack the host last deployed, then deploy. +Before a host that carries the marker goes back to a 0.16 store, through `stalwart-migrate rollback` or a backup taken under 0.16, delete the marker, so the next deploy reads the store. + ## Verifying a production server Deploying against a publicly reachable mail server additionally asserts that server's live **hard facts** — the records and listeners either match the deployed configuration or they do not. There is no mail-flow scenario here; that is what the suites above are for. diff --git a/roles/web-app-stalwart/files/playwright/test-login-native.js b/roles/web-app-stalwart/files/playwright/test-login-native.js index ea3b2d01ae..5bab25daed 100644 --- a/roles/web-app-stalwart/files/playwright/test-login-native.js +++ b/roles/web-app-stalwart/files/playwright/test-login-native.js @@ -30,16 +30,10 @@ test("administrator: webmail password login reaches the mailbox (no sso)", async await expect(page.locator("#mailboxlist li.mailbox.inbox")).toBeVisible(); }); -// WebAdmin native login: the variant where Keycloak is absent and Stalwart's own -// directory owns the credentials. Without this the sso=false variant deploys a -// login surface no spec ever exercises, because every other spec self-skips on sso. -// The account is Stalwart's own WebAdmin administrator (STALWART_ADMIN_USER), not the -// platform's administrator — the latter lives in the OIDC directory and is rejected here. -test("administrator: stalwart native login and logout (no sso)", async ({ page }) => { - test.skip( - safeIsEnabled("sso"), - "Native login is only exercised in the variant without Keycloak — when SSO is on the OIDC path owns the journey.", - ); +// The account is Stalwart's recovery admin (STALWART_ADMIN_USER), not the platform's administrator: +// discovery sends it to Stalwart's own OAuth server even when Keycloak serves the mail domain, so this +// journey runs with and without SSO. +test("administrator: stalwart recovery admin native login and logout", async ({ page }) => { expect(stalwartAdminUsername, "STALWART_ADMIN_USERNAME must be set").toBeTruthy(); expect(stalwartAdminPassword, "STALWART_ADMIN_PASSWORD must be set").toBeTruthy(); @@ -59,6 +53,11 @@ test("administrator: stalwart native login and logout (no sso)", async ({ page } .first() .click(); + // Stalwart asks consent for every registered OAuth client before it shows the password form. + const allow = page.getByRole("button", { name: /^allow$/i }); + await allow.waitFor({ state: "visible", timeout: resolveTimeout(30_000) }); + await allow.click(); + const passwordField = page.locator("input[type='password'], input[name='password']").first(); await passwordField.waitFor({ state: "visible", timeout: resolveTimeout(30_000) }); await passwordField.fill(stalwartAdminPassword); diff --git a/roles/web-app-stalwart/files/shell/migrate_v016.sh b/roles/web-app-stalwart/files/shell/migrate_v016.sh new file mode 100644 index 0000000000..be7a632494 --- /dev/null +++ b/roles/web-app-stalwart/files/shell/migrate_v016.sh @@ -0,0 +1,233 @@ +#!/usr/bin/env bash +# Param $1: upgrade | check | backup | target | prepare | sync | final | status | all, the steps of "Upgrading from 0.16" in roles/web-app-stalwart/README.md. +# Param migrate.env: the values the deploy rendered next to this script. +set -euo pipefail +umask 077 + +HERE="$(dirname "$(readlink -f "$0")")" +readonly HERE +readonly ENV_FILE="${HERE}/migrate.env" +readonly UPGRADE_OVERRIDE="${HERE}/compose.upgrade.yml" +readonly SOURCE_MOUNT=/migrate/source +readonly TARGET_MOUNT=/migrate/target +readonly STATE_MOUNT=/migrate/state +readonly HEALTH_TIMEOUT_SECONDS=300 + +# shellcheck source=/dev/null +source "$ENV_FILE" + +die() { + echo "migrate: $*" >&2 + exit 1 +} + +stop_stalwart() { + if [ "$DEPLOYMENT_MODE" = "swarm" ]; then + container service scale "${STALWART_SERVICE:?}=0" + else + container stop "$STALWART_CONTAINER" + fi +} + +start_stalwart() { + if [ "$DEPLOYMENT_MODE" = "swarm" ]; then + container service scale "${STALWART_SERVICE:?}=1" + else + container start "$STALWART_CONTAINER" + fi +} + +psql_admin() { + container exec -i "$PG_ADDRESS" psql -X -q -v ON_ERROR_STOP=1 -U "$PG_ADMIN" -d "$1" -At -c "$2" +} + +database_exists() { + [ "$(psql_admin postgres "SELECT count(*) FROM pg_database WHERE datname = '$1'")" = "1" ] +} + +migrate() { + local tty=() + if [ -t 0 ] && [ -t 1 ]; then + tty=(-it) + fi + container run --rm "${tty[@]}" --user 0:0 --network "$NETWORK" \ + -v "${SOURCE_DIR}:${SOURCE_MOUNT}:ro" \ + -v "${TARGET_DIR}:${TARGET_MOUNT}:ro" \ + -v "${STATE_DIR}:${STATE_MOUNT}" \ + "$IMAGE" "$@" +} + +read_series() { + local help banner + help="$(container run --rm --user 0:0 "$IMAGE" --help)" + banner="$(grep -m1 -E 'Stalwart v[0-9]+\.[0-9]+ deployment to v[0-9]+\.[0-9]+' <<< "$help")" \ + || die "${IMAGE} does not name its source and target series in its --help output" + [[ "$banner" =~ Stalwart\ (v[0-9]+\.[0-9]+)\ deployment\ to\ (v[0-9]+\.[0-9]+) ]] \ + || die "${IMAGE} does not name its source and target series in '${banner}'" + SOURCE_SERIES="${BASH_REMATCH[1]}" + TARGET_SERIES="${BASH_REMATCH[2]}" +} + +running_image() { + container inspect --type container --format '{{.Config.Image}}' "$STALWART_ADDRESS" \ + || die "no Stalwart container found; start the stack this host last deployed" +} + +running_image_id() { + container inspect --type container --format '{{.Image}}' "$STALWART_ADDRESS" +} + +required_image() { + local current + current="$(running_image)" + echo "${current%:*}:${SOURCE_SERIES}" +} + +pull_required_image_id() { + container pull -q "$(required_image)" > /dev/null + container image inspect --format '{{.Id}}' "$(required_image)" +} + +wait_healthy() { + local deadline status + deadline=$((SECONDS + HEALTH_TIMEOUT_SECONDS)) + while [ "$SECONDS" -lt "$deadline" ]; do + # shellcheck source=/dev/null + source "$ENV_FILE" + status="$(container inspect --type container --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$STALWART_ADDRESS" 2> /dev/null || true)" # nocheck: shell-or-true the container is being recreated, a missing one is retried until the deadline + case "$status" in + healthy | running) return 0 ;; + esac + sleep 5 + done + die "Stalwart did not become healthy within ${HEALTH_TIMEOUT_SECONDS}s after the upgrade" +} + +phase_upgrade() { + read_series + local current required required_id + current="$(running_image)" + [[ "${current##*:}" == "${SOURCE_SERIES}."* || "${current##*:}" == "${SOURCE_SERIES}" ]] \ + || die "Stalwart runs ${current}, outside the ${SOURCE_SERIES} series that ${IMAGE} migrates" + required="$(required_image)" + required_id="$(pull_required_image_id)" + if [ "$(running_image_id)" = "$required_id" ]; then + echo "upgrade: ${current} already is the last ${SOURCE_SERIES} release" + return 0 + fi + if [ "$DEPLOYMENT_MODE" = "swarm" ]; then + container service update --image "$required" "${STALWART_SERVICE:?}" + else + printf 'services:\n %s:\n image: "%s"\n' "$COMPOSE_SERVICE" "$required" > "$UPGRADE_OVERRIDE" + compose --chdir "$STACK_DIR" -f "$UPGRADE_OVERRIDE" up -d "$COMPOSE_SERVICE" + fi + wait_healthy + [ "$(running_image_id)" = "$required_id" ] || die "Stalwart still runs ${current} after the upgrade to ${required}" + echo "upgrade: ${current} -> ${required}" +} + +phase_check() { + read_series + local current required_id networks + current="$(running_image)" + required_id="$(pull_required_image_id)" + [ "$(running_image_id)" = "$required_id" ] \ + || die "Stalwart runs ${current}, not the last ${SOURCE_SERIES} release $(required_image); run the upgrade phase first" + [[ "$TARGET_VERSION" == "${TARGET_SERIES}."* ]] \ + || die "the role deploys Stalwart ${TARGET_VERSION}, but ${IMAGE} writes ${TARGET_SERIES} stores" + # shellcheck disable=SC2016 + networks="$(container inspect --type container --format '{{range $name, $_ := .NetworkSettings.Networks}}{{$name}} {{end}}' "$STALWART_ADDRESS")" + [[ " ${networks} " == *" ${NETWORK} "* ]] \ + || die "Stalwart is attached to '${networks}', not to the database network ${NETWORK}" + ! database_exists "$DB_V016" || die "database ${DB_V016} exists, the swap ran already" + [ "$(psql_admin "$DB" "$LAYOUT_SQL")" = "bigint" ] || die "database ${DB} holds no 0.16 store" + [ ! -e "$MARKER" ] || die "${MARKER} marks this host as migrated; remove it only if the store really is 0.16" + echo "check: ${current} is the last ${SOURCE_SERIES} release on a 0.16 store in database ${DB}; ${IMAGE} writes ${TARGET_SERIES} for ${TARGET_VERSION}; network ${NETWORK}" +} + +phase_backup() { + mkdir -p "$(dirname "$BACKUP_FILE")" + container exec "$PG_ADDRESS" pg_dump -Fc -U "$PG_ADMIN" -d "$DB" > "${BACKUP_FILE}.part" + mv "${BACKUP_FILE}.part" "$BACKUP_FILE" + echo "backup: ${BACKUP_FILE} ($(du -h "$BACKUP_FILE" | cut -f1))" +} + +phase_target() { + if database_exists "$DB_V1"; then + echo "target: database ${DB_V1} exists, the next sync continues it" + else + psql_admin postgres "CREATE DATABASE \"${DB_V1}\" OWNER \"${DB_OWNER}\"" + echo "target: created database ${DB_V1} owned by ${DB_OWNER}" + fi +} + +accept_recommended_answers() { + local answers="${STATE_DIR}/answers.toml" + [ -f "$answers" ] || die "prepare wrote no ${answers}" + awk ' + /^# Not answered yet: uncomment the table to accept the recommended values\.$/ { open = 1; print; next } + open && /^# / { sub(/^# /, ""); print; next } + { open = 0; print } + ' "$answers" > "${answers}.part" + mv "${answers}.part" "$answers" +} + +phase_prepare() { + mkdir -p "$STATE_DIR" + if [ -t 0 ] && [ -t 1 ]; then + migrate prepare --source "${SOURCE_MOUNT}/config.json" --state "$STATE_MOUNT" + return 0 + fi + if ! migrate prepare --source "${SOURCE_MOUNT}/config.json" --state "$STATE_MOUNT" --non-interactive; then + accept_recommended_answers + migrate prepare --source "${SOURCE_MOUNT}/config.json" --state "$STATE_MOUNT" --non-interactive \ + || die "questions remain open after accepting the recommended answers; run prepare on a terminal" + echo "prepare: accepted the recommended answers in ${STATE_DIR}/answers.toml" + fi +} + +phase_sync() { + migrate run --source "${SOURCE_MOUNT}/config.json" --target "${TARGET_MOUNT}/config.json" --state "$STATE_MOUNT" +} + +phase_final() { + phase_check + stop_stalwart + if ! migrate run --final --yes --source "${SOURCE_MOUNT}/config.json" --target "${TARGET_MOUNT}/config.json" --state "$STATE_MOUNT"; then + start_stalwart + die "the final run failed and nothing was swapped; Stalwart 0.16 serves again, see ${STATE_DIR}/final-report.txt" + fi + psql_admin postgres "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname IN ('${DB}', '${DB_V1}') AND pid <> pg_backend_pid()" > /dev/null + psql_admin postgres "ALTER DATABASE \"${DB}\" RENAME TO \"${DB_V016}\"" + if ! psql_admin postgres "ALTER DATABASE \"${DB_V1}\" RENAME TO \"${DB}\""; then + psql_admin postgres "ALTER DATABASE \"${DB_V016}\" RENAME TO \"${DB}\"" + start_stalwart + die "renaming ${DB_V1} to ${DB} failed; ${DB} is the 0.16 store again and Stalwart 0.16 serves it" + fi + [ "$(psql_admin "$DB" "$LAYOUT_SQL")" = "bytea" ] || die "database ${DB} does not hold a 1.x store after the swap" + echo "final: ${DB} holds the 1.x store, ${DB_V016} the 0.16 one; deploy web-app-stalwart next" +} + +phase_status() { + migrate status --state "$STATE_MOUNT" +} + +phase_all() { + phase_upgrade + phase_check + phase_backup + phase_target + phase_prepare + phase_sync + phase_final +} + +case "${1:-}" in + upgrade | check | backup | target | prepare | sync | final | status | all) + "phase_$1" + ;; + *) + echo "usage: $0 upgrade|check|backup|target|prepare|sync|final|status|all" >&2 + exit 2 + ;; +esac diff --git a/roles/web-app-stalwart/files/sql/store/database.sql b/roles/web-app-stalwart/files/sql/store/database.sql new file mode 100644 index 0000000000..053b8dd618 --- /dev/null +++ b/roles/web-app-stalwart/files/sql/store/database.sql @@ -0,0 +1,3 @@ +SELECT count(*) +FROM pg_catalog.pg_database +WHERE datname = %(name)s; diff --git a/roles/web-app-stalwart/files/sql/store/layout.sql b/roles/web-app-stalwart/files/sql/store/layout.sql new file mode 100644 index 0000000000..97bde8ab74 --- /dev/null +++ b/roles/web-app-stalwart/files/sql/store/layout.sql @@ -0,0 +1,9 @@ +SELECT + coalesce(( + SELECT format_type(attribute.atttypid, attribute.atttypmod) + FROM pg_catalog.pg_attribute AS attribute + WHERE + attribute.attrelid = to_regclass('u') + AND attribute.attname = 'v' + AND NOT attribute.attisdropped + ), 'absent'); diff --git a/roles/web-app-stalwart/meta/csp.yml b/roles/web-app-stalwart/meta/csp.yml index fdf8f27457..178a954acb 100644 --- a/roles/web-app-stalwart/meta/csp.yml +++ b/roles/web-app-stalwart/meta/csp.yml @@ -9,4 +9,4 @@ flags: unsafe-eval: true # nocheck: csp-unsafe Reason: the WebAdmin bundle builds functions dynamically at runtime; blocked, the SPA aborts during boot with an EvalError before it renders. whitelist: connect-src: - - "{{ lookup('tls', 'web-app-keycloak', 'url.base') | regex_replace('/+$', '') }}" + - "{{ lookup('tls', 'web-app-keycloak', 'url.origin') }}" diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index de8e8b3dee..5ef5cb606e 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -43,13 +43,13 @@ stalwart: # nocheck: default-placement-manager mail edge at a known IP: MX A-record, PTR and SPF bind to the stack host IP (a floating task's egress IP breaks deliverability); the mail store is NFS-hostile and IS the app — same rationale as web-app-mailu placement: manager image: stalwartlabs/stalwart - version: "v0.16.27" - webui_version: "v1.0.11" + version: "v1.0.1" + webui_version: "v2.0.2" update: - key: webui_version type: git_tags repository: https://github.com/stalwartlabs/webui.git - match: "v" + match: "v2." name: stalwart backup: project_hard_restart: true @@ -141,6 +141,13 @@ clamav: mem_reservation: 1g mem_limit: 3g pids_limit: 512 +# nocheck: dynamic-flag image of the 0.16 store migration that migrate.sh runs; never deployed as a service +# nocheck: playwright-service-flag no Playwright surface, the image only runs inside migrate.sh +stalwart_migrate: + enabled: false + shared: false + image: stalwartlabs/stalwart-migrate + version: "1.0.0" design: bond: 1 enabled: "{{ 'web-svc-design' in group_names }}" diff --git a/roles/web-app-stalwart/tasks/00_core.yml b/roles/web-app-stalwart/tasks/00_core.yml index e500abf9d3..ac18ed3056 100644 --- a/roles/web-app-stalwart/tasks/00_core.yml +++ b/roles/web-app-stalwart/tasks/00_core.yml @@ -11,6 +11,10 @@ `.test` domain for local/CI stacks. quiet: true +- name: "🛡️ Refuse to replace a Stalwart that serves a store from before 1.0" + include_tasks: store_guard.yml + when: IS_STACK_HOST | bool + - name: "🔴 Disable SMTP to avoid port conflicts" include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-mail-smtp/tasks/disable.yml') }}" diff --git a/roles/web-app-stalwart/tasks/02_webadmin.yml b/roles/web-app-stalwart/tasks/02_webadmin.yml index 8b0790bf92..9d0dadefff 100644 --- a/roles/web-app-stalwart/tasks/02_webadmin.yml +++ b/roles/web-app-stalwart/tasks/02_webadmin.yml @@ -29,13 +29,46 @@ ansible.builtin.set_fact: stalwart_webui_app_id: "{{ stalwart_webui_apps[0].id }}" -- name: "🔗 Point the WebUI Application at the locally-staged bundle" +- name: "📖 List Stalwart OAuth clients" + include_tasks: jmap_call.yml + vars: + stalwart_jmap_body: "{{ lookup('template', 'jmap/oauth_client/get.json.j2') }}" + +- name: "🔍 Resolve the WebUI OAuth client" + ansible.builtin.set_fact: + stalwart_webui_oauth_client: "{{ lookup('template', 'jmap/oauth_client/webui.json.j2') | from_json }}" + stalwart_webui_oauth_clients: >- + {{ stalwart_jmap.methodResponses[0][1].list + | selectattr('clientId', 'equalto', STALWART_WEBUI_OAUTH_CLIENT_ID) + | list }} + vars: + stalwart_webui_url_prefixes: "{{ stalwart_webui_apps[0].urlPrefix | list }}" + +- name: "📁 Register the WebUI OAuth client" + include_tasks: jmap_call.yml + vars: + stalwart_jmap_body: "{{ lookup('template', 'jmap/oauth_client/create.json.j2') }}" + when: stalwart_webui_oauth_clients | length == 0 + +- name: "🔄 Align the WebUI OAuth client with the origin the WebUI is served from" + include_tasks: jmap_call.yml + vars: + stalwart_jmap_body: "{{ lookup('template', 'jmap/oauth_client/update.json.j2') }}" + when: + - stalwart_webui_oauth_clients | length > 0 + - >- + (stalwart_webui_oauth_clients[0] | dict2items + | selectattr('key', 'in', stalwart_webui_oauth_client) | items2dict) + != stalwart_webui_oauth_client + +- name: "🔗 Point the WebUI Application at the locally-staged bundle and its OAuth client" include_tasks: jmap_call.yml vars: stalwart_jmap_body: >- {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], 'methodCalls': [['x:Application/set', - {'update': {stalwart_webui_app_id: {'resourceUrl': STALWART_WEBUI_LOCAL_URL}}}, + {'update': {stalwart_webui_app_id: {'resourceUrl': STALWART_WEBUI_LOCAL_URL, + 'oauthClientId': STALWART_WEBUI_OAUTH_CLIENT_ID}}}, 'c0']]} | to_json }} - name: "📦 Unpack the WebUI bundle from the local file" diff --git a/roles/web-app-stalwart/tasks/04_manage_user.yml b/roles/web-app-stalwart/tasks/04_manage_user.yml index 23e13ba3e5..89a0b20766 100644 --- a/roles/web-app-stalwart/tasks/04_manage_user.yml +++ b/roles/web-app-stalwart/tasks/04_manage_user.yml @@ -44,17 +44,23 @@ {%- set result = stalwart_jmap.methodResponses[0][1] -%} {%- set listed = {} -%} {%- for held in stalwart_jmap.methodResponses[1][1].list if held.domainId == stalwart_domain_id -%} - {%- set _ = listed.update({held.name | lower: held.id}) -%} + {%- set _ = listed.update({held.name | lower: held}) -%} {%- endfor -%} {%- set accounts = [] -%} {%- for account in stalwart_accounts -%} {%- set created = (result.created | default({}, true)).get('u' ~ loop.index0) or {} -%} {%- set refusal = (result.notCreated | default({}, true)).get('u' ~ loop.index0) or {} -%} - {%- set existing = refusal.get('type') == 'alreadyExists' -%} + {%- set held = listed.get(account.name | lower) or {} -%} + {%- set conflict = refusal.get('objectId') or {} -%} + {%- set credentials = held.get('credentials') or {} -%} + {%- set passwords = credentials | dict2items | selectattr('value.@type', 'equalto', 'Password') + | map(attribute='key') | list -%} {%- set _ = accounts.append(account | combine({ - 'id': ((refusal.get('objectId') or {}).get('id') if existing else created.get('id')) - or listed.get(account.name | lower, ''), - 'existing': existing, + 'id': created.get('id') or held.get('id', ''), + 'existing': refusal.get('type') == 'primaryKeyViolation' and conflict.get('object') == 'Account' + and held.get('id') is not none and conflict.get('id') == held.get('id'), + 'password_key': passwords | first if passwords + else (credentials | map('int') | max + 1 if credentials else 0), 'refusal': refusal})) -%} {%- endfor -%} {{ accounts }} @@ -68,8 +74,10 @@ vars: stalwart_account_refused: >- {%- set refused = {} -%} - {%- for account in stalwart_accounts if not account.id -%} - {%- if account.bot or not (STALWART_SSO_ENABLED | bool and account.refusal.get('type') == 'forbidden') -%} + {%- for account in stalwart_accounts -%} + {%- set external = STALWART_SSO_ENABLED | bool and account.refusal.get('type') == 'forbidden' -%} + {%- if (not account.id and (account.bot or not external)) + or (account.refusal and not (account.existing or external)) -%} {%- set _ = refused.update({account.address: account.refusal}) -%} {%- endif -%} {%- endfor -%} @@ -86,7 +94,7 @@ {%- set changes = {} -%} {%- for account in stalwart_accounts if account.existing -%} {%- set _ = changes.update({account.id: { - 'credentials': {'0': {'@type': 'Password', 'secret': account.secret}}}}) -%} + 'credentials/' ~ account.password_key ~ '/secret': account.secret}}) -%} {%- endfor -%} {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], 'methodCalls': [['x:Account/set', {'update': changes}, 'c0']]} | to_json }} @@ -108,16 +116,17 @@ - name: "💾 Persist the Stalwart submission credential of every bot" ansible.builtin.include_role: name: sys-token-store - tasks_from: write.yml + tasks_from: write_many.yml vars: - sys_token_store_user_key: "{{ stalwart_bot.key }}" - sys_token_store_app: "{{ application_id }}" - sys_token_store_token: "{{ stalwart_bot.secret }}" - loop: "{{ stalwart_accounts | selectattr('bot') | list }}" - loop_control: - loop_var: stalwart_bot - label: "{{ stalwart_bot.address }}" - when: not (STALWART_SSO_ENABLED | bool) + sys_token_store_entries: >- + {%- set entries = [] -%} + {%- for bot in stalwart_accounts if bot.bot -%} + {%- set _ = entries.append({'user_key': bot.key, 'app': application_id, 'token': bot.secret}) -%} + {%- endfor -%} + {{ entries }} + when: + - not (STALWART_SSO_ENABLED | bool) + - stalwart_accounts | selectattr('bot') | list | length > 0 no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - name: "🔑 Keep an app password for every bot under SSO" diff --git a/roles/web-app-stalwart/tasks/04_manage_user/app_password.yml b/roles/web-app-stalwart/tasks/04_manage_user/app_password.yml index 1b4faff5aa..896dc8d747 100644 --- a/roles/web-app-stalwart/tasks/04_manage_user/app_password.yml +++ b/roles/web-app-stalwart/tasks/04_manage_user/app_password.yml @@ -62,15 +62,14 @@ - name: "💾 Persist the new app passwords" ansible.builtin.include_role: name: sys-token-store - tasks_from: write.yml + tasks_from: write_many.yml vars: - sys_token_store_user_key: "{{ stalwart_app_password_new.key }}" - sys_token_store_app: "{{ application_id }}" - sys_token_store_token: "{{ stalwart_app_password_new.secret }}" - loop: "{{ stalwart_app_password_minted }}" - loop_control: - loop_var: stalwart_app_password_new - label: "{{ stalwart_app_password_new.address }}" + sys_token_store_entries: >- + {%- set entries = [] -%} + {%- for minted in stalwart_app_password_minted -%} + {%- set _ = entries.append({'user_key': minted.key, 'app': application_id, 'token': minted.secret}) -%} + {%- endfor -%} + {{ entries }} no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - name: "🏷️ Retire the app passwords the new ones replace" diff --git a/roles/web-app-stalwart/tasks/06_oidc.yml b/roles/web-app-stalwart/tasks/06_oidc.yml index d88733927d..6423a94059 100644 --- a/roles/web-app-stalwart/tasks/06_oidc.yml +++ b/roles/web-app-stalwart/tasks/06_oidc.yml @@ -32,10 +32,10 @@ - name: "🔧 Reconcile the OIDC directory the realm is reached through" when: stalwart_oidc_dir_id | length > 0 block: - - name: "🧹 Clear the OIDC directory's required audience" + - name: "🔧 Accept Keycloak tokens without a Stalwart audience or mail scope" include_tasks: jmap_call.yml vars: - stalwart_jmap_body: "{{ lookup('template', 'jmap/directory/clear_audience.json.j2') }}" + stalwart_jmap_body: "{{ lookup('template', 'jmap/directory/token_validation.json.j2') }}" - name: "👥 Let the OIDC directory read the RBAC groups the token carries" include_tasks: jmap_call.yml diff --git a/roles/web-app-stalwart/tasks/07_antivirus.yml b/roles/web-app-stalwart/tasks/07_antivirus.yml index 8391e25fbd..91e947ede3 100644 --- a/roles/web-app-stalwart/tasks/07_antivirus.yml +++ b/roles/web-app-stalwart/tasks/07_antivirus.yml @@ -1,5 +1,5 @@ --- -# Register the ClamAV container as a DATA-stage milter (idempotent by hostname). +# Register the ClamAV container as a DATA-stage milter (idempotent by host). # Short timeouts + fail-open keep mail flowing while clamd warms up. # JMAP request bodies live in templates/jmap/*.json.j2. - name: "📖 List existing Stalwart milters" @@ -11,7 +11,7 @@ ansible.builtin.set_fact: stalwart_av_milter_id: >- {{ (stalwart_jmap.methodResponses[0][1].list - | selectattr('hostname', 'equalto', STALWART_CLAMAV_HOST) + | selectattr('host', 'equalto', STALWART_CLAMAV_HOST) | map(attribute='id') | first) | default('') }} - name: "📁 Create the ClamAV milter" diff --git a/roles/web-app-stalwart/tasks/16_forwards.yml b/roles/web-app-stalwart/tasks/16_forwards.yml index 07076750e5..1d5d584401 100644 --- a/roles/web-app-stalwart/tasks/16_forwards.yml +++ b/roles/web-app-stalwart/tasks/16_forwards.yml @@ -1,13 +1,15 @@ --- # include-gated: when: STALWART_FORWARDS | length > 0 -- name: "📖 Read the Sieve limits of user scripts" +- name: "📖 Read the Sieve limits of user scripts and the accounts the forwards belong to" include_tasks: jmap_call.yml vars: stalwart_jmap_body: >- {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:SieveUserInterpreter/get', {'ids': ['singleton']}, 'c0']]} | to_json }} + 'methodCalls': [['x:SieveUserInterpreter/get', {'ids': ['singleton']}, 'c0'], + ['x:Domain/get', {'ids': none}, 'c1'], + ['x:Account/get', {'ids': none}, 'c2']]} | to_json }} -- name: "🔍 Compare the Sieve limits with the widest forward" +- name: "🔍 Check Sieve limits against the widest forward, resolve forwarders" ansible.builtin.set_fact: stalwart_sieve_limits: maxRedirects: "{{ [stalwart_jmap.methodResponses[0][1].list[0].maxRedirects | int, stalwart_forward_width | int] | max }}" @@ -15,9 +17,25 @@ stalwart_sieve_limits_live: maxRedirects: "{{ stalwart_jmap.methodResponses[0][1].list[0].maxRedirects | int }}" maxOutMessages: "{{ stalwart_jmap.methodResponses[0][1].list[0].maxOutMessages | int }}" + stalwart_forward_account_ids: >- + {%- set domains = dict(stalwart_jmap.methodResponses[1][1].list | map(attribute='id') + | zip(stalwart_jmap.methodResponses[1][1].list | map(attribute='name'))) -%} + {%- set ids = {} -%} + {%- for account in stalwart_jmap.methodResponses[2][1].list if account.domainId in domains -%} + {%- set _ = ids.update({(account.name ~ '@' ~ domains[account.domainId]) | lower: account.id}) -%} + {%- endfor -%} + {{ ids }} vars: stalwart_forward_width: "{{ STALWART_FORWARDS | map(attribute='destinations') | map('length') | max }}" +- name: "✅ Ensure every forwarding address is a Stalwart account" + ansible.builtin.assert: + that: stalwart_forward_missing | length == 0 + fail_msg: "Forwards are declared for addresses without a Stalwart account: {{ stalwart_forward_missing }}" + quiet: true + vars: + stalwart_forward_missing: "{{ STALWART_FORWARDS | map(attribute='address') | reject('in', stalwart_forward_account_ids) | list }}" + - name: "🔧 Raise the Sieve redirect limits to the widest forward" when: stalwart_sieve_limits != stalwart_sieve_limits_live block: @@ -38,38 +56,9 @@ {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], 'methodCalls': [['x:Action/set', {'create': {'a': {'@type': 'ReloadSettings'}}}, 'c0']]} | to_json }} -- name: "📖 List the Stalwart accounts the forwards belong to" - include_tasks: jmap_call.yml - vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'], - 'methodCalls': [['x:Domain/get', {'ids': none}, 'c0'], ['x:Account/get', {'ids': none}, 'c1']]} | to_json }} - -- name: "🔍 Resolve the account id of every forwarding address" - ansible.builtin.set_fact: - stalwart_forward_account_ids: >- - {%- set domains = dict(stalwart_jmap.methodResponses[0][1].list | map(attribute='id') - | zip(stalwart_jmap.methodResponses[0][1].list | map(attribute='name'))) -%} - {%- set ids = {} -%} - {%- for account in stalwart_jmap.methodResponses[1][1].list if account.domainId in domains -%} - {%- set _ = ids.update({(account.name ~ '@' ~ domains[account.domainId]) | lower: account.id}) -%} - {%- endfor -%} - {{ ids }} - -- name: "✅ Ensure every forwarding address is a Stalwart account" - ansible.builtin.assert: - that: stalwart_forward_missing | length == 0 - fail_msg: "Forwards are declared for addresses without a Stalwart account: {{ stalwart_forward_missing }}" - quiet: true - vars: - stalwart_forward_missing: "{{ STALWART_FORWARDS | map(attribute='address') | reject('in', stalwart_forward_account_ids) | list }}" - -- name: "📨 Keep each forward script in place" +- name: "📨 Keep the forward script of every forwarding account in place" include_tasks: 16_forwards/apply.yml - vars: - stalwart_jmap_act_as: "{{ stalwart_forward.address }}" - stalwart_forward_account_id: "{{ stalwart_forward_account_ids[stalwart_forward.address] }}" - loop: "{{ STALWART_FORWARDS }}" + loop: "{{ STALWART_FORWARDS | batch(STALWART_JMAP_MAX_METHOD_CALLS) | list }}" loop_control: - loop_var: stalwart_forward - label: "{{ stalwart_forward.address }}" + loop_var: stalwart_forward_chunk + label: "{{ stalwart_forward_chunk | map(attribute='address') | join(', ') }}" diff --git a/roles/web-app-stalwart/tasks/16_forwards/apply.yml b/roles/web-app-stalwart/tasks/16_forwards/apply.yml index 48e53024af..54782dfcad 100644 --- a/roles/web-app-stalwart/tasks/16_forwards/apply.yml +++ b/roles/web-app-stalwart/tasks/16_forwards/apply.yml @@ -1,75 +1,111 @@ --- -# Param: stalwart_forward - one STALWART_FORWARDS entry, {address, destinations}. -# Param: stalwart_forward_account_id - JMAP account id of stalwart_forward.address. -# Param: stalwart_jmap_act_as - stalwart_forward.address, every call below runs as that account. -- name: "📖 List the Sieve scripts of '{{ stalwart_forward.address }}'" +# Param: stalwart_forward_chunk - up to STALWART_JMAP_MAX_METHOD_CALLS STALWART_FORWARDS entries; each method call addresses one account through its accountId and is named by its address. +# Param: stalwart_forward_account_ids - JMAP account id per forwarding address. +- name: "📖 List the Sieve scripts of the forwarding accounts" include_tasks: "{{ role_path }}/tasks/jmap_call.yml" vars: stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:sieve'], - 'methodCalls': [['SieveScript/get', {'accountId': stalwart_forward_account_id, 'ids': none}, 'c0']]} | to_json }} + {%- set calls = [] -%} + {%- for forward in stalwart_forward_chunk -%} + {%- set _ = calls.append(['SieveScript/get', + {'accountId': stalwart_forward_account_ids[forward.address], 'ids': none}, forward.address]) -%} + {%- endfor -%} + {{ {'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:sieve'], 'methodCalls': calls} | to_json }} -- name: "🔍 Find the forward script of '{{ stalwart_forward.address }}'" +- name: "🔍 Find the forward script of every forwarding account" ansible.builtin.set_fact: - stalwart_forward_scripts: "{{ stalwart_jmap.methodResponses[0][1].list }}" - stalwart_forward_own: >- - {{ stalwart_jmap.methodResponses[0][1].list - | selectattr('name', 'equalto', STALWART_FORWARD_SCRIPT_NAME) | list }} + stalwart_forward_states: >- + {%- set listed = {} -%} + {%- for method, result, call in stalwart_jmap.methodResponses -%} + {%- set _ = listed.update({call: result.list}) -%} + {%- endfor -%} + {%- set states = [] -%} + {%- for forward in stalwart_forward_chunk -%} + {%- set own = listed[forward.address] | selectattr('name', 'equalto', STALWART_FORWARD_SCRIPT_NAME) | list -%} + {%- set _ = states.append(forward | combine({ + 'account': stalwart_forward_account_ids[forward.address], + 'scripts': listed[forward.address], + 'own': (own | first) if own else none})) -%} + {%- endfor -%} + {{ states }} -- name: "📖 Read the forward script of '{{ stalwart_forward.address }}'" +- name: "📖 Read the forward scripts the accounts already hold" include_tasks: "{{ role_path }}/tasks/jmap_call.yml" vars: stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:blob'], - 'methodCalls': [['Blob/get', {'accountId': stalwart_forward_account_id, - 'ids': [stalwart_forward_own[0].blobId], 'properties': ['data:asText']}, 'c0']]} | to_json }} - when: stalwart_forward_own | length > 0 + {%- set calls = [] -%} + {%- for forward in stalwart_forward_states if forward.own -%} + {%- set _ = calls.append(['Blob/get', {'accountId': forward.account, 'ids': [forward.own.blobId], + 'properties': ['data:asText']}, forward.address]) -%} + {%- endfor -%} + {{ {'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:blob'], 'methodCalls': calls} | to_json }} + when: stalwart_forward_states | selectattr('own') | list | length > 0 -- name: "🔍 Render the forward script of '{{ stalwart_forward.address }}'" +- name: "🔍 Render the forward script of every forwarding account" ansible.builtin.set_fact: - stalwart_forward_current: "{{ stalwart_forward_text }}" - stalwart_forward_desired: >- - {{ stalwart_forward.destinations | stalwart_forward_script( - stalwart_forward_scripts | stalwart_forward_include(STALWART_FORWARD_SCRIPT_NAME, stalwart_forward_text)) }} - stalwart_forward_inactive: "{{ (stalwart_forward_own | length > 0) and not (stalwart_forward_own[0].isActive | bool) }}" + stalwart_forward_plan: >- + {%- set texts = {} -%} + {%- for method, result, call in stalwart_jmap.methodResponses if method == 'Blob/get' and result.list -%} + {%- set _ = texts.update({call: result.list[0]['data:asText']}) -%} + {%- endfor -%} + {%- set plan = [] -%} + {%- for forward in stalwart_forward_states -%} + {%- set current = texts[forward.address] if forward.address in texts else '' -%} + {%- set desired = forward.destinations | stalwart_forward_script( + forward.scripts | stalwart_forward_include(STALWART_FORWARD_SCRIPT_NAME, current)) -%} + {%- set _ = plan.append({ + 'address': forward.address, + 'account': forward.account, + 'n': loop.index0, + 'own': forward.own.id if forward.own else '', + 'unread': forward.own is not none and forward.address not in texts, + 'write': desired != current, + 'activate': desired == current and forward.own is not none and not (forward.own.isActive | bool), + 'script': desired}) -%} + {%- endfor -%} + {{ plan }} + +- name: "✅ Ensure Stalwart returned the forward script of every account that holds one" + ansible.builtin.assert: + that: stalwart_forward_unread | length == 0 + fail_msg: "Stalwart returned no forward script for {{ stalwart_forward_unread }}" + quiet: true vars: - stalwart_forward_text: >- - {{ stalwart_jmap.methodResponses[0][1].list[0]['data:asText'] - if stalwart_forward_own | length > 0 else '' }} + stalwart_forward_unread: "{{ stalwart_forward_plan | selectattr('unread') | map(attribute='address') | list }}" -- name: "📁 Write and activate the forward script of '{{ stalwart_forward.address }}'" - when: stalwart_forward_desired != stalwart_forward_current - block: - - name: "📤 Upload the forward script of '{{ stalwart_forward.address }}'" - include_tasks: "{{ role_path }}/tasks/jmap_call.yml" - vars: - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:blob'], - 'methodCalls': [['Blob/upload', {'accountId': stalwart_forward_account_id, - 'create': {'b': {'data': [{'data:asText': stalwart_forward_desired}]}}}, 'c0']]} | to_json }} - - - name: "📁 Point the forward script of '{{ stalwart_forward.address }}' at the upload" - include_tasks: "{{ role_path }}/tasks/jmap_call.yml" - vars: - stalwart_forward_blob: "{{ stalwart_jmap.methodResponses[0][1].created.b.id }}" - stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:sieve'], - 'methodCalls': [['SieveScript/set', ( - {'accountId': stalwart_forward_account_id, - 'update': {stalwart_forward_own[0].id: {'blobId': stalwart_forward_blob}}, - 'onSuccessActivateScript': stalwart_forward_own[0].id} - if stalwart_forward_own | length > 0 else - {'accountId': stalwart_forward_account_id, - 'create': {'f': {'name': STALWART_FORWARD_SCRIPT_NAME, 'blobId': stalwart_forward_blob}}, - 'onSuccessActivateScript': '#f'}), 'c0']]} | to_json }} - -- name: "🔀 Re-activate the forward script of '{{ stalwart_forward.address }}'" +- name: "📤 Upload the changed forward scripts" include_tasks: "{{ role_path }}/tasks/jmap_call.yml" vars: stalwart_jmap_body: >- - {{ {'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:sieve'], - 'methodCalls': [['SieveScript/set', {'accountId': stalwart_forward_account_id, - 'onSuccessActivateScript': stalwart_forward_own[0].id}, 'c0']]} | to_json }} - when: - - stalwart_forward_desired == stalwart_forward_current - - stalwart_forward_inactive | bool + {%- set calls = [] -%} + {%- for step in stalwart_forward_plan if step.write -%} + {%- set _ = calls.append(['Blob/upload', {'accountId': step.account, + 'create': {'b' ~ step.n: {'data': [{'data:asText': step.script}]}}}, step.address]) -%} + {%- endfor -%} + {{ {'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:blob'], 'methodCalls': calls} | to_json }} + when: stalwart_forward_plan | selectattr('write') | list | length > 0 + +- name: "📁 Point the forward scripts at their uploads and activate them" + include_tasks: "{{ role_path }}/tasks/jmap_call.yml" + vars: + stalwart_jmap_body: >- + {%- set uploaded = {} -%} + {%- for method, result, call in stalwart_jmap.methodResponses if method == 'Blob/upload' -%} + {%- set _ = uploaded.update({call: result.created}) -%} + {%- endfor -%} + {%- set calls = [] -%} + {%- for step in stalwart_forward_plan if step.write or step.activate -%} + {%- if not step.write -%} + {%- set arguments = {'onSuccessActivateScript': step.own} -%} + {%- elif step.own -%} + {%- set arguments = {'update': {step.own: {'blobId': uploaded[step.address]['b' ~ step.n].id}}, + 'onSuccessActivateScript': step.own} -%} + {%- else -%} + {%- set arguments = {'create': {'f' ~ step.n: {'name': STALWART_FORWARD_SCRIPT_NAME, + 'blobId': uploaded[step.address]['b' ~ step.n].id}}, + 'onSuccessActivateScript': '#f' ~ step.n} -%} + {%- endif -%} + {%- set _ = calls.append(['SieveScript/set', {'accountId': step.account} | combine(arguments), step.address]) -%} + {%- endfor -%} + {{ {'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:sieve'], 'methodCalls': calls} | to_json }} + when: stalwart_forward_plan | selectattr('write') | list | length > 0 or stalwart_forward_plan | selectattr('activate') | list | length > 0 diff --git a/roles/web-app-stalwart/tasks/jmap_call.yml b/roles/web-app-stalwart/tasks/jmap_call.yml index 4dd3c3426e..d76e74a1c2 100644 --- a/roles/web-app-stalwart/tasks/jmap_call.yml +++ b/roles/web-app-stalwart/tasks/jmap_call.yml @@ -1,8 +1,7 @@ --- # Reusable management JMAP call: in `stalwart_jmap_body` (JSON), out `stalwart_jmap`. # Param: stalwart_jmap_body - JSON request; a batch carries one method call per object owner, its call id naming that owner in a refusal. -# Param: stalwart_jmap_tolerate_rejected - true when the caller reads a set-level rejection itself (e.g. alreadyExists). -# Param: stalwart_jmap_act_as - account address the recovery admin acts for; unset runs the call as the admin itself. +# Param: stalwart_jmap_tolerate_rejected - true when the caller reads a set-level rejection itself (e.g. primaryKeyViolation). - name: "🔧 Stalwart JMAP call" ansible.builtin.shell: cmd: >- @@ -11,7 +10,7 @@ -H "Content-Type:application/json" {{ STALWART_JMAP_URL }} stdin: |- - user = {{ ((stalwart_jmap_act_as ~ '%' if stalwart_jmap_act_as is defined else '') ~ STALWART_ADMIN_USER ~ ':' ~ STALWART_ADMIN_PASSWORD) | to_json(ensure_ascii=False) }} + user = {{ (STALWART_ADMIN_USER ~ ':' ~ STALWART_ADMIN_PASSWORD) | to_json(ensure_ascii=False) }} data-binary = {{ stalwart_jmap_body | to_json(ensure_ascii=False) }} register: stalwart_jmap_raw changed_when: false diff --git a/roles/web-app-stalwart/tasks/manager_ops.yml b/roles/web-app-stalwart/tasks/manager_ops.yml index 48bd7cc209..ce1486c0ec 100644 --- a/roles/web-app-stalwart/tasks/manager_ops.yml +++ b/roles/web-app-stalwart/tasks/manager_ops.yml @@ -52,3 +52,9 @@ - name: "📨 Provision the declared per-account forwards" include_tasks: 16_forwards.yml when: STALWART_FORWARDS | length > 0 + +- name: "📝 Record that Stalwart 1.x serves the store of this host" + stack_host_copy: + content: "{{ STALWART_STORE_LAYOUT_VERSION }}\n" + dest: "{{ STALWART_STORE_MARKER_FILE }}" + mode: "0644" diff --git a/roles/web-app-stalwart/tasks/store_guard.yml b/roles/web-app-stalwart/tasks/store_guard.yml new file mode 100644 index 0000000000..e27b5b4e48 --- /dev/null +++ b/roles/web-app-stalwart/tasks/store_guard.yml @@ -0,0 +1,128 @@ +--- +# Stalwart 1.x keeps a bytea column v in table u; every 0.x store keeps its bigint quota counters under the same name. +# mask_values scrubs the role's names out of psql errors, so existence comes from the shared catalog or the dedicated volume, and a stopped dedicated database fails its own assert instead of a masked psql error. +# The host marker outranks the store: a marked host that goes back to a 0.16 store (rollback, old backup) passes unless the marker is removed first. + +- name: "🔍 Find the 1.x store marker of this host" + ansible.builtin.stat: + path: "{{ STALWART_STORE_MARKER_FILE }}" + register: stalwart_store_marker_file + +- name: "📖 Read the 1.x store marker of this host" + ansible.builtin.slurp: + src: "{{ STALWART_STORE_MARKER_FILE }}" + register: stalwart_store_marker + when: stalwart_store_marker_file.stat.exists + +- name: "🔧 Record whether this host last deployed Stalwart 1.x on its store" + ansible.builtin.set_fact: + stalwart_store_marked: >- + {{ stalwart_store_marker is not skipped + and (stalwart_store_marker.content | b64decode | trim) == (STALWART_STORE_LAYOUT_VERSION | string) }} + +- name: "🔍 Find the store database on the shared PostgreSQL" + database_query: + config: >- + {{ lookup('database', application_id) | combine({ + 'username': 'postgres', + 'name': 'postgres', + 'password': lookup('config', 'svc-db-postgres', 'secrets.credentials.POSTGRES_PASSWORD'), + }) }} + query_file: "{{ role_path }}/files/sql/store/database.sql" + named_args: + name: "{{ lookup('database', application_id, 'name') }}" + expect_rows: true + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: stalwart_store_database + until: stalwart_store_database is succeeded + retries: 6 + delay: 5 + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + when: + - not (stalwart_store_marked | bool) + - STALWART_DATABASE_SHARED | bool + +- name: "🔍 Find the volume of the dedicated store database" + ansible.builtin.command: >- + container volume ls -q --filter name=^{{ lookup('database', application_id, 'volume') }}$ + register: stalwart_store_volume + changed_when: false + when: + - not (stalwart_store_marked | bool) + - not (STALWART_DATABASE_SHARED | bool) + +- name: "🔧 Record whether a store exists that this host never deployed Stalwart 1.x on" + ansible.builtin.set_fact: + stalwart_store_exists: >- + {{ not (stalwart_store_marked | bool) and ( + (stalwart_store_database.rows[0][0] | int > 0) + if STALWART_DATABASE_SHARED | bool + else (stalwart_store_volume.stdout | trim | length > 0)) }} + +- name: "🔍 Find the running container of the dedicated store database" + ansible.builtin.command: + argv: + - container + - ps + - --quiet + - --filter + - status=running + - --filter + - >- + {{ ('label=com.docker.swarm.service.name=' ~ lookup('database', application_id, 'service_name')) + if DEPLOYMENT_MODE == 'swarm' + else ('name=^' ~ lookup('database', application_id, 'container') ~ '$') }} + register: stalwart_store_engine + changed_when: false + when: + - stalwart_store_exists | bool + - not (STALWART_DATABASE_SHARED | bool) + +- name: "✅ Ensure the dedicated store database runs, so the deploy can read its layout" + ansible.builtin.assert: + that: + - stalwart_store_engine.stdout | trim | length > 0 + fail_msg: >- + The dedicated store database of Stalwart, service '{{ lookup('database', application_id, 'host') }}' + of stack '{{ application_id | get_entity_name }}', is not running on {{ inventory_hostname }}, + so the deploy cannot read the layout of the store in volume '{{ lookup('database', application_id, 'volume') }}'. + This host has no record of a Stalwart 1.x deploy ({{ STALWART_STORE_MARKER_FILE }}), so that store may predate 1.0, + and the deploy stops before Stalwart {{ lookup('config', application_id, 'services.stalwart.version') }} opens it. + Start that database from the stack this host last deployed, or finish the stalwart-migrate steps of + "Upgrading from 0.16" in roles/web-app-stalwart/README.md, then deploy again. + quiet: true + when: stalwart_store_engine is not skipped + +- name: "🔍 Read the layout of the store Stalwart opens" + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/store/layout.sql" + expect_rows: true + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: stalwart_store_layout + until: stalwart_store_layout is succeeded + retries: 6 + delay: 5 + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + when: stalwart_store_exists | bool + +- name: "🚚 Migrate the 0.16 store to 1.x with stalwart-migrate" + ansible.builtin.include_tasks: store_guard/migrate.yml + when: + - stalwart_store_layout is not skipped + - stalwart_store_layout.rows[0][0] not in ['bytea', 'absent'] + +- name: "✅ Ensure Stalwart opens no store from before 1.0" + ansible.builtin.assert: + that: + - stalwart_store_layout.rows[0][0] in ['bytea', 'absent'] + fail_msg: >- + The store in database '{{ lookup('database', application_id, 'name') }}' still predates Stalwart 1.0 + after the migration (type of column u.v: {{ stalwart_store_layout.rows[0][0] }}, a 1.x store holds bytea), + so the deploy stops before Stalwart {{ lookup('config', application_id, 'services.stalwart.version') }} opens it. + Inspect {{ STALWART_MIGRATE_DIR }} on this host, rerun {{ STALWART_MIGRATE_SCRIPT }} phase by phase + ("Upgrading from 0.16" in roles/web-app-stalwart/README.md), then deploy again. + quiet: true + when: stalwart_store_layout is not skipped diff --git a/roles/web-app-stalwart/tasks/store_guard/migrate.yml b/roles/web-app-stalwart/tasks/store_guard/migrate.yml new file mode 100644 index 0000000000..bd61c6749f --- /dev/null +++ b/roles/web-app-stalwart/tasks/store_guard/migrate.yml @@ -0,0 +1,25 @@ +--- +- name: "📝 Stage the stalwart-migrate script for the 0.16 store" + ansible.builtin.include_tasks: store_guard/stage_migration.yml + +- name: "🚚 Migrate the 0.16 store to 1.x (upgrade to final)" + ansible.builtin.command: + argv: + - bash + - "{{ STALWART_MIGRATE_SCRIPT }}" + - all + register: stalwart_store_migration + changed_when: true + +- name: "🔍 Read the layout of the store after the migration" + database_query: + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/store/layout.sql" + expect_rows: true + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + register: stalwart_store_layout + until: stalwart_store_layout is succeeded + retries: 6 + delay: 5 + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/web-app-stalwart/tasks/store_guard/stage_migration.yml b/roles/web-app-stalwart/tasks/store_guard/stage_migration.yml new file mode 100644 index 0000000000..99a50234b1 --- /dev/null +++ b/roles/web-app-stalwart/tasks/store_guard/stage_migration.yml @@ -0,0 +1,28 @@ +--- +- name: "📁 Ensure the migration directories exist" + ansible.builtin.file: + path: "{{ item }}" + state: directory + mode: "0700" + loop: + - "{{ STALWART_MIGRATE_DIR }}" + - "{{ STALWART_MIGRATE_TARGET_CONFIG | dirname }}" + +- name: "📄 Render the 1.x target configuration for stalwart-migrate" + stack_host_copy: + content: "{{ lookup('template', 'config.json.j2') | from_json | combine({'database': STALWART_MIGRATE_TARGET_DATABASE}) | to_nice_json }}\n" + dest: "{{ STALWART_MIGRATE_TARGET_CONFIG }}" + mode: "0600" + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "📄 Render the values of the migration script" + stack_host_template: + src: migrate.env.j2 + dest: "{{ [STALWART_MIGRATE_DIR, 'migrate.env'] | path_join }}" + mode: "0600" + +- name: "📄 Install the migration script" + stack_host_copy: + src: shell/migrate_v016.sh + dest: "{{ STALWART_MIGRATE_SCRIPT }}" + mode: "0700" diff --git a/roles/web-app-stalwart/templates/jmap/directory/create_oidc.json.j2 b/roles/web-app-stalwart/templates/jmap/directory/create_oidc.json.j2 index 785ad55cee..370271efda 100644 --- a/roles/web-app-stalwart/templates/jmap/directory/create_oidc.json.j2 +++ b/roles/web-app-stalwart/templates/jmap/directory/create_oidc.json.j2 @@ -6,6 +6,8 @@ "issuerUrl": {{ OIDC.CLIENT.ISSUER_URL | to_json }}, "claimUsername": {{ OIDC.ATTRIBUTES.USERNAME | to_json }}, "usernameDomain": {{ STALWART_DOMAIN | to_json }}, - "claimName": "name" + "claimName": "name", + "skipAudienceValidation": {{ STALWART_OIDC_TOKEN_VALIDATION.skipAudienceValidation | to_json }}, + "unscopedTokens": {{ STALWART_OIDC_TOKEN_VALIDATION.unscopedTokens | to_json }} }}}, "c0"]] } diff --git a/roles/web-app-stalwart/templates/jmap/directory/clear_audience.json.j2 b/roles/web-app-stalwart/templates/jmap/directory/token_validation.json.j2 similarity index 61% rename from roles/web-app-stalwart/templates/jmap/directory/clear_audience.json.j2 rename to roles/web-app-stalwart/templates/jmap/directory/token_validation.json.j2 index f7f1eb04a1..ae09aa5f28 100644 --- a/roles/web-app-stalwart/templates/jmap/directory/clear_audience.json.j2 +++ b/roles/web-app-stalwart/templates/jmap/directory/token_validation.json.j2 @@ -1,4 +1,4 @@ { "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], - "methodCalls": [["x:Directory/set", {"update": { {{ stalwart_oidc_dir_id | to_json }}: {"requireAudience": null} }}, "c0"]] + "methodCalls": [["x:Directory/set", {"update": { {{ stalwart_oidc_dir_id | to_json }}: {{ STALWART_OIDC_TOKEN_VALIDATION | to_json }} }}, "c0"]] } diff --git a/roles/web-app-stalwart/templates/jmap/milter/create.json.j2 b/roles/web-app-stalwart/templates/jmap/milter/create.json.j2 index 0dfe7281b8..627e7d8d8b 100644 --- a/roles/web-app-stalwart/templates/jmap/milter/create.json.j2 +++ b/roles/web-app-stalwart/templates/jmap/milter/create.json.j2 @@ -1,12 +1,12 @@ { "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], "methodCalls": [["x:MtaMilter/set", {"create": {"av": { - "hostname": {{ STALWART_CLAMAV_HOST | to_json }}, + "host": {{ STALWART_CLAMAV_HOST | to_json }}, "port": {{ STALWART_CLAMAV_MILTER_PORT | int }}, "stages": {"data": true}, "tempFailOnError": false, - "timeoutConnect": {{ STALWART_CLAMAV_MILTER_TIMEOUT_CONNECT_MS | int }}, - "timeoutCommand": {{ STALWART_CLAMAV_MILTER_TIMEOUT_COMMAND_MS | int }}, - "timeoutData": {{ STALWART_CLAMAV_MILTER_TIMEOUT_DATA_MS | int }} + "connectTimeout": {{ STALWART_CLAMAV_MILTER_TIMEOUT_CONNECT_MS | int }}, + "commandTimeout": {{ STALWART_CLAMAV_MILTER_TIMEOUT_COMMAND_MS | int }}, + "dataTimeout": {{ STALWART_CLAMAV_MILTER_TIMEOUT_DATA_MS | int }} }}}, "c0"]] } diff --git a/roles/web-app-stalwart/templates/jmap/milter/update.json.j2 b/roles/web-app-stalwart/templates/jmap/milter/update.json.j2 index 13cc9fea77..19efe3d4ee 100644 --- a/roles/web-app-stalwart/templates/jmap/milter/update.json.j2 +++ b/roles/web-app-stalwart/templates/jmap/milter/update.json.j2 @@ -2,8 +2,8 @@ "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], "methodCalls": [["x:MtaMilter/set", {"update": { {{ stalwart_av_milter_id | to_json }}: { "tempFailOnError": false, - "timeoutConnect": {{ STALWART_CLAMAV_MILTER_TIMEOUT_CONNECT_MS | int }}, - "timeoutCommand": {{ STALWART_CLAMAV_MILTER_TIMEOUT_COMMAND_MS | int }}, - "timeoutData": {{ STALWART_CLAMAV_MILTER_TIMEOUT_DATA_MS | int }} + "connectTimeout": {{ STALWART_CLAMAV_MILTER_TIMEOUT_CONNECT_MS | int }}, + "commandTimeout": {{ STALWART_CLAMAV_MILTER_TIMEOUT_COMMAND_MS | int }}, + "dataTimeout": {{ STALWART_CLAMAV_MILTER_TIMEOUT_DATA_MS | int }} }}}, "c0"]] } diff --git a/roles/web-app-stalwart/templates/jmap/oauth_client/create.json.j2 b/roles/web-app-stalwart/templates/jmap/oauth_client/create.json.j2 new file mode 100644 index 0000000000..21c7a60ae3 --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/oauth_client/create.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:OAuthClient/set", {"create": {"webui": {{ stalwart_webui_oauth_client | to_json }} }}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/oauth_client/get.json.j2 b/roles/web-app-stalwart/templates/jmap/oauth_client/get.json.j2 new file mode 100644 index 0000000000..0fcaac0e8e --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/oauth_client/get.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:OAuthClient/get", {"ids": null}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/oauth_client/update.json.j2 b/roles/web-app-stalwart/templates/jmap/oauth_client/update.json.j2 new file mode 100644 index 0000000000..b6b4cfe671 --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/oauth_client/update.json.j2 @@ -0,0 +1,4 @@ +{ + "using": ["urn:ietf:params:jmap:core", "urn:stalwart:jmap"], + "methodCalls": [["x:OAuthClient/set", {"update": { {{ stalwart_webui_oauth_clients[0].id | to_json }}: {{ stalwart_webui_oauth_client | to_json }} }}, "c0"]] +} diff --git a/roles/web-app-stalwart/templates/jmap/oauth_client/webui.json.j2 b/roles/web-app-stalwart/templates/jmap/oauth_client/webui.json.j2 new file mode 100644 index 0000000000..a794170c34 --- /dev/null +++ b/roles/web-app-stalwart/templates/jmap/oauth_client/webui.json.j2 @@ -0,0 +1,17 @@ +{# firstParty is load-bearing: a third-party client's tokens are cut down to their granted scopes, which locks the WebUI out of the management API. #} +{ + "clientId": {{ STALWART_WEBUI_OAUTH_CLIENT_ID | to_json }}, + "description": {{ STALWART_WEBUI_APP_DESCRIPTION | to_json }}, + "firstParty": true, + "grantTypes": {"authorizationCode": true, "refreshToken": true}, + "redirectUris": { +{% for prefix in stalwart_webui_url_prefixes %} + {{ (STALWART_WEBUI_BASE_URL ~ '/' ~ (prefix | trim('/')) ~ '/oauth/callback') | to_json }}: true{{ '' if loop.last else ',' }} +{% endfor %} + }, + "postLogoutRedirectUris": { +{% for prefix in stalwart_webui_url_prefixes %} + {{ (STALWART_WEBUI_BASE_URL ~ '/' ~ (prefix | trim('/')) ~ '/login') | to_json }}: true{{ '' if loop.last else ',' }} +{% endfor %} + } +} diff --git a/roles/web-app-stalwart/templates/jmap/route/create.json.j2 b/roles/web-app-stalwart/templates/jmap/route/create.json.j2 index 5d3ed5029e..2658fb7e7f 100644 --- a/roles/web-app-stalwart/templates/jmap/route/create.json.j2 +++ b/roles/web-app-stalwart/templates/jmap/route/create.json.j2 @@ -3,7 +3,7 @@ "methodCalls": [["x:MtaRoute/set", {"create": { {{ STALWART_ONION_ROUTE_NAME | to_json }}: { "@type": "Relay", "name": {{ STALWART_ONION_ROUTE_NAME | to_json }}, - "address": {{ STALWART_ONION_RELAY_HOST | to_json }}, + "host": {{ STALWART_ONION_RELAY_HOST | to_json }}, "port": {{ STALWART_ONION_RELAY_PORT | int }}, "protocol": "smtp", "implicitTls": false, diff --git a/roles/web-app-stalwart/templates/keycloak/clients.json.j2 b/roles/web-app-stalwart/templates/keycloak/clients.json.j2 index ec0f0e5bb3..caf8d1b91e 100644 --- a/roles/web-app-stalwart/templates/keycloak/clients.json.j2 +++ b/roles/web-app-stalwart/templates/keycloak/clients.json.j2 @@ -15,7 +15,7 @@ limit. Reuses the shared client secret. Keep `description` under Keycloak's 255-char column. #} -{% set stalwart_kc_webui = lookup('network_urls', lookup('tls', 'web-app-stalwart', 'url.base') | regex_replace('/+$', '')) %} +{% set stalwart_kc_webui = lookup('network_urls', lookup('tls', 'web-app-stalwart', 'url.origin')) %} {% set stalwart_kc_webmail = lookup('network_urls', lookup('canonical_url', 'web-app-stalwart', 'webmail')) %} {% set stalwart_kc_webui_redirects = stalwart_kc_webui | map('regex_replace', '$', '/*') | list %} {% set stalwart_kc_webmail_redirects = stalwart_kc_webmail | map('regex_replace', '$', '/*') | list %} diff --git a/roles/web-app-stalwart/templates/migrate.env.j2 b/roles/web-app-stalwart/templates/migrate.env.j2 new file mode 100644 index 0000000000..2493ae0c46 --- /dev/null +++ b/roles/web-app-stalwart/templates/migrate.env.j2 @@ -0,0 +1,23 @@ +IMAGE={{ STALWART_MIGRATE_IMAGE | quote }} +TARGET_VERSION={{ lookup('config', application_id, 'services.stalwart.version') | quote }} +NETWORK={{ lookup('database', application_id, 'network') | quote }} +PG_ADMIN={{ ('postgres' if STALWART_DATABASE_SHARED | bool else lookup('database', application_id, 'username')) | quote }} +PG_ADDRESS={{ lookup('database', application_id, 'address') }} +DB={{ lookup('database', application_id, 'name') | quote }} +DB_OWNER={{ lookup('database', application_id, 'username') | quote }} +DB_V1={{ STALWART_MIGRATE_TARGET_DATABASE | quote }} +DB_V016={{ STALWART_MIGRATE_RETIRED_DATABASE | quote }} +LAYOUT_SQL={{ lookup('file', 'sql/store/layout.sql') | replace('\n', ' ') | quote }} +SOURCE_DIR={{ STALWART_CONFIG_DIR | quote }} +TARGET_DIR={{ STALWART_MIGRATE_TARGET_CONFIG | dirname | quote }} +STATE_DIR={{ [STALWART_MIGRATE_DIR, 'state'] | path_join | quote }} +BACKUP_FILE={{ [STALWART_MIGRATE_DIR, 'backup', lookup('database', application_id, 'name') ~ '-v016.dump'] | path_join | quote }} +MARKER={{ STALWART_STORE_MARKER_FILE | quote }} +DEPLOYMENT_MODE={{ DEPLOYMENT_MODE | quote }} +STALWART_CONTAINER={{ STALWART_CONTAINER | quote }} +STACK_DIR={{ lookup('container', application_id, 'directories.instance') | quote }} +COMPOSE_SERVICE=stalwart +STALWART_ADDRESS={{ STALWART_CONTAINER_ADDRESS }} +{% if DEPLOYMENT_MODE == 'swarm' %} +STALWART_SERVICE={{ lookup('container_service', application_id, 'stalwart') | quote }} +{% endif %} diff --git a/roles/web-app-stalwart/vars/main.yml b/roles/web-app-stalwart/vars/main.yml index 6e83d7cc17..da8e1a3503 100644 --- a/roles/web-app-stalwart/vars/main.yml +++ b/roles/web-app-stalwart/vars/main.yml @@ -42,8 +42,21 @@ container_hostname: "{{ lookup('container_hostname', application_id) }}" STALWART_OIDC_ONION_ISSUER: "{{ lookup('tls', 'web-app-keycloak', 'domain').endswith('.onion') }}" STALWART_OIDC_SOCKS_PROXY: "{{ lookup('tor_socks_proxy') if STALWART_OIDC_ONION_ISSUER | bool else '' }}" +# Keycloak access tokens carry neither a Stalwart audience nor a urn:ietf:params:oauth:scope:mail scope, so the v1 defaults reject every one of them. +STALWART_OIDC_TOKEN_VALIDATION: + skipAudienceValidation: true + unscopedTokens: "interoperable" STALWART_CONTAINER: "{{ lookup('config', application_id, 'services.stalwart.name') }}" +STALWART_DATABASE_SHARED: "{{ lookup('database', application_id, 'shared') | bool }}" +STALWART_STORE_LAYOUT_VERSION: "1" +STALWART_STORE_MARKER_FILE: "{{ [ lookup('container', application_id, 'directories.instance'), 'store.layout' ] | path_join }}" +STALWART_MIGRATE_DIR: "{{ [ lookup('container', application_id, 'directories.instance'), 'migrate-v016' ] | path_join }}" +STALWART_MIGRATE_SCRIPT: "{{ [ STALWART_MIGRATE_DIR, 'migrate.sh' ] | path_join }}" +STALWART_MIGRATE_TARGET_CONFIG: "{{ [ STALWART_MIGRATE_DIR, 'target', 'config.json' ] | path_join }}" +STALWART_MIGRATE_IMAGE: "{{ lookup('image', application_id, 'stalwart_migrate') }}" +STALWART_MIGRATE_TARGET_DATABASE: "{{ lookup('database', application_id, 'name') }}_v1" +STALWART_MIGRATE_RETIRED_DATABASE: "{{ lookup('database', application_id, 'name') }}_v016" STALWART_ANTIVIRUS_ENABLED: "{{ lookup('config', application_id, 'services.clamav.enabled') | bool }}" STALWART_CLAMAV_HOST: "clamav" @@ -67,6 +80,8 @@ STALWART_WEBUI_LOCAL_FILE: "{{ [ STALWART_CONFIG_DIR, 'webui.zip' ] | path_join STALWART_WEBUI_CONTAINER_FILE: "{{ lookup('volume', application_id, 'webui_bundle').target }}" STALWART_WEBUI_LOCAL_URL: "file://{{ STALWART_WEBUI_CONTAINER_FILE }}" STALWART_WEBUI_APP_DESCRIPTION: "Stalwart Web Interface" +STALWART_WEBUI_OAUTH_CLIENT_ID: "{{ lookup('config', application_id, 'services.sso.oidc.clients.webui') }}" +STALWART_WEBUI_BASE_URL: "{{ lookup('canonical_url', application_id) }}" STALWART_IP4_PUBLIC: "{{ DOCKER_PUBLIC_BIND_HOST }}" STALWART_ACTIVE_PROVIDER: "{{ lookup('mail_provider') == application_id }}" @@ -98,7 +113,8 @@ STALWART_ALLOWED_IPS: - "{{ lookup('subnet_gateway') }}" STALWART_ALLOWED_IP_REASON: "Docker gateway: reverse-proxied HTTP and container hairpin traffic share this address" STALWART_HTTP_SETTINGS: - useXForwarded: true + clientIpSource: forwarded + forwardedHops: 1 STALWART_SSO_ENABLED: "{{ lookup('sso', application_id, 'is_enabled') | bool }}" diff --git a/roles/web-app-wordpress/meta/addons/freedomtranslate-wp.yml b/roles/web-app-wordpress/meta/addons/freedomtranslate-wp.yml index d32d5a47c6..1a6fa77386 100644 --- a/roles/web-app-wordpress/meta/addons/freedomtranslate-wp.yml +++ b/roles/web-app-wordpress/meta/addons/freedomtranslate-wp.yml @@ -14,4 +14,4 @@ config: - name: freedomtranslate_service value: libretranslate - name: freedomtranslate_api_url - value: "{{ lookup('tls', 'web-svc-translate', 'url.base') | regex_replace('/+$', '') ~ '/translate' }}" + value: "{{ lookup('tls', 'web-svc-translate', 'url.origin') ~ '/translate' }}" diff --git a/roles/web-app-wordpress/meta/addons/integration-for-listmonk-mailing-list-and-newsletter-manager.yml b/roles/web-app-wordpress/meta/addons/integration-for-listmonk-mailing-list-and-newsletter-manager.yml index 323e433117..e03f4a3efc 100644 --- a/roles/web-app-wordpress/meta/addons/integration-for-listmonk-mailing-list-and-newsletter-manager.yml +++ b/roles/web-app-wordpress/meta/addons/integration-for-listmonk-mailing-list-and-newsletter-manager.yml @@ -11,4 +11,4 @@ update: upstream_id: integration-for-listmonk-mailing-list-and-newsletter-manager config: listmonk_settings: - api_url: "{{ lookup('tls', 'web-app-listmonk', 'url.base') }}/api" + api_url: "{{ lookup('tls', 'web-app-listmonk', 'url.origin') }}/api" diff --git a/roles/web-app-wordpress/meta/services.yml b/roles/web-app-wordpress/meta/services.yml index da87330f62..a9326d0886 100644 --- a/roles/web-app-wordpress/meta/services.yml +++ b/roles/web-app-wordpress/meta/services.yml @@ -66,7 +66,7 @@ wordpress: enabled: true swarm: enabled: true - version: 7.1.3 + version: 7.1.4 image: wordpress custom: true name: wordpress diff --git a/roles/web-app-xwiki/files/shell/debug_superadmin.sh b/roles/web-app-xwiki/files/shell/debug_superadmin.sh index 53cd6b4919..6e55db9997 100755 --- a/roles/web-app-xwiki/files/shell/debug_superadmin.sh +++ b/roles/web-app-xwiki/files/shell/debug_superadmin.sh @@ -10,7 +10,8 @@ # Usage: # debug_superadmin.sh \ # STATUS REDIRECTED URL WWW_AUTHENTICATE CONTENT_TYPE CONTENT_HEAD \ -# XWIKI_CONTAINER ANSIBLE_PASSWORD +# XWIKI_CONTAINER < password +# stdin: the inventory's superadmin password. set -euo pipefail STATUS="$1" @@ -20,7 +21,8 @@ WWW_AUTHENTICATE="$4" CONTENT_TYPE="$5" CONTENT_HEAD="$6" XWIKI_CONTAINER="$7" -ANSIBLE_PASSWORD="$8" +ANSIBLE_PASSWORD="$(cat)" +: "${ANSIBLE_PASSWORD:?the superadmin password must arrive on stdin}" echo "=== superadmin check ===" echo "status=$STATUS" diff --git a/roles/web-app-xwiki/tasks/02_manager_ops.yml b/roles/web-app-xwiki/tasks/02_manager_ops.yml index a4d7ce4c99..54afeebbbb 100644 --- a/roles/web-app-xwiki/tasks/02_manager_ops.yml +++ b/roles/web-app-xwiki/tasks/02_manager_ops.yml @@ -18,16 +18,21 @@ - block: - name: "🐛 DEBUG | superadmin check + pw hash compare (condensed)" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - script: >- - shell/debug_superadmin.sh - "{{ _super_check_ext.status }}" - "{{ _super_check_ext.redirected | default('n/a') }}" - "{{ _super_check_ext.url | default('n/a') }}" - "{{ _super_check_ext.www_authenticate | default(_super_check_ext.headers['www-authenticate'] | default('n/a')) }}" - "{{ _super_check_ext.content_type | default(_super_check_ext.headers['content-type'] | default('n/a')) }}" - "{{ (_super_check_ext.content | default(''))[:600] | replace('\n','\\n') }}" - "{{ XWIKI_CONTAINER }}" - "{{ XWIKI_SUPERADMIN_PASSWORD }}" + ansible.builtin.command: + argv: + - bash + - -c + - "{{ lookup('file', 'shell/debug_superadmin.sh') }}" + - debug_superadmin.sh + - "{{ _super_check_ext.status }}" + - "{{ _super_check_ext.redirected | default('n/a') }}" + - "{{ _super_check_ext.url | default('n/a') }}" + - "{{ _super_check_ext.www_authenticate | default(_super_check_ext.headers['www-authenticate'] | default('n/a')) }}" + - "{{ _super_check_ext.content_type | default(_super_check_ext.headers['content-type'] | default('n/a')) }}" + - "{{ (_super_check_ext.content | default(''))[:600] | replace('\n','\\n') }}" + - "{{ XWIKI_CONTAINER }}" + stdin: "{{ XWIKI_SUPERADMIN_PASSWORD }}" + expand_argument_vars: false register: _dbg_superadmin changed_when: false failed_when: false diff --git a/roles/web-app-xwiki/vars/main.yml b/roles/web-app-xwiki/vars/main.yml index 0ef6054c66..e94c94faec 100644 --- a/roles/web-app-xwiki/vars/main.yml +++ b/roles/web-app-xwiki/vars/main.yml @@ -8,7 +8,7 @@ container_hostname: "{{ lookup('container_hostname', application_id) }}" XWIKI_HOST_PORT: "{{ lookup('config', application_id, 'services.xwiki.ports.local.http') }}" XWIKI_HOSTNAME: "{{ container_hostname }}" -XWIKI_URL: "{{ lookup('tls', application_id, 'url.base') | regex_replace('/+$', '') }}" +XWIKI_URL: "{{ lookup('tls', application_id, 'url.origin') }}" XWIKI_HOST_PROPERTIES_PATH: "{{ [lookup('container', application_id, 'directories.config'), 'xwiki.properties'] | path_join }}" XWIKI_DOCK_DATA_DIR: "{{ lookup('volume', 'web-app-xwiki', 'data').target }}" diff --git a/roles/web-app-yourls/vars/main.yml b/roles/web-app-yourls/vars/main.yml index 0405654f05..036576c88b 100644 --- a/roles/web-app-yourls/vars/main.yml +++ b/roles/web-app-yourls/vars/main.yml @@ -10,7 +10,7 @@ YOURLS_VERSION: "{{ lookup('config', application_id, 'services.yourls.version') YOURLS_IMAGE: "{{ lookup('config', application_id, 'services.yourls.image') }}" YOURLS_CONTAINER: "{{ lookup('config', application_id, 'services.yourls.name') }}" YOURLS_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, entity_name) }}" -YOURLS_URL: "{{ lookup('tls', application_id, 'url.base') | regex_replace('/+$', '') }}" +YOURLS_URL: "{{ lookup('tls', application_id, 'url.origin') }}" YOURLS_ADMIN_LOCATION: "{{ lookup('config', application_id, 'server.locations.admin') }}" YOURLS_LANDINGPAGE_STATUS_CODE: "{{ lookup('config', application_id, 'server.status_codes.default') }}" YOURLS_DOCROOT: "/var/www/html" diff --git a/roles/web-opt-rdr-domains/tasks/main.yml b/roles/web-opt-rdr-domains/tasks/main.yml index f5fbcfda31..e9965b1e68 100644 --- a/roles/web-opt-rdr-domains/tasks/main.yml +++ b/roles/web-opt-rdr-domains/tasks/main.yml @@ -44,9 +44,19 @@ - name: 📜 TLS | Ensure the certificates of the redirect sources when: redirect_sources | selectattr('enabled') | list | length > 0 block: + - name: 🔎 TLS | Check which certificate directories of the redirect sources exist + ansible.builtin.stat: + path: "{{ redirect_cert_dir }}" + loop: "{{ redirect_sources | selectattr('enabled') | map(attribute='certs') | flatten | map('dirname') | unique }}" + loop_control: + loop_var: redirect_cert_dir + register: redirect_cert_dirs + - name: 🔎 TLS | Find the certificates of the redirect sources ansible.builtin.find: - paths: "{{ redirect_sources | selectattr('enabled') | map(attribute='certs') | flatten | map('dirname') | unique }}" + paths: >- + {{ redirect_cert_dirs.results | selectattr('stat.exists') | selectattr('stat.isdir') + | map(attribute='redirect_cert_dir') | list }} patterns: "{{ redirect_sources | selectattr('enabled') | map(attribute='certs') | flatten | map('basename') | unique }}" file_type: any follow: true diff --git a/roles/web-svc-logout/templates/compose.yml.j2 b/roles/web-svc-logout/templates/compose.yml.j2 index 88143e65e4..850bf35d61 100644 --- a/roles/web-svc-logout/templates/compose.yml.j2 +++ b/roles/web-svc-logout/templates/compose.yml.j2 @@ -3,7 +3,7 @@ {% set service_name = 'logout' | labelled(logout_instance.label, '-') %} {% set logout_urls = [] %} {% for logout_domain in lookup('applications') | logout_domains(group_names, lookup('domains'), logout_instance.network) | unique | sort %} - {% set _ = logout_urls.append(lookup('tls', logout_domain, 'url.base') | regex_replace('/+$', '')) %} + {% set _ = logout_urls.append(lookup('tls', logout_domain, 'url.origin')) %} {% endfor %} {{ service_name }}: {% include 'roles/sys-svc-container/templates/base.yml.j2' %} diff --git a/roles/web-svc-logout/templates/logout-proxy.conf.j2 b/roles/web-svc-logout/templates/logout-proxy.conf.j2 index 107fd67c4a..1c7cfc2cfc 100644 --- a/roles/web-svc-logout/templates/logout-proxy.conf.j2 +++ b/roles/web-svc-logout/templates/logout-proxy.conf.j2 @@ -1,14 +1,11 @@ location = /logout { {{ lookup('proxy_pass', 'web-svc-logout', 'logout', 'http', tail='/logout') }} - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; + {% include 'roles/sys-svc-proxy/templates/headers/forwarded_base.conf.j2' %} proxy_http_version 1.1; {% include 'roles/sys-svc-proxy/templates/headers/upstream_strips.conf.j2' %} - {%- set aca_origin = (lookup('tls', 'web-svc-logout', 'url.base') | regex_replace('/$', '')) ~ " always" -%} + {%- set aca_origin = lookup('tls', 'web-svc-logout', 'url.origin') ~ " always" -%} {%- set aca_credentials = "'true' always" -%} {%- set aca_methods = "'GET, OPTIONS' always" -%} {%- set aca_headers = "'Accept, Authorization' always" -%} diff --git a/roles/web-svc-seaweedfs/README.md b/roles/web-svc-seaweedfs/README.md index ddd02354f7..cfba524c05 100644 --- a/roles/web-svc-seaweedfs/README.md +++ b/roles/web-svc-seaweedfs/README.md @@ -19,9 +19,13 @@ A node running this role without the console keeps its object store and its S3 e Per-consumer S3 identities are rendered into `s3.json`: each consuming role receives an access key and bucket-scoped `Read`, `Write`, `WriteAcp`, `List`, and `Tagging` actions, and consumers marked `public` additionally receive anonymous read on their bucket. Consumer buckets are created through `weed shell` when a consumer role requests provisioning. +The bucket of every consumer not marked `public` carries a bucket policy statement `DenyAnonymousRead` that denies all unsigned reads, so a `public-read` ACL set by an app never exposes an object; signed and presigned requests are unaffected. +Every deploy of this role converges that statement on all existing consumer buckets, adding it to private buckets and removing it from public ones, and a consumer's provisioning applies it right after creating the bucket. +Other statements an operator adds to a consumer's bucket policy are kept. In embedded mode (`shared: false`) a consumer's compose stack receives a storage-only SeaweedFS container without UI or published ports. -The embedded S3 listener performs no authentication, so it MUST stay confined to the consumer's isolated compose network. +The embedded S3 listener starts without identities and accepts unauthenticated requests until the background `s3.configure` grant at startup registers the consumer identity; from then on it authenticates against that identity. +Embedded buckets carry no `DenyAnonymousRead` statement because the listener publishes no port, so the container MUST stay confined to the consumer's isolated compose network. ## Features diff --git a/roles/web-svc-seaweedfs/tasks/00_core.yml b/roles/web-svc-seaweedfs/tasks/00_core.yml index 9682fa26ca..0650be0cfc 100644 --- a/roles/web-svc-seaweedfs/tasks/00_core.yml +++ b/roles/web-svc-seaweedfs/tasks/00_core.yml @@ -49,3 +49,16 @@ until: _seaweedfs_ready.rc == 0 changed_when: false when: IS_STACK_HOST | bool + +- name: "🔐 Converge the bucket policy of every existing consumer bucket" + when: IS_STACK_HOST | bool + block: + - name: "📋 List SeaweedFS buckets" + include_tasks: utils/bucket/list.yml + + - name: "🔐 Converge the bucket policy of each consumer whose bucket exists" + include_tasks: utils/bucket/policy.yml + loop: "{{ lookup('objstore_consumers', 'seaweedfs') }}" + loop_control: + loop_var: seaweedfs_bucket_policy_consumer + when: lookup('objstore', seaweedfs_bucket_policy_consumer, 'bucket') in (_seaweedfs_buckets.stdout | seaweedfs_bucket_names) diff --git a/roles/web-svc-seaweedfs/tasks/01_init_consumer.yml b/roles/web-svc-seaweedfs/tasks/01_init_consumer.yml index ce674b212b..b22b8e95ee 100644 --- a/roles/web-svc-seaweedfs/tasks/01_init_consumer.yml +++ b/roles/web-svc-seaweedfs/tasks/01_init_consumer.yml @@ -7,19 +7,11 @@ - name: "🔧 Provision the SeaweedFS bucket on the stack host" when: IS_STACK_HOST | bool + vars: + _seaweedfs_bucket_listed: "{{ lookup('objstore', objstore_consumer_id, 'bucket') in (_seaweedfs_buckets.stdout | seaweedfs_bucket_names) }}" block: - name: "📋 List SeaweedFS buckets" - ansible.builtin.shell: | - set -euo pipefail - echo 's3.bucket.list' | container exec -i {{ SEAWEEDFS_CONTAINER_ADDRESS }} weed shell -master=localhost:{{ SEAWEEDFS_MASTER_PORT_INTERNAL }} - args: - executable: /bin/bash - register: _seaweedfs_buckets - changed_when: false - timeout: "{{ lookup('timeout', 60) | int }}" - retries: 3 - delay: 10 - until: _seaweedfs_buckets is succeeded + include_tasks: utils/bucket/list.yml - name: "📁 Create the SeaweedFS bucket for '{{ objstore_consumer_id }}'" ansible.builtin.shell: | @@ -33,4 +25,10 @@ retries: 3 delay: 10 until: _seaweedfs_create is succeeded - when: lookup('objstore', objstore_consumer_id, 'bucket') not in _seaweedfs_buckets.stdout + when: not _seaweedfs_bucket_listed + + - name: "🔐 Converge the bucket policy of '{{ objstore_consumer_id }}'" + include_tasks: utils/bucket/policy.yml + vars: + seaweedfs_bucket_policy_consumer: "{{ objstore_consumer_id }}" + when: _seaweedfs_bucket_listed or _seaweedfs_create is changed diff --git a/roles/web-svc-seaweedfs/tasks/utils/bucket/list.yml b/roles/web-svc-seaweedfs/tasks/utils/bucket/list.yml new file mode 100644 index 0000000000..39897a0bf8 --- /dev/null +++ b/roles/web-svc-seaweedfs/tasks/utils/bucket/list.yml @@ -0,0 +1,14 @@ +--- +- name: "📋 List SeaweedFS buckets" + ansible.builtin.shell: | + set -euo pipefail + echo 's3.bucket.list' | container exec -i {{ SEAWEEDFS_CONTAINER_ADDRESS }} weed shell -master=localhost:{{ SEAWEEDFS_MASTER_PORT_INTERNAL }} + args: + executable: /bin/bash + register: _seaweedfs_buckets + changed_when: false + check_mode: false + timeout: "{{ lookup('timeout', 60) | int }}" + retries: 3 + delay: 10 + until: _seaweedfs_buckets is succeeded diff --git a/roles/web-svc-seaweedfs/tasks/utils/bucket/policy.yml b/roles/web-svc-seaweedfs/tasks/utils/bucket/policy.yml new file mode 100644 index 0000000000..80fd40746a --- /dev/null +++ b/roles/web-svc-seaweedfs/tasks/utils/bucket/policy.yml @@ -0,0 +1,63 @@ +--- +# Param: seaweedfs_bucket_policy_consumer - consumer role id; its bucket MUST already exist +- name: "🔐 Converge the bucket policy of '{{ seaweedfs_bucket_policy_consumer }}'" + vars: + _seaweedfs_bucket: "{{ lookup('objstore', seaweedfs_bucket_policy_consumer, 'bucket') }}" + _seaweedfs_bucket_policy_url: "http://127.0.0.1:{{ SEAWEEDFS_S3_PORT_INTERNAL }}/{{ _seaweedfs_bucket }}?policy" + _seaweedfs_bucket_policy_stored: "{{ _seaweedfs_bucket_policy_read.stdout | seaweedfs_stored_bucket_policy }}" + _seaweedfs_bucket_policy_target: >- + {{ _seaweedfs_bucket_policy_stored | seaweedfs_bucket_policy_target( + _seaweedfs_bucket, + lookup('objstore', seaweedfs_bucket_policy_consumer, 'public') | bool) }} + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + block: + - name: "🔍 Read the bucket policy of '{{ seaweedfs_bucket_policy_consumer }}'" + ansible.builtin.shell: >- + {{ SEAWEEDFS_S3_ADMIN_CURL }} -w '\n%{http_code}' {{ _seaweedfs_bucket_policy_url | quote }} + args: + executable: /bin/bash + stdin: "{{ SEAWEEDFS_ADMIN_CREDENTIALS }}" + register: _seaweedfs_bucket_policy_read + changed_when: false + check_mode: false + failed_when: >- + _seaweedfs_bucket_policy_read.rc != 0 + or (_seaweedfs_bucket_policy_read.stdout | seaweedfs_stored_bucket_policy) is none + timeout: "{{ lookup('timeout', 60) | int }}" + retries: 3 + delay: 10 + until: _seaweedfs_bucket_policy_read is succeeded + + - name: "🔒 Put the target bucket policy on '{{ seaweedfs_bucket_policy_consumer }}'" + ansible.builtin.shell: >- + {{ SEAWEEDFS_S3_ADMIN_CURL }} -f -X PUT --data-binary @- {{ _seaweedfs_bucket_policy_url | quote }} + args: + executable: /bin/bash + stdin: |- + {{ SEAWEEDFS_ADMIN_CREDENTIALS }} + {{ _seaweedfs_bucket_policy_target | to_json }} + register: _seaweedfs_bucket_policy_put + changed_when: true + timeout: "{{ lookup('timeout', 60) | int }}" + retries: 3 + delay: 10 + until: _seaweedfs_bucket_policy_put is succeeded + when: >- + _seaweedfs_bucket_policy_target | length > 0 + and _seaweedfs_bucket_policy_target != _seaweedfs_bucket_policy_stored + + - name: "🔓 Delete the bucket policy of '{{ seaweedfs_bucket_policy_consumer }}'" + ansible.builtin.shell: >- + {{ SEAWEEDFS_S3_ADMIN_CURL }} -f -X DELETE {{ _seaweedfs_bucket_policy_url | quote }} + args: + executable: /bin/bash + stdin: "{{ SEAWEEDFS_ADMIN_CREDENTIALS }}" + register: _seaweedfs_bucket_policy_delete + changed_when: true + timeout: "{{ lookup('timeout', 60) | int }}" + retries: 3 + delay: 10 + until: _seaweedfs_bucket_policy_delete is succeeded + when: >- + _seaweedfs_bucket_policy_target | length == 0 + and _seaweedfs_bucket_policy_stored | length > 0 diff --git a/roles/web-svc-seaweedfs/vars/main.yml b/roles/web-svc-seaweedfs/vars/main.yml index 15dabf47a8..5b1e7003bd 100644 --- a/roles/web-svc-seaweedfs/vars/main.yml +++ b/roles/web-svc-seaweedfs/vars/main.yml @@ -15,5 +15,13 @@ SEAWEEDFS_S3_DOMAIN: "{{ lookup('config', application_id, 'domains.canonical.api SEAWEEDFS_ADMIN_ACCESS_KEY: "{{ lookup('users', 'platform_administrator').username }}" SEAWEEDFS_ADMIN_SECRET_KEY: "{{ lookup('users', 'platform_administrator').password }}" +SEAWEEDFS_ADMIN_CREDENTIALS: "{{ SEAWEEDFS_ADMIN_ACCESS_KEY }}:{{ SEAWEEDFS_ADMIN_SECRET_KEY }}" + +SEAWEEDFS_S3_REGION: "{{ lookup('config', application_id, 'services.seaweedfs.region') }}" +SEAWEEDFS_S3_ADMIN_CURL: >- + IFS= read -r SEAWEEDFS_ADMIN_CREDENTIALS && export SEAWEEDFS_ADMIN_CREDENTIALS && + container exec -i -e SEAWEEDFS_ADMIN_CREDENTIALS {{ SEAWEEDFS_CONTAINER_ADDRESS }} + sh -c 'exec {{ lookup('timeout', 30) | curl(retries=0) }} -S --aws-sigv4 "aws:amz:{{ SEAWEEDFS_S3_REGION }}:s3" --variable %SEAWEEDFS_ADMIN_CREDENTIALS --expand-user + "{{ '{{' }}SEAWEEDFS_ADMIN_CREDENTIALS{{ '}}' }}" "$@"' curl SEAWEEDFS_S3_CONFIG_PATH: "{{ [ lookup('container', application_id, 'directories.volumes'), 's3.json' ] | path_join }}" diff --git a/scripts/github/README.md b/scripts/github/README.md index 7aa85f7720..b8e2b42c1f 100644 --- a/scripts/github/README.md +++ b/scripts/github/README.md @@ -13,6 +13,7 @@ This directory holds the shell helpers that GitHub Actions workflows under [`.gi | [update/](update/) | The scheduled `🔄 Update versions` pipeline (version bumps and PR open/refresh). | | [i18n/](i18n/) | Catalog extraction and machine translation for the per-language runners of `🌐 Translate catalogs`. | | [release/](release/) | Release-time gates that decide whether a tagged commit may be released. | +| [sync/](sync/) | Mirroring the source repository's `main` into a fork on every push. | A new helper MUST live in the subfolder that matches its responsibility. New responsibilities MAY motivate a new subfolder, but MUST NOT flatten back into the top level. diff --git a/scripts/github/sync/README.md b/scripts/github/sync/README.md new file mode 100644 index 0000000000..81f7e8bc51 --- /dev/null +++ b/scripts/github/sync/README.md @@ -0,0 +1,5 @@ +# GitHub Sync Helpers 🔄 + +[main_from_repository.sh](main_from_repository.sh) force-pushes the source repository's `main` onto the current repository's `main`. The `🔄 Sync main` job of [entry-push-latest.yml](../../../.github/workflows/entry-push-latest.yml) runs it on every push. + +The push needs the secret `CI_SYNC_MAIN_TOKEN`, see [secrets.md](../../../docs/contributing/tools/github/actions/secrets.md). The source repository and the switch to disable the sync are the repository variable `CI_SYNC_MAIN_SOURCE_REPOSITORY`, see [configuration.md](../../../docs/contributing/tools/github/actions/configuration.md). diff --git a/scripts/github/sync/main_from_repository.sh b/scripts/github/sync/main_from_repository.sh new file mode 100755 index 0000000000..576795e947 --- /dev/null +++ b/scripts/github/sync/main_from_repository.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash +# +# Env: +# GITHUB_REPOSITORY - owner/repo of the running job, whose main is overwritten +# CI_SYNC_MAIN_TOKEN - fine-grained token for GITHUB_REPOSITORY only, with Contents and Workflows write +# CI_SYNC_MAIN_SOURCE_REPOSITORY, CI_SYNC_MAIN_SOURCE_REPOSITORY_IS_SET, +# CI_SYNC_MAIN_SOURCE_REPOSITORY_DEFAULT - the source of main, see scripts/meta/resolve/baseline_remote.sh +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/../../.." && pwd)" + +: "${GITHUB_REPOSITORY:?Missing GITHUB_REPOSITORY}" + +source_remote="$(bash "${REPO_ROOT}/scripts/meta/resolve/baseline_remote.sh")" +if [[ "${source_remote}" == "origin" ]]; then + echo "Main sync skipped: no source repository other than ${GITHUB_REPOSITORY} is configured." + exit 0 +fi + +if [[ -z "${CI_SYNC_MAIN_TOKEN:-}" ]]; then + echo "ERROR: secret CI_SYNC_MAIN_TOKEN is not set, so ${GITHUB_REPOSITORY}:main cannot be synced from ${source_remote}." >&2 + echo "Create it as described in docs/contributing/tools/github/actions/secrets.md, or disable the sync through the repository variable CI_SYNC_MAIN_SOURCE_REPOSITORY." >&2 + exit 1 +fi + +echo "Syncing ${GITHUB_REPOSITORY}:main from ${source_remote}." +git fetch "${source_remote}" main:refs/remotes/main-sync-source/main --force + +auth="$(printf 'x-access-token:%s' "${CI_SYNC_MAIN_TOKEN}" | base64 -w0)" +GIT_CONFIG_COUNT=1 \ + GIT_CONFIG_KEY_0="http.extraheader" \ + GIT_CONFIG_VALUE_0="AUTHORIZATION: basic ${auth}" \ + git push "https://github.com/${GITHUB_REPOSITORY}.git" refs/remotes/main-sync-source/main:refs/heads/main --force diff --git a/scripts/lint/README.md b/scripts/lint/README.md index 4a6f29322c..01d706314e 100644 --- a/scripts/lint/README.md +++ b/scripts/lint/README.md @@ -6,5 +6,11 @@ This directory contains scripts that run repository lint checks. - 🔎 Keep lint entry points small, explicit, and callable from `make` - ✅ Separate lint execution from tool installation and environment bootstrap +## Changed files only 🎯 + +Outside CI, [wrapper.sh](wrapper.sh) lists every file changed since the merge-base of `HEAD` and `INFINITO_LINT_DIFF_BASE` (default `origin/main`, untracked files included) and hands the list to the container as `LINT_DIFF_FILES`. The `ansible`, `javascript`, `markdown`, `mermaid`, `shellcheck` and `sql` lints, and the matching workers of `autoformat`, then check only those files. They check every file again when the list names their own configuration or a shared lint script, when `INFINITO_LINT_DIFF_BASE` is empty or has no merge-base, and in CI. The rules live in [diff/files.sh](diff/files.sh). + +`lint-ansible` additionally skips ansible-lint while the tree matches the last green run, which `autoformat` records after a clean `ansible-lint --fix` ([ansible/stamp.sh](ansible/stamp.sh)); the playbook syntax check always runs. + The scope of this folder is lint execution. Tool installation belongs in `scripts/install`, while build and test workflows should stay in their dedicated script directories. diff --git a/scripts/lint/ansible.sh b/scripts/lint/ansible.sh index 6264b22558..e647486e9e 100755 --- a/scripts/lint/ansible.sh +++ b/scripts/lint/ansible.sh @@ -1,9 +1,5 @@ #!/usr/bin/env bash # shellcheck shell=bash -# Syntax-check the playbook, then run ansible-lint behind a content -# fingerprint gate: when no file ansible-lint walks (or its config) changed -# since the last green run, the lint is skipped; any change triggers the -# full run again, so coverage never shrinks. set -euo pipefail SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" @@ -28,33 +24,31 @@ if ! command -v ansible-lint >/dev/null 2>&1; then exit 0 fi -LINT_SCOPE=(roles tasks group_vars host_vars library plugins playbook.yml ansible.cfg .ansible-lint .ansible-lint-ignore) -STAMP="build/ansible-lint.stamp" +# shellcheck source=scripts/lint/diff/files.sh +source "${SCRIPT_DIR}/diff/files.sh" +# shellcheck source=scripts/lint/ansible/stamp.sh +source "${SCRIPT_DIR}/ansible/stamp.sh" -fingerprint() { - { - git rev-parse HEAD 2>/dev/null - git ls-files -s -- "${LINT_SCOPE[@]}" 2>/dev/null - git status --porcelain -- "${LINT_SCOPE[@]}" 2>/dev/null | - awk '{print $NF}' | sort -u | - while IFS= read -r dirty; do - [ -f "${dirty}" ] && sha256sum "${dirty}" - done - } | sha256sum | cut -d' ' -f1 -} - -current="" -if git rev-parse HEAD >/dev/null 2>&1; then - current="$(fingerprint)" +current="$(ansible_lint_fingerprint all)" +if ansible_lint_stamp_matches "${current}"; then + echo "ansible-lint: no file changed since the last green run; skipping" + exit 0 fi -if [[ -n "${current}" && -f "${STAMP}" && "$(cat "${STAMP}")" == "${current}" ]]; then - echo "ansible-lint: no lintable file changed since the last green run; skipping" + +if lint_diff_active ansible; then + mapfile -t yaml_files < <(lint_diff_files '\.ya?ml$' | ansible_lint_included) + if [[ "${#yaml_files[@]}" -eq 0 ]]; then + echo "ansible-lint: no changed YAML file; skipping" + exit 0 + fi + ansible-lint "${yaml_files[@]}" exit 0 fi ansible-lint - -if [[ -n "${current}" ]]; then - mkdir -p "$(dirname "${STAMP}")" - printf '%s\n' "${current}" >"${STAMP}" +mapfile -t custom_roles < <(lint_custom_roles) +if [[ "${#custom_roles[@]}" -gt 0 ]]; then + ansible-lint "${custom_roles[@]}" fi + +ansible_lint_stamp_record "${current}" diff --git a/scripts/lint/ansible/stamp.sh b/scripts/lint/ansible/stamp.sh new file mode 100755 index 0000000000..8918a88d71 --- /dev/null +++ b/scripts/lint/ansible/stamp.sh @@ -0,0 +1,48 @@ +# shellcheck shell=bash +# Param ansible_lint_fingerprint : content hash of every file in the tree, or of its YAML files only. +# Param ansible_lint_stamp_matches : succeeds when the last green ansible-lint run saw this fingerprint. +# Param ansible_lint_stamp_record : records the fingerprint as linted green. +# Param ansible_lint_included: passes on the stdin paths that lie outside the exclude_paths of .ansible-lint. +ANSIBLE_LINT_STAMP="build/ansible-lint.stamp" + +ansible_lint_fingerprint() { + local -a only=() + case "$1" in + all) ;; + yaml) only=(\( -name '*.yml' -o -name '*.yaml' \)) ;; + *) + printf 'ansible_lint_fingerprint: expected all or yaml, got %s\n' "$1" >&2 + return 2 + ;; + esac + find . \( -path ./build -o -name .git -o -name node_modules -o -name __pycache__ -o -name .ansible \ + -o -name .cache -o -name .pytest_cache -o -name .ruff_cache -o -name .phpunit.result.cache \) -prune \ + -o -type f "${only[@]}" -print0 | + LC_ALL=C sort -z | + xargs -0 sha256sum | + sha256sum | + cut -d' ' -f1 +} + +ansible_lint_stamp_matches() { + [[ -f "${ANSIBLE_LINT_STAMP}" && "$(<"${ANSIBLE_LINT_STAMP}")" == "$1" ]] +} + +ansible_lint_stamp_record() { + mkdir -p "$(dirname "${ANSIBLE_LINT_STAMP}")" + printf '%s\n' "$1" >"${ANSIBLE_LINT_STAMP}" +} + +ansible_lint_included() { + python3 -c ' +import sys +import yaml + +with open(".ansible-lint", encoding="utf-8") as handle: + prefixes = [entry.strip("/") + "/" for entry in yaml.safe_load(handle)["exclude_paths"]] +for line in sys.stdin: + path = line.rstrip("\n") + if not any((path + "/").startswith(prefix) for prefix in prefixes): + print(path) +' +} diff --git a/scripts/lint/autoformat.sh b/scripts/lint/autoformat.sh index 36613beaf0..fa2c392848 100755 --- a/scripts/lint/autoformat.sh +++ b/scripts/lint/autoformat.sh @@ -22,6 +22,11 @@ cd "${REPO_ROOT}" RUFF_CACHE_DIR="build/ruff-cache-$(id -u)" export RUFF_CACHE_DIR +# shellcheck source=scripts/lint/diff/files.sh +source "${SCRIPT_DIR}/diff/files.sh" +# shellcheck source=scripts/lint/ansible/stamp.sh +source "${SCRIPT_DIR}/ansible/stamp.sh" + status_dir="$(mktemp -d)" # $1 = tool name, $2 = OK|SKIP @@ -37,8 +42,10 @@ run_ruff() { return 0 fi local rc=0 - ruff format . || rc=$? - [[ $rc -eq 0 ]] && { ruff check . --fix || rc=$?; } + local -a custom_roles=() + mapfile -t custom_roles < <(lint_custom_roles) + ruff format . "${custom_roles[@]}" || rc=$? + [[ $rc -eq 0 ]] && { ruff check . --fix "${custom_roles[@]}" || rc=$?; } if [[ $rc -eq 0 ]]; then write_status ruff OK else @@ -71,7 +78,11 @@ run_shell_pair() { fi if command -v shellcheck &>/dev/null; then - mapfile -t shellcheck_files < <(find . -type f -name '*.sh' 2>/dev/null | sort) + if lint_diff_active shellcheck; then + mapfile -t shellcheck_files < <(lint_diff_files '\.sh$') + else + mapfile -t shellcheck_files < <(find . -type f -name '*.sh' 2>/dev/null | sort) + fi if [[ "${#shellcheck_files[@]}" -gt 0 ]]; then local diff_file rc=0 diff_file="$(mktemp)" @@ -102,7 +113,16 @@ run_markdownlint() { return 0 fi local rc=0 - markdownlint-cli2 --fix >/dev/null 2>&1 || rc=$? + local -a args=() + if lint_diff_active markdown; then + mapfile -t args < <(lint_diff_files '\.md$' | sed 's/^/:/') + if [[ "${#args[@]}" -eq 0 ]]; then + write_status markdownlint-cli2 OK + return 0 + fi + args=(--no-globs "${args[@]}") + fi + markdownlint-cli2 --fix "${args[@]}" >/dev/null 2>&1 || rc=$? if [[ $rc -le 1 ]]; then write_status markdownlint-cli2 OK else @@ -115,9 +135,26 @@ run_ansible_lint() { write_status ansible-lint SKIP return 0 fi - local rc=0 out + local rc=0 out yaml_before + local -a targets=() custom_roles=() + if lint_diff_active ansible; then + mapfile -t targets < <(lint_diff_files '\.ya?ml$' | ansible_lint_included) + if [[ "${#targets[@]}" -eq 0 ]]; then + write_status ansible-lint OK + return 0 + fi + else + mapfile -t custom_roles < <(lint_custom_roles) + fi out="$(mktemp)" - ansible-lint --fix >"${out}" 2>&1 || rc=$? + yaml_before="$(ansible_lint_fingerprint yaml)" + ansible-lint --fix "${targets[@]}" >"${out}" 2>&1 || rc=$? + if [[ "${#custom_roles[@]}" -gt 0 && ($rc -eq 0 || $rc -eq 2 || $rc -eq 8) ]]; then + ansible-lint --fix "${custom_roles[@]}" >>"${out}" 2>&1 || rc=$? + fi + if [[ $rc -eq 0 && "${#targets[@]}" -eq 0 && "$(ansible_lint_fingerprint yaml)" == "${yaml_before}" ]]; then + touch "${status_dir}/.ansible-lint-clean" + fi if [[ $rc -eq 0 || $rc -eq 2 || $rc -eq 8 ]]; then write_status ansible-lint OK else @@ -149,7 +186,15 @@ run_eslint() { return 0 fi local rc=0 - npx --no-install eslint --fix 'roles/**/files/**/*.js' >/dev/null 2>&1 || rc=$? + local -a targets=('roles/**/files/**/*.js') + if lint_diff_active javascript; then + mapfile -t targets < <(lint_diff_files '^roles/[^/]+/files/.*\.js$') + if [[ "${#targets[@]}" -eq 0 ]]; then + write_status eslint OK + return 0 + fi + fi + npx --no-install eslint --fix --no-warn-ignored "${targets[@]}" >/dev/null 2>&1 || rc=$? if [[ $rc -le 1 ]]; then write_status eslint OK else @@ -175,6 +220,10 @@ else for w in "${workers[@]}"; do "${w}" || true; done # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error fi +if [[ -f "${status_dir}/.ansible-lint-clean" ]]; then + ansible_lint_stamp_record "$(ansible_lint_fingerprint all)" +fi + ran=() failed=() skipped=() diff --git a/scripts/lint/diff/files.sh b/scripts/lint/diff/files.sh new file mode 100755 index 0000000000..3fb0288d2d --- /dev/null +++ b/scripts/lint/diff/files.sh @@ -0,0 +1,57 @@ +# shellcheck shell=bash +# Param lint_diff_write : on the host, writes build/lint-diff-.txt with every file changed since the merge-base of HEAD and INFINITO_LINT_DIFF_BASE (untracked files and pulled custom roles included) and prints its path; prints nothing when every file must be linted. +# Param lint_diff_active : succeeds when LINT_DIFF_FILES names a list and none of its files is configuration of that tool or a shared lint script. +# Param lint_diff_files : prints the listed files matching that still exist, one per line. +# Param lint_custom_roles: prints every pulled custom role directory (roles/web-app-cst-*), one per line; Git ignores them, so tools that honour .gitignore get them passed explicitly. + +lint_custom_roles() { + find roles -mindepth 1 -maxdepth 1 -type d -name 'web-app-cst-*' -print | LC_ALL=C sort +} + +lint_diff_write() { + local list="build/lint-diff-$1.txt" merge_base + if [[ -n "${GITHUB_ACTIONS:-}" || -z "${INFINITO_LINT_DIFF_BASE:-}" ]]; then + return 0 + fi + if ! merge_base="$(git merge-base HEAD "${INFINITO_LINT_DIFF_BASE}" 2>/dev/null)"; then + echo "lint $1: no merge-base with ${INFINITO_LINT_DIFF_BASE}; checking every file" >&2 + return 0 + fi + mkdir -p build + { + git diff --name-only --diff-filter=d "${merge_base}" + git ls-files --others --exclude-standard + lint_custom_roles | xargs -r -d '\n' -I{} find {} -type f -print + } | LC_ALL=C sort -u >"${list}" + echo "lint $1: $(wc -l <"${list}") file(s) changed since ${INFINITO_LINT_DIFF_BASE}; ansible, javascript, markdown, mermaid, shellcheck and sql check only those unless their configuration changed" >&2 + printf '%s\n' "${list}" +} + +lint_diff_active() { + local list="${LINT_DIFF_FILES:-}" trigger + case "$1" in + ansible) trigger='^(\.ansible-lint|\.ansible-lint-ignore|ansible\.cfg|requirements/[^/]+\.ya?ml|scripts/lint/ansible\.sh|scripts/lint/ansible/.*)$' ;; + javascript) trigger='^(eslint\.config\.js|package\.json|package-lock\.json|scripts/lint/javascript\.sh)$' ;; + markdown) trigger='(^|/)\.markdownlint[^/]*$|^scripts/lint/markdown\.sh$' ;; + mermaid) trigger='^scripts/lint/mermaid\.sh$' ;; + shellcheck) trigger='(^|/)\.shellcheckrc$|^scripts/lint/shellcheck\.sh$' ;; + sql) trigger='(^|/)\.sqlfluff$|^scripts/lint/sql\.sh$' ;; + *) + echo "lint_diff_active: unknown tool '$1'" >&2 + return 2 + ;; + esac + [[ -n "${list}" && -f "${list}" ]] || return 1 + if grep -qE "${trigger}|^scripts/lint/(wrapper|autoformat)\.sh$|^scripts/lint/diff/" "${list}"; then + return 1 + fi +} + +lint_diff_files() { + local file + { grep -E "$1" "${LINT_DIFF_FILES}" || [[ $? -eq 1 ]]; } | while IFS= read -r file; do + if [[ -f "${file}" ]]; then + printf '%s\n' "${file}" + fi + done +} diff --git a/scripts/lint/javascript.sh b/scripts/lint/javascript.sh index 233872d888..5ea9def5c9 100755 --- a/scripts/lint/javascript.sh +++ b/scripts/lint/javascript.sh @@ -16,4 +16,17 @@ if [[ ! -d "node_modules/eslint" ]]; then exit 127 fi -npx --no-install eslint 'roles/**/files/**/*.js' +# shellcheck source=scripts/lint/diff/files.sh +source "${SCRIPT_DIR}/diff/files.sh" + +if ! lint_diff_active javascript; then + npx --no-install eslint 'roles/**/files/**/*.js' + exit +fi + +mapfile -t js_files < <(lint_diff_files '^roles/[^/]+/files/.*\.js$') +if [[ "${#js_files[@]}" -eq 0 ]]; then + echo "No changed JavaScript files." + exit 0 +fi +npx --no-install eslint --no-warn-ignored "${js_files[@]}" diff --git a/scripts/lint/markdown.sh b/scripts/lint/markdown.sh index cc873ce39b..f339b8b4d8 100755 --- a/scripts/lint/markdown.sh +++ b/scripts/lint/markdown.sh @@ -16,4 +16,17 @@ if ! command -v markdownlint-cli2 >/dev/null 2>&1; then exit 127 fi -markdownlint-cli2 +# shellcheck source=scripts/lint/diff/files.sh +source "${SCRIPT_DIR}/diff/files.sh" + +if ! lint_diff_active markdown; then + markdownlint-cli2 + exit +fi + +mapfile -t md_files < <(lint_diff_files '\.md$') +if [[ "${#md_files[@]}" -eq 0 ]]; then + echo "No changed Markdown files." + exit 0 +fi +markdownlint-cli2 --no-globs "${md_files[@]/#/:}" diff --git a/scripts/lint/mermaid.sh b/scripts/lint/mermaid.sh index 1f1a606485..7127666a11 100755 --- a/scripts/lint/mermaid.sh +++ b/scripts/lint/mermaid.sh @@ -26,7 +26,14 @@ trap 'rm -rf "${workdir}"' EXIT puppeteer_cfg="${workdir}/puppeteer-config.json" printf '%s\n' '{"args":["--no-sandbox","--disable-gpu"]}' >"${puppeteer_cfg}" -mapfile -t md_files < <(grep -rlF --include='*.md' '```mermaid' . 2>/dev/null | sort || true) +# shellcheck source=scripts/lint/diff/files.sh +source "${SCRIPT_DIR}/diff/files.sh" + +if lint_diff_active mermaid; then + mapfile -t md_files < <(lint_diff_files '\.md$' | xargs -r -d '\n' grep -lF '```mermaid' || true) +else + mapfile -t md_files < <(grep -rlF --include='*.md' '```mermaid' . 2>/dev/null | sort || true) +fi if [[ ${#md_files[@]} -eq 0 ]]; then echo "No Markdown files contain a mermaid block; nothing to render." diff --git a/scripts/lint/python.sh b/scripts/lint/python.sh index c5da2efda9..420b4d60ff 100755 --- a/scripts/lint/python.sh +++ b/scripts/lint/python.sh @@ -11,6 +11,10 @@ cd "${REPO_ROOT}" RUFF_CACHE_DIR="build/ruff-cache-$(id -u)" export RUFF_CACHE_DIR +# shellcheck source=scripts/lint/diff/files.sh +source "${SCRIPT_DIR}/diff/files.sh" +mapfile -t custom_roles < <(lint_custom_roles) + shfmt -w scripts -ruff format . -ruff check . --fix +ruff format . "${custom_roles[@]}" +ruff check . --fix "${custom_roles[@]}" diff --git a/scripts/lint/shellcheck.sh b/scripts/lint/shellcheck.sh index ce9ed1768b..0dce5748d4 100755 --- a/scripts/lint/shellcheck.sh +++ b/scripts/lint/shellcheck.sh @@ -8,12 +8,30 @@ REPO_ROOT="$(cd -- "${SCRIPT_DIR}/../.." && pwd)" cd "${REPO_ROOT}" -mapfile -t shellcheck_files < <(find . -type f -name '*.sh' 2>/dev/null | sed 's|^\./||' | sort) +# shellcheck source=scripts/lint/diff/files.sh +source "${SCRIPT_DIR}/diff/files.sh" + +if lint_diff_active shellcheck; then + mapfile -t shellcheck_files < <(lint_diff_files '\.sh$') +else + mapfile -t shellcheck_files < <(find . -type f -name '*.sh' 2>/dev/null | sed 's|^\./||' | sort) +fi if [[ "${#shellcheck_files[@]}" -eq 0 ]]; then printf 'No shell scripts found.\n' exit 0 fi +: "${INFINITO_WORKER_CPU:?INFINITO_WORKER_CPU must be set (provided by default.env via the env loader)}" + +check() { + printf '%s\0' "${shellcheck_files[@]}" | + xargs -0 -n 25 -P "${INFINITO_WORKER_CPU}" shellcheck -x +} + +if check; then + exit 0 +fi + diff_file="$(mktemp)" cleanup() { rm -f "${diff_file}" @@ -24,9 +42,10 @@ set +e shellcheck -f diff -x "${shellcheck_files[@]}" >"${diff_file}" 2>/dev/null set -e -if [[ -s "${diff_file}" ]]; then - printf 'Applying ShellCheck autofixes.\n' - git apply --whitespace=nowarn "${diff_file}" +if [[ ! -s "${diff_file}" ]]; then + exit 1 fi -shellcheck -x "${shellcheck_files[@]}" +printf 'Applying ShellCheck autofixes.\n' +git apply --whitespace=nowarn "${diff_file}" +check diff --git a/scripts/lint/sql.sh b/scripts/lint/sql.sh index c49aa57e01..ef8a709dc8 100755 --- a/scripts/lint/sql.sh +++ b/scripts/lint/sql.sh @@ -15,12 +15,19 @@ REPO_ROOT="$(cd -- "${SCRIPT_DIR}/../.." && pwd)" cd "${REPO_ROOT}" -mapfile -t sql_files < <( - find . -type f -name '*.sql' \ - -not -path './node_modules/*' \ - -not -path './.git/*' | - sed 's|^\./||' | sort -) +# shellcheck source=scripts/lint/diff/files.sh +source "${SCRIPT_DIR}/diff/files.sh" + +if lint_diff_active sql; then + mapfile -t sql_files < <(lint_diff_files '\.sql$') +else + mapfile -t sql_files < <( + find . -type f -name '*.sql' \ + -not -path './node_modules/*' \ + -not -path './.git/*' | + sed 's|^\./||' | sort + ) +fi if [[ "${#sql_files[@]}" -eq 0 ]]; then printf 'No SQL files found.\n' exit 0 @@ -31,12 +38,9 @@ if ! command -v sqlfluff >/dev/null 2>&1; then exit 0 fi -failed=0 -for file in "${sql_files[@]}"; do - if ! sqlfluff parse "${file}" >/dev/null; then - printf '%s: does not parse\n' "${file}" >&2 - failed=1 - fi -done +: "${INFINITO_WORKER_CPU:?INFINITO_WORKER_CPU must be set (provided by default.env via the env loader)}" -exit "${failed}" +# shellcheck disable=SC2016 +printf '%s\0' "${sql_files[@]}" | + xargs -0 -n 1 -P "${INFINITO_WORKER_CPU}" sh -c \ + 'sqlfluff parse "$1" >/dev/null || { printf "%s: does not parse\n" "$1" >&2; exit 1; }' _ diff --git a/scripts/lint/wrapper.sh b/scripts/lint/wrapper.sh index b29a8b0a18..27eee663dd 100755 --- a/scripts/lint/wrapper.sh +++ b/scripts/lint/wrapper.sh @@ -28,9 +28,13 @@ if [[ ! -f "${target_script}" ]]; then exit 2 fi +# shellcheck source=scripts/lint/diff/files.sh +source scripts/lint/diff/files.sh +diff_files="$(lint_diff_write "${lint_type}")" + case "${INFINITO_LINT_RUNNER}" in host) - exec bash --login "${target_script}" "$@" + LINT_DIFF_FILES="${diff_files}" exec bash --login "${target_script}" "$@" ;; docker) # like ruff / mbake / ansible-lint undiscoverable. BASH_ENV via -e @@ -51,6 +55,7 @@ docker) -e GITHUB_REPOSITORY="${GITHUB_REPOSITORY:-}" \ -e GITHUB_REPOSITORY_OWNER="${GITHUB_REPOSITORY_OWNER:-}" \ -e GITHUB_SHA="${GITHUB_SHA:-}" \ + -e LINT_DIFF_FILES="${diff_files}" \ --workdir "${INFINITO_SRC_DIR}" \ infinito \ bash "${INFINITO_SRC_DIR}/${target_script}" "$@" diff --git a/scripts/tests/deploy/act/copy_worktree_to_node.sh b/scripts/tests/deploy/act/copy_worktree_to_node.sh index a81a00db0f..e72b490174 100755 --- a/scripts/tests/deploy/act/copy_worktree_to_node.sh +++ b/scripts/tests/deploy/act/copy_worktree_to_node.sh @@ -14,6 +14,9 @@ cd "${repo_root}" # shellcheck source=scripts/meta/env/load.sh source "${repo_root}/scripts/meta/env/load.sh" -git ls-files -z -m -o --exclude-standard | +{ + git ls-files -z -m -o --exclude-standard + git ls-files -z -o -i --exclude-standard -- 'roles/web-app-cst-*' +} | tar --null -cf - -T - | docker exec -i "${node}" tar -C "${INFINITO_NODE_SRC_DIR:?}" -xpf - diff --git a/scripts/tests/deploy/act/workflow.sh b/scripts/tests/deploy/act/workflow.sh index 39952f46bf..3f6f9f8a61 100755 --- a/scripts/tests/deploy/act/workflow.sh +++ b/scripts/tests/deploy/act/workflow.sh @@ -52,7 +52,8 @@ fi cmd=(act "${ACT_EVENT}" -W "${_act_workflow}") cmd+=(-P "ubuntu-latest=${ACT_PLATFORM_IMAGE}") cmd+=(-P "ubuntu-24.04-arm=${ACT_PLATFORM_IMAGE}") -_act_workflows_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)/.github/workflows" +_act_repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../../.." && pwd)" +_act_workflows_dir="${_act_repo_root}/.github/workflows" while read -r _act_label; do cmd+=(-P "${_act_label}=${ACT_PLATFORM_IMAGE}") done < <(grep -rhE 'runs-on:' "${_act_workflows_dir}" | grep -oE 'ubuntu-[0-9]+\.[0-9]+' | sort -u) @@ -97,6 +98,10 @@ if [[ "${ACT_RM}" == "true" ]]; then fi cmd+=(--cache-server-addr 127.0.0.1) cmd+=(--artifact-server-addr 127.0.0.1) +if [[ "${ACT_BIND}" != "true" ]] && compgen -G "${_act_repo_root}/roles/web-app-cst-*" >/dev/null; then + echo "act: binding the checkout to carry the pulled custom roles (roles/web-app-cst-*)" + ACT_BIND=true +fi if [[ "${ACT_BIND}" == "true" ]]; then cmd+=(--bind) fi diff --git a/scripts/tests/deploy/local/deploy/container/initialize/all.sh b/scripts/tests/deploy/local/deploy/container/initialize/all.sh index e16dd4ca83..77172e72df 100755 --- a/scripts/tests/deploy/local/deploy/container/initialize/all.sh +++ b/scripts/tests/deploy/local/deploy/container/initialize/all.sh @@ -56,6 +56,7 @@ echo ">>> Deploying against ${INFINITO_INVENTORY_FILE}" infinito administration deploy dedicated "${INFINITO_INVENTORY_FILE}" \ --skip-backup \ + --skip-pull \ --debug \ --log "${INFINITO_SRC_DIR}/logs" \ -l "${INFINITO_LIMIT_HOST}" \ diff --git a/scripts/tests/deploy/local/deploy/container/update/all.sh b/scripts/tests/deploy/local/deploy/container/update/all.sh index cc680128ae..6ea35f8fcc 100755 --- a/scripts/tests/deploy/local/deploy/container/update/all.sh +++ b/scripts/tests/deploy/local/deploy/container/update/all.sh @@ -27,6 +27,7 @@ echo ">>> entry.sh bootstrap" cmd=(infinito administration deploy dedicated "${INFINITO_INVENTORY_FILE}" --skip-backup --skip-cleanup + --skip-pull -l "${INFINITO_LIMIT_HOST}" --diff -vv diff --git a/scripts/tests/deploy/local/deploy/container/update/selection.sh b/scripts/tests/deploy/local/deploy/container/update/selection.sh index b5f82f0ad2..70591978de 100755 --- a/scripts/tests/deploy/local/deploy/container/update/selection.sh +++ b/scripts/tests/deploy/local/deploy/container/update/selection.sh @@ -53,6 +53,7 @@ read -ra app_ids <<<"${apps}" cmd=(infinito administration deploy dedicated "${INFINITO_INVENTORY_FILE}" --skip-backup --skip-cleanup + --skip-pull --id "${app_ids[@]}" -l localhost --diff diff --git a/tasks/stages/01_constructor.yml b/tasks/stages/01_constructor.yml index cfc82cfe56..2a02f42970 100644 --- a/tasks/stages/01_constructor.yml +++ b/tasks/stages/01_constructor.yml @@ -70,6 +70,20 @@ applications_carrier: {} when: IS_SWARM_MODE +- name: "📦 Install the packages of every role this host may run, in one run" + package_install: + id: "{{ _package_batch_ids }}" + vars: + _package_batch_inventory: "{{ PACKAGES | default([]) }}" + _package_batch_ids: >- + {{ + ( + lookup('package_batch', group_names) + + ([_package_batch_inventory] if _package_batch_inventory is string else _package_batch_inventory) + ) | unique + }} + when: _package_batch_ids | length > 0 + - name: "🥾 Bootstrap svc-swarm-node" ansible.builtin.include_role: name: svc-swarm-node @@ -125,8 +139,3 @@ loop_control: loop_var: role_group label: "{{ role_group }}" - -- name: 📦 Install inventory-defined packages - package_install: - id: "{{ PACKAGES }}" - when: PACKAGES | default([]) | length > 0 diff --git a/tests/integration/ansible/lookups/test_package_batch.py b/tests/integration/ansible/lookups/test_package_batch.py new file mode 100644 index 0000000000..b870584156 --- /dev/null +++ b/tests/integration/ansible/lookups/test_package_batch.py @@ -0,0 +1,96 @@ +"""Integration test: package_batch against the real merged config and role tree. + +The host deploys the application set of a local Nextcloud deploy. The batch +must hold the ids of the supporting roles that deploy ran through +``include_role`` (none of them is an application of the host), and nothing a +role still installs itself or only a workstation runs. +""" + +from __future__ import annotations + +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from plugins.lookup.applications import _reset_cache_for_tests +from plugins.lookup.package_batch import LookupModule as PackageBatchLookup +from utils.packages.registry import build_registry + +from . import PROJECT_ROOT + +APPLICATIONS = [ + "svc-bkp-secrets-2-local", + "svc-bkp-volume-2-local", + "svc-db-mariadb", + "svc-db-openldap", + "svc-db-postgres", + "svc-db-redis", + "web-app-keycloak", + "web-app-nextcloud", + "web-app-seaweedfs", + "web-svc-cdn", + "web-svc-collabora", + "web-svc-coturn", + "web-svc-logout", +] +SUPPORTING_ROLE_IDS = { + "sys-daemon": "systemd-tools", + "sys-openssl": "openssl", + "sys-svc-compose": "python-yaml", + "sys-svc-mail-msmtp": "msmtp", + "sys-svc-nss": "nss-myhostname", + "svc-db-openldap": "openldap-dev", +} +WORKSTATION_ID = "firefox" + + +def _variables(group_names: list[str]) -> dict: + return { + "applications": {}, + "users": {}, + "DOMAIN_PRIMARY": "infinito.test", + "SYSTEM_EMAIL_DOMAIN": "infinito.test", + "DIR_COMPOSITIONS": "/opt/compose/", + "group_names": list(group_names), + } + + +class TestPackageBatchIntegration(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + _reset_cache_for_tests() + lookup = PackageBatchLookup() + lookup._loader = DataLoader() + lookup._templar = Templar(loader=lookup._loader) + cls.batch = lookup.run([APPLICATIONS], variables=_variables(APPLICATIONS))[0] + cls.registry = build_registry(PROJECT_ROOT) + + @classmethod + def tearDownClass(cls) -> None: + _reset_cache_for_tests() + + def test_supporting_roles_are_covered(self) -> None: + missing = { + role: package_id + for role, package_id in SUPPORTING_ROLE_IDS.items() + if package_id not in self.batch + } + self.assertEqual( + missing, + {}, + "The deploy runs these roles through include_role only; the batch " + "dropped their ids, so nothing installs them any more.", + ) + + def test_the_batch_holds_no_unbatched_id(self) -> None: + self.assertEqual( + [pid for pid in self.batch if not self.registry[pid].batch], [] + ) + + def test_a_server_gets_no_workstation_package(self) -> None: + self.assertNotIn(WORKSTATION_ID, self.batch) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/infrastructure/compose/test_no_raw_docker.py b/tests/integration/infrastructure/compose/test_no_raw_docker.py index 31ffd7eb75..8f16a933ca 100644 --- a/tests/integration/infrastructure/compose/test_no_raw_docker.py +++ b/tests/integration/infrastructure/compose/test_no_raw_docker.py @@ -1,14 +1,13 @@ from __future__ import annotations import re -import subprocess import unittest from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING from utils.annotations.suppress import is_suppressed_at, is_suppressed_in_head -from utils.cache.files import iter_project_files, read_text +from utils.cache.files import iter_project_files, read_text, repository_files from . import PROJECT_ROOT @@ -163,12 +162,7 @@ RULES: tuple[tuple[str, re.Pattern, str], ...] = ( def git_ls_files(root: Path) -> list[Path]: try: - out = subprocess.check_output( - ["git", "-C", str(root), "ls-files", "-z"], - stderr=subprocess.STDOUT, - ) - rels = [p for p in out.decode("utf-8", errors="replace").split("\0") if p] - return [root / p for p in rels] + return [root / p for p in repository_files(untracked=True)] except Exception: results: list[Path] = [] for path_str in iter_project_files(): diff --git a/tests/integration/roles/custom/README.md b/tests/integration/roles/custom/README.md new file mode 100644 index 0000000000..c785435a5a --- /dev/null +++ b/tests/integration/roles/custom/README.md @@ -0,0 +1,5 @@ +# Custom Role Tests 🧩 + +Integration tests that pull a custom role (`web-app-cst-*`) into a throwaway copy of the core checkout with its real `.gitignore` and check that Git never sees it. + +For framework and `make test-integration` usage see [integration.md](../../../../docs/contributing/actions/testing/integration.md). diff --git a/tests/integration/roles/custom/__init__.py b/tests/integration/roles/custom/__init__.py new file mode 100644 index 0000000000..039b52c789 --- /dev/null +++ b/tests/integration/roles/custom/__init__.py @@ -0,0 +1,3 @@ +from tests.integration.roles import PROJECT_ROOT + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/integration/roles/custom/test_git_status.py b/tests/integration/roles/custom/test_git_status.py new file mode 100644 index 0000000000..c713840a00 --- /dev/null +++ b/tests/integration/roles/custom/test_git_status.py @@ -0,0 +1,108 @@ +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +from cli.administration.roles.placement import clean, pull +from utils.cache.files import read_text +from utils.roles.mapping import ROLE_FILE_META_MAIN, ROLE_FILE_VARS_MAIN + +from . import PROJECT_ROOT + +ROLE = "web-app-cst-demo" +_ENV = { + **{key: value for key, value in os.environ.items() if not key.startswith("GIT_")}, + "GIT_CONFIG_GLOBAL": os.devnull, +} + + +def _git(repository: Path, *arguments: str) -> str: + return subprocess.run( + [ + "git", + "-c", + "user.name=ci", + "-c", + "user.email=ci@example.invalid", + "-c", + "commit.gpgsign=false", + *arguments, + ], + cwd=repository, + env=_ENV, + check=True, + capture_output=True, + text=True, + ).stdout + + +def _write(path: Path, text: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +@unittest.skipUnless(shutil.which("git"), "git is required for this test") +class TestPulledRoleStaysOutOfGit(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + base = Path(tmp.name) + self.checkout = base / "core" + self.roles = self.checkout / "roles" + self.work = self.checkout / "build" / "custom-roles" + _write( + self.checkout / ".gitignore", read_text(str(PROJECT_ROOT / ".gitignore")) + ) + _write( + self.roles / "web-app-nextcloud" / ROLE_FILE_META_MAIN, "galaxy_info: {}\n" + ) + _git(self.checkout, "init", "--quiet") + _git(self.checkout, "add", "--all") + _git(self.checkout, "commit", "--quiet", "--no-verify", "--message", "core") + source = base / "landingpage" / "ansible" / "roles" / ROLE + _write(source / ROLE_FILE_META_MAIN, "galaxy_info: {}\n") + _write(source / ROLE_FILE_VARS_MAIN, f"application_id: {ROLE}\n") + applications = { + ROLE: { + "custom": True, + "source": { + "url": str(base / "landingpage"), + "path": f"ansible/roles/{ROLE}", + }, + } + } + _write( + base / "inventory" / "host_vars" / "localhost.yml", + json.dumps({"applications": applications}), + ) + _write( + base / "inventory" / "devices.yml", + json.dumps({"all": {"children": {ROLE: {"hosts": {"localhost": {}}}}}}), + ) + self.inventory = base / "inventory" / "devices.yml" + + def test_a_pulled_role_leaves_git_status_empty(self) -> None: + pull(self.inventory, self.roles, self.work) + self.assertTrue((self.roles / ROLE / ROLE_FILE_VARS_MAIN).is_file()) + self.assertEqual("", _git(self.checkout, "status", "--porcelain")) + self.assertIn( + f"roles/{ROLE}/", + _git(self.checkout, "status", "--porcelain", "--ignored"), + ) + + def test_clean_leaves_only_the_tracked_roles(self) -> None: + pull(self.inventory, self.roles, self.work) + clean(self.roles, self.work) + self.assertEqual(["web-app-nextcloud"], [e.name for e in self.roles.iterdir()]) + self.assertEqual( + "", _git(self.checkout, "status", "--porcelain", "--ignored", "roles") + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/roles/naming/test_custom_prefix_reserved.py b/tests/integration/roles/naming/test_custom_prefix_reserved.py new file mode 100644 index 0000000000..6277fc0ee5 --- /dev/null +++ b/tests/integration/roles/naming/test_custom_prefix_reserved.py @@ -0,0 +1,38 @@ +"""The custom-role prefix is reserved for roles an inventory pulls. + +``roles/web-app-cst-*`` is where the pull places the custom roles an +inventory declares, and Git ignores that path. A role committed to core +under that prefix would be replaced or deleted by the next pull, so no +tracked file may live there. +""" + +from __future__ import annotations + +import subprocess +import unittest + +from utils.roles.custom import PREFIX, ROLES_GLOB + +from . import PROJECT_ROOT + + +class TestCustomPrefixReserved(unittest.TestCase): + def test_no_in_tree_role_uses_the_custom_prefix(self): + tracked = subprocess.run( + ["git", "-c", "safe.directory=*", "ls-files", "-z", "--", ROLES_GLOB], + cwd=PROJECT_ROOT, + capture_output=True, + text=True, + check=True, + ).stdout + roles = sorted({path.split("/")[1] for path in tracked.split("\0") if path}) + self.assertEqual( + [], + roles, + f"In-tree roles must not start with {PREFIX}, the prefix of the custom " + f"roles an inventory pulls into roles/; rename: {', '.join(roles)}", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/jinja/test_compose_argv_no_secret.py b/tests/lint/ansible/jinja/test_compose_argv_no_secret.py new file mode 100644 index 0000000000..ba195ae8c9 --- /dev/null +++ b/tests/lint/ansible/jinja/test_compose_argv_no_secret.py @@ -0,0 +1,97 @@ +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 = "compose-argv-secret" + +_SCAN_PREFIX = "roles/" +_ARGV_KEY = re.compile( + r"^(?P\s*)(?:-\s+)?(?:command|entrypoint|healthcheck|test)\s*:" +) +_EXPRESSION = re.compile(r"\{\{(.*?)\}\}") +_CREDENTIAL = re.compile( + r"(?i)(?:password|passwd|pwd|secret|token|api_?key|private_?key|credential)" +) +_DESCRIBES_CREDENTIAL = re.compile( + r"(?i)(?:password|passwd|pwd|secret|token|api_?key|private_?key|credential)\w*" + r"_(?:file|path|dir|id|name|user|username|hash|length)\b" +) + + +def _indent(line: str) -> int: + return len(line) - len(line.lstrip()) + + +def _argv_secret_lines(lines: list[str]) -> list[int]: + """Return the 1-based lines that render a credential into an argv block. + + Args: + lines: the template's lines. + + Returns: + every line inside a ``command``, ``entrypoint``, ``healthcheck`` or + ``test`` value whose Jinja expression names a credential. + """ + found: list[int] = [] + block_indent: int | None = None + for index, line in enumerate(lines): + stripped = line.strip() + key = _ARGV_KEY.match(line) + if key: + block_indent = len(key.group("indent")) + elif ( + block_indent is not None + and stripped + and not stripped.startswith("{%") + and _indent(line) <= block_indent + ): + block_indent = None + if block_indent is None: + continue + for expression in _EXPRESSION.findall(line): + if _CREDENTIAL.search(expression) and not _DESCRIBES_CREDENTIAL.search( + expression + ): + found.append(index + 1) + break + return found + + +class TestComposeArgvNoSecret(unittest.TestCase): + def test_compose_argv_renders_no_credential(self) -> None: + findings: list[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() + if not rel.startswith(_SCAN_PREFIX) or "/templates/" not in rel: + continue + lines = content.splitlines() + findings.extend( + f"- {rel}:{line_no}: {lines[line_no - 1].strip()}" + for line_no in _argv_secret_lines(lines) + if not is_suppressed_at(lines, line_no, _RULE, mode="same-or-above") + ) + + self.assertFalse( + findings, + "A credential is rendered into a container's command, entrypoint or " + "healthcheck, where `docker inspect` and the host's `ps` show it. Put " + "it into the container environment (env file or `environment:`) and " + "read it there at runtime, e.g. `$$REDIS_PASSWORD` in a CMD-SHELL " + "or a tool's own variable such as REDISCLI_AUTH. Mark a deliberate " + f"exception with `# nocheck: {_RULE}`.\n\nOffenders:\n" + + "\n".join(findings), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/jinja/test_task_argv_no_secret.py b/tests/lint/ansible/jinja/test_task_argv_no_secret.py new file mode 100644 index 0000000000..9dbc179f4b --- /dev/null +++ b/tests/lint/ansible/jinja/test_task_argv_no_secret.py @@ -0,0 +1,165 @@ +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 +from .test_compose_argv_no_secret import _CREDENTIAL, _EXPRESSION, _indent + +_RULE = "task-argv-secret" + +_MODULE_KEY = re.compile( + r"^(?P\s*(?:-\s+)?)(?:ansible\.builtin\.)?(?:script|command|shell)\s*:" +) +_STDIN_KEY = re.compile(r"^(?P\s*)stdin\s*:") +_EXEC = re.compile( + r"\b(?:container|docker)\b[\s\S]{0,80}?\b(?:exec|run)\b|_EXEC_[A-Z]|_EXEC\b" +) +_FILE_REFERENCE = re.compile( + r"^\s*lookup\(\s*['\"](?:file|path_absolute|template)['\"]" +) +_CREDENTIAL_SUFFIX = re.compile(r"(?i)_(?:pw|pass)\b") +_DESCRIBES_CREDENTIAL = re.compile( + r"(?i)(?:password|passwd|pwd|secret|token|api_?key|private_?key|credential)\w*" + r"_(?:file|path|dir|id|ids|name|names|user|username|owner|email|hash|length" + r"|days|description|url|uri|host|port|type|enabled)\b" +) + + +def _module_blocks(lines: list[str]) -> list[list[int]]: + """Group a task file's lines into the bodies of command-running modules. + + Args: + lines: the task file's lines. + + Returns: + one list of 0-based line indexes per ``script``, ``command`` or + ``shell`` module, its ``stdin:`` value left out. + """ + blocks: list[list[int]] = [] + index = 0 + while index < len(lines): + key = _MODULE_KEY.match(lines[index]) + if not key: + index += 1 + continue + indent = len(key.group("indent")) + block = [index] + stdin_indent: int | None = None + index += 1 + while index < len(lines): + line = lines[index] + if line.strip() and _indent(line) <= indent: + break + if ( + stdin_indent is not None + and line.strip() + and _indent(line) <= stdin_indent + ): + stdin_indent = None + stdin = _STDIN_KEY.match(line) + if stdin: + stdin_indent = len(stdin.group("indent")) + elif stdin_indent is None: + block.append(index) + index += 1 + blocks.append(block) + return blocks + + +def _argv_secret_lines(lines: list[str]) -> list[int]: + """Return the 1-based lines that render a credential into a task's argv. + + Args: + lines: the task file's lines. + + Returns: + every line of a ``script``, ``command`` or ``shell`` module whose Jinja + expression names a credential; modules that run ``container exec`` or + ``docker run`` are left to the exec-argv rules. + """ + found: list[int] = [] + for block in _module_blocks(lines): + if _EXEC.search("\n".join(lines[i] for i in block)): + continue + for i in block: + for expression in _EXPRESSION.findall(lines[i]): + if _FILE_REFERENCE.search(expression): + continue + names_credential = _CREDENTIAL.search( + expression + ) or _CREDENTIAL_SUFFIX.search(expression) + if names_credential and not _DESCRIBES_CREDENTIAL.search(expression): + found.append(i + 1) + break + return found + + +class TestArgvSecretLines(unittest.TestCase): + def test_a_positional_script_argument_is_flagged(self) -> None: + lines = [ + "- ansible.builtin.script: >-", + " set_pw.sh {{ ADDRESS | quote }}", + " {{ POSTGRES_PASSWORD | quote }}", + ] + self.assertEqual(_argv_secret_lines(lines), [3]) + + def test_a_pw_or_pass_suffix_is_flagged(self) -> None: + lines = [ + " command: >", + " ldapsm -W '{{ OPENLDAP_BIND_PW }}'", + " --admin {{ KEYCLOAK_ADMIN_PASS }}", + ] + self.assertEqual(_argv_secret_lines(lines), [2, 3]) + + def test_stdin_environment_and_exec_lines_pass(self) -> None: + lines = [ + "- ansible.builtin.command:", + " argv: [cli, login]", + " stdin: '{{ ADMIN_PASSWORD }}'", + " environment:", + " TOKEN: '{{ API_TOKEN }}'", + "- ansible.builtin.shell: >-", + " container exec app cli --pass {{ ADMIN_PASSWORD }}", + "- ansible.builtin.command: cli --lifetime {{ MCP_TOKEN_LIFETIME_DAYS }}", + ] + self.assertEqual(_argv_secret_lines(lines), []) + + +class TestTaskArgvNoSecret(unittest.TestCase): + def test_task_argv_renders_no_credential(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 rel.startswith("roles/") or not ( + "/tasks/" in rel or "/handlers/" in rel + ): + continue + lines = content.splitlines() + findings.extend( + f"- {rel}:{line_no}: {lines[line_no - 1].strip()}" + for line_no in _argv_secret_lines(lines) + if not is_suppressed_at(lines, line_no, _RULE, mode="same-or-above") + ) + + self.assertFalse( + findings, + "A credential is rendered into the command line of a script, command " + "or shell task, where the host's `ps` shows it to every local account " + "while the call runs and `no_log` cannot mask it. Pass it on the " + "module's `stdin:` and read it there; a task-level `environment:` " + "does not help, Ansible prefixes it to its own `/bin/sh -c` command " + "line. Mark a deliberate exception with " + f"`# nocheck: {_RULE}`.\n\nOffenders:\n" + "\n".join(findings), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/jinja/test_url_base_no_double_slash.py b/tests/lint/ansible/jinja/test_url_base_no_double_slash.py new file mode 100644 index 0000000000..176d85871f --- /dev/null +++ b/tests/lint/ansible/jinja/test_url_base_no_double_slash.py @@ -0,0 +1,225 @@ +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 = "url-base-double-slash" +_ADDON_RULE = "url-base-addon-value" +_STRIP_RULE = "url-base-strip" + +_SCAN_PREFIXES = ("roles/", "group_vars/") +_ADDON_DIRS = ("/meta/addons/", "/tasks/addons/") +_INSTANCE_KEYS = ("oauth_instance_url", "openproject_instance_url", "url") +_CONFIGKEY = re.compile(r"""configkey:\s*['"]?(?P[A-Za-z0-9_.]+)""") +_URL_BASE = r"""lookup\(\s*['"]tls['"]\s*,[^)]*['"]url\.base['"]\s*\)""" +_DIRECT = re.compile(_URL_BASE + r"""\s*(?:\}\}/|~\s*['"]/)""") +_STRIP = ( + r"""(?:\s*\))*\s*(?:\|\s*(?:regex_replace\(\s*['"]/\+?\$['"]|trim\(\s*['"]/['"])""" + r"""|\.rstrip\(\s*['"]/['"]\s*\))""" +) +_DIRECT_STRIP = re.compile(_URL_BASE + _STRIP) +_BARE_VAR = re.compile( + r"""^\s*(?:-\s+)?(?P[A-Za-z_][A-Za-z0-9_]*):\s*['"]?\{\{\s*""" + + _URL_BASE + + r"""(?:\s*\|\s*trim)?\s*\}\}['"]?\s*$""" +) +_BARE_SET = re.compile( + r"""\{%-?\s*set\s+(?P[A-Za-z_][A-Za-z0-9_]*)\s*=\s*""" + + _URL_BASE + + r"""(?:\s*\|\s*trim)?\s*-?%\}""" +) + + +def _bare_url_base_names(files: list[tuple[str, list[str]]]) -> set[str]: + """Return every variable name defined as a bare url.base lookup. + + Args: + files: (relative path, lines) of every scanned file. + + Returns: + names whose value is ``lookup('tls', ..., 'url.base')`` with at most a + ``trim``, the value that always ends in "/". + """ + names: set[str] = set() + for _, lines in files: + for line in lines: + for pattern in (_BARE_VAR, _BARE_SET): + match = pattern.search(line) + if match: + names.add(match.group("name")) + return names + + +def _double_slash_lines(lines: list[str], names: set[str]) -> list[int]: + """Return the 1-based lines that append "/" to a url.base value. + + Args: + lines: the file's lines. + names: variables that hold a bare url.base. + + Returns: + lines where url.base, directly or through one of ``names``, is followed + by "}}/" or "~ '/". + """ + via_name = ( + re.compile( + r"""\{\{\s*(?:""" + + "|".join(sorted(map(re.escape, names))) + + r""")\s*(?:\}\}/|~\s*['"]/)""" + ) + if names + else None + ) + return [ + index + 1 + for index, line in enumerate(lines) + if _DIRECT.search(line) or (via_name and via_name.search(line)) + ] + + +def _strip_lines(lines: list[str], names: set[str]) -> list[int]: + """Return the 1-based lines that strip the trailing "/" from url.base. + + Args: + lines: the file's lines. + names: variables that hold a bare url.base. + + Returns: + lines where url.base, directly or through one of ``names``, goes through + ``regex_replace('/$', '')``, ``regex_replace('/+$', '')``, ``trim('/')`` + or ``.rstrip('/')``. + """ + via_name = ( + re.compile( + r"""\b(?:""" + "|".join(sorted(map(re.escape, names))) + r""")\b""" + _STRIP + ) + if names + else None + ) + return [ + index + 1 + for index, line in enumerate(lines) + if _DIRECT_STRIP.search(line) or (via_name and via_name.search(line)) + ] + + +def _addon_bare_value_lines(lines: list[str], names: set[str]) -> list[int]: + """Return the 1-based lines that hand an integration app a bare url.base. + + Args: + lines: the addon file's lines. + names: variables that hold a bare url.base. + + Returns: + lines whose whole value is url.base or one of ``names`` and that are a + ``configvalue`` of one of ``_INSTANCE_KEYS``, a ``url`` key, or a + ``*_base_url`` fact. + """ + pattern = re.compile( + r"""^\s*(?:-\s+)?(?P[A-Za-z_][A-Za-z0-9_]*):\s*['"]?\{\{\s*(?:""" + + _URL_BASE + + (("|" + "|".join(sorted(map(re.escape, names)))) if names else "") + + r""")(?:\s*\|\s*trim)?\s*\}\}['"]?\s*$""" + ) + found: list[int] = [] + configkey = "" + for index, line in enumerate(lines): + key = _CONFIGKEY.search(line) + if key: + configkey = key.group("name") + match = pattern.search(line) + if not match: + continue + name = match.group("key") + if ( + (name == "configvalue" and configkey in _INSTANCE_KEYS) + or name == "url" + or name.endswith("_base_url") + ): + found.append(index + 1) + return found + + +def _scanned_files() -> list[tuple[str, list[str]]]: + files: list[tuple[str, list[str]]] = [] + for path_str, content in iter_project_files_with_content( + extensions=(".yml", ".yaml", ".j2"), + exclude_tests=True, + ): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + if rel.startswith(_SCAN_PREFIXES): + files.append((rel, content.splitlines())) + return files + + +class TestUrlBaseNoDoubleSlash(unittest.TestCase): + def test_addon_settings_hold_partner_urls_without_trailing_slash(self) -> None: + files = _scanned_files() + names = _bare_url_base_names(files) + findings = [ + f"- {rel}:{line_no}: {lines[line_no - 1].strip()}" + for rel, lines in files + if any(part in rel for part in _ADDON_DIRS) + for line_no in _addon_bare_value_lines(lines, names) + if not is_suppressed_at(lines, line_no, _ADDON_RULE, mode="same-or-above") + ] + + self.assertFalse( + findings, + "An addon setting holds lookup('tls', ..., 'url.base') as is, with " + "its trailing '/'. Integration apps append their own paths to it " + "(integration_openproject builds '//oauth/token'), so store " + "lookup('tls', ..., 'url.origin') instead. Mark a setting that needs " + f"the slash with `# nocheck: {_ADDON_RULE}`.\n\nOffenders:\n" + + "\n".join(findings), + ) + + def test_no_path_is_appended_to_url_base_with_a_leading_slash(self) -> None: + files = _scanned_files() + names = _bare_url_base_names(files) + findings = [ + f"- {rel}:{line_no}: {lines[line_no - 1].strip()}" + for rel, lines in files + for line_no in _double_slash_lines(lines, names) + if not is_suppressed_at(lines, line_no, _RULE, mode="same-or-above") + ] + + self.assertFalse( + findings, + "lookup('tls', ..., 'url.base') ends in '/', so appending '/path' " + "yields 'https://host//path', which exact-match OAuth redirect " + "URIs and token endpoints reject. Append the path to " + "lookup('tls', ..., 'url.origin'), join with `[base, 'path'] | " + "url_join`, or append the path without its leading slash. Mark a " + f"deliberate exception with `# nocheck: {_RULE}`.\n\nOffenders:\n" + + "\n".join(findings), + ) + + def test_url_base_is_never_stripped_of_its_trailing_slash(self) -> None: + files = _scanned_files() + names = _bare_url_base_names(files) + findings = [ + f"- {rel}:{line_no}: {lines[line_no - 1].strip()}" + for rel, lines in files + for line_no in _strip_lines(lines, names) + if not is_suppressed_at(lines, line_no, _STRIP_RULE, mode="same-or-above") + ] + + self.assertFalse( + findings, + "url.base is stripped of its trailing '/'. The tls lookup already " + "returns that value as lookup('tls', ..., 'url.origin'), so read it " + "there instead of rebuilding it per call site. Mark a deliberate " + f"exception with `# nocheck: {_STRIP_RULE}`.\n\nOffenders:\n" + + "\n".join(findings), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/modules/README.md b/tests/lint/ansible/modules/README.md index 9fa7a8e392..951908eaa5 100644 --- a/tests/lint/ansible/modules/README.md +++ b/tests/lint/ansible/modules/README.md @@ -10,6 +10,7 @@ Tests in this directory MUST only cover Ansible module / task usage rules. - `test_no_legacy_uri_module_usage.py` forbids the unqualified `uri:` module name; tasks MUST use `ansible.builtin.uri`. - `test_no_literal_no_log.py` forbids literal `no_log: true` / `no_log: false`; every gate MUST flow through the `MASK_CREDENTIALS_IN_LOGS` variable. - `test_no_redundant_default_on_module_io.py` forbids `| default(...)` on a task's own `register:` output or input arguments inside its own conditionals, where the value is provably set. +- `test_package_batch.py` requires that a role's own `package_install` tasks install only ids flagged `batch: false` in `meta/packages.yml`, that every id of a role the constructor runs before the deploy-start batch carries that flag, and that a `shared: true` reference names a root id. - `test_run_once_tags.py` requires that every `set_fact` marked `run_once: true` carries the canonical run-once tags so re-runs and `--tags` filters keep the fact populated. Shell-pipeline rules and SQL formatting rules live in sibling directories; see [`../shell/`](../shell/) and [`../sql/`](../sql/). diff --git a/tests/lint/ansible/modules/test_no_raw_db_query_module_usage.py b/tests/lint/ansible/modules/test_no_raw_db_query_module_usage.py index 917c8e9856..0c2cf35e10 100644 --- a/tests/lint/ansible/modules/test_no_raw_db_query_module_usage.py +++ b/tests/lint/ansible/modules/test_no_raw_db_query_module_usage.py @@ -1,5 +1,5 @@ -"""Forbid `community.postgresql.postgresql_query` / `community.mysql.mysql_query` -in role tasks; redirect callers to the project's `database_query` module +"""Forbid `community.postgresql.postgresql_query` / `ansible.mysql.mysql_query` / +`ansible.mariadb.mariadb_query` in role tasks; redirect callers to the project's `database_query` module (``library/database_query.py``). Rationale @@ -36,8 +36,10 @@ _RAW_DB_QUERY_MODULE_PATTERN = re.compile( r"^\s*(" r"community\.postgresql\.postgresql_query" r"|postgresql_query" - r"|community\.mysql\.mysql_query" + r"|(?:community|ansible)\.mysql\.mysql_query" r"|mysql_query" + r"|ansible\.mariadb\.mariadb_query" + r"|mariadb_query" r")\s*:\s*(?:#.*)?$" ) diff --git a/tests/lint/ansible/modules/test_package_batch.py b/tests/lint/ansible/modules/test_package_batch.py new file mode 100644 index 0000000000..4180dd6263 --- /dev/null +++ b/tests/lint/ansible/modules/test_package_batch.py @@ -0,0 +1,224 @@ +"""Lint: a role installs only the package ids the deploy-start batch leaves out. + +The constructor installs every id of every role a deploy may run in one +``package_install`` run (``lookup('package_batch')``). An id stays out of it +only when its ``meta/packages.yml`` entry says ``batch: false``, and then the +role's own task installs it. Four rules hold that split together: + +* an unconditional ``package_install`` task installs only ``batch: false`` + ids; any other id is covered by the batch, so the task goes; +* a ``package_install`` task under a ``when:``, on the task or an enclosing + block, installs only ``batch: false`` ids, so the batch does not install + them on hosts where the condition is false; +* every id of a role the constructor runs ahead of the batch is + ``batch: false``, because the batch would install it too late; +* a role file references only ids the shared root file declares; +* every ``package_install`` task of a role carries + ``# nocheck: package-install `` on its module line or the line + above, naming why it cannot ride the batch. The batch cannot see the + conditions an include or a role invocation puts around a task file, so an + unmarked install would slip past the first two rules. + +A ``run_once_`` guard is no condition here: it only keeps a role from +running twice in one deploy. +""" + +from __future__ import annotations + +import re +import unittest +from pathlib import Path +from typing import Any + +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 utils.packages.registry import build_registry, load_references +from utils.roles.invocations import ( + CONSTRUCTOR_STAGE, + NESTED_KEYS, + STAGES_DIR, + expand_roles, + iter_tasks, + role_names, + task_invocations, +) + +from . import PROJECT_ROOT + +_RUN_ONCE_GUARD_RE = re.compile( + r"^(?:run_once_\w+\s+is\s+not\s+defined" + r"|not\s+\(\s*run_once_\w+\s*\|\s*default\(false\)\s*\|\s*bool\s*\))$" +) +_BATCH_LOOKUP = "lookup('package_batch'" +_RULE = "package-install" +_MODULE_LINE_RE = re.compile(r"^\s*(?:-\s+)?package_install:") + + +def _conditions(task: dict[str, Any]) -> list[str]: + when = task.get("when") + if when is None: + return [] + return [ + str(condition).strip() + for condition in (when if isinstance(when, list) else [when]) + if not _RUN_ONCE_GUARD_RE.match(str(condition).strip()) + ] + + +def _package_tasks( + node: Any, inherited: list[str] +) -> list[tuple[dict[str, Any], list[str]]]: + found: list[tuple[dict[str, Any], list[str]]] = [] + if not isinstance(node, list): + return found + for task in node: + if not isinstance(task, dict): + continue + conditions = inherited + _conditions(task) + if isinstance(task.get("package_install"), dict): + found.append((task, conditions)) + for key in NESTED_KEYS: + found.extend(_package_tasks(task.get(key), conditions)) + return found + + +def _ids(task: dict[str, Any]) -> list[str]: + raw = task["package_install"].get("id") + ids = raw if isinstance(raw, list) else [raw] + return [str(item).strip() for item in ids if isinstance(item, str)] + + +def _role_task_files() -> list[Path]: + roles = PROJECT_ROOT / "roles" + return [ + Path(path) + for path in iter_project_files(extensions=(".yml",)) + if Path(path).is_relative_to(roles) + and Path(path).relative_to(roles).parts[1:2] in (("tasks",), ("handlers",)) + ] + + +def _constructor_tasks_ahead_of_the_batch() -> list[dict[str, Any]] | None: + tasks = load_yaml_any(str(PROJECT_ROOT / STAGES_DIR / CONSTRUCTOR_STAGE)) + for index, task in enumerate(tasks): + if "package_install" in task and _BATCH_LOOKUP in str(task.get("vars")): + return tasks[:index] + return None + + +def _roles_ahead_of_the_batch(tasks: list[dict[str, Any]]) -> set[str]: + known = role_names(str(PROJECT_ROOT / "roles")) + seeds: set[str] = set() + for task in iter_tasks(tasks): + seeds |= task_invocations(task, known)[0] + return expand_roles({}, seeds, project_root=PROJECT_ROOT) + + +class TestPackageBatch(unittest.TestCase): + def setUp(self) -> None: + self.registry = build_registry(PROJECT_ROOT) + + def _offenders(self, *, conditional: bool) -> list[str]: + offenders: list[str] = [] + for path in _role_task_files(): + doc = load_yaml_any(str(path), default_if_missing=None) + for task, conditions in _package_tasks(doc, []): + if bool(conditions) != conditional: + continue + batched = [ + package_id + for package_id in _ids(task) + if package_id in self.registry and self.registry[package_id].batch + ] + if batched: + rel = path.relative_to(PROJECT_ROOT) + offenders.append( + f"{rel}: '{task.get('name', 'unnamed')}' installs " + f"{', '.join(batched)}" + ) + return offenders + + def test_unconditional_tasks_install_only_unbatched_ids(self) -> None: + offenders = self._offenders(conditional=False) + if offenders: + self.fail( + f"{len(offenders)} unconditional package_install task(s) install an " + "id the deploy-start batch already installs. Remove the task, or " + "flag the id 'batch: false' in its meta/packages.yml when it must " + "wait for a setup step the role runs first:\n" + + "\n".join(f" - {o}" for o in offenders) + ) + + def test_conditional_tasks_install_only_unbatched_ids(self) -> None: + offenders = self._offenders(conditional=True) + if offenders: + self.fail( + f"{len(offenders)} package_install task(s) under a when: install an " + "id the deploy-start batch installs unconditionally. Flag the id " + "'batch: false' in its meta/packages.yml:\n" + + "\n".join(f" - {o}" for o in offenders) + ) + + def test_roles_ahead_of_the_batch_install_only_unbatched_ids(self) -> None: + tasks = _constructor_tasks_ahead_of_the_batch() + self.assertIsNotNone( + tasks, + f"{STAGES_DIR / CONSTRUCTOR_STAGE} has no package_install task fed by " + f"{_BATCH_LOOKUP}...), so no deploy installs the batched ids.", + ) + references = load_references(PROJECT_ROOT) + offenders: list[str] = [] + for role in sorted(_roles_ahead_of_the_batch(tasks)): + owned = { + package_id + for package_id, declaration in self.registry.items() + if declaration.role == role + } + for package_id in sorted(owned | references.get(role, set())): + declaration = self.registry.get(package_id) + if declaration is not None and declaration.batch: + offenders.append(f"{role}: {package_id}") + if offenders: + self.fail( + f"{len(offenders)} id(s) belong to a role the constructor runs before " + "the deploy-start batch, so the batch installs them too late. Flag " + "each 'batch: false' in its meta/packages.yml:\n" + + "\n".join(f" - {o}" for o in offenders) + ) + + def test_role_package_installs_are_marked(self) -> None: + offenders: list[str] = [] + for path in _role_task_files(): + lines = read_text(str(path)).splitlines() + offenders.extend( + f"{path.relative_to(PROJECT_ROOT)}:{number}" + for number, line in enumerate(lines, start=1) + if _MODULE_LINE_RE.match(line) + and not is_suppressed_at(lines, number, _RULE) + ) + if offenders: + self.fail( + f"{len(offenders)} package_install task(s) in a role bypass the " + "deploy-start batch without saying why. Drop the task so the batch " + "installs the id, or flag the id 'batch: false' and mark the task " + f"'# nocheck: {_RULE} ':\n" + + "\n".join(f" - {o}" for o in offenders) + ) + + def test_references_name_shared_ids(self) -> None: + offenders = [ + f"roles/{role}/meta/packages.yml: '{package_id}'" + for role, package_ids in sorted(load_references(PROJECT_ROOT).items()) + for package_id in sorted(package_ids) + if package_id not in self.registry or not self.registry[package_id].shared + ] + if offenders: + self.fail( + f"{len(offenders)} 'shared: true' reference(s) name no id of the " + "root meta/packages.yml:\n" + "\n".join(f" - {o}" for o in offenders) + ) + + +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 index d66a0d7406..ad5363611c 100644 --- a/tests/lint/ansible/roles/test_playwright_helpers_staged.py +++ b/tests/lint/ansible/roles/test_playwright_helpers_staged.py @@ -27,11 +27,13 @@ from utils.cache.files import ( iter_project_files_with_content, read_text, ) +from utils.roles.mapping import ROLE_FILE_VARS_MAIN _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" +STAGING_TASK = PROJECT_ROOT / "roles/test-e2e-playwright/tasks/01_setup.yml" +STAGING_VARS = PROJECT_ROOT / "roles/test-e2e-playwright" / ROLE_FILE_VARS_MAIN RERUN_SCRIPT = PROJECT_ROOT / "scripts/tests/e2e/rerun-spec.sh" LINT_SCRIPT = PROJECT_ROOT / "scripts/lint/playwright.sh" @@ -41,7 +43,11 @@ _MOUNTED_AS_DIRECTORY = frozenset({"personas"}) _NOT_A_HELPER = frozenset({"playwright.config.js"}) -_GLOB_MARKER = "roles/test-e2e-playwright/files') }}/*.js" +_GLOB_MARKER = "query('fileglob', TEST_E2E_PLAYWRIGHT_HELPERS_DIR ~ '/*.js')" +_DIR_MARKER = ( + "TEST_E2E_PLAYWRIGHT_HELPERS_DIR: " + "\"{{ lookup('path_absolute', 'roles/test-e2e-playwright/files') }}\"" +) _SHELL_GLOB_MARKER = 'roles/test-e2e-playwright/files"/*.js' _LINT_GLOB_MARKER = '"${HELPERS_SRC}"/*.js' @@ -88,7 +94,7 @@ def unstaged_requires() -> list[str]: 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" + f"sibling spec nor staged by 01_setup.yml" ) return findings @@ -105,6 +111,7 @@ def stagers_without_the_glob() -> list[str]: findings = [] for path, marker in ( (STAGING_TASK, _GLOB_MARKER), + (STAGING_VARS, _DIR_MARKER), (RERUN_SCRIPT, _SHELL_GLOB_MARKER), (LINT_SCRIPT, _LINT_GLOB_MARKER), ): diff --git a/tests/lint/ansible/roles/test_vhost_cross_cutting_includes.py b/tests/lint/ansible/roles/test_vhost_cross_cutting_includes.py index 939e488803..8b446e3e30 100644 --- a/tests/lint/ansible/roles/test_vhost_cross_cutting_includes.py +++ b/tests/lint/ansible/roles/test_vhost_cross_cutting_includes.py @@ -193,6 +193,22 @@ GATED_INCLUDES = ( "roles/sys-svc-proxy/templates/headers/buffers.conf.j2", ) +ACL_INCLUDE = "roles/sys-svc-proxy/templates/location/sso_acl.conf.j2" + + +def sso_block(role: str) -> Mapping | None: + """Return the role's ``sso`` service block from ``meta/services.yml``. + + Args: + role: the role directory name. + """ + meta = PROJECT_ROOT / "roles" / role / ROLE_FILE_META_SERVICES + if not meta.is_file(): + return None + block = load_yaml_any(str(meta), default_if_missing={}) + sso = block.get("sso") if isinstance(block, Mapping) else None + return sso if isinstance(sso, Mapping) else None + def is_proxy_gated(role: str) -> bool: """Return whether oauth2-proxy fronts the role, per ``meta/services.yml``. @@ -204,14 +220,21 @@ def is_proxy_gated(role: str) -> bool: ``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" + sso = sso_block(role) + return ( + sso is not None and bool(sso.get("enabled")) and sso.get("flavor") == "oauth2" + ) + + +def declares_acl(role: str) -> bool: + """Return whether the role declares ``services.sso.oauth2.acl``. + + Args: + role: the role directory name. + """ + sso = sso_block(role) + oauth2 = sso.get("oauth2") if sso is not None else None + return isinstance(oauth2, Mapping) and bool(oauth2.get("acl")) def gated_without_the_gate() -> list[str]: @@ -219,9 +242,10 @@ def gated_without_the_gate() -> list[str]: 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. + nginx's defaults. One that declares an ACL also needs the ACL locations, + or the paths it opens stay behind the gate. None is in the shared + flavours' intersection, so the rule above cannot ask for them; an override + that flips to ``oauth2`` later would drop them without a word. """ findings = [] for path in OVERRIDES: @@ -231,7 +255,8 @@ def gated_without_the_gate() -> list[str]: content = read_text(str(path)) if is_suppressed_in_head(content.splitlines(), _RULE): continue - for missing in GATED_INCLUDES: + required = GATED_INCLUDES + ((ACL_INCLUDE,) if declares_acl(role) else ()) + for missing in required: if missing not in content: rel = path.relative_to(PROJECT_ROOT) findings.append(f"{rel}: is proxy-gated but omits {missing!r}") @@ -280,6 +305,17 @@ class TestVhostCrossCuttingIncludes(unittest.TestCase): "no role both overrides its vhost and is fronted by oauth2-proxy", ) + def test_an_acl_declaring_gated_override_is_actually_reached(self) -> None: + """Without one the ACL requirement would pass over nothing.""" + self.assertTrue( + [ + role_of(p) + for p in OVERRIDES + if is_proxy_gated(role_of(p)) and declares_acl(role_of(p)) + ], + "no gated override declares services.sso.oauth2.acl", + ) + 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))] diff --git a/tests/lint/ansible/services/test_memory_parameters_use_lookup.py b/tests/lint/ansible/services/test_memory_parameters_use_lookup.py index 70a725928d..0eb0410909 100644 --- a/tests/lint/ansible/services/test_memory_parameters_use_lookup.py +++ b/tests/lint/ansible/services/test_memory_parameters_use_lookup.py @@ -33,14 +33,13 @@ written another way is not seen; add its spelling when a role introduces one. from __future__ import annotations import re -import subprocess import unittest from bisect import bisect_right from collections import defaultdict from functools import cache from typing import TYPE_CHECKING, ClassVar -from utils.cache.files import read_text +from utils.cache.files import read_text, repository_files from utils.roles.mapping import ROLE_FILE_TEMPL_COMPOSE from . import PROJECT_ROOT @@ -278,22 +277,9 @@ def _scope(rel: str) -> str: @cache def _tracked_texts() -> dict[str, str]: - out = subprocess.check_output( - [ - "git", - "-c", - "safe.directory=*", - "-C", - str(PROJECT_ROOT), - "ls-files", - "roles", - _SHARED_SCOPE, - ], - text=True, - ) texts: dict[str, str] = {} - for rel in out.splitlines(): - if rel.endswith(".md"): + for rel in repository_files(): + if not rel.startswith(("roles/", f"{_SHARED_SCOPE}/")) or rel.endswith(".md"): continue try: texts[rel] = read_text(str(PROJECT_ROOT / rel)) diff --git a/tests/lint/ansible/shell/container/test_address_never_quoted.py b/tests/lint/ansible/shell/container/test_address_never_quoted.py index 7d48675f6f..624a0908a1 100644 --- a/tests/lint/ansible/shell/container/test_address_never_quoted.py +++ b/tests/lint/ansible/shell/container/test_address_never_quoted.py @@ -18,7 +18,7 @@ Add ``# nocheck: container-address-quote`` on the same line as the Reserved for sites that provably never see the swarm fragment (``IS_COMPOSE_MODE``-gated tasks, roles pinned via ``compose_mode_force``) or consumers that re-evaluate the argument -themselves (e.g. ``set_postgres_superuser_password.sh``). +themselves. """ from __future__ import annotations diff --git a/tests/lint/ansible/tasks/test_file_mode_is_quoted.py b/tests/lint/ansible/tasks/test_file_mode_is_quoted.py new file mode 100644 index 0000000000..f5e19605a3 --- /dev/null +++ b/tests/lint/ansible/tasks/test_file_mode_is_quoted.py @@ -0,0 +1,107 @@ +"""Lint: a file ``mode`` is a quoted string. + +YAML reads an unquoted ``mode: 600`` as the decimal number 600, which Ansible +applies as octal 1130 (sticky bit, owner execute only, group write and +execute). An unquoted ``0644`` only works through YAML 1.1 octal parsing. +Ansible documents a quoted string such as ``"0600"`` as the reliable form. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``nocheck: file-mode-quoted`` on the module line or the one above it. +""" + +from __future__ import annotations + +import unittest +from pathlib import Path +from typing import Any + +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 utils.roles.invocations import iter_tasks + +from . import PROJECT_ROOT +from .test_path_single_owner import module_line + +_RULE = "file-mode-quoted" + +_SHORT_MODULES = ( + "file", + "copy", + "template", + "get_url", + "unarchive", + "assemble", + "lineinfile", + "blockinfile", + "replace", +) +MODE_MODULES = ( + _SHORT_MODULES + + tuple(f"ansible.builtin.{name}" for name in _SHORT_MODULES) + + tuple(f"ansible.legacy.{name}" for name in _SHORT_MODULES) + + ("ini_file", "community.general.ini_file") +) + + +def offenders(tasks: Any) -> list[tuple[str, str, int]]: + """Return ``(task name, module, mode)`` of every unquoted numeric mode. + + Args: + tasks: a parsed task file. + """ + found: list[tuple[str, str, int]] = [] + for task in iter_tasks(tasks): + for module in MODE_MODULES: + args = task.get(module) + if not isinstance(args, dict): + continue + mode = args.get("mode") + if isinstance(mode, int) and not isinstance(mode, bool): + found.append((str(task.get("name", "")), module, mode)) + return found + + +class TestFileModeIsQuoted(unittest.TestCase): + def test_every_file_mode_is_a_quoted_string(self) -> None: + findings: list[str] = [] + for path in iter_project_files( + extensions=(".yml", ".yaml"), exclude_tests=True + ): + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + if "/tasks/" not in "/" + rel and "/handlers/" not in "/" + rel: + continue + found = offenders(load_yaml_any(path)) + if not found: + continue + lines = read_text(path).splitlines() + for name, module, mode in found: + line = module_line(lines, name, module) + if is_suppressed_at(lines, line, _RULE, mode="same-or-above"): + continue + findings.append( + f"- {rel}:{line}: {name or ''} (mode parsed as {mode})" + ) + + if findings: + self.fail( + "These modes are YAML numbers, so Ansible applies a different " + "permission than the digits suggest:\n" + + "\n".join(findings) + + "\n\nFix: quote the mode as a four-digit octal string, e.g. " + '`mode: "0600"`.' + ) + + def test_an_unquoted_mode_is_found(self) -> None: + tasks = [ + {"template": {"src": "a.j2", "dest": "/a", "mode": 600}}, + {"ansible.builtin.copy": {"src": "b", "dest": "/b", "mode": 420}}, + {"file": {"path": "/c", "mode": "0600"}}, + {"file": {"path": "/d", "mode": "{{ MODE }}"}}, + ] + self.assertEqual([mode for _, _, mode in offenders(tasks)], [600, 420]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/tasks/test_path_single_owner.py b/tests/lint/ansible/tasks/test_path_single_owner.py new file mode 100644 index 0000000000..a9f240ad77 --- /dev/null +++ b/tests/lint/ansible/tasks/test_path_single_owner.py @@ -0,0 +1,257 @@ +"""Lint: one task across all roles owns a path's owner, group and mode. + +When two roles both run ``file: state: directory`` on the same path and both +set ``owner``, ``group`` or ``mode``, every deploy flips the path between the +two settings: each task reports ``changed``, handlers fire, and the state the +host ends in depends on which role ran last. + +Paths are compared after substituting the plain ``{{ NAME }}`` variables of +``group_vars/all``; a literal ``loop`` over paths is expanded. A path spelled +through a filter or a dict attribute in one role and through a variable in the +other is not recognised as the same path. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``nocheck: path-single-owner`` on the module line or the one above it, when + the two tasks provably never run on the same host, or set identical values + because each must hold on hosts the other never reaches. +""" + +from __future__ import annotations + +import re +import unittest +from collections import defaultdict +from functools import cache +from pathlib import Path +from typing import Any + +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 utils.roles.invocations import iter_tasks +from utils.roles.mapping import ROLE_FILE_TASKS_MAIN + +from . import PROJECT_ROOT + +_RULE = "path-single-owner" + +FILE_MODULES = ("file", "ansible.builtin.file", "ansible.legacy.file") +PATH_KEYS = ("path", "dest", "name") +OWNING_KEYS = ("owner", "group", "mode") +MANAGED_STATES = (None, "directory", "file", "touch") +LOOP_KEYS = ("loop", "with_items", "with_list") + +_VARIABLE = re.compile(r"\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}") +_EXPRESSION = re.compile(r"\{\{\s*(.*?)\s*\}\}") + + +@cache +def global_strings() -> dict[str, str]: + """Return every top-level string variable of ``group_vars/all``.""" + found: dict[str, str] = {} + for path in sorted((PROJECT_ROOT / "group_vars" / "all").glob("*.yml")): + data = load_yaml_any(str(path)) + if not isinstance(data, dict): + continue + found.update( + {key: value for key, value in data.items() if isinstance(value, str)} + ) + return found + + +def canonical_path(raw: str, variables: dict[str, str]) -> str: + """Return *raw* with its plain variables substituted and spacing normalised. + + Args: + raw: the path as the task spells it. + variables: variable name to unrendered value. + """ + text = str(raw).strip() + for _ in range(10): + match = next( + (m for m in _VARIABLE.finditer(text) if m.group(1) in variables), None + ) + if match is None: + break + text = text[: match.start()] + variables[match.group(1)] + text[match.end() :] + text = _EXPRESSION.sub(lambda m: "{{ " + " ".join(m.group(1).split()) + " }}", text) + return text.rstrip("/") or "/" + + +def owned_paths(tasks: Any, variables: dict[str, str]) -> list[tuple[str, str, str]]: + """Return ``(canonical path, task name, module)`` for every task that sets + owner, group or mode on a path it keeps present. + + Args: + tasks: a parsed task file. + variables: variable name to unrendered value. + """ + found: list[tuple[str, str, str]] = [] + for task in iter_tasks(tasks): + module = next((m for m in FILE_MODULES if isinstance(task.get(m), dict)), None) + if module is None: + continue + args = task[module] + if args.get("state") not in MANAGED_STATES: + continue + if not any(key in args for key in OWNING_KEYS): + continue + raw = next((args[key] for key in PATH_KEYS if key in args), None) + if raw is None: + continue + name = str(task.get("name", "")) + loop = next((task[key] for key in LOOP_KEYS if key in task), None) + if loop is None: + found.append((canonical_path(raw, variables), name, module)) + continue + control = task.get("loop_control") + loop_var = ( + control.get("loop_var", "item") if isinstance(control, dict) else "item" + ) + if ( + not isinstance(loop, list) + or canonical_path(raw, {}) != f"{{{{ {loop_var} }}}}" + ): + continue + found.extend( + (canonical_path(item, variables), name, module) + for item in loop + if isinstance(item, str) + ) + return found + + +def module_line(lines: list[str], name: str, module: str) -> int: + """Return the 1-based line of *module* inside the task named *name*. + + Args: + lines: the task file's lines. + name: the task name; empty for an unnamed task. + module: the module key the task uses. + """ + start = 0 + if name: + start = next( + ( + index + for index, line in enumerate(lines) + if name in line and line.lstrip().startswith(("- name:", "name:")) + ), + 0, + ) + for index in range(start, len(lines)): + if lines[index].strip().lstrip("- ").startswith(f"{module}:"): + return index + 1 + return start + 1 + + +def _role_of(rel: str) -> str: + parts = rel.split("/") + return "/".join(parts[:2]) if parts[0] == "roles" else parts[0] + + +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() + ) + + +def conflicts( + setters: dict[str, list[tuple[str, int]]], +) -> dict[str, list[tuple[str, int]]]: + """Return the paths more than one role sets owner, group or mode on. + + Args: + setters: canonical path to ``(file, line)`` of every unsuppressed setter. + """ + return { + path: entries + for path, entries in setters.items() + if len({_role_of(rel) for rel, _ in entries}) > 1 + } + + +class TestPathSingleOwner(unittest.TestCase): + def test_one_role_owns_each_path(self) -> None: + variables = global_strings() + setters: dict[str, list[tuple[str, int]]] = defaultdict(list) + for path in _task_files(): + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + found = owned_paths(load_yaml_any(path), variables) + if not found: + continue + lines = read_text(path).splitlines() + for canonical, name, module in found: + line = module_line(lines, name, module) + if is_suppressed_at(lines, line, _RULE, mode="same-or-above"): + continue + setters[canonical].append((rel, line)) + + clashes = conflicts(setters) + if clashes: + report = [] + for path, entries in sorted(clashes.items()): + report.append(f"- {path}") + report.extend(f" {rel}:{line}" for rel, line in sorted(entries)) + self.fail( + "These paths get owner, group or mode from more than one role, so " + "every deploy flips them between the settings:\n" + + "\n".join(report) + + "\n\nFix: keep owner, group and mode in the one role that owns " + "the path and let the others only ensure it exists " + f"(`state: directory`), or mark a setter `nocheck: {_RULE}` when " + "the tasks never run on the same host or set identical values " + "for hosts the other never reaches." + ) + + def test_two_roles_setting_one_path_are_found(self) -> None: + variables = {"DIR_ROOT": "/srv/x", "DIR_SUB": "{{ DIR_ROOT }}/sub"} + first = owned_paths( + [ + { + "file": { + "path": "{{ DIR_SUB }}/", + "state": "directory", + "mode": "0700", + } + } + ], + variables, + ) + second = owned_paths( + [ + { + "ansible.builtin.file": { + "path": "{{ entry }}", + "state": "directory", + "owner": "root", + }, + "loop": ["/srv/x/sub", "/srv/other"], + "loop_control": {"loop_var": "entry"}, + } + ], + variables, + ) + setters = { + first[0][0]: [(f"roles/a/{ROLE_FILE_TASKS_MAIN}", 1)], + } + for canonical, _, _ in second: + setters.setdefault(canonical, []).append( + (f"roles/b/{ROLE_FILE_TASKS_MAIN}", 1) + ) + self.assertEqual(list(conflicts(setters)), ["/srv/x/sub"]) + + def test_existence_only_and_absent_tasks_are_ignored(self) -> None: + tasks = [ + {"file": {"path": "/srv/x", "state": "directory"}}, + {"file": {"path": "/srv/x", "state": "absent", "mode": "0700"}}, + {"file": {"path": "/srv/x", "state": "link", "src": "/a", "owner": "root"}}, + ] + self.assertEqual(owned_paths(tasks, {}), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/tasks/test_touch_preserves_times.py b/tests/lint/ansible/tasks/test_touch_preserves_times.py new file mode 100644 index 0000000000..db958a7fb9 --- /dev/null +++ b/tests/lint/ansible/tasks/test_touch_preserves_times.py @@ -0,0 +1,102 @@ +"""Lint: ``file: state: touch`` keeps the file's times. + +Without ``modification_time: preserve`` and ``access_time: preserve`` the +module stamps the current time on every run, so a task meant to ensure a file +exists reports ``changed`` on every deploy. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``nocheck: touch-preserves-times`` on the module line or the one above it, + when a consumer reads the new modification time. +""" + +from __future__ import annotations + +import unittest +from pathlib import Path +from typing import Any + +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 utils.roles.invocations import iter_tasks + +from . import PROJECT_ROOT +from .test_path_single_owner import FILE_MODULES, module_line + +_RULE = "touch-preserves-times" + +PRESERVE = "preserve" + + +def offenders(tasks: Any) -> list[tuple[str, str]]: + """Return ``(task name, module)`` of every touch that restamps the times. + + Args: + tasks: a parsed task file. + """ + found: list[tuple[str, str]] = [] + for task in iter_tasks(tasks): + module = next((m for m in FILE_MODULES if isinstance(task.get(m), dict)), None) + if module is None: + continue + args = task[module] + if args.get("state") != "touch": + continue + if ( + args.get("modification_time") == PRESERVE + and args.get("access_time") == PRESERVE + ): + continue + found.append((str(task.get("name", "")), module)) + return found + + +class TestTouchPreservesTimes(unittest.TestCase): + def test_every_touch_preserves_times(self) -> None: + findings: list[str] = [] + for path in iter_project_files( + extensions=(".yml", ".yaml"), exclude_tests=True + ): + rel = Path(path).relative_to(PROJECT_ROOT).as_posix() + if "/tasks/" not in "/" + rel: + continue + found = offenders(load_yaml_any(path)) + if not found: + continue + lines = read_text(path).splitlines() + for name, module in found: + line = module_line(lines, name, module) + if is_suppressed_at(lines, line, _RULE, mode="same-or-above"): + continue + findings.append(f"- {rel}:{line}: {name or ''}") + + if findings: + self.fail( + "These touches stamp the current time on every run and report " + "changed on every deploy:\n" + + "\n".join(findings) + + "\n\nFix: add `modification_time: preserve` and `access_time: " + f"preserve`, or mark it `nocheck: {_RULE}` when a consumer reads " + "the new modification time." + ) + + def test_a_touch_without_preserve_is_found(self) -> None: + tasks = [ + {"file": {"path": "/a", "state": "touch"}}, + {"file": {"path": "/b", "state": "touch", "modification_time": "preserve"}}, + { + "ansible.builtin.file": { + "path": "/c", + "state": "touch", + "modification_time": "preserve", + "access_time": "preserve", + } + }, + {"file": {"path": "/d", "state": "directory"}}, + ] + self.assertEqual(len(offenders(tasks)), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/ansible/test_no_deprecated_ansible_patterns.py b/tests/lint/ansible/test_no_deprecated_ansible_patterns.py index 2f9a27b744..5d466a63a9 100644 --- a/tests/lint/ansible/test_no_deprecated_ansible_patterns.py +++ b/tests/lint/ansible/test_no_deprecated_ansible_patterns.py @@ -10,9 +10,10 @@ Forbidden (with fix): Write the ``.list`` via ``ansible.builtin.copy`` (the repo's apt_repo.sh keeps the canonical .list and deletes .sources, so deb822_repository is unusable here) plus an explicit ``apt: update_cache``. -* ``community.mysql.*`` -- the collection moved to ``ansible.mysql`` (community - removes it in 6.0.0). Use ``ansible.mysql.`` and keep ``ansible.mysql`` - in requirements/requirements.galaxy.yml. +* ``community.mysql.*`` / ``ansible.mysql.*`` -- every database this project + runs is MariaDB, which ``ansible.mysql`` warns about and drops in 6.0.0. Use + ``ansible.mariadb.mariadb_`` and keep ``ansible.mariadb`` in both + requirements files. * top-level injected gathered facts (``ansible_os_family`` and friends) -- ``INJECT_FACTS_AS_VARS`` default is deprecated. Use ``ansible_facts['']``. Only gathered facts are denied; magic/connection vars (ansible_version, host, @@ -86,9 +87,9 @@ _PATTERNS: tuple[tuple[str, re.Pattern[str], str], ...] = ( "deprecated module -> write the .list via ansible.builtin.copy + apt update_cache", ), ( - "community.mysql", - re.compile(r"\bcommunity\.mysql\."), - "collection renamed -> use ansible.mysql. (add ansible.mysql to galaxy reqs)", + "mysql-collection", + re.compile(r"\b(?:community|ansible)\.mysql\."), + "MariaDB leaves the mysql collection in 6.0.0 -> use ansible.mariadb.mariadb_ (ansible.mariadb in both requirements files)", ), ( "injected-fact", diff --git a/tests/lint/filesystem/env/test_env_file_schema.py b/tests/lint/filesystem/env/test_env_file_schema.py index 581ca86338..d96db02ce9 100644 --- a/tests/lint/filesystem/env/test_env_file_schema.py +++ b/tests/lint/filesystem/env/test_env_file_schema.py @@ -48,12 +48,11 @@ Style guidance for the one comment line (see `docs/contributing/documentation.md from __future__ import annotations import re -import subprocess import unittest from dataclasses import dataclass from typing import TYPE_CHECKING -from utils.cache.files import read_text +from utils.cache.files import read_text, repository_files from . import PROJECT_ROOT @@ -257,25 +256,10 @@ def validate_env_file(path: Path, *, strict: bool) -> list[Violation]: return violations -def _git_ls_files() -> list[str]: - out = subprocess.check_output( - [ - "git", - "-c", - "safe.directory=*", - "-C", - str(PROJECT_ROOT), - "ls-files", - ], - text=True, - ) - return [line for line in out.splitlines() if line] - - def _scan_targets() -> list[tuple[Path, bool]]: """Return (path, strict) pairs for every env-file the lint covers.""" targets: list[tuple[Path, bool]] = [] - for rel in _git_ls_files(): + for rel in repository_files(): if rel.endswith(".env"): strict = rel.startswith("env/") or rel == ".env" targets.append((PROJECT_ROOT / rel, strict)) diff --git a/tests/lint/filesystem/playwright/test_onion_request_timeout.py b/tests/lint/filesystem/playwright/test_onion_request_timeout.py index 042c37e828..7139b02404 100644 --- a/tests/lint/filesystem/playwright/test_onion_request_timeout.py +++ b/tests/lint/filesystem/playwright/test_onion_request_timeout.py @@ -28,12 +28,11 @@ never an onion host (localhost, an external clearnet API, ...). from __future__ import annotations import re -import subprocess import unittest from dataclasses import dataclass from typing import TYPE_CHECKING -from utils.cache.files import read_text +from utils.cache.files import read_text, repository_files from . import PROJECT_ROOT @@ -55,14 +54,6 @@ class Violation: detail: str -def _git_ls_files() -> list[str]: - out = subprocess.check_output( - ["git", "-c", "safe.directory=*", "-C", str(PROJECT_ROOT), "ls-files"], - text=True, - ) - return [line for line in out.splitlines() if line] - - def _call_end(text: str, open_idx: int) -> int: """Index of the ``)`` matching the ``(`` at ``open_idx`` (string-aware). @@ -139,7 +130,7 @@ def _scan_file(path: Path) -> list[Violation]: def _scan_targets() -> list[Path]: return [ PROJECT_ROOT / rel - for rel in _git_ls_files() + for rel in repository_files() if rel.endswith(".js") and "/files/playwright/" in rel ] diff --git a/tests/lint/filesystem/python/test_python_shebangs.py b/tests/lint/filesystem/python/test_python_shebangs.py index e3143a9b77..3613a20bbd 100755 --- a/tests/lint/filesystem/python/test_python_shebangs.py +++ b/tests/lint/filesystem/python/test_python_shebangs.py @@ -2,11 +2,10 @@ from __future__ import annotations -import subprocess import unittest from pathlib import Path -from utils.cache.files import iter_project_files +from utils.cache.files import iter_project_files, repository_files from . import PROJECT_ROOT @@ -21,14 +20,7 @@ class TestPythonShebangs(unittest.TestCase): def _tracked_files(self) -> list[Path]: try: - out = subprocess.check_output( - ["git", "-C", str(self.repo_root), "ls-files", "-z"], - stderr=subprocess.STDOUT, - ) - rel_paths = [ - p for p in out.decode("utf-8", errors="replace").split("\0") if p - ] - return [self.repo_root / p for p in rel_paths] + return [self.repo_root / p for p in repository_files(untracked=True)] except Exception: return [Path(p) for p in iter_project_files()] diff --git a/tests/lint/filesystem/shell/test_no_infinito_defaults.py b/tests/lint/filesystem/shell/test_no_infinito_defaults.py index 78f422afe0..4f06db4950 100644 --- a/tests/lint/filesystem/shell/test_no_infinito_defaults.py +++ b/tests/lint/filesystem/shell/test_no_infinito_defaults.py @@ -27,12 +27,11 @@ overrides not exposed as a stack-wide variable). from __future__ import annotations import re -import subprocess import unittest from dataclasses import dataclass from typing import TYPE_CHECKING -from utils.cache.files import read_text +from utils.cache.files import read_text, repository_files from . import PROJECT_ROOT @@ -56,21 +55,6 @@ class Violation: detail: str -def _git_ls_files() -> list[str]: - out = subprocess.check_output( - [ - "git", - "-c", - "safe.directory=*", - "-C", - str(PROJECT_ROOT), - "ls-files", - ], - text=True, - ) - return [line for line in out.splitlines() if line] - - def _scan_file(path: Path) -> list[Violation]: violations: list[Violation] = [] rel = path.relative_to(PROJECT_ROOT).as_posix() @@ -117,7 +101,7 @@ def _scan_file(path: Path) -> list[Violation]: def _scan_targets() -> list[Path]: - return [PROJECT_ROOT / rel for rel in _git_ls_files() if rel.endswith(".sh")] + return [PROJECT_ROOT / rel for rel in repository_files() if rel.endswith(".sh")] class TestShellNoInfinitoDefaults(unittest.TestCase): diff --git a/tests/lint/filesystem/shell/test_no_or_true.py b/tests/lint/filesystem/shell/test_no_or_true.py index f414bb593c..07c7da8610 100644 --- a/tests/lint/filesystem/shell/test_no_or_true.py +++ b/tests/lint/filesystem/shell/test_no_or_true.py @@ -17,12 +17,11 @@ exists to stop *new* blanket ``|| true`` from creeping in. from __future__ import annotations import re -import subprocess import unittest from dataclasses import dataclass from typing import TYPE_CHECKING -from utils.cache.files import read_text +from utils.cache.files import read_text, repository_files from . import PROJECT_ROOT @@ -40,21 +39,6 @@ class Violation: detail: str -def _git_ls_files() -> list[str]: - out = subprocess.check_output( - [ - "git", - "-c", - "safe.directory=*", - "-C", - str(PROJECT_ROOT), - "ls-files", - ], - text=True, - ) - return [line for line in out.splitlines() if line] - - def _scan_file(path: Path) -> list[Violation]: violations: list[Violation] = [] rel = path.relative_to(PROJECT_ROOT).as_posix() @@ -81,7 +65,7 @@ def _scan_file(path: Path) -> list[Violation]: def _scan_targets() -> list[Path]: - return [PROJECT_ROOT / rel for rel in _git_ls_files() if rel.endswith(".sh")] + return [PROJECT_ROOT / rel for rel in repository_files() if rel.endswith(".sh")] class TestShellNoOrTrue(unittest.TestCase): diff --git a/tests/lint/filesystem/shell/test_no_path_defaults.py b/tests/lint/filesystem/shell/test_no_path_defaults.py index 4d050a0c92..c4253fa693 100644 --- a/tests/lint/filesystem/shell/test_no_path_defaults.py +++ b/tests/lint/filesystem/shell/test_no_path_defaults.py @@ -30,12 +30,11 @@ only when the shell context genuinely cannot consume ``default.env``. from __future__ import annotations import re -import subprocess import unittest from dataclasses import dataclass from typing import TYPE_CHECKING -from utils.cache.files import read_text +from utils.cache.files import read_text, repository_files from . import PROJECT_ROOT @@ -56,24 +55,6 @@ class Violation: detail: str -def _git_ls_files() -> list[str]: - """List tracked files; ``safe.directory=*`` bypasses git's ownership - check, which fails inside the dev container when the bind-mounted - repo's UID does not match the container user.""" - out = subprocess.check_output( - [ - "git", - "-c", - "safe.directory=*", - "-C", - str(PROJECT_ROOT), - "ls-files", - ], - text=True, - ) - return [line for line in out.splitlines() if line] - - def _scan_file(path: Path) -> list[Violation]: violations: list[Violation] = [] rel = path.relative_to(PROJECT_ROOT).as_posix() @@ -104,7 +85,7 @@ def _scan_file(path: Path) -> list[Violation]: def _scan_targets() -> list[Path]: - return [PROJECT_ROOT / rel for rel in _git_ls_files() if rel.endswith(".sh")] + return [PROJECT_ROOT / rel for rel in repository_files() if rel.endswith(".sh")] class TestShellNoPathDefaults(unittest.TestCase): diff --git a/tests/lint/filesystem/test_no_rsync_backup_flag.py b/tests/lint/filesystem/test_no_rsync_backup_flag.py index 37afb60c9d..1687d9b8e7 100644 --- a/tests/lint/filesystem/test_no_rsync_backup_flag.py +++ b/tests/lint/filesystem/test_no_rsync_backup_flag.py @@ -18,12 +18,11 @@ Suppress on a per-line basis with a same-line ``# nocheck: rsync-backup -- from __future__ import annotations import re -import subprocess import unittest from dataclasses import dataclass from pathlib import Path -from utils.cache.files import read_text +from utils.cache.files import read_text, repository_files from . import PROJECT_ROOT @@ -44,14 +43,6 @@ class Violation: detail: str -def _git_ls_files() -> list[str]: - out = subprocess.check_output( - ["git", "-c", "safe.directory=*", "-C", str(PROJECT_ROOT), "ls-files"], - text=True, - ) - return [line for line in out.splitlines() if line] - - def _offending_flag(line: str) -> str | None: """Name the backup flag on a line, or None when it carries none. @@ -103,7 +94,7 @@ def _scan_file(path: Path) -> list[Violation]: def _scan_targets() -> list[Path]: return [ PROJECT_ROOT / rel - for rel in _git_ls_files() + for rel in repository_files() if rel.endswith(_SCANNED_SUFFIXES) and rel != _SELF_REL and (PROJECT_ROOT / rel).exists() diff --git a/tests/lint/repository/documentation/test_todo_transparency.py b/tests/lint/repository/documentation/test_todo_transparency.py index 14e8157cf4..edc9df2c00 100644 --- a/tests/lint/repository/documentation/test_todo_transparency.py +++ b/tests/lint/repository/documentation/test_todo_transparency.py @@ -9,13 +9,12 @@ readable. from __future__ import annotations import re -import subprocess import unittest from dataclasses import dataclass from pathlib import Path from utils.annotations.message import in_github_actions, warning -from utils.cache.files import iter_project_files, read_text +from utils.cache.files import iter_project_files, read_text, repository_files from . import PROJECT_ROOT @@ -79,12 +78,7 @@ class TodoFinding: def tracked_files(root: Path) -> list[Path]: try: - out = subprocess.check_output( - ["git", "-C", str(root), "ls-files", "-z"], - stderr=subprocess.STDOUT, - ) - rel_paths = [p for p in out.decode("utf-8", errors="replace").split("\0") if p] - return [root / rel for rel in rel_paths] + return [root / rel for rel in repository_files(untracked=True)] except Exception: return [Path(p) for p in iter_project_files()] diff --git a/tests/lint/repository/test_comments_valid.py b/tests/lint/repository/test_comments_valid.py index 1d22894f84..193f52ee60 100644 --- a/tests/lint/repository/test_comments_valid.py +++ b/tests/lint/repository/test_comments_valid.py @@ -41,9 +41,9 @@ intentionally OUT of scope (reliably distinguishing them from ``#`` inside a string needs a full lexer per language, and false positives would make the linter unusable). -SCOPE: every tracked file of a checked type, plus untracked new ones. The -policy holds for the whole repository, not only for the files a change happens -to touch. +SCOPE: every tracked file of a checked type, plus untracked new ones and the +custom roles pulled into ``roles/``. The policy holds for the whole repository, +not only for the files a change happens to touch. A whole file opts out with a ``# nocheck: comments-valid`` marker in its first 30 lines (any comment prefix, e.g. ``{# nocheck: comments-valid #}`` for Jinja), @@ -61,11 +61,12 @@ import unittest from typing import TYPE_CHECKING from utils.annotations.suppress import is_suppressed_in_head -from utils.cache.files import read_text +from utils.cache.files import read_text, repository_files, untracked_files from . import PROJECT_ROOT if TYPE_CHECKING: + from collections.abc import Callable from pathlib import Path _FILE_NOCHECK_RULE = "comments-valid" @@ -452,32 +453,20 @@ def find_invalid_comments(path: Path): _EXTS = (".py", ".sh", ".yml", ".yaml", ".rb", ".php", ".css", ".j2") -def _git_lines(args: list[str]) -> list[str]: - """Run a git command and return its stdout lines. - - safe.directory='*' is required because the make-test container mounts the - repo as a different uid; bare git would abort with dubious-ownership and the - linter would silently scan zero files. - """ +def _listed(listing: Callable[[], tuple[str, ...]]) -> set[str]: try: - result = subprocess.run( - ["git", "-c", "safe.directory=*", *args], - cwd=str(PROJECT_ROOT), - capture_output=True, - text=True, - check=True, - ) + return set(listing()) except (OSError, subprocess.SubprocessError): - return [] - return result.stdout.splitlines() + return set() def _all_targets(): - """Every tracked file of a checked type, plus untracked new ones.""" - rel = set(_git_lines(["ls-files"])) - rel |= set(_git_lines(["ls-files", "--others", "--exclude-standard"])) + """Every tracked file of a checked type, plus untracked new ones. + + A failing git listing loses only its own files. + """ targets = [] - for r in sorted(rel): + for r in sorted(_listed(repository_files) | _listed(untracked_files)): if r.endswith(_EXTS) or r.rsplit("/", 1)[-1] == "Dockerfile": path = PROJECT_ROOT / r if path.is_file(): diff --git a/tests/lint/repository/test_no_debian_codename_tags.py b/tests/lint/repository/test_no_debian_codename_tags.py index 5445e3ab86..7a0634813d 100644 --- a/tests/lint/repository/test_no_debian_codename_tags.py +++ b/tests/lint/repository/test_no_debian_codename_tags.py @@ -20,7 +20,7 @@ the way every other version pin does. Scope ----- -Every tracked file. Two shapes are recognised: +Every tracked file and every pulled custom role. Two shapes are recognised: * a ``name:tag`` image reference with no space after the colon, which covers ``image:`` values, Dockerfile ``FROM`` lines and heredocs, @@ -46,13 +46,12 @@ 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 utils.cache.files import read_text, repository_files from . import PROJECT_ROOT @@ -145,23 +144,13 @@ def _references_on(line: str) -> list[tuple[str, str]]: 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") - ) + return set(repository_files(untracked=True)) def _scan_file(path: Path) -> list[Violation]: diff --git a/tests/unit/python/cli/administration/deploy/dedicated/test_command.py b/tests/unit/python/cli/administration/deploy/dedicated/test_command.py index df0d5b1249..9476110fbd 100644 --- a/tests/unit/python/cli/administration/deploy/dedicated/test_command.py +++ b/tests/unit/python/cli/administration/deploy/dedicated/test_command.py @@ -1,9 +1,43 @@ -# cli/administration/deploy/dedicated/tests/test_command_ids.py from __future__ import annotations import unittest +from types import SimpleNamespace +from unittest import mock -from cli.administration.deploy.dedicated.command import _normalize_app_ids +from cli.administration.deploy.dedicated import command +from cli.administration.deploy.dedicated.command import ( + _normalize_app_ids, + pull_custom_roles, +) + + +class TestPullCustomRoles(unittest.TestCase): + @mock.patch("cli.administration.deploy.dedicated.command.pull_or_exit") + def test_pulls_the_inventory_by_default(self, pull_or_exit): + pull_custom_roles(SimpleNamespace(inventory="inv/devices.yml", skip_pull=False)) + pull_or_exit.assert_called_once_with("inv/devices.yml") + + @mock.patch("cli.administration.deploy.dedicated.command.pull_or_exit") + def test_skip_pull_keeps_the_placed_roles(self, pull_or_exit): + pull_custom_roles(SimpleNamespace(inventory="inv/devices.yml", skip_pull=True)) + pull_or_exit.assert_not_called() + + def test_main_pulls_before_anything_reads_roles(self): + calls: list[str] = [] + args = SimpleNamespace(inventory="inv/devices.yml", skip_pull=False) + with ( + mock.patch.object(command, "parse_args", return_value=(args, [], {})), + mock.patch.object( + command, "pull_or_exit", side_effect=lambda _inv: calls.append("pull") + ), + mock.patch.object( + command, + "run_from_args", + side_effect=lambda *_a: calls.append("deploy") or 0, + ), + ): + self.assertEqual(0, command.main([])) + self.assertEqual(["pull", "deploy"], calls) class TestNormalizeAppIds(unittest.TestCase): diff --git a/tests/unit/python/cli/administration/deploy/dedicated/test_command_passthrough.py b/tests/unit/python/cli/administration/deploy/dedicated/test_command_passthrough.py index a86a187859..3dc5968010 100644 --- a/tests/unit/python/cli/administration/deploy/dedicated/test_command_passthrough.py +++ b/tests/unit/python/cli/administration/deploy/dedicated/test_command_passthrough.py @@ -7,6 +7,7 @@ from cli.administration.deploy.dedicated import command as dedicated_command class TestDedicatedCommandPassthrough(unittest.TestCase): + @unittest.mock.patch("cli.administration.deploy.dedicated.command.pull_or_exit") @unittest.mock.patch( "cli.administration.deploy.dedicated.command.validate_application_ids" ) @@ -29,6 +30,7 @@ class TestDedicatedCommandPassthrough(unittest.TestCase): mock_load_modes_from_yaml, mock_run_ansible_playbook, mock_validate_application_ids, + _mock_pull_or_exit, ): mock_load_modes_from_yaml.return_value = [] mock_add_dynamic_mode_args.return_value = {} diff --git a/tests/unit/python/cli/administration/deploy/dedicated/test_main.py b/tests/unit/python/cli/administration/deploy/dedicated/test_main.py index 054fd8aa82..d21e60e63d 100644 --- a/tests/unit/python/cli/administration/deploy/dedicated/test_main.py +++ b/tests/unit/python/cli/administration/deploy/dedicated/test_main.py @@ -15,6 +15,7 @@ class TestDedicatedMainParser(unittest.TestCase): self.assertIn("limit", opts) self.assertIn("password_file", opts) self.assertIn("skip_build", opts) + self.assertIn("skip_pull", opts) self.assertIn("id", opts) self.assertIn("verbose", opts) self.assertIn("diff", opts) diff --git a/tests/unit/python/cli/administration/deploy/development/deploy/__init__.py b/tests/unit/python/cli/administration/deploy/development/deploy/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/administration/deploy/development/deploy/test_run.py b/tests/unit/python/cli/administration/deploy/development/deploy/test_run.py new file mode 100644 index 0000000000..53110503bb --- /dev/null +++ b/tests/unit/python/cli/administration/deploy/development/deploy/test_run.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +import unittest +from types import SimpleNamespace +from unittest import mock + +from cli.administration.deploy.development.deploy.run import _run_deploy + + +class TestRunDeploy(unittest.TestCase): + def deploy_cmd(self) -> list[str]: + compose = mock.Mock() + compose.exec.return_value = SimpleNamespace(returncode=0) + _run_deploy( + compose, + deploy_ids=["web-app-cst-demo"], + debug=False, + passthrough=[], + inventory_dir="/etc/inventories/dev", + container_name="infinito", + ) + return compose.exec.call_args.args[0] + + def test_deploys_the_generated_inventory(self): + cmd = self.deploy_cmd() + self.assertEqual("/etc/inventories/dev/devices.yml", cmd[3]) + self.assertEqual(["--id", "web-app-cst-demo"], cmd[-2:]) + + def test_generated_inventory_keeps_the_placed_custom_roles(self): + self.assertIn("--skip-pull", self.deploy_cmd()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py b/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py index ecb67600c8..e3ac2a5445 100644 --- a/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py +++ b/tests/unit/python/cli/administration/deploy/development/test_env_compose_file_args.py @@ -9,7 +9,9 @@ from __future__ import annotations import os import re +import tempfile import unittest +from pathlib import Path from unittest.mock import patch from cli.administration.deploy.development.env import ( @@ -35,6 +37,7 @@ _LOCAL_PRIMARY = { "INFINITO_TOOLS_MODELS_HOST_PATH": "/var/cache/infinito/core/cache/models", "INFINITO_TOOLS_S1_PORT": "8096", "INFINITO_TOOLS_TRANSLATE_PORT": "8101", + "INFINITO_EXTRA_MOUNTS": "", } _WORKTREE = { @@ -168,6 +171,35 @@ class TestComposeFileArgs(unittest.TestCase): def test_the_models_path_gates_the_tools_lane_too(self) -> None: self.assertNotIn("compose/tools.override.yml", compose_file_args()) + def test_extra_mounts_append_their_generated_override(self) -> None: + with ( + tempfile.TemporaryDirectory() as mount, + patch.dict( + os.environ, + {**_LOCAL_PRIMARY, "INFINITO_EXTRA_MOUNTS": mount}, + clear=False, + ), + patch( + "cli.administration.deploy.development.extra_mounts.write_mounts_override", + return_value="build/compose/extra-mounts.override.yml", + ) as write, + ): + args = compose_file_args() + self.assertEqual(write.call_args.args[1], [Path(mount)]) + self.assertEqual(args[-2:], ["-f", "build/compose/extra-mounts.override.yml"]) + + def test_an_entry_that_is_no_directory_stops_the_stack_naming_it(self) -> None: + with ( + patch.dict( + os.environ, + {**_LOCAL_PRIMARY, "INFINITO_EXTRA_MOUNTS": "/nonexistent/gui"}, + clear=False, + ), + self.assertRaises(SystemExit) as ctx, + ): + compose_file_args() + self.assertIn("/nonexistent/gui", str(ctx.exception.code)) + class TestToolsLaneGateCoversItsGuards(unittest.TestCase): def test_every_guard_the_override_adds_is_gated(self) -> None: diff --git a/tests/unit/python/cli/administration/deploy/development/test_extra_mounts.py b/tests/unit/python/cli/administration/deploy/development/test_extra_mounts.py new file mode 100644 index 0000000000..4f45d7165e --- /dev/null +++ b/tests/unit/python/cli/administration/deploy/development/test_extra_mounts.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path + +from cli.administration.deploy.development.extra_mounts import ( + OVERRIDE, + parse_mounts, + write_mounts_override, +) +from utils.cache.yaml import load_yaml + + +class TestParseMounts(unittest.TestCase): + def test_existing_absolute_directories_are_returned(self) -> None: + with ( + tempfile.TemporaryDirectory() as first, + tempfile.TemporaryDirectory() as second, + ): + self.assertEqual( + parse_mounts(f"{first}, {second},"), [Path(first), Path(second)] + ) + + def test_empty_value_mounts_nothing(self) -> None: + self.assertEqual(parse_mounts(""), []) + + def test_relative_entry_is_rejected_naming_it(self) -> None: + with self.assertRaises(SystemExit) as ctx: + parse_mounts("relative/dir") + self.assertIn("relative/dir", str(ctx.exception.code)) + + def test_missing_directory_is_rejected_naming_it(self) -> None: + with tempfile.TemporaryDirectory() as tmp, self.assertRaises(SystemExit) as ctx: + parse_mounts(str(Path(tmp) / "absent")) + self.assertIn("absent", str(ctx.exception.code)) + + +class TestWriteMountsOverride(unittest.TestCase): + def test_each_directory_is_bound_read_only_at_its_own_path(self) -> None: + with tempfile.TemporaryDirectory() as repo: + relative = write_mounts_override(Path(repo), [Path("/srv/gui")]) + override = load_yaml(Path(repo) / relative) + self.assertEqual(relative, OVERRIDE) + self.assertEqual( + override, + { + "services": { + "infinito": { + "volumes": [ + { + "type": "bind", + "source": "/srv/gui", + "target": "/srv/gui", + "read_only": True, + } + ] + } + } + }, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/deploy/swarm/test_command.py b/tests/unit/python/cli/administration/deploy/swarm/test_command.py new file mode 100644 index 0000000000..ed6c33c2c5 --- /dev/null +++ b/tests/unit/python/cli/administration/deploy/swarm/test_command.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +import unittest +from types import SimpleNamespace +from unittest import mock + +from cli.administration.deploy.swarm import command + + +class TestSwarmMain(unittest.TestCase): + def test_custom_roles_are_pulled_before_the_closure_reads_roles(self): + calls: list[str] = [] + args = SimpleNamespace(id=["web-app-cst-demo"], inventory="inv/devices.yml") + + def closure(ids, _inventory): + calls.append("closure") + return ids + + with ( + mock.patch.object(command, "parse_args", return_value=(args, [], {})), + mock.patch.object( + command, + "pull_custom_roles", + side_effect=lambda _args: calls.append("pull"), + ), + mock.patch.object(command, "swarm_deploy_targets", side_effect=closure), + mock.patch.object(command, "run_from_args", return_value=0) as run, + ): + self.assertEqual(0, command.main([])) + + self.assertEqual(["pull", "closure"], calls) + run.assert_called_once_with(args, [], {}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/deploy/test_container.py b/tests/unit/python/cli/administration/deploy/test_container.py index be9641f83e..e73605d2ba 100644 --- a/tests/unit/python/cli/administration/deploy/test_container.py +++ b/tests/unit/python/cli/administration/deploy/test_container.py @@ -83,6 +83,35 @@ class TestEnsureImage(unittest.TestCase): ) +class TestRunInContainer(unittest.TestCase): + @unittest.mock.patch("subprocess.run") + @unittest.mock.patch( + "cli.administration.deploy.container.command.docker_exec", + return_value=subprocess.CompletedProcess(args=[], returncode=0), + ) + @unittest.mock.patch( + "cli.administration.deploy.container.command.start_ci_container", + return_value="infinito-ci-test", + ) + def test_generated_inventory_keeps_the_placed_custom_roles( + self, _start, mock_docker_exec, _run + ): + deploy_container.run_in_container( + image="infinito:latest", + build=False, + rebuild=False, + no_cache=False, + inventory_dir="/tmp/inventory", + inventory_args=[], + deploy_args=["--debug"], + ) + + deploy_cmd = mock_docker_exec.call_args_list[-1].args[1] + self.assertIn("cli.administration.deploy.dedicated", deploy_cmd) + self.assertIn("--skip-pull", deploy_cmd) + self.assertEqual("--debug", deploy_cmd[-1]) + + class TestMain(unittest.TestCase): @unittest.mock.patch("cli.administration.deploy.container.command.run_in_container") def test_main_requires_forwarded_args(self, mock_run_in_container): 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 index d503658a5c..ccbbaabb72 100644 --- a/tests/unit/python/cli/administration/inventory/provision/test_users_generator.py +++ b/tests/unit/python/cli/administration/inventory/provision/test_users_generator.py @@ -1,8 +1,10 @@ +import importlib.util import re import shutil import tempfile import unittest from pathlib import Path +from typing import ClassVar from unittest.mock import patch from ruamel.yaml import YAML @@ -20,7 +22,10 @@ from cli.administration.inventory.provision.users_generator import ( required_user_policies, ) from cli.administration.inventory.validate.users import compare_user_keys +from plugins.filter.reserved_users import non_reserved_users +from utils.cache import ROLES_DIR from utils.cache.files import read_text +from utils.cache.users import get_user_defaults from utils.roles.mapping import ROLE_FILE_META_USERS MODULE = "cli.administration.inventory.provision.users_generator" @@ -69,16 +74,81 @@ def _write_role_users(roles_dir: Path, application_id: str, body: str) -> None: class TestRequiredUserPolicies(unittest.TestCase): - def test_only_the_resolved_roles_contribute(self): + def test_a_reservation_of_an_unresolved_role_is_not_required(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") + _write_role_users(roles_dir, "web-app-b", "bob:\n accounts: []\n") self.assertEqual( ["alice"], list(required_user_policies(roles_dir, ["web-app-a"])) ) + def test_a_reservation_of_a_resolved_role_is_required(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users( + roles_dir, "web-app-a", "stalwartadmin:\n accounts: []\n" + ) + + self.assertEqual( + ["stalwartadmin"], + list(required_user_policies(roles_dir, ["web-app-a"])), + ) + + def test_a_bot_of_an_unresolved_role_is_required(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", + "no-reply:\n roles: [bot]\n accounts: [mailbox]\n", + ) + + self.assertIn("no-reply", required_user_policies(roles_dir, ["web-app-a"])) + + def test_a_bot_without_an_account_of_its_own_is_required(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users( + roles_dir, "web-app-b", "relay:\n roles: [bot]\n accounts: []\n" + ) + + self.assertEqual(["relay"], list(required_user_policies(roles_dir, []))) + + def test_an_identity_user_of_an_unresolved_role_is_required(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users(roles_dir, "web-app-b", "hermes: {}\n") + + self.assertEqual(["hermes"], list(required_user_policies(roles_dir, []))) + + def test_a_password_an_unresolved_role_states_outright_is_left_to_it(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users( + roles_dir, + "web-app-b", + "breakglass:\n password: '{{ ansible_become_password }}'\n", + ) + + self.assertEqual({}, required_user_policies(roles_dir, [])) + + def test_a_provisioned_user_takes_the_policy_of_its_unresolved_role(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users( + roles_dir, + "web-app-b", + "relay:\n roles: [bot]\n password:\n algorithm: alphanumeric\n", + ) + + self.assertEqual( + {"relay": {"algorithm": "alphanumeric", "validation": None}}, + required_user_policies(roles_dir, []), + ) + def test_a_user_declared_by_two_roles_appears_once(self): with tempfile.TemporaryDirectory() as tmpdir: roles_dir = Path(tmpdir) @@ -158,15 +228,30 @@ class TestGenerateUserPasswords(unittest.TestCase): node = doc["users"][username]["password"] self.assertEqual("!vault", getattr(node, "tag", None)) - def test_a_user_of_an_unresolved_role_is_not_pinned(self): + def test_a_reservation_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"] + {"web-app-a": "alice: {}\n", "web-app-b": "bob:\n accounts: []\n"}, + ["web-app-a"], ) self.assertEqual(1, count) self.assertIn("alice", doc["users"]) self.assertNotIn("bob", doc["users"]) + def test_a_bot_of_an_unresolved_role_is_pinned(self): + count, doc = self._run( + { + "web-app-a": "alice:\n accounts: []\n", + "web-app-b": "no-reply:\n roles: [bot]\n accounts: [mailbox]\n", + }, + ["web-app-a"], + ) + + self.assertEqual(2, count) + self.assertEqual( + "!vault", getattr(doc["users"]["no-reply"]["password"], "tag", None) + ) + def test_an_existing_password_is_never_overwritten(self): existing = CommentedMap() users = CommentedMap() @@ -239,7 +324,7 @@ class TestGenerateUserPasswords(unittest.TestCase): self.assertIs(True, doc["TLS_ENABLED"]) def test_no_required_users_writes_no_file(self): - count, doc = self._run({"web-app-a": "alice: {}\n"}, []) + count, doc = self._run({"web-app-a": "alice:\n accounts: []\n"}, []) self.assertEqual(0, count) self.assertIsNone(doc) @@ -514,6 +599,23 @@ class TestDeclaredPasswordPolicy(unittest.TestCase): ], ) + def test_a_role_that_asks_for_nothing_first_does_not_conflict(self): + with tempfile.TemporaryDirectory() as tmpdir: + roles_dir = Path(tmpdir) + _write_role_users(roles_dir, "web-app-a", "bot: {}\n") + _write_role_users( + roles_dir, + "web-app-b", + "bot:\n password:\n algorithm: strong_password\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]" @@ -530,5 +632,56 @@ class TestDeclaredPasswordPolicy(unittest.TestCase): self.assertRegex(password, r"[-_.]") +def _role_plugin(role: str, name: str): + path = ROLES_DIR / role / "lookup_plugins" / f"{name}.py" + spec = importlib.util.spec_from_file_location(f"_users_generator_{name}", path) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class TestRepositoryCatalogue(unittest.TestCase): + """The roles of the local Stalwart stack whose bots re-rendered per deploy.""" + + STALWART_STACK: ClassVar[list[str]] = [ + "svc-bkp-secrets-2-local", + "svc-bkp-volume-2-local", + "svc-net-tor-smtp", + "web-app-stalwart", + ] + + def test_every_user_a_provider_creates_on_the_fallback_is_pinned(self): + stalwart = _role_plugin("web-app-stalwart", "stalwart_users") + mailu = _role_plugin("web-app-mailu", "mailu_users") + catalogue = get_user_defaults(roles_dir=ROLES_DIR) + directory = non_reserved_users(catalogue) + required = required_user_policies(ROLES_DIR, self.STALWART_STACK) + + for username, user in catalogue.items(): + created = ( + stalwart.provisioned_by_stalwart(user) + or mailu.provisioned_by_mailu(user) + or username in directory + ) + if created and "strong_password" in str(user["password"]): + with self.subTest(username=username): + self.assertIn(username, required) + + def test_the_bots_stalwart_provisions_are_pinned(self): + required = required_user_policies(ROLES_DIR, self.STALWART_STACK) + + for username in ( + "blackhole", + "bounce", + "contact", + "helpdesk", + "newsletter", + "no-reply", + ): + with self.subTest(username=username): + self.assertIn(username, required) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/cli/administration/inventory/validate/test_applications.py b/tests/unit/python/cli/administration/inventory/validate/test_applications.py index aea6e30f54..3f9ed263c2 100644 --- a/tests/unit/python/cli/administration/inventory/validate/test_applications.py +++ b/tests/unit/python/cli/administration/inventory/validate/test_applications.py @@ -94,6 +94,24 @@ class TestCompareApplicationKeys(unittest.TestCase): self.assertEqual(len(result), 1) self.assertIn("services.dashbaord", result[0]) + def test_custom_role_declaration_keys_are_legal(self): + apps = { + "web-app-cst-demo": { + "custom": True, + "source": {"url": "https://x/y.git", "version": "v1", "path": "r"}, + "services": {"port": 8080}, + } + } + defaults = {"web-app-cst-demo": {"services": {"port": 8080}}} + self.assertEqual(compare_application_keys(apps, defaults, "src"), []) + + def test_declaration_keys_on_an_in_tree_role_are_flagged(self): + apps = {"app1": {"custom": True, "source": {"url": "https://x/y.git"}}} + defaults = {"app1": {"services": {}}} + result = compare_application_keys(apps, defaults, "src") + self.assertEqual(3, len(result)) + self.assertTrue(any(err.endswith("app1: custom") for err in result)) + if __name__ == "__main__": # pragma: no cover unittest.main() diff --git a/tests/unit/python/cli/administration/inventory/validate/test_loaders.py b/tests/unit/python/cli/administration/inventory/validate/test_loaders.py index 56041360af..fc592b98a6 100644 --- a/tests/unit/python/cli/administration/inventory/validate/test_loaders.py +++ b/tests/unit/python/cli/administration/inventory/validate/test_loaders.py @@ -27,7 +27,7 @@ class TestLoadYamlFile(LoadersTestBase, unittest.TestCase): data = load_yaml_file(path) self.assertEqual(data, {"applications": {"app1": {"key": "value"}}}) - def test_vault_blocks_are_stripped_before_parse(self): + def test_a_vaulted_value_loads_as_its_ciphertext(self): path = self.tmp_path / "vaulted.yml" path.write_text( "applications:\n" @@ -43,10 +43,60 @@ class TestLoadYamlFile(LoadersTestBase, unittest.TestCase): data = load_yaml_file(path) self.assertEqual( data["applications"]["app1"]["credentials"]["api_key"], - "", + "$ANSIBLE_VAULT;1.1;AES256\n61626364656667686970716e\n", ) self.assertEqual(data["users"], {"alice": {}}) + def test_keys_after_a_vaulted_value_survive(self): + path = self.tmp_path / "siblings.yml" + path.write_text( + "users:\n" + " administrator:\n" + " password: !vault |\n" + " $ANSIBLE_VAULT;1.1;AES256\n" + " 61626364\n" + " email: admin@example.org\n" + " biber:\n" + " username: biber\n" + " carl:\n" + " tokens:\n" + " - !vault |\n" + " $ANSIBLE_VAULT;1.1;AES256\n" + " 65666768\n" + "applications:\n" + " app1:\n" + " credentials:\n" + " api_key: !vault |\n" + " $ANSIBLE_VAULT;1.1;AES256\n" + "\n" + " 65666768\n" + " app2: {}\n", + encoding="utf-8", + ) + data = load_yaml_file(path) + self.assertEqual( + data["users"], + { + "administrator": { + "password": "$ANSIBLE_VAULT;1.1;AES256\n61626364\n", + "email": "admin@example.org", + }, + "biber": {"username": "biber"}, + "carl": {"tokens": ["$ANSIBLE_VAULT;1.1;AES256\n65666768\n"]}, + }, + ) + self.assertEqual( + data["applications"], + { + "app1": { + "credentials": { + "api_key": "$ANSIBLE_VAULT;1.1;AES256\n\n65666768\n" + } + }, + "app2": {}, + }, + ) + def test_missing_file_returns_none_and_warns(self): data = load_yaml_file(self.tmp_path / "does-not-exist.yml") self.assertIsNone(data) diff --git a/tests/unit/python/cli/administration/inventory/validate/test_users.py b/tests/unit/python/cli/administration/inventory/validate/test_users.py index cfaab98617..33c2b87e0f 100644 --- a/tests/unit/python/cli/administration/inventory/validate/test_users.py +++ b/tests/unit/python/cli/administration/inventory/validate/test_users.py @@ -24,6 +24,15 @@ class TestCompareUserKeys(unittest.TestCase): self.assertEqual(result, []) self.assertIn("Unknown user 'bob'", buf.getvalue()) + def test_an_inventory_only_user_with_its_own_username_does_not_warn(self): + users = {"biber": {"username": "biber", "email": "b@example.org"}} + defaults = {"alice": {"email": "default"}} + buf = io.StringIO() + with redirect_stderr(buf): + result = compare_user_keys(users, defaults, "src") + self.assertEqual(result, []) + self.assertEqual(buf.getvalue(), "") + def test_missing_default_for_extra_key(self): users = {"alice": {"email": "a@example.org", "extra": True}} defaults = {"alice": {"email": "default"}} diff --git a/tests/unit/python/cli/administration/roles/__init__.py b/tests/unit/python/cli/administration/roles/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/administration/roles/_fixtures.py b/tests/unit/python/cli/administration/roles/_fixtures.py new file mode 100644 index 0000000000..8b7302d911 --- /dev/null +++ b/tests/unit/python/cli/administration/roles/_fixtures.py @@ -0,0 +1,149 @@ +"""Throwaway role repositories, inventories and core roles/ trees for the pull tests.""" + +from __future__ import annotations + +import json +import os +import subprocess +from typing import TYPE_CHECKING + +from utils.roles.mapping import ( + ROLE_FILE_META_MAIN, + ROLE_FILE_TASKS_MAIN, + ROLE_FILE_VARS_MAIN, +) + +if TYPE_CHECKING: + from pathlib import Path + +ROLE = "web-app-cst-demo" +ROLE_PATH = f"ansible/roles/{ROLE}" + +_ENV = { + **{key: value for key, value in os.environ.items() if not key.startswith("GIT_")}, + "GIT_CONFIG_GLOBAL": os.devnull, +} + + +def git(cwd: Path, *args: str) -> str: + """Run git in *cwd* with a throwaway identity and no signing. + + Args: + cwd: the repository. + args: the git subcommand and its arguments. + """ + return subprocess.run( + [ + "git", + "-c", + "user.name=test", + "-c", + "user.email=test@example.invalid", + "-c", + "commit.gpgsign=false", + "-c", + "tag.gpgsign=false", + *args, + ], + cwd=cwd, + env=_ENV, + capture_output=True, + text=True, + check=True, + ).stdout + + +def write(path: Path, text: str) -> Path: + """Write *text* to *path*, creating its parents. + + Args: + path: the file. + text: its content. + """ + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return path + + +def role_repo(root: Path, application_id: str = ROLE) -> Path: + """A repository whose tag ``v1.0.0`` holds the role and whose branch ``feature`` moved on. + + Args: + root: directory the repository is created in. + application_id: the ``vars/main.yml`` application_id of the role. + """ + repo = root / "repo" + write(repo / "README.md", "repository root\n") + write(repo / ROLE_PATH / ROLE_FILE_META_MAIN, "galaxy_info: {}\n") + write(repo / ROLE_PATH / ROLE_FILE_VARS_MAIN, f"application_id: {application_id}\n") + write(repo / ROLE_PATH / ROLE_FILE_TASKS_MAIN, "release: v1\n") + git(repo, "init", "-q", "-b", "main") + git(repo, "add", "-A") + git(repo, "commit", "-q", "-m", "v1") + git(repo, "tag", "v1.0.0") + git(repo, "checkout", "-q", "-b", "feature") + write(repo / ROLE_PATH / ROLE_FILE_TASKS_MAIN, "release: feature\n") + git(repo, "commit", "-q", "-am", "feature") + return repo + + +def local_role(root: Path, group: str) -> Path: + """A checkout without Git history that holds the role *group* under ansible/roles/. + + Args: + root: directory the checkout is created in. + group: the role's group and application_id. + """ + checkout = root / f"{group}-checkout" + write(checkout / "ansible/roles" / group / ROLE_FILE_META_MAIN, "galaxy_info: {}\n") + write( + checkout / "ansible/roles" / group / ROLE_FILE_VARS_MAIN, + f"application_id: {group}\n", + ) + return checkout + + +def inventory(root: Path, groups: list[str], applications: dict) -> Path: + """An inventory whose host joins *groups* and whose host_vars set *applications*. + + Args: + root: directory the inventory is created in. + groups: inventory groups ``localhost`` joins. + applications: the host_vars ``applications`` block. + """ + write( + root / "host_vars/localhost.yml", + json.dumps({"applications": applications}), + ) + children = {group: {"hosts": {"localhost": {}}} for group in groups} + return write(root / "devices.yml", json.dumps({"all": {"children": children}})) + + +def declaration( + url: str, version: str | None = "v1.0.0", path: str = ROLE_PATH +) -> dict: + """The ``applications.`` block that declares a custom role. + + Args: + url: ``source.url``. + version: ``source.version``; ``None`` leaves it out. + path: ``source.path``. + """ + source = {"url": url, "path": path} + if version is not None: + source["version"] = version + return {"custom": True, "source": source} + + +def roles_dir(root: Path, *in_tree: str) -> Path: + """A core roles/ holding the given in-tree role directories. + + Args: + root: directory the roles/ is created in. + in_tree: names of in-tree roles to create. + """ + roles = root / "roles" + roles.mkdir(parents=True) + for name in in_tree: + (roles / name).mkdir() + return roles diff --git a/tests/unit/python/cli/administration/roles/clean/__init__.py b/tests/unit/python/cli/administration/roles/clean/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/administration/roles/clean/test_main.py b/tests/unit/python/cli/administration/roles/clean/test_main.py new file mode 100644 index 0000000000..c3b921fc3c --- /dev/null +++ b/tests/unit/python/cli/administration/roles/clean/test_main.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +import contextlib +import io +import unittest +from unittest import mock + +import cli.administration.roles.clean.__main__ as clean_main + + +class TestCleanMain(unittest.TestCase): + def test_reports_the_roles_it_removed_and_the_entries_it_left(self): + lines = [ + "web-app-cst-a: removed", + "web-app-cst-hand: left in place, the pull did not place it", + ] + with ( + mock.patch.object(clean_main, "clean", return_value=lines) as clean, + contextlib.redirect_stdout(io.StringIO()) as out, + ): + self.assertEqual(0, clean_main.main([])) + clean.assert_called_once_with(clean_main.ROLES_DIR, clean_main.WORK_DIR) + self.assertEqual( + "custom role web-app-cst-a: removed\n" + "custom role web-app-cst-hand: left in place, the pull did not place it\n", + out.getvalue(), + ) + + def test_a_filesystem_error_exits_with_it(self): + with ( + mock.patch.object(clean_main, "clean", side_effect=OSError("busy")), + self.assertRaises(SystemExit) as exit_, + ): + clean_main.main([]) + self.assertIn("busy", str(exit_.exception.code)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/roles/list/__init__.py b/tests/unit/python/cli/administration/roles/list/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/administration/roles/list/test_main.py b/tests/unit/python/cli/administration/roles/list/test_main.py new file mode 100644 index 0000000000..7e89a24a5e --- /dev/null +++ b/tests/unit/python/cli/administration/roles/list/test_main.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +import contextlib +import io +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +import cli.administration.roles.list.__main__ as list_main +from cli.administration.roles.marker import MARKER_FILE, marker_text + +ORIGIN = "https://example.invalid/w.git ansible/roles/web-app-cst-a @ v1 (commit abc)" + + +class TestListMain(unittest.TestCase): + def test_prints_each_placed_role_with_source_and_commit(self): + with tempfile.TemporaryDirectory() as tmp: + roles = Path(tmp) + marker = roles / "web-app-cst-a" / MARKER_FILE + marker.parent.mkdir() + marker.write_text( + marker_text("web-app-cst-a", "web-app-cst-a", ORIGIN), encoding="utf-8" + ) + (roles / "web-app-cst-hand").mkdir() + (roles / "web-app-nextcloud").mkdir() + with ( + mock.patch.object(list_main, "ROLES_DIR", roles), + contextlib.redirect_stdout(io.StringIO()) as out, + ): + self.assertEqual(0, list_main.main([])) + self.assertEqual(f"web-app-cst-a: {ORIGIN}\n", out.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/roles/pull/__init__.py b/tests/unit/python/cli/administration/roles/pull/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/administration/roles/pull/test_command.py b/tests/unit/python/cli/administration/roles/pull/test_command.py new file mode 100644 index 0000000000..6412c37d9e --- /dev/null +++ b/tests/unit/python/cli/administration/roles/pull/test_command.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +import contextlib +import io +import tarfile +import unittest +from pathlib import Path +from unittest import mock + +from yaml.constructor import ConstructorError + +from cli.administration.roles.paths import WORK_DIR +from cli.administration.roles.pull import command +from utils.cache import ROLES_DIR +from utils.roles.custom import CustomRoleError + + +class TestPullCommand(unittest.TestCase): + @mock.patch.object( + command, "pull", return_value=["web-app-cst-demo: repo path @ v1 (commit abc)"] + ) + def test_pulls_the_inventory_into_the_core_roles(self, pull): + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertEqual(0, command.main(["inv/devices.yml"])) + pull.assert_called_once_with(Path("inv/devices.yml"), ROLES_DIR, WORK_DIR) + self.assertIn("web-app-cst-demo: repo path @ v1 (commit abc)", out.getvalue()) + + @mock.patch.object(command, "pull", return_value=[]) + def test_nothing_declared_or_placed_prints_nothing(self, _pull): + with contextlib.redirect_stdout(io.StringIO()) as out: + command.main(["inv/devices.yml"]) + self.assertEqual("", out.getvalue()) + + def test_unpacking_parsing_and_filesystem_errors_exit_1_naming_them(self): + for error in ( + tarfile.AbsoluteLinkError(tarfile.TarInfo(".infinito-custom-role")), + ConstructorError(None, None, "found an undefined tag in inv/hosts.yml"), + PermissionError(13, "Permission denied", "roles/web-app-cst-demo"), + ): + with self.subTest(error=type(error).__name__): + with ( + mock.patch.object(command, "pull", side_effect=error), + contextlib.redirect_stderr(io.StringIO()) as err, + self.assertRaises(SystemExit) as exit_, + ): + command.main(["inv/devices.yml"]) + self.assertEqual(1, exit_.exception.code) + self.assertIn(str(error), err.getvalue()) + + @mock.patch.object( + command, + "pull", + side_effect=CustomRoleError( + "web-app-cst-demo: git fetch of v1 failed: fatal: unable to access " + "'https://deploy:s3cr3t@example.invalid/w.git/'" + ), + ) + def test_credentials_in_a_url_are_never_echoed(self, _pull): + with ( + contextlib.redirect_stderr(io.StringIO()) as err, + self.assertRaises(SystemExit), + ): + command.main(["inv/devices.yml"]) + self.assertNotIn("s3cr3t", err.getvalue()) + self.assertIn("web-app-cst-demo: git fetch of v1 failed", err.getvalue()) + + @mock.patch.object( + command, "pull", side_effect=CustomRoleError("web-app-cst-demo: refused") + ) + def test_refused_pull_exits_1_with_the_reason(self, _pull): + with ( + contextlib.redirect_stderr(io.StringIO()) as err, + self.assertRaises(SystemExit) as exit_, + ): + command.main(["inv/devices.yml"]) + self.assertEqual(1, exit_.exception.code) + self.assertIn("web-app-cst-demo: refused", err.getvalue()) + + def test_inventory_argument_is_required(self): + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): + command.main([]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/roles/test_declaration.py b/tests/unit/python/cli/administration/roles/test_declaration.py new file mode 100644 index 0000000000..8fc828bf76 --- /dev/null +++ b/tests/unit/python/cli/administration/roles/test_declaration.py @@ -0,0 +1,230 @@ +from __future__ import annotations + +import json +import tempfile +import unittest +from pathlib import Path + +from cli.administration.roles.declaration import Source, read_declarations + +from ._fixtures import ROLE, ROLE_PATH, declaration, inventory, roles_dir, write + +GIT_URL = "https://github.com/acme/widgets.git" + + +class TestReadDeclarations(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.roles = roles_dir(self.root, "web-app-nextcloud") + + def read(self, applications: dict, groups: tuple[str, ...] = (ROLE,)): + inv = inventory(self.root / "inventory", list(groups), applications) + return read_declarations(inv, self.roles) + + def assert_refused(self, applications: dict, *fragments: str, groups=(ROLE,)): + declared, errors = self.read(applications, groups) + message = "\n".join(errors) + for fragment in fragments: + self.assertIn(fragment, message) + return declared + + def test_complete_declaration_is_read(self): + declared, errors = self.read({ROLE: declaration(GIT_URL)}) + self.assertEqual([], errors) + self.assertEqual({ROLE: Source(GIT_URL, "v1.0.0", ROLE_PATH)}, declared) + + def test_ssh_url_is_accepted(self): + _declared, errors = self.read( + {ROLE: declaration("git@github.com:acme/widgets.git")} + ) + self.assertEqual([], errors) + + def test_ssh_config_host_alias_is_accepted(self): + _declared, errors = self.read( + {ROLE: declaration("github-store:acme/widgets.git")} + ) + self.assertEqual([], errors) + + def test_plain_http_url_is_refused(self): + self.assert_refused( + {ROLE: declaration("http://github.com/acme/widgets.git")}, + ROLE, + "source.url is neither", + ) + + def test_missing_url_names_group_and_field(self): + applications = { + ROLE: {"custom": True, "source": {"version": "v1", "path": ROLE_PATH}} + } + declared = self.assert_refused(applications, ROLE, "source.url is missing") + self.assertEqual({}, declared) + + def test_missing_version_of_a_git_url_names_the_field(self): + self.assert_refused( + {ROLE: declaration(GIT_URL, version=None)}, + ROLE, + "source.version is missing", + ) + + def test_missing_path_names_the_field(self): + applications = { + ROLE: {"custom": True, "source": {"url": GIT_URL, "version": "v1"}} + } + self.assert_refused(applications, ROLE, "source.path is missing") + + def test_missing_source_names_the_field(self): + self.assert_refused( + {ROLE: {"custom": True}}, ROLE, f"applications.{ROLE}.source is missing" + ) + + def test_local_directory_needs_no_version(self): + declared, errors = self.read({ROLE: declaration(str(self.root), version=None)}) + self.assertEqual([], errors) + self.assertTrue(declared[ROLE].local) + self.assertIsNone(declared[ROLE].version) + + def test_url_that_is_neither_git_nor_absolute_is_refused(self): + self.assert_refused( + {ROLE: declaration("checkouts/widgets")}, ROLE, "source.url is neither" + ) + + def test_url_with_credentials_is_refused_without_echoing_it(self): + for url in ( + "https://deploy:s3cr3t@github.com/acme/widgets.git", + "https://ghp_s3cr3t@github.com/acme/widgets.git", + "ssh://git:s3cr3t@github.com/acme/widgets.git", + ): + with self.subTest(url=url.split("@", 1)[1]): + declared, errors = self.read({ROLE: declaration(url)}) + message = "\n".join(errors) + self.assertIn( + f"{ROLE}: applications.{ROLE}.source.url embeds credentials", + message, + ) + self.assertNotIn("s3cr3t", message) + self.assertEqual({}, declared) + + def test_ssh_user_without_password_is_no_credential(self): + _declared, errors = self.read( + {ROLE: declaration("ssh://git@github.com/acme/widgets.git")} + ) + self.assertEqual([], errors) + + def test_jinja_in_a_source_field_is_refused(self): + applications = {ROLE: declaration("{{ lookup('env', 'ROLE_URL') }}")} + self.assert_refused(applications, ROLE, "source.url holds a Jinja expression") + + def test_jinja_in_custom_is_refused(self): + applications = {ROLE: {**declaration(GIT_URL), "custom": "{{ true }}"}} + declared = self.assert_refused( + applications, ROLE, f"{ROLE}.custom holds a Jinja expression" + ) + self.assertEqual({}, declared) + + def test_unknown_source_field_is_refused(self): + applications = {ROLE: declaration(GIT_URL)} + applications[ROLE]["source"]["tag"] = "v1" + self.assert_refused(applications, ROLE, "source.tag is not a source field") + + def test_path_leaving_the_repository_is_refused(self): + applications = {ROLE: declaration(GIT_URL, path=f"../{ROLE}")} + self.assert_refused(applications, ROLE, "relative path inside the repository") + + def test_directory_name_other_than_the_group_names_both(self): + applications = {ROLE: declaration(GIT_URL, path="ansible/roles/web-app-demo")} + self.assert_refused( + applications, "'web-app-demo'", f"'{ROLE}'", "never renames" + ) + + def test_group_without_custom_true_is_refused(self): + self.assert_refused( + {}, f"{ROLE}: inventory group without applications.{ROLE}.custom: true" + ) + + def test_custom_false_counts_as_undeclared(self): + applications = {ROLE: {**declaration(GIT_URL), "custom": False}} + declared = self.assert_refused(applications, f"{ROLE}: inventory group without") + self.assertEqual({}, declared) + + def test_custom_true_outside_the_prefix_is_refused(self): + applications = {"web-app-demo": declaration(GIT_URL)} + self.assert_refused( + applications, "web-app-demo: custom: true marks a group outside", groups=() + ) + + def test_entity_name_of_an_in_tree_role_is_refused(self): + applications = { + "web-app-cst-nextcloud": declaration( + GIT_URL, path="roles/web-app-cst-nextcloud" + ) + } + self.assert_refused( + applications, + "web-app-cst-nextcloud: entity name 'nextcloud'", + "in-tree role web-app-nextcloud", + groups=("web-app-cst-nextcloud",), + ) + + def test_declarations_that_differ_between_files_are_refused(self): + write( + self.root / "inventory/group_vars/all.yml", + json.dumps( + {"applications": {ROLE: declaration(GIT_URL, version="v2.0.0")}} + ), + ) + self.assert_refused( + {ROLE: declaration(GIT_URL)}, f"applications.{ROLE}.source differs between" + ) + + def read_yaml(self, host_vars: str): + base = self.root / "inventory" + write(base / "host_vars/localhost.yml", host_vars) + devices = {"all": {"children": {ROLE: {"hosts": {"localhost": {}}}}}} + return read_declarations( + write(base / "devices.yml", json.dumps(devices)), self.roles + ) + + def test_tagged_custom_is_refused_naming_the_tag(self): + declared, errors = self.read_yaml( + f"applications:\n {ROLE}:\n custom: !vault |\n" + " $ANSIBLE_VAULT;1.1;AES256\n 6162\n" + ) + self.assertEqual({}, declared) + self.assertIn( + f"{ROLE}: applications.{ROLE}.custom holds a !vault value", + "\n".join(errors), + ) + + def test_tagged_source_field_is_refused_naming_the_tag(self): + declared, errors = self.read_yaml( + f"applications:\n {ROLE}:\n custom: true\n source:\n" + f" url: {GIT_URL}\n version: !unsafe v1.0.0\n path: {ROLE_PATH}\n" + ) + self.assertEqual({}, declared) + self.assertIn( + f"{ROLE}: applications.{ROLE}.source.version holds a !unsafe value", + "\n".join(errors), + ) + + def test_unparsable_file_declares_nothing_and_is_the_only_error(self): + broken = write(self.root / "inventory/group_vars/all.yml", "applications: [\n") + declared, errors = self.read({ROLE: declaration(GIT_URL)}) + self.assertEqual({}, declared) + self.assertEqual(1, len(errors)) + self.assertTrue(errors[0].startswith(f"{broken}: cannot read"), errors[0]) + + def test_settings_without_custom_in_another_file_do_not_conflict(self): + write( + self.root / "inventory/group_vars/all.yml", + json.dumps( + {"applications": {ROLE: {"services": {"web": {"enabled": True}}}}} + ), + ) + _declared, errors = self.read({ROLE: declaration(GIT_URL)}) + self.assertEqual([], errors) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/roles/test_marker.py b/tests/unit/python/cli/administration/roles/test_marker.py new file mode 100644 index 0000000000..5cf799cd43 --- /dev/null +++ b/tests/unit/python/cli/administration/roles/test_marker.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +import os +import shutil +import tempfile +import unittest +from pathlib import Path + +from cli.administration.roles.marker import ( + MARKER_FILE, + custom_entries, + is_placed, + marker_text, + placed_roles, + provenance, + write_marker, +) + +from ._fixtures import write + +ORIGIN = "https://example.invalid/w.git ansible/roles/web-app-cst-a @ v1 (commit abc)" +PLACED = "web-app-cst-a" + + +class TestMarker(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.roles = Path(tmp.name) / "roles" + write(self.roles / PLACED / MARKER_FILE, marker_text(PLACED, PLACED, ORIGIN)) + write(self.roles / "web-app-cst-hand" / "mine.yml", "mine: true\n") + write(self.roles / "web-app-cst-forged" / MARKER_FILE, "something else\n") + shutil.copytree(self.roles / PLACED, self.roles / "web-app-cst-copy") + (self.roles / "web-app-cst-linked" / "x").mkdir(parents=True) + (self.roles / "web-app-cst-linked" / MARKER_FILE).symlink_to( + self.roles / PLACED / MARKER_FILE + ) + write( + self.roles / "web-app-nextcloud" / MARKER_FILE, + marker_text("web-app-nextcloud", "web-app-nextcloud", ORIGIN), + ) + (self.roles / "web-app-cst-link").symlink_to(self.roles / PLACED) + + def test_only_a_directory_whose_marker_names_it_is_placed(self): + self.assertTrue(is_placed(self.roles / PLACED)) + self.assertFalse(is_placed(self.roles / "web-app-cst-hand")) + self.assertFalse(is_placed(self.roles / "web-app-cst-forged")) + + def test_a_copy_under_another_name_is_not_placed(self): + self.assertFalse(is_placed(self.roles / "web-app-cst-copy")) + + def test_a_marker_that_is_a_symbolic_link_is_not_read(self): + self.assertFalse(is_placed(self.roles / "web-app-cst-linked")) + + def test_a_marker_that_is_a_fifo_is_not_placed(self): + fifo = self.roles / "web-app-cst-fifo" + fifo.mkdir() + os.mkfifo(fifo / MARKER_FILE) + self.assertFalse(is_placed(fifo)) + + def test_a_symbolic_link_to_a_placed_role_is_not_placed(self): + self.assertFalse(is_placed(self.roles / "web-app-cst-link")) + + def test_provenance_reads_back_what_the_pull_recorded(self): + self.assertEqual(ORIGIN, provenance(self.roles / PLACED)) + + def test_custom_entries_are_every_prefixed_entry(self): + self.assertEqual( + [ + PLACED, + "web-app-cst-copy", + "web-app-cst-forged", + "web-app-cst-hand", + "web-app-cst-link", + "web-app-cst-linked", + ], + [entry.name for entry in custom_entries(self.roles)], + ) + + def test_placed_roles_are_the_custom_entries_whose_marker_names_them(self): + self.assertEqual([PLACED], [entry.name for entry in placed_roles(self.roles)]) + + +class TestWriteMarker(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.role = self.root / PLACED + self.role.mkdir() + + def test_marker_names_the_directory_and_the_group(self): + write_marker(self.role, PLACED, ORIGIN) + self.assertTrue(is_placed(self.role)) + self.assertEqual(ORIGIN, provenance(self.role)) + + def test_a_symbolic_link_under_the_marker_name_is_replaced_not_followed(self): + victim = write(self.root / "victim.yml", "victim: true\n") + (self.role / MARKER_FILE).symlink_to(victim) + write_marker(self.role, PLACED, ORIGIN) + text = victim.read_text(encoding="utf-8") # nocheck: cache-read tempdir + self.assertEqual("victim: true\n", text) + self.assertFalse((self.role / MARKER_FILE).is_symlink()) + self.assertTrue(is_placed(self.role)) + + def test_a_directory_under_the_marker_name_is_replaced(self): + write(self.role / MARKER_FILE / "nested.yml", "nested: true\n") + write_marker(self.role, PLACED, ORIGIN) + self.assertTrue((self.role / MARKER_FILE).is_file()) + self.assertTrue(is_placed(self.role)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/roles/test_placement.py b/tests/unit/python/cli/administration/roles/test_placement.py new file mode 100644 index 0000000000..03ca58c399 --- /dev/null +++ b/tests/unit/python/cli/administration/roles/test_placement.py @@ -0,0 +1,489 @@ +from __future__ import annotations + +import re +import shutil +import tempfile +import threading +import unittest +from pathlib import Path +from unittest import mock + +from cli.administration.roles import placement +from cli.administration.roles.marker import MARKER_FILE, is_placed +from cli.administration.roles.placement import clean, pull +from utils.cache.files import read_text +from utils.roles.custom import CustomRoleError +from utils.roles.mapping import ( + ROLE_FILE_META_MAIN, + ROLE_FILE_TASKS_MAIN, + ROLE_FILE_VARS_MAIN, +) + +from ._fixtures import ( + ROLE, + ROLE_PATH, + declaration, + git, + inventory, + local_role, + role_repo, + roles_dir, + write, +) + +OTHER = "web-app-cst-other" +COPY = "web-app-cst-mywork" +LEFT = "left in place, the pull did not place it" + + +class _PullFixture: + """Mixin with a core roles/, a role repository and a pull helper. + + Combined with ``unittest.TestCase`` on each concrete class so the + test-discovery lint sees the ``TestCase`` base directly. + """ + + def setUp(self) -> None: + super().setUp() + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.roles = roles_dir(self.root, "web-app-nextcloud") + self.work = self.root / "build" / "custom-roles" + self.repo = role_repo(self.root) + self.inventories = 0 + + def next_inventory(self) -> Path: + self.inventories += 1 + return self.root / f"inventory-{self.inventories}" + + def pull(self, applications: dict, groups: tuple[str, ...] = (ROLE,)) -> list[str]: + inv = inventory(self.next_inventory(), list(groups), applications) + return pull(inv, self.roles, self.work) + + def pull_yaml(self, devices: str, host_vars: str) -> list[str]: + base = self.next_inventory() + write(base / "host_vars/localhost.yml", host_vars) + return pull(write(base / "devices.yml", devices), self.roles, self.work) + + def placed(self) -> list[str]: + return sorted(path.name for path in self.roles.iterdir()) + + def leftovers(self) -> list[Path]: + if not self.work.exists(): + return [] + return [path for path in self.work.iterdir() if path.is_dir()] + + def tag(self, name: str) -> None: + git(self.repo, "add", "-A") + git(self.repo, "commit", "-q", "-m", name) + git(self.repo, "tag", name) + + +class TestPullPlacement(_PullFixture, unittest.TestCase): + def test_role_is_placed_at_its_tag_with_the_resolved_commit(self): + lines = self.pull({ROLE: declaration(str(self.repo))}) + self.assertEqual( + "release: v1\n", read_text(str(self.roles / ROLE / ROLE_FILE_TASKS_MAIN)) + ) + self.assertTrue(is_placed(self.roles / ROLE)) + self.assertRegex( + lines[0], rf"^{ROLE}: .* @ v1\.0\.0 \(commit [0-9a-f]{{40}}\)$" + ) + + def test_placed_role_carries_no_git_metadata(self): + self.pull({ROLE: declaration(str(self.repo), path=ROLE_PATH)}) + self.assertFalse((self.roles / ROLE / ".git").exists()) + + def test_local_working_tree_is_placed_without_a_version(self): + write(self.repo / ROLE_PATH / ROLE_FILE_TASKS_MAIN, "release: uncommitted\n") + self.pull({ROLE: declaration(str(self.repo), version=None)}) + self.assertEqual( + "release: uncommitted\n", + read_text(str(self.roles / ROLE / ROLE_FILE_TASKS_MAIN)), + ) + + def test_pull_again_replaces_the_placed_content(self): + self.pull({ROLE: declaration(str(self.repo))}) + write(self.roles / ROLE / "stale.yml", "stale: true\n") + self.pull({ROLE: declaration(str(self.repo))}) + self.assertFalse((self.roles / ROLE / "stale.yml").exists()) + self.assertTrue((self.roles / ROLE / ROLE_FILE_VARS_MAIN).is_file()) + + def test_role_the_inventory_no_longer_declares_is_removed(self): + self.pull({ROLE: declaration(str(self.repo))}) + lines = self.pull({}, groups=()) + self.assertEqual(["web-app-nextcloud"], self.placed()) + self.assertIn(f"{ROLE}: removed, the inventory no longer declares it", lines) + + def test_in_tree_roles_are_never_touched(self): + self.pull({ROLE: declaration(str(self.repo))}) + self.assertEqual([ROLE, "web-app-nextcloud"], self.placed()) + + def test_no_staging_or_leftover_directory_remains(self): + self.pull({ROLE: declaration(str(self.repo))}) + self.pull({ROLE: declaration(str(self.repo))}) + self.assertEqual([ROLE, "web-app-nextcloud"], self.placed()) + self.assertEqual([], self.leftovers()) + + def test_undeclared_directory_the_pull_did_not_place_is_left_alone(self): + write(self.roles / OTHER / "keep.yml", "keep: true\n") + lines = self.pull({ROLE: declaration(str(self.repo))}) + self.assertTrue((self.roles / OTHER / "keep.yml").is_file()) + self.assertIn(f"{OTHER}: {LEFT}", lines) + + +class TestPullRefusal(_PullFixture, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + self.pull({ROLE: declaration(str(self.repo))}) + write(self.roles / ROLE / "sentinel.yml", "placed: true\n") + + def assert_untouched(self) -> None: + self.assertTrue((self.roles / ROLE / "sentinel.yml").is_file()) + self.assertEqual([ROLE, "web-app-nextcloud"], self.placed()) + self.assertEqual([], self.leftovers()) + + def test_branch_as_version_is_refused_before_anything_changes(self): + with self.assertRaisesRegex(CustomRoleError, "'feature' names a branch"): + self.pull({ROLE: declaration(str(self.repo), version="feature")}) + self.assert_untouched() + + def test_application_id_other_than_the_group_names_both(self): + other = role_repo(self.root / "other", application_id="web-app-demo") + with self.assertRaisesRegex( + CustomRoleError, + f"application_id is 'web-app-demo', but the group is '{ROLE}'", + ): + self.pull({ROLE: declaration(str(other))}) + self.assert_untouched() + + def test_missing_application_id_is_refused(self): + write(self.repo / ROLE_PATH / ROLE_FILE_VARS_MAIN, "other: value\n") + with self.assertRaisesRegex(CustomRoleError, "application_id is None"): + self.pull({ROLE: declaration(str(self.repo), version=None)}) + self.assert_untouched() + + def test_source_without_meta_main_is_refused(self): + (self.repo / ROLE_PATH / ROLE_FILE_META_MAIN).unlink() + with self.assertRaisesRegex(CustomRoleError, "no role directory"): + self.pull({ROLE: declaration(str(self.repo), version=None)}) + self.assert_untouched() + + def test_invalid_declaration_is_refused_before_anything_changes(self): + with self.assertRaisesRegex(CustomRoleError, "source.path is missing"): + self.pull( + { + ROLE: { + "custom": True, + "source": {"url": str(self.repo), "version": "v1.0.0"}, + } + } + ) + self.assert_untouched() + + def test_path_that_is_no_directory_in_the_source_is_refused(self): + with self.assertRaisesRegex(CustomRoleError, "source.path is not a directory"): + self.pull({ROLE: declaration(str(self.repo), path=f"absent/{ROLE}")}) + self.assert_untouched() + + def test_local_source_inside_its_placement_is_refused(self): + with self.assertRaisesRegex(CustomRoleError, "never deletes its own source"): + self.pull( + {ROLE: declaration(str(self.root), version=None, path=f"roles/{ROLE}")} + ) + self.assert_untouched() + + def test_a_failing_role_leaves_every_placed_role_unchanged(self): + broken = { + "custom": True, + "source": {"url": str(self.root / "absent"), "path": f"x/{OTHER}"}, + } + with self.assertRaisesRegex(CustomRoleError, OTHER): + self.pull( + {ROLE: declaration(str(self.repo)), OTHER: broken}, groups=(ROLE, OTHER) + ) + self.assert_untouched() + + def test_missing_inventory_is_refused(self): + with self.assertRaisesRegex(CustomRoleError, "neither a file nor a directory"): + pull(self.root / "absent/devices.yml", self.roles, self.work) + self.assert_untouched() + + def test_unparsable_vars_file_stops_the_pull_naming_it(self): + inv = inventory(self.next_inventory(), [], {}) + broken = write(inv.parent / "group_vars/all.yml", "applications:\n x: [open\n") + with self.assertRaisesRegex( + CustomRoleError, rf"{re.escape(str(broken))}: cannot read" + ): + pull(inv, self.roles, self.work) + self.assert_untouched() + + def test_vars_file_that_is_no_utf8_stops_the_pull_naming_it(self): + inv = inventory(self.next_inventory(), [], {}) + latin = inv.parent / "group_vars/all.yml" + latin.parent.mkdir() + latin.write_bytes("applications: {caf\xe9: {}}\n".encode("latin-1")) + with self.assertRaisesRegex( + CustomRoleError, rf"{re.escape(str(latin))}: cannot read" + ): + pull(inv, self.roles, self.work) + self.assert_untouched() + + def test_inventory_file_that_is_no_utf8_stops_the_pull_naming_it(self): + inv = inventory(self.next_inventory(), [], {}) + inv.write_bytes("all:\n hosts:\n caf\xe9: {}\n".encode("latin-1")) + with self.assertRaisesRegex( + CustomRoleError, rf"{re.escape(str(inv))}: cannot read" + ): + pull(inv, self.roles, self.work) + self.assert_untouched() + + +class TestPullInventoryForms(_PullFixture, unittest.TestCase): + def test_directory_inventory_is_read_like_a_file_inventory(self): + inv = inventory( + self.next_inventory(), [ROLE], {ROLE: declaration(str(self.repo))} + ) + pull(inv.parent, self.roles, self.work) + self.assertTrue(is_placed(self.roles / ROLE)) + + def test_group_of_a_hosts_file_in_a_directory_inventory_needs_custom_true(self): + base = self.next_inventory() + write(base / "hosts", f"[{ROLE}]\nlocalhost\n") + write(base / "README.md", "[web-app-cst-ignored]\n") + write(base / "host_vars/localhost.yml", "applications: {}\n") + with self.assertRaises(CustomRoleError) as refused: + pull(base, self.roles, self.work) + self.assertIn(f"{ROLE}: inventory group without", str(refused.exception)) + self.assertNotIn("web-app-cst-ignored", str(refused.exception)) + + def test_host_list_declares_nothing_and_changes_nothing(self): + self.pull({ROLE: declaration(str(self.repo))}) + self.assertEqual([], pull(Path("localhost,"), self.roles, self.work)) + self.assertTrue(is_placed(self.roles / ROLE)) + + +class TestPullAnsibleTags(_PullFixture, unittest.TestCase): + DEVICES = ( + "all:\n" + " hosts:\n" + " localhost:\n" + " motd: !unsafe '{{ literal }}'\n" + " children:\n" + f" {ROLE}:\n" + " hosts:\n" + " localhost: {}\n" + ) + + def host_vars(self, url: str) -> str: + return ( + "secret: !vault |\n" + " $ANSIBLE_VAULT;1.1;AES256\n" + " 6162\n" + "applications:\n" + f" {ROLE}:\n" + " custom: true\n" + " source:\n" + f" url: {url}\n" + " version: v1.0.0\n" + f" path: {ROLE_PATH}\n" + ) + + def test_tagged_values_elsewhere_in_the_inventory_keep_the_pull_working(self): + self.pull_yaml(self.DEVICES, self.host_vars(str(self.repo))) + self.assertTrue(is_placed(self.roles / ROLE)) + + def test_tagged_source_value_is_refused_like_a_jinja_value(self): + with self.assertRaisesRegex( + CustomRoleError, + f"{ROLE}: applications.{ROLE}.source.url holds a !unsafe value", + ): + self.pull_yaml(self.DEVICES, self.host_vars(f"!unsafe '{self.repo}'")) + self.assertEqual(["web-app-nextcloud"], self.placed()) + + +class TestPullOwnership(_PullFixture, unittest.TestCase): + def test_symbolic_link_under_a_declared_name_is_refused_and_kept(self): + target = self.root / "elsewhere" + write(target / "keep.yml", "keep: true\n") + (self.roles / ROLE).symlink_to(target) + with self.assertRaisesRegex( + CustomRoleError, f"{ROLE}: .* is a symbolic link .* remove the link" + ): + self.pull({ROLE: declaration(str(self.repo))}) + self.assertTrue((self.roles / ROLE).is_symlink()) + self.assertTrue((target / "keep.yml").is_file()) + + def test_hand_placed_directory_under_a_declared_name_is_refused_and_kept(self): + write(self.roles / ROLE / "mine.yml", "mine: true\n") + with self.assertRaisesRegex( + CustomRoleError, f"{ROLE}: .* was not placed by a pull" + ): + self.pull({ROLE: declaration(str(self.repo))}) + self.assertTrue((self.roles / ROLE / "mine.yml").is_file()) + self.assertFalse((self.roles / ROLE / MARKER_FILE).exists()) + + def test_copy_of_a_placed_role_is_left_in_place_and_reported(self): + self.pull({ROLE: declaration(str(self.repo))}) + shutil.copytree(self.roles / ROLE, self.roles / COPY) + lines = self.pull({}, groups=()) + self.assertEqual([COPY, "web-app-nextcloud"], self.placed()) + self.assertIn(f"{COPY}: {LEFT}", lines) + + def test_declared_name_that_meets_a_copy_is_refused_and_kept(self): + self.pull({ROLE: declaration(str(self.repo))}) + shutil.copytree(self.roles / ROLE, self.roles / COPY) + write(self.roles / COPY / "mine.yml", "mine: true\n") + checkout = local_role(self.root, COPY) + mine = declaration(str(checkout), version=None, path=f"ansible/roles/{COPY}") + with self.assertRaisesRegex( + CustomRoleError, f"{COPY}: .* was not placed by a pull" + ): + self.pull({ROLE: declaration(str(self.repo)), COPY: mine}, (ROLE, COPY)) + self.assertTrue((self.roles / COPY / "mine.yml").is_file()) + + +class TestPullMarker(_PullFixture, unittest.TestCase): + def setUp(self) -> None: + super().setUp() + self.in_tree = write( + self.roles / "web-app-nextcloud" / ROLE_FILE_TASKS_MAIN, "in-tree: true\n" + ) + + def assert_in_tree_untouched(self) -> None: + text = self.in_tree.read_text(encoding="utf-8") # nocheck: cache-read tempdir + self.assertEqual("in-tree: true\n", text) + self.assertEqual(["web-app-nextcloud"], self.placed()) + self.assertEqual([], self.leftovers()) + + def test_marker_link_in_a_local_source_is_refused_and_never_followed(self): + checkout = local_role(self.root, ROLE) + (checkout / "ansible/roles" / ROLE / MARKER_FILE).symlink_to(self.in_tree) + with self.assertRaisesRegex( + CustomRoleError, f"{ROLE}: .*{MARKER_FILE} is a symbolic link" + ): + self.pull( + { + ROLE: declaration( + str(checkout), version=None, path=f"ansible/roles/{ROLE}" + ) + } + ) + self.assert_in_tree_untouched() + + def test_relative_marker_link_in_a_tag_is_refused(self): + (self.repo / ROLE_PATH / MARKER_FILE).symlink_to(ROLE_FILE_TASKS_MAIN) + self.tag("v2.0.0") + with self.assertRaisesRegex( + CustomRoleError, f"{ROLE}: .*{MARKER_FILE} is a symbolic link" + ): + self.pull({ROLE: declaration(str(self.repo), version="v2.0.0")}) + self.assert_in_tree_untouched() + + def test_absolute_link_in_a_tag_is_refused_naming_the_group(self): + (self.repo / ROLE_PATH / MARKER_FILE).symlink_to(self.in_tree) + self.tag("v2.0.0") + with self.assertRaisesRegex(CustomRoleError, f"^{ROLE}: .*absolute"): + self.pull({ROLE: declaration(str(self.repo), version="v2.0.0")}) + self.assert_in_tree_untouched() + + +class TestPullCommit(_PullFixture, unittest.TestCase): + def test_interrupt_while_deleting_the_old_copy_keeps_the_new_one(self): + self.pull({ROLE: declaration(str(self.repo))}) + write(self.roles / ROLE / "stale.yml", "stale: true\n") + rmtree = shutil.rmtree + + def interrupted(path, *args, **kwargs): + if ".retired." in str(path): + raise KeyboardInterrupt + return rmtree(path, *args, **kwargs) + + with ( + mock.patch.object(placement.shutil, "rmtree", interrupted), + self.assertRaises(KeyboardInterrupt), + ): + self.pull({ROLE: declaration(str(self.repo))}) + self.assertTrue(is_placed(self.roles / ROLE)) + self.assertFalse((self.roles / ROLE / "stale.yml").exists()) + self.pull({ROLE: declaration(str(self.repo))}) + self.assertEqual([], self.leftovers()) + + def test_directory_that_appears_at_a_declared_name_during_the_pull_is_kept(self): + stage = placement.stage + + def stage_beside_a_hand_placed_copy(group, source, target): + write(self.roles / group / "mine.yml", "mine: true\n") + return stage(group, source, target) + + with ( + mock.patch.object(placement, "stage", stage_beside_a_hand_placed_copy), + self.assertRaisesRegex( + CustomRoleError, f"{ROLE}: .* was not placed by a pull" + ), + ): + self.pull({ROLE: declaration(str(self.repo))}) + self.assertTrue((self.roles / ROLE / "mine.yml").is_file()) + self.assertFalse(is_placed(self.roles / ROLE)) + self.assertEqual([], self.leftovers()) + + def test_clean_waits_until_a_running_pull_has_finished(self): + events: list[tuple[str, object]] = [] + cleaner = threading.Thread( + target=lambda: events.append(("cleaned", clean(self.roles, self.work))) + ) + stage = placement.stage + + def stage_while_a_clean_starts(group, source, target): + cleaner.start() + cleaner.join(timeout=0.5) + events.append(("clean still waiting", cleaner.is_alive())) + return stage(group, source, target) + + with mock.patch.object(placement, "stage", stage_while_a_clean_starts): + self.pull({ROLE: declaration(str(self.repo))}) + cleaner.join(timeout=30) + self.assertEqual(("clean still waiting", True), events[0]) + self.assertEqual("cleaned", events[1][0]) + self.assertEqual(["web-app-nextcloud"], self.placed()) + + +class TestClean(_PullFixture, unittest.TestCase): + def test_removes_only_the_roles_the_pull_placed_and_reports_the_rest(self): + checkout = local_role(self.root, OTHER) + self.pull( + { + ROLE: declaration(str(self.repo)), + OTHER: declaration( + str(checkout), version=None, path=f"ansible/roles/{OTHER}" + ), + }, + groups=(ROLE, OTHER), + ) + shutil.copytree(self.roles / ROLE, self.roles / COPY) + write(self.roles / "web-app-cst-hand" / "mine.yml", "mine: true\n") + target = self.root / "elsewhere" + write(target / "keep.yml", "keep: true\n") + (self.roles / "web-app-cst-link").symlink_to(target) + lines = clean(self.roles, self.work) + self.assertEqual( + [ + f"{ROLE}: removed", + f"web-app-cst-hand: {LEFT}", + f"web-app-cst-link: {LEFT}", + f"{COPY}: {LEFT}", + f"{OTHER}: removed", + ], + lines, + ) + self.assertEqual( + ["web-app-cst-hand", "web-app-cst-link", COPY, "web-app-nextcloud"], + self.placed(), + ) + self.assertTrue((target / "keep.yml").is_file()) + self.assertEqual([], self.leftovers()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/cli/administration/roles/test_source.py b/tests/unit/python/cli/administration/roles/test_source.py new file mode 100644 index 0000000000..e37dbe2f1b --- /dev/null +++ b/tests/unit/python/cli/administration/roles/test_source.py @@ -0,0 +1,186 @@ +from __future__ import annotations + +import re +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from cli.administration.roles import source as source_module +from cli.administration.roles.declaration import Source +from cli.administration.roles.source import check, stage +from utils.cache.files import read_text +from utils.roles.custom import CustomRoleError +from utils.roles.mapping import ROLE_FILE_TASKS_MAIN + +from ._fixtures import ROLE, ROLE_PATH, git, role_repo, roles_dir, write + + +class _SourceFixture: + """Mixin with a core roles/ and a role repository. + + Combined with ``unittest.TestCase`` on each concrete class so the + test-discovery lint sees the ``TestCase`` base directly. + """ + + def setUp(self) -> None: + super().setUp() + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.roles = roles_dir(self.root) + self.repo = role_repo(self.root) + + def check(self, source: Source, placements: tuple[Path, ...] = ()) -> None: + check(ROLE, source, list(placements), self.roles) + + +class TestCheckVersion(_SourceFixture, unittest.TestCase): + def test_tag_is_accepted(self): + self.check(Source(str(self.repo), "v1.0.0", ROLE_PATH)) + + def test_full_commit_sha_is_accepted(self): + sha = git(self.repo, "rev-parse", "v1.0.0").strip() + self.check(Source(str(self.repo), sha, ROLE_PATH)) + + def test_full_commit_sha_needs_no_ref_lookup(self): + self.check(Source("https://example.invalid/widgets.git", "a" * 40, ROLE_PATH)) + + def test_branch_is_refused(self): + with self.assertRaisesRegex( + CustomRoleError, f"{ROLE}: source.version 'feature' names a branch" + ): + self.check(Source(str(self.repo), "feature", ROLE_PATH)) + + def test_abbreviated_sha_is_refused(self): + sha = git(self.repo, "rev-parse", "--short", "v1.0.0").strip() + with self.assertRaisesRegex( + CustomRoleError, "neither a tag nor a full commit SHA" + ): + self.check(Source(str(self.repo), sha, ROLE_PATH)) + + def test_unknown_tag_is_refused(self): + with self.assertRaisesRegex(CustomRoleError, "'v9.9.9' is neither a tag"): + self.check(Source(str(self.repo), "v9.9.9", ROLE_PATH)) + + +class TestCheckLocalSource(_SourceFixture, unittest.TestCase): + def test_missing_directory_is_refused(self): + with self.assertRaisesRegex(CustomRoleError, "is not a directory"): + self.check(Source(str(self.root / "absent"), None, ROLE_PATH)) + + def test_own_placement_directory_is_refused_naming_the_path(self): + (self.roles / ROLE).mkdir() + placement = re.escape(str((self.roles / ROLE).resolve())) + with self.assertRaisesRegex( + CustomRoleError, f"{placement} lies in the placement directory" + ): + self.check(Source(str(self.root), None, f"roles/{ROLE}")) + + def test_another_placement_is_refused(self): + other = self.roles / "web-app-cst-other" + other.mkdir() + with self.assertRaisesRegex(CustomRoleError, "never deletes its own source"): + self.check( + Source(str(self.root), None, f"roles/{other.name}/{ROLE}"), (other,) + ) + + def test_placement_reached_through_a_symlink_is_refused(self): + (self.roles / ROLE).symlink_to(self.repo / ROLE_PATH) + with self.assertRaisesRegex(CustomRoleError, "never deletes its own source"): + self.check(Source(str(self.repo), None, ROLE_PATH)) + + def test_source_through_a_symlinked_checkout_is_refused(self): + alias = self.root / "alias" + alias.symlink_to(self.root) + with self.assertRaisesRegex(CustomRoleError, "never deletes its own source"): + self.check(Source(str(alias), None, f"roles/{ROLE}")) + + def test_checkout_outside_roles_is_accepted(self): + self.check(Source(str(self.repo), None, ROLE_PATH)) + + +class TestStage(_SourceFixture, unittest.TestCase): + def test_tag_stages_only_the_role_path_at_that_tag(self): + target = self.root / "staged" + origin = stage(ROLE, Source(str(self.repo), "v1.0.0", ROLE_PATH), target) + sha = git(self.repo, "rev-parse", "v1.0.0^{commit}").strip() + self.assertEqual("release: v1\n", read_text(str(target / ROLE_FILE_TASKS_MAIN))) + self.assertFalse((target / "README.md").exists()) + self.assertIn(f"(commit {sha})", origin) + + def test_full_commit_sha_is_staged(self): + sha = git(self.repo, "rev-parse", "v1.0.0^{commit}").strip() + target = self.root / "staged" + stage(ROLE, Source(str(self.repo), sha, ROLE_PATH), target) + self.assertEqual("release: v1\n", read_text(str(target / ROLE_FILE_TASKS_MAIN))) + + def test_local_directory_without_version_is_its_working_tree(self): + write(self.repo / ROLE_PATH / ROLE_FILE_TASKS_MAIN, "release: uncommitted\n") + (self.repo / ROLE_PATH / "__pycache__").mkdir() + target = self.root / "staged" + origin = stage(ROLE, Source(str(self.repo), None, ROLE_PATH), target) + self.assertEqual( + "release: uncommitted\n", read_text(str(target / ROLE_FILE_TASKS_MAIN)) + ) + self.assertFalse((target / "__pycache__").exists()) + self.assertIn("(working tree)", origin) + + def test_path_that_is_a_file_is_refused(self): + with self.assertRaisesRegex(CustomRoleError, "source.path is not a directory"): + stage(ROLE, Source(str(self.repo), "v1.0.0", "README.md"), self.root / "s") + + def test_missing_path_is_refused(self): + with self.assertRaisesRegex(CustomRoleError, "source.path is not a directory"): + stage( + ROLE, + Source(str(self.repo), "v1.0.0", f"absent/{ROLE}"), + self.root / "s", + ) + + def test_failed_fetch_names_the_group(self): + with self.assertRaisesRegex( + CustomRoleError, f"{ROLE}: git fetch of v1.0.0 failed" + ): + stage( + ROLE, + Source(str(self.root / "absent"), "v1.0.0", ROLE_PATH), + self.root / "staged", + ) + + +class TestGitNeverPrompts(unittest.TestCase): + def test_git_runs_detached_without_a_prompt_or_askpass(self): + failed = subprocess.CompletedProcess( + ["git"], 128, stdout=b"", stderr=b"fatal: could not read Username" + ) + source = Source("git@example.invalid:acme/widgets.git", "v1.0.0", ROLE_PATH) + with ( + tempfile.TemporaryDirectory() as tmp, + mock.patch.dict( + "os.environ", + { + "GIT_ASKPASS": "/bin/askpass", + "SSH_ASKPASS": "/bin/askpass", + "SSH_AUTH_SOCK": "/run/agent.sock", + }, + ), + mock.patch.object( + source_module.subprocess, "run", return_value=failed + ) as run, + self.assertRaisesRegex(CustomRoleError, "could not read Username"), + ): + stage(ROLE, source, Path(tmp) / "staged") + kwargs = run.call_args.kwargs + self.assertEqual("0", kwargs["env"]["GIT_TERMINAL_PROMPT"]) + self.assertEqual("never", kwargs["env"]["SSH_ASKPASS_REQUIRE"]) + self.assertNotIn("GIT_ASKPASS", kwargs["env"]) + self.assertNotIn("SSH_ASKPASS", kwargs["env"]) + self.assertEqual("/run/agent.sock", kwargs["env"]["SSH_AUTH_SOCK"]) + self.assertTrue(kwargs["start_new_session"]) + self.assertEqual(subprocess.DEVNULL, kwargs["stdin"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/action/test_package_install.py b/tests/unit/python/plugins/action/test_package_install.py index 765211c548..373dab2db6 100644 --- a/tests/unit/python/plugins/action/test_package_install.py +++ b/tests/unit/python/plugins/action/test_package_install.py @@ -1,11 +1,28 @@ import unittest import unittest.mock as mock +from typing import ClassVar -from ansible.errors import AnsibleActionFail +from ansible.errors import AnsibleActionFail, AnsibleConnectionFailure +from ansible.plugins.action import ActionBase from ansible.plugins.loader import become_loader, shell_loader from plugins.action.package_install import ActionModule -from utils.packages.calls import GENERIC_PACKAGE, ModuleCall, RetryPolicy +from utils.packages.calls import ( + GENERIC_PACKAGE, + STATE_ABSENT, + STATE_PRESENT, + ModuleCall, + RetryPolicy, + package_call, +) +from utils.packages.outcome import aggregate +from utils.packages.schema import PackageSpec + +QUERY = "ansible.builtin.command" + + +def _modules(execute) -> list[str]: + return [call.kwargs["module_name"] for call in execute.call_args_list] def _action(args) -> ActionModule: @@ -238,6 +255,170 @@ class TestTargetFacts(unittest.TestCase): self.assertIn("localhost", str(caught.exception)) +class TestRunMergesPlainPlans(unittest.TestCase): + FACTS: ClassVar[dict[str, str]] = { + "distribution": "Debian", + "os_family": "Debian", + "pkg_mgr": "apt", + } + + def _run(self, package_ids, specs, query=None): + action = _action({"id": package_ids}) + action._task._role = None + action._task.delegate_to = None + action._connection = mock.Mock(become=None, transport="local") + action._execute_module = mock.Mock( + side_effect=lambda module_name, **_: ( + query or {} if module_name == QUERY else {"changed": False} + ) + ) + registry = { + package_id: mock.Mock(package_id=package_id, role=None, shared=True) + for package_id in package_ids + } + with ( + mock.patch.object(ActionBase, "run", return_value={}), + mock.patch( + "plugins.action.package_install.build_registry", return_value=registry + ), + mock.patch( + "plugins.action.package_install.resolve", + side_effect=lambda declaration, *_: specs[declaration.package_id], + ), + ): + result = action.run(task_vars={"ansible_facts": self.FACTS}) + return action._execute_module, result + + def test_two_repository_ids_cost_one_package_manager_call(self): + execute, _result = self._run( + ["git", "curl"], + {"git": PackageSpec(("git",)), "curl": PackageSpec(("curl",))}, + ) + self.assertEqual(_modules(execute), [QUERY, "apt"]) + self.assertEqual( + execute.call_args.kwargs["module_args"]["name"], ["git", "curl"] + ) + + def test_one_query_covers_the_merged_names_and_skips_the_call(self): + execute, result = self._run( + ["git", "curl"], + {"git": PackageSpec(("git",)), "curl": PackageSpec(("curl",))}, + {"rc": 0, "stdout": "git\tii \ncurl\tii ", "stderr": ""}, + ) + self.assertEqual(_modules(execute), [QUERY]) + self.assertEqual( + execute.call_args.kwargs["module_args"]["argv"][-2:], ["git", "curl"] + ) + self.assertFalse(result["changed"]) + self.assertNotIn("failed", result) + + def test_an_id_without_names_is_reported_skipped(self): + _execute, result = self._run( + ["git", "mhwd"], {"git": PackageSpec(("git",)), "mhwd": PackageSpec(())} + ) + self.assertEqual(result["skipped_ids"], ["mhwd"]) + + +class TestStateAlreadyHeld(unittest.TestCase): + def _attempt(self, names, state, query, pkg_mgr="apt"): + def execute(module_name, **_kwargs): + if module_name != QUERY: + return {"changed": True} + if isinstance(query, Exception): + raise query + return query + + action = _action({}) + action._connection = mock.Mock(become=None, transport="local") + action._execute_module = mock.Mock(side_effect=execute) + result = action._attempt(package_call(names, state), {}, {"pkg_mgr": pkg_mgr}) + return action._execute_module, result + + def test_all_installed_skips_the_package_manager(self): + execute, result = self._attempt( + ["git", "curl"], + STATE_PRESENT, + {"rc": 0, "stdout": "git\tii \ncurl\tii ", "stderr": ""}, + ) + self.assertEqual(_modules(execute), [QUERY]) + self.assertFalse(result["changed"]) + self.assertEqual(result["module"], GENERIC_PACKAGE) + self.assertFalse(aggregate([result], [], "debian")["changed"]) + + def test_the_query_runs_without_a_shell_or_variable_expansion(self): + execute, _result = self._attempt( + ["git"], STATE_PRESENT, {"rc": 0, "stdout": "git\tii ", "stderr": ""} + ) + args = execute.call_args.kwargs["module_args"] + self.assertEqual(args["argv"][-1], "git") + self.assertFalse(args["expand_argument_vars"]) + + def test_one_missing_name_runs_the_package_manager(self): + execute, result = self._attempt( + ["git", "curl"], + STATE_PRESENT, + { + "rc": 1, + "stdout": "git\tii ", + "stderr": "dpkg-query: no packages found matching curl", + }, + ) + self.assertEqual(_modules(execute), [QUERY, "apt"]) + self.assertTrue(result["changed"]) + + def test_a_failing_query_runs_the_package_manager(self): + execute, _result = self._attempt( + ["git"], + STATE_PRESENT, + {"rc": 2, "stdout": "", "stderr": "dpkg-query: error", "failed": True}, + ) + self.assertEqual(_modules(execute), [QUERY, "apt"]) + + def test_an_unexpected_answer_runs_the_package_manager(self): + execute, _result = self._attempt( + ["git"], STATE_PRESENT, {"rc": 0, "stdout": "garbage", "stderr": ""} + ) + self.assertEqual(_modules(execute), [QUERY, "apt"]) + + def test_a_raising_query_runs_the_package_manager(self): + execute, _result = self._attempt( + ["git"], STATE_PRESENT, AnsibleConnectionFailure("gone") + ) + self.assertEqual(_modules(execute), [QUERY, "apt"]) + + def test_a_name_that_is_not_plain_is_never_queried(self): + execute, _result = self._attempt(["nginx=1.24"], STATE_PRESENT, {}) + self.assertEqual(_modules(execute), ["apt"]) + + def test_absent_with_no_name_installed_skips_the_package_manager(self): + execute, result = self._attempt( + ["postfix", "postfix-lmdb"], + STATE_ABSENT, + { + "rc": 1, + "stdout": "", + "stderr": "error: package 'postfix' was not found\n" + "error: package 'postfix-lmdb' was not found", + }, + pkg_mgr="pacman", + ) + self.assertEqual(_modules(execute), [QUERY]) + self.assertFalse(result["changed"]) + + def test_absent_with_one_name_installed_runs_the_package_manager(self): + execute, _result = self._attempt( + ["postfix", "postfix-lmdb"], + STATE_ABSENT, + { + "rc": 1, + "stdout": "postfix\npackage postfix-lmdb is not installed", + "stderr": "", + }, + pkg_mgr="dnf", + ) + self.assertEqual(_modules(execute), [QUERY, "dnf"]) + + class TestAttempt(unittest.TestCase): def _action_with(self, results): action = _action({}) diff --git a/tests/unit/python/plugins/filter/test_seaweedfs.py b/tests/unit/python/plugins/filter/test_seaweedfs.py index 0d4511b33a..df539149c3 100644 --- a/tests/unit/python/plugins/filter/test_seaweedfs.py +++ b/tests/unit/python/plugins/filter/test_seaweedfs.py @@ -1,15 +1,73 @@ +import json import unittest +from ansible.errors import AnsibleFilterError + from plugins.filter.seaweedfs import ( + ANONYMOUS_DENY_SID, MIN_FREE_SPACE_VOLUMES, VOLUME_GROW_BATCH, VOLUME_SIZE_LIMIT_MB, min_free_space, + seaweedfs_anonymous_deny_policy, + seaweedfs_bucket_names, + seaweedfs_bucket_policy_target, seaweedfs_command, seaweedfs_sidecar_script, + seaweedfs_stored_bucket_policy, volume_slots, ) +FOREIGN_STATEMENT = { + "Sid": "OperatorReadOnly", + "Effect": "Allow", + "Principal": {"AWS": ["arn:aws:iam::000000000000:user/auditor"]}, + "Action": "s3:GetObject", + "Resource": "arn:aws:s3:::mastodon/*", +} + +NO_SUCH_BUCKET_POLICY_XML = ( + '\n' + "NoSuchBucketPolicy" + "The bucket policy does not exist" + "/mastodon1" + "mastodon" +) + +NO_SUCH_BUCKET_XML = ( + '\n' + "NoSuchBucket" + "The specified bucket does not exist" + "/mastodon1" + "mastodon" +) + + +def _deny(bucket="mastodon"): + (statement,) = seaweedfs_anonymous_deny_policy(bucket)["Statement"] + return statement + + +def _go_marshal(value): + """Mirror how SeaweedFS 4.51 re-serialises a stored policy. + + Args: + value: policy fragment; every one-element string list collapses to + its string, as ``StringOrStringSlice.MarshalJSON`` does. + """ + if isinstance(value, dict): + return {key: _go_marshal(item) for key, item in value.items()} + if isinstance(value, list) and len(value) == 1 and isinstance(value[0], str): + return value[0] + if isinstance(value, list): + return [_go_marshal(item) for item in value] + return value + + +def _curl_output(body, status): + return f"{body}\n{status}" + + BASE = [ "server", "-dir=/data", @@ -92,5 +150,141 @@ class TestSeaweedfsSidecarScriptFilter(unittest.TestCase): self.assertNotIn("$", seaweedfs_sidecar_script("app", 8333, "AK", "SK")) +class TestSeaweedfsAnonymousDenyPolicyFilter(unittest.TestCase): + def test_uses_the_only_policy_version_seaweedfs_accepts(self): + self.assertEqual(seaweedfs_anonymous_deny_policy("b")["Version"], "2012-10-17") + + def test_is_an_explicit_deny_for_every_principal(self): + statement = _deny() + self.assertEqual(statement["Effect"], "Deny") + self.assertEqual(statement["Principal"], "*") + + def test_spares_requests_that_carry_a_signed_username(self): + self.assertEqual(_deny()["Condition"], {"Null": {"aws:username": "true"}}) + + def test_covers_reads_and_listings_but_no_writes(self): + self.assertEqual(_deny()["Action"], ["s3:Get*", "s3:List*"]) + + def test_scopes_the_bucket_and_its_objects(self): + self.assertEqual( + _deny("pixelfed")["Resource"], + ["arn:aws:s3:::pixelfed", "arn:aws:s3:::pixelfed/*"], + ) + + def test_carries_the_sid_the_converge_step_owns(self): + self.assertEqual(_deny()["Sid"], ANONYMOUS_DENY_SID) + + def test_survives_the_seaweedfs_round_trip_unchanged(self): + policy = seaweedfs_anonymous_deny_policy("mastodon") + self.assertEqual(_go_marshal(json.loads(json.dumps(policy))), policy) + + +class TestSeaweedfsBucketNamesFilter(unittest.TestCase): + def test_reads_every_listed_bucket(self): + output = ( + " mastodon\tsize:0\tlogical:0\tchunk:0\n" + ' pixelfed\tsize:42\tlogical:40\tchunk:3\towner:"pixelfed"\n' + ) + self.assertEqual(seaweedfs_bucket_names(output), ["mastodon", "pixelfed"]) + + def test_reads_a_bucket_printed_after_the_shell_prompt(self): + output = "> " + " mastodon\tsize:0\tlogical:0\tchunk:0\n> " + self.assertEqual(seaweedfs_bucket_names(output), ["mastodon"]) + + def test_a_name_inside_a_longer_one_is_not_listed(self): + names = seaweedfs_bucket_names(" mastodon-media\tsize:0\tlogical:0\tchunk:0\n") + self.assertNotIn("mastodon", names) + + def test_an_empty_listing_yields_no_bucket(self): + self.assertEqual(seaweedfs_bucket_names("> "), []) + + +class TestSeaweedfsStoredBucketPolicyFilter(unittest.TestCase): + def test_a_stored_policy_is_returned(self): + policy = seaweedfs_anonymous_deny_policy("mastodon") + output = _curl_output(json.dumps(policy, separators=(",", ":")) + "\n", 200) + self.assertEqual(seaweedfs_stored_bucket_policy(output), policy) + + def test_no_such_bucket_policy_reads_as_no_policy(self): + output = _curl_output(NO_SUCH_BUCKET_POLICY_XML, 404) + self.assertEqual(seaweedfs_stored_bucket_policy(output), {}) + + def test_a_missing_bucket_is_refused(self): + output = _curl_output(NO_SUCH_BUCKET_XML, 404) + self.assertIsNone(seaweedfs_stored_bucket_policy(output)) + + def test_access_denied_is_refused(self): + output = _curl_output("AccessDenied", 403) + self.assertIsNone(seaweedfs_stored_bucket_policy(output)) + + def test_a_server_error_is_refused(self): + output = _curl_output("InternalError", 500) + self.assertIsNone(seaweedfs_stored_bucket_policy(output)) + + def test_a_404_without_the_policy_code_is_refused(self): + self.assertIsNone(seaweedfs_stored_bucket_policy(_curl_output("", 404))) + + +class TestSeaweedfsBucketPolicyTargetFilter(unittest.TestCase): + def _policy(self, *statements): + return {"Version": "2012-10-17", "Statement": list(statements)} + + def test_a_private_bucket_without_policy_gets_the_deny(self): + self.assertEqual( + seaweedfs_bucket_policy_target({}, "mastodon", False), + seaweedfs_anonymous_deny_policy("mastodon"), + ) + + def test_a_private_bucket_with_the_deny_stays_as_stored(self): + stored = _go_marshal(seaweedfs_anonymous_deny_policy("mastodon")) + self.assertEqual( + seaweedfs_bucket_policy_target(stored, "mastodon", False), stored + ) + + def test_a_private_bucket_keeps_a_foreign_statement_next_to_the_deny(self): + stored = self._policy(FOREIGN_STATEMENT, _deny()) + self.assertEqual( + seaweedfs_bucket_policy_target(stored, "mastodon", False), stored + ) + + def test_a_private_bucket_with_only_a_foreign_statement_gains_the_deny(self): + stored = self._policy(FOREIGN_STATEMENT) + self.assertEqual( + seaweedfs_bucket_policy_target(stored, "mastodon", False), + self._policy(FOREIGN_STATEMENT, _deny()), + ) + + def test_a_stale_deny_is_replaced_by_the_current_one(self): + stale = {**_deny(), "Action": "s3:GetObject"} + self.assertEqual( + seaweedfs_bucket_policy_target(self._policy(stale), "mastodon", False), + self._policy(_deny()), + ) + + def test_a_public_bucket_without_policy_stays_without(self): + self.assertEqual(seaweedfs_bucket_policy_target({}, "mastodon", True), {}) + + def test_a_public_bucket_loses_the_deny(self): + stored = seaweedfs_anonymous_deny_policy("mastodon") + self.assertEqual(seaweedfs_bucket_policy_target(stored, "mastodon", True), {}) + + def test_a_public_bucket_loses_a_stale_deny_by_its_sid(self): + stale = {**_deny(), "Action": "s3:GetObject", "Condition": {}} + self.assertEqual( + seaweedfs_bucket_policy_target(self._policy(stale), "mastodon", True), {} + ) + + def test_a_public_bucket_keeps_a_foreign_statement(self): + stored = self._policy(_deny(), FOREIGN_STATEMENT) + self.assertEqual( + seaweedfs_bucket_policy_target(stored, "mastodon", True), + self._policy(FOREIGN_STATEMENT), + ) + + def test_public_must_be_a_bool(self): + with self.assertRaises(AnsibleFilterError): + seaweedfs_bucket_policy_target({}, "mastodon", "False") + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_nginx.py b/tests/unit/python/plugins/lookup/test_nginx.py index 4cf21aa8e2..ad1aaf5c58 100644 --- a/tests/unit/python/plugins/lookup/test_nginx.py +++ b/tests/unit/python/plugins/lookup/test_nginx.py @@ -208,6 +208,43 @@ class TestNginxPathsLookup(unittest.TestCase): protocol="ftp", ) + def test_files_lua_is_one_file_per_domain(self): + with ( + patch( + "plugins.lookup.nginx.get", + side_effect=self._fake_get, + ), + patch( + "plugins.lookup.nginx.get_canonical_volumes", + return_value={}, + ), + patch("plugins.lookup.nginx.lookup_loader") as loader_mock, + ): + loader_mock.get.side_effect = self._loader_get() + out = self.plugin.run( + ["files.lua", "filer.example.com"], + variables=self.variables, + protocol="https", + )[0] + + self.assertEqual(out, "/opt/mock/nginx/conf.d/lua/filer.example.com.lua") + + def test_files_lua_without_domain_raises(self): + with ( + patch( + "plugins.lookup.nginx.get", + side_effect=self._fake_get, + ), + patch( + "plugins.lookup.nginx.get_canonical_volumes", + return_value={}, + ), + patch("plugins.lookup.nginx.lookup_loader") as loader_mock, + self.assertRaises(AnsibleError), + ): + loader_mock.get.side_effect = self._loader_get() + self.plugin.run(["files.lua"], variables=self.variables) + def test_invalid_usage_raises(self): with ( patch( diff --git a/tests/unit/python/plugins/lookup/test_package_batch.py b/tests/unit/python/plugins/lookup/test_package_batch.py new file mode 100644 index 0000000000..207854df7d --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_package_batch.py @@ -0,0 +1,52 @@ +import unittest +from unittest import mock + +from ansible.errors import AnsibleError + +from plugins.lookup.package_batch import LookupModule +from utils.packages.schema import PackagesShapeError + +MODULE = "plugins.lookup.package_batch" + + +class TestPackageBatchLookup(unittest.TestCase): + def _run(self, terms, group_names, closure=None, side_effect=None): + applications = mock.Mock() + applications.run.return_value = [{"web-app-x": {}}] + with ( + mock.patch(f"{MODULE}.lookup_loader.get", return_value=applications), + mock.patch(f"{MODULE}.types_from_group_names", return_value=["server"]), + mock.patch( + f"{MODULE}.deploy_closure", + return_value=closure or {"web-app-x"}, + side_effect=side_effect, + ) as closure_mock, + mock.patch(f"{MODULE}.batch_ids", return_value=["git"]) as ids_mock, + ): + lookup = LookupModule() + result = lookup.run(terms, variables={"group_names": group_names}) + return result, closure_mock, ids_mock + + def test_returns_the_batch_ids_of_the_closure(self): + result, _closure, ids = self._run([["web-app-x"]], ["web-app-x"]) + self.assertEqual(result, [["git"]]) + self.assertEqual(ids.call_args.args[0], {"web-app-x"}) + + def test_nested_and_scalar_terms_become_one_seed_list(self): + _result, closure, _ids = self._run([["web-app-x"], "role-b"], ["web-app-x"]) + self.assertEqual(closure.call_args.args[1], ["web-app-x", "role-b"]) + + def test_the_host_groups_select_types_and_gates(self): + _result, closure, _ids = self._run([["web-app-x"]], ["web-app-x", "servers"]) + self.assertEqual(closure.call_args.kwargs["host_types"], ["server"]) + self.assertEqual( + closure.call_args.kwargs["group_names"], ["web-app-x", "servers"] + ) + + def test_a_registry_error_becomes_an_ansible_error(self): + with self.assertRaises(AnsibleError): + self._run([["web-app-x"]], [], side_effect=PackagesShapeError("broken")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_tls.py b/tests/unit/python/plugins/lookup/test_tls.py index d12abb2b72..2d9c24fe5d 100644 --- a/tests/unit/python/plugins/lookup/test_tls.py +++ b/tests/unit/python/plugins/lookup/test_tls.py @@ -85,6 +85,16 @@ class TestTlsResolveLookup(unittest.TestCase): )[0] self.assertEqual(val, "https://a.example/") + def test_url_origin_is_the_base_url_without_its_trailing_slash(self): + origin, base = ( + self.lookup.run(["web-app-a", want], variables=self.base_vars, mode="app")[ + 0 + ] + for want in ("url.origin", "url.base") + ) + self.assertEqual(origin, "https://a.example") + self.assertEqual(f"{origin}/", base) + def test_protocols_web_path_is_http_for_an_onion_only_app(self): onion = dict(self.base_vars) onion["domains"] = {**self.domains, "web-app-onion": "abc123.onion"} 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 dc94fb3b47..9edbbda07b 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 @@ -6,7 +6,7 @@ import unittest from pathlib import Path from unittest.mock import patch -from utils.cache.yaml import load_yaml, load_yaml_str +from utils.cache.yaml import load_yaml, load_yaml_any, load_yaml_str from . import PROJECT_ROOT @@ -15,6 +15,24 @@ _CA_TRUST = load_yaml(str(PROJECT_ROOT / "group_vars" / "all" / "02_tls.yml"))[ ] CA_CERT_CONTAINER = _CA_TRUST["inject_cert_container"] CA_WRAPPER_CONTAINER = _CA_TRUST["inject_wrapper_container"] +COMPOSE_HANDLERS = PROJECT_ROOT / "roles/sys-svc-compose/handlers/compose.yml" + + +def _flushed_shells(*topics: str) -> list[str]: + """Shell bodies of the compose handlers one flush runs, in run order. + + Args: + topics: the notified listen topics. + + Returns: + the `ansible.builtin.shell` body of every handler listening on any + topic, in definition order. + """ + return [ + handler.get("ansible.builtin.shell", "") + for handler in load_yaml_any(str(COMPOSE_HANDLERS)) + if set(topics) & set(handler["listen"]) + ] def _load_module(rel_path: str, name: str): @@ -960,6 +978,37 @@ class TestComposeCaInject(unittest.TestCase): ["sh", "-lc", 'exec "$$CHESS_ENTRYPOINT_INT"'], ) + def test_render_override_keeps_the_compose_config_escape_of_a_service_command(self): + services = { + "svc": { + "image": "img:1", + "command": ["sh", "-c", 'exec server --pass "$$SERVER_PASSWORD"'], + } + } + service_to_cmd = {"svc": ["docker", "compose", "-p", "p", "-f", "compose.yml"]} + + with patch.object( + self.m, + "gather_image_meta", + return_value={"img:1": (True, ["/entry.sh"], ["serve"], True)}, + ): + doc = self.m.render_override( + services, + service_to_cmd, + cwd=Path("/tmp"), + env={}, + ca_host="/host/ca.crt", + wrapper_host="/host/with-ca-trust.sh", + ca_container=CA_CERT_CONTAINER, + wrapper_container=CA_WRAPPER_CONTAINER, + trust_name="infinito.local", + ) + + self.assertEqual( + doc["services"]["svc"].get("command"), + ["/entry.sh", "sh", "-c", 'exec server --pass "$$SERVER_PASSWORD"'], + ) + 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. @@ -1183,5 +1232,64 @@ class TestComposeCaInject(unittest.TestCase): ) +class TestFirstDeployFlush(unittest.TestCase): + def setUp(self): + self.m = _load_module( + "roles/sys-svc-compose-ca/files/python/compose_ca.py", + "compose_ca_first_deploy_mod", + ) + + def test_compose_up_starts_a_freshly_built_image_behind_the_wrapper(self): + image = "app_custom:1" + built: set[str] = set() + + def fake_run(cmd, *, cwd, env, timeout=None, capture=True): + if cmd[:3] == ["docker", "image", "inspect"]: + if cmd[3] not in built: + return 1, "", f"No such image: {cmd[3]}" + cfg = [{"Config": {"Entrypoint": ["/entry.sh"], "Cmd": ["serve"]}}] + return 0, json.dumps(cfg), "" + if cmd[:5] == ["docker", "run", "--rm", "--entrypoint", "/bin/sh"]: + return 0, "", "" + return 1, "", "unexpected" + + override: dict = {} + started_with = None + for shell in _flushed_shells("compose-build", "compose-up"): + if "compose build" in shell: + built.add(image) + elif "compose_ca_inject_cmd" in shell: + with patch.object(self.m, "run", side_effect=fake_run): + override = self.m.render_override( + {"app": {"image": image, "build": {"context": "."}}}, + {"app": ["docker", "compose", "-p", "p", "-f", "compose.yml"]}, + cwd=Path("/tmp"), + env={}, + ca_host="/host/ca.crt", + wrapper_host="/host/with-ca-trust.sh", + ca_container=CA_CERT_CONTAINER, + wrapper_container=CA_WRAPPER_CONTAINER, + trust_name="infinito.local", + ) + elif "compose up -d --force-recreate" in shell: + started_with = dict(override) + + self.assertIsNotNone(started_with, "the flush never reached compose up") + self.assertIn( + "services", + started_with, + "compose up ran before the CA override was generated", + ) + service = started_with["services"]["app"] + self.assertEqual( + service.get("entrypoint"), + [CA_WRAPPER_CONTAINER], + "compose up started the image this flush built without the CA " + "wrapper: the override was generated before compose build, when " + "the locally built tag could not be inspected yet", + ) + self.assertEqual(service.get("command"), ["/entry.sh", "serve"]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/sys-svc-container/test_mtu_probe.py b/tests/unit/python/roles/sys-svc-container/test_mtu_probe.py new file mode 100644 index 0000000000..72fe0a2b12 --- /dev/null +++ b/tests/unit/python/roles/sys-svc-container/test_mtu_probe.py @@ -0,0 +1,113 @@ +import unittest + +from jinja2 import StrictUndefined +from jinja2.nativetypes import NativeEnvironment + +from utils import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +ROLE = PROJECT_ROOT / "roles" / "sys-svc-container" +EGRESS_MTUS = (1200, 1280, 1400, 1500, 9000) +IPV4_ICMP_HEADER_BYTES = 28 +INTERNET_MTU = 1500 + +_ENV = NativeEnvironment(undefined=StrictUndefined) + + +def _render(value, context): + if isinstance(value, str) and "{{" in value: + return _ENV.from_string(value).render(context) + return value + + +def _task(tasks, register): + return next(task for task in tasks if task.get("register") == register) + + +def _option(argv, flag): + return int(argv[argv.index(flag) + 1]) + + +class TestAutomtuProbeWindow(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + cls.tasks = load_yaml_any(ROLE / "tasks" / "_mtu.yml") + networks = load_yaml_any( + PROJECT_ROOT / "group_vars" / "all" / "08_networks.yml" + ) + cls.context = { + "ansible_python_interpreter": "python3", + "NETWORK_PUBLIC_DNS_RESOLVERS": networks["NETWORK_PUBLIC_DNS_RESOLVERS"], + } + for key, value in load_yaml_any(ROLE / ROLE_FILE_VARS_MAIN).items(): + if key.startswith("SYS_SVC_DOCKER_AUTOMTU_"): + cls.context[key] = _render(value, cls.context) + + def _detect_argv(self, egress_mtu): + task = _task(self.tasks, "automtu_mtu") + context = {**self.context, "automtu_egress": {"stdout": str(egress_mtu)}} + for key, value in task["vars"].items(): + context[key] = _render(value, context) + return [ + str(_render(arg, context)) + for arg in task["ansible.builtin.command"]["argv"] + ] + + def test_the_probe_window_is_one_size_at_the_largest_reachable_mtu(self) -> None: + for egress_mtu in EGRESS_MTUS: + with self.subTest(egress_mtu=egress_mtu): + argv = self._detect_argv(egress_mtu) + low = _option(argv, "--pmtu-min-payload") + high = _option(argv, "--pmtu-max-payload") + self.assertEqual( + low, + high, + "a binary search turns every lost echo into a lower MTU; a " + "one-size window confirms the ceiling and only searches " + "below it when that size fails", + ) + self.assertEqual( + high + IPV4_ICMP_HEADER_BYTES, + min(egress_mtu, INTERNET_MTU), + "automtu returns min(egress, measured): a probe above the egress " + "MTU or above the internet MTU only buys a 1 s timeout, a probe " + "below it lowers the result", + ) + + def test_one_target_confirming_the_window_decides(self) -> None: + argv = self._detect_argv(1400) + self.assertEqual( + argv[argv.index("--pmtu-policy") + 1], + "max", + "under min one target's lost echoes lower daemon.json, and every " + "change restarts dockerd; max keeps the largest size a target " + "confirmed end to end, which never exceeds the egress MTU", + ) + + def test_the_window_comes_from_automtu_not_from_gathered_facts(self) -> None: + egress = _task(self.tasks, "automtu_egress") + argv = egress["ansible.builtin.command"]["argv"] + self.assertEqual(argv[-2:], ["--print-mtu", "egress"]) + self.assertNotIn("--pmtu-target", argv) + detect = _task(self.tasks, "automtu_mtu") + self.assertLess(self.tasks.index(egress), self.tasks.index(detect)) + for fact in ("ansible_facts", "ansible_default_ipv4", "ansible_default_ipv6"): + self.assertNotIn( + fact, + repr(detect), + "this file installs iproute, so a fresh container gathered no " + "network facts and default_ipv4 is undefined when the probe runs", + ) + + def test_every_target_answers_icmp_echo(self) -> None: + self.assertNotIn( + "registry-1.docker.io", + self.context["SYS_SVC_DOCKER_AUTOMTU_TARGETS"], + "registry-1.docker.io drops ICMP echo, so it only adds four 1 s " + "timeouts to every deploy", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/test_forwarded_client_address.py b/tests/unit/python/roles/sys-svc-proxy/templates/test_forwarded_client_address.py index 07fd957d87..7ea003ba64 100644 --- a/tests/unit/python/roles/sys-svc-proxy/templates/test_forwarded_client_address.py +++ b/tests/unit/python/roles/sys-svc-proxy/templates/test_forwarded_client_address.py @@ -21,7 +21,7 @@ def render(**context) -> str: context: variables the template reads. """ env = Environment( - loader=FileSystemLoader(str(TEMPLATE_DIR)), + loader=FileSystemLoader([str(TEMPLATE_DIR), str(PROJECT_ROOT)]), undefined=StrictUndefined, autoescape=select_autoescape(), ) diff --git a/tests/unit/python/roles/sys-token-store/test_write_many.py b/tests/unit/python/roles/sys-token-store/test_write_many.py new file mode 100644 index 0000000000..728eabea4d --- /dev/null +++ b/tests/unit/python/roles/sys-token-store/test_write_many.py @@ -0,0 +1,164 @@ +from __future__ import annotations + +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any +from utils.templating.ansible import _trust_as_template + +TASKS = PROJECT_ROOT / "roles" / "sys-token-store" / "tasks" +MERGE = "🔨 Build merged structure" +EMPTY = "🛑 Abort if a token is empty (do not persist empties)" +PERSIST = "💾 Persist store (idempotent, single-writer via STACK_HOST)" +MIRROR = "🪞 Mirror the store onto the controller, where every users lookup reads" +HAND_OVER = "🔄 Hand the written store to the lookups of the rest of the play" +RERENDER = "🧊 Re-render the applications SPOT the new tokens invalidated" + +USERS = { + "alice": {"tokens": {"web-app-a": "old-a"}, "note": "kept"}, + "carol": {"tokens": {"web-app-c": "token-c"}}, +} +SKIPPED = {"changed": False, "skipped": True} + + +def _tasks(name: str) -> list[dict]: + return load_yaml_any(str(TASKS / name), default_if_missing=[]) + + +def _task(name: str) -> dict: + return next(t for t in _tasks("write_many.yml") if t.get("name") == name) + + +def _render(template, **variables): + templar = Templar(loader=DataLoader(), variables=variables) + return templar.template(_trust_as_template(template)) + + +def _merged(entries: list[dict], users: dict = USERS) -> dict: + return _render( + _task(MERGE)["ansible.builtin.set_fact"]["sys_token_store_users_merged"], + sys_token_store_entries=entries, + sys_token_store_users=users, + ) + + +def _when(name: str, **variables) -> bool: + when = _task(name)["when"] + conditions = when if isinstance(when, list) else [when] + return _render( + "{{ ((" + ") and (".join(conditions) + ")) | bool }}", + DEPLOYMENT_MODE="swarm", + **variables, + ) + + +def _entry(user_key: str, app: str, token: str) -> dict: + return {"user_key": user_key, "app": app, "token": token} + + +class TestWriteMany(unittest.TestCase): + def test_every_entry_lands_in_one_merge(self): + merged = _merged( + [ + _entry("alice", "web-app-b", " new-b "), + _entry("alice", "web-app-a", "new-a"), + _entry("bob", "web-app-b", "token-b"), + ] + ) + self.assertEqual( + merged, + { + "alice": { + "tokens": {"web-app-a": "new-a", "web-app-b": "new-b"}, + "note": "kept", + }, + "bob": {"tokens": {"web-app-b": "token-b"}}, + "carol": {"tokens": {"web-app-c": "token-c"}}, + }, + ) + + def test_the_later_entry_of_one_user_and_app_wins(self): + merged = _merged( + [_entry("bob", "web-app-b", "first"), _entry("bob", "web-app-b", "second")] + ) + self.assertEqual(merged["bob"], {"tokens": {"web-app-b": "second"}}) + + def test_an_unchanged_store_skips_the_write_and_the_rerender(self): + merged = _merged( + [ + _entry("alice", "web-app-a", "old-a"), + _entry("carol", "web-app-c", "token-c"), + ] + ) + self.assertEqual(merged, USERS) + state = {"sys_token_store_users_merged": merged, "sys_token_store_users": USERS} + self.assertFalse(_when(PERSIST, **state)) + self.assertFalse(_when(MIRROR, **state)) + self.assertFalse(_when(HAND_OVER, **state)) + self.assertFalse( + _when( + RERENDER, + sys_token_store_persisted=SKIPPED, + sys_token_store_mirrored=SKIPPED, + ) + ) + + def test_a_changed_store_is_written_and_rerendered_once(self): + merged = _merged([_entry("bob", "web-app-b", "token-b")]) + state = {"sys_token_store_users_merged": merged, "sys_token_store_users": USERS} + self.assertTrue(_when(PERSIST, **state)) + self.assertTrue(_when(HAND_OVER, **state)) + self.assertTrue( + _when( + RERENDER, + sys_token_store_persisted={"changed": True}, + sys_token_store_mirrored=SKIPPED, + ) + ) + rerenders = [t for t in _tasks("write_many.yml") if "applications_carrier" in t] + self.assertEqual(len(rerenders), 1) + self.assertNotIn("loop", rerenders[0]) + + def test_the_store_has_one_writer(self): + persist = _task(PERSIST) + self.assertEqual(persist["delegate_to"], "{{ STACK_HOST }}") + self.assertIs(persist["run_once"], True) + mirror = _task(MIRROR) + self.assertEqual(mirror["delegate_to"], "localhost") + self.assertIs(mirror["run_once"], True) + + def test_an_empty_token_is_refused_by_name(self): + empty = _render( + _task(EMPTY)["vars"]["sys_token_store_empty"], + sys_token_store_entries=[ + _entry("alice", "web-app-a", "set"), + _entry("bob", "web-app-b", " "), + ], + ) + self.assertEqual(empty, ["bob/web-app-b"]) + + +class TestWriteIsAOneEntryBatch(unittest.TestCase): + def test_the_single_token_contract_feeds_write_many(self): + tasks = _tasks("write.yml") + self.assertEqual(len(tasks), 1) + self.assertEqual(tasks[0]["ansible.builtin.import_tasks"], "write_many.yml") + single = { + "sys_token_store_user_key": "administrator", + "sys_token_store_app": "web-app-matomo", + "sys_token_store_token": "secret-token", + } + entries = [ + {field: _render(value, **single) for field, value in entry.items()} + for entry in tasks[0]["vars"]["sys_token_store_entries"] + ] + self.assertEqual( + entries, [_entry("administrator", "web-app-matomo", "secret-token")] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-keycloak/files/test_keycloak_admin.py b/tests/unit/python/roles/web-app-keycloak/files/test_keycloak_admin.py index f27d8c58a1..c700259df0 100644 --- a/tests/unit/python/roles/web-app-keycloak/files/test_keycloak_admin.py +++ b/tests/unit/python/roles/web-app-keycloak/files/test_keycloak_admin.py @@ -55,6 +55,26 @@ class TestKeycloakClient(unittest.TestCase): self.assertEqual(created, "new-id") self.assertEqual(sum(url.endswith("/token") for url in calls), 1) + def test_realm_level_calls_reach_any_realm_with_the_same_token(self): + token = json.dumps({"access_token": "t", "expires_in": 300}).encode() + calls = [] + + def urlopen(request, timeout): + calls.append(request.full_url) + if request.full_url.endswith("/token"): + return _Response(token) + return _Response(b"{}") + + kc = m.Keycloak("http://kc", "r", "admin", "pw") + with mock.patch.object(m.urllib.request, "urlopen", urlopen): + kc.call("GET", "clients") + kc.admin("GET", "master") + self.assertEqual( + [url for url in calls if not url.endswith("/token")], + ["http://kc/admin/realms/r/clients", "http://kc/admin/realms/master"], + ) + self.assertEqual(sum(url.endswith("/token") for url in calls), 1) + def test_an_http_error_names_the_status_but_not_the_body(self): token = json.dumps({"access_token": "t", "expires_in": 300}).encode() diff --git a/tests/unit/python/roles/web-app-keycloak/files/test_realm_settings.py b/tests/unit/python/roles/web-app-keycloak/files/test_realm_settings.py new file mode 100644 index 0000000000..44e8931e48 --- /dev/null +++ b/tests/unit/python/roles/web-app-keycloak/files/test_realm_settings.py @@ -0,0 +1,415 @@ +import contextlib +import io +import json +import os +import sys +import unittest +import unittest.mock as mock +import urllib.parse +from copy import deepcopy + +from . import PROJECT_ROOT + +sys.path.insert(0, str(PROJECT_ROOT / "roles/web-app-keycloak/files/python")) + +import realm_settings as m + +MASK = "**********" +KINDS = { + "default-client-scopes": "defaultClientScopes", + "optional-client-scopes": "optionalClientScopes", +} + + +class FakeKeycloak: + def __init__(self): + self.clients = {} + self.scopes = {} + self.assigned = {} + self.realms = {} + self.writes = [] + self._next = 0 + + def _id(self, prefix): + self._next += 1 + return f"{prefix}-{self._next}" + + def add_scope(self, name): + scope_id = self._id("s") + self.scopes[scope_id] = {"id": scope_id, "name": name, "protocol": "oidc"} + return scope_id + + def scope_id(self, name): + return next(s["id"] for s in self.scopes.values() if s["name"] == name) + + def add_client(self, rep): + client_id = self._id("c") + stored = {k: v for k, v in deepcopy(rep).items() if k not in KINDS.values()} + self.clients[client_id] = { + **stored, + "id": client_id, + "access": {"view": True}, + "attributes": {**stored["attributes"], "realm_client": "false"}, + "redirectUris": list(reversed(stored["redirectUris"])), + } + for kind, field in KINDS.items(): + self.assigned[(client_id, kind)] = { + self.scope_id(name) for name in rep[field] + } + return client_id + + def add_realm(self, name, smtp): + self.realms[name] = { + "id": name, + "realm": name, + "enabled": True, + "webAuthnPolicyRpEntityName": "keycloak", + "smtpServer": deepcopy(smtp), + } + + def shown(self, client_id): + client = deepcopy(self.clients[client_id]) + if client.get("publicClient") or client.get("bearerOnly"): + client = {k: v for k, v in client.items() if k != "secret"} + for kind, field in KINDS.items(): + client[field] = [ + self.scopes[s]["name"] for s in self.assigned[(client_id, kind)] + ] + return client + + def call(self, method, path, payload=None, timeout=60): + route, _, query = path.partition("?") + parts = route.split("/") + if method != "GET": + self.writes.append((method, route, deepcopy(payload))) + if route == "client-scopes" and method == "GET": + return [dict(s) for s in self.scopes.values()], "" + if route == "client-scopes" and method == "POST": + scope_id = self._id("s") + self.scopes[scope_id] = {**payload, "id": scope_id} + return None, scope_id + if route == "clients" and method == "GET": + wanted = urllib.parse.parse_qs(query).get("clientId") + return [ + self.shown(c) + for c, rep in self.clients.items() + if wanted is None or rep["clientId"] == wanted[0] + ], "" + if route == "clients" and method == "POST": + if any(c["clientId"] == payload["clientId"] for c in self.clients.values()): + raise m.KeycloakError(f"POST cymais/{path}: HTTP 409") + return None, self.add_client(payload) + if len(parts) == 2 and method == "PUT": + self.clients[parts[1]] = { + k: v for k, v in deepcopy(payload).items() if k not in KINDS.values() + } + return None, "" + if len(parts) == 3 and method == "GET": + return [ + dict(self.scopes[s]) for s in self.assigned[(parts[1], parts[2])] + ], "" + if len(parts) == 4 and method == "DELETE": + self.assigned[(parts[1], parts[2])].discard(parts[3]) + return None, "" + if len(parts) == 4 and method == "PUT": + self.assigned[(parts[1], parts[2])].add(parts[3]) + return None, "" + raise AssertionError(f"unexpected call {method} {path}") + + def admin(self, method, path, payload=None, timeout=60): + realm = urllib.parse.unquote(path) + if method == "GET": + shown = deepcopy(self.realms[realm]) + if "password" in shown["smtpServer"]: + shown["smtpServer"]["password"] = MASK + return shown, "" + if method == "PUT": + self.writes.append((method, realm, deepcopy(payload))) + stored = deepcopy(payload) + if stored["smtpServer"].get("password") == MASK: + stored["smtpServer"]["password"] = self.realms[realm]["smtpServer"][ + "password" + ] + self.realms[realm] = stored + return None, "" + raise AssertionError(f"unexpected admin call {method} {path}") + + +def _client(**changes): + return { + "clientId": "cymais.cloud", + "publicClient": False, + "secret": "s3cret", + "redirectUris": ["https://a.example/*", "https://b.example/*"], + "attributes": {"frontchannel.logout.url": "https://logout.example/"}, + "protocolMappers": [ + { + "name": "audience", + "protocolMapper": "oidc-audience-mapper", + "config": {"access.token.claim": "true"}, + } + ], + "defaultClientScopes": ["profile", "rbac"], + "optionalClientScopes": ["offline_access"], + **changes, + } + + +def _keycloak(): + kc = FakeKeycloak() + for name in ("profile", "rbac", "offline_access", "phone"): + kc.add_scope(name) + return kc + + +def _catalog(kc): + return {s["name"]: s["id"] for s in kc.scopes.values()} + + +def _deployed(kc, client): + client_id = kc.add_client(client) + mapper = kc.clients[client_id]["protocolMappers"][0] + mapper.update({"id": "pm-1", "protocol": "openid-connect"}) + return client_id + + +def _converge(kc, desired): + existing = next( + ( + kc.shown(c) + for c, r in kc.clients.items() + if r["clientId"] == desired["clientId"] + ), + None, + ) + return m.converge_client(kc, desired, existing, _catalog(kc)) + + +class TestMatches(unittest.TestCase): + def test_equal_values_match(self): + self.assertTrue(m.matches({"a": [1, {"b": "c"}]}, {"a": [1, {"b": "c"}]})) + + def test_list_order_does_not_count(self): + self.assertTrue(m.matches(["x", "y"], ["y", "x"])) + + def test_keys_keycloak_adds_do_not_count(self): + self.assertTrue(m.matches([{"name": "n"}], [{"name": "n", "id": "1"}])) + + def test_an_empty_desired_value_matches_a_key_keycloak_omits(self): + self.assertTrue(m.matches({"name": "", "mappers": []}, {})) + + def test_a_changed_value_does_not_match(self): + self.assertFalse(m.matches({"a": {"b": "new"}}, {"a": {"b": "old"}})) + + def test_an_extra_current_list_item_does_not_match(self): + self.assertFalse(m.matches(["x"], ["x", "y"])) + + def test_a_set_desired_value_does_not_match_a_key_keycloak_omits(self): + self.assertFalse(m.matches({"secret": "s"}, {})) + + +class TestConvergeClient(unittest.TestCase): + def test_an_unchanged_client_is_not_written(self): + kc = _keycloak() + _deployed(kc, _client()) + self.assertEqual(_converge(kc, _client()), "unchanged") + self.assertEqual(kc.writes, []) + + def test_a_drifted_client_is_written_once_and_keeps_its_other_fields(self): + kc = _keycloak() + client_id = _deployed(kc, _client()) + drifted = _client(attributes={"frontchannel.logout.url": "https://new/"}) + self.assertEqual(_converge(kc, drifted), "updated") + self.assertEqual( + [(w[0], w[1]) for w in kc.writes], [("PUT", f"clients/{client_id}")] + ) + body = kc.writes[0][2] + self.assertEqual(body["id"], client_id) + self.assertEqual(body["attributes"]["realm_client"], "false") + self.assertEqual(body["attributes"]["frontchannel.logout.url"], "https://new/") + + def test_the_hidden_secret_of_a_public_client_does_not_count_as_drift(self): + kc = _keycloak() + _deployed(kc, _client(publicClient=True)) + self.assertEqual(_converge(kc, _client(publicClient=True)), "unchanged") + self.assertEqual(kc.writes, []) + + def test_a_rotated_secret_of_a_confidential_client_is_written(self): + kc = _keycloak() + client_id = _deployed(kc, _client()) + self.assertEqual(_converge(kc, _client(secret="rotated")), "updated") + self.assertEqual(kc.clients[client_id]["secret"], "rotated") + self.assertEqual(len(kc.writes), 1) + + def test_an_absent_client_is_created_with_one_post(self): + kc = _keycloak() + self.assertEqual(_converge(kc, _client()), "created") + self.assertEqual([(w[0], w[1]) for w in kc.writes], [("POST", "clients")]) + + def test_a_client_another_writer_created_meanwhile_is_updated_instead(self): + kc = _keycloak() + _deployed(kc, _client(secret="old")) + outcome = m.converge_client(kc, _client(), None, _catalog(kc)) + self.assertEqual(outcome, "updated") + self.assertEqual([w[0] for w in kc.writes], ["POST", "PUT"]) + + def test_scope_list_drift_moves_only_the_scopes_and_skips_the_client_put(self): + kc = _keycloak() + client_id = _deployed(kc, _client(defaultClientScopes=["profile"])) + desired = _client(optionalClientScopes=[]) + self.assertEqual(_converge(kc, desired), "updated") + self.assertEqual( + sorted((w[0], w[1]) for w in kc.writes), + [ + ( + "DELETE", + f"clients/{client_id}/optional-client-scopes/{kc.scope_id('offline_access')}", + ), + ( + "PUT", + f"clients/{client_id}/default-client-scopes/{kc.scope_id('rbac')}", + ), + ], + ) + + def test_an_unknown_scope_is_refused_before_any_scope_moves(self): + kc = _keycloak() + client_id = _deployed(kc, _client()) + with self.assertRaises(m.RefusalError) as raised: + _converge(kc, _client(defaultClientScopes=["profile", "ghost"])) + self.assertIn("ghost", str(raised.exception)) + self.assertEqual(kc.writes, []) + self.assertIn( + kc.scope_id("rbac"), kc.assigned[(client_id, "default-client-scopes")] + ) + + +class TestCreateScope(unittest.TestCase): + def test_a_missing_scope_is_created_and_catalogued(self): + kc = _keycloak() + catalog = _catalog(kc) + self.assertEqual(m.create_scope(kc, {"name": "nextcloud"}, catalog), "created") + self.assertEqual(catalog["nextcloud"], kc.scope_id("nextcloud")) + self.assertEqual([(w[0], w[1]) for w in kc.writes], [("POST", "client-scopes")]) + + def test_an_existing_scope_is_left_alone(self): + kc = _keycloak() + outcome = m.create_scope(kc, {"name": "rbac", "protocol": "x"}, _catalog(kc)) + self.assertEqual(outcome, "unchanged") + self.assertEqual(kc.writes, []) + + +class TestConvergeRealm(unittest.TestCase): + def test_matching_mail_settings_without_a_secret_are_not_written(self): + kc = FakeKeycloak() + kc.add_realm("master", {"host": "mail.example", "port": "587"}) + outcome = m.converge_realm( + kc, "master", {"smtpServer": {"host": "mail.example"}} + ) + self.assertEqual(outcome, "unchanged") + self.assertEqual(kc.writes, []) + + def test_drifted_mail_settings_are_written_once_into_the_whole_realm(self): + kc = FakeKeycloak() + kc.add_realm("master", {"host": "old.example", "port": "587"}) + outcome = m.converge_realm( + kc, "master", {"smtpServer": {"host": "new.example"}} + ) + self.assertEqual(outcome, "updated") + self.assertEqual(len(kc.writes), 1) + self.assertEqual( + kc.realms["master"]["smtpServer"], {"host": "new.example", "port": "587"} + ) + self.assertEqual(kc.realms["master"]["webAuthnPolicyRpEntityName"], "keycloak") + + def test_a_masked_password_is_written_so_rotation_reaches_keycloak(self): + kc = FakeKeycloak() + kc.add_realm("cymais", {"host": "mail.example", "password": "old"}) + desired = {"smtpServer": {"host": "mail.example", "password": "new"}} + self.assertEqual(m.converge_realm(kc, "cymais", desired), "updated") + self.assertEqual(kc.realms["cymais"]["smtpServer"]["password"], "new") + + def test_mail_settings_of_a_disabled_mailer_leave_the_realm_alone(self): + kc = FakeKeycloak() + kc.add_realm("cymais", {"host": "mail.example", "password": "pw"}) + self.assertEqual( + m.converge_realm(kc, "cymais", {"smtpServer": {}}), "unchanged" + ) + self.assertEqual(kc.writes, []) + + +class TestMain(unittest.TestCase): + def _run(self, kc, spec): + out, err = io.StringIO(), io.StringIO() + env = {"KC_URL": "http://kc", "KC_PID": "1", "KC_REALM": "cymais"} + with ( + mock.patch.dict(os.environ, env), + mock.patch.object(m, "Keycloak", lambda *args: kc), + mock.patch.object(m, "container_credentials", lambda path: ("a", "p")), + mock.patch.object(m.sys, "stdin", io.StringIO(json.dumps(spec))), + contextlib.redirect_stdout(out), + contextlib.redirect_stderr(err), + ): + code = m.main() + return code, out.getvalue().splitlines(), err.getvalue() + + def _spec(self, clients, smtp): + return { + "clientScopes": [{"name": "rbac"}], + "clients": clients, + "realms": [ + {"realm": "cymais", "desired": {"smtpServer": smtp}}, + {"realm": "master", "desired": {"smtpServer": smtp}}, + ], + } + + def _deployment(self): + kc = _keycloak() + client_id = _deployed(kc, _client()) + kc.add_realm("cymais", {"host": "mail.example"}) + kc.add_realm("master", {"host": "mail.example"}) + return kc, client_id + + def test_an_unchanged_deployment_writes_nothing(self): + kc, _ = self._deployment() + spec = self._spec([_client()], {"host": "mail.example"}) + code, lines, _ = self._run(kc, spec) + self.assertEqual(code, 0) + self.assertEqual(kc.writes, []) + self.assertEqual(lines[-1], "summary created=0 updated=0 unchanged=4 failed=0") + + def test_each_drifted_object_gets_one_write(self): + kc, client_id = self._deployment() + drifted = _client(redirectUris=["https://a.example/*"]) + code, lines, _ = self._run(kc, self._spec([drifted], {"host": "new.example"})) + self.assertEqual(code, 0) + self.assertEqual( + [(w[0], w[1]) for w in kc.writes], + [("PUT", f"clients/{client_id}"), ("PUT", "cymais"), ("PUT", "master")], + ) + self.assertIn("updated client cymais.cloud", lines) + self.assertEqual(lines[-1], "summary created=0 updated=3 unchanged=1 failed=0") + + def test_a_refused_client_fails_the_run_and_is_named(self): + kc, _ = self._deployment() + refused = _client(defaultClientScopes=["ghost"]) + spec = self._spec([refused], {"host": "mail.example"}) + code, lines, err = self._run(kc, spec) + self.assertEqual(code, 1) + self.assertIn("failed client cymais.cloud", lines) + self.assertIn( + "client cymais.cloud: client scopes missing in the realm: ghost", err + ) + self.assertIn("unchanged realm master", lines) + + def test_a_spec_without_realms_fails_before_any_call(self): + kc, _ = self._deployment() + spec = {"clientScopes": [], "clients": []} + code, lines, _ = self._run(kc, spec) + self.assertEqual(code, 1) + self.assertTrue(lines[0].startswith("listing-failed")) + self.assertEqual(kc.writes, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-keycloak/test_async_kcadm_jobs.py b/tests/unit/python/roles/web-app-keycloak/test_async_kcadm_jobs.py index 927e3ff774..cf49766032 100644 --- a/tests/unit/python/roles/web-app-keycloak/test_async_kcadm_jobs.py +++ b/tests/unit/python/roles/web-app-keycloak/test_async_kcadm_jobs.py @@ -65,9 +65,6 @@ def reaches_a_reap(result: str, facts: dict[str, str], reaped: list[str]) -> boo class TestAsyncKcadmJobs(unittest.TestCase): - def test_the_role_runs_kcadm_jobs_async(self): - self.assertTrue(list(async_kcadm_jobs())) - def test_every_async_kcadm_job_goes_through_the_lock_retrying_module(self): for label, task in async_kcadm_jobs(): with self.subTest(task=label): diff --git a/tests/unit/python/roles/web-app-keycloak/test_logout_status_panel.py b/tests/unit/python/roles/web-app-keycloak/test_logout_status_panel.py index 7cce64b97d..8d3d1750fc 100644 --- a/tests/unit/python/roles/web-app-keycloak/test_logout_status_panel.py +++ b/tests/unit/python/roles/web-app-keycloak/test_logout_status_panel.py @@ -50,7 +50,8 @@ PANEL = ROLE / "files" / "javascript" / "logout-panel.js" ASSEMBLY = ROLE / "templates" / "logout-panel.js.j2" CATALOGUE_FILE = ROLE / "files" / "logout_i18n.yml" VARS = ROLE / ROLE_FILE_VARS_MAIN -FRAMED_ORIGIN_LOOKUP = "lookup('tls', 'web-svc-logout', 'url.base')" +FRAMED_URL_LOOKUP = "lookup('tls', 'web-svc-logout', 'url.base')" +PANEL_ORIGIN_LOOKUP = "lookup('tls', 'web-svc-logout', 'url.origin')" ORIGIN = "https://logout.example.test" DOMAINS = ("https://shop.example.test", "https://cloud.example.test") @@ -361,15 +362,16 @@ class TestPanelTrustsTheFramedOrigin(unittest.TestCase): declaration, f"KEYCLOAK_FRONTCHANNEL_LOGOUT_URL missing from {VARS}" ) self.assertIn( - FRAMED_ORIGIN_LOOKUP, + FRAMED_URL_LOOKUP, declaration, "the front-channel logout URL decides which origin ends up framed", ) self.assertIn( - FRAMED_ORIGIN_LOOKUP, + PANEL_ORIGIN_LOOKUP, read_text(str(ASSEMBLY)), - "the panel discards messages from any other origin, so its constant and" - " the framed URL must come from one expression or the panel goes silent", + "the panel discards messages from any other origin, so its constant must" + " be the origin of the same tls resolution that builds the framed URL," + " or the panel goes silent", ) 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 3b902b60f8..7ecae1e199 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 @@ -1,6 +1,7 @@ from __future__ import annotations import importlib.util +import json import sys import unittest @@ -41,7 +42,7 @@ def _status(rc: int = 1, stdout: str = "", stderr: str = "") -> dict: def _tolerated(status: dict) -> bool: - """Whether 01_install.yml's failed_when lets the play continue.""" + """Whether 02_install.yml's failed_when lets the play continue.""" return status["ok"] or status["unavailable"] @@ -89,5 +90,220 @@ class TestNextcloudInstallStatus(unittest.TestCase): MODULE.nextcloud_install_status("rc=0") +RECOGNIZE_VERSIONS = [ + "002002000Date20220614094721", + "002003000Date20220713094721", + "003001000Date20221017094721", + "003004000Date20230107094721", + "010000001Date20250727094721", + "010000001Date20250727094821", + "011000001Date20251215094821", + "011000002Date20260129094821", +] +RUNNING = json.dumps({"started": True, "finished": False, "ansible_job_id": "j1.2"}) +PROBE_FAILURES = ( + (0, ""), + (255, ""), + (124, ""), + (1, "Could not open input file"), +) + + +def _probe(rows: list[str], files: list[str] | None) -> tuple[int, str]: + """Answer the way files/php/utils/migration_state.php does on stable34. + + Args: + rows: versions recorded in oc_migrations for the app. + files: Version*.php versions on disk, None while the app directory + does not exist yet. + + Returns: + (exit code, stdout). + """ + if files is None: + return 0, "" + state = {"migrated": sorted(rows), "available": sorted(files)} + return 0, "MIGRATION_STATE " + json.dumps(state) + + +def _gate(rows: list[str], files: list[str] | None) -> str: + rc, probe = _probe(rows, files) + return MODULE.nextcloud_background_gate( + {"rc": rc, "stdout": RUNNING + "\n" + probe, "attempts": 1} + ) + + +def _ended(job: dict) -> str: + return MODULE.nextcloud_background_gate( + {"rc": 0, "stdout": json.dumps(job) + "\n", "attempts": 9} + ) + + +class TestNextcloudBackgroundGate(unittest.TestCase): + def test_an_applied_schema_opens_the_gate(self): + self.assertEqual(_gate(RECOGNIZE_VERSIONS, RECOGNIZE_VERSIONS), "open") + + def test_a_missing_app_directory_waits(self): + self.assertEqual(_gate([], None), "wait") + + def test_a_probe_without_its_marker_waits_whatever_its_exit_code(self): + for rc, stdout in PROBE_FAILURES: + with self.subTest(rc=rc, stdout=stdout): + self.assertEqual( + MODULE.nextcloud_background_gate( + {"rc": rc, "stdout": RUNNING + "\n" + stdout, "attempts": 1} + ), + "wait", + ) + + def test_a_running_job_with_nothing_after_its_file_waits(self): + self.assertEqual( + MODULE.nextcloud_background_gate( + {"rc": 0, "stdout": RUNNING, "attempts": 1} + ), + "wait", + ) + + def test_two_markers_wait(self): + _, probe = _probe(RECOGNIZE_VERSIONS, RECOGNIZE_VERSIONS) + self.assertEqual( + MODULE.nextcloud_background_gate( + { + "rc": 0, + "stdout": RUNNING + "\n" + probe + "\n" + probe, + "attempts": 1, + } + ), + "wait", + ) + + def test_a_copy_without_recorded_migrations_waits(self): + for copied in range(len(RECOGNIZE_VERSIONS) + 1): + with self.subTest(copied=copied): + self.assertEqual(_gate([], RECOGNIZE_VERSIONS[:copied]), "wait") + + def test_migrations_marked_one_by_one_wait_for_the_last(self): + for marked in range(1, len(RECOGNIZE_VERSIONS)): + with self.subTest(marked=marked): + self.assertEqual( + _gate(RECOGNIZE_VERSIONS[:marked], RECOGNIZE_VERSIONS), "wait" + ) + + def test_rows_without_their_newest_file_wait(self): + self.assertEqual(_gate(RECOGNIZE_VERSIONS[-1:], RECOGNIZE_VERSIONS), "wait") + rows = [*RECOGNIZE_VERSIONS[:7], "012000000Date20200101000000"] + self.assertEqual(_gate(rows, RECOGNIZE_VERSIONS), "wait") + + def test_leftover_rows_of_an_older_release_wait_while_its_files_are_copied(self): + rows = RECOGNIZE_VERSIONS[:7] + for copied in range(7): + with self.subTest(copied=copied): + self.assertEqual(_gate(rows, RECOGNIZE_VERSIONS[:copied]), "wait") + self.assertEqual(_gate(rows, RECOGNIZE_VERSIONS), "wait") + + def test_residual_leftover_rows_open_between_the_last_old_and_first_new_file(self): + self.assertEqual(_gate(RECOGNIZE_VERSIONS[:7], RECOGNIZE_VERSIONS[:7]), "open") + + def test_leftover_rows_of_a_removed_migration_never_open_the_gate(self): + rows = [*RECOGNIZE_VERSIONS, "001000000Date20210101000000"] + self.assertEqual(_gate(rows, RECOGNIZE_VERSIONS), "wait") + + def test_leftover_rows_of_the_same_release_open_with_nothing_left_to_run(self): + self.assertEqual(_gate(RECOGNIZE_VERSIONS, RECOGNIZE_VERSIONS[:7]), "wait") + self.assertEqual(_gate(RECOGNIZE_VERSIONS, RECOGNIZE_VERSIONS), "open") + + def test_a_probe_line_amid_php_notices_is_found(self): + rc, probe = _probe(RECOGNIZE_VERSIONS, RECOGNIZE_VERSIONS) + stdout = RUNNING + "\nPHP Deprecated: something\n" + probe + "\n" + self.assertEqual( + MODULE.nextcloud_background_gate( + {"rc": rc, "stdout": stdout, "attempts": 1} + ), + "open", + ) + + def test_a_failed_probe_waits_whatever_it_printed(self): + _, probe = _probe(RECOGNIZE_VERSIONS, RECOGNIZE_VERSIONS) + self.assertEqual( + MODULE.nextcloud_background_gate( + {"rc": 1, "stdout": RUNNING + "\n" + probe, "attempts": 1} + ), + "wait", + ) + + def test_a_job_that_ended_with_an_occ_exit_code_opens_the_gate(self): + for rc in (0, 1): + with self.subTest(rc=rc): + self.assertEqual( + _ended({"rc": rc, "stdout": "", "changed": False}), "open" + ) + + def test_a_job_that_ended_without_an_occ_exit_code_fails_the_gate(self): + for job in ( + {"rc": 124}, + {"rc": 137}, + {"rc": 143}, + {"rc": -9}, + {"msg": "Timeout exceeded", "failed": True, "child_pid": 42}, + {"failed": True, "msg": "Traceback", "data": ""}, + ): + with self.subTest(job=job): + self.assertEqual(_ended(job), "killed") + + def test_a_job_file_not_written_yet_waits_for_the_grace_attempts(self): + rc, probe = _probe([], None) + for attempts in (1, 15): + with self.subTest(attempts=attempts): + self.assertEqual( + MODULE.nextcloud_background_gate( + {"rc": rc, "stdout": "\n" + probe, "attempts": attempts} + ), + "wait", + ) + self.assertEqual( + MODULE.nextcloud_background_gate( + {"rc": rc, "stdout": "\n" + probe, "attempts": 16} + ), + "killed", + ) + + def test_a_job_file_that_is_no_object_is_rejected(self): + with self.assertRaises(TypeError): + MODULE.nextcloud_background_gate({"rc": 0, "stdout": "[]\n", "attempts": 1}) + + def test_a_non_dict_result_is_rejected(self): + with self.assertRaises(TypeError): + MODULE.nextcloud_background_gate("0") + + +class TestNextcloudBackgroundLost(unittest.TestCase): + def test_an_occ_exit_code_is_a_joined_job(self): + for rc in (0, 1): + with self.subTest(rc=rc): + self.assertFalse(MODULE.nextcloud_background_lost({"rc": rc})) + + def test_a_job_without_exit_code_is_lost(self): + for result in ( + {"finished": False, "started": True}, + {"msg": "Timeout exceeded", "failed": True, "child_pid": 42}, + ): + with self.subTest(result=result): + self.assertTrue(MODULE.nextcloud_background_lost(result)) + + def test_a_killed_exec_or_shell_is_lost(self): + for rc in (124, 129, 137, 143, 192, -9, -15): + with self.subTest(rc=rc): + self.assertTrue(MODULE.nextcloud_background_lost({"rc": rc})) + + def test_a_php_fatal_error_is_an_occ_exit_code(self): + for rc in (2, 255): + with self.subTest(rc=rc): + self.assertFalse(MODULE.nextcloud_background_lost({"rc": rc})) + + def test_a_non_dict_result_is_rejected(self): + with self.assertRaises(TypeError): + MODULE.nextcloud_background_lost(None) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_oauth_client.py b/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_oauth_client.py new file mode 100644 index 0000000000..55ca3c97d9 --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_oauth_client.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +import importlib.util +import json +import sys +import unittest + +from ansible.errors import AnsibleFilterError + +from . import PROJECT_ROOT + + +def _load_module(): + path = ( + PROJECT_ROOT + / "roles/web-app-nextcloud/filter_plugins/nextcloud_oauth_client.py" + ) + spec = importlib.util.spec_from_file_location("nextcloud_oauth_client", str(path)) + module = importlib.util.module_from_spec(spec) + assert spec and spec.loader + sys.modules["nextcloud_oauth_client"] = module + spec.loader.exec_module(module) + return module + + +MODULE = _load_module() + + +def _stdout(state: dict, before: str = "", after: str = "") -> str: + return f"{before}NC_OAUTH_CLIENT {json.dumps(state)}\n{after}" + + +class TestNextcloudOauthClientState(unittest.TestCase): + def test_an_unchanged_client_without_stale_clients_is_not_changed(self): + state = MODULE.nextcloud_oauth_client_state( + _stdout({"action": "unchanged", "id": 7, "client_id": "abc", "removed": 0}) + ) + self.assertFalse(state["changed"]) + self.assertEqual(state["id"], 7) + + def test_removing_a_stale_client_is_a_change(self): + state = MODULE.nextcloud_oauth_client_state( + _stdout({"action": "unchanged", "id": 7, "client_id": "abc", "removed": 2}) + ) + self.assertTrue(state["changed"]) + + def test_a_fixed_redirect_and_a_created_client_are_changes(self): + for action in ("redirect_fixed", "created"): + with self.subTest(action=action): + state = MODULE.nextcloud_oauth_client_state( + _stdout( + {"action": action, "id": 7, "client_id": "abc", "removed": 0} + ) + ) + self.assertTrue(state["changed"]) + + def test_the_marker_is_found_among_php_notices(self): + state = MODULE.nextcloud_oauth_client_state( + _stdout( + { + "action": "created", + "id": 9, + "client_id": "x", + "client_secret": "s", + "removed": 1, + }, + before="PHP Deprecated: something\n", + after="PHP Notice: else\n", + ) + ) + self.assertEqual(state["action"], "created") + self.assertEqual(state["client_secret"], "s") + + def test_a_missing_or_doubled_marker_fails(self): + line = _stdout({"action": "unchanged", "id": 1, "client_id": "a", "removed": 0}) + for stdout in ("", "PHP Fatal error: class not found\n", line + line): + with ( + self.subTest(stdout=stdout[:20]), + self.assertRaises(AnsibleFilterError), + ): + MODULE.nextcloud_oauth_client_state(stdout) + + def test_an_unknown_action_fails(self): + with self.assertRaises(AnsibleFilterError): + MODULE.nextcloud_oauth_client_state( + _stdout({"action": "deleted", "id": 1, "client_id": "a", "removed": 0}) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_plugin_plan.py b/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_plugin_plan.py index 959441e468..7faabd531e 100644 --- a/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_plugin_plan.py +++ b/tests/unit/python/roles/web-app-nextcloud/filter_plugins/test_nextcloud_plugin_plan.py @@ -4,6 +4,8 @@ import importlib.util import sys import unittest +from utils.cache.yaml import load_yaml_any + from . import PROJECT_ROOT @@ -46,6 +48,7 @@ class TestNextcloudPluginPlan(unittest.TestCase): { "disable": [], "install": [], + "background": [], "enable": [], "configure": ["calendar", "deck"], }, @@ -142,5 +145,120 @@ class TestNextcloudPluginPlan(unittest.TestCase): self.assertEqual(plan["install"], ["deck"]) +BACKGROUND = {"enabled": True, "config": {"background_install": True}} + + +class TestBackgroundPlan(unittest.TestCase): + def test_a_missing_plugin_marked_background_leaves_the_install_loop(self): + plan = nextcloud_plugin_plan( + _items(("deck", {"enabled": True}), ("recognize", BACKGROUND)), _apps() + ) + self.assertEqual(plan["background"], ["recognize"]) + self.assertEqual(plan["install"], ["deck"]) + + def test_an_unmarked_plugin_stays_in_the_install_loop(self): + plan = nextcloud_plugin_plan(_items(("recognize", {"enabled": True})), _apps()) + self.assertEqual(plan["background"], []) + self.assertEqual(plan["install"], ["recognize"]) + + def test_a_marked_plugin_on_disk_is_enabled_not_reinstalled(self): + plan = nextcloud_plugin_plan( + _items(("recognize", BACKGROUND)), _apps(disabled=("recognize",)) + ) + self.assertEqual(plan["background"], []) + self.assertEqual(plan["enable"], ["recognize"]) + + def test_a_marked_running_plugin_is_only_configured(self): + plan = nextcloud_plugin_plan( + _items(("recognize", BACKGROUND)), _apps(enabled=("recognize",)) + ) + self.assertEqual(plan["background"], []) + self.assertEqual(plan["configure"], ["recognize"]) + + def test_a_marked_plugin_switched_off_is_not_installed(self): + plan = nextcloud_plugin_plan( + _items( + ( + "recognize", + {"enabled": False, "config": {"background_install": True}}, + ) + ), + _apps(), + ) + self.assertEqual(plan["background"], []) + self.assertEqual(plan["install"], []) + + def test_a_pinned_archive_never_runs_in_the_background(self): + plan = nextcloud_plugin_plan( + _items( + ( + "onlyoffice", + { + "enabled": True, + "config": { + "archive": "https://x/o.tar.gz", + "background_install": True, + }, + }, + ) + ), + _apps(), + ) + self.assertEqual(plan["background"], []) + self.assertEqual(plan["install"], ["onlyoffice"]) + + def test_a_mandatory_plugin_keeps_its_install_guard(self): + plan = nextcloud_plugin_plan( + _items( + ( + "oidc_login", + { + "enabled": True, + "config": {"background_install": True, "mandatory": True}, + }, + ) + ), + _apps(), + ) + self.assertEqual(plan["background"], []) + self.assertEqual(plan["install"], ["oidc_login"]) + + def test_a_templated_string_flag_is_honoured(self): + plan = nextcloud_plugin_plan( + _items( + ( + "recognize", + {"enabled": "True", "config": {"background_install": "True"}}, + ) + ), + _apps(), + ) + self.assertEqual(plan["background"], ["recognize"]) + + def test_every_wanted_plugin_lands_in_exactly_one_list(self): + items = _items( + ("deck", {"enabled": True}), + ("recognize", BACKGROUND), + ("news", {"enabled": True}), + ("calendar", {"enabled": True}), + ) + plan = nextcloud_plugin_plan( + items, _apps(enabled=("calendar",), disabled=("news",)) + ) + placed = ( + plan["install"] + plan["background"] + plan["enable"] + plan["configure"] + ) + self.assertCountEqual(placed, ["deck", "recognize", "news", "calendar"]) + + +class TestRecognizeAddon(unittest.TestCase): + def test_recognize_is_installed_in_the_background(self): + spec = load_yaml_any( + str(PROJECT_ROOT / "roles/web-app-nextcloud/meta/addons/recognize.yml") + ) + plan = nextcloud_plugin_plan(_items(("recognize", spec)), _apps()) + self.assertEqual(plan["background"], ["recognize"]) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/web-app-nextcloud/test_plugin_background_install.py b/tests/unit/python/roles/web-app-nextcloud/test_plugin_background_install.py new file mode 100644 index 0000000000..c65686e4ed --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_plugin_background_install.py @@ -0,0 +1,357 @@ +from __future__ import annotations + +import importlib.util +import json +import sys +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar +from jinja2 import Environment + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_any +from utils.templating.ansible import _trust_as_template + +ROLE = PROJECT_ROOT / "roles/web-app-nextcloud" +MANAGER_OPS = ROLE / "tasks/02_manager_ops.yml" +PLUGIN = ROLE / "tasks/02_manager_ops/06_plugin.yml" +BACKGROUND = ROLE / "tasks/02_manager_ops/06_plugin/01_background.yml" +PROBE = ROLE / "files/php/utils/migration_state.php" + + +def _load_filters(): + path = ROLE / "filter_plugins/nextcloud_install.py" + spec = importlib.util.spec_from_file_location("nextcloud_install_wiring", str(path)) + module = importlib.util.module_from_spec(spec) + assert spec and spec.loader + sys.modules["nextcloud_install_wiring"] = module + spec.loader.exec_module(module) + return module.FilterModule().filters() + + +FILTERS = _load_filters() + + +def _flat(tasks: list[dict]) -> list[dict]: + """Return the tasks in run order, block sections expanded in place. + + Args: + tasks: parsed task list of one task file. + """ + flat: list[dict] = [] + for task in tasks: + if "block" in task: + flat.extend(_flat(task["block"]) + _flat(task.get("always", []))) + else: + flat.append(task) + return flat + + +def _tasks(path) -> list[dict]: + return _flat(load_yaml_any(str(path), default_if_missing=[])) + + +def _index(tasks: list[dict], fragment: str) -> int: + return next(i for i, task in enumerate(tasks) if fragment in task.get("name", "")) + + +def _task(path, fragment: str) -> dict: + tasks = _tasks(path) + return tasks[_index(tasks, fragment)] + + +def _install_block() -> dict: + return next( + task + for task in load_yaml_any(str(PLUGIN), default_if_missing=[]) + if "block" in task + ) + + +def _eval(expression: str, **variables) -> bool: + env = Environment(autoescape=True) + env.filters.update(FILTERS) + return bool(env.compile_expression(expression)(**variables)) + + +def _ansible_eval(expression: str, **variables) -> bool: + templar = Templar(loader=DataLoader(), variables=variables) + return bool( + templar.template(_trust_as_template("{{ (" + expression + ") | bool }}")) + ) + + +class TestOrder(unittest.TestCase): + def setUp(self): + self.tasks = _tasks(PLUGIN) + + def test_the_background_job_starts_after_the_last_ddl_before_the_loop(self): + self.assertLess( + _index(self.tasks, "Disable the plugins that end up disabled"), + _index(self.tasks, "Start the installs that run beside the install loop"), + ) + self.assertLess( + _index(self.tasks, "Start the installs that run beside the install loop"), + _index(self.tasks, "Install and enable the plugins Nextcloud lacks"), + ) + + def test_the_join_sits_between_the_install_loop_and_the_plugins_own_stage(self): + order = [ + _index(self.tasks, "Install and enable the plugins Nextcloud lacks"), + _index(self.tasks, "Join the background installs"), + _index( + self.tasks, + "Enable and configure the plugins installed in the background", + ), + _index(self.tasks, "Enable the installed plugins Nextcloud keeps disabled"), + _index(self.tasks, "Configure every queued plugin in one batch"), + ] + self.assertEqual(order, sorted(order)) + + def test_both_background_steps_loop_over_the_background_plan(self): + for fragment in ( + "Start the installs that run beside the install loop", + "Enable and configure the plugins installed in the background", + ): + with self.subTest(fragment=fragment): + task = _task(PLUGIN, fragment) + self.assertIn("nextcloud_plugin_plan.background", task["loop"]) + self.assertIn( + "nextcloud_plugin_plan.install", + _task(PLUGIN, "Install and enable the plugins Nextcloud lacks")["loop"], + ) + + def test_the_background_job_follows_the_occ_delegation_of_the_plugin_stage(self): + include = _task(MANAGER_OPS, "Setup Nextcloud Plugins") + self.assertEqual( + include["include_tasks"]["apply"]["delegate_to"], + "{{ NEXTCLOUD_HOST_NODE }}", + ) + join = _task(PLUGIN, "Join the background installs") + for task in [*_tasks(BACKGROUND), join]: + with self.subTest(task=task["name"]): + self.assertNotIn("delegate_to", task) + + def test_a_failing_install_loop_still_joins_the_background_jobs(self): + block = _install_block() + self.assertEqual( + [task["name"] for task in block["block"]], + [ + "🛫 Start the installs that run beside the install loop", + "📦 Install and enable the plugins Nextcloud lacks", + ], + ) + self.assertEqual( + [task["name"] for task in block["always"]], + ["⏳ Join the background installs"], + ) + + def test_the_includes_hand_over_the_plugin(self): + start = _task(PLUGIN, "Start the installs that run beside the install loop") + self.assertEqual(start["vars"]["plugin_key"], "{{ plugin_item.key }}") + stage = _task( + PLUGIN, "Enable and configure the plugins installed in the background" + ) + self.assertEqual(stage["vars"]["plugin_key"], "{{ plugin_item.key }}") + self.assertEqual(stage["vars"]["plugin_value"], "{{ plugin_item.value }}") + + +class TestBackgroundJob(unittest.TestCase): + def setUp(self): + self.tasks = _tasks(BACKGROUND) + self.job = self.tasks[_index(self.tasks, "in the background")] + + def test_the_job_starts_then_queues_then_the_gate_polls(self): + order = [ + _index(self.tasks, "in the background"), + _index(self.tasks, "Queue"), + _index(self.tasks, "Hold the other installs"), + ] + self.assertEqual(order, sorted(order)) + self.assertEqual(len(order), len(self.tasks)) + + def test_the_job_is_fire_and_forget_in_every_mode(self): + self.assertEqual( + self.job["async"], "{{ NEXTCLOUD_PLUGIN_BACKGROUND_ASYNC_TIME }}" + ) + self.assertEqual(self.job["poll"], 0) + self.assertNotIn( + "ASYNC_ENABLED", str(self.job["async"]) + str(self.job["poll"]) + ) + + def test_the_gate_reads_the_job_file_first_then_the_schema_state(self): + script = self.job["ansible.builtin.shell"] + self.assertIn("app:install {{ plugin_key | quote }}", script) + gate = _task(BACKGROUND, "Hold the other installs")["ansible.builtin.shell"] + lines = gate["cmd"].strip().splitlines() + self.assertEqual( + lines[0], "cat {{ nextcloud_plugin_background_job.results_file | quote }}" + ) + self.assertEqual(lines[1], "echo") + self.assertEqual( + lines[2], + "{{ NEXTCLOUD_DOCKER_EXEC_INTERACTIVE }} php -- " + "{{ NEXTCLOUD_DOCKER_WORK_DIRECTORY | quote }} {{ plugin_key | quote }}", + ) + self.assertEqual(len(lines), 3) + self.assertEqual( + gate["stdin"], "{{ lookup('file', 'php/utils/migration_state.php') }}" + ) + + def test_the_gate_does_not_rely_on_debug_only_occ_commands(self): + gate = _task(BACKGROUND, "Hold the other installs")["ansible.builtin.shell"] + self.assertNotIn("migrations:", gate["cmd"]) + + def test_the_probe_reads_what_the_installer_writes(self): + probe = read_text(str(PROBE)) + self.assertIn("new \\OC\\DB\\MigrationService($appId", probe) + self.assertIn("\\OCP\\Server::get(\\OC\\DB\\Connection::class)", probe) + self.assertIn('"migrated" => $migrations->getMigratedVersions()', probe) + self.assertIn('"available" => $migrations->getAvailableVersions()', probe) + self.assertIn('echo "MIGRATION_STATE "', probe) + self.assertIn("[, $serverRoot, $appId] = $argv;", probe) + + def test_the_job_never_forces_an_install(self): + self.assertNotIn("--force", self.job["ansible.builtin.shell"]) + + def test_the_job_is_queued_for_the_join(self): + queue = _task(BACKGROUND, "Queue")["ansible.builtin.set_fact"] + jobs = queue["nextcloud_plugin_background_jobs"] + self.assertIn("nextcloud_plugin_background_job.ansible_job_id", jobs) + + +RUNNING = json.dumps({"started": True, "finished": False, "ansible_job_id": "j1.2"}) + + +def _gate_result(job: str, probe: str, rc: int) -> dict: + return { + "nextcloud_plugin_background_gate": { + "rc": rc, + "stdout": job + "\n" + probe, + "attempts": 1, + } + } + + +def _state(migrated: int, available: int) -> str: + versions = [f"{n:09d}Date20260129094821" for n in range(1, available + 1)] + state = {"migrated": versions[:migrated], "available": versions} + return "MIGRATION_STATE " + json.dumps(state) + + +SETTLED = _state(migrated=8, available=8) +MARKING = _state(migrated=3, available=8) + + +class TestGate(unittest.TestCase): + def setUp(self): + self.gate = _task(BACKGROUND, "Hold the other installs") + + def _decide(self, result: dict) -> tuple[bool, bool]: + return _eval(self.gate["until"], **result), _eval( + self.gate["failed_when"], **result + ) + + def test_an_applied_schema_releases_the_loop(self): + self.assertEqual( + self._decide(_gate_result(RUNNING, SETTLED, rc=0)), (True, False) + ) + + def test_a_schema_in_progress_keeps_polling(self): + until, _ = self._decide(_gate_result(RUNNING, MARKING, rc=0)) + self.assertFalse(until) + + def test_a_gate_that_never_opens_fails_the_deploy(self): + _, failed = self._decide(_gate_result(RUNNING, MARKING, rc=0)) + self.assertTrue(failed) + + def test_the_download_phase_keeps_polling(self): + self.assertEqual(self._decide(_gate_result(RUNNING, "", rc=0)), (False, True)) + + def test_an_ended_job_releases_the_loop(self): + ended = json.dumps({"rc": 1, "stdout": "recognize already installed"}) + self.assertEqual(self._decide(_gate_result(ended, "", rc=0)), (True, False)) + + def test_a_killed_job_stops_polling_and_fails(self): + for job in ( + {"rc": 124}, + {"rc": -9}, + {"msg": "Timeout exceeded", "failed": True}, + ): + with self.subTest(job=job): + self.assertEqual( + self._decide(_gate_result(json.dumps(job), MARKING, rc=0)), + (True, True), + ) + + def test_the_gate_outlasts_the_job(self): + self.assertEqual(self.gate["delay"], 2) + self.assertIn("NEXTCLOUD_PLUGIN_BACKGROUND_ASYNC_TIME", self.gate["retries"]) + self.assertIn("/ 2", self.gate["retries"]) + + def test_a_hung_probe_is_cut_off_by_the_exec_wrapper(self): + self.assertEqual( + self.gate["environment"]["CONTAINER_EXEC_TIMEOUT"], + "{{ lookup('timeout', 60) | int }}", + ) + + +class TestJoin(unittest.TestCase): + def setUp(self): + self.join = _task(PLUGIN, "Join the background installs") + + def _result(self, **result) -> dict: + return {"nextcloud_plugin_background_result": result} + + def test_the_join_outlasts_the_job(self): + self.assertEqual(self.join["delay"], 5) + self.assertIn("NEXTCLOUD_PLUGIN_BACKGROUND_ASYNC_TIME", self.join["retries"]) + self.assertIn("/ 5", self.join["retries"]) + + def test_a_running_job_is_polled(self): + self.assertFalse( + _ansible_eval( + self.join["until"], **self._result(started=True, finished=False) + ) + ) + + def test_a_finished_job_ends_the_poll(self): + self.assertTrue( + _ansible_eval(self.join["until"], **self._result(finished=True, rc=1)) + ) + + def test_an_occ_failure_is_left_to_the_install_stage(self): + for rc in (0, 1): + with self.subTest(rc=rc): + self.assertFalse( + _eval( + self.join["failed_when"], **self._result(finished=True, rc=rc) + ) + ) + + def test_a_job_without_an_occ_exit_code_fails_the_deploy(self): + for result in ( + {"finished": False, "started": True}, + {"finished": True, "msg": "Timeout exceeded", "failed": True}, + {"finished": True, "rc": 124}, + {"finished": True, "rc": -9}, + ): + with self.subTest(result=result): + self.assertTrue( + _eval(self.join["failed_when"], **self._result(**result)) + ) + + def test_only_a_fresh_install_reports_a_change(self): + changed = self.join["changed_when"] + self.assertTrue( + _eval(changed, **self._result(rc=0, stdout="recognize 12.0.2 installed")) + ) + self.assertFalse( + _eval(changed, **self._result(rc=1, stdout="recognize already installed")) + ) + self.assertFalse(_eval(changed, **self._result(finished=False))) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py b/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py index d55a5af2ef..0cf70f711c 100644 --- a/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py +++ b/tests/unit/python/roles/web-app-openbao/test_credential_rotation.py @@ -31,6 +31,7 @@ HCL_CONTEXT = { "OPENBAO_SEAL_KEY_ID": "0123456789abcdef", "OPENBAO_SEAL_KEY_PREVIOUS_ID": "fedcba9876543210", "OPENBAO_BASE_URL": "https://bao.example.com", + "OPENBAO_AUDIT_PATH": "stdout", } ENV_CONTEXT = { diff --git a/tests/unit/python/roles/web-app-openproject/filter_plugins/test_openproject_migrate.py b/tests/unit/python/roles/web-app-openproject/filter_plugins/test_openproject_migrate.py new file mode 100644 index 0000000000..7df5eb364b --- /dev/null +++ b/tests/unit/python/roles/web-app-openproject/filter_plugins/test_openproject_migrate.py @@ -0,0 +1,75 @@ +import importlib.util +import unittest + +from ansible.errors import AnsibleFilterError + +from . import PROJECT_ROOT + +PLUGIN = ( + PROJECT_ROOT + / "roles" + / "web-app-openproject" + / "filter_plugins" + / "openproject_migrate.py" +) + +_spec = importlib.util.spec_from_file_location("openproject_migrate", PLUGIN) +_mod = importlib.util.module_from_spec(_spec) +assert _spec.loader is not None +_spec.loader.exec_module(_mod) + +openproject_migrations_pending = _mod.openproject_migrations_pending +FilterModule = _mod.FilterModule + +PREVIOUS_IMAGE = "sha256:" + "a" * 64 +RUNNING_IMAGE = "sha256:" + "b" * 64 + + +class TestOpenprojectMigrationsPending(unittest.TestCase): + def test_registry_exposes_the_filter(self): + self.assertEqual( + set(FilterModule().filters()), {"openproject_migrations_pending"} + ) + + def test_unstamped_schema_migrates(self): + self.assertTrue(openproject_migrations_pending("", RUNNING_IMAGE)) + + def test_schema_stamped_by_the_running_image_skips(self): + self.assertFalse(openproject_migrations_pending(RUNNING_IMAGE, RUNNING_IMAGE)) + + def test_new_image_migrates(self): + self.assertTrue(openproject_migrations_pending(PREVIOUS_IMAGE, RUNNING_IMAGE)) + + def test_failed_first_migration_left_no_stamp_and_migrates_again(self): + self.assertTrue(openproject_migrations_pending("\n", RUNNING_IMAGE)) + + def test_failed_migration_of_a_new_image_kept_the_old_stamp_and_migrates_again( + self, + ): + self.assertTrue(openproject_migrations_pending(PREVIOUS_IMAGE, RUNNING_IMAGE)) + + def test_stamp_that_only_prefixes_the_image_migrates(self): + self.assertTrue( + openproject_migrations_pending(RUNNING_IMAGE[:-1], RUNNING_IMAGE) + ) + + def test_masked_stamp_migrates(self): + masked = RUNNING_IMAGE[:20] + "********" + RUNNING_IMAGE[28:] + self.assertTrue(openproject_migrations_pending(masked, RUNNING_IMAGE)) + + def test_trailing_newlines_of_both_reads_are_ignored(self): + self.assertFalse( + openproject_migrations_pending(RUNNING_IMAGE + "\n", RUNNING_IMAGE + "\n") + ) + + def test_missing_image_stops(self): + with self.assertRaisesRegex(AnsibleFilterError, "no image id"): + openproject_migrations_pending(RUNNING_IMAGE, "") + + def test_blank_image_stops_even_against_a_blank_stamp(self): + with self.assertRaises(AnsibleFilterError): + openproject_migrations_pending("", " \n") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-openproject/test_admin_stamp.py b/tests/unit/python/roles/web-app-openproject/test_admin_stamp.py new file mode 100644 index 0000000000..b6161d2fd5 --- /dev/null +++ b/tests/unit/python/roles/web-app-openproject/test_admin_stamp.py @@ -0,0 +1,352 @@ +from __future__ import annotations + +import base64 +import json +import re +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +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_SERVICES, ROLE_FILE_VARS_MAIN +from utils.templating.ansible import _trust_as_template + +ROLE = PROJECT_ROOT / "roles" / "web-app-openproject" +GATE = ROLE / "tasks" / "04_admin.yml" +STATE = ROLE / "tasks" / "04_admin" / "state.yml" +PROVISION = ROLE / "tasks" / "04_admin" / "provision.yml" +VARS = ROLE / ROLE_FILE_VARS_MAIN +SERVICES = ROLE / ROLE_FILE_META_SERVICES +QUERY = ROLE / "files" / "sql" / "select" / "admin-state.sql" + +FIRST_READ = "📖 Read the settings, administrator and LDAP link OpenProject holds" +READ = "🔍 Read the settings, administrator and LDAP link OpenProject holds" +DIGEST = "🧮 Digest the run's sources, inputs and the state OpenProject holds" +DECIDE = "🧮 Decide whether the settings and administrator need a run" +GATED = "🔧 Run the settings and administrator step and stamp what it left" +RUN = "🔧 Apply settings, ensure the administrator and link it to LDAP" +REREAD = "📖 Read the settings, administrator and LDAP link the run left" +STAMP = "📝 Stamp the settings, administrator and LDAP link the run left" + +SETTINGS = { + "email_delivery_method": "smtp", + "smtp_address": "mail.infinito.example", + "smtp_domain": "infinito.example", + "smtp_user_name": "no-reply@infinito.example", + "smtp_password": "smtp-token", + "smtp_ssl": False, +} +STORED_SETTINGS = "email_delivery_method=a1,smtp_address=b2,smtp_password=c3" +STEADY = { + "id": "7", + "admin": "t", + "status": "1", + "force_password_change": "f", + "ldap_auth_source_id": "3", + "password_id": "41", + "password_md5": "9f86d081", + "ldap_source_id": "3", + "settings": STORED_SETTINGS, + "seeded_admin": "1=3", +} +ABSENT = { + "changed": False, + "skipped": True, + "false_condition": "openproject_admin_stamp_file.stat.exists", +} + + +def _row(**changes: str) -> list[str]: + """Return the row the state query yields, in its column order. + + Args: + changes: columns whose value differs from the steady state. + """ + return list({**STEADY, **changes}.values()) + + +def _flat(tasks: list[dict]) -> list[dict]: + """Return the tasks in run order, each block followed by its children. + + Args: + tasks: parsed task list of one task file. + """ + flat: list[dict] = [] + for task in tasks: + flat.append(task) + flat.extend(_flat(task.get("block") or [])) + return flat + + +def _tasks(path) -> list[dict]: + return _flat(load_yaml_any(str(path), default_if_missing=[])) + + +def _task(path, name: str) -> dict: + return next(task for task in _tasks(path) if task.get("name") == name) + + +def _render(template, **variables): + templar = Templar(loader=DataLoader(), variables=variables) + return templar.template(_trust_as_template(template)) + + +def _sources() -> list[str]: + raw = load_yaml_any(str(VARS))["OPENPROJECT_ADMIN_SOURCES"] + return [_render(item, role_path=str(ROLE)) for item in raw] + + +INPUTS = { + "OPENPROJECT_ADMIN_SOURCES": _sources(), + "OPENPROJECT_VERSION": "17", + "OPENPROJECT_ADMINISTRATOR_USERNAME": "administrator", + "OPENPROJECT_ADMINISTRATOR_EMAIL": "administrator@infinito.example", + "OPENPROJECT_ADMINISTRATOR_PASSWORD": "Sw0rdf1sh!", + "OPENPROJECT_RAILS_SETTINGS": SETTINGS, + "OPENPROJECT_ADMIN_LDAP_NAME": "infinito.example", +} + + +def _digest(row: list[str], **inputs) -> str: + """Render the digest the state step records. + + Args: + row: the one row the state query returns. + inputs: overrides of the role variables in INPUTS. + """ + expression = _task(STATE, DIGEST)["ansible.builtin.set_fact"][ + "openproject_admin_digest" + ] + return _render( + expression, + **{**INPUTS, **inputs}, + openproject_admin_state={"rows": [row]}, + ) + + +def _stamp(digest: str) -> dict: + """Return the slurp result of a stamp holding ``digest``. + + Args: + digest: the digest the stamp file holds. + """ + content = base64.b64encode(f"{digest}\n".encode()).decode() + return {"changed": False, "content": content, "encoding": "base64"} + + +def _decision() -> str: + return _task(GATE, DECIDE)["ansible.builtin.set_fact"]["openproject_admin_due"] + + +def _due(stamp: dict, digest: str, force=False, decision: str = "") -> bool: + """Render whether the settings and administrator run is due. + + Args: + stamp: the registered slurp result of the stamp file. + digest: the digest of the current sources, inputs and state. + force: the value of services.openproject.admin.force. + decision: the decision expression; the gate's own when empty. + """ + due = _render( + decision or _decision(), + OPENPROJECT_ADMIN_FORCE=force, + openproject_admin_stamp=stamp, + openproject_admin_digest=digest, + ) + return _render("{{ due | bool }}", due=due) + + +class TestDecision(unittest.TestCase): + def setUp(self): + self.digest = _digest(_row()) + + def test_a_missing_stamp_runs_the_step(self): + self.assertTrue(_due(ABSENT, self.digest)) + + def test_a_stamp_equal_to_the_digest_skips_the_step(self): + self.assertFalse(_due(_stamp(self.digest), self.digest)) + + def test_a_stamp_different_from_the_digest_runs_the_step(self): + rotated = _digest(_row(), OPENPROJECT_ADMINISTRATOR_PASSWORD="rotated") + self.assertTrue(_due(_stamp(rotated), self.digest)) + + def test_force_runs_the_step_on_an_equal_stamp(self): + for force in (True, "true"): + with self.subTest(force=force): + self.assertTrue(_due(_stamp(self.digest), self.digest, force=force)) + + def test_negative_control_a_gate_blind_to_the_digest_misses_the_drift(self): + blind = _decision().replace( + "!= openproject_admin_digest", + "!= (openproject_admin_stamp.content | b64decode | trim)", + ) + self.assertNotEqual(blind, _decision()) + demoted = _stamp(_digest(_row(admin="f"))) + self.assertFalse(_due(demoted, self.digest, decision=blind)) + self.assertTrue(_due(demoted, self.digest)) + + +class TestDigest(unittest.TestCase): + def test_the_same_sources_inputs_and_state_give_the_same_digest(self): + self.assertEqual(_digest(_row()), _digest(_row())) + self.assertRegex(_digest(_row()), r"^[0-9a-f]{64}$") + + def test_drift_in_openproject_changes_the_digest(self): + removed = dict.fromkeys(list(STEADY)[:7], "") + drifts = { + "administrator removed": _row(**removed), + "administrator demoted": _row(admin="f"), + "administrator locked": _row(status="3"), + "password change forced": _row(force_password_change="t"), + "LDAP link dropped": _row(ldap_auth_source_id=""), + "password changed in the UI": _row(password_id="42", password_md5="e3b0"), + "password rehashed in place": _row(password_md5="e3b0"), + "LDAP source replaced": _row(ldap_source_id="4"), + "setting edited in the UI": _row( + settings=STORED_SETTINGS.replace("c3", "d4") + ), + "setting deleted": _row(settings="email_delivery_method=a1"), + "seeded admin unlocked": _row(seeded_admin="1=1"), + } + steady = _digest(_row()) + for drift, row in drifts.items(): + with self.subTest(drift=drift): + self.assertEqual(len(row), len(STEADY)) + self.assertNotEqual(_digest(row), steady) + + def test_changed_inputs_change_the_digest(self): + changes = { + "OPENPROJECT_ADMINISTRATOR_PASSWORD": "rotated", + "OPENPROJECT_ADMINISTRATOR_USERNAME": "root", + "OPENPROJECT_ADMINISTRATOR_EMAIL": "root@infinito.example", + "OPENPROJECT_RAILS_SETTINGS": {**SETTINGS, "smtp_password": "rotated"}, + "OPENPROJECT_ADMIN_LDAP_NAME": "", + "OPENPROJECT_VERSION": "18", + "OPENPROJECT_ADMIN_SOURCES": [ + str(ROLE / "files" / "ruby" / "drain_jobs.rb"), + *INPUTS["OPENPROJECT_ADMIN_SOURCES"][1:], + ], + } + steady = _digest(_row()) + for name, value in changes.items(): + with self.subTest(input=name): + self.assertNotEqual(_digest(_row(), **{name: value}), steady) + + def test_secrets_reach_the_digest_only_hashed(self): + expression = _task(STATE, DIGEST)["ansible.builtin.set_fact"][ + "openproject_admin_digest" + ] + for entry in ( + "'password': OPENPROJECT_ADMINISTRATOR_PASSWORD | hash('sha256')", + ( + "'settings': OPENPROJECT_RAILS_SETTINGS | to_json(sort_keys=true)" + " | hash('sha256')" + ), + ): + with self.subTest(entry=entry): + self.assertIn(entry, expression) + + +class TestSources(unittest.TestCase): + def test_every_file_the_run_reads_is_a_source(self): + provision = read_text(str(PROVISION)) + read = { + str(ROLE / "files" / name) + for name in re.findall(r"lookup\('file', '([^']+)'\)", provision) + } + self.assertEqual(len(read), 4) + self.assertLessEqual(read | {str(PROVISION)}, set(_sources())) + + def test_every_source_exists(self): + for source in _sources(): + with self.subTest(source=source): + self.assertTrue(read_text(source)) + + +class TestQuery(unittest.TestCase): + def test_the_query_reads_what_the_scripts_write(self): + sql = read_text(str(QUERY)) + for fragment in ( + "account.admin", + "account.status", + "account.force_password_change", + "account.ldap_auth_source_id", + "FROM user_passwords", + "JOIN ldap_auth_sources", + "FROM settings", + "seeded.status", + ): + with self.subTest(fragment=fragment): + self.assertIn(fragment, sql) + + def test_the_query_returns_hashes_not_secrets(self): + sql = read_text(str(QUERY)) + secrets = [ + match + for match in re.finditer(r"(\w+)\.(hashed_password|value)\b", sql) + if match.group(1) != "candidate" + ] + self.assertEqual(len(secrets), 2) + for match in secrets: + with self.subTest(column=match.group(0)): + self.assertEqual(sql[match.start() - 4 : match.start()], "md5(") + + def test_the_query_reads_exactly_the_settings_the_run_applies(self): + args = _task(STATE, READ)["database_query"]["named_args"] + names = _render(args["settings"], OPENPROJECT_RAILS_SETTINGS=SETTINGS) + self.assertEqual(json.loads(names), list(SETTINGS)) + self.assertEqual(args["ldap_name"], "{{ OPENPROJECT_ADMIN_LDAP_NAME }}") + self.assertEqual(args["login"], "{{ OPENPROJECT_ADMINISTRATOR_USERNAME }}") + + +class TestWiring(unittest.TestCase): + def test_the_run_is_followed_by_a_reread_and_a_stamp(self): + names = [task["name"] for task in _tasks(GATE)] + order = [names.index(n) for n in (FIRST_READ, DECIDE, RUN, REREAD, STAMP)] + self.assertEqual(order, sorted(order)) + + def test_run_reread_and_stamp_wait_for_the_decision(self): + gated = _task(GATE, GATED) + self.assertEqual(gated["when"], "openproject_admin_due | bool") + self.assertEqual( + [task["name"] for task in gated["block"]], [RUN, REREAD, STAMP] + ) + + def test_both_state_reads_are_masked(self): + for name in (FIRST_READ, REREAD): + with self.subTest(task=name): + include = _task(GATE, name)["include_tasks"] + self.assertEqual(include["file"], "04_admin/state.yml") + self.assertEqual( + include["apply"]["no_log"], + "{{ MASK_CREDENTIALS_IN_LOGS | bool }}", + ) + + def test_the_stamp_holds_only_the_digest_and_only_for_its_owner(self): + stamp = _task(GATE, STAMP)["stack_host_copy"] + self.assertEqual(stamp["content"], "{{ openproject_admin_digest }}\n") + self.assertEqual(stamp["mode"], "0600") + self.assertEqual(stamp["dest"], "{{ OPENPROJECT_ADMIN_STAMP_FILE }}") + self.assertIn( + "directories.instance", + load_yaml_any(str(VARS))["OPENPROJECT_ADMIN_STAMP_FILE"], + ) + + def test_the_force_flag_is_declared_off(self): + openproject = load_yaml_any(str(SERVICES))["openproject"] + self.assertIs(openproject["admin"]["force"], False) + self.assertIn( + "'services.openproject.admin.force'", + load_yaml_any(str(VARS))["OPENPROJECT_ADMIN_FORCE"], + ) + + def test_the_link_uses_the_ldap_name_the_state_reads(self): + provision = read_text(str(PROVISION)) + self.assertIn("OPENPROJECT_ADMIN_LDAP_NAME", provision) + self.assertNotIn("OPENPROJECT_LDAP.name", provision) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-stalwart/test_account_batch.py b/tests/unit/python/roles/web-app-stalwart/test_account_batch.py index c31ac7363d..c033c699ec 100644 --- a/tests/unit/python/roles/web-app-stalwart/test_account_batch.py +++ b/tests/unit/python/roles/web-app-stalwart/test_account_batch.py @@ -82,19 +82,42 @@ BASE = { "stalwart_app_password_stale": {}, } +PASSWORD = {"@type": "Password", "secret": "********"} +APP_PASSWORD = {"@type": "AppPassword", "description": DESCRIPTION} + + +def _violation(object_id: str, object_type: str = "Account") -> dict: + return { + "type": "primaryKeyViolation", + "properties": ["email"], + "objectId": {"object": object_type, "id": object_id}, + } + + +def _held(object_id: str, name: str, credentials: dict | None = None) -> dict: + return { + "id": object_id, + "name": name, + "domainId": "d1", + "credentials": {"0": PASSWORD} if credentials is None else credentials, + } + + CREATE_RESPONSE = [ [ "x:Account/set", { "created": {"u0": {"id": "a"}}, - "notCreated": { - "u1": {"type": "alreadyExists", "objectId": {"id": "b"}}, - "u2": {"type": "alreadyExists", "objectId": {"id": "c"}}, - }, + "notCreated": {"u1": _violation("b"), "u2": _violation("c")}, }, "c0", ] ] +HELD = ( + _held("a", "administrator"), + _held("b", "no-reply"), + _held("c", "contact"), +) def _resolved() -> list[dict]: @@ -106,7 +129,7 @@ def _resolved() -> list[dict]: ) -def _matched(response: list = CREATE_RESPONSE, listed: tuple = ()) -> list[dict]: +def _matched(response: list = CREATE_RESPONSE, listed: tuple = HELD) -> list[dict]: return _fact( "04_manage_user.yml", "🔍 Match every account to its Stalwart id", @@ -209,10 +232,73 @@ class TestAccountPhases(unittest.TestCase): def test_an_existing_account_without_an_id_fails(self): response = [ - ["x:Account/set", {"notCreated": {"u0": {"type": "alreadyExists"}}}, "c0"] + [ + "x:Account/set", + {"notCreated": {"u0": {"type": "primaryKeyViolation"}}}, + "c0", + ] + ] + refused = _refused(_matched(response, listed=())) + self.assertIn("administrator@infinito.test", refused) + + def test_a_primary_key_violation_on_the_listed_account_is_existing(self): + accounts = {a["key"]: a for a in _matched()} + self.assertEqual( + {key: (a["id"], a["existing"]) for key, a in accounts.items()}, + { + "administrator": ("a", False), + "no-reply": ("b", True), + "contact": ("c", True), + }, + ) + self.assertEqual(_refused(list(accounts.values())), {}) + + def test_a_violation_against_another_object_is_refused(self): + alias = _violation("a") + mailing_list = _violation("c", "MailingList") + response = [ + [ + "x:Account/set", + { + "created": {"u0": {"id": "a"}}, + "notCreated": {"u1": alias, "u2": mailing_list}, + }, + "c0", + ] + ] + accounts = _matched(response) + self.assertEqual([a["existing"] for a in accounts], [False, False, False]) + self.assertEqual( + _refused(accounts), + {"no-reply@infinito.test": alias, "contact@infinito.test": mailing_list}, + ) + + def test_an_unknown_refusal_of_a_listed_bot_fails_without_sso(self): + refusal = {"type": "invalidProperties", "properties": ["description"]} + response = [ + [ + "x:Account/set", + {"notCreated": {"u0": _violation("a"), "u1": refusal, "u2": refusal}}, + "c0", + ] ] refused = _refused(_matched(response)) - self.assertIn("administrator@infinito.test", refused) + self.assertEqual( + refused, + {"no-reply@infinito.test": refusal, "contact@infinito.test": refusal}, + ) + + def test_an_unknown_refusal_of_a_listed_bot_fails_under_sso(self): + refusal = {"type": "invalidProperties", "properties": ["description"]} + response = [ + [ + "x:Account/set", + {"notCreated": {"u0": EXTERNAL, "u1": refusal, "u2": EXTERNAL}}, + "c0", + ] + ] + refused = _refused(_matched(response), sso=True) + self.assertEqual(refused, {"no-reply@infinito.test": refusal}) def test_accounts_of_an_external_directory_take_their_listed_ids(self): listed = ( @@ -271,9 +357,65 @@ class TestAccountPhases(unittest.TestCase): ) method, arguments, _ = body["methodCalls"][0] self.assertEqual(method, "x:Account/set") - self.assertEqual(sorted(arguments["update"]), ["b", "c"]) self.assertEqual( - arguments["update"]["c"]["credentials"]["0"]["secret"], _sha("contact-pw") + arguments["update"], + { + "b": {"credentials/0/secret": _sha("no-reply-pw")}, + "c": {"credentials/0/secret": _sha("contact-pw")}, + }, + ) + + def _update_of_contact(self, credentials: dict) -> dict: + listed = (*HELD[:2], _held("c", "contact", credentials)) + body = _body( + "04_manage_user.yml", + "🔄 Send the passwords of the pre-existing accounts", + **BASE, + stalwart_accounts=_matched(listed=listed), + ) + return body["methodCalls"][0][1]["update"]["c"] + + def test_the_patch_keeps_the_other_credentials_of_the_account(self): + update = self._update_of_contact({"0": APP_PASSWORD, "3": PASSWORD}) + self.assertEqual(update, {"credentials/3/secret": _sha("contact-pw")}) + + def test_an_account_without_a_password_gets_one_at_a_free_key(self): + self.assertEqual( + self._update_of_contact({"0": APP_PASSWORD, "1": APP_PASSWORD}), + {"credentials/2/secret": _sha("contact-pw")}, + ) + self.assertEqual( + self._update_of_contact({}), {"credentials/0/secret": _sha("contact-pw")} + ) + + def test_one_store_write_carries_every_bot(self): + task = _task( + "04_manage_user.yml", + "💾 Persist the Stalwart submission credential of every bot", + ) + self.assertEqual( + task["ansible.builtin.include_role"]["tasks_from"], "write_many.yml" + ) + self.assertNotIn("loop", task) + entries = _render( + task["vars"]["sys_token_store_entries"], + **BASE, + stalwart_accounts=_matched(), + ) + self.assertEqual( + entries, + [ + { + "user_key": "no-reply", + "app": "web-app-stalwart", + "token": _sha("no-reply-pw"), + }, + { + "user_key": "contact", + "app": "web-app-stalwart", + "token": _sha("contact-pw"), + }, + ], ) def test_a_refused_update_fails_naming_the_account(self): @@ -493,6 +635,31 @@ class TestAppPasswordPhases(unittest.TestCase): ], ) + def test_the_minted_passwords_land_in_one_store_write(self): + task = _task( + "04_manage_user/app_password.yml", "💾 Persist the new app passwords" + ) + self.assertEqual( + task["ansible.builtin.include_role"]["tasks_from"], "write_many.yml" + ) + self.assertNotIn("loop", task) + minted = [ + {"key": "no-reply", "address": "no-reply@infinito.test", "secret": "p1"}, + {"key": "contact", "address": "contact@infinito.test", "secret": "p2"}, + ] + entries = _render( + task["vars"]["sys_token_store_entries"], + **BASE, + stalwart_app_password_minted=minted, + ) + self.assertEqual( + entries, + [ + {"user_key": "no-reply", "app": "web-app-stalwart", "token": "p1"}, + {"user_key": "contact", "app": "web-app-stalwart", "token": "p2"}, + ], + ) + def test_the_record_keeps_the_owners_of_an_earlier_chunk(self): stale = _fact( "04_manage_user/app_password.yml", diff --git a/tests/unit/python/roles/web-app-stalwart/test_forward_batch.py b/tests/unit/python/roles/web-app-stalwart/test_forward_batch.py new file mode 100644 index 0000000000..304599ea3d --- /dev/null +++ b/tests/unit/python/roles/web-app-stalwart/test_forward_batch.py @@ -0,0 +1,369 @@ +from __future__ import annotations + +import json +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.plugins.loader import filter_loader +from ansible.template import Templar + +from utils.cache.yaml import load_yaml_any +from utils.templating.ansible import _trust_as_template + +from . import PROJECT_ROOT + +ROLE = PROJECT_ROOT / "roles" / "web-app-stalwart" +TASKS = ROLE / "tasks" +OWN = "infinito-forward" +SETUP = "16_forwards.yml" +APPLY = "16_forwards/apply.yml" +UPLOAD = "📤 Upload the changed forward scripts" +POINT = "📁 Point the forward scripts at their uploads and activate them" + +filter_loader.add_directory(str(ROLE / "filter_plugins")) + +ACCOUNT_IDS = { + "kept@infinito.test": "k", + "paused@infinito.test": "p", + "fresh@infinito.test": "f", + "moved@infinito.test": "m", +} +CHUNK = [ + {"address": "kept@infinito.test", "destinations": ["a@example.org"]}, + {"address": "paused@infinito.test", "destinations": ["b@example.org"]}, + {"address": "fresh@infinito.test", "destinations": ["c@example.org"]}, + {"address": "moved@infinito.test", "destinations": ["new@example.org"]}, +] + + +def _flatten(tasks: list[dict]) -> list[dict]: + flat = [] + for task in tasks: + flat.append(task) + flat.extend(_flatten(task.get("block") or [])) + return flat + + +def _task(path: str, name: str) -> dict: + tasks = _flatten(load_yaml_any(str(TASKS / path), default_if_missing=[])) + return next(t for t in tasks if t.get("name") == name) + + +def _render(template, **variables): + templar = Templar(loader=DataLoader(), variables=variables) + return templar.template(_trust_as_template(template)) + + +def _with_task_vars(task: dict, variables: dict) -> dict: + variables = dict(variables) + for name, raw in (task.get("vars") or {}).items(): + if name != "stalwart_jmap_body": + variables[name] = _render(raw, **variables) + return variables + + +def _fact(path: str, name: str, fact: str, **variables): + task = _task(path, name) + return _render( + task["ansible.builtin.set_fact"][fact], **_with_task_vars(task, variables) + ) + + +def _body(path: str, name: str, **variables) -> dict: + task = _task(path, name) + return json.loads( + _render(task["vars"]["stalwart_jmap_body"], **_with_task_vars(task, variables)) + ) + + +def _when(path: str, name: str, **variables) -> bool: + task = _task(path, name) + return _render("{{ (" + task["when"] + ") | bool }}", **variables) + + +def _script(destinations: list[str], include: str = "") -> str: + return _render( + "{{ destinations | stalwart_forward_script(include) }}", + destinations=destinations, + include=include, + ) + + +def _upload(account: str, n: int, script: str) -> dict: + return { + "accountId": account, + "create": {f"b{n}": {"data": [{"data:asText": script}]}}, + } + + +BASE = { + "STALWART_FORWARD_SCRIPT_NAME": OWN, + "STALWART_FORWARDS": CHUNK, + "STALWART_JMAP_MAX_METHOD_CALLS": 16, + "stalwart_forward_chunk": CHUNK, + "stalwart_forward_account_ids": ACCOUNT_IDS, +} + +LISTED = { + "kept@infinito.test": [ + {"id": "s1", "name": OWN, "blobId": "B1", "isActive": True}, + ], + "paused@infinito.test": [ + {"id": "s2", "name": OWN, "blobId": "B2", "isActive": False}, + ], + "fresh@infinito.test": [ + {"id": "u3", "name": "rules", "blobId": "B3", "isActive": True}, + ], + "moved@infinito.test": [ + {"id": "s4", "name": OWN, "blobId": "B4", "isActive": True}, + ], +} +TEXTS = { + "kept@infinito.test": _script(["a@example.org"]), + "paused@infinito.test": _script(["b@example.org"]), + "moved@infinito.test": _script(["old@example.org"]), +} + + +def _states() -> list[dict]: + return _fact( + APPLY, + "🔍 Find the forward script of every forwarding account", + "stalwart_forward_states", + **BASE, + stalwart_jmap={ + "methodResponses": [ + ["SieveScript/get", {"list": scripts}, address] + for address, scripts in reversed(list(LISTED.items())) + ] + }, + ) + + +def _plan(texts: dict = TEXTS) -> list[dict]: + return _fact( + APPLY, + "🔍 Render the forward script of every forwarding account", + "stalwart_forward_plan", + **BASE, + stalwart_forward_states=_states(), + stalwart_jmap={ + "methodResponses": [ + ["Blob/get", {"list": [{"id": "x", "data:asText": text}]}, address] + for address, text in texts.items() + ] + }, + ) + + +def _only(address: str) -> list[dict]: + return [step for step in _plan() if step["address"] == address] + + +class TestForwardSetup(unittest.TestCase): + def test_one_read_carries_the_limits_domains_and_accounts(self): + body = _body( + SETUP, + "📖 Read the Sieve limits of user scripts and the accounts the forwards belong to", + **BASE, + ) + self.assertEqual( + [call[0] for call in body["methodCalls"]], + ["x:SieveUserInterpreter/get", "x:Domain/get", "x:Account/get"], + ) + + def test_accounts_resolve_by_their_full_address(self): + ids = _fact( + SETUP, + "🔍 Check Sieve limits against the widest forward, resolve forwarders", + "stalwart_forward_account_ids", + **BASE, + stalwart_jmap={ + "methodResponses": [ + ["x:SieveUserInterpreter/get", {"list": [{}]}, "c0"], + [ + "x:Domain/get", + {"list": [{"id": "d1", "name": "infinito.test"}]}, + "c1", + ], + [ + "x:Account/get", + { + "list": [ + {"id": "k", "name": "Kept", "domainId": "d1"}, + {"id": "z", "name": "kept", "domainId": "d9"}, + ] + }, + "c2", + ], + ] + }, + ) + self.assertEqual(ids, {"kept@infinito.test": "k"}) + + def test_forwards_are_chunked_by_the_method_call_limit(self): + loop = _task( + SETUP, "📨 Keep the forward script of every forwarding account in place" + )["loop"] + forwards = [{"address": f"f{i}@infinito.test"} for i in range(17)] + chunks = _render( + loop, STALWART_FORWARDS=forwards, STALWART_JMAP_MAX_METHOD_CALLS=16 + ) + self.assertEqual([len(c) for c in chunks], [16, 1]) + + +class TestForwardPhases(unittest.TestCase): + def test_one_list_addresses_every_account_by_its_id(self): + body = _body( + APPLY, "📖 List the Sieve scripts of the forwarding accounts", **BASE + ) + self.assertEqual( + body["using"], ["urn:ietf:params:jmap:core", "urn:ietf:params:jmap:sieve"] + ) + self.assertEqual( + body["methodCalls"], + [ + [ + "SieveScript/get", + {"accountId": ACCOUNT_IDS[f["address"]], "ids": None}, + f["address"], + ] + for f in CHUNK + ], + ) + + def test_one_read_fetches_only_the_scripts_the_role_owns(self): + body = _body( + APPLY, + "📖 Read the forward scripts the accounts already hold", + **BASE, + stalwart_forward_states=_states(), + ) + self.assertEqual( + body["methodCalls"], + [ + [ + "Blob/get", + { + "accountId": account, + "ids": [blob], + "properties": ["data:asText"], + }, + address, + ] + for address, account, blob in ( + ("kept@infinito.test", "k", "B1"), + ("paused@infinito.test", "p", "B2"), + ("moved@infinito.test", "m", "B4"), + ) + ], + ) + + def test_the_plan_writes_changed_scripts_and_reactivates_paused_ones(self): + plan = {step["address"]: step for step in _plan()} + self.assertEqual( + {a: (s["write"], s["activate"]) for a, s in plan.items()}, + { + "kept@infinito.test": (False, False), + "paused@infinito.test": (False, True), + "fresh@infinito.test": (True, False), + "moved@infinito.test": (True, False), + }, + ) + self.assertEqual( + plan["fresh@infinito.test"]["script"], _script(["c@example.org"], "rules") + ) + self.assertEqual(plan["moved@infinito.test"]["own"], "s4") + self.assertEqual(plan["fresh@infinito.test"]["own"], "") + + def test_an_owned_script_stalwart_did_not_return_is_named(self): + texts = {a: t for a, t in TEXTS.items() if a != "paused@infinito.test"} + unread = _render( + _task( + APPLY, + "✅ Ensure Stalwart returned the forward script of every account that holds one", + )["vars"]["stalwart_forward_unread"], + stalwart_forward_plan=_plan(texts), + ) + self.assertEqual(unread, ["paused@infinito.test"]) + + def test_upload_and_set_touch_only_the_accounts_that_need_it(self): + plan = _plan() + upload = _body(APPLY, UPLOAD, **BASE, stalwart_forward_plan=plan) + self.assertEqual( + upload["methodCalls"], + [ + [ + "Blob/upload", + _upload("f", 2, _script(["c@example.org"], "rules")), + "fresh@infinito.test", + ], + [ + "Blob/upload", + _upload("m", 3, _script(["new@example.org"])), + "moved@infinito.test", + ], + ], + ) + point = _body( + APPLY, + POINT, + **BASE, + stalwart_forward_plan=plan, + stalwart_jmap={ + "methodResponses": [ + [ + "Blob/upload", + {"created": {"b2": {"id": "N2"}}}, + "fresh@infinito.test", + ], + [ + "Blob/upload", + {"created": {"b3": {"id": "N3"}}}, + "moved@infinito.test", + ], + ] + }, + ) + self.assertEqual( + point["methodCalls"], + [ + [ + "SieveScript/set", + {"accountId": "p", "onSuccessActivateScript": "s2"}, + "paused@infinito.test", + ], + [ + "SieveScript/set", + { + "accountId": "f", + "create": {"f2": {"name": OWN, "blobId": "N2"}}, + "onSuccessActivateScript": "#f2", + }, + "fresh@infinito.test", + ], + [ + "SieveScript/set", + { + "accountId": "m", + "update": {"s4": {"blobId": "N3"}}, + "onSuccessActivateScript": "s4", + }, + "moved@infinito.test", + ], + ], + ) + + def test_a_steady_state_skips_upload_and_set(self): + plan = _only("kept@infinito.test") + self.assertFalse(_when(APPLY, UPLOAD, stalwart_forward_plan=plan)) + self.assertFalse(_when(APPLY, POINT, stalwart_forward_plan=plan)) + + def test_a_reactivation_alone_skips_the_upload_but_not_the_set(self): + plan = _only("paused@infinito.test") + self.assertFalse(_when(APPLY, UPLOAD, stalwart_forward_plan=plan)) + self.assertTrue(_when(APPLY, POINT, stalwart_forward_plan=plan)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-stalwart/test_onion_route.py b/tests/unit/python/roles/web-app-stalwart/test_onion_route.py index 296133e61b..5ed52da1f0 100644 --- a/tests/unit/python/roles/web-app-stalwart/test_onion_route.py +++ b/tests/unit/python/roles/web-app-stalwart/test_onion_route.py @@ -121,7 +121,7 @@ class TestRelayRouteRendersValidJson(unittest.TestCase): route = args["create"][ROUTE_NAME] self.assertEqual(route["@type"], "Relay") self.assertEqual(route["name"], ROUTE_NAME) - self.assertEqual(route["address"], "tor-smtp") + self.assertEqual(route["host"], "tor-smtp") self.assertEqual(route["port"], 1525) def test_the_relay_hop_is_plaintext_smtp(self): diff --git a/tests/unit/python/roles/web-app-stalwart/test_store_guard.py b/tests/unit/python/roles/web-app-stalwart/test_store_guard.py new file mode 100644 index 0000000000..d4fac3929c --- /dev/null +++ b/tests/unit/python/roles/web-app-stalwart/test_store_guard.py @@ -0,0 +1,203 @@ +"""The guard that keeps Stalwart 1.x from opening a store from before 1.0. + +The marker a finished 1.x deploy leaves on the stack host passes the guard +without touching the store. Without the marker the guard reads every store +that exists, stops when a dedicated database is not running, migrates a store +from before 1.0, stops when the migration leaves it unmigrated, and lets a +fresh install through. +""" + +from __future__ import annotations + +import base64 +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from utils.cache.yaml import load_yaml_any +from utils.roles.mapping import ROLE_FILE_VARS_MAIN +from utils.templating.ansible import _trust_as_template + +from . import PROJECT_ROOT + +ROLE = PROJECT_ROOT / "roles" / "web-app-stalwart" +GUARD = ROLE / "tasks" / "store_guard.yml" +MANAGER_OPS = ROLE / "tasks" / "manager_ops.yml" +VARS = ROLE / ROLE_FILE_VARS_MAIN + +PASS = "pass" +ENGINE_DOWN = "Ensure the dedicated store database runs" +PRE_1_0 = "Ensure Stalwart opens no store from before 1.0" +MIGRATION = "store_guard/migrate.yml" + +SKIPPED = {"skipped": True, "changed": False} +NO_MARKER = { + "stalwart_store_marker_file": {"changed": False, "stat": {"exists": False}} +} + + +def _render(template: str, **variables): + templar = Templar(loader=DataLoader(), variables=variables) + return templar.template(_trust_as_template(template)) + + +def _holds(condition: str, facts: dict) -> bool: + return _render("{{ (" + condition + ") | bool }}", **facts) + + +def _module(task: dict, name: str) -> dict | None: + return task.get(f"ansible.builtin.{name}") or task.get(name) + + +def _layout_version() -> str: + return load_yaml_any(str(VARS), default_if_missing={})[ + "STALWART_STORE_LAYOUT_VERSION" + ] + + +def _written_marker() -> str: + tasks = load_yaml_any(str(MANAGER_OPS), default_if_missing=[]) + copy = next( + t["stack_host_copy"] + for t in tasks + if t.get("stack_host_copy", {}).get("dest") + == "{{ STALWART_STORE_MARKER_FILE }}" + ) + return _render(copy["content"], STALWART_STORE_LAYOUT_VERSION=_layout_version()) + + +def _guard(results: dict[str, dict], *, shared: bool) -> str: + """Walk store_guard.yml in task order, the way Ansible runs it. + + Args: + results: the result of every task that runs, keyed by its register name, + and the layout the migration leaves, keyed by MIGRATION; a task that + runs without an entry fails the test with a KeyError. + shared: whether the store lives on the shared PostgreSQL. + + Returns: + the name of the first assert that fails, or PASS. + """ + facts = { + "STALWART_DATABASE_SHARED": shared, + "STALWART_STORE_LAYOUT_VERSION": _layout_version(), + } + for task in load_yaml_any(str(GUARD), default_if_missing=[]): + when = task.get("when", []) + if not all( + _holds(c, facts) for c in (when if isinstance(when, list) else [when]) + ): + if "register" in task: + facts[task["register"]] = SKIPPED + continue + set_fact = _module(task, "set_fact") + assertion = _module(task, "assert") + include = _module(task, "include_tasks") + if set_fact is not None: + facts.update({k: _render(v, **facts) for k, v in set_fact.items()}) + elif include is not None: + facts["stalwart_store_layout"] = results[include] + elif assertion is not None: + if not all(_holds(c, facts) for c in assertion["that"]): + return task["name"] + else: + facts[task["register"]] = results[task["register"]] + return PASS + + +def _marker(content: str) -> dict: + return { + "stalwart_store_marker_file": {"changed": False, "stat": {"exists": True}}, + "stalwart_store_marker": { + "changed": False, + "content": base64.b64encode(content.encode()).decode(), + }, + } + + +def _rows(value: str) -> dict: + return {"changed": False, "rows": [[value]]} + + +def _stdout(value: str) -> dict: + return {"changed": False, "stdout": value} + + +def _shared(layout: str) -> dict: + return { + **NO_MARKER, + "stalwart_store_database": _rows("1"), + "stalwart_store_layout": _rows(layout), + } + + +def _dedicated(engine: str, layout: str | None = None) -> dict: + results = { + **NO_MARKER, + "stalwart_store_volume": _stdout("stalwart_database\n"), + "stalwart_store_engine": _stdout(engine), + } + if layout is not None: + results["stalwart_store_layout"] = _rows(layout) + return results + + +class TestTheMarkerOfA1xDeployPassesWithoutTheStore(unittest.TestCase): + def test_a_marked_dedicated_store_passes_with_its_database_down(self): + self.assertEqual(_guard(_marker(_written_marker()), shared=False), PASS) + + def test_a_marked_shared_store_passes_without_a_query(self): + self.assertEqual(_guard(_marker(_written_marker()), shared=True), PASS) + + def test_a_marker_of_another_layout_leaves_the_store_to_be_read(self): + results = {**_dedicated(""), **_marker("0\n")} + self.assertIn(ENGINE_DOWN, _guard(results, shared=False)) + + +class TestAHostWithoutAStoreIsAFreshInstall(unittest.TestCase): + def test_no_store_database_on_the_shared_postgres_passes(self): + results = {**NO_MARKER, "stalwart_store_database": _rows("0")} + self.assertEqual(_guard(results, shared=True), PASS) + + def test_no_dedicated_volume_passes(self): + results = {**NO_MARKER, "stalwart_store_volume": _stdout("")} + self.assertEqual(_guard(results, shared=False), PASS) + + +class TestASharedStoreIsRead(unittest.TestCase): + def test_a_store_from_before_1_0_is_migrated(self): + results = {**_shared("bigint"), MIGRATION: _rows("bytea")} + self.assertEqual(_guard(results, shared=True), PASS) + + def test_a_store_the_migration_leaves_before_1_0_stops_the_deploy(self): + results = {**_shared("bigint"), MIGRATION: _rows("bigint")} + self.assertIn(PRE_1_0, _guard(results, shared=True)) + + def test_a_1_x_store_passes(self): + self.assertEqual(_guard(_shared("bytea"), shared=True), PASS) + + def test_a_database_without_a_store_passes(self): + self.assertEqual(_guard(_shared("absent"), shared=True), PASS) + + +class TestADedicatedStoreIsReadInItsRunningDatabase(unittest.TestCase): + def test_a_stopped_database_stops_the_deploy_before_any_query(self): + self.assertIn(ENGINE_DOWN, _guard(_dedicated(""), shared=False)) + + def test_a_store_from_before_1_0_is_migrated(self): + results = {**_dedicated("4f2a9c1e7b3d\n", "bigint"), MIGRATION: _rows("bytea")} + self.assertEqual(_guard(results, shared=False), PASS) + + def test_a_store_the_migration_leaves_before_1_0_stops_the_deploy(self): + results = {**_dedicated("4f2a9c1e7b3d\n", "bigint"), MIGRATION: _rows("bigint")} + self.assertIn(PRE_1_0, _guard(results, shared=False)) + + def test_a_1_x_store_passes(self): + self.assertEqual( + _guard(_dedicated("4f2a9c1e7b3d\n", "bytea"), shared=False), PASS + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-stalwart/test_webui_oauth_client.py b/tests/unit/python/roles/web-app-stalwart/test_webui_oauth_client.py new file mode 100644 index 0000000000..063623dbaf --- /dev/null +++ b/tests/unit/python/roles/web-app-stalwart/test_webui_oauth_client.py @@ -0,0 +1,211 @@ +"""The OAuth client the WebUI signs in with when Stalwart is the authorization server. + +The WebUI Application always names ``stalwart-webui`` as its client id, so +Stalwart resolves it against a registered ``x:OAuthClient``. That client's +redirect URIs must be the WebUI's own ``//oauth/callback`` for +every URL prefix, also for a plaintext onion origin, and it must be first-party +or its tokens cannot reach the management API. A deploy updates the client only +when it differs from that target. +""" + +from __future__ import annotations + +import json +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar + +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.templating.ansible import _trust_as_template + +from . import PROJECT_ROOT + +ROLE = PROJECT_ROOT / "roles" / "web-app-stalwart" +TASK = ROLE / "tasks" / "02_webadmin.yml" +JMAP = ROLE / "templates" / "jmap" / "oauth_client" + +CLIENT_ID = "stalwart-webui" +ONION = "http://mail.abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion" +CLEARNET = "https://mail.example.test" +PREFIXES = ["/admin", "/account"] + + +def _render(template: str, **variables): + templar = Templar(loader=DataLoader(), variables=variables) + return templar.template(_trust_as_template(template)) + + +def _client(base_url: str, prefixes: list[str]) -> dict: + rendered = _render( + read_text(JMAP / "webui.json.j2"), + STALWART_WEBUI_OAUTH_CLIENT_ID=CLIENT_ID, + STALWART_WEBUI_APP_DESCRIPTION="Stalwart Web Interface", + STALWART_WEBUI_BASE_URL=base_url, + stalwart_webui_url_prefixes=prefixes, + ) + return json.loads(rendered) + + +def _task(name_fragment: str) -> dict: + tasks = load_yaml_any(str(TASK), default_if_missing=[]) + return next(t for t in tasks if name_fragment in t.get("name", "")) + + +def _updates(live: dict, desired: dict) -> bool: + variables = { + "stalwart_webui_oauth_clients": [live], + "stalwart_webui_oauth_client": desired, + } + return all( + _render("{{ (" + condition + ") | bool }}", **variables) + for condition in _task("Align the WebUI OAuth client")["when"] + ) + + +class TestWebuiClientRedirectUris(unittest.TestCase): + def test_an_onion_origin_registers_plaintext_callbacks(self): + client = _client(ONION, PREFIXES) + self.assertEqual( + sorted(client["redirectUris"]), + [f"{ONION}/account/oauth/callback", f"{ONION}/admin/oauth/callback"], + ) + + def test_a_clearnet_origin_registers_tls_callbacks(self): + client = _client(CLEARNET, PREFIXES) + self.assertEqual( + sorted(client["redirectUris"]), + [f"{CLEARNET}/account/oauth/callback", f"{CLEARNET}/admin/oauth/callback"], + ) + + def test_prefix_slashes_do_not_leak_into_the_uri(self): + client = _client(ONION, ["admin/", "//account"]) + self.assertEqual( + sorted(client["redirectUris"]), + [f"{ONION}/account/oauth/callback", f"{ONION}/admin/oauth/callback"], + ) + + def test_logout_returns_to_the_login_page_of_each_prefix(self): + client = _client(ONION, PREFIXES) + self.assertEqual( + sorted(client["postLogoutRedirectUris"]), + [f"{ONION}/account/login", f"{ONION}/admin/login"], + ) + + def test_a_single_prefix_still_renders_valid_json(self): + client = _client(ONION, ["/account"]) + self.assertEqual( + client["redirectUris"], {f"{ONION}/account/oauth/callback": True} + ) + + +class TestWebuiClientIsAFirstPartyPublicClient(unittest.TestCase): + def setUp(self): + self.client = _client(ONION, PREFIXES) + + def test_it_carries_the_application_client_id(self): + self.assertEqual(self.client["clientId"], CLIENT_ID) + + def test_it_is_first_party(self): + self.assertIs(self.client["firstParty"], True) + + def test_it_has_no_secret(self): + self.assertNotIn("secret", self.client) + + def test_it_allows_the_code_and_refresh_grants(self): + self.assertEqual( + self.client["grantTypes"], + {"authorizationCode": True, "refreshToken": True}, + ) + + +class TestWebuiClientJmapBodies(unittest.TestCase): + def setUp(self): + self.client = _client(ONION, PREFIXES) + + def test_create_registers_the_client(self): + body = json.loads( + _render( + read_text(JMAP / "create.json.j2"), + stalwart_webui_oauth_client=self.client, + ) + ) + method, args, _tag = body["methodCalls"][0] + self.assertEqual(method, "x:OAuthClient/set") + self.assertEqual(list(args["create"].values()), [self.client]) + + def test_update_patches_the_registered_record(self): + body = json.loads( + _render( + read_text(JMAP / "update.json.j2"), + stalwart_webui_oauth_client=self.client, + stalwart_webui_oauth_clients=[{"id": "b7", "clientId": CLIENT_ID}], + ) + ) + method, args, _tag = body["methodCalls"][0] + self.assertEqual(method, "x:OAuthClient/set") + self.assertEqual(args["update"], {"b7": self.client}) + + def test_get_lists_every_client(self): + body = json.loads(read_text(JMAP / "get.json.j2")) + method, args, _tag = body["methodCalls"][0] + self.assertEqual(method, "x:OAuthClient/get") + self.assertIsNone(args["ids"]) + + +class TestWebuiClientIsUpdatedOnlyOnDrift(unittest.TestCase): + def setUp(self): + self.desired = _client(ONION, PREFIXES) + self.live = { + **self.desired, + "id": "b7", + "createdAt": "2026-10-27T10:00:00Z", + "expiresAt": None, + "contacts": {}, + "logo": None, + "scopes": {}, + } + + def test_a_matching_client_is_left_alone(self): + self.assertFalse(_updates(self.live, self.desired)) + + def test_a_client_for_another_origin_is_updated(self): + live = { + **self.live, + "redirectUris": _client(CLEARNET, PREFIXES)["redirectUris"], + } + self.assertTrue(_updates(live, self.desired)) + + def test_a_client_missing_a_logout_target_is_updated(self): + live = {**self.live, "postLogoutRedirectUris": {}} + self.assertTrue(_updates(live, self.desired)) + + def test_a_third_party_client_is_updated(self): + live = {**self.live, "firstParty": False} + self.assertTrue(_updates(live, self.desired)) + + +class TestApplicationNamesTheClientUnconditionally(unittest.TestCase): + def _oauth_client_id(self, sso_enabled: bool) -> str: + task = _task("Point the WebUI Application") + body = json.loads( + _render( + task["vars"]["stalwart_jmap_body"], + stalwart_webui_app_id="a1", + STALWART_WEBUI_LOCAL_URL="file:///etc/stalwart/webui.zip", + STALWART_WEBUI_OAUTH_CLIENT_ID=CLIENT_ID, + STALWART_SSO_ENABLED=sso_enabled, + ) + ) + return body["methodCalls"][0][1]["update"]["a1"]["oauthClientId"] + + def test_with_sso(self): + self.assertEqual(self._oauth_client_id(True), CLIENT_ID) + + def test_without_sso(self): + self.assertEqual(self._oauth_client_id(False), CLIENT_ID) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web_app_keycloak/test_saml_clients_on_existing_realms.py b/tests/unit/python/roles/web_app_keycloak/test_saml_clients_on_existing_realms.py index d79db1a0c4..e2ccebf711 100644 --- a/tests/unit/python/roles/web_app_keycloak/test_saml_clients_on_existing_realms.py +++ b/tests/unit/python/roles/web_app_keycloak/test_saml_clients_on_existing_realms.py @@ -1,5 +1,7 @@ import unittest +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar from jinja2 import Environment from utils.cache.yaml import load_yaml_any @@ -9,17 +11,38 @@ from . import PROJECT_ROOT ROLE = PROJECT_ROOT / "roles" / "web-app-keycloak" VARS = ROLE / ROLE_FILE_VARS_MAIN -ROUTINES = ROLE / "tasks" / "03_manager_ops" / "update_routines.yml" +SMTP = {"host": "mail.example", "password": "pw"} REALM = { "clients": [ {"clientId": "account", "protocol": "openid-connect"}, {"clientId": "cymais.cloud", "protocol": "openid-connect"}, + {"clientId": "stalwart-webui", "protocol": "openid-connect"}, {"clientId": "https://crm.example/saml/metadata", "protocol": "saml"}, - ] + ], + "clientScopes": [{"name": "rbac"}], + "smtpServer": SMTP, } +def render(name: str, declared_client_ids: list[str]): + """Resolve one variable of the role's ``vars/main.yml`` against ``REALM``. + + Args: + name: the variable. + declared_client_ids: ``KEYCLOAK_DECLARED_CLIENT_IDS``. + """ + declared = DataLoader().load_from_file(str(VARS), trusted_as_template=True) + inputs = { + "KEYCLOAK_DICTIONARY_REALM": REALM, + "KEYCLOAK_CLIENT_ID": "cymais.cloud", + "KEYCLOAK_DECLARED_CLIENT_IDS": declared_client_ids, + "KEYCLOAK_REALM": "cymais", + } + templar = Templar(loader=DataLoader(), variables={**declared, **inputs}) + return templar.template(declared[name]) + + class TestSamlClientsReachExistingRealms(unittest.TestCase): def test_only_saml_clients_of_the_realm_dictionary_are_selected(self): template = load_yaml_any(str(VARS))["KEYCLOAK_SAML_CLIENT_IDS"] @@ -29,13 +52,43 @@ class TestSamlClientsReachExistingRealms(unittest.TestCase): ) self.assertEqual(selected, ["https://crm.example/saml/metadata"]) - def test_the_existing_realm_reconcile_loops_over_saml_clients(self): - task = next( - t - for t in load_yaml_any(str(ROUTINES)) - if "10_declared_client.yml" in str(t.get("include_tasks", "")) + def test_the_existing_realm_reconcile_covers_saml_clients(self): + clients = render("KEYCLOAK_SETTINGS_SPEC", [])["clients"] + self.assertIn( + "https://crm.example/saml/metadata", [c["clientId"] for c in clients] + ) + + +class TestSettingsSpec(unittest.TestCase): + def test_main_declared_and_saml_clients_are_converged_built_ins_are_not(self): + clients = render("KEYCLOAK_SETTINGS_SPEC", ["stalwart-webui"])["clients"] + self.assertEqual( + [c["clientId"] for c in clients], + ["cymais.cloud", "stalwart-webui", "https://crm.example/saml/metadata"], + ) + + def test_both_realms_get_the_mail_settings_of_the_realm_dictionary(self): + realms = render("KEYCLOAK_SETTINGS_SPEC", [])["realms"] + self.assertEqual( + realms, + [ + {"realm": "cymais", "desired": {"smtpServer": SMTP}}, + {"realm": "master", "desired": {"smtpServer": SMTP}}, + ], + ) + + def test_the_client_scopes_of_the_realm_dictionary_are_passed_on(self): + spec = render("KEYCLOAK_SETTINGS_SPEC", []) + self.assertEqual(spec["clientScopes"], [{"name": "rbac"}]) + + def test_a_declared_client_the_dictionary_lacks_is_reported_missing(self): + missing = render("KEYCLOAK_SETTINGS_MISSING_CLIENT_IDS", ["ghost", "account"]) + self.assertEqual(missing, ["ghost"]) + + def test_nothing_is_missing_when_every_client_is_declared_in_the_dictionary(self): + self.assertEqual( + render("KEYCLOAK_SETTINGS_MISSING_CLIENT_IDS", ["stalwart-webui"]), [] ) - self.assertIn("KEYCLOAK_SAML_CLIENT_IDS", task["loop"]) if __name__ == "__main__": diff --git a/tests/unit/python/tests/lint/__init__.py b/tests/unit/python/tests/lint/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/tests/lint/ansible/__init__.py b/tests/unit/python/tests/lint/ansible/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/tests/lint/ansible/roles/__init__.py b/tests/unit/python/tests/lint/ansible/roles/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/tests/lint/ansible/roles/test_readme.py b/tests/unit/python/tests/lint/ansible/roles/test_readme.py new file mode 100644 index 0000000000..ae3cb6506a --- /dev/null +++ b/tests/unit/python/tests/lint/ansible/roles/test_readme.py @@ -0,0 +1,69 @@ +"""The role README lint exempts a custom role from the Infinito.Nexus licence only.""" + +from __future__ import annotations + +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory + +from tests.lint.ansible.roles import test_readme as lint +from utils.roles.mapping import ROLE_FILE_META_MAIN, ROLE_FILE_README + +AUTHOR = "Jane Doe" +IMPLEMENTED = f"Implemented by **{AUTHOR}**.\n" +PROJECT = ( + "Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code) " + "and maintained by [Kevin Veen-Birkenbach](https://www.veen.world).\n" +) +INFINITO_LICENSE = ( + "Licensed under the [Infinito.Nexus Community License (Non-Commercial)]" + "(https://s.infinito.nexus/license).\n" +) +OWN_LICENSE = "Licensed under the [MIT License](https://opensource.org/licenses/MIT).\n" +TAIL_PROBLEM = "Credits tail does not match the canonical wording" + + +class TestCreditsLicence(unittest.TestCase): + def setUp(self) -> None: + tmp = TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.roles = Path(tmp.name) + + def _problems(self, role: str, *lines: str) -> list[str]: + readme = self.roles / role / ROLE_FILE_README + meta = readme.parent / ROLE_FILE_META_MAIN + meta.parent.mkdir(parents=True) + meta.write_text(f"galaxy_info:\n author: {AUTHOR}\n", encoding="utf-8") + text = "## Credits\n\n" + "".join(lines) + readme.write_text(text, encoding="utf-8") + return lint._validate_credits(text, readme) + + def test_a_custom_role_with_its_own_licence_passes(self) -> None: + self.assertEqual( + [], + self._problems("web-app-cst-demo", IMPLEMENTED, PROJECT, OWN_LICENSE), + ) + + def test_an_in_tree_role_without_the_infinito_licence_fails(self) -> None: + problems = self._problems("web-app-demo", IMPLEMENTED, PROJECT, OWN_LICENSE) + self.assertTrue(any(TAIL_PROBLEM in problem for problem in problems)) + + def test_an_in_tree_role_with_the_infinito_licence_passes(self) -> None: + self.assertEqual( + [], + self._problems("web-app-demo", IMPLEMENTED, PROJECT, INFINITO_LICENSE), + ) + + def test_a_custom_role_without_the_project_line_still_fails(self) -> None: + problems = self._problems("web-app-cst-demo", IMPLEMENTED, OWN_LICENSE) + self.assertTrue(any(TAIL_PROBLEM in problem for problem in problems)) + + def test_a_custom_role_still_needs_the_author_spot(self) -> None: + problems = self._problems( + "web-app-cst-demo", "Implemented by **Someone Else**.\n", PROJECT + ) + self.assertTrue(any("galaxy_info.author" in problem for problem in problems)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/tests/test_untracked_files_in_scope.py b/tests/unit/python/tests/test_untracked_files_in_scope.py new file mode 100644 index 0000000000..ef85777c49 --- /dev/null +++ b/tests/unit/python/tests/test_untracked_files_in_scope.py @@ -0,0 +1,83 @@ +"""Repository scans see a file before it is added, whichever runner lists the files.""" + +from __future__ import annotations + +import subprocess +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory +from types import SimpleNamespace +from unittest import mock + +from tests.integration.infrastructure.compose import test_no_raw_docker as raw_docker +from tests.lint.filesystem.python import test_python_shebangs as shebangs +from tests.lint.repository import test_comments_valid as comments +from tests.lint.repository.documentation import test_todo_transparency as todo +from utils.cache import files as files_module + +TRACKED = "tracked.py" +UNTRACKED = "new.py" +FAILED = subprocess.CalledProcessError(128, "git") + + +class _ListingFixture: + """Mixin with a project root holding one tracked and one untracked file. + + Combined with ``unittest.TestCase`` on each concrete class so the + test-discovery lint sees the ``TestCase`` base directly. + """ + + def setUp(self) -> None: + super().setUp() + files_module._reset() + self.addCleanup(files_module._reset) + tmp = TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + for name in (TRACKED, UNTRACKED): + (self.root / name).write_text("", encoding="utf-8") + for module in (files_module, comments): + patcher = mock.patch.object(module, "PROJECT_ROOT", self.root) + patcher.start() + self.addCleanup(patcher.stop) + + def git(self, tracked: bytes | Exception, untracked: bytes | Exception): + def run(args, **_kwargs): + listing = untracked if "--others" in args else tracked + if isinstance(listing, Exception): + raise listing + return SimpleNamespace(stdout=listing) + + return mock.patch.object(files_module.subprocess, "run", side_effect=run) + + +class TestScansListUntrackedFiles(_ListingFixture, unittest.TestCase): + def test_every_scan_lists_a_file_that_is_not_added_yet(self): + scans = { + "test_python_shebangs": lambda: shebangs.TestPythonShebangs._tracked_files( + SimpleNamespace(repo_root=self.root) + ), + "test_todo_transparency": lambda: todo.tracked_files(self.root), + "test_no_raw_docker": lambda: raw_docker.git_ls_files(self.root), + } + for name, scan in scans.items(): + with ( + self.subTest(scan=name), + self.git(f"{TRACKED}\0".encode(), f"{UNTRACKED}\0".encode()), + ): + files_module._reset() + self.assertIn(self.root / UNTRACKED, scan()) + + +class TestCommentScanKeepsEachListing(_ListingFixture, unittest.TestCase): + def test_failing_tracked_listing_keeps_the_untracked_files(self): + with self.git(FAILED, f"{UNTRACKED}\0".encode()): + self.assertEqual([self.root / UNTRACKED], comments._all_targets()) + + def test_failing_untracked_listing_keeps_the_tracked_files(self): + with self.git(f"{TRACKED}\0".encode(), FAILED): + self.assertEqual([self.root / TRACKED], comments._all_targets()) + + +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 38a2ebb085..717714097b 100644 --- a/tests/unit/python/utils/cache/test_applications.py +++ b/tests/unit/python/utils/cache/test_applications.py @@ -402,7 +402,53 @@ class TestGetMergedApplicationsCarrierFact(unittest.TestCase): "key": [key[0], list(key[1])], "applications": {"web-app-foo": {"carried": True}}, } - tokens.write_text("users: {}\n", encoding="utf-8") + tokens.write_text( + "users: {no-reply: {tokens: {web-app-stalwart: minted}}}\n", + encoding="utf-8", + ) + merged = cache_apps.get_merged_applications( + variables=variables, roles_dir=roles, templar=None + ) + self.assertNotIn("carried", merged["web-app-foo"]) + + def _park_from_the_tokens_file(self, tmp: Path, token: str) -> tuple: + roles = _seed_minimal_roles(tmp) + tokens = tmp / "tokens.yml" + tokens.write_text( + f"users: {{no-reply: {{tokens: {{web-app-stalwart: {token}}}}}}}\n", + encoding="utf-8", + ) + variables = self._variables() + variables["FILE_TOKENS"] = str(tokens) + 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, + } + return roles, variables, carried + + def test_the_store_fact_with_the_file_tokens_keeps_the_carrier(self): + with tempfile.TemporaryDirectory() as tmp: + roles, variables, carried = self._park_from_the_tokens_file( + Path(tmp), "minted" + ) + variables["sys_token_store_users"] = { + "no-reply": {"tokens": {"web-app-stalwart": "minted"}} + } + merged = cache_apps.get_merged_applications( + variables=variables, roles_dir=roles, templar=None + ) + self.assertIs(merged, carried) + + def test_the_store_fact_with_other_tokens_than_the_file_rejects_the_carrier( + self, + ): + with tempfile.TemporaryDirectory() as tmp: + roles, variables, _ = self._park_from_the_tokens_file(Path(tmp), "minted") + variables["sys_token_store_users"] = { + "no-reply": {"tokens": {"web-app-stalwart": "rotated"}} + } merged = cache_apps.get_merged_applications( variables=variables, roles_dir=roles, templar=None ) diff --git a/tests/unit/python/utils/cache/test_files.py b/tests/unit/python/utils/cache/test_files.py index 331fa38f85..42de4006da 100644 --- a/tests/unit/python/utils/cache/test_files.py +++ b/tests/unit/python/utils/cache/test_files.py @@ -8,9 +8,11 @@ the module so the real repo tree is never touched. from __future__ import annotations +import subprocess import unittest from pathlib import Path from tempfile import TemporaryDirectory +from types import SimpleNamespace from unittest.mock import patch from utils.cache import files as files_module @@ -20,7 +22,7 @@ from utils.cache.files import ( iter_project_files_with_content, read_text, ) -from utils.roles.mapping import ROLE_FILE_META_SERVICES +from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_TASKS_MAIN def _touch(path: Path, content: str = "") -> Path: @@ -191,6 +193,56 @@ class TestReset(_ProjectRootFixture, unittest.TestCase): self.assertEqual(read_text(str(self.root / "x.txt")), "v1-changed") +class TestRepositoryFiles(_ProjectRootFixture, unittest.TestCase): + TRACKED = f"roles/web-app-nextcloud/{ROLE_FILE_TASKS_MAIN}" + CUSTOM = f"roles/web-app-cst-demo/{ROLE_FILE_TASKS_MAIN}" + + def _git(self, *listings: bytes): + return patch.object( + files_module.subprocess, + "run", + side_effect=[SimpleNamespace(stdout=listing) for listing in listings], + ) + + def test_lists_placed_custom_roles_next_to_the_tracked_files(self) -> None: + _touch(self.root / self.TRACKED, "- y") + _touch(self.root / self.CUSTOM, "- x") + _touch(self.root / "roles/web-app-cst-demo/__pycache__/x.pyc", "") + with self._git(f"{self.TRACKED}\0".encode()): + self.assertEqual( + (self.CUSTOM, self.TRACKED), + files_module.repository_files(), + ) + + def test_lists_only_the_tracked_files_without_placed_custom_roles(self) -> None: + _touch(self.root / self.TRACKED, "- y") + _touch(self.root / "build/install.stamp", "") + with self._git(f"{self.TRACKED}\0".encode()): + self.assertEqual((self.TRACKED,), files_module.repository_files()) + + def test_untracked_adds_the_files_gitignore_does_not_exclude(self) -> None: + with self._git(f"{self.TRACKED}\0".encode(), b"new.py\0") as run: + self.assertEqual( + ("new.py", self.TRACKED), + files_module.repository_files(untracked=True), + ) + self.assertEqual( + ["--others", "--exclude-standard"], + run.call_args_list[1].args[0][-2:], + ) + + def test_a_git_failure_propagates(self) -> None: + with ( + patch.object( + files_module.subprocess, + "run", + side_effect=subprocess.CalledProcessError(128, "git"), + ), + self.assertRaises(subprocess.CalledProcessError), + ): + files_module.repository_files() + + class TestWalkIsKeyedOnTheRoot(_ProjectRootFixture, unittest.TestCase): def test_a_second_root_is_walked_rather_than_answered_from_the_first( self, diff --git a/tests/unit/python/utils/cache/test_gitignore.py b/tests/unit/python/utils/cache/test_gitignore.py new file mode 100644 index 0000000000..549da606d0 --- /dev/null +++ b/tests/unit/python/utils/cache/test_gitignore.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path + +from utils.cache import gitignore +from utils.roles.custom import ROLES_GLOB +from utils.roles.mapping import ROLE_FILE_TASKS_MAIN + + +class TestLoadGitignorePatterns(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.addCleanup(gitignore._reset) + self.root = Path(tmp.name) + (self.root / ".gitignore").write_text( + f"# comment\n*.log\n{ROLES_GLOB}\n!keep.log\nbuild/*\n", encoding="utf-8" + ) + + def test_reads_plain_patterns(self): + patterns = gitignore.load_gitignore_patterns(str(self.root)) + self.assertEqual(("*.log", "build/*"), patterns) + + def test_pulled_custom_roles_stay_in_the_scanned_tree(self): + patterns = gitignore.load_gitignore_patterns(str(self.root)) + self.assertFalse( + gitignore.is_path_gitignored( + f"roles/web-app-cst-demo/{ROLE_FILE_TASKS_MAIN}", patterns + ) + ) + + def test_ignored_files_inside_a_custom_role_stay_ignored(self): + patterns = gitignore.load_gitignore_patterns(str(self.root)) + self.assertTrue( + gitignore.is_path_gitignored("roles/web-app-cst-demo/debug.log", patterns) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/cache/test_yaml.py b/tests/unit/python/utils/cache/test_yaml.py index cd948e5d93..240f4dd245 100644 --- a/tests/unit/python/utils/cache/test_yaml.py +++ b/tests/unit/python/utils/cache/test_yaml.py @@ -7,11 +7,13 @@ from pathlib import Path from tempfile import TemporaryDirectory from utils.cache.yaml import ( + TaggedValue, _reset_cache_for_tests, dump_yaml, invalidate, load_yaml, load_yaml_any, + load_yaml_tagged, ) @@ -158,5 +160,38 @@ class TestInvalidate(unittest.TestCase): invalidate(self.tmp / "never-loaded.yml") +class TestLoadYamlTagged(unittest.TestCase): + def setUp(self) -> None: + _reset_cache_for_tests() + self._tmp = TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.path = Path(self._tmp.name) / "inventory.yml" + self.path.write_text( + "motd: !unsafe '{{ literal }}'\n" + "secret: !vault |\n" + " $ANSIBLE_VAULT;1.1;AES256\n" + " 6162\n" + "hosts: !custom [a, b]\n" + "plain: value\n", + encoding="utf-8", + ) + + def test_every_local_tag_loads_as_its_raw_value(self): + self.assertEqual( + { + "motd": TaggedValue("!unsafe", "{{ literal }}"), + "secret": TaggedValue("!vault", "$ANSIBLE_VAULT;1.1;AES256\n6162\n"), + "hosts": TaggedValue("!custom", ["a", "b"]), + "plain": "value", + }, + load_yaml_tagged(self.path), + ) + + def test_load_yaml_any_still_reads_vault_as_its_ciphertext(self): + self.path.write_text("secret: !vault abc\n", encoding="utf-8") + load_yaml_tagged(self.path) + self.assertEqual({"secret": "abc"}, load_yaml_any(self.path)) + + if __name__ == "__main__": 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 7049e98cc3..ff71a3b171 100644 --- a/tests/unit/python/utils/cache/users/test_module.py +++ b/tests/unit/python/utils/cache/users/test_module.py @@ -20,6 +20,7 @@ from pathlib import Path from utils.cache import _reset_cache_for_tests from utils.cache import base as cache_base from utils.cache import users as cache_users +from utils.cache.users import store as cache_users_store from utils.cache.yaml import dump_yaml_str from utils.domains.default_primary import default_domain_primary from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_META_USERS @@ -425,5 +426,89 @@ class TestGetMergedUsersTokenSource(unittest.TestCase): self.assertEqual(after["foo"]["tokens"]["web-app-foo"], "minted") +class TestStoreSignature(unittest.TestCase): + def setUp(self) -> None: + _reset_cache_for_tests() + + @staticmethod + def _signature(store: dict) -> tuple: + with tempfile.TemporaryDirectory() as tmp: + return cache_users._store_signature( + {cache_users_store.STORE_FACT: store}, Path(tmp) / "tokens.yml" + ) + + @staticmethod + def _hydrated(store: dict) -> str: + users = {"foo": {"tokens": {"web-app-foo": ""}}} + return repr(cache_users._hydrate_users_tokens(users, store)) + + def test_the_tokens_file_signs_like_the_store_fact_with_the_same_tokens(self): + store = {"foo": {"tokens": {"web-app-foo": "minted"}}} + with tempfile.TemporaryDirectory() as tmp: + tokens_file = Path(tmp) / "tokens.yml" + tokens_file.write_text(dump_yaml_str({"users": store}), encoding="utf-8") + self.assertEqual( + cache_users._store_signature({}, tokens_file), + cache_users._store_signature( + {cache_users_store.STORE_FACT: store}, tokens_file + ), + ) + + def test_a_missing_tokens_file_signs_like_an_empty_store_fact(self): + with tempfile.TemporaryDirectory() as tmp: + absent = Path(tmp) / "tokens.yml" + self.assertEqual( + cache_users._store_signature({}, absent), + cache_users._store_signature( + {cache_users_store.STORE_FACT: {}}, absent + ), + ) + + def test_fields_and_padding_the_hydration_ignores_keep_the_signature(self): + plain = {"foo": {"tokens": {"web-app-foo": "minted"}}} + for variant in ( + {"foo": {"tokens": {"web-app-foo": " minted "}}}, + {"foo": {"tokens": {"web-app-foo": "minted"}, "note": "unread"}}, + {"foo": {"tokens": {"web-app-foo": "minted", "web-app-bar": None}}}, + {"foo": {"tokens": {"web-app-foo": "minted"}}, "bar": "not-a-mapping"}, + ): + with self.subTest(variant=variant): + self.assertEqual(self._hydrated(variant), self._hydrated(plain)) + self.assertEqual(self._signature(variant), self._signature(plain)) + + def test_the_store_order_enters_the_signature_because_the_hydration_keeps_it( + self, + ): + first = {"bar": {"tokens": {"x": "1"}}, "baz": {"tokens": {"y": "2"}}} + swapped = {"baz": {"tokens": {"y": "2"}}, "bar": {"tokens": {"x": "1"}}} + self.assertNotEqual(self._hydrated(first), self._hydrated(swapped)) + self.assertNotEqual(self._signature(first), self._signature(swapped)) + + def test_an_equal_signature_means_an_equal_hydration(self): + stores = [ + {"foo": {"tokens": {"web-app-foo": "minted"}}}, + {"foo": {"tokens": {"web-app-foo": " minted "}}}, + {"foo": {"tokens": {"web-app-foo": "rotated"}}}, + {"foo": {"tokens": {"web-app-foo": None}}}, + {"foo": {"tokens": {"web-app-foo": ""}}}, + {"foo": {"tokens": {}}}, + {"foo": {"tokens": "not-a-mapping"}}, + {"foo": {}}, + {"foo": "not-a-mapping"}, + {}, + {"bar": {"tokens": {"x": "1"}}}, + {"bar": {"tokens": {"x": 1}}}, + {"bar": {"tokens": {}}}, + {1: {"tokens": {"x": "1"}}}, + {"1": {"tokens": {"x": "1"}}}, + ] + for first in stores: + for second in stores: + if self._signature(first) != self._signature(second): + continue + with self.subTest(first=first, second=second): + self.assertEqual(self._hydrated(first), self._hydrated(second)) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/inventory/test_groups.py b/tests/unit/python/utils/inventory/test_groups.py index 76a79270b6..4a6db23e5a 100644 --- a/tests/unit/python/utils/inventory/test_groups.py +++ b/tests/unit/python/utils/inventory/test_groups.py @@ -1,4 +1,4 @@ -"""Unit tests for utils.inventory.groups.inventory_has_group.""" +"""Unit tests for utils.inventory.groups.""" from __future__ import annotations @@ -7,7 +7,92 @@ import unittest from pathlib import Path from tempfile import TemporaryDirectory -from utils.inventory.groups import inventory_has_group +from utils.inventory.groups import inventory_groups, inventory_has_group + + +class TestInventoryGroups(unittest.TestCase): + def setUp(self) -> None: + self.tmp = TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + + def _write(self, name: str, body: str) -> str: + path = self.root / name + path.write_text(textwrap.dedent(body).lstrip("\n"), encoding="utf-8") + return str(path) + + def test_yaml_lists_top_level_and_nested_children(self) -> None: + path = self._write( + "inv.yml", + """ + all: + children: + web-app-cst-store: + children: + nested-group: + hosts: {} + hosts: + localhost: {} + """, + ) + self.assertEqual( + {"all", "web-app-cst-store", "nested-group"}, inventory_groups(path) + ) + + def test_yaml_hosts_and_vars_are_no_groups(self) -> None: + path = self._write( + "inv.yml", + """ + all: + hosts: + web-app-cst-host: {} + vars: + applications: + web-app-cst-store: {custom: true} + """, + ) + self.assertEqual({"all"}, inventory_groups(path)) + + def test_ini_lists_sections_and_children(self) -> None: + path = self._write( + "hosts", + """ + # [comment-group] + [web-app-cst-store] + localhost + + [parent:children] + child-group + + [parent:vars] + key=value + """, + ) + self.assertEqual( + {"web-app-cst-store", "parent", "child-group"}, inventory_groups(path) + ) + + def test_yaml_with_ansible_tags_lists_its_groups(self) -> None: + path = self._write( + "inv.yml", + """ + all: + hosts: + localhost: + motd: !unsafe '{{ literal }}' + secret: !vault | + $ANSIBLE_VAULT;1.1;AES256 + 6162 + children: + web-app-cst-store: + hosts: {} + """, + ) + self.assertEqual({"all", "web-app-cst-store"}, inventory_groups(path)) + + def test_missing_yaml_inventory_raises(self) -> None: + with self.assertRaises(FileNotFoundError): + inventory_groups(str(self.root / "absent.yml")) class TestInventoryHasGroupYaml(unittest.TestCase): diff --git a/tests/unit/python/utils/packages/test_batch.py b/tests/unit/python/utils/packages/test_batch.py new file mode 100644 index 0000000000..430b9eee2a --- /dev/null +++ b/tests/unit/python/utils/packages/test_batch.py @@ -0,0 +1,76 @@ +import tempfile +import unittest +from pathlib import Path + +from utils.cache.yaml import dump_yaml +from utils.packages.batch import batch_ids, batch_ids_by_role + + +def _write(root: Path, relative: str, payload) -> None: + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + dump_yaml(str(path), payload) + + +class TestBatchIds(unittest.TestCase): + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.root = Path(self._tmp.name) + self.addCleanup(self._tmp.cleanup) + _write( + self.root, + "meta/packages.yml", + { + "git": {"Debian": ["git"]}, + "postfix": {"Debian": ["postfix"], "batch": False}, + }, + ) + + def test_a_role_batches_its_own_ids(self): + _write(self.root, "roles/role-a/meta/packages.yml", {"jq": {"Debian": ["jq"]}}) + self.assertEqual(batch_ids(["role-a"], self.root), ["jq"]) + + def test_an_unbatched_own_id_is_left_to_the_role(self): + _write( + self.root, + "roles/role-a/meta/packages.yml", + {"jq": {"Debian": ["jq"], "batch": False}}, + ) + self.assertEqual(batch_ids(["role-a"], self.root), []) + + def test_a_referenced_shared_id_is_batched_with_the_role(self): + _write(self.root, "roles/role-a/meta/packages.yml", {"git": {"shared": True}}) + self.assertEqual(batch_ids(["role-a"], self.root), ["git"]) + + def test_a_referenced_unbatched_shared_id_stays_out(self): + _write( + self.root, "roles/role-a/meta/packages.yml", {"postfix": {"shared": True}} + ) + self.assertEqual(batch_ids(["role-a"], self.root), []) + + def test_shared_ids_nobody_references_stay_out(self): + self.assertEqual(batch_ids(["role-a"], self.root), []) + + def test_roles_outside_the_deploy_contribute_nothing(self): + _write(self.root, "roles/role-a/meta/packages.yml", {"jq": {"Debian": ["jq"]}}) + _write( + self.root, "roles/role-b/meta/packages.yml", {"curl": {"Debian": ["curl"]}} + ) + self.assertEqual(batch_ids(["role-a"], self.root), ["jq"]) + + def test_ids_are_sorted_and_unique(self): + _write( + self.root, + "roles/role-a/meta/packages.yml", + {"jq": {"Debian": ["jq"]}, "git": {"shared": True}}, + ) + _write(self.root, "roles/role-b/meta/packages.yml", {"git": {"shared": True}}) + self.assertEqual(batch_ids(["role-b", "role-a"], self.root), ["git", "jq"]) + + def test_ids_are_grouped_by_role(self): + _write(self.root, "roles/role-a/meta/packages.yml", {"jq": {"Debian": ["jq"]}}) + self.assertEqual(batch_ids_by_role(self.root), {"role-a": {"jq"}}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/packages/test_installed.py b/tests/unit/python/utils/packages/test_installed.py new file mode 100644 index 0000000000..8e84634708 --- /dev/null +++ b/tests/unit/python/utils/packages/test_installed.py @@ -0,0 +1,207 @@ +import unittest + +from utils.packages.calls import ( + GENERIC_PACKAGE, + STATE_ABSENT, + STATE_PRESENT, + ModuleCall, + package_call, +) +from utils.packages.installed import query_argv, state_holds + + +def _holds(pkg_mgr, names, state, rc, stdout="", stderr="", **extra): + result = {"rc": rc, "stdout": stdout, "stderr": stderr, **extra} + return state_holds(package_call(names, state), pkg_mgr, result) + + +def _present(pkg_mgr, names, rc, stdout="", stderr=""): + return _holds(pkg_mgr, names, STATE_PRESENT, rc, stdout, stderr) + + +def _absent(pkg_mgr, names, rc, stdout="", stderr=""): + return _holds(pkg_mgr, names, STATE_ABSENT, rc, stdout, stderr) + + +class TestQueryArgv(unittest.TestCase): + def test_apt_asks_dpkg_for_every_name_in_the_c_locale(self): + argv = query_argv(package_call(["git", "curl"], STATE_PRESENT), "apt") + self.assertEqual(argv[:3], ["env", "LC_ALL=C", "dpkg-query"]) + self.assertEqual(argv[-3:], ["--", "git", "curl"]) + + def test_pacman_asks_the_local_database(self): + argv = query_argv(package_call(["git"], STATE_ABSENT), "pacman") + self.assertEqual(argv[2:5], ["pacman", "--query", "--"]) + + def test_every_rpm_manager_asks_rpm(self): + for pkg_mgr in ("dnf", "dnf5", "yum"): + with self.subTest(pkg_mgr=pkg_mgr): + argv = query_argv(package_call(["git"], STATE_PRESENT), pkg_mgr) + self.assertEqual(argv[2], "rpm") + self.assertEqual(argv[-1], "git") + + def test_an_unknown_manager_is_not_queried(self): + self.assertIsNone(query_argv(package_call(["git"], STATE_PRESENT), "zypper")) + + def test_a_name_that_is_not_plain_is_not_queried(self): + for name in ( + "nginx=1.24", + "libc6:i386", + "/tmp/pkg.deb", + "https://example.org/pkg.rpm", + "python3-*", + "-x", + "", + ): + with self.subTest(name=name): + call = package_call(["git", name], STATE_PRESENT) + self.assertIsNone(query_argv(call, "apt")) + + def test_a_concrete_module_is_not_queried(self): + call = ModuleCall( + "community.general.pacman", {"name": ["git"], "state": "present"} + ) + self.assertIsNone(query_argv(call, "pacman")) + + def test_a_call_under_another_user_is_not_queried(self): + call = ModuleCall( + GENERIC_PACKAGE, {"name": ["git"], "state": "present"}, become_user="b" + ) + self.assertIsNone(query_argv(call, "pacman")) + + def test_a_call_with_further_arguments_is_not_queried(self): + call = ModuleCall( + GENERIC_PACKAGE, + {"name": ["git"], "state": "present", "update_cache": True}, + ) + self.assertIsNone(query_argv(call, "apt")) + + def test_an_empty_name_list_is_not_queried(self): + self.assertIsNone(query_argv(package_call([], STATE_PRESENT), "apt")) + + +class TestDpkg(unittest.TestCase): + def test_every_name_installed_holds_present(self): + self.assertTrue(_present("apt", ["git", "curl"], 0, "git\tii \ncurl\tii ")) + + def test_a_held_package_counts_as_installed(self): + self.assertTrue(_present("apt", ["git"], 0, "git\thi ")) + + def test_a_trimmed_last_line_still_parses(self): + self.assertTrue(_present("apt", ["git"], 0, "git\tii")) + + def test_one_unknown_name_breaks_present(self): + stderr = "dpkg-query: no packages found matching curl" + self.assertFalse(_present("apt", ["git", "curl"], 1, "git\tii ", stderr)) + + def test_one_installed_name_breaks_absent(self): + stderr = "dpkg-query: no packages found matching curl" + self.assertFalse(_absent("apt", ["git", "curl"], 1, "git\tii ", stderr)) + + def test_unknown_and_config_files_only_hold_absent(self): + stderr = "dpkg-query: no packages found matching postfix-lmdb" + self.assertTrue( + _absent("apt", ["postfix", "postfix-lmdb"], 1, "postfix\trc ", stderr) + ) + + def test_config_files_only_breaks_present(self): + self.assertFalse(_present("apt", ["postfix"], 0, "postfix\trc ")) + + def test_a_half_installed_package_holds_neither_state(self): + self.assertFalse(_present("apt", ["git"], 0, "git\tiU ")) + self.assertFalse(_absent("apt", ["git"], 0, "git\tiU ")) + + def test_a_package_that_needs_reinstalling_is_not_installed(self): + self.assertFalse(_present("apt", ["git"], 0, "git\tiiR")) + + def test_every_architecture_must_be_installed(self): + self.assertTrue(_present("apt", ["libc6"], 0, "libc6\tii \nlibc6\tii ")) + self.assertFalse(_present("apt", ["libc6"], 0, "libc6\tii \nlibc6\trc ")) + self.assertFalse(_absent("apt", ["libc6"], 0, "libc6\tii \nlibc6\trc ")) + + +class TestPacman(unittest.TestCase): + def test_every_name_installed_holds_present(self): + self.assertTrue( + _present("pacman", ["git", "curl"], 0, "git 2.51-1\ncurl 8.16-1") + ) + + def test_one_missing_name_breaks_present(self): + stderr = "error: package 'curl' was not found" + self.assertFalse(_present("pacman", ["git", "curl"], 1, "git 2.51-1", stderr)) + + def test_no_name_installed_holds_absent(self): + stderr = ( + "error: package 'postfix' was not found\n" + "error: package 'postfix-lmdb' was not found" + ) + self.assertTrue(_absent("pacman", ["postfix", "postfix-lmdb"], 1, "", stderr)) + + def test_one_installed_name_breaks_absent(self): + stderr = "error: package 'postfix-lmdb' was not found" + self.assertFalse( + _absent("pacman", ["postfix", "postfix-lmdb"], 1, "postfix 3.11-2", stderr) + ) + + def test_a_name_answered_by_its_provider_proves_nothing(self): + self.assertFalse(_present("pacman", ["sh"], 0, "bash 5.3-1")) + self.assertFalse(_absent("pacman", ["sh"], 0, "bash 5.3-1")) + + +class TestRpm(unittest.TestCase): + def test_every_name_installed_holds_present(self): + self.assertTrue(_present("dnf", ["git", "curl"], 0, "git\ncurl")) + + def test_one_missing_name_holds_neither_state(self): + stdout = "git\npackage curl is not installed" + self.assertFalse(_present("dnf5", ["git", "curl"], 1, stdout)) + self.assertFalse(_absent("dnf5", ["git", "curl"], 1, stdout)) + + def test_no_name_installed_holds_absent(self): + stdout = ( + "package postfix is not installed\npackage postfix-lmdb is not installed" + ) + self.assertTrue(_absent("yum", ["postfix", "postfix-lmdb"], 2, stdout)) + + def test_the_not_installed_message_may_come_on_stderr(self): + stderr = "package postfix is not installed" + self.assertTrue(_absent("dnf", ["postfix"], 1, "", stderr)) + + def test_a_version_match_under_another_name_proves_nothing(self): + self.assertFalse(_present("dnf", ["foo-1.0"], 0, "foo")) + + def test_a_translated_message_proves_nothing(self): + stdout = "Paket postfix ist nicht installiert" + self.assertFalse(_absent("dnf", ["postfix"], 1, stdout)) + + +class TestDoubtRunsTheModule(unittest.TestCase): + def test_a_check_mode_skip_proves_nothing(self): + self.assertFalse(_holds("apt", ["git"], STATE_ABSENT, 0, skipped=True)) + + def test_a_failure_without_a_not_found_message_proves_nothing(self): + self.assertFalse(_absent("apt", ["git"], 1)) + self.assertFalse(_absent("pacman", ["git"], 1)) + self.assertFalse(_absent("dnf", ["git"], 1)) + + def test_success_with_a_not_found_message_proves_nothing(self): + stderr = "dpkg-query: no packages found matching git" + self.assertFalse(_absent("apt", ["git"], 0, "", stderr)) + + def test_a_name_left_unanswered_proves_nothing(self): + self.assertFalse(_present("apt", ["git", "curl"], 0, "git\tii ")) + + def test_a_foreign_stderr_line_proves_nothing(self): + stderr = "dpkg-query: error: parsing file '/var/lib/dpkg/status'" + self.assertFalse(_present("apt", ["git"], 0, "git\tii ", stderr)) + + def test_a_foreign_stdout_line_proves_nothing(self): + self.assertFalse(_present("apt", ["git"], 0, "git\tii \ncurl\tii ")) + + def test_a_result_without_output_proves_nothing(self): + call = package_call(["git"], STATE_ABSENT) + self.assertFalse(state_holds(call, "apt", {"failed": True, "msg": "boom"})) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/packages/test_plan.py b/tests/unit/python/utils/packages/test_plan.py index b23c21f024..aed8afb966 100644 --- a/tests/unit/python/utils/packages/test_plan.py +++ b/tests/unit/python/utils/packages/test_plan.py @@ -2,7 +2,7 @@ import re import unittest from utils.packages.calls import STATE_ABSENT, STATE_PRESENT -from utils.packages.plan import build_plan +from utils.packages.plan import build_plan, merge_plans from utils.packages.schema import ( SOURCE_AUR, SOURCE_BUILD, @@ -367,5 +367,55 @@ class TestFlatpakSource(unittest.TestCase): ) +def _plan(*names, **spec): + return build_plan(PackageSpec(tuple(names), **spec), STATE_PRESENT) + + +def _names(call): + return call.args["name"] + + +class TestMergePlans(unittest.TestCase): + def test_plain_plans_share_one_call(self): + merged = merge_plans([_plan("git"), _plan("curl", "jq")]) + self.assertEqual(len(merged), 1) + self.assertEqual([_names(call) for call in merged[0]], [["git", "curl", "jq"]]) + + def test_a_name_requested_twice_is_installed_once(self): + merged = merge_plans([_plan("git"), _plan("git")]) + self.assertEqual(_names(merged[0][0]), ["git"]) + + def test_bootstrap_packages_install_before_every_name(self): + epel = {"repo": {"bootstrap_package": "epel-release"}} + merged = merge_plans( + [_plan("git"), _plan("micro", **epel), _plan("jq", **epel)] + ) + self.assertEqual( + [_names(call) for call in merged[0]], + [["epel-release"], ["git", "micro", "jq"]], + ) + + def test_a_plan_with_other_modules_runs_unchanged_after_the_merged_one(self): + aur = _plan("caffeine", source=SOURCE_AUR) + merged = merge_plans([aur, _plan("git")]) + self.assertEqual([_names(call) for call in merged[0]], [["git"]]) + self.assertEqual(merged[1], aur) + + def test_plans_of_different_states_never_merge(self): + absent = build_plan(PackageSpec(("postfix",)), STATE_ABSENT) + merged = merge_plans([_plan("git"), absent]) + self.assertEqual( + [(call.args["state"], _names(call)) for plan in merged for call in plan], + [(STATE_PRESENT, ["git"]), (STATE_ABSENT, ["postfix"])], + ) + + def test_no_plans_merge_to_nothing(self): + self.assertEqual(merge_plans([]), []) + + def test_the_merged_call_keeps_the_retry_policy(self): + merged = merge_plans([_plan("git"), _plan("curl")]) + self.assertIsNotNone(merged[0][0].retry) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/utils/packages/test_registry.py b/tests/unit/python/utils/packages/test_registry.py index 3b232049be..f649296aa7 100644 --- a/tests/unit/python/utils/packages/test_registry.py +++ b/tests/unit/python/utils/packages/test_registry.py @@ -7,6 +7,7 @@ from utils.packages.registry import ( build_registry, iter_inventory_package_lists, load_declarations, + load_references, resolve, ) from utils.packages.schema import ( @@ -312,6 +313,40 @@ class TestRegistry(unittest.TestCase): with self.assertRaises(PackagesShapeError): list(iter_inventory_package_lists(self.root)) + def test_an_unflagged_id_is_batched(self): + _write_role(self.root, "role-a", {"git": {"Debian": ["git"]}}) + self.assertTrue(self._declaration("git").batch) + + def test_batch_false_keeps_the_id_out_of_the_batch(self): + _write_role(self.root, "role-a", {"git": {"Debian": ["git"], "batch": False}}) + self.assertFalse(self._declaration("git").batch) + + def test_the_batch_flag_is_no_distro_key(self): + _write_role(self.root, "role-a", {"git": {"Debian": ["git"], "batch": False}}) + self.assertIsNone(resolve(self._declaration("git"), "arch")) + + def test_non_boolean_batch_raises(self): + _write_role(self.root, "role-a", {"git": {"Debian": ["git"], "batch": "no"}}) + with self.assertRaises(PackagesShapeError): + load_declarations(self.root) + + def test_a_shared_reference_is_no_declaration(self): + _write_shared(self.root, {"git": {"Debian": ["git"]}}) + _write_role(self.root, "role-a", {"git": {"shared": True}}) + declaration = self._declaration("git") + self.assertTrue(declaration.shared) + + def test_shared_references_are_collected_per_role(self): + _write_shared(self.root, {"git": {"Debian": ["git"]}}) + _write_role(self.root, "role-a", {"git": {"shared": True}}) + _write_role(self.root, "role-b", {"curl": {"Debian": ["curl"]}}) + self.assertEqual(load_references(self.root), {"role-a": {"git"}}) + + def test_shared_flag_in_the_root_file_is_no_reference(self): + _write_shared(self.root, {"git": {"shared": True}}) + self.assertEqual(load_references(self.root), {}) + self.assertIn("git", build_registry(self.root)) + def test_default_matrix_covers_five_distros(self): self.assertEqual( sorted(DISTRO_FAMILY), ["arch", "centos", "debian", "fedora", "ubuntu"] diff --git a/tests/unit/python/utils/roles/test_custom.py b/tests/unit/python/utils/roles/test_custom.py new file mode 100644 index 0000000000..1a3dc96ae9 --- /dev/null +++ b/tests/unit/python/utils/roles/test_custom.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +import unittest + +from utils.roles.custom import is_custom, is_custom_path +from utils.roles.mapping import ROLE_FILE_TASKS_MAIN + + +class TestIsCustom(unittest.TestCase): + def test_reserved_prefix_is_custom(self): + self.assertTrue(is_custom("web-app-cst-security-check")) + + def test_in_tree_application_is_not_custom(self): + self.assertFalse(is_custom("web-app-nextcloud")) + + def test_category_name_alone_is_not_custom(self): + self.assertFalse(is_custom("web-app-cst")) + + +class TestIsCustomPath(unittest.TestCase): + def test_file_in_a_placed_custom_role(self): + self.assertTrue( + is_custom_path(f"roles/web-app-cst-store/{ROLE_FILE_TASKS_MAIN}") + ) + + def test_file_in_an_in_tree_role(self): + self.assertFalse( + is_custom_path(f"roles/web-app-nextcloud/{ROLE_FILE_TASKS_MAIN}") + ) + + def test_custom_prefix_outside_roles(self): + self.assertFalse(is_custom_path("docs/web-app-cst-store/README.md")) + + def test_roles_directory_itself(self): + self.assertFalse(is_custom_path("roles")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/roles/test_invocations.py b/tests/unit/python/utils/roles/test_invocations.py new file mode 100644 index 0000000000..bc733816c5 --- /dev/null +++ b/tests/unit/python/utils/roles/test_invocations.py @@ -0,0 +1,241 @@ +import tempfile +import unittest +from pathlib import Path + +from utils.cache.yaml import dump_yaml +from utils.roles.invocations import ( + deploy_closure, + expand_roles, + role_invocations, + stage_files, + stage_invocations, +) +from utils.roles.mapping import ( + ROLE_FILE_HANDLERS_MAIN, + ROLE_FILE_META_MAIN, + ROLE_FILE_TASKS_MAIN, + ROLE_FILE_VARS_MAIN, +) + +ROLES = ("role-a", "role-b", "role-c", "sys-ctl-hlth-x", "sys-ctl-hlth-y") + + +def _role_file(role: str, role_file: str) -> str: + return f"roles/{role}/{role_file}" + + +class _TreeMixin: + def setUp(self) -> None: + self._tmp = tempfile.TemporaryDirectory() + self.root = Path(self._tmp.name) + self.addCleanup(self._tmp.cleanup) + for role in ROLES: + (self.root / "roles" / role / "tasks").mkdir(parents=True) + + def _write(self, relative: str, payload) -> Path: + path = self.root / relative + path.parent.mkdir(parents=True, exist_ok=True) + dump_yaml(str(path), payload) + return path + + def _invoked(self, tasks, role: str = "role-a") -> frozenset[str]: + self._write(_role_file(role, ROLE_FILE_TASKS_MAIN), tasks) + return role_invocations(str(self.root / "roles"), role) + + +class TestRoleInvocations(_TreeMixin, unittest.TestCase): + def test_a_literal_include_role_is_an_edge(self): + self.assertEqual( + self._invoked([{"include_role": {"name": "role-b"}}]), {"role-b"} + ) + + def test_an_import_role_is_an_edge(self): + self.assertEqual( + self._invoked([{"ansible.builtin.import_role": {"name": "role-b"}}]), + {"role-b"}, + ) + + def test_a_literal_loop_names_every_item(self): + tasks = [ + { + "include_role": {"name": "{{ dep }}"}, + "loop": ["role-b", "role-c"], + "loop_control": {"loop_var": "dep"}, + } + ] + self.assertEqual(self._invoked(tasks), {"role-b", "role-c"}) + + def test_a_template_with_a_literal_part_matches_a_glob(self): + tasks = [{"include_role": {"name": "sys-ctl-hlth-{{ kind }}"}}] + self.assertEqual(self._invoked(tasks), {"sys-ctl-hlth-x", "sys-ctl-hlth-y"}) + + def test_a_role_name_handed_over_as_a_var_is_an_edge(self): + tasks = [ + { + "include_tasks": "utils/load/app.yml", + "vars": {"load_app_id": "role-b"}, + } + ] + self.assertEqual(self._invoked(tasks), {"role-b"}) + + def test_including_a_task_file_of_another_role_is_an_edge(self): + tasks = [ + { + "include_tasks": "{{ lookup('path_absolute', 'roles/role-c/tasks/x.yml') }}" + } + ] + self.assertEqual(self._invoked(tasks), {"role-c"}) + + def test_includes_nested_in_blocks_count(self): + tasks = [ + { + "block": [{"include_role": {"name": "role-b"}}], + "rescue": [{"include_role": {"name": "role-c"}}], + } + ] + self.assertEqual(self._invoked(tasks), {"role-b", "role-c"}) + + def test_conditions_do_not_hide_an_edge(self): + tasks = [{"include_role": {"name": "role-b"}, "when": "false"}] + self.assertEqual(self._invoked(tasks), {"role-b"}) + + def test_a_bare_template_falls_back_to_quoted_role_names_in_vars(self): + self._write( + _role_file("role-a", ROLE_FILE_VARS_MAIN), + {"DEPS": "{{ ['role-b'] + (['role-c'] if flag else []) }}"}, + ) + tasks = [ + { + "include_role": {"name": "{{ dep }}"}, + "loop": "{{ DEPS }}", + "loop_control": {"loop_var": "dep"}, + } + ] + self.assertEqual(self._invoked(tasks), {"role-b", "role-c"}) + + def test_quoted_names_are_ignored_while_every_include_resolves(self): + self._write( + _role_file("role-a", ROLE_FILE_VARS_MAIN), {"OTHER": "{{ 'role-c' }}"} + ) + self.assertEqual( + self._invoked([{"include_role": {"name": "role-b"}}]), {"role-b"} + ) + + def test_unknown_role_names_are_dropped(self): + self.assertEqual( + self._invoked([{"include_role": {"name": "role-missing"}}]), frozenset() + ) + + def test_a_role_does_not_invoke_itself(self): + self.assertEqual( + self._invoked([{"include_role": {"name": "role-a"}}]), frozenset() + ) + + def test_handlers_count(self): + self._write( + _role_file("role-a", ROLE_FILE_HANDLERS_MAIN), + [{"include_role": {"name": "role-c"}}], + ) + self.assertEqual( + self._invoked([{"include_role": {"name": "role-b"}}]), {"role-b", "role-c"} + ) + + +class TestStageInvocations(_TreeMixin, unittest.TestCase): + def _stage(self, tasks): + return self._write("tasks/stages/01_constructor.yml", tasks) + + def test_a_group_membership_gate_closes_for_a_non_member(self): + path = self._stage( + [{"include_role": {"name": "role-b"}, "when": "'role-b' in group_names"}] + ) + self.assertEqual( + stage_invocations(path, frozenset(ROLES), seeds=[], group_names=[]), set() + ) + + def test_a_group_membership_gate_opens_for_a_member(self): + path = self._stage( + [{"include_role": {"name": "role-b"}, "when": "'role-b' in group_names"}] + ) + self.assertEqual( + stage_invocations(path, frozenset(ROLES), seeds=[], group_names=["role-b"]), + {"role-b"}, + ) + + def test_an_application_allowed_gate_decides_on_the_seeds(self): + path = self._stage( + [ + { + "when": "'role-b' | application_allowed(group_names, whitelist)", + "block": [{"include_role": {"name": "role-b"}}], + } + ] + ) + self.assertEqual( + stage_invocations(path, frozenset(ROLES), seeds=[], group_names=["role-b"]), + set(), + ) + self.assertEqual( + stage_invocations(path, frozenset(ROLES), seeds=["role-b"], group_names=[]), + {"role-b"}, + ) + + def test_any_other_condition_keeps_the_include(self): + path = self._stage( + [{"include_role": {"name": "role-c"}, "when": ["MODE_CLEANUP | bool"]}] + ) + self.assertEqual( + stage_invocations(path, frozenset(ROLES), seeds=[], group_names=[]), + {"role-c"}, + ) + + def test_stage_files_follow_the_host_types(self): + for name in ("01_constructor", "02_server", "02_workstation", "03_destructor"): + self._write(f"tasks/stages/{name}.yml", []) + self.assertEqual( + [path.name for path in stage_files(self.root, ["server"])], + ["01_constructor.yml", "02_server.yml", "03_destructor.yml"], + ) + + +class TestClosure(_TreeMixin, unittest.TestCase): + def test_invocations_are_followed_transitively(self): + self._write( + _role_file("role-b", ROLE_FILE_TASKS_MAIN), + [{"include_role": {"name": "role-c"}}], + ) + self._write( + _role_file("role-a", ROLE_FILE_TASKS_MAIN), + [{"include_role": {"name": "role-b"}}], + ) + self.assertEqual( + expand_roles({}, ["role-a"], project_root=self.root), + {"role-a", "role-b", "role-c"}, + ) + + def test_meta_dependencies_are_followed(self): + self._write( + _role_file("role-a", ROLE_FILE_META_MAIN), {"dependencies": ["role-c"]} + ) + self.assertEqual( + expand_roles({}, ["role-a"], project_root=self.root), {"role-a", "role-c"} + ) + + def test_the_deploy_closure_adds_the_stage_roles(self): + self._write( + "tasks/stages/01_constructor.yml", [{"include_role": {"name": "role-c"}}] + ) + self.assertEqual( + deploy_closure( + {}, + ["role-a"], + project_root=self.root, + host_types=[], + group_names=["role-a"], + ), + {"role-a", "role-c"}, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/utils/tests/swarm/test_matrix.py b/tests/unit/python/utils/tests/swarm/test_matrix.py new file mode 100644 index 0000000000..aa5db995bc --- /dev/null +++ b/tests/unit/python/utils/tests/swarm/test_matrix.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +import unittest +from unittest import mock + +from utils.tests.swarm import matrix + + +class TestSwarmDeployCommands(unittest.TestCase): + @mock.patch.object(matrix, "run_step", return_value=0) + def test_round_deploy_keeps_the_placed_custom_roles(self, run_step): + matrix._deploy( + app_id="web-app-cst-demo", + inv_dir="/tmp/inv-0", + extras_path="/tmp/extras.yml", + round_index=0, + total=1, + ) + cmd = run_step.call_args.kwargs["cmd"] + self.assertIn("cli.administration.deploy.swarm", cmd) + self.assertIn("--skip-pull", cmd) + + @mock.patch.object(matrix, "run_step", return_value=0) + def test_backup_host_deploy_keeps_the_placed_custom_roles(self, run_step): + matrix._deploy_backup_host( + app_id="web-app-cst-demo", + inv_dir="/tmp/inv-0", + extras_path="/tmp/extras.yml", + ) + cmd = run_step.call_args.kwargs["cmd"] + self.assertIn("cli.administration.deploy.dedicated", cmd) + self.assertIn("--skip-pull", cmd) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/cache/README.md b/utils/cache/README.md index a13fa7c6a4..aeba13cee2 100644 --- a/utils/cache/README.md +++ b/utils/cache/README.md @@ -11,7 +11,7 @@ This package contains the in-process cache layers Infinito.Nexus uses to keep CL | [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/` | 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). | +| `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; `users/store.py` reads the `sys_token_store_users` fact and digests the tokens the users are hydrated from, the digest the users and carrier keys share). | | [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. | diff --git a/utils/cache/files.py b/utils/cache/files.py index 4b2b2907ea..15bb488e88 100644 --- a/utils/cache/files.py +++ b/utils/cache/files.py @@ -29,10 +29,13 @@ view without subprocessing. from __future__ import annotations import os +import subprocess from functools import lru_cache from pathlib import Path from typing import TYPE_CHECKING +from utils.roles.custom import is_custom_path + from . import PROJECT_ROOT from .gitignore import is_path_gitignored, load_gitignore_patterns @@ -201,6 +204,54 @@ def iter_non_ignored_files( yield path +@lru_cache(maxsize=2) +def repository_files(*, untracked: bool = False) -> tuple[str, ...]: + """Repository-relative POSIX paths of every file ``git ls-files`` lists. + + Git ignores the custom roles an inventory pulls into ``roles/``, yet + every scan checks them like in-tree roles, so their files are listed + as well. + + Args: + untracked: also list the untracked files ``.gitignore`` does not exclude. + + Raises: + OSError: git is not installed. + subprocess.CalledProcessError: git cannot list the files. + """ + root = str(PROJECT_ROOT) + rels = _git_files() + if untracked: + rels.update(untracked_files()) + rels.update( + rel + for path in iter_project_files() + if is_custom_path(rel := os.path.relpath(path, root).replace(os.sep, "/")) + ) + return tuple(sorted(rels)) + + +@lru_cache(maxsize=1) +def untracked_files() -> tuple[str, ...]: + """Repository-relative POSIX paths of the untracked files ``.gitignore`` does not exclude. + + Raises: + OSError: git is not installed. + subprocess.CalledProcessError: git cannot list the files. + """ + return tuple(sorted(_git_files("--others", "--exclude-standard"))) + + +def _git_files(*options: str) -> set[str]: + out = subprocess.run( + ["git", "-c", "safe.directory=*", "ls-files", "-z", *options], + cwd=str(PROJECT_ROOT), + capture_output=True, + check=True, + ).stdout + return {rel for rel in out.decode("utf-8", errors="replace").split("\0") if rel} + + def _reset() -> None: """Test-only helper: clear the project-walk and file-content caches. @@ -211,3 +262,5 @@ def _reset() -> None: _all_project_files.cache_clear() _local_exclude_dirs.cache_clear() read_text.cache_clear() + repository_files.cache_clear() + untracked_files.cache_clear() diff --git a/utils/cache/gitignore.py b/utils/cache/gitignore.py index 3503f8b7bf..ea5355ae62 100644 --- a/utils/cache/gitignore.py +++ b/utils/cache/gitignore.py @@ -26,6 +26,8 @@ from functools import lru_cache from pathlib import Path from typing import TYPE_CHECKING +from utils.roles.custom import ROLES_GLOB + from . import PROJECT_ROOT if TYPE_CHECKING: @@ -45,6 +47,10 @@ def load_gitignore_patterns(root: str | None = None) -> tuple[str, ...]: would require a real pathspec implementation. If a future ``.gitignore`` adds them, extend this helper rather than duplicating the logic in callers. + + The custom-role pattern (:data:`utils.roles.custom.ROLES_GLOB`) is + left out: Git ignores pulled custom roles, yet every project-tree + scan checks them like in-tree roles. """ base = Path(root) if root else PROJECT_ROOT gitignore = base / ".gitignore" @@ -53,7 +59,7 @@ def load_gitignore_patterns(root: str | None = None) -> tuple[str, ...]: patterns: list[str] = [] for raw in gitignore.read_text(encoding="utf-8").splitlines(): line = raw.strip() - if not line or line.startswith(("#", "!")): + if not line or line.startswith(("#", "!")) or line == ROLES_GLOB: continue patterns.append(line) return tuple(patterns) diff --git a/utils/cache/users/__init__.py b/utils/cache/users/__init__.py index 9aa90b4f51..2d51d8332e 100644 --- a/utils/cache/users/__init__.py +++ b/utils/cache/users/__init__.py @@ -22,13 +22,12 @@ from utils.cache.base import ( _RENDER_GUARD, _cache_key, _deep_merge, - _fingerprint_mapping, _render_with_templar, _resolve_override_mapping, _resolve_roles_dir, _stable_variables_signature, - _tokens_file_signature, ) +from utils.cache.users import store as _store from utils.cache.users.placeholders import ( substitute_primary_domain_placeholder as _substitute_primary_domain_placeholder, ) @@ -224,34 +223,20 @@ def _load_store_users(file_tokens: str | os.PathLike[str] | None) -> dict[str, A return users if isinstance(users, dict) else {} -STORE_FACT = "sys_token_store_users" - - -def _store_snapshot(variables: Mapping[str, Any] | None) -> Mapping[str, Any] | None: - """Return the token store the play read from the stack host. - - Args: - variables: the play's variable scope. - - Returns: - The ``sys_token_store_users`` fact, or None outside a play that loaded - ``sys-token-store``. - """ - snapshot = (variables or {}).get(STORE_FACT) - return snapshot if isinstance(snapshot, Mapping) else None - - def _store_signature(variables: Mapping[str, Any] | None, tokens_file: Path) -> tuple: """Return the cache-key part of the store the users are hydrated from. Args: variables: the play's variable scope. tokens_file: the controller's tokens file, used when no snapshot exists. + + Returns: + ``(STORE_FACT, digest)``, equal for the tokens file and the + ``sys_token_store_users`` fact when both hold the same tokens. """ - snapshot = _store_snapshot(variables) - if snapshot is not None: - return (STORE_FACT, _fingerprint_mapping(snapshot)) - return _tokens_file_signature(tokens_file) + snapshot = _store.snapshot(variables) + store = snapshot if snapshot is not None else _load_store_users(tokens_file) + return (_store.STORE_FACT, _store.tokens_digest(store)) def _resolve_tokens_file(variables: Mapping[str, Any] | None) -> Path: @@ -435,7 +420,7 @@ def get_merged_users( resolved_roles_dir = _resolve_roles_dir(roles_dir=roles_dir) tokens_file = _resolve_tokens_file(variables) - snapshot = _store_snapshot(variables) + snapshot = _store.snapshot(variables) cache_key = ( _cache_key(resolved_roles_dir), _stable_variables_signature(source_variables), @@ -487,3 +472,4 @@ def get_merged_users( def _reset() -> None: _USERS_DEFAULTS_CACHE.clear() _MERGED_USERS_CACHE.clear() + _store._reset() diff --git a/utils/cache/users/store.py b/utils/cache/users/store.py new file mode 100644 index 0000000000..b779c0f698 --- /dev/null +++ b/utils/cache/users/store.py @@ -0,0 +1,68 @@ +"""The token store the users are hydrated from: the play fact and its digest.""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import Mapping +from typing import Any + +STORE_FACT = "sys_token_store_users" + +_DIGESTS: dict[str, str] = {} + + +def snapshot(variables: Mapping[str, Any] | None) -> Mapping[str, Any] | None: + """Return the token store the play read from the stack host. + + Args: + variables: the play's variable scope. + + Returns: + The ``sys_token_store_users`` fact, or None outside a play that loaded + ``sys-token-store``. + """ + value = (variables or {}).get(STORE_FACT) + return value if isinstance(value, Mapping) else None + + +def _tagged(value: Any) -> list: + return [True, str(value)] if isinstance(value, str) else [False, repr(value)] + + +def tokens_digest(store_users: Mapping[str, Any]) -> str: + """Digest exactly the part of a store that `_hydrate_users_tokens` reads. + + Args: + store_users: the store's ``users`` mapping. + + Returns: + The SHA-256 of every user entry with a tokens mapping, in store order, + and its non-empty stripped tokens, memoised per store content. + """ + memo_key = hashlib.md5( + repr(list(store_users.items())).encode("utf-8"), usedforsecurity=False + ).hexdigest() + digest = _DIGESTS.get(memo_key) + if digest is not None: + return digest + entries: list = [] + for user_key, user_data in store_users.items(): + if not isinstance(user_data, Mapping): + continue + tokens = user_data.get("tokens", {}) + if not isinstance(tokens, Mapping): + continue + kept = [] + for app_id, token in tokens.items(): + text = "" if token is None else str(token).strip() + if text: + kept.append([_tagged(app_id), text]) + entries.append([_tagged(user_key), kept]) + digest = hashlib.sha256(json.dumps(entries).encode("utf-8")).hexdigest() + _DIGESTS[memo_key] = digest + return digest + + +def _reset() -> None: + _DIGESTS.clear() diff --git a/utils/cache/yaml.py b/utils/cache/yaml.py index ceed126af2..33e1e614a4 100644 --- a/utils/cache/yaml.py +++ b/utils/cache/yaml.py @@ -33,6 +33,7 @@ CACHE SEMANTICS from __future__ import annotations from collections.abc import Mapping +from dataclasses import dataclass from pathlib import Path from typing import Any @@ -65,8 +66,42 @@ def _construct_vault_tag(loader, node): yaml.SafeLoader.add_constructor("!vault", _construct_vault_tag) _Loader.add_constructor("!vault", _construct_vault_tag) + +@dataclass(frozen=True) +class TaggedValue: + """A value under a local YAML tag, such as Ansible's ``!unsafe`` or ``!vault``, kept as written. + + Args: + tag: the tag, for example ``!vault``. + value: the scalar text, list or mapping under the tag; never rendered or decrypted. + """ + + tag: str + value: Any + + +def _construct_tagged(loader, _suffix, node): + if isinstance(node, yaml.SequenceNode): + return TaggedValue(node.tag, loader.construct_sequence(node, deep=True)) + if isinstance(node, yaml.MappingNode): + return TaggedValue(node.tag, loader.construct_mapping(node, deep=True)) + return TaggedValue(node.tag, loader.construct_scalar(node)) + + +class _TaggedLoader(_Loader): + pass + + +_TaggedLoader.yaml_constructors = { + tag: constructor + for tag, constructor in _Loader.yaml_constructors.items() + if not (tag or "").startswith("!") +} +_TaggedLoader.add_multi_constructor("!", _construct_tagged) + _MISSING = object() _CACHE: dict[tuple[str, int, int], list[Any]] = {} +_TAGGED_CACHE: dict[tuple[str, int, int], list[Any]] = {} def _path_key(path) -> str: @@ -89,18 +124,21 @@ def _load_docs(path) -> list[Any]: synthetic ``default_if_missing`` value never enters the cache and a later ``dump_yaml`` is picked up cleanly). """ - p = Path(path) + return _cached_docs(Path(path), _Loader, _CACHE) + + +def _cached_docs(p: Path, loader, cache: dict) -> list[Any]: sig = _signature(p) - if sig in _CACHE: - return _CACHE[sig] + if sig in cache: + return cache[sig] path_str = sig[0] - for stale_key in [k for k in _CACHE if k[0] == path_str and k != sig]: - _CACHE.pop(stale_key, None) + for stale_key in [k for k in cache if k[0] == path_str and k != sig]: + cache.pop(stale_key, None) with p.open("r", encoding="utf-8") as f: - docs = list(yaml.load_all(f, Loader=_Loader)) # nocheck: direct-yaml - _CACHE[sig] = docs + docs = list(yaml.load_all(f, Loader=loader)) # nocheck: direct-yaml + cache[sig] = docs return docs @@ -118,7 +156,24 @@ def _load_raw(path, *, default_if_missing: Any) -> Any: raise FileNotFoundError(p) return default_if_missing - docs = _load_docs(p) + return _single_doc(path, _load_docs(p)) + + +def load_yaml_tagged(path) -> Any: + """Load a single-document YAML file, keeping every local tag as a :class:`TaggedValue`. + + Reads files Ansible reads, where ``!unsafe`` and ``!vault`` are + legal, without rendering or decrypting any value. The parse is + cached apart from :func:`load_yaml_any`, which loads ``!vault`` as + its ciphertext string. + + Args: + path: the YAML file; a missing one raises ``FileNotFoundError``. + """ + return _single_doc(path, _cached_docs(Path(path), _TaggedLoader, _TAGGED_CACHE)) + + +def _single_doc(path, docs: list[Any]) -> Any: if not docs: return {} if len(docs) > 1: @@ -255,8 +310,9 @@ def load_yaml_all_str(text: str) -> list: def _drop_path(path) -> None: """Drop every cache entry for `path`.""" path_str = _path_key(path) - for stale_key in [k for k in _CACHE if k[0] == path_str]: - _CACHE.pop(stale_key, None) + for cache in (_CACHE, _TAGGED_CACHE): + for stale_key in [k for k in cache if k[0] == path_str]: + cache.pop(stale_key, None) def invalidate(path) -> None: @@ -280,6 +336,7 @@ def _reset() -> None: orchestrates calls to all of them. """ _CACHE.clear() + _TAGGED_CACHE.clear() _reset_cache_for_tests = _reset diff --git a/utils/env/handlers/passthrough.py b/utils/env/handlers/passthrough.py index 23e1560589..2b504fce0d 100644 --- a/utils/env/handlers/passthrough.py +++ b/utils/env/handlers/passthrough.py @@ -84,6 +84,7 @@ STATIC_KEYS = ( "INFINITO_PLAYWRIGHT_KEEP", "INFINITO_INVENTORY_EXTRA_VARS", "INFINITO_PUBLISH_PORTS", + "INFINITO_EXTRA_MOUNTS", "INFINITO_SKILLS_REPOSITORY", "INFINITO_SKIP_COMPILE", "INFINITO_MAIL_PRODUCTION_HOST", @@ -92,6 +93,7 @@ STATIC_KEYS = ( "INFINITO_TEST_RUNNER", "INFINITO_WORKSPACE_TRACKS", "INFINITO_LINT_RUNNER", + "INFINITO_LINT_DIFF_BASE", "INFINITO_APP_DISCOVERY_RUNNER", "INFINITO_DEPLOY_MODE", "INFINITO_DISCOVERY_SEED", diff --git a/utils/inventory/groups.py b/utils/inventory/groups.py index b0ec8e445b..10c83eafbd 100644 --- a/utils/inventory/groups.py +++ b/utils/inventory/groups.py @@ -1,10 +1,10 @@ -"""Static-inventory group-existence checks (YAML + INI).""" +"""Static-inventory group lookups (YAML + INI).""" from __future__ import annotations from pathlib import Path -from utils.cache.yaml import load_yaml_any +from utils.cache.yaml import load_yaml_any, load_yaml_tagged def inventory_has_group(inventory_path: str, group_name: str) -> bool: @@ -14,6 +14,48 @@ def inventory_has_group(inventory_path: str, group_name: str) -> bool: return _find_ini_section(inventory_path, group_name) +def inventory_groups(inventory_path: str) -> set[str]: + """Return every group a static inventory file declares. + + Ansible tags such as ``!unsafe`` and ``!vault`` load as opaque values. + + Args: + inventory_path: YAML (``.yml``/``.yaml``) or INI inventory file. + """ + if Path(inventory_path).suffix in (".yml", ".yaml"): + return _yaml_groups(load_yaml_tagged(inventory_path)) + return _ini_groups(inventory_path) + + +def _yaml_groups(node) -> set[str]: + groups: set[str] = set() + if not isinstance(node, dict): + return groups + for name, body in node.items(): + groups.add(str(name)) + if isinstance(body, dict): + groups |= _yaml_groups(body.get("children")) + return groups + + +def _ini_groups(inventory_path: str) -> set[str]: + groups: set[str] = set() + in_children = False + with Path(inventory_path).open(encoding="utf-8") as f: + for raw in f: + line = raw.strip() + if not line or line.startswith(("#", ";")): + continue + if line.startswith("[") and line.endswith("]"): + name, _, kind = line[1:-1].strip().partition(":") + groups.add(name) + in_children = kind == "children" + continue + if in_children: + groups.add(line.split()[0]) + return groups + + def _find_yaml_key(node, key: str) -> bool: if isinstance(node, dict): for k, v in node.items(): diff --git a/utils/networks/proxy.py b/utils/networks/proxy.py index 02f5366346..30c0ccd4a3 100644 --- a/utils/networks/proxy.py +++ b/utils/networks/proxy.py @@ -1,7 +1,7 @@ """Mode-aware nginx ``proxy_pass`` directive renderer (compose/swarm), SPOT. Trip-wire: the swarm oauth2 endpoint must forward ``$uri$is_args$args``, not -``$request_uri`` — during ``error_page 401 = /oauth2/start`` the original +``$request_uri`` — during the ``error_page 401 = @oauth2_start`` jump the original ``$request_uri`` stays ``/`` and oauth2-proxy 403s instead of redirecting. """ diff --git a/utils/packages/batch.py b/utils/packages/batch.py new file mode 100644 index 0000000000..64eec9be92 --- /dev/null +++ b/utils/packages/batch.py @@ -0,0 +1,50 @@ +"""The package ids a deploy installs in one run at its start. + +A role's batched ids are the ids its own ``meta/packages.yml`` declares plus +the shared root ids it references there, minus every id flagged +``batch: false``. Which roles a deploy may run is +:func:`utils.roles.invocations.deploy_closure`. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from utils.packages.registry import build_registry, load_references + +if TYPE_CHECKING: + from collections.abc import Iterable + from pathlib import Path + + +def batch_ids_by_role(project_root: Path) -> dict[str, set[str]]: + """Return, per role, the ids the deploy-start batch installs for it. + + Args: + project_root: repository root holding the package registry. + """ + registry = build_registry(project_root) + by_role: dict[str, set[str]] = {} + for package_id, declaration in registry.items(): + if declaration.role is not None and declaration.batch: + by_role.setdefault(declaration.role, set()).add(package_id) + for role, package_ids in load_references(project_root).items(): + by_role.setdefault(role, set()).update( + package_id + for package_id in package_ids + if package_id in registry and registry[package_id].batch + ) + return by_role + + +def batch_ids(roles: Iterable[str], project_root: Path) -> list[str]: + """Return the sorted ids the deploy-start batch installs for *roles*. + + Args: + roles: every role the deploy may run on the host. + project_root: repository root holding the package registry. + """ + by_role = batch_ids_by_role(project_root) + return sorted( + {package_id for role in roles for package_id in by_role.get(role, ())} + ) diff --git a/utils/packages/installed.py b/utils/packages/installed.py new file mode 100644 index 0000000000..3765874367 --- /dev/null +++ b/utils/packages/installed.py @@ -0,0 +1,173 @@ +"""Prove from the local package database that a package call has nothing to do. + +The action plugin runs the argv built here through ``ansible.builtin.command`` +and hands the result back. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +from utils.packages.calls import GENERIC_PACKAGE, STATE_PRESENT, STATES, ModuleCall + +if TYPE_CHECKING: + from collections.abc import Callable + +PLAIN_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9+._-]*") +"""Names carrying a version, an architecture, a path or a URL go to the +package manager module unqueried.""" + +INSTALLED = "i" +GONE = frozenset({"n", "c"}) +"""dpkg status letters: ``n`` (not-installed) and ``c`` (config-files) leave +no package behind. Every letter besides these and ``i`` marks a half-done +transaction that only the package manager module can finish.""" + +C_LOCALE = ("env", "LC_ALL=C") +"""The not-found messages are translated; only the C locale makes them +comparable.""" + + +def _dpkg_entry(line: str) -> tuple[str, str] | None: + name, tab, abbrev = line.partition("\t") + flags = abbrev.rstrip() + if not tab or len(flags) not in (2, 3): + return None + return name, flags[1:] + + +def _pacman_entry(line: str) -> tuple[str, str] | None: + fields = line.split(" ") + return (fields[0], INSTALLED) if len(fields) == 2 else None + + +def _rpm_entry(line: str) -> tuple[str, str] | None: + return (line, INSTALLED) if line.split() == [line] else None + + +@dataclass(frozen=True) +class _Query: + """How one package database is asked about a list of names. + + Args: + argv: the command, to which the names are appended. + entry: parses one stdout line into ``(name, state)``, None if foreign. + missing: the message naming a package the database does not know. + """ + + argv: tuple[str, ...] + entry: Callable[[str], tuple[str, str] | None] + missing: str + + +_RPM = _Query( + (*C_LOCALE, "rpm", "--query", "--queryformat=%{NAME}\n"), + _rpm_entry, + "package {} is not installed", +) + +QUERIES: dict[str, _Query] = { + "apt": _Query( + ( + *C_LOCALE, + "dpkg-query", + "--show", + "--showformat=${Package}\t${db:Status-Abbrev}\n", + "--", + ), + _dpkg_entry, + "dpkg-query: no packages found matching {}", + ), + "pacman": _Query( + (*C_LOCALE, "pacman", "--query", "--"), + _pacman_entry, + "error: package '{}' was not found", + ), + "dnf": _RPM, + "dnf5": _RPM, + "yum": _RPM, +} + + +def query_argv(call: ModuleCall, pkg_mgr: str) -> list[str] | None: + """Return the argv of the query that can prove *call* has nothing to do. + + Args: + call: one module call of a package plan. + pkg_mgr: the target's ``ansible_facts.pkg_mgr``. + + Returns: + None unless *call* is a plain host package manager call over plain + names, on a manager whose database this module can read. + """ + names = call.args.get("name") + if ( + call.module != GENERIC_PACKAGE + or call.become_user is not None + or set(call.args) != {"name", "state"} + or call.args["state"] not in STATES + or pkg_mgr not in QUERIES + or not isinstance(names, list) + or not names + or not all(isinstance(n, str) and PLAIN_NAME.fullmatch(n) for n in names) + ): + return None + return [*QUERIES[pkg_mgr].argv, *names] + + +def state_holds(call: ModuleCall, pkg_mgr: str, result: dict[str, Any]) -> bool: + """Tell whether the query result proves *call* has nothing to do. + + Args: + call: a call :func:`query_argv` built a query for. + pkg_mgr: the target's ``ansible_facts.pkg_mgr``. + result: the ``ansible.builtin.command`` result of that query. + + Returns: + True only when every name is proven to be in the requested state. + A result that cannot be read in full returns False. + """ + states = _states(QUERIES[pkg_mgr], call.args["name"], result) + if states is None: + return False + if call.args["state"] == STATE_PRESENT: + return all(found == {INSTALLED} for found in states.values()) + return all(found <= GONE for found in states.values()) + + +def _states( + query: _Query, names: list[str], result: dict[str, Any] +) -> dict[str, set[str]] | None: + rc, stdout, stderr = result.get("rc"), result.get("stdout"), result.get("stderr") + if ( + result.get("skipped") + or not isinstance(rc, int) + or not isinstance(stdout, str) + or not isinstance(stderr, str) + ): + return None + wanted = set(names) + messages = {query.missing.format(name): name for name in wanted} + states: dict[str, set[str]] = {} + missing: set[str] = set() + for line in stdout.splitlines(): + if line in messages: + missing.add(messages[line]) + continue + entry = query.entry(line) + if entry is None or entry[0] not in wanted: + return None + states.setdefault(entry[0], set()).add(entry[1]) + for line in stderr.splitlines(): + if line not in messages: + return None + missing.add(messages[line]) + if ( + states.keys() & missing + or states.keys() | missing != wanted + or (rc == 0) == bool(missing) + ): + return None + return {**states, **{name: set() for name in missing}} diff --git a/utils/packages/plan.py b/utils/packages/plan.py index cbc9eb3391..bc397ca129 100644 --- a/utils/packages/plan.py +++ b/utils/packages/plan.py @@ -9,7 +9,10 @@ plugin only executes what it is handed. from __future__ import annotations +from dataclasses import replace + from utils.packages.calls import ( + GENERIC_PACKAGE, STATE_ABSENT, STATE_PRESENT, ModuleCall, @@ -64,3 +67,49 @@ def build_plan(spec: PackageSpec, state: str) -> list[ModuleCall]: if spec.repo: return repository_calls(spec.repo, names) return [package_call(names, STATE_PRESENT)] + + +def _plain(plan: list[ModuleCall]) -> bool: + if not plan or any( + call.module != GENERIC_PACKAGE + or call.become_user is not None + or set(call.args) != {"name", "state"} + for call in plan + ): + return False + return len({call.args["state"] for call in plan}) == 1 + + +def merge_plans(plans: list[list[ModuleCall]]) -> list[list[ModuleCall]]: + """Fold the plans that only call the host's package manager into one plan. + + The plain plans are aligned on their last call, so the n-th call from + the end of every plan lands in the same merged call and each plan's own + order survives: a bootstrap package still installs before the names it + unlocks. Every other plan follows unchanged, in request order. + + Args: + plans: one plan per package id, in request order. + + Returns: + one merged plan per state the plain plans bring their names into, + then every other plan. + """ + groups: dict[str, list[list[ModuleCall]]] = {} + for plan in plans: + if _plain(plan): + groups.setdefault(plan[-1].args["state"], []).append(plan) + return [_merge(group) for group in groups.values()] + [ + plan for plan in plans if not _plain(plan) + ] + + +def _merge(plain: list[list[ModuleCall]]) -> list[ModuleCall]: + merged: list[ModuleCall] = [] + for offset in range(max(len(plan) for plan in plain), 0, -1): + calls = [plan[-offset] for plan in plain if len(plan) >= offset] + names = list( + dict.fromkeys(name for call in calls for name in call.args["name"]) + ) + merged.append(replace(calls[0], args={**calls[0].args, "name": names})) + return merged diff --git a/utils/packages/registry.py b/utils/packages/registry.py index d2dac39382..10098914fd 100644 --- a/utils/packages/registry.py +++ b/utils/packages/registry.py @@ -25,9 +25,11 @@ if TYPE_CHECKING: from utils.cache import PROJECT_ROOT from utils.cache.yaml import load_yaml_any from utils.packages.schema import ( + BATCH_KEY, DISTRO_FAMILY, INVENTORY_PACKAGES_VAR, ROLE_FILE_META_PACKAGES, + SHARED_REFERENCE, PackageSpec, PackagesShapeError, normalize_entry, @@ -53,6 +55,11 @@ class Declaration: """Human-readable owner for lint and runtime messages.""" return self.role or "the shared registry" + @property + def batch(self) -> bool: + """Whether the deploy-start batch installs this id.""" + return self.mapping.get(BATCH_KEY, True) + def iter_package_files(project_root: Path) -> Iterator[tuple[str | None, Path]]: """Yield ``(role_or_None, path)`` for every package declaration file. @@ -73,13 +80,7 @@ def iter_package_files(project_root: Path) -> Iterator[tuple[str | None, Path]]: yield role_dir.name, path -def load_declarations(project_root: Path) -> list[Declaration]: - """Read every ``meta/packages.yml`` without deduplicating. - - Duplicates are returned as-is so the uniqueness lint can report all - offenders instead of failing on the first one. - """ - declarations: list[Declaration] = [] +def _entries(project_root: Path) -> Iterator[tuple[str | None, Path, str, Any]]: for role, path in iter_package_files(project_root): raw = load_yaml_any(str(path), default_if_missing={}) or {} if not isinstance(raw, dict): @@ -88,15 +89,46 @@ def load_declarations(project_root: Path) -> list[Declaration]: f"got {type(raw).__name__}." ) for package_id, mapping in raw.items(): - if not isinstance(mapping, dict): - raise PackagesShapeError( - f"{path}: package '{package_id}' must map distro keys to " - f"specs, got {type(mapping).__name__}." - ) - declarations.append(Declaration(str(package_id), role, path, mapping)) + yield role, path, str(package_id), mapping + + +def _is_reference(role: str | None, mapping: Any) -> bool: + return role is not None and mapping == SHARED_REFERENCE + + +def load_declarations(project_root: Path) -> list[Declaration]: + """Read every ``meta/packages.yml`` without deduplicating. + + Duplicates are returned as-is so the uniqueness lint can report all + offenders instead of failing on the first one. A role's reference to a + shared id is no declaration and is left to :func:`load_references`. + """ + declarations: list[Declaration] = [] + for role, path, package_id, mapping in _entries(project_root): + if _is_reference(role, mapping): + continue + if not isinstance(mapping, dict): + raise PackagesShapeError( + f"{path}: package '{package_id}' must map distro keys to " + f"specs, got {type(mapping).__name__}." + ) + if not isinstance(mapping.get(BATCH_KEY, False), bool): + raise PackagesShapeError( + f"{path}: {package_id}.{BATCH_KEY} must be a boolean when set." + ) + declarations.append(Declaration(package_id, role, path, mapping)) return declarations +def load_references(project_root: Path) -> dict[str, set[str]]: + """Return, per role, the shared root ids its own file references.""" + references: dict[str, set[str]] = {} + for role, _path, package_id, mapping in _entries(project_root): + if _is_reference(role, mapping): + references.setdefault(str(role), set()).add(package_id) + return references + + def iter_inventory_package_lists( project_root: Path, ) -> Iterator[tuple[Path, list[str]]]: diff --git a/utils/packages/schema.py b/utils/packages/schema.py index ec8e782cff..31c921f3b1 100644 --- a/utils/packages/schema.py +++ b/utils/packages/schema.py @@ -71,6 +71,26 @@ which counts as covered; a *missing* key is a coverage gap. ``virtual: true`` records that the package manager satisfies the name through an RPM ``Provides`` rather than a package of that name, so an index lookup by name legitimately finds nothing while the install works. + +Every id is installed by the one ``package_install`` run the constructor +starts each deploy with, for every role that deploy may run. ``batch: false`` +on the id, next to its distro keys, takes it out of that run; the role's own +``package_install`` task then installs it, which is required when the install +is conditional or must wait for a setup step:: + + docker-cli: + Archlinux: [docker] + Debian: + names: [docker-ce] + repo: + managed_externally: the role adds the Docker repository first + batch: false + +A role that needs an id of the shared root file references it in its own +file, so the batch knows to install it with the role:: + + git: + shared: true """ from __future__ import annotations @@ -87,6 +107,12 @@ ROLE_FILE_META_PACKAGES = "meta/packages.yml" INVENTORY_PACKAGES_VAR = "PACKAGES" """Inventory variable listing extra package ids a bundle installs.""" +BATCH_KEY = "batch" +"""Id-level flag; ``false`` keeps the id out of the deploy-start batch.""" + +SHARED_REFERENCE: dict[str, bool] = {"shared": True} +"""The whole mapping of a role-file entry that references a root id.""" + SOURCE_REPO = "repo" SOURCE_AUR = "aur" SOURCE_COPR = "copr" diff --git a/utils/roles/custom.py b/utils/roles/custom.py new file mode 100644 index 0000000000..5a8ee0b5ce --- /dev/null +++ b/utils/roles/custom.py @@ -0,0 +1,40 @@ +"""Custom-role naming SPOT. + +A custom role is the inventory group ``web-app-cst-``. Its +``applications.`` block marks it with ``custom: true`` and names +the repository it comes from under ``source``. The pull places it as +``roles/``, which ``.gitignore`` keeps out of every core commit. + +Keep this module free of imports beyond the standard library: the +project-tree scan helpers in :mod:`utils.cache` read it. +""" + +from __future__ import annotations + +PREFIX: str = "web-app-cst-" +ROLES_GLOB: str = f"roles/{PREFIX}*" +CUSTOM_KEY: str = "custom" +SOURCE_KEY: str = "source" + + +class CustomRoleError(Exception): + """A custom-role declaration, fetch or placement that stops the run.""" + + +def is_custom(name: str) -> bool: + """Whether *name* carries the reserved custom-role prefix. + + Args: + name: a role directory, inventory group or application_id. + """ + return name.startswith(PREFIX) + + +def is_custom_path(rel_path: str) -> bool: + """Whether a repository-relative POSIX path lies in a placed custom role. + + Args: + rel_path: path relative to the repository root, ``/``-separated. + """ + parts = rel_path.split("/") + return len(parts) > 1 and parts[0] == "roles" and is_custom(parts[1]) diff --git a/utils/roles/invocations.py b/utils/roles/invocations.py new file mode 100644 index 0000000000..ad52eb1674 --- /dev/null +++ b/utils/roles/invocations.py @@ -0,0 +1,326 @@ +"""Roles a deploy may run, read statically from task files. + +A role invokes another role when an ``include_role``/``import_role`` names it +(literally, through a literal loop item, or through a template whose literal +part narrows a glob), when one of its tasks hands a role name to an include +as a ``vars`` value (``load_app_id``, ``list_or_shoot_roles``), and when it +includes a task or handler file of that role by path. A role that includes +a bare template no loop resolves invokes every role its ``vars`` and +``defaults`` name in quotes. + +Conditions inside roles are ignored, so :func:`deploy_closure` returns every +role a deploy may run, a superset of the roles it will run. The play's stage +files are the one exception: a group-membership gate there +(``'' in group_names``, ``'' | application_allowed(...)``) is +decided against the host, because it is what selects the host's roles. +""" + +from __future__ import annotations + +import fnmatch +import re +from functools import cache +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml_any +from utils.roles.applications.in_group_deps import reachable_roles + +if TYPE_CHECKING: + from collections.abc import Iterable, Iterator + +INCLUDE_ROLE_KEYS: frozenset[str] = frozenset( + { + "include_role", + "import_role", + "ansible.builtin.include_role", + "ansible.builtin.import_role", + } +) +TASK_FILE_DIRS: tuple[str, ...] = ("tasks", "handlers") +TEMPLATE_DIRS: tuple[str, ...] = ("vars", "defaults") +LOOP_KEYS: tuple[str, ...] = ("loop", "with_items", "with_list") +NESTED_KEYS: tuple[str, ...] = ("block", "rescue", "always") +STAGES_DIR = Path("tasks") / "stages" +CONSTRUCTOR_STAGE = "01_constructor.yml" +DESTRUCTOR_STAGE = "03_destructor.yml" + +_ROLE_FILE_REF_RE = re.compile(r"roles/(?P[a-z0-9-]+)/(?:tasks|handlers)/") +_QUOTED_NAME_RE = re.compile(r"['\"](?P[a-z0-9][a-z0-9-]*)['\"]") +_TEMPLATE_RE = re.compile(r"\{\{.*?\}\}") +_MEMBERSHIP_GATE_RE = re.compile( + r"^'(?P[a-z0-9-]+)'\s*(?Pin\s+group_names|\|\s*application_allowed\b)" +) + + +@cache +def role_names(roles_dir: str) -> frozenset[str]: + """Return the name of every role directory under *roles_dir*.""" + root = Path(roles_dir) + if not root.is_dir(): + return frozenset() + return frozenset(path.name for path in root.iterdir() if path.is_dir()) + + +def iter_tasks(node: Any) -> Iterator[dict[str, Any]]: + """Yield every task of a task list, descending into blocks.""" + if not isinstance(node, list): + return + for task in node: + if not isinstance(task, dict): + continue + yield task + for key in NESTED_KEYS: + yield from iter_tasks(task.get(key)) + + +def _strings(value: Any) -> Iterator[str]: + if isinstance(value, str): + yield value + elif isinstance(value, dict): + for item in value.values(): + yield from _strings(item) + elif isinstance(value, list): + for item in value: + yield from _strings(item) + + +def _named(name: str, known: frozenset[str]) -> set[str] | None: + name = name.strip() + if "{{" not in name: + return {name} + pattern = _TEMPLATE_RE.sub("*", name) + if not pattern.strip("*"): + return None + return set(fnmatch.filter(known, pattern)) + + +def _looped(task: dict[str, Any]) -> set[str] | None: + for key in LOOP_KEYS: + if key not in task: + continue + items = task[key] + if not isinstance(items, list): + return None + found: set[str] = set() + for item in items: + if isinstance(item, str): + found.add(item.strip()) + elif isinstance(item, dict): + found.update( + str(item[field]).strip() + for field in ("role", "name") + if isinstance(item.get(field), str) + ) + return found + return None + + +def task_invocations( + task: dict[str, Any], known: frozenset[str] +) -> tuple[set[str], bool]: + """Return the roles one task invokes, and whether a name stayed unresolved. + + Args: + task: one task mapping; the tasks nested in its blocks are not read. + known: every existing role name. + """ + own = {key: value for key, value in task.items() if key not in NESTED_KEYS} + invoked = {value.strip() for value in _strings(own.get("vars"))} & known + for value in _strings(own): + invoked.update( + match.group("role") for match in _ROLE_FILE_REF_RE.finditer(value) + ) + + unresolved = False + for key in INCLUDE_ROLE_KEYS & own.keys(): + spec = own[key] + name = spec.get("name") if isinstance(spec, dict) else spec + named = _named(name, known) if isinstance(name, str) else None + if named is None: + named = _looped(own) + if named is None: + unresolved = True + continue + invoked |= named + return invoked & known, unresolved + + +def file_invocations(path: Path, known: frozenset[str]) -> tuple[set[str], bool]: + """Return the roles one task file invokes, and whether a name stayed unresolved. + + Args: + path: a task or handler file. + known: every existing role name. + """ + invoked: set[str] = set() + unresolved = False + for task in iter_tasks(load_yaml_any(str(path), default_if_missing=None)): + roles, open_name = task_invocations(task, known) + invoked |= roles + unresolved = unresolved or open_name + return invoked, unresolved + + +def _files(role_dir: Path, subdirs: Iterable[str]) -> list[Path]: + return sorted( + path + for sub in subdirs + if (role_dir / sub).is_dir() + for path in (role_dir / sub).rglob("*.yml") + ) + + +@cache +def role_invocations(roles_dir: str, role: str) -> frozenset[str]: + """Return every other role *role* may invoke. + + Args: + roles_dir: directory holding the role folders. + role: role name. + """ + known = role_names(roles_dir) + role_dir = Path(roles_dir) / role + invoked: set[str] = set() + unresolved = False + for path in _files(role_dir, TASK_FILE_DIRS): + roles, open_name = file_invocations(path, known) + invoked |= roles + unresolved = unresolved or open_name + if unresolved: + for path in _files(role_dir, TEMPLATE_DIRS): + invoked.update( + match.group("name") + for match in _QUOTED_NAME_RE.finditer(read_text(str(path))) + ) + invoked.discard(role) + return frozenset(invoked & known) + + +def stage_files(project_root: Path, host_types: Iterable[str]) -> list[Path]: + """Return the play's stage files a host with *host_types* runs, in order. + + Args: + project_root: repository root. + host_types: the host's deployment types (``server``, ``workstation``). + """ + stages = Path(project_root) / STAGES_DIR + names = [ + CONSTRUCTOR_STAGE, + *(f"02_{host_type}.yml" for host_type in host_types), + DESTRUCTOR_STAGE, + ] + return [stages / name for name in names if (stages / name).is_file()] + + +def _gate_closed( + task: dict[str, Any], seeds: frozenset[str], group_names: frozenset[str] +) -> bool: + when = task.get("when") + for condition in when if isinstance(when, list) else [when]: + if not isinstance(condition, str): + continue + match = _MEMBERSHIP_GATE_RE.match(condition.strip()) + if match is None: + continue + members = group_names if match.group("test").startswith("in") else seeds + if match.group("role") not in members: + return True + return False + + +def _open_tasks( + node: Any, seeds: frozenset[str], group_names: frozenset[str] +) -> Iterator[dict[str, Any]]: + if not isinstance(node, list): + return + for task in node: + if not isinstance(task, dict) or _gate_closed(task, seeds, group_names): + continue + yield task + for key in NESTED_KEYS: + yield from _open_tasks(task.get(key), seeds, group_names) + + +def stage_invocations( + path: Path, + known: frozenset[str], + *, + seeds: Iterable[str], + group_names: Iterable[str], +) -> set[str]: + """Return the roles a stage file invokes on one host. + + Args: + path: a file under ``tasks/stages/``. + known: every existing role name. + seeds: the application roles the host deploys. + group_names: the host's inventory groups. + """ + doc = load_yaml_any(str(path), default_if_missing=None) + invoked: set[str] = set() + for task in _open_tasks(doc, frozenset(seeds), frozenset(group_names)): + invoked |= task_invocations(task, known)[0] + return invoked + + +def deploy_closure( + applications: dict[str, Any], + seeds: Iterable[str], + *, + project_root: Path, + host_types: Iterable[str], + group_names: Iterable[str], +) -> set[str]: + """Return every role a deploy may run on one host. + + Args: + applications: the merged applications map, for service edges. + seeds: the application roles the host deploys. + project_root: repository root. + host_types: the host's deployment types, selecting its stage files. + group_names: the host's inventory groups. + """ + known = role_names(str(Path(project_root) / "roles")) + seed_set = {str(seed) for seed in seeds} + roots = set(seed_set) + for path in stage_files(project_root, host_types): + roots |= stage_invocations(path, known, seeds=seed_set, group_names=group_names) + return expand_roles(applications, roots, project_root=project_root) + + +def expand_roles( + applications: dict[str, Any], roles: Iterable[str], *, project_root: Path +) -> set[str]: + """Return *roles* plus every role they reach, transitively. + + Edges are ``meta/main.yml`` dependencies, the service edges of + *applications*, and :func:`role_invocations`. + + Args: + applications: the merged applications map; empty for no service edges. + roles: the roles to start from. + project_root: repository root. + """ + roles_dir = str(Path(project_root) / "roles") + known = role_names(roles_dir) + frontier = {str(role) for role in roles} + reached: set[str] = set() + while frontier: + expanded = ( + reachable_roles( + applications, + sorted(frontier), + project_root=str(project_root), + roles_dir=roles_dir, + ) + | frontier + ) - reached + reached |= expanded + frontier = { + invoked + for role in expanded & known + for invoked in role_invocations(roles_dir, role) + } - reached + return reached diff --git a/utils/tests/swarm/matrix.py b/utils/tests/swarm/matrix.py index 08aad5219e..73d9a25fd8 100644 --- a/utils/tests/swarm/matrix.py +++ b/utils/tests/swarm/matrix.py @@ -158,6 +158,7 @@ def _deploy( "-p", f"{inv_dir}/.password", "--skip-build", + "--skip-pull", "--skip-cleanup", "--skip-backup", "-e", @@ -195,6 +196,7 @@ def _deploy_backup_host(*, app_id: str, inv_dir: str, extras_path: str) -> int: "-p", f"{inv_dir}/.password", "--skip-build", + "--skip-pull", "--skip-cleanup", "--skip-backup", "-e",