diff --git a/README.md b/README.md index c85979e481..ab09fa0062 100644 --- a/README.md +++ b/README.md @@ -183,7 +183,7 @@ Every invokable role in the tested lifecycle envelope, with its upstream homepag | [Unbound](roles/svc-dns-unbound/) | beta | Central recursive/forwarding DNSSEC resolver on a static IP for consumer stacks to target as their DNS | [🌐](https://nlnetlabs.nl/projects/unbound/about/) [πŸ› οΈ](roles/svc-dns-unbound/README.md#quick-setup) | | | [Universal Logout](roles/web-svc-logout/) | beta | Central logout proxy for single-action sign-out across all OIDC-connected apps, with Nginx snippets and a live status UI | [πŸ› οΈ](roles/web-svc-logout/README.md#quick-setup) | [Corporate Design](roles/web-svc-css/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/) | | [Wazuh](roles/web-app-wazuh/) | beta | Open-source SIEM and XDR platform for monitoring, log analysis, intrusion/vulnerability detection, and compliance | [🌐](https://wazuh.com/) [🎬](https://www.youtube.com/watch?v=peTSzcAueEc) [πŸ› οΈ](roles/web-app-wazuh/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [OpenLDAP](roles/svc-db-openldap/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | -| [web-app-pihole](roles/web-app-pihole/) | beta | Network-wide DNS sinkhole for blocking ads and trackers across all devices, with DHCP and a web admin dashboard | [🌐](https://pi-hole.net/) [🎬](https://youtu.be/KBXTnrD_Zs4) [πŸ› οΈ](roles/web-app-pihole/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Redis](roles/svc-db-redis/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | +| [web-app-pihole](roles/web-app-pihole/) | beta | Network-wide DNS sinkhole for blocking ads and trackers across all devices, with DHCP and a web admin dashboard | [🌐](https://pi-hole.net/) [🎬](https://youtu.be/KBXTnrD_Zs4) [πŸ› οΈ](roles/web-app-pihole/README.md#quick-setup) | [Backup Docker Volumes](roles/svc-bkp-volume-2-local/), [Content Delivery Network](roles/web-svc-cdn/), [Corporate Design](roles/web-svc-css/), [Dashboard](roles/web-app-dashboard/), [Keycloak](roles/web-app-keycloak/), [Matomo](roles/web-app-matomo/), [Prometheus](roles/web-app-prometheus/), [Tor Onion Service](roles/svc-net-tor/), [Universal Logout](roles/web-svc-logout/) | | [Wireguard](roles/svc-net-wireguard-core/) | alpha | Host-level WireGuard VPN service with wg-quick config, package install, and IP-forwarding sysctl for secure tunnels | [🌐](https://www.wireguard.com/) [πŸ› οΈ](roles/svc-net-wireguard-core/README.md#quick-setup) | | | [Wireguard Client](roles/svc-net-wireguard-plain/) | alpha | Client-side WireGuard VPN role for stable connectivity with a systemd service and script that tune interface MTU | [🌐](https://www.wireguard.com/) [πŸ› οΈ](roles/svc-net-wireguard-plain/README.md#quick-setup) | | | [WireGuard Client behind NAT](roles/svc-net-wireguard-firewalled/) | alpha | Networking helper for iptables forwarding and NAT masquerading of a WireGuard client running behind NAT or a firewall | [πŸ› οΈ](roles/svc-net-wireguard-firewalled/README.md#quick-setup) | | diff --git a/cli/build/docs/readme/generate.py b/cli/build/docs/readme/generate.py index 201362567f..40b6b7c780 100644 --- a/cli/build/docs/readme/generate.py +++ b/cli/build/docs/readme/generate.py @@ -44,9 +44,10 @@ def _is_invokable(role_name: str) -> bool: def _render_template(ctx: dict) -> str: - env = jinja2.Environment( # noqa: S701 β€” renders Markdown, not HTML; escaping would corrupt it + env = jinja2.Environment( loader=jinja2.FileSystemLoader(str(schema.TEMPLATE_DIR)), keep_trailing_newline=True, + autoescape=jinja2.select_autoescape(), ) return env.get_template(schema.TEMPLATE_NAME).render(**ctx) diff --git a/cli/build/docs/readme/schema.py b/cli/build/docs/readme/schema.py index dc66b8ea89..ca7a3b3c47 100644 --- a/cli/build/docs/readme/schema.py +++ b/cli/build/docs/readme/schema.py @@ -42,9 +42,10 @@ _OPTIONAL_CTX: dict = { def _render(ctx: dict) -> str: - env = jinja2.Environment( # noqa: S701 β€” renders Markdown, not HTML; escaping would corrupt it + env = jinja2.Environment( loader=jinja2.FileSystemLoader(str(TEMPLATE_DIR)), keep_trailing_newline=True, + autoescape=jinja2.select_autoescape(), ) return env.get_template(TEMPLATE_NAME).render(**ctx) diff --git a/docs/contributing/artefact/files/role/playwright.specs.js.md b/docs/contributing/artefact/files/role/playwright.specs.js.md index be19d1f763..cbb0404262 100644 --- a/docs/contributing/artefact/files/role/playwright.specs.js.md +++ b/docs/contributing/artefact/files/role/playwright.specs.js.md @@ -308,6 +308,8 @@ The teardown MUST: Specs MUST decode quoted values before building URLs or typing credentials. The recurring helpers `decodeDotenvQuotedValue(value)` and `normalizeBaseUrl(value)` live in [`personas/utils/dotenv.js`](../../../../../roles/test-e2e-playwright/files/personas/utils/dotenv.js) and are re-exported through `require("./personas")`. Specs that need them MUST import from `./personas`; inline copies are forbidden and caught at review. +- A role whose spec files cannot run in parallel MUST set `PLAYWRIGHT_MAX_WORKERS` in `templates/playwright.env.j2`. + The central `playwright.config.js` runs the suite on the smaller of that value and the worker count the harness computed. ## Service gating contract πŸ”’ diff --git a/group_vars/all/17_resource.yml b/group_vars/all/17_resource.yml index 281b5eff75..4392f54ade 100644 --- a/group_vars/all/17_resource.yml +++ b/group_vars/all/17_resource.yml @@ -43,16 +43,9 @@ RESOURCE_MEM_LIMIT: "{{ RESOURCE_MEM_LIMIT_NUM }}g" RESOURCE_PIDS_LIMIT: 512 POSTGRES_VCPUS: "{{ ansible_facts['processor_vcpus'] | int }}" -POSTGRES_TOTAL_RAM_MB: "{{ ansible_facts['memtotal_mb'] | int }}" POSTGRES_MAX_CONNECTIONS: "{{ [ ((POSTGRES_VCPUS | int) * 30 + 50), 400 ] | min }}" POSTGRES_ALLOWED_AVG_CONNECTIONS: "{{ (POSTGRES_MAX_CONNECTIONS | split_postgres_connections(lookup('path_absolute', 'roles'))) | int }}" POSTGRES_SUPERUSER_RESERVED_CONNECTIONS: 3 -POSTGRES_SHARED_BUFFERS_MB: "{{ ((POSTGRES_TOTAL_RAM_MB | int) * 25) // 100 }}" -POSTGRES_SHARED_BUFFERS: "{{ POSTGRES_SHARED_BUFFERS_MB ~ 'MB' }}" -POSTGRES_WORK_MEM_MB: "{{ [ ( (POSTGRES_TOTAL_RAM_MB | int) // ( [ (POSTGRES_MAX_CONNECTIONS | int), 1 ] | max ) // 2 ), 1 ] | max }}" -POSTGRES_WORK_MEM: "{{ POSTGRES_WORK_MEM_MB ~ 'MB' }}" -POSTGRES_MAINTENANCE_WORK_MEM_MB: "{{ [ (((POSTGRES_TOTAL_RAM_MB | int) * 5) // 100), 64 ] | max }}" -POSTGRES_MAINTENANCE_WORK_MEM: "{{ POSTGRES_MAINTENANCE_WORK_MEM_MB ~ 'MB' }}" POSTGRES_MAX_LOCKS_PER_TRANSACTION: 256 POSTGRES_DELAY: 2 diff --git a/library/keycloak_kcadm_update.py b/library/keycloak_kcadm_update.py index 3913e0ec17..863c67aca3 100755 --- a/library/keycloak_kcadm_update.py +++ b/library/keycloak_kcadm_update.py @@ -14,6 +14,9 @@ from ansible.module_utils.keycloak_scopes import converge_client_scope_lists NO_SUCH_CONTAINER_RE = re.compile(r"no such container", re.IGNORECASE) DEAD_CID_MAX_RETRIES = 80 DEAD_CID_RETRY_DELAY = 3 +CONFIG_LOCK_RE = re.compile(r"Failed to get lock on") +CONFIG_LOCK_MAX_RETRIES = 10 +CONFIG_LOCK_RETRY_DELAY = 1 DOCUMENTATION = r""" --- @@ -119,7 +122,7 @@ result: """ -def _shell(cmd, check): +def _shell(cmd, check, lock_retries=CONFIG_LOCK_MAX_RETRIES): rc = subprocess.run( # noqa: S602 - host-trusted argv; kcadm wrapper needs shell pipes/&& cmd, shell=True, @@ -128,6 +131,9 @@ def _shell(cmd, check): ) stdout = rc.stdout.decode("utf-8", errors="replace").strip() stderr = rc.stderr.decode("utf-8", errors="replace").strip() + if rc.returncode != 0 and lock_retries and CONFIG_LOCK_RE.search(stderr): + time.sleep(CONFIG_LOCK_RETRY_DELAY) + return _shell(cmd, check, lock_retries - 1) return rc.returncode, stdout, stderr diff --git a/package-lock.json b/package-lock.json index 219614de7d..dec3a469ef 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,7 @@ "devDependencies": { "@eslint/js": "^10.0.1", "@playwright/test": "^1.63.0", - "eslint": "^10.9.1", + "eslint": "^10.12.0", "eslint-plugin-playwright": "^2.10.5", "globals": "^17.13.0", "stylelint": "^17.16.0" @@ -848,9 +848,9 @@ } }, "node_modules/eslint": { - "version": "10.10.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.10.0.tgz", - "integrity": "sha512-NPXn6r5zl4uET1DAVPaOwzX3rut4c0wcmw3dWJAfOsTM5+TogXo0DDjz8pwm/hL8cyVNpHqeK4JpN0NjnyFFNw==", + "version": "10.12.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.12.0.tgz", + "integrity": "sha512-npHjrHb2o4ehH3mE+YuxABR+0gyb0aVWCIolgJDArwCiHEIsonBm3ZKjel5b0U5+a+MbEvIyRCGCzD3eKKK2NA==", "dev": true, "license": "MIT", "workspaces": [ diff --git a/package.json b/package.json index d07df50441..799548eab2 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "devDependencies": { "@eslint/js": "^10.0.1", "@playwright/test": "^1.63.0", - "eslint": "^10.9.1", + "eslint": "^10.12.0", "eslint-plugin-playwright": "^2.10.5", "globals": "^17.13.0", "stylelint": "^17.16.0" diff --git a/plugins/filter/memory_filters.py b/plugins/filter/memory_filters.py deleted file mode 100644 index e62cdc5df2..0000000000 --- a/plugins/filter/memory_filters.py +++ /dev/null @@ -1,184 +0,0 @@ -from __future__ import annotations - -import re - -from ansible.errors import AnsibleFilterError - -from utils.roles.applications.config import get -from utils.roles.entity.name import get_entity_name - -_UNIT_RE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([kKmMgGtT]?[bB]?)?\s*$") -_FACTORS = { - "": 1, - "b": 1, - "k": 1024, - "kb": 1024, - "m": 1024**2, - "mb": 1024**2, - "g": 1024**3, - "gb": 1024**3, - "t": 1024**4, - "tb": 1024**4, -} - -# ------------------------------------------------------ -# Helpers: unit conversion -# ------------------------------------------------------ - - -def _to_bytes(v: str) -> int: - """Convert a human-readable size string (e.g., '2g', '512m') to bytes.""" - if v is None: - raise AnsibleFilterError("memory_filters: size value is None") - - s = str(v).strip() - m = _UNIT_RE.match(s) - if not m: - raise AnsibleFilterError(f"memory_filters: invalid size '{v}'") - - num, unit = m.group(1), (m.group(2) or "").lower() - - try: - val = float(num) - except ValueError as e: - raise AnsibleFilterError(f"memory_filters: invalid numeric size '{v}'") from e - - factor = _FACTORS.get(unit) - if factor is None: - raise AnsibleFilterError(f"memory_filters: unknown unit in '{v}'") - - return int(val * factor) - - -def _to_mb(v: str) -> int: - """Convert human-readable size to megabytes.""" - return max(0, _to_bytes(v) // (1024 * 1024)) - - -# ------------------------------------------------------ -# JVM-specific helpers -# ------------------------------------------------------ - - -def _svc(app_id: str) -> str: - """Resolve the internal service name for JVM-based applications.""" - return get_entity_name(app_id) - - -def _mem_limit_mb(apps: dict, app_id: str) -> int: - """Resolve mem_limit for the JVM service of the given application.""" - svc = _svc(app_id) - raw = get(apps, app_id, f"services.{svc}.mem_limit") - mb = _to_mb(raw) - - if mb <= 0: - raise AnsibleFilterError( - f"memory_filters: mem_limit for '{svc}' must be > 0 MB (got '{raw}')" - ) - return mb - - -def _mem_res_mb(apps: dict, app_id: str) -> int: - """Resolve mem_reservation for the JVM service of the given application.""" - svc = _svc(app_id) - raw = get(apps, app_id, f"services.{svc}.mem_reservation") - mb = _to_mb(raw) - - if mb <= 0: - raise AnsibleFilterError( - f"memory_filters: mem_reservation for '{svc}' must be > 0 MB (got '{raw}')" - ) - return mb - - -def jvm_max_mb(apps: dict, app_id: str) -> int: - """ - Compute recommended JVM Xmx in MB using: - Xmx = min( - floor(0.7 * mem_limit), - mem_limit - 1024, - 12288 - ) - with a lower bound of 1024 MB. - """ - limit_mb = _mem_limit_mb(apps, app_id) - c1 = (limit_mb * 7) // 10 - c2 = max(0, limit_mb - 1024) - c3 = 12288 - - return max(1024, min(c1, c2, c3)) - - -def jvm_min_mb(apps: dict, app_id: str) -> int: - """ - Compute recommended JVM Xms in MB using: - Xms = min( - floor(Xmx / 2), - mem_reservation, - Xmx - ) - with a lower bound of 512 MB. - """ - xmx = jvm_max_mb(apps, app_id) - res = _mem_res_mb(apps, app_id) - - return max(512, min(xmx // 2, res, xmx)) - - -# ------------------------------------------------------ -# Redis-specific helpers (always service name "redis") -# ------------------------------------------------------ - - -def _redis_mem_limit_mb(apps: dict, app_id: str, default_mb: int = 256) -> int: - """ - Resolve mem_limit for the Redis service of an application. - Unlike JVM-based services, Redis always uses the service name "redis". - - If no mem_limit is defined, fall back to default_mb. - """ - raw = get( - apps, - app_id, - "services.redis.mem_limit", - strict=False, - default=f"{default_mb}m", - ) - - mb = _to_mb(raw) - - if mb <= 0: - raise AnsibleFilterError( - f"memory_filters: mem_limit for 'redis' must be > 0 MB (got '{raw}')" - ) - - return mb - - -def redis_maxmemory_mb( - apps: dict, app_id: str, factor: float = 0.8, min_mb: int = 64 -) -> int: - """ - Compute recommended Redis `maxmemory` in MB. - - * factor: fraction of allowed memory used for Redis data (default 0.8) - * min_mb: minimum floor value (default 64 MB) - - maxmemory = max(min_mb, floor(factor * mem_limit)) - """ - limit_mb = _redis_mem_limit_mb(apps, app_id) - return max(min_mb, int(limit_mb * factor)) - - -# ------------------------------------------------------ -# Filter module -# ------------------------------------------------------ - - -class FilterModule: - def filters(self): - return { - "jvm_max_mb": jvm_max_mb, - "jvm_min_mb": jvm_min_mb, - "redis_maxmemory_mb": redis_maxmemory_mb, - } diff --git a/plugins/lookup/service_memory_mb.py b/plugins/lookup/service_memory_mb.py new file mode 100644 index 0000000000..bc7ab9975c --- /dev/null +++ b/plugins/lookup/service_memory_mb.py @@ -0,0 +1,149 @@ +"""Derive a memory parameter in MiB from the memory limit of a service's container. + + -Xmx{{ lookup('service_memory_mb', application_id, 'search', 0.25) }}m + memory_limit = {{ lookup('service_memory_mb', application_id, entity_name, 0.5) }}M + +The limit is resolved the way ``sys-svc-container`` resolves the container's own +``mem_limit``: ``services..mem_limit``, then the role's primary entity, +then ``RESOURCE_MEM_LIMIT``. ``share`` is the fraction of that limit the +parameter may claim, so a heap, a cache or a per-request limit follows the +container instead of a literal that drifts away from it. + +A sidecar that a provider role ships into other stacks passes ``provider``: + + --maxmemory {{ lookup('service_memory_mb', application_id, 'redis', 0.8, provider='svc-db-redis') }}mb + +An application that declares no ``mem_limit`` for that service lets its container +inherit the primary entity's, which is sized for the application and not for the +engine beside it. The result is then capped at the same share of the provider's +own limit. An application that declares the limit itself is not capped. + +Sizes are read like Docker reads them: ``k``, ``m`` and ``g`` are binary, a bare +number is bytes. The result is whole MiB, the unit ``-Xmxm``, PHP ``M``, +``memcached -m``, Redis ``mb`` and PostgreSQL ``MB`` all share. +""" + +from __future__ import annotations + +import re +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from plugins.filter.resource_filter import resource_filter +from utils.roles.applications.config import ( + AppConfigKeyError, + ConfigEntryNotSetError, + get, +) + +_SIZE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([bkmg]?)b?\s*$", re.IGNORECASE) +_FACTOR = {"": 1, "b": 1, "k": 1024, "m": 1024**2, "g": 1024**3} +_MEBIBYTE = 1024**2 +_HOST_DEFAULT = "RESOURCE_MEM_LIMIT" +_UNDECLARED = object() + + +def docker_bytes(size: Any) -> int: + """Return a Docker memory size in bytes. + + Args: + size: a size such as ``2g``, ``1.5g``, ``512m`` or a byte count. + + Raises: + AnsibleError: the size is not a number with an optional b/k/m/g unit. + """ + match = _SIZE.match(str(size)) + if match is None: + raise AnsibleError(f"lookup('service_memory_mb'): unreadable size {size!r}") + return int(float(match.group(1)) * _FACTOR[match.group(2).lower()]) + + +def share_mb(mem_limit: Any, share: Any) -> int: + """Return ``share`` of ``mem_limit`` in whole MiB. + + Args: + mem_limit: Docker size of the container limit, e.g. ``2g`` or ``512m``. + share: fraction of the limit, above 0 and at most 1. + + Raises: + AnsibleError: the share is no fraction in that range, the size is + unreadable, or the result is below 1 MiB. + """ + try: + fraction = float(share) + except (TypeError, ValueError) as exc: + raise AnsibleError( + f"lookup('service_memory_mb'): share {share!r} is not a number" + ) from exc + if not 0 < fraction <= 1: + raise AnsibleError( + f"lookup('service_memory_mb'): share {share!r} must be above 0 and at most 1" + ) + megabytes = int(docker_bytes(mem_limit) * fraction) // _MEBIBYTE + if megabytes < 1: + raise AnsibleError( + f"lookup('service_memory_mb'): {share!r} of {mem_limit!r} is below 1 MiB" + ) + return megabytes + + +class LookupModule(LookupBase): + """lookup('service_memory_mb', application_id, service_name, share[, provider=role])""" + + def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): + if len(terms) != 3: + raise AnsibleError( + "lookup('service_memory_mb', application_id, service_name, share) " + "expects exactly 3 positional terms." + ) + application_id, service_name, share = terms + unknown = sorted(set(kwargs) - {"provider"}) + if unknown: + raise AnsibleError( + f"lookup('service_memory_mb'): unknown option(s) {unknown}; " + "the only option is provider=" + ) + + templar = self._templar + variables = variables or templar.available_variables + applications = lookup_loader.get( + "applications", loader=self._loader, templar=templar + ).run([], variables=variables)[0] + + mem_limit = resource_filter( + applications, application_id, "mem_limit", service_name, _UNDECLARED + ) + if mem_limit is _UNDECLARED: + if _HOST_DEFAULT not in variables: + raise AnsibleError( + f"lookup('service_memory_mb'): '{application_id}' declares no " + f"mem_limit for '{service_name}' and {_HOST_DEFAULT} is unset" + ) + mem_limit = templar.template(variables[_HOST_DEFAULT]) + megabytes = share_mb(mem_limit, share) + + if "provider" in kwargs: + if not kwargs["provider"] or not isinstance(kwargs["provider"], str): + raise AnsibleError( + "lookup('service_memory_mb'): provider must name a role" + ) + own = f"services.{service_name}.mem_limit" + try: + ceiling = get(applications, kwargs["provider"], own, False, _UNDECLARED) + inherited = ( + get(applications, application_id, own, False, _UNDECLARED) + is _UNDECLARED + ) + except (AppConfigKeyError, ConfigEntryNotSetError) as exc: + raise AnsibleError(f"lookup('service_memory_mb'): {exc}") from exc + if ceiling is _UNDECLARED: + raise AnsibleError( + f"lookup('service_memory_mb'): provider {kwargs['provider']!r} " + f"declares no mem_limit for '{service_name}'" + ) + if inherited: + megabytes = min(megabytes, share_mb(ceiling, share)) + return [megabytes] diff --git a/requirements/requirements.galaxy.yml b/requirements/requirements.galaxy.yml index 0a1db299fb..ef98c31538 100644 --- a/requirements/requirements.galaxy.yml +++ b/requirements/requirements.galaxy.yml @@ -7,10 +7,10 @@ collections: - name: kewlfft.aur version: 0.13.0 - name: community.general - version: 13.4.0 + version: 13.5.0 - name: community.docker version: 5.4.0 - name: community.library_inventory_filtering_v1 version: 1.1.5 - name: hetzner.hcloud - version: 7.1.0 + version: 7.2.0 diff --git a/requirements/requirements.git.yml b/requirements/requirements.git.yml index eef6cbd713..58808ee14c 100644 --- a/requirements/requirements.git.yml +++ b/requirements/requirements.git.yml @@ -18,7 +18,7 @@ collections: - name: community.general source: https://github.com/ansible-collections/community.general.git type: git - version: 13.4.0 + version: 13.5.0 - name: community.docker source: https://github.com/ansible-collections/community.docker.git @@ -33,4 +33,4 @@ collections: - name: hetzner.hcloud source: https://github.com/ansible-collections/hetzner.hcloud.git type: git - version: 7.1.0 + version: 7.2.0 diff --git a/roles/svc-ai-mcp-adapter/README.md b/roles/svc-ai-mcp-adapter/README.md index cfd9b2bf62..2d0d4d4bc3 100644 --- a/roles/svc-ai-mcp-adapter/README.md +++ b/roles/svc-ai-mcp-adapter/README.md @@ -26,6 +26,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - **Client-facing authentication:** The adapter issues its own bearer. The upstream credential authenticates the adapter to the provider and says nothing about who called the adapter, which is the gap the project-owned MCP sidecars leave open. - **Allowlist on `tools/call`:** Filtering only `tools/list` would leave every unlisted operation callable by name. - **Read-only by default:** A non-`GET`/`HEAD` operation is refused unless `mutating_tools_enabled` is explicitly true. +- **Path arguments stay in their segment:** A value that fills a `{placeholder}` of the contracted path is percent-encoded, and an empty value or one made only of dots is refused, so a call cannot resolve to a path the contract does not name. - **Enforced ceilings:** Request size, response size, timeout, concurrency, page size and result count come from the contract and are applied, not merely declared. - **Bounded ranges:** A tool whose schema declares `start`, `end` and `step` has its point count checked against `result_items` and is refused with the smallest step that fits, so the upstream never scans a range whose result the adapter would discard. - **Fail-closed on drift:** A tool contract whose hash no longer matches its pinned `schema_sha256` refuses to start. diff --git a/roles/svc-ai-mcp-adapter/files/python/policy.py b/roles/svc-ai-mcp-adapter/files/python/policy.py index fc4ed18be2..b527da2b6c 100644 --- a/roles/svc-ai-mcp-adapter/files/python/policy.py +++ b/roles/svc-ai-mcp-adapter/files/python/policy.py @@ -47,6 +47,7 @@ DENY_TOO_MANY_REQUESTS = "too_many_concurrent_requests" DENY_UNKNOWN_ARGUMENT = "undeclared_argument" DENY_MISSING_ARGUMENT = "missing_required_argument" DENY_RANGE_TOO_WIDE = "range_too_wide" +DENY_PATH_ARGUMENT = "path_argument_not_a_segment" RANGE_ARGUMENTS = ("start", "end", "step") @@ -189,6 +190,17 @@ def assert_arguments( raise PermissionError(f"{DENY_MISSING_ARGUMENT}: {name!r} requires {missing}") +def assert_path_arguments( + spec: Mapping[str, Any], name: str, arguments: Mapping[str, Any] | None +) -> None: + path = str(spec["path"]) + for key, value in (arguments or {}).items(): + if "{" + key + "}" in path and not str(value).strip("."): + raise PermissionError( + f"{DENY_PATH_ARGUMENT}: {name!r} takes no {str(value)!r} as {key!r}" + ) + + def parse_instant(value: Any) -> float: """Return a range boundary in unix seconds. @@ -217,10 +229,14 @@ def parse_duration(value: Any) -> float: return float(text) except ValueError: pass - parts = re.findall(r"(\d+)(ms|[smhdwy])", text) - if not parts or "".join(n + u for n, u in parts) != text: + *tokens, rest = re.split(r"(ms|[smhdwy])", text) + numbers, units = tokens[::2], tokens[1::2] + if rest or not numbers or not all(number.isdecimal() for number in numbers): raise ValueError(f"not a duration: {text!r}") - return sum(int(n) * DURATION_UNITS[u] for n, u in parts) + return sum( + int(number) * DURATION_UNITS[unit] + for number, unit in zip(numbers, units, strict=True) + ) def assert_range( @@ -341,6 +357,7 @@ def authorize_call( ) assert_arguments(spec, name, arguments) + assert_path_arguments(spec, name, arguments) assert_range(spec, name, arguments, contract["limits"]["result_items"]) return method, str(spec["path"]) diff --git a/roles/svc-ai-ollama/meta/services.yml b/roles/svc-ai-ollama/meta/services.yml index 676af6a455..b60dc775cc 100644 --- a/roles/svc-ai-ollama/meta/services.yml +++ b/roles/svc-ai-ollama/meta/services.yml @@ -13,7 +13,7 @@ ollama: backup: no_stop_required: true image: ollama/ollama - version: 0.35.1 + version: 0.40.0 name: ollama min_storage: 3473MB cpus: "4.0" diff --git a/roles/svc-db-elasticsearch/meta/services.yml b/roles/svc-db-elasticsearch/meta/services.yml index 6f13b566e6..d40ab5fa1d 100644 --- a/roles/svc-db-elasticsearch/meta/services.yml +++ b/roles/svc-db-elasticsearch/meta/services.yml @@ -12,7 +12,7 @@ elasticsearch: bond: 1 image: elasticsearch name: elasticsearch - version: "9.5.3" + version: "9.5.5" min_storage: 1066MB backup: database_routine: true diff --git a/roles/svc-db-elasticsearch/templates/env.j2 b/roles/svc-db-elasticsearch/templates/env.j2 index 40b5ca2cc8..e3160aa57f 100644 --- a/roles/svc-db-elasticsearch/templates/env.j2 +++ b/roles/svc-db-elasticsearch/templates/env.j2 @@ -6,4 +6,4 @@ xpack.security.enabled=true xpack.security.http.ssl.enabled=false xpack.security.transport.ssl.enabled=false bootstrap.memory_lock=true -ES_JAVA_OPTS=-Xms1g -Xmx1g +ES_JAVA_OPTS=-Xms{{ ELASTICSEARCH_HEAP_MB }}m -Xmx{{ ELASTICSEARCH_HEAP_MB }}m diff --git a/roles/svc-db-elasticsearch/vars/main.yml b/roles/svc-db-elasticsearch/vars/main.yml index af2430a228..39e44dc3c0 100644 --- a/roles/svc-db-elasticsearch/vars/main.yml +++ b/roles/svc-db-elasticsearch/vars/main.yml @@ -10,6 +10,7 @@ ELASTICSEARCH_PASSWORD: "{{ lookup('config', application_id, 'secrets.credential ELASTICSEARCH_EXPOSE_LOCAL: true ELASTICSEARCH_LOCAL_HOST: "127.0.0.1" ELASTICSEARCH_INTERNAL_PORT: "{{ lookup('config', application_id, 'services.elasticsearch.ports.internal.elasticsearch') }}" +ELASTICSEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, entity_name, 0.25) }}" ELASTICSEARCH_RETRIES: 5 ELASTICSEARCH_DELAY: 2 ELASTICSEARCH_API_BASE: "http://{{ ELASTICSEARCH_LOCAL_HOST }}:{{ ELASTICSEARCH_INTERNAL_PORT }}" diff --git a/roles/svc-db-memcached/templates/compose.yml.j2 b/roles/svc-db-memcached/templates/compose.yml.j2 index 1b3883ec84..687ed7e2b7 100644 --- a/roles/svc-db-memcached/templates/compose.yml.j2 +++ b/roles/svc-db-memcached/templates/compose.yml.j2 @@ -3,10 +3,7 @@ {{ service_name }}: {{ lookup('compose_only', 'container_name', MEMCACHED_CONTAINER) }} {{ lookup('container_image', application_id, 'memcached') }} - command: - - "memcached" - - "-m" - - "{{ MEMCACHED_MEMORY_LIMIT_MB }}" + command: ["memcached", "-m", "{{ MEMCACHED_MEMORY_LIMIT_MB }}"] {% include 'roles/sys-svc-container/templates/base.yml.j2' %} {% if MEMCACHED_EXPOSE_LOCAL %} diff --git a/roles/svc-db-memcached/templates/service.yml.j2 b/roles/svc-db-memcached/templates/service.yml.j2 index cf91ec5014..257b24f783 100644 --- a/roles/svc-db-memcached/templates/service.yml.j2 +++ b/roles/svc-db-memcached/templates/service.yml.j2 @@ -5,10 +5,7 @@ {{ lookup('compose_restart') }} logging: driver: journald - command: - - memcached - - -m - - "64" + command: ["memcached", "-m", "{{ lookup('service_memory_mb', application_id, 'memcached', 0.25, provider='svc-db-memcached') }}"] # nocheck: container-healthcheck-literal probes every second, so the SPOT's 5s start cadence would report healthy later than this block already does healthcheck: # nocheck: healthcheck-timing-override, healthcheck-start-period-covers-interval a swarm-init gate that must clear in seconds, so it runs without a start window rather than inside one test: ["CMD-SHELL", "printf 'version\\r\\n' | nc -w 1 127.0.0.1 11211 | grep -q VERSION"] diff --git a/roles/svc-db-memcached/vars/main.yml b/roles/svc-db-memcached/vars/main.yml index 3066f45915..9294151ce2 100644 --- a/roles/svc-db-memcached/vars/main.yml +++ b/roles/svc-db-memcached/vars/main.yml @@ -10,6 +10,6 @@ MEMCACHED_EXPOSE_LOCAL: true MEMCACHED_LOCAL_HOST: "127.0.0.1" MEMCACHED_RETRIES: 5 MEMCACHED_DELAY: 5 -MEMCACHED_MEMORY_LIMIT_MB: 192 +MEMCACHED_MEMORY_LIMIT_MB: "{{ lookup('service_memory_mb', application_id, entity_name, 0.75) }}" MEMCACHED_EXEC_SHELL: "container exec {{ MEMCACHED_CONTAINER_ADDRESS }} sh -lc" MEMCACHED_PROBE: "printf \"version\\r\\n\" | nc -w 1 {{ MEMCACHED_LOCAL_HOST }} 11211 | grep -q VERSION" diff --git a/roles/svc-db-postgres/vars/main.yml b/roles/svc-db-postgres/vars/main.yml index ab4253a155..b1ff5e62c5 100644 --- a/roles/svc-db-postgres/vars/main.yml +++ b/roles/svc-db-postgres/vars/main.yml @@ -15,3 +15,6 @@ POSTGRES_EXPOSE_LOCAL: true POSTGRES_LOCAL_HOST: "127.0.0.1" POSTGRES_LIBRARIES: "{{ lookup('postgres_libraries', lookup('service_extensions', 'postgres').values() | sum(start=[]) | unique | list) }}" POSTGRES_RETRIES: 5 +POSTGRES_SHARED_BUFFERS: "{{ lookup('service_memory_mb', application_id, entity_name, 0.25) }}MB" +POSTGRES_WORK_MEM: "{{ [ (lookup('service_memory_mb', application_id, entity_name, 0.5) | int) // ([ POSTGRES_MAX_CONNECTIONS | int, 1 ] | max), 1 ] | max }}MB" +POSTGRES_MAINTENANCE_WORK_MEM: "{{ [ lookup('service_memory_mb', application_id, entity_name, 0.05) | int, 64 ] | max }}MB" diff --git a/roles/svc-db-qdrant/meta/services.yml b/roles/svc-db-qdrant/meta/services.yml index 50a5a5fb7c..7b363b9248 100644 --- a/roles/svc-db-qdrant/meta/services.yml +++ b/roles/svc-db-qdrant/meta/services.yml @@ -12,7 +12,7 @@ qdrant: bond: 1 image: qdrant/qdrant name: qdrant - version: v1.19.1 + version: v1.19.2 min_storage: 270MB backup: database_routine: true diff --git a/roles/svc-db-redis/README.md b/roles/svc-db-redis/README.md index 6a4f203290..70b1588070 100644 --- a/roles/svc-db-redis/README.md +++ b/roles/svc-db-redis/README.md @@ -18,7 +18,7 @@ The central stack (`templates/compose.yml.j2`) runs `redis:alpine` with: Per-consumer provisioning (`tasks/01_init.yml`) runs with `application_id=svc-db-redis` and `database_consumer_id=`; it resolves the consumer's username, password and key-prefix via `lookup('engine', 'redis', , ...)` and reconciles an idempotent `ACL SETUSER` restricted to `~{entity}:*`. The ACL users are recreated by the consumer's `01_init` on every deploy, so a container restart that drops the in-memory ACL set is healed on the next run. -The embedded snippet (`templates/service.yml.j2`) keeps the previous single-host behaviour: an unauthenticated in-memory Redis attached to the consumer stack's default network. +The embedded snippet (`templates/service.yml.j2`) keeps the previous single-host behaviour: an unauthenticated in-memory Redis attached to the consumer stack's default network. Its `maxmemory` is 80 % of the consumer's `services.redis.mem_limit`; a consumer that declares none gets 80 % of the limit its container inherits, at most 80 % of this role's own `mem_limit`. ## Cosmos diff --git a/roles/svc-db-redis/templates/compose.yml.j2 b/roles/svc-db-redis/templates/compose.yml.j2 index efdbf2ef51..ce32003147 100644 --- a/roles/svc-db-redis/templates/compose.yml.j2 +++ b/roles/svc-db-redis/templates/compose.yml.j2 @@ -10,7 +10,7 @@ exec redis-server --requirepass {{ REDIS_PASSWORD | quote }} --appendonly yes - --maxmemory {{ lookup('applications') | redis_maxmemory_mb(application_id, 0.8, RESOURCE_MEM_LIMIT | int) }}mb + --maxmemory {{ lookup('service_memory_mb', application_id, service_name, 0.8) }}mb --maxmemory-policy allkeys-lru {% include 'roles/sys-svc-container/templates/base.yml.j2' %} diff --git a/roles/svc-db-redis/templates/service.yml.j2 b/roles/svc-db-redis/templates/service.yml.j2 index e678ee590e..8bc3775856 100644 --- a/roles/svc-db-redis/templates/service.yml.j2 +++ b/roles/svc-db-redis/templates/service.yml.j2 @@ -13,7 +13,7 @@ - "no" - --save - "" - - --maxmemory {{ lookup('applications') | redis_maxmemory_mb(application_id, 0.8, RESOURCE_MEM_LIMIT | int ) }}mb + - --maxmemory {{ lookup('service_memory_mb', application_id, 'redis', 0.8, provider='svc-db-redis') }}mb - --maxmemory-policy - "allkeys-lru" # nocheck: container-healthcheck-literal probes every second, so the SPOT's 5s start cadence would report healthy later than this block already does diff --git a/roles/svc-net-tor/files/shell/entrypoint.sh b/roles/svc-net-tor/files/shell/entrypoint.sh index ccf615aad1..27fe61bc7d 100644 --- a/roles/svc-net-tor/files/shell/entrypoint.sh +++ b/roles/svc-net-tor/files/shell/entrypoint.sh @@ -21,6 +21,9 @@ if [ "${TOR_FLAVOR}" = "chutney" ]; then CHUTNEY_LISTEN_ADDRESS=127.0.0.1 \ ./chutney init --net "${net}" ./chutney configure + for torrc in net/nodes/*/torrc; do + echo "NumCPUs 1" >>"${torrc}" + done ./chutney start ./chutney wait_for_bootstrap diff --git a/roles/svc-net-tor/files/test/test.sh b/roles/svc-net-tor/files/test/test.sh index 68677e034b..f3a8989df7 100755 --- a/roles/svc-net-tor/files/test/test.sh +++ b/roles/svc-net-tor/files/test/test.sh @@ -18,6 +18,8 @@ # SLEEP_SECONDS wait between attempts # TOR_DNSMASQ_CONF the dnsmasq drop-in path; its directory is scanned for # upstreams when a probe fails +# TOR_CONTAINER address of the tor container +# TOR_FLAVOR public or chutney set -uo pipefail @@ -26,6 +28,8 @@ NGINX_SERVERS_DIR="${NGINX_SERVERS_DIR:?pass NGINX_SERVERS_DIR as env (the deplo RETRIES="${RETRIES:?pass RETRIES as env (attempts per domain, from svc-net-tor test.env)}" SLEEP_SECONDS="${SLEEP_SECONDS:?pass SLEEP_SECONDS as env (wait between attempts, from svc-net-tor test.env)}" TOR_DNSMASQ_CONF="${TOR_DNSMASQ_CONF:?pass TOR_DNSMASQ_CONF as env (the dnsmasq drop-in path, from svc-net-tor vars)}" +TOR_CONTAINER="${TOR_CONTAINER:?pass TOR_CONTAINER as env (address of the tor container, from svc-net-tor test.env)}" +TOR_FLAVOR="${TOR_FLAVOR:?pass TOR_FLAVOR as env (public or chutney, from svc-net-tor test.env)}" discover_domains() { find "${NGINX_SERVERS_DIR}/http" "${NGINX_SERVERS_DIR}/https" \ @@ -102,4 +106,19 @@ echo "[INFO] ${#domains[@]} probed, ${failed} failed" "$(dirname "${BASH_SOURCE[0]}")/onion_ports.py" || failed=$((failed + 1)) +if [[ "${TOR_FLAVOR}" == "chutney" ]]; then + status=0 + workers="$(container exec "${TOR_CONTAINER}" sh -c 'grep -cH "^NumCPUs 1$" /opt/chutney/net/nodes/*/torrc')" || status=$? + unbounded="$(sed -n 's/:0$//p' <<<"${workers}")" + if [[ "${status}" -gt 1 || -z "${workers}" ]]; then + echo "[FAIL] cannot read the chutney node torrcs in ${TOR_CONTAINER}" + failed=$((failed + 1)) + elif [[ -n "${unbounded}" ]]; then + echo "[FAIL] chutney nodes without NumCPUs 1 start one worker per host core: ${unbounded//$'\n'/ }" + failed=$((failed + 1)) + else + echo "[OK] every chutney node runs one worker" + fi +fi + [[ "${failed}" -eq 0 ]] diff --git a/roles/svc-net-tor/templates/test.env.j2 b/roles/svc-net-tor/templates/test.env.j2 index 6e0bec9054..51288356b2 100644 --- a/roles/svc-net-tor/templates/test.env.j2 +++ b/roles/svc-net-tor/templates/test.env.j2 @@ -5,5 +5,7 @@ ONION_PORT_RETRIES=2 ONION_PORT_TIMEOUT=60 RETRIES=5 SLEEP_SECONDS=10 +TOR_CONTAINER={{ lookup('container_address', application_id, 'tor') }} TOR_DNSMASQ_CONF={{ TOR_DNSMASQ_CONF }} +TOR_FLAVOR={{ TOR_FLAVOR }} TOR_SOCKS={{ lookup('tor_socks') }} diff --git a/roles/test-e2e-cli/files/shared/mcp/contract.py b/roles/test-e2e-cli/files/shared/mcp/contract.py index 4af0b34781..f7997a1f7a 100644 --- a/roles/test-e2e-cli/files/shared/mcp/contract.py +++ b/roles/test-e2e-cli/files/shared/mcp/contract.py @@ -45,6 +45,7 @@ Environment: from __future__ import annotations +import contextlib import json import os import queue @@ -76,7 +77,7 @@ SESSION_TIMEOUT = 20 WRONG_CREDENTIAL = "Bearer " + "0" * 40 SESSION_HEADER = "Mcp-Session-Id" -SESSION = {"id": ""} +SESSION = {"id": "", "protocol": ""} def unguarded_url(): @@ -120,6 +121,8 @@ def rpc(method, params=None, authorization=None, url=None, notification=False): request.add_header("Authorization", authorization) if SESSION["id"]: request.add_header(SESSION_HEADER, SESSION["id"]) + if SESSION["protocol"]: + request.add_header("MCP-Protocol-Version", SESSION["protocol"]) try: with urllib.request.urlopen(request, timeout=TIMEOUT) as response: # noqa: S310 fixed internal http origin session = response.headers.get(SESSION_HEADER) @@ -320,21 +323,20 @@ class SseSession: self.content_type = self._response.headers.get("Content-Type", "") event = None try: - for raw in self._response: - line = raw.decode(errors="replace").rstrip("\r\n") - if line.startswith("event:"): - event = line.split(":", 1)[1].strip() - elif line.startswith("data:"): - data = line.split(":", 1)[1].strip() - if event == "endpoint": - self.endpoint = urllib.parse.urljoin(self.url, data) - self._announced.set() - else: - self._messages.put(data) - elif not line: - event = None - except (OSError, ValueError): - pass + with contextlib.suppress(OSError, ValueError): + for raw in self._response: + line = raw.decode(errors="replace").rstrip("\r\n") + if line.startswith("event:"): + event = line.split(":", 1)[1].strip() + elif line.startswith("data:"): + data = line.split(":", 1)[1].strip() + if event == "endpoint": + self.endpoint = urllib.parse.urljoin(self.url, data) + self._announced.set() + else: + self._messages.put(data) + elif not line: + event = None finally: self._announced.set() @@ -463,6 +465,8 @@ def main(): if status != 200: reject(f"authenticated initialize answered {status}: {body[:200]}") reject_error("authenticated initialize", rpc_error(body)) + result = json.loads(body).get("result") or {} + SESSION["protocol"] = result.get("protocolVersion", "") rpc("notifications/initialized", authorization=AUTH, notification=True) diff --git a/roles/test-e2e-playwright/files/playwright.config.js b/roles/test-e2e-playwright/files/playwright.config.js index 0587e22fcb..34ea0b334f 100644 --- a/roles/test-e2e-playwright/files/playwright.config.js +++ b/roles/test-e2e-playwright/files/playwright.config.js @@ -48,7 +48,10 @@ module.exports = defineConfig({ expect: { timeout: requiredTimeout("PLAYWRIGHT_EXPECT_TIMEOUT") }, ...(globalTimeout > 0 ? { globalTimeout } : {}), retries: 2, - workers: Number(process.env.PLAYWRIGHT_WORKERS) || 1, + workers: Math.min( + Number(process.env.PLAYWRIGHT_WORKERS) || 1, + Number(process.env.PLAYWRIGHT_MAX_WORKERS) || Infinity + ), fullyParallel: (process.env.PLAYWRIGHT_FULLY_PARALLEL || "").toLowerCase() === "true", outputDir: "/reports/test-results", reporter: [ diff --git a/roles/web-app-confluence/README.md b/roles/web-app-confluence/README.md index 390ac319d6..d92f4d1a65 100644 --- a/roles/web-app-confluence/README.md +++ b/roles/web-app-confluence/README.md @@ -6,7 +6,7 @@ Confluence is Atlassian’s enterprise wiki and collaboration platform. This rol ## Overview -The role builds a minimal custom image on top of the official Confluence image, prepares persistent volumes, and exposes the app behind your reverse proxy. Configuration is driven by variables (image, version, volumes, domains, OIDC). JVM heap sizing is auto-derived from host RAM with safe caps to avoid `Xms > Xmx`. +The role builds a minimal custom image on top of the official Confluence image, prepares persistent volumes, and exposes the app behind your reverse proxy. Configuration is driven by variables (image, version, volumes, domains, OIDC). JVM heap sizing follows the container's `mem_limit`: `JVM_MAXIMUM_MEMORY` is 70 % of it and `JVM_MINIMUM_MEMORY` 35 %. ## Cosmos @@ -60,7 +60,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( * **Reverse-Proxy Ready:** Sets `ATL_PROXY_NAME/PORT/SCHEME/SECURE` so Confluence generates correct external URLs behind HTTPS. * **OIDC SSO (Optional):** Pre-templated vars for issuer, client, scopes, JWKS; compatible with Atlassian DC SSO/OIDC marketplace apps. * **Central Database:** PostgreSQL integration (local or central DB) with bootstrap credentials from role vars. -* **JVM Auto-Tuning:** `JVM_MINIMUM_MEMORY` / `JVM_MAXIMUM_MEMORY` computed from host memory with upper bounds. +* **JVM Auto-Tuning:** `JVM_MINIMUM_MEMORY` / `JVM_MAXIMUM_MEMORY` are 35 % and 70 % of the service `mem_limit`. * **Health Checks:** Curl-based container healthcheck for early failure detection. * **CSP & Canonical Domains:** Hooks into platform CSP/SSL/domain management to keep policies strict and URLs stable. * **Backup Friendly:** Data isolated under `{{ CONFLUENCE_HOME }}`. diff --git a/roles/web-app-confluence/vars/main.yml b/roles/web-app-confluence/vars/main.yml index 2ce263f096..180441ce0b 100644 --- a/roles/web-app-confluence/vars/main.yml +++ b/roles/web-app-confluence/vars/main.yml @@ -25,7 +25,7 @@ CONFLUENCE_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_na CONFLUENCE_IMAGE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.image') }}" CONFLUENCE_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.name') }}" -CONFLUENCE_JVM_MAX: "{{ lookup('applications') | jvm_max_mb(application_id) }}m" -CONFLUENCE_JVM_MIN: "{{ lookup('applications') | jvm_min_mb(application_id) }}m" +CONFLUENCE_JVM_MAX: "{{ lookup('service_memory_mb', application_id, entity_name, 0.7) }}m" +CONFLUENCE_JVM_MIN: "{{ lookup('service_memory_mb', application_id, entity_name, 0.35) }}m" CONFLUENCE_TRUST_STORE_ENABLED: "{{ lookup('config', application_id, 'services.confluence.truststore_enabled') }}" diff --git a/roles/web-app-discourse/templates/config.yml.j2 b/roles/web-app-discourse/templates/config.yml.j2 index 884d949e89..c72c6c1adc 100644 --- a/roles/web-app-discourse/templates/config.yml.j2 +++ b/roles/web-app-discourse/templates/config.yml.j2 @@ -22,7 +22,7 @@ params: ## Set db_shared_buffers to a max of 25% of the total memory. ## will be set automatically by bootstrap based on detected RAM, or you can override - db_shared_buffers: "4096MB" + db_shared_buffers: "{{ lookup('service_memory_mb', application_id, 'discourse', 0.25) }}MB" ## can improve sorting performance, but adds memory usage per-connection #db_work_mem: "40MB" diff --git a/roles/web-app-erpnext/meta/services.yml b/roles/web-app-erpnext/meta/services.yml index be86d8e07e..cc24f369e8 100644 --- a/roles/web-app-erpnext/meta/services.yml +++ b/roles/web-app-erpnext/meta/services.yml @@ -65,7 +65,7 @@ erpnext: enabled: true shared: true image: frappe/erpnext - version: "v16.37.0" + version: "v16.50.0" name: erpnext min_storage: 1017MB ports: diff --git a/roles/web-app-gitea/meta/services.yml b/roles/web-app-gitea/meta/services.yml index bf0b9f8563..ac35951047 100644 --- a/roles/web-app-gitea/meta/services.yml +++ b/roles/web-app-gitea/meta/services.yml @@ -49,7 +49,7 @@ gitea: shared: true provides: gitea image: gitea/gitea - version: 28.0.0 + version: 28.1.0 replicas: 1 # nocheck: single-replica single-writer app state on swarm-shared NFS; concurrent multi-node writers corrupt app.ini min_storage: 270MB backup: @@ -112,11 +112,18 @@ giteamcpupstream: enabled: "{{ lookup('config', 'web-app-gitea', 'mcp.enabled') | bool }}" shared: false image: docker.gitea.com/gitea-mcp-server - version: "1.6.0" + version: "1.8.0" update: type: registry_tags image: docker.gitea.com/gitea-mcp-server name: gitea-mcp + healthcheck: + test: + - "CMD" + - "/app/gitea-mcp" + - "-healthcheck" + - "--port" + - "{{ lookup('config', 'web-app-gitea', 'services.giteamcpupstream.ports.internal.http') | string }}" cpus: 0.25 mem_reservation: 0.1g mem_limit: 0.25g diff --git a/roles/web-app-gitea/templates/compose.yml.j2 b/roles/web-app-gitea/templates/compose.yml.j2 index 2e56345b14..8ebf840c08 100644 --- a/roles/web-app-gitea/templates/compose.yml.j2 +++ b/roles/web-app-gitea/templates/compose.yml.j2 @@ -28,6 +28,7 @@ GITEA_HOST: "{{ GITEA_MCP_UPSTREAM_URL }}" GITEA_SCOPES: "{{ GITEA_MCP_TOOL_SCOPES }}" GITEA_READONLY: "true" + {{ lookup('container_healthcheck', service_name) | indent(4) }} networks: # nocheck: networks-literal the sidecar authenticates nobody, so it joins the private upstream net and nothing else {{ GITEA_MCP_UPSTREAM_NETWORK }}: {{ lookup('depends_on', {'gitea': 'service_healthy'}) }} @@ -55,6 +56,7 @@ ADAPTER_PORT: "{{ GITEA_MCP_PORT }}" expose: - "{{ GITEA_MCP_PORT }}" + {{ lookup('depends_on', {GITEA_MCP_SIDECAR_SERVICE_KEY: 'service_healthy'}) }} {{ lookup('container_healthcheck', 'giteamcp') | indent(4) }} {{ lookup('container_networks', own_network_only=True, provider_self_alias=False) | indent(4) }} {{ GITEA_MCP_UPSTREAM_NETWORK }}: diff --git a/roles/web-app-gitea/vars/main.yml b/roles/web-app-gitea/vars/main.yml index 50fb563bdf..7b36c9e8e4 100644 --- a/roles/web-app-gitea/vars/main.yml +++ b/roles/web-app-gitea/vars/main.yml @@ -62,7 +62,7 @@ GITEA_MCP_COMMAND: - "-t" - "http" - "--port" - - "{{ GITEA_MCP_PORT | string }}" + - "{{ GITEA_MCP_SIDECAR_PORT | string }}" - "-r" GITEA_MCP_INITIALIZE_PAYLOAD: jsonrpc: "2.0" diff --git a/roles/web-app-hugo/Administration.md b/roles/web-app-hugo/Administration.md index aa4b507021..e03fbf1527 100644 --- a/roles/web-app-hugo/Administration.md +++ b/roles/web-app-hugo/Administration.md @@ -42,9 +42,9 @@ make compose-exec cmd="docker compose -f /opt/docker/web-app-hugo/docker-compose Common causes: - **`hugo` reports unknown content / module errors**: the upstream repository moved a directory or a Hugo Module. Pin to a known-good tag in `source_version`. -- **`hugo` reports template execution errors**: the theme's templates are incompatible with the bundled Hugo binary. Bump `services.hugo.builder_version` (e.g. to a newer `exts-` tag) or pin the source repo to a tag known to build with the current Hugo. +- **`hugo` reports template execution errors**: the theme's templates are incompatible with the bundled Hugo binary. Bump `services.hugo.builder_version` (e.g. to a newer `v` tag) or pin the source repo to a tag known to build with the current Hugo. - **Module fetch fails (`go.mod` resolution)**: Hugo modules pull from `proxy.golang.org`. Network egress to that host must be allowed by the local firewall / proxy. ## Rotating the Hugo binary -To upgrade the extended Hugo binary independently of the content repo, edit `services.hugo.builder_version` in `meta/services.yml` (e.g. `exts-0.149.0`). The change invalidates only the builder layer, not the cloned repo, so the next `compose build` reuses the same content but with the new binary. +To upgrade the extended Hugo binary independently of the content repo, edit `services.hugo.builder_version` in `meta/services.yml` (e.g. `v0.166.0`). The change invalidates only the builder layer, not the cloned repo, so the next `compose build` reuses the same content but with the new binary. diff --git a/roles/web-app-hugo/README.md b/roles/web-app-hugo/README.md index f40499e847..9d3a9390a5 100644 --- a/roles/web-app-hugo/README.md +++ b/roles/web-app-hugo/README.md @@ -8,7 +8,7 @@ The role uses a multi-stage Dockerfile: -1. **Builder stage:** pinned `hugomods/hugo:exts-` (extended Hugo) clones the configured content repository and runs `hugo --minify -e -b ` to render the site to `/public`. +1. **Builder stage:** pinned `ghcr.io/gohugoio/hugo:v` (the official extended Hugo image) clones the configured content repository and runs `hugo --minify -e -b ` to render the site to `/public`. 2. **Serve stage:** pinned `nginx:-alpine` ships the rendered `/public` from the builder stage as `/usr/share/nginx/html`. `compose build` re-bakes the static output whenever the cloned content changes, so deploys are content-driven without any runtime build step. @@ -96,13 +96,7 @@ docker run --rm -it \ ## Configuration -The default configuration in `meta/services.yml` builds the Hugo documentation: - -```yaml -hugo: - source_repository: https://github.com/gohugoio/hugoDocs.git - source_version: v0.148.0 -``` +The default configuration in `meta/services.yml` builds the Hugo documentation from `https://github.com/gohugoio/hugoDocs.git` at the tag pinned as `services.hugo.source_version`. To host your own Hugo site, override `services.hugo.source_repository` and `services.hugo.source_version` in your inventory. Example: @@ -125,7 +119,7 @@ V1 supports **exactly one canonical domain** per role deploy. The play asserts t - [Hugo official site](https://gohugo.io/) - [Hugo documentation source: gohugoio/hugoDocs](https://github.com/gohugoio/hugoDocs) -- [hugomods/hugo Docker images](https://hub.docker.com/r/hugomods/hugo) +- [Official Hugo container image](https://github.com/gohugoio/hugo/pkgs/container/hugo) ## Persona contract opt-outs diff --git a/roles/web-app-hugo/files/Dockerfile b/roles/web-app-hugo/files/Dockerfile index b610e36e1d..a6ed6eeb13 100644 --- a/roles/web-app-hugo/files/Dockerfile +++ b/roles/web-app-hugo/files/Dockerfile @@ -15,10 +15,13 @@ ARG HUGO_BASE_URL ARG HUGO_ENVIRONMENT ARG HUGO_MINIFY +USER root +RUN install -d -o hugo -g hugo /src /public +USER hugo:hugo + WORKDIR /src -COPY ./services/repository/ /src/ +COPY --chown=hugo:hugo ./services/repository/ /src/ -RUN apk add --no-cache nodejs npm RUN set -eu; \ if [ -f package.json ]; then \ npm install --no-audit --no-fund --no-progress; \ diff --git a/roles/web-app-hugo/meta/services.yml b/roles/web-app-hugo/meta/services.yml index 836b451aa7..f2b70dadc4 100644 --- a/roles/web-app-hugo/meta/services.yml +++ b/roles/web-app-hugo/meta/services.yml @@ -34,15 +34,15 @@ hugo: image: nginx version: 1.31-alpine custom: true - builder_image: hugomods/hugo - builder_version: exts-0.148.0 + builder_image: ghcr.io/gohugoio/hugo + builder_version: v0.167.0 source_repository: https://github.com/gohugoio/hugoDocs.git - source_version: v0.148.0 + source_version: v0.165.0 update: - key: builder_version type: registry_tags - image: hugomods/hugo - match: "exts-" + image: ghcr.io/gohugoio/hugo + match: "v" - key: source_version type: git_tags repository: https://github.com/gohugoio/hugoDocs.git diff --git a/roles/web-app-jira/README.md b/roles/web-app-jira/README.md index 0614a6a212..552a6756be 100644 --- a/roles/web-app-jira/README.md +++ b/roles/web-app-jira/README.md @@ -6,7 +6,7 @@ ## Overview -The role builds a lean custom image on top of the official Jira Software image, provisions persistent volumes, and exposes the app behind your reverse proxy. Variables control image/version/volumes/domains/SSO. JVM heap sizing is auto-derived from host RAM with safe caps to prevent `Xms > Xmx`. +The role builds a lean custom image on top of the official Jira Software image, provisions persistent volumes, and exposes the app behind your reverse proxy. Variables control image/version/volumes/domains/SSO. JVM heap sizing follows the container's `mem_limit`: `JVM_MAXIMUM_MEMORY` is 70 % of it and `JVM_MINIMUM_MEMORY` 35 %. ## Cosmos @@ -60,7 +60,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( * **Reverse-Proxy/HTTPS Ready:** Preconfigured Atlassian Tomcat proxy envs so Jira respects external scheme/host/port. * **OIDC SSO (Optional):** Pre-templated vars for issuer, client, endpoints, scopes; compatible with Atlassian DC SSO/OIDC marketplace apps. * **Central Database:** PostgreSQL integration (local or central) with credentials sourced from role configuration. -* **JVM Auto-Tuning:** Safe calculation of `JVM_MINIMUM_MEMORY` / `JVM_MAXIMUM_MEMORY` with caps to avoid VM init errors. +* **JVM Auto-Tuning:** `JVM_MINIMUM_MEMORY` / `JVM_MAXIMUM_MEMORY` are 35 % and 70 % of the service `mem_limit`. * **Health Checks:** Container healthcheck for quicker failure detection and stable automation. * **CSP & Canonical Domains:** Integrates with platform CSP and domain management. * **Backup Ready:** Persistent data under `{{ JIRA_STORAGE_PATH }}`. diff --git a/roles/web-app-jira/meta/services.yml b/roles/web-app-jira/meta/services.yml index e45dcd4d71..e9237405fb 100644 --- a/roles/web-app-jira/meta/services.yml +++ b/roles/web-app-jira/meta/services.yml @@ -37,7 +37,7 @@ jira: swarm: enabled: true image: atlassian/jira-software - version: 11.3.11 + version: 11.3.12 custom: true name: jira min_storage: 1027MB diff --git a/roles/web-app-jira/vars/main.yml b/roles/web-app-jira/vars/main.yml index 1e5fbc3de4..820d9117fb 100644 --- a/roles/web-app-jira/vars/main.yml +++ b/roles/web-app-jira/vars/main.yml @@ -25,5 +25,5 @@ JIRA_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ ' JIRA_IMAGE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.image') }}" JIRA_CONTAINER: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.name') }}" -JIRA_JVM_MAX: "{{ lookup('applications') | jvm_max_mb(application_id) }}m" -JIRA_JVM_MIN: "{{ lookup('applications') | jvm_min_mb(application_id) }}m" +JIRA_JVM_MAX: "{{ lookup('service_memory_mb', application_id, entity_name, 0.7) }}m" +JIRA_JVM_MIN: "{{ lookup('service_memory_mb', application_id, entity_name, 0.35) }}m" diff --git a/roles/web-app-joomla/meta/services.yml b/roles/web-app-joomla/meta/services.yml index 46483ce2ee..282f2caffb 100644 --- a/roles/web-app-joomla/meta/services.yml +++ b/roles/web-app-joomla/meta/services.yml @@ -51,9 +51,6 @@ joomla: no_stop_required: true upload: size_mb: 100 - performance: - php: - memory_limit: 512M autocreate_users: true ports: local: diff --git a/roles/web-app-joomla/tasks/08_oidc_plugin.yml b/roles/web-app-joomla/tasks/08_oidc_plugin.yml index 9c04694812..037239a96c 100644 --- a/roles/web-app-joomla/tasks/08_oidc_plugin.yml +++ b/roles/web-app-joomla/tasks/08_oidc_plugin.yml @@ -53,7 +53,7 @@ - name: "πŸ“¦ Install plg_system_keycloak via Joomla CLI" ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec --user {{ JOOMLA_WEB_USER | quote }} {{ JOOMLA_LOCAL_CID | quote }} - php -d memory_limit=512M {{ JOOMLA_CLI_FILE | quote }} + php -d memory_limit={{ JOOMLA_PHP_MEMORY_LIMIT }} {{ JOOMLA_CLI_FILE | quote }} extension:install --path={{ JOOMLA_OIDC_PLUGIN_ZIP | quote }} register: plugin_install changed_when: "'Extension installed successfully' in plugin_install.stdout" @@ -63,8 +63,8 @@ delegate_to: "{{ JOOMLA_HOST_NODE }}" - name: "πŸ” Resolve plg_system_keycloak extension ID" # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node - ansible.builtin.shell: "container exec --user {{ JOOMLA_WEB_USER }} {{ JOOMLA_LOCAL_CID | quote }} php -d memory_limit=512M {{ JOOMLA_CLI_FILE }} extension:list - | awk '/plg_system_keycloak/ {print $2; exit}'" + ansible.builtin.shell: "container exec --user {{ JOOMLA_WEB_USER }} {{ JOOMLA_LOCAL_CID | quote }} php -d memory_limit={{ JOOMLA_PHP_MEMORY_LIMIT }} {{ JOOMLA_CLI_FILE + }} extension:list | awk '/plg_system_keycloak/ {print $2; exit}'" register: plugin_id_lookup changed_when: false failed_when: plugin_id_lookup.stdout | trim | length == 0 @@ -73,7 +73,7 @@ - name: "🟒 Enable plg_system_keycloak via Joomla CLI" ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node container exec --user {{ JOOMLA_WEB_USER | quote }} {{ JOOMLA_LOCAL_CID | quote }} - php -d memory_limit=512M {{ JOOMLA_CLI_FILE | quote }} + php -d memory_limit={{ JOOMLA_PHP_MEMORY_LIMIT }} {{ JOOMLA_CLI_FILE | quote }} extension:enable {{ plugin_id_lookup.stdout | trim | quote }} register: plugin_enable changed_when: "'has been enabled' in plugin_enable.stdout or 'enabled successfully' in plugin_enable.stdout" diff --git a/roles/web-app-joomla/vars/main.yml b/roles/web-app-joomla/vars/main.yml index c7d2ddee5a..a8b0f5d4ae 100644 --- a/roles/web-app-joomla/vars/main.yml +++ b/roles/web-app-joomla/vars/main.yml @@ -23,7 +23,7 @@ JOOMLA_UPLOAD_CONFIG: "{{ [ lookup('container', application_id, 'directories.ins JOOMLA_UPLOAD_SIZE: "{{ lookup('config', application_id, 'services.joomla.upload.size_mb') }}" JOOMLA_UPLOAD_MAX_FILESIZE: "{{ (JOOMLA_UPLOAD_SIZE | int) }}M" JOOMLA_POST_MAX_SIZE: "{{ ((JOOMLA_UPLOAD_SIZE | int) * 12 // 10) }}M" -JOOMLA_PHP_MEMORY_LIMIT: "{{ lookup('config', application_id, 'services.joomla.performance.php.memory_limit') }}" +JOOMLA_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, entity_name, 0.5) }}M" JOOMLA_USER_NAME: "{{ lookup('users', 'administrator').username }}" JOOMLA_USER: "{{ JOOMLA_USER_NAME | capitalize }}" 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 2eb7d792cd..51d773280a 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 @@ -61,8 +61,6 @@ - name: "⏳ Reap the remaining Keycloak update jobs" ansible.builtin.include_tasks: utils/async/reap.yml vars: - async_reap_jobs: >- - {{ (kc_rbac_default.results | default([kc_rbac_default] if kc_rbac_default is defined else [])) - + (kc_declared_client_jobs | default([])) }} + 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/02_mail_realm.yml b/roles/web-app-keycloak/tasks/update/02_mail_realm.yml index f5484e1888..073fa710df 100644 --- a/roles/web-app-keycloak/tasks/update/02_mail_realm.yml +++ b/roles/web-app-keycloak/tasks/update/02_mail_realm.yml @@ -10,6 +10,3 @@ kcadm_exec: "{{ KEYCLOAK_EXEC_KCADM }}" assert_mode: "{{ MODE_ASSERT }}" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - # rationale: async; smtpServer is written here and never read back anywhere - 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/03_mail_master.yml b/roles/web-app-keycloak/tasks/update/03_mail_master.yml index 71d80a3d89..7340996078 100644 --- a/roles/web-app-keycloak/tasks/update/03_mail_master.yml +++ b/roles/web-app-keycloak/tasks/update/03_mail_master.yml @@ -10,6 +10,3 @@ kcadm_exec: "{{ KEYCLOAK_EXEC_KCADM }}" assert_mode: "{{ MODE_ASSERT }}" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - # rationale: async; writes the master realm smtpServer, which nothing reads 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/04_rbac_client_scope.yml b/roles/web-app-keycloak/tasks/update/04_rbac_client_scope.yml index a849f9fb31..9d6ee571b9 100644 --- a/roles/web-app-keycloak/tasks/update/04_rbac_client_scope.yml +++ b/roles/web-app-keycloak/tasks/update/04_rbac_client_scope.yml @@ -92,8 +92,4 @@ {{ KEYCLOAK_EXEC_KCADM }} update clients/{{ app_client_id }}/default-client-scopes/{{ scope_id_rbac }} -r {{ KEYCLOAK_REALM }} - register: kc_rbac_default changed_when: true - # rationale: async; no task in the chain reads the scope back, 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 }}" diff --git a/roles/web-app-magento/templates/compose.yml.j2 b/roles/web-app-magento/templates/compose.yml.j2 index 8ab9ce649d..74e909bc1e 100644 --- a/roles/web-app-magento/templates/compose.yml.j2 +++ b/roles/web-app-magento/templates/compose.yml.j2 @@ -39,7 +39,7 @@ environment: - discovery.type=single-node - plugins.security.disabled=true - - OPENSEARCH_JAVA_OPTS=-Xms512m -Xmx512m + - OPENSEARCH_JAVA_OPTS=-Xms{{ MAGENTO_SEARCH_HEAP_MB }}m -Xmx{{ MAGENTO_SEARCH_HEAP_MB }}m {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} diff --git a/roles/web-app-magento/templates/env.j2 b/roles/web-app-magento/templates/env.j2 index 2de3c20154..e75d1eeab5 100644 --- a/roles/web-app-magento/templates/env.j2 +++ b/roles/web-app-magento/templates/env.j2 @@ -41,6 +41,6 @@ MAGENTO_REMOTE_STORAGE_REGION={{ lookup('objstore', application_id, 'region') }} MAGENTO_REMOTE_STORAGE_PATH_STYLE=1 {% endif %} -PHP_MEMORY_LIMIT=768M +PHP_MEMORY_LIMIT={{ lookup('service_memory_mb', application_id, 'php', 0.75) }}M APACHE_SERVERNAME={{ MAGENTO_DOMAIN }} diff --git a/roles/web-app-magento/vars/main.yml b/roles/web-app-magento/vars/main.yml index d420819050..ce391fede0 100644 --- a/roles/web-app-magento/vars/main.yml +++ b/roles/web-app-magento/vars/main.yml @@ -19,6 +19,7 @@ MAGENTO_PHP_FPM_CONF_PATH: "{{ [ lookup('container', application_id, 'directorie MAGENTO_OBJSTORE_ENABLED: "{{ lookup('objstore', application_id, 'enabled') }}" MAGENTO_SEARCH_CONTAINER: "{{ lookup('config', application_id, 'services.search.name') }}" +MAGENTO_SEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, 'search', 0.25) }}" MAGENTO_PHP_CONTAINER: "{{ lookup('config', application_id, 'services.php.name') }}" MAGENTO_PHP_CONTAINER_ADDRESS: "{{ lookup('container_address', application_id, 'php') }}" diff --git a/roles/web-app-moodle/README.md b/roles/web-app-moodle/README.md index a0a39431e2..fd795b0944 100644 --- a/roles/web-app-moodle/README.md +++ b/roles/web-app-moodle/README.md @@ -121,7 +121,7 @@ docker run --rm -it \ ## MCP server -The role exposes a Model Context Protocol surface through the `webservice_mcp` protocol plugin, baked into the image at `webservice/mcp` and served by the NGINX sidecar. +The role exposes a Model Context Protocol surface through the `webservice_mcp` protocol plugin, baked into the image at `public/webservice/mcp` and served by the NGINX sidecar. | Property | Value | | --- | --- | @@ -173,7 +173,13 @@ This is an accepted trade-off, not an oversight. Moodle offers no allowlist, so ## Image source -This role builds its own Moodle image from upstream Moodle source on top of the official `php:8.3-fpm` base. +This role builds its own Moodle image from upstream Moodle source on top of the official `php:8.3-fpm` base and installs the Composer dependencies that source declares. The NGINX sidecar serves the `public` directory of the code volume and hands every other path to Moodle's router. + +## Updates + +The image carries the Moodle release pinned as `services.moodle.app_version` in `meta/services.yml`. On start the entrypoint compares that release with the one recorded in the code volume. When the image is newer, it copies the image's tree next to the old one and swaps them once the copy is complete. An image that is older than the recorded release refuses to start. `tasks/01_manager_ops.yml` then runs `admin/cli/upgrade.php`, which migrates the database. + +Plugins installed through the web interface live only in the code volume and are not carried over to the next release. Declare a plugin under `meta/addons/` so the image ships it. ## Further Resources diff --git a/roles/web-app-moodle/files/Dockerfile b/roles/web-app-moodle/files/Dockerfile index dc36c5be3a..f6aa1f92c2 100644 --- a/roles/web-app-moodle/files/Dockerfile +++ b/roles/web-app-moodle/files/Dockerfile @@ -96,6 +96,8 @@ COPY build/php-conf/opcache-recommended.ini /usr/local/etc/php/conf.d/opcache-re COPY build/php-conf/moodle-runtime.ini /usr/local/etc/php/conf.d/moodle-runtime.ini COPY build/php-conf/zz-moodle-pool.conf /usr/local/etc/php-fpm.d/zz-moodle-pool.conf +COPY --from=composer:2 /usr/bin/composer /usr/bin/composer + COPY build/install/moodle-source.sh /tmp/install-moodle-source.sh RUN bash /tmp/install-moodle-source.sh && rm /tmp/install-moodle-source.sh diff --git a/roles/web-app-moodle/files/build/config.php b/roles/web-app-moodle/files/build/config.php index 5434affc26..5e66fb1fcd 100644 --- a/roles/web-app-moodle/files/build/config.php +++ b/roles/web-app-moodle/files/build/config.php @@ -40,6 +40,7 @@ $CFG->dataroot = moodle_env('MOODLE_DATAROOT'); $CFG->localcachedir = moodle_env('MOODLE_LOCALCACHEDIR'); $CFG->admin = 'admin'; $CFG->directorypermissions = 02770; +$CFG->routerconfigured = true; $CFG->reverseproxy = moodle_env_bool('MOODLE_REVERSEPROXY'); $CFG->sslproxy = moodle_env_bool('MOODLE_SSLPROXY'); diff --git a/roles/web-app-moodle/files/build/install/moodle-source.sh b/roles/web-app-moodle/files/build/install/moodle-source.sh index 8674cbc69f..17e5fa8df1 100644 --- a/roles/web-app-moodle/files/build/install/moodle-source.sh +++ b/roles/web-app-moodle/files/build/install/moodle-source.sh @@ -26,6 +26,8 @@ tar -xzf "${TARBALL_PATH}" --strip-components=1 -C "${MOODLE_SOURCE_DIR}" test -d "${MOODLE_SOURCE_DIR}/${MOODLE_AUTH_SUBDIR}" test -f "${MOODLE_SOURCE_DIR}/${MOODLE_VERSION_FILE}" +COMPOSER_ALLOW_SUPERUSER=1 composer install --no-dev --classmap-authoritative --no-interaction --working-dir="${MOODLE_SOURCE_DIR}" + mkdir -p "${MOODLE_CODE_DIR}" "${MOODLE_DATA_DIR}" chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" \ "${MOODLE_SOURCE_DIR}" "${MOODLE_CODE_DIR}" "${MOODLE_DATA_DIR}" diff --git a/roles/web-app-moodle/files/build/moodle-entrypoint.sh b/roles/web-app-moodle/files/build/moodle-entrypoint.sh index 8474a21407..30083ff2ff 100644 --- a/roles/web-app-moodle/files/build/moodle-entrypoint.sh +++ b/roles/web-app-moodle/files/build/moodle-entrypoint.sh @@ -1,6 +1,6 @@ #!/bin/bash # Moodle container entrypoint. Bootstrap the persistent code volume -# from ${MOODLE_SOURCE_DIR} on first start, ensure ownership on the +# from ${MOODLE_SOURCE_DIR}, ensure ownership on the # data dir, then drop privileges (unless launching php-fpm β€” its # master process must keep root so the FPM error log can write to # /proc/self/fd/2; workers fork to ${MOODLE_RUNTIME_USER} per the pool). @@ -14,9 +14,11 @@ set -euo pipefail : "${MOODLE_SOURCE_DIR:?required}" : "${MOODLE_RUNTIME_USER:?required}" : "${MOODLE_VERSION_FILE:?required}" +: "${MOODLE_RELEASE:?required}" MOODLE_BOOTSTRAP_SENTINEL="${MOODLE_CODE_DIR}/.bootstrap.done" MOODLE_BOOTSTRAP_LOCK="${MOODLE_CODE_DIR}/.bootstrap.lock" +MOODLE_BOOTSTRAP_STAGE="${MOODLE_CODE_DIR}/.bootstrap.stage" mkdir -p "${MOODLE_DATA_DIR}" chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_DATA_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error @@ -26,17 +28,36 @@ if [ "$(id -u)" -eq 0 ]; then chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_LOCAL_CACHE_DIR}" fi +moodle_code_dir_is_current() { + [ "$(cat "${MOODLE_BOOTSTRAP_SENTINEL}" 2>/dev/null)" = "${MOODLE_RELEASE}" ] +} + +moodle_code_dir_is_newer() { + local recorded newest + recorded="$(cat "${MOODLE_BOOTSTRAP_SENTINEL}" 2>/dev/null)" || return 1 + [ -n "${recorded}" ] || return 1 + newest="$(printf '%s\n' "${recorded}" "${MOODLE_RELEASE}" | sort -V | tail -n 1)" + [ "${newest}" = "${recorded}" ] && [ "${recorded}" != "${MOODLE_RELEASE}" ] +} + moodle_bootstrap_code_dir() { - if [ -f "${MOODLE_BOOTSTRAP_SENTINEL}" ]; then + if moodle_code_dir_is_current; then return 0 fi - if [ -d "${MOODLE_SOURCE_DIR}" ]; then - cp -an "${MOODLE_SOURCE_DIR}/." "${MOODLE_CODE_DIR}/" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error + if moodle_code_dir_is_newer; then + echo "The code volume holds Moodle $(cat "${MOODLE_BOOTSTRAP_SENTINEL}"), this image ships the older ${MOODLE_RELEASE}; refusing to replace it." >&2 + exit 1 fi + rm -rf "${MOODLE_BOOTSTRAP_STAGE}" + mkdir "${MOODLE_BOOTSTRAP_STAGE}" + cp -a "${MOODLE_SOURCE_DIR}/." "${MOODLE_BOOTSTRAP_STAGE}/" + find "${MOODLE_CODE_DIR}" -mindepth 1 -maxdepth 1 ! -name "${MOODLE_BOOTSTRAP_LOCK##*/}" ! -name "${MOODLE_BOOTSTRAP_STAGE##*/}" -exec rm -rf {} + + find "${MOODLE_BOOTSTRAP_STAGE}" -mindepth 1 -maxdepth 1 -exec mv -t "${MOODLE_CODE_DIR}" {} + + rmdir "${MOODLE_BOOTSTRAP_STAGE}" chown -R "${MOODLE_RUNTIME_USER}:${MOODLE_RUNTIME_USER}" "${MOODLE_CODE_DIR}" || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error find "${MOODLE_CODE_DIR}" -type d -exec chmod 0755 {} + || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error find "${MOODLE_CODE_DIR}" -type f -exec chmod 0644 {} + || true # nocheck: shell-or-true -- grandfathered: worked in practice; TODO: sharpen to catch only the exact tolerated error - touch "${MOODLE_BOOTSTRAP_SENTINEL}" + printf '%s' "${MOODLE_RELEASE}" > "${MOODLE_BOOTSTRAP_SENTINEL}" } moodle_refresh_config() { @@ -51,7 +72,7 @@ moodle_refresh_config() { } mkdir -p "${MOODLE_CODE_DIR}" -while [ ! -f "${MOODLE_BOOTSTRAP_SENTINEL}" ]; do +until moodle_code_dir_is_current; do exec 9>>"${MOODLE_BOOTSTRAP_LOCK}" if flock -w 30 9; then moodle_bootstrap_code_dir diff --git a/roles/web-app-moodle/files/build/php-conf/opcache-recommended.ini b/roles/web-app-moodle/files/build/php-conf/opcache-recommended.ini index be3fc9f5dc..6271cf8344 100644 --- a/roles/web-app-moodle/files/build/php-conf/opcache-recommended.ini +++ b/roles/web-app-moodle/files/build/php-conf/opcache-recommended.ini @@ -1,4 +1,3 @@ -opcache.memory_consumption=256 opcache.interned_strings_buffer=16 opcache.max_accelerated_files=20000 opcache.revalidate_freq=60 diff --git a/roles/web-app-moodle/meta/addons/auth_oidc.yml b/roles/web-app-moodle/meta/addons/auth_oidc.yml index 1e33ee4776..5d68112121 100644 --- a/roles/web-app-moodle/meta/addons/auth_oidc.yml +++ b/roles/web-app-moodle/meta/addons/auth_oidc.yml @@ -3,11 +3,11 @@ enabled: "{{ lookup('config', 'web-app-moodle', 'services.sso.enabled') | bool } required: false mechanism: plugin source: upstream -version: "v4.5.8" +version: "v5.2.1" bridges: - sso update: monitored: true catalog: github-releases upstream_id: microsoft/moodle-auth_oidc - match: "v4.5." + match: "v" diff --git a/roles/web-app-moodle/meta/server.yml b/roles/web-app-moodle/meta/server.yml new file mode 100644 index 0000000000..f365eb8102 --- /dev/null +++ b/roles/web-app-moodle/meta/server.yml @@ -0,0 +1,5 @@ +--- +status_codes: + default: + - 200 + - 303 diff --git a/roles/web-app-moodle/meta/services.yml b/roles/web-app-moodle/meta/services.yml index 70f66d0f48..9c89c98c08 100644 --- a/roles/web-app-moodle/meta/services.yml +++ b/roles/web-app-moodle/meta/services.yml @@ -45,7 +45,7 @@ moodle: bond: 1 enabled: true # nocheck: dynamic-flag shared: true - app_version: 4.5.11 + app_version: 5.3.0 update: key: app_version type: git_tags @@ -65,7 +65,6 @@ moodle: site_titel: Academy on {{ DOMAIN_PRIMARY }} performance: php: - memory_limit: 512M upload_max_filesize: 256M post_max_size: 256M ports: diff --git a/roles/web-app-moodle/tasks/01_manager_ops.yml b/roles/web-app-moodle/tasks/01_manager_ops.yml index 078f32c1ca..93cd1d5e97 100644 --- a/roles/web-app-moodle/tasks/01_manager_ops.yml +++ b/roles/web-app-moodle/tasks/01_manager_ops.yml @@ -48,6 +48,13 @@ - "'Database tables already present' not in moodle_install.stderr" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" +- name: "⬆️ Upgrade the Moodle database to the release in the code volume" + shell: > + container exec --user {{ MOODLE_RUNTIME_USER }} {{ MOODLE_CONTAINER_ADDRESS }} + php {{ MOODLE_CLI_DIR }}/upgrade.php --non-interactive + register: moodle_upgrade + changed_when: "'No upgrade needed' not in moodle_upgrade.stderr" + - name: "πŸ”‘ Realign the administrator password Moodle persisted at install" when: not (MOODLE_OIDC_ENABLED | bool) # nocheck: password-quote the token is upstream's CLI filename, not a credential diff --git a/roles/web-app-moodle/tasks/04_oidc.yml b/roles/web-app-moodle/tasks/04_oidc.yml index e150b4d5ed..2166ccec42 100644 --- a/roles/web-app-moodle/tasks/04_oidc.yml +++ b/roles/web-app-moodle/tasks/04_oidc.yml @@ -93,7 +93,7 @@ - { name: "field_map_lastnamephonetic", value: "name_phonetic_family" } - { name: "field_lock_lastnamephonetic", value: "locked" } - { name: "field_updatelocal_lastnamephonetic", value: "oneveryloginupdate" } - - { name: "alternateloginurl", value: "{{ lookup('tls', application_id, 'url.base') }}{{ MOODLE_OIDC_PLUGIN_RELPATH }}/" } + - { name: "alternateloginurl", value: "{{ lookup('tls', application_id, 'url.base') }}{{ MOODLE_OIDC_PLUGIN_URL_PATH }}/" } loop_control: label: "{{ item.name }}" shell: > diff --git a/roles/web-app-moodle/templates/build/php-conf/moodle-runtime.ini.j2 b/roles/web-app-moodle/templates/build/php-conf/moodle-runtime.ini.j2 index 2b8afa62a3..8eb37db7bc 100644 --- a/roles/web-app-moodle/templates/build/php-conf/moodle-runtime.ini.j2 +++ b/roles/web-app-moodle/templates/build/php-conf/moodle-runtime.ini.j2 @@ -1,4 +1,5 @@ memory_limit={{ MOODLE_PHP_MEMORY_LIMIT }} +opcache.memory_consumption={{ lookup('service_memory_mb', application_id, 'moodle', 0.125) }} upload_max_filesize={{ MOODLE_PHP_UPLOAD_MAX_FILESIZE }} post_max_size={{ MOODLE_PHP_POST_MAX_SIZE }} max_execution_time={{ MOODLE_PHP_MAX_EXECUTION_TIME }} diff --git a/roles/web-app-moodle/templates/nginx-moodle.conf.j2 b/roles/web-app-moodle/templates/nginx-moodle.conf.j2 index 477b89cd1f..ca7b6a2a03 100644 --- a/roles/web-app-moodle/templates/nginx-moodle.conf.j2 +++ b/roles/web-app-moodle/templates/nginx-moodle.conf.j2 @@ -7,7 +7,7 @@ server { listen [::]:{{ MOODLE_NGINX_PORT }}; server_name _; - root {{ MOODLE_CODE_DIR }}; + root {{ MOODLE_PUBLIC_DIR }}; index index.php; client_max_body_size 256M; @@ -16,16 +16,19 @@ server { set $moodle_upstream {{ MOODLE_CONTAINER }}; location / { - try_files $uri $uri/ /index.php?$query_string; + try_files $uri $uri/ /r.php$is_args$args; } location ~ [^/]\.php(/|$) { - fastcgi_split_path_info ^(.+\.php)(/.+)$; + fastcgi_split_path_info ^(.+\.php)(/.*)?$; + set $path_info $fastcgi_path_info; + try_files $fastcgi_script_name $fastcgi_script_name/ /r.php$is_args$args; fastcgi_index index.php; fastcgi_pass $moodle_upstream:{{ MOODLE_FPM_PORT }}; include fastcgi_params; - fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; - fastcgi_param PATH_INFO $fastcgi_path_info; + fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; + fastcgi_param DOCUMENT_ROOT $realpath_root; + fastcgi_param PATH_INFO $path_info; fastcgi_param HTTP_PROXY ""; fastcgi_read_timeout 300; } diff --git a/roles/web-app-moodle/vars/main.yml b/roles/web-app-moodle/vars/main.yml index 786edc0c15..b674edd777 100644 --- a/roles/web-app-moodle/vars/main.yml +++ b/roles/web-app-moodle/vars/main.yml @@ -19,15 +19,18 @@ MOODLE_BUILD_FILES: opcache_ini: "php-conf/opcache-recommended.ini" runtime_ini: "php-conf/moodle-runtime.ini" fpm_pool: "php-conf/zz-moodle-pool.conf" -MOODLE_VERSION_FILE: "version.php" # bootstrap-detection sentinel -MOODLE_AUTH_SUBDIR: "auth" # top-level auth/ tree -MOODLE_WEBSERVICE_SUBDIR: "webservice" +MOODLE_PUBLIC_SUBDIR: "public" +MOODLE_PUBLIC_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_PUBLIC_SUBDIR] | path_join }}" +MOODLE_VERSION_FILE: "{{ [MOODLE_PUBLIC_SUBDIR, 'version.php'] | path_join }}" +MOODLE_AUTH_SUBDIR: "{{ [MOODLE_PUBLIC_SUBDIR, 'auth'] | path_join }}" +MOODLE_WEBSERVICE_SUBDIR: "{{ [MOODLE_PUBLIC_SUBDIR, 'webservice'] | path_join }}" MOODLE_CLI_RELPATH: "admin/cli" # admin CLI script dir MOODLE_OIDC_PLUGIN_VERSION: "{{ lookup('config', application_id, 'addons.auth_oidc.version') }}" MOODLE_OIDC_PLUGIN_UPSTREAM: "{{ lookup('config', application_id, 'addons.auth_oidc.update.upstream_id') }}" MOODLE_OIDC_PLUGIN_ARCHIVE_URL: "https://github.com/{{ MOODLE_OIDC_PLUGIN_UPSTREAM }}/archive/refs/tags/{{ MOODLE_OIDC_PLUGIN_VERSION }}.zip" -MOODLE_OIDC_PLUGIN_RELPATH: "{{ [MOODLE_AUTH_SUBDIR, 'oidc'] | path_join }}" +MOODLE_OIDC_PLUGIN_URL_PATH: "auth/oidc" +MOODLE_OIDC_PLUGIN_RELPATH: "{{ [MOODLE_PUBLIC_SUBDIR, MOODLE_OIDC_PLUGIN_URL_PATH] | path_join }}" MOODLE_OIDC_PLUGIN_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_OIDC_PLUGIN_RELPATH] | path_join }}" MOODLE_CLI_DIR: "{{ [MOODLE_CODE_DIR, MOODLE_CLI_RELPATH] | path_join }}" MOODLE_CONFIG: "{{ [MOODLE_CODE_DIR, 'config.php'] | path_join }}" @@ -130,7 +133,7 @@ MOODLE_SITE_TITLE: "{{ lookup('config', application_id, 'services.moodle.site_ti MOODLE_FPM_PORT: "{{ lookup('config', application_id, 'services.moodle.ports.internal.fpm') }}" MOODLE_NGINX_PORT: "{{ lookup('config', application_id, 'services.moodle.ports.internal.http') }}" -MOODLE_PHP_MEMORY_LIMIT: "{{ lookup('config', application_id, 'services.moodle.performance.php.memory_limit') }}" +MOODLE_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, 'moodle', 0.25) }}M" MOODLE_PHP_UPLOAD_MAX_FILESIZE: "{{ lookup('config', application_id, 'services.moodle.performance.php.upload_max_filesize') }}" MOODLE_PHP_POST_MAX_SIZE: "{{ lookup('config', application_id, 'services.moodle.performance.php.post_max_size') }}" MOODLE_PHP_MAX_EXECUTION_TIME: "300" diff --git a/roles/web-app-n8n/files/javascript/hooks.js b/roles/web-app-n8n/files/javascript/hooks.js index 9b70bddff5..80e3f06db6 100644 --- a/roles/web-app-n8n/files/javascript/hooks.js +++ b/roles/web-app-n8n/files/javascript/hooks.js @@ -48,10 +48,12 @@ module.exports = { this.logger?.info(`SSO middleware initializing with header: ${headerName}`); - const Layer = require('router/lib/layer'); + const { createRequire } = require('module'); const { dirname, resolve } = require('path'); const { randomBytes } = require('crypto'); - const { hash } = require('bcryptjs'); + const n8nRequire = createRequire(require.resolve('n8n')); + const Layer = createRequire(n8nRequire.resolve('express'))('router/lib/layer'); + const { hash } = n8nRequire('bcryptjs'); const { issueCookie } = require(resolve(dirname(require.resolve('n8n')), 'auth/jwt')); // Trust the proxy for correct X-Forwarded-* handling and rate limiting @@ -114,18 +116,17 @@ module.exports = { this.logger?.info(`SSO auto-login attempt for email: ${userEmail}`); - // 1) Try to fetch the user (n8n 1.95.3 stores 'role' as a plain string column) let user = await UserRepo.findOne({ where: { email: userEmail }, + relations: ['role'], }); - // 2) If not found β€” create the user (with 'global:member' role) and a project if (!user) { const hashed = await hash(randomBytes(16).toString('hex'), 10); const userData = { email: userEmail, - role: 'global:member', // string-based role is valid for createUserWithProject + role: { slug: 'global:member' }, password: hashed, }; if (userFirstName) userData.firstName = userFirstName; @@ -136,7 +137,6 @@ module.exports = { this.logger?.info(`Created new user: ${userEmail} (${userFirstName} ${userLastName}) via SSO`); } else { - // 3) Update first/last name if they changed upstream let changed = false; if (userFirstName && user.firstName !== userFirstName) { user.firstName = userFirstName; @@ -154,7 +154,6 @@ module.exports = { } } - // 4) Ensure 'user.role' exists (plain string column, e.g. 'global:member') if (!user.role) { this.logger?.error(`User ${userEmail} has no valid role; cannot issue cookie.`); res.statusCode = 401; @@ -162,10 +161,8 @@ module.exports = { return; } - // 5) Issue n8n auth cookie issueCookie(res, user); - // 6) Attach context for downstream middleware/routes req.user = user; req.userId = user.id; diff --git a/roles/web-app-n8n/meta/services.yml b/roles/web-app-n8n/meta/services.yml index a7ad1c3b40..156c60abc5 100644 --- a/roles/web-app-n8n/meta/services.yml +++ b/roles/web-app-n8n/meta/services.yml @@ -67,7 +67,7 @@ n8n: backup: no_stop_required: false image: docker.n8n.io/n8nio/n8n - version: "1.100.1" + version: "2.42.3" update: type: registry_tags image: docker.n8n.io/n8nio/n8n diff --git a/roles/web-app-nextcloud/files/playwright/_shared.js b/roles/web-app-nextcloud/files/playwright/_shared.js index 06dd40577f..e154b3e2f1 100644 --- a/roles/web-app-nextcloud/files/playwright/_shared.js +++ b/roles/web-app-nextcloud/files/playwright/_shared.js @@ -22,6 +22,8 @@ const mastodonBaseUrl = decodeDotenvQuotedValue(process.env.MASTODON_BASE_URL); const moodleBaseUrl = decodeDotenvQuotedValue(process.env.MOODLE_BASE_URL); const peertubeBaseUrl = decodeDotenvQuotedValue(process.env.PEERTUBE_BASE_URL); const xwikiBaseUrl = decodeDotenvQuotedValue(process.env.XWIKI_BASE_URL); +const MINIMAL_DOCX_BASE64 = + "UEsDBBQAAAAIAEq201x5bjPX6AAAAK0BAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbH1QyU7DMBD9FWuuKHHggBCK0wPLETiUDxjZk8SqN3nc0v49Tlt6QIXjzFv1+tXeO7GjzDYGBbdtB4KCjsaGScHn+rV5AMEFg0EXAyk4EMNq6NeHRCyqNrCCuZT0KCXrmTxyGxOFiowxeyz1zJNMqDc4kbzrunupYygUSlMWDxj6Zxpx64p42df3qUcmxyCeTsQlSwGm5KzGUnG5C+ZXSnNOaKvyyOHZJr6pBJBXExbk74Cz7r0Ok60h8YG5vKGvLPkVs5Em6q2vyvZ/mys94zhaTRf94pZy1MRcF/euvSAebfjpL49zD99QSwMECgAAAAAASrbTXAAAAAAAAAAAAAAAAAYAAABfcmVscy9QSwMEFAAAAAgASrbTXJv9N+qtAAAAKQEAAAsAAABfcmVscy8ucmVsc43POw7CMAwG4KtE3mlaBoRQ0y4IqSsqB7ASN61oHkrCo7cnAwNFDIy2f3+W6/ZpZnanECdnBVRFCYysdGqyWsClP232wGJCq3B2lgQsFKFt6jPNmPJKHCcfWTZsFDCm5A+cRzmSwVg4TzZPBhcMplwGzT3KK2ri27Lc8fBpwNpknRIQOlUB6xdP/9huGCZJRydvhmz6ceIrkWUMmpKAhwuKq3e7yCzwpuarF5sXUEsDBAoAAAAAAEq201wAAAAAAAAAAAAAAAAFAAAAd29yZC9QSwMEFAAAAAgASrbTXC5rweurAAAA6wAAABEAAAB3b3JkL2RvY3VtZW50LnhtbEWOQQ7CIBBFr0LYW6oLY5q27jyBHgBhaIkwQ4Bae3uhLty8n8lM3p/++vGOvSEmSzjwY9NyBqhIW5wG/rjfDhfOUpaopSOEgW+Q+HXs106TWjxgZkWAqVsHPuccOiGSmsHL1FAALDtD0ctcxjiJlaIOkRSkVPzeiVPbnoWXFnlVPklvNUNFrMijRWPRZmKEbiNjrAKmaAmuCFhpUq9e1LvKuDPs/LnE/8/xC1BLAQIeAxQAAAAIAEq201x5bjPX6AAAAK0BAAATAAAAAAAAAAEAAACkgQAAAABbQ29udGVudF9UeXBlc10ueG1sUEsBAh4DCgAAAAAASrbTXAAAAAAAAAAAAAAAAAYAAAAAAAAAAAAQAO1BGQEAAF9yZWxzL1BLAQIeAxQAAAAIAEq201yb/TfqrQAAACkBAAALAAAAAAAAAAEAAACkgT0BAABfcmVscy8ucmVsc1BLAQIeAwoAAAAAAEq201wAAAAAAAAAAAAAAAAFAAAAAAAAAAAAEADtQRMCAAB3b3JkL1BLAQIeAxQAAAAIAEq201wua8HrqwAAAOsAAAARAAAAAAAAAAEAAACkgTYCAAB3b3JkL2RvY3VtZW50LnhtbFBLBQYAAAAABQAFACABAAAQAwAAAAA="; const nextcloudUsernameFieldPattern = /account name(?: or email)?|username(?: or email)?/i; const nextcloudCredentialSubmitPattern = /^(sign in|log in)$/i; @@ -205,6 +207,7 @@ function beforeEach() { } module.exports = { + MINIMAL_DOCX_BASE64, env: { loginUsername, loginPassword, diff --git a/roles/web-app-nextcloud/files/playwright/addons/onlyoffice.spec.js b/roles/web-app-nextcloud/files/playwright/addons/onlyoffice.spec.js index 56333e0a42..a16e0a87e9 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/onlyoffice.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/onlyoffice.spec.js @@ -6,9 +6,6 @@ const { gotoOnion } = require("../personas"); test.use({ ignoreHTTPSErrors: true }); -const MINIMAL_DOCX_BASE64 = - "UEsDBBQAAAAIAEq201x5bjPX6AAAAK0BAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbH1QyU7DMBD9FWuuKHHggBCK0wPLETiUDxjZk8SqN3nc0v49Tlt6QIXjzFv1+tXeO7GjzDYGBbdtB4KCjsaGScHn+rV5AMEFg0EXAyk4EMNq6NeHRCyqNrCCuZT0KCXrmTxyGxOFiowxeyz1zJNMqDc4kbzrunupYygUSlMWDxj6Zxpx64p42df3qUcmxyCeTsQlSwGm5KzGUnG5C+ZXSnNOaKvyyOHZJr6pBJBXExbk74Cz7r0Ok60h8YG5vKGvLPkVs5Em6q2vyvZ/mys94zhaTRf94pZy1MRcF/euvSAebfjpL49zD99QSwMECgAAAAAASrbTXAAAAAAAAAAAAAAAAAYAAABfcmVscy9QSwMEFAAAAAgASrbTXJv9N+qtAAAAKQEAAAsAAABfcmVscy8ucmVsc43POw7CMAwG4KtE3mlaBoRQ0y4IqSsqB7ASN61oHkrCo7cnAwNFDIy2f3+W6/ZpZnanECdnBVRFCYysdGqyWsClP232wGJCq3B2lgQsFKFt6jPNmPJKHCcfWTZsFDCm5A+cRzmSwVg4TzZPBhcMplwGzT3KK2ri27Lc8fBpwNpknRIQOlUB6xdP/9huGCZJRydvhmz6ceIrkWUMmpKAhwuKq3e7yCzwpuarF5sXUEsDBAoAAAAAAEq201wAAAAAAAAAAAAAAAAFAAAAd29yZC9QSwMEFAAAAAgASrbTXC5rweurAAAA6wAAABEAAAB3b3JkL2RvY3VtZW50LnhtbEWOQQ7CIBBFr0LYW6oLY5q27jyBHgBhaIkwQ4Bae3uhLty8n8lM3p/++vGOvSEmSzjwY9NyBqhIW5wG/rjfDhfOUpaopSOEgW+Q+HXs106TWjxgZkWAqVsHPuccOiGSmsHL1FAALDtD0ctcxjiJlaIOkRSkVPzeiVPbnoWXFnlVPklvNUNFrMijRWPRZmKEbiNjrAKmaAmuCFhpUq9e1LvKuDPs/LnE/8/xC1BLAQIeAxQAAAAIAEq201x5bjPX6AAAAK0BAAATAAAAAAAAAAEAAACkgQAAAABbQ29udGVudF9UeXBlc10ueG1sUEsBAh4DCgAAAAAASrbTXAAAAAAAAAAAAAAAAAYAAAAAAAAAAAAQAO1BGQEAAF9yZWxzL1BLAQIeAxQAAAAIAEq201yb/TfqrQAAACkBAAALAAAAAAAAAAEAAACkgT0BAABfcmVscy8ucmVsc1BLAQIeAwoAAAAAAEq201wAAAAAAAAAAAAAAAAFAAAAAAAAAAAAEADtQRMCAAB3b3JkL1BLAQIeAxQAAAAIAEq201wua8HrqwAAAOsAAAARAAAAAAAAAAEAAACkgTYCAAB3b3JkL2RvY3VtZW50LnhtbFBLBQYAAAAABQAFACABAAAQAwAAAAA="; - test("onlyoffice addon: opening a document loads the partner document-server editor", async ({ browser }) => { skipUnlessAddonEnabled("onlyoffice"); test.setTimeout(resolveTimeout(180_000)); @@ -39,7 +36,7 @@ test("onlyoffice addon: opening a document loads the partner document-server edi .setInputFiles({ name: docName, mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - buffer: Buffer.from(MINIMAL_DOCX_BASE64, "base64"), + buffer: Buffer.from(shared.MINIMAL_DOCX_BASE64, "base64"), }); const docBasename = docName.replace(/\.docx$/, ""); diff --git a/roles/web-app-nextcloud/files/playwright/addons/richdocuments.spec.js b/roles/web-app-nextcloud/files/playwright/addons/richdocuments.spec.js index 516ee5f251..a70ee3f1b9 100644 --- a/roles/web-app-nextcloud/files/playwright/addons/richdocuments.spec.js +++ b/roles/web-app-nextcloud/files/playwright/addons/richdocuments.spec.js @@ -57,3 +57,65 @@ test("richdocuments addon: Collabora connector wired to the partner WOPI server" await context.close().catch(() => {}); } }); + +test("richdocuments addon: opening a document loads it through the partner WOPI server", async ({ browser }) => { + skipUnlessAddonEnabled("richdocuments"); + test.setTimeout(resolveTimeout(240_000)); + + const context = await browser.newContext({ ignoreHTTPSErrors: true }); + const page = await context.newPage(); + const editorReplies = []; + page.on("websocket", (socket) => { + if (!/\/cool\/(?:.+\/)?ws(?:\?|$)/.test(socket.url())) { + return; + } + socket.on("framereceived", ({ payload }) => { + const reply = payload.toString().slice(0, 120); + if (/^(status|error):/.test(reply)) { + editorReplies.push(reply); + } + }); + }); + + try { + await shared.loginToStandaloneNextcloud(page); + + const filesUrl = new URL("apps/files/", shared.env.nextcloudBaseUrl).toString(); + await gotoOnion(page, filesUrl, { waitUntil: "domcontentloaded", timeout: resolveTimeout(60_000) }); + await shared.dismissBlockingNextcloudModals(page, page); + + const docBasename = `infinito-collabora-${Date.now()}`; + await page + .locator('input[type="file"]') + .first() + .setInputFiles({ + name: `${docBasename}.docx`, + mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + buffer: Buffer.from(shared.MINIMAL_DOCX_BASE64, "base64"), + }); + + const uploadedRow = page.getByText(docBasename, { exact: false }).first(); + await expect( + uploadedRow, + `the uploaded document '${docBasename}.docx' must appear in the Files listing before it can be opened in Collabora` + ).toBeVisible({ timeout: resolveTimeout(60_000) }); + + await shared.dismissBlockingNextcloudModals(page, page); + await uploadedRow.click(); + + await expect + .poll(() => editorReplies.length, { + message: + "opening the document must make Collabora answer on its editor websocket (/cool/ws) with a 'status:' or an 'error:' frame; silence means the browser never reached the editor that the discovery of web-svc-collabora advertises", + timeout: resolveTimeout(180_000), + }) + .toBeGreaterThan(0); + expect( + editorReplies[0], + "Collabora must answer the document load with a 'status:' frame; 'error: cmd=internal kind=unauthorized' means it refused the WOPI host (aliasgroup1 of web-svc-collabora) or its CheckFileInfo call to Nextcloud failed, and the Collabora log names which" + ).toMatch(/^status:/); + } finally { + await page.close().catch(() => {}); + await context.close().catch(() => {}); + } +}); diff --git a/roles/web-app-nextcloud/meta/services.yml b/roles/web-app-nextcloud/meta/services.yml index 13f7f4b47e..6e0d032d02 100644 --- a/roles/web-app-nextcloud/meta/services.yml +++ b/roles/web-app-nextcloud/meta/services.yml @@ -84,9 +84,7 @@ nextcloud: enabled: "{{ not (lookup('config', 'web-app-nextcloud', 'services.sso.enabled') | bool) }}" performance: php: - memory_limit: "{{ ((ansible_facts['memtotal_mb'] | int) / 30) | int }}M" upload_limit: 5G - opcache_memory_consumption: "{{ ((ansible_facts['memtotal_mb'] | int) / 30) | int }}M" fpm: max_children: 16 start_servers: 4 diff --git a/roles/web-app-nextcloud/templates/env.j2 b/roles/web-app-nextcloud/templates/env.j2 index e63e181507..523629cb98 100644 --- a/roles/web-app-nextcloud/templates/env.j2 +++ b/roles/web-app-nextcloud/templates/env.j2 @@ -5,9 +5,9 @@ MYSQL_USER={{ lookup('database', application_id, 'username') }} MYSQL_PASSWORD={{ lookup('database', application_id, 'password') | dotenv_quote }} MYSQL_HOST={{ lookup('database', application_id, 'host') }}:{{ lookup('database', application_id, 'port') }} -PHP_MEMORY_LIMIT={{ lookup('config', application_id, 'services.nextcloud.performance.php.memory_limit') }} +PHP_MEMORY_LIMIT={{ lookup('service_memory_mb', application_id, 'nextcloud', 0.5) }}M PHP_UPLOAD_LIMIT={{ lookup('config', application_id, 'services.nextcloud.performance.php.upload_limit') }} -PHP_OPCACHE_MEMORY_CONSUMPTION={{ lookup('config', application_id, 'services.nextcloud.performance.php.opcache_memory_consumption') }} +PHP_OPCACHE_MEMORY_CONSUMPTION={{ lookup('service_memory_mb', application_id, 'nextcloud', 0.125) }}M {% set email = lookup('email', application_id) %} {% if email.enabled | bool %} diff --git a/roles/web-app-odoo/README.md b/roles/web-app-odoo/README.md index 62e7a4d9b5..c9904b6e56 100644 --- a/roles/web-app-odoo/README.md +++ b/roles/web-app-odoo/README.md @@ -216,7 +216,7 @@ docker logs odoo -f ## Persona contract opt-outs -The shared `biber` and `administrator` persona helpers are declared blocked in [templates/playwright.env.j2](./templates/playwright.env.j2). Odoo renders its SSO provider link only on `/web/login` inside the `.o_login_auth` container, not on the site root the persona helper starts from, and it exposes no in-app logout control β€” signing out means navigating to `/web/session/logout`. The full Keycloak round trip for both users is covered by the role's own `odoo: admin sso login, verify ui, logout` and `odoo: biber sso login, verify ui, logout` scenarios in [files/playwright/playwright.spec.js](./files/playwright/playwright.spec.js). +The shared `biber` and `administrator` persona helpers are declared blocked in [templates/playwright.env.j2](./templates/playwright.env.j2). Odoo renders its SSO provider link only on `/web/login` inside the `.o_login_auth` container, not on the site root the persona helper starts from, and its logout sits behind the user menu. The full Keycloak round trip for both users is covered by the role's own `odoo: admin sso login, verify ui, logout` and `odoo: biber sso login, verify ui, logout` scenarios in [files/playwright/playwright.spec.js](./files/playwright/playwright.spec.js). ## Credits diff --git a/roles/web-app-odoo/files/addons/auth_oauth_https/__manifest__.py b/roles/web-app-odoo/files/addons/auth_oauth_https/__manifest__.py index 5a042e03b9..70528d4956 100644 --- a/roles/web-app-odoo/files/addons/auth_oauth_https/__manifest__.py +++ b/roles/web-app-odoo/files/addons/auth_oauth_https/__manifest__.py @@ -1,7 +1,7 @@ # nocheck: mirrored-unit-test - an Odoo addon manifest, a bare dict literal the registry reads; there is no behaviour to exercise { # noqa: B018 Odoo addon manifests are bare dict expressions at module level by design "name": "OAuth HTTPS & Configurable UID", - "version": "19.0.1.8.0", + "version": "1.8.0", "category": "Authentication", "summary": "Force HTTPS redirect URIs and configurable OIDC UID field for OAuth", "description": """ diff --git a/roles/web-app-odoo/files/addons/auth_oauth_https/controllers/main.py b/roles/web-app-odoo/files/addons/auth_oauth_https/controllers/main.py index 0995cf2eb8..c637e3d3fe 100644 --- a/roles/web-app-odoo/files/addons/auth_oauth_https/controllers/main.py +++ b/roles/web-app-odoo/files/addons/auth_oauth_https/controllers/main.py @@ -2,14 +2,11 @@ # Part of Infinito.Nexus. See LICENSE file for full copyright and licensing details. import json -import logging import werkzeug.urls from odoo.addons.auth_oauth.controllers.main import OAuthLogin from odoo.http import request -_logger = logging.getLogger(__name__) - class OAuthLoginHTTPS(OAuthLogin): """ @@ -30,18 +27,11 @@ class OAuthLoginHTTPS(OAuthLogin): Returns the configured web.base.url, or falls back to request.httprequest.url_root if not set. """ - try: - base_url = ( - request.env["ir.config_parameter"].sudo().get_param("web.base.url") - ) - if base_url: - if not base_url.endswith("/"): - base_url += "/" - return base_url - except Exception: - _logger.exception( - "Failed to read 'web.base.url' from ir.config_parameter; falling back to request URL root." - ) + base_url = request.env["ir.config_parameter"].sudo().get_str("web.base.url") + if base_url: + if not base_url.endswith("/"): + base_url += "/" + return base_url return request.httprequest.url_root def list_providers(self): diff --git a/roles/web-app-odoo/files/playwright/playwright.spec.js b/roles/web-app-odoo/files/playwright/playwright.spec.js index bf7aeb77a2..f0dc42b44e 100644 --- a/roles/web-app-odoo/files/playwright/playwright.spec.js +++ b/roles/web-app-odoo/files/playwright/playwright.spec.js @@ -74,14 +74,9 @@ async function isOdooAuthenticated(locator) { } } -// Perform logout from Odoo by navigating directly to the logout URL. -async function performOdooLogout(page, odooBaseUrl) { - const logoutUrl = `${odooBaseUrl.replace(/\/$/, "")}/web/session/logout`; - - await gotoOnion(page, logoutUrl); - - // Give the logout a moment to process - await page.waitForTimeout(resolveTimeout(2_000)); +async function logOutThroughTheUserMenu(page) { + await page.locator("button.o_user_menu").first().click({ timeout: resolveTimeout(30_000) }); + await page.locator('[data-menu="logout"]').first().click({ timeout: resolveTimeout(30_000) }); } test.beforeEach(() => { @@ -93,6 +88,13 @@ test.beforeEach(() => { expect(biberPassword, "BIBER_PASSWORD must be set in the Playwright env file").toBeTruthy(); }); +test("odoo: the suite runs on one worker", async () => { + expect( + test.info().config.workers, + "an OAuth sign-in ends every other session of the same account, so PLAYWRIGHT_MAX_WORKERS must keep the spec files that share the administrator on one worker" + ).toBe(1); +}); + // Scenario I: Odoo β†’ SSO login as admin β†’ verify authenticated β†’ logout // (dashboard-iframe mechanics covered by web-app-dashboard SPOT) test("odoo: admin sso login, verify ui, logout", async ({ page }) => { @@ -137,8 +139,8 @@ test("odoo: admin sso login, verify ui, logout", async ({ page }) => { ) .toBe(true); - // 7. Perform logout from Odoo by navigating to the logout URL - await performOdooLogout(page, odooBaseUrl); + // 7. Log out through the user menu + await logOutThroughTheUserMenu(page); // 8. Verify we're back on the login page (provider list visible again) await expect @@ -198,8 +200,8 @@ test("odoo: biber sso login, verify ui, logout", async ({ page }) => { ) .toBe(true); - // 7. Perform logout from Odoo - await performOdooLogout(page, odooBaseUrl); + // 7. Log out through the user menu + await logOutThroughTheUserMenu(page); // 8. Verify we're back on the login page await expect diff --git a/roles/web-app-odoo/files/sql/select/installed-module.sql b/roles/web-app-odoo/files/sql/select/installed-module.sql new file mode 100644 index 0000000000..0d0dde252d --- /dev/null +++ b/roles/web-app-odoo/files/sql/select/installed-module.sql @@ -0,0 +1 @@ +SELECT name FROM ir_module_module WHERE name = %(module)s AND state = 'installed'; diff --git a/roles/web-app-odoo/tasks/03_install_modules/module_ops.yml b/roles/web-app-odoo/tasks/03_install_modules/module_ops.yml index 7829592d9a..6e216510b5 100644 --- a/roles/web-app-odoo/tasks/03_install_modules/module_ops.yml +++ b/roles/web-app-odoo/tasks/03_install_modules/module_ops.yml @@ -79,6 +79,18 @@ auth_oauth_https_install.rc != 0 or 'invalid module names' in (auth_oauth_https_install.stdout ~ auth_oauth_https_install.stderr) +- name: "πŸ›‘ Fail when Odoo did not install the auth_oauth_https module" + database_query: + mask_values: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + config: "{{ lookup('database', application_id) }}" + query_file: "{{ role_path }}/files/sql/select/installed-module.sql" + named_args: + module: "auth_oauth_https" + expect_rows: true + register: auth_oauth_https_installed + failed_when: auth_oauth_https_installed.rows | length == 0 + when: ODOO_OIDC_ENABLED | bool + - name: "πŸ“¦ Install auth_ldap module for LDAP support" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node diff --git a/roles/web-app-odoo/templates/odoo.conf.j2 b/roles/web-app-odoo/templates/odoo.conf.j2 index f1d2487621..71f4837ed4 100644 --- a/roles/web-app-odoo/templates/odoo.conf.j2 +++ b/roles/web-app-odoo/templates/odoo.conf.j2 @@ -28,8 +28,8 @@ gevent_port = {{ container_websocket_port }} proxy_mode = True workers = 4 max_cron_threads = 2 -limit_memory_hard = 2684354560 -limit_memory_soft = 2147483648 +limit_memory_hard = {{ (lookup('service_memory_mb', application_id, 'odoo', 0.625) | int) * 1048576 }} +limit_memory_soft = {{ (lookup('service_memory_mb', application_id, 'odoo', 0.5) | int) * 1048576 }} limit_time_cpu = 600 limit_time_real = 1200 limit_time_real_cron = 600 diff --git a/roles/web-app-odoo/templates/playwright.env.j2 b/roles/web-app-odoo/templates/playwright.env.j2 index fc973b9455..ba10af4e05 100644 --- a/roles/web-app-odoo/templates/playwright.env.j2 +++ b/roles/web-app-odoo/templates/playwright.env.j2 @@ -28,12 +28,14 @@ ODOO_BASE_URL={{ lookup('tls', application_id, 'url.base') | dotenv_quote }} OIDC_ISSUER_URL={{ OIDC.CLIENT.ISSUER_URL | dotenv_quote }} -# nocheck: persona-block-rationale β€” Odoo's SSO entry is an auth_oauth provider link that only renders inside .o_login_auth on /web/login (files/playwright/playwright.spec.js:25-44), not on the APP_BASE_URL root the persona helper starts from, and Odoo offers no in-app logout control β€” the role logs out by navigating to /web/session/logout (files/playwright/playwright.spec.js:77-84); the admin chain is covered by "odoo: admin sso login, verify ui, logout" (see README "Persona contract opt-outs"). +# nocheck: persona-block-rationale β€” Odoo's SSO entry is an auth_oauth provider link that only renders inside .o_login_auth on /web/login (files/playwright/playwright.spec.js:26-45), not on the APP_BASE_URL root the persona helper starts from, and its logout sits behind the user menu (files/playwright/playwright.spec.js:77-80); the admin chain is covered by "odoo: admin sso login, verify ui, logout" (see README "Persona contract opt-outs"). PERSONA_ADMINISTRATOR_BLOCKED=true -# nocheck: persona-block-rationale β€” see PERSONA_ADMINISTRATOR_BLOCKED above; biber's chain is covered by "odoo: biber sso login, verify ui, logout" (files/playwright/playwright.spec.js:159). +# nocheck: persona-block-rationale β€” see PERSONA_ADMINISTRATOR_BLOCKED above; biber's chain is covered by "odoo: biber sso login, verify ui, logout" (files/playwright/playwright.spec.js:162). PERSONA_BIBER_BLOCKED=true +PLAYWRIGHT_MAX_WORKERS=1 + SSO_SERVICE_ENABLED={{ lookup('config', application_id, 'services.sso.enabled') | string | lower }} {{ lookup('addon_env_flags', application_id) }} diff --git a/roles/web-app-opentalk/meta/services.yml b/roles/web-app-opentalk/meta/services.yml index 41d2c1e836..5509c681aa 100644 --- a/roles/web-app-opentalk/meta/services.yml +++ b/roles/web-app-opentalk/meta/services.yml @@ -96,7 +96,7 @@ controller: livekit: name: opentalk-livekit image: livekit/livekit-server - version: v1.13.7 + version: v1.13.8 min_storage: 238MB cpus: "2.0" mem_reservation: 512m diff --git a/roles/web-app-penpot/meta/services.yml b/roles/web-app-penpot/meta/services.yml index c75856a556..9f9f4ccb1e 100644 --- a/roles/web-app-penpot/meta/services.yml +++ b/roles/web-app-penpot/meta/services.yml @@ -79,7 +79,7 @@ penpot: lifecycle: beta frontend: image: penpotapp/frontend - version: "2.18.1" + version: "2.18.3" name: penpot-frontend cpus: "0.5" mem_reservation: 256m @@ -87,7 +87,7 @@ frontend: pids_limit: 256 backend: image: penpotapp/backend - version: "2.18.1" + version: "2.18.3" name: penpot-backend cpus: "1.0" mem_reservation: 1g @@ -100,7 +100,7 @@ backend: http: 6060 exporter: image: penpotapp/exporter - version: "2.18.1" + version: "2.18.3" name: penpot-exporter cpus: "0.5" mem_reservation: 512m diff --git a/roles/web-app-penpot/templates/compose.yml.j2 b/roles/web-app-penpot/templates/compose.yml.j2 index e04f73a5ce..2e27c07ec1 100644 --- a/roles/web-app-penpot/templates/compose.yml.j2 +++ b/roles/web-app-penpot/templates/compose.yml.j2 @@ -8,7 +8,7 @@ command: - /bin/bash - -c - - 'until getent hosts {{ PENPOT_BACKEND_SERVICE }} >/dev/null 2>&1 && getent hosts {{ PENPOT_EXPORTER_SERVICE }} >/dev/null 2>&1; do sleep 1; done; exec nginx -g "daemon off;"' + - 'until getent hosts {{ PENPOT_BACKEND_SERVICE }}. >/dev/null 2>&1 && getent hosts {{ PENPOT_EXPORTER_SERVICE }}. >/dev/null 2>&1; do sleep 1; done; exec nginx -g "daemon off;"' {{ lookup('container_ports', ['penpot', 'http', DOCKER_BIND_HOST]) | indent(4) }} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_healthcheck', 'penpot') | indent(4) }} diff --git a/roles/web-app-pihole/README.md b/roles/web-app-pihole/README.md index 1f3b88fe90..c192fda89f 100644 --- a/roles/web-app-pihole/README.md +++ b/roles/web-app-pihole/README.md @@ -18,7 +18,6 @@ The diagram places web-app-pihole in the Infinito.Nexus cosmos: the components i flowchart LR subgraph deps [Dependencies] dep_svc_bkp_volume_2_local["svc-bkp-volume-2-local πŸ’»"] - dep_svc_db_redis["svc-db-redis 🐳🐝"] dep_svc_net_tor["svc-net-tor 🐳🐝"] dep_web_app_dashboard["web-app-dashboard 🐳🐝"] dep_web_app_keycloak["web-app-keycloak 🐳🐝"] @@ -33,7 +32,6 @@ flowchart LR svc_dashboard["dashboard"] svc_matomo["matomo"] svc_email["email ❌"] - svc_redis["redis"] svc_javascript["javascript"] svc_prometheus["prometheus"] svc_tor["tor"] @@ -43,7 +41,6 @@ flowchart LR svc_container_backup["container_backup"] end dep_svc_bkp_volume_2_local -. "0..1" .-> svc_container_backup - dep_svc_db_redis -- "1:1" --> svc_redis dep_svc_net_tor -. "0..1" .-> svc_tor dep_web_app_dashboard -. "0..1" .-> svc_dashboard dep_web_app_keycloak -. "0..1" .-> svc_javascript @@ -53,7 +50,7 @@ flowchart LR dep_web_app_stalwart -- "0..0" --> svc_email dep_web_svc_css -. "0..1" .-> svc_css dep_web_svc_logout -. "0..1" .-> svc_logout - linkStyle 8 stroke:red; + linkStyle 7 stroke:red; ``` Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional (enabled only in matching deployments); red `0..0` edges are turned off in this role. Node markers show the role's deploy modes (πŸ’» host, 🐳 compose, 🐝 swarm); ❌ marks a service that is explicitly turned off, and βš™οΈ an Ansible role dependency declared in `meta/main.yml`. diff --git a/roles/web-app-pihole/meta/services.yml b/roles/web-app-pihole/meta/services.yml index e30e2bd67c..c85d8ff8a9 100644 --- a/roles/web-app-pihole/meta/services.yml +++ b/roles/web-app-pihole/meta/services.yml @@ -21,12 +21,6 @@ email: shared: false # nocheck: dynamic-flag # nocheck: playwright-service-flag -redis: - bond: 1 - enabled: true - shared: true -# nocheck: dynamic-flag -# nocheck: playwright-service-flag javascript: bond: 1 enabled: "{{ 'web-app-keycloak' in group_names }}" diff --git a/roles/web-app-shopware/files/shell/init.sh b/roles/web-app-shopware/files/shell/init.sh index 4a7383182a..f758352a92 100644 --- a/roles/web-app-shopware/files/shell/init.sh +++ b/roles/web-app-shopware/files/shell/init.sh @@ -11,6 +11,7 @@ APP_ROOT="/var/www/html" MARKER="$APP_ROOT/.infinito/installed" LOG_PREFIX="[INIT]" PHP_BIN="php" +PHP_MEMORY_LIMIT="${INIT_PHP_MEMORY_LIMIT:?INIT_PHP_MEMORY_LIMIT must be set}" log() { printf "%s %s\n" "$LOG_PREFIX" "$1"; } fail() { printf "%s [ERROR] %s\n" "$LOG_PREFIX" "$1" >&2; exit 1; } @@ -104,18 +105,18 @@ fi if [ "$FIRST_INSTALL" -eq 1 ]; then log "Performing first-time Shopware installation..." - $PHP_BIN -d memory_limit=1024M bin/console system:install --basic-setup --create-database + $PHP_BIN -d memory_limit="$PHP_MEMORY_LIMIT" bin/console system:install --basic-setup --create-database log "Locking the 'admin' account that --basic-setup creates with the published default password..." DEFAULT_ADMIN_PASSWORD="$($PHP_BIN -r 'echo bin2hex(random_bytes(32));')" - $PHP_BIN -d memory_limit=1024M bin/console user:change-password admin \ + $PHP_BIN -d memory_limit="$PHP_MEMORY_LIMIT" bin/console user:change-password admin \ --password="$DEFAULT_ADMIN_PASSWORD" mkdir -p "$(dirname "$MARKER")" : > "$MARKER" fi log "Running database migrations..." -$PHP_BIN -d memory_limit=1024M bin/console database:migrate --all -$PHP_BIN -d memory_limit=1024M bin/console database:migrate-destructive --all +$PHP_BIN -d memory_limit="$PHP_MEMORY_LIMIT" bin/console database:migrate --all +$PHP_BIN -d memory_limit="$PHP_MEMORY_LIMIT" bin/console database:migrate-destructive --all log "Rebuilding caches and assets..." $PHP_BIN bin/console cache:clear diff --git a/roles/web-app-shopware/meta/services.yml b/roles/web-app-shopware/meta/services.yml index 6aeca33839..2e31a7bd76 100644 --- a/roles/web-app-shopware/meta/services.yml +++ b/roles/web-app-shopware/meta/services.yml @@ -99,7 +99,6 @@ worker: - async - low_priority - --time-limit=300 - - --memory-limit=512M cpus: 1.0 mem_reservation: 1g mem_limit: 2g diff --git a/roles/web-app-shopware/templates/compose.yml.j2 b/roles/web-app-shopware/templates/compose.yml.j2 index 7ee84b255d..e3867b9f80 100644 --- a/roles/web-app-shopware/templates/compose.yml.j2 +++ b/roles/web-app-shopware/templates/compose.yml.j2 @@ -53,6 +53,7 @@ x-environment: &shopware <<: *shopware {{ lookup('compose_only', 'container_name', SHOPWARE_WORKER_CONTAINER) }} entrypoint: {{ SHOPWARE_WORKER_ENTRYPOINT }} + command: ["--memory-limit={{ lookup('service_memory_mb', application_id, service_name, 0.25) }}M"] {{ lookup('depends_on', {'init': 'service_completed_successfully'}) }} {{ lookup('container_healthcheck', service_name) | indent(4) }} {{ lookup('container_volumes', service_name) | indent(4) }} @@ -82,7 +83,7 @@ x-environment: &shopware - discovery.type=single-node - plugins.security.disabled=true - bootstrap.memory_lock=true - - OPENSEARCH_JAVA_OPTS=-Xms{{ SHOPWARE_OPENSEARCH_MEM_RESERVATION }} -Xmx{{ SHOPWARE_OPENSEARCH_MEM_RESERVATION }} + - OPENSEARCH_JAVA_OPTS=-Xms{{ SHOPWARE_OPENSEARCH_HEAP_MB }}m -Xmx{{ SHOPWARE_OPENSEARCH_HEAP_MB }}m ulimits: memlock: { soft: -1, hard: -1 } {{ lookup('depends_on', {'init': 'service_completed_successfully'}) }} diff --git a/roles/web-app-shopware/templates/env.j2 b/roles/web-app-shopware/templates/env.j2 index f0cbf7103c..99b6e59b08 100644 --- a/roles/web-app-shopware/templates/env.j2 +++ b/roles/web-app-shopware/templates/env.j2 @@ -11,6 +11,7 @@ TRUSTED_PROXIES={{ ([networks.internet.values() | select | list, NETWORK_TRUSTED TRUSTED_HOSTS={{ SHOPWARE_DOMAIN }} DATABASE_URL=mysql://{{ lookup('database', application_id, 'username') }}:{{ lookup('database', application_id, 'password') }}@{{ lookup('database', application_id, 'host') }}:{{ lookup('database', application_id, 'port') }}/{{ lookup('database', application_id, 'name') }} +INIT_PHP_MEMORY_LIMIT={{ lookup('service_memory_mb', application_id, 'init', 0.5) }}M {% if SHOPWARE_REDIS_ENABLED | bool %} REDIS_URL={{ SHOPWARE_REDIS_URL }}/0 diff --git a/roles/web-app-shopware/vars/main.yml b/roles/web-app-shopware/vars/main.yml index a60d6a404d..3a5fedff4a 100644 --- a/roles/web-app-shopware/vars/main.yml +++ b/roles/web-app-shopware/vars/main.yml @@ -44,7 +44,7 @@ SHOPWARE_REDIS_URL: "{{ lookup('engine', 'redis', application_id, 'url') }}" SHOPWARE_OPENSEARCH_PORT: "{{ lookup('config', application_id, 'services.opensearch.ports.internal.http') }}" SHOPWARE_OPENSEARCH_ENABLED: "{{ lookup('config', application_id, 'services.opensearch.enabled') }}" SHOPWARE_OPENSEARCH_CONTAINER: "{{ lookup('config', application_id, 'services.opensearch.name') }}" -SHOPWARE_OPENSEARCH_MEM_RESERVATION: "{{ lookup('config', application_id, 'services.opensearch.mem_reservation') }}" +SHOPWARE_OPENSEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, 'opensearch', 0.5) }}" SHOPWARE_OPENSEARCH_INITIAL_ADMIN_PASSWORD: "{{ lookup('config', application_id, 'secrets.credentials.opensearch_initial_admin_password') }}" swarm_stack_fatal_grace: 600 diff --git a/roles/web-app-snipe-it/tasks/01_install.yml b/roles/web-app-snipe-it/tasks/01_install.yml index e7dad621e8..ffe2af0b82 100644 --- a/roles/web-app-snipe-it/tasks/01_install.yml +++ b/roles/web-app-snipe-it/tasks/01_install.yml @@ -41,7 +41,7 @@ -e APP_KEY="{{ SNIPE_IT_APP_KEY }}" -e XDG_CONFIG_HOME=/tmp {{ SNIPE_IT_CONTAINER_ADDRESS }} - php -d memory_limit=512M artisan db:seed --force + php -d memory_limit={{ lookup('service_memory_mb', application_id, SNIPE_IT_SERVICE, 0.25) }}M artisan db:seed --force register: snipeit_seed changed_when: "'Seeding:' in snipeit_seed.stdout" failed_when: snipeit_seed.rc != 0 diff --git a/roles/web-app-snipe-it/templates/env.j2 b/roles/web-app-snipe-it/templates/env.j2 index 4814df58e9..a725042808 100644 --- a/roles/web-app-snipe-it/templates/env.j2 +++ b/roles/web-app-snipe-it/templates/env.j2 @@ -148,5 +148,5 @@ APP_LOCKED=false APP_CIPHER=AES-256-CBC APP_FORCE_TLS={{ lookup('tls', application_id, 'enabled') | string | lower }} GOOGLE_MAPS_API= -LDAP_MEM_LIM=500M +LDAP_MEM_LIM={{ lookup('service_memory_mb', application_id, SNIPE_IT_SERVICE, 0.25) }}M LDAP_TIME_LIM=600 diff --git a/roles/web-app-socialhome/meta/services.yml b/roles/web-app-socialhome/meta/services.yml index 7992c0a1d8..b2252ea28f 100644 --- a/roles/web-app-socialhome/meta/services.yml +++ b/roles/web-app-socialhome/meta/services.yml @@ -13,7 +13,7 @@ socialhome: # nocheck: default-placement-manager embedded sqlite in a node-local volume; no clustered storage placement: manager image: ghcr.io/social-home-io/socialhome - version: "2026.10.4" + version: "2026.10.6" ports: local: http: 8089 diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index e9edc177cb..9f0b082711 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -44,7 +44,7 @@ stalwart: placement: manager image: stalwartlabs/stalwart version: "v0.16.25" - webui_version: "v1.0.5" + webui_version: "v1.0.11" update: key: webui_version type: git_tags diff --git a/roles/web-app-suitecrm/files/Dockerfile b/roles/web-app-suitecrm/files/Dockerfile index cab3b11d0f..681672774b 100644 --- a/roles/web-app-suitecrm/files/Dockerfile +++ b/roles/web-app-suitecrm/files/Dockerfile @@ -4,6 +4,7 @@ ARG SUITECRM_BASE_VERSION FROM ${SUITECRM_BASE_IMAGE}:${SUITECRM_BASE_VERSION} AS base ARG SUITECRM_APP_DIR +ARG SUITECRM_PHP_MEMORY_LIMIT RUN rm -rf /var/lib/apt/lists/* \ && apt-get -o Acquire::Retries=3 update && apt-get -o Acquire::Retries=3 install -y \ @@ -31,11 +32,11 @@ RUN rm -rf /var/lib/apt/lists/* \ ldap \ && rm -rf /var/lib/apt/lists/* -RUN { \ +RUN : "${SUITECRM_PHP_MEMORY_LIMIT:?}" && { \ echo 'file_uploads = On'; \ echo 'upload_max_filesize = 32M'; \ echo 'post_max_size = 32M'; \ - echo 'memory_limit = 512M'; \ + echo "memory_limit = ${SUITECRM_PHP_MEMORY_LIMIT}"; \ } > /usr/local/etc/php/conf.d/suitecrm-upload.ini RUN a2enmod rewrite headers diff --git a/roles/web-app-suitecrm/templates/compose.yml.j2 b/roles/web-app-suitecrm/templates/compose.yml.j2 index d0ce7a9b64..62057023e5 100644 --- a/roles/web-app-suitecrm/templates/compose.yml.j2 +++ b/roles/web-app-suitecrm/templates/compose.yml.j2 @@ -10,6 +10,7 @@ SUITECRM_ENTRYPOINT_SCRIPT_DOCKER: "{{ SUITECRM_ENTRYPOINT_SCRIPT_DOCKER }}" SUITECRM_LDAP_EXTENSION_DIR: "{{ SUITECRM_LDAP_EXTENSION_DIR }}" SUITECRM_APP_DIR: "{{ SUITECRM_APP_DIR }}" + SUITECRM_PHP_MEMORY_LIMIT: "{{ SUITECRM_PHP_MEMORY_LIMIT }}" SUITECRM_SEED_DIR: "{{ SUITECRM_SEED_DIR }}" SUITECRM_WEB_USER: "{{ SUITECRM_WEB_USER }}" SUITECRM_WEB_GROUP: "{{ SUITECRM_WEB_GROUP }}" diff --git a/roles/web-app-suitecrm/vars/main.yml b/roles/web-app-suitecrm/vars/main.yml index f87c7b5368..fca35e9cd1 100644 --- a/roles/web-app-suitecrm/vars/main.yml +++ b/roles/web-app-suitecrm/vars/main.yml @@ -39,3 +39,4 @@ SUITECRM_ENTRYPOINT_SCRIPT_HOST_REL: "volumes/{{ SUITECRM_ENTRYPOINT_SCRIPT_FILE SUITECRM_ENTRYPOINT_SCRIPT_DOCKER: "{{ [ '/usr/local/bin/', SUITECRM_ENTRYPOINT_SCRIPT_FILE ] | path_join }}" SUITECRM_MAX_OLD_SPACE_SIZE: "{{ lookup('node_max_old_space_size', application_id, entity_name) }}" +SUITECRM_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, entity_name, 0.25) }}M" diff --git a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml index 60fd5c6322..a56aa4270f 100644 --- a/roles/web-app-wordpress/meta/addons/mcp-adapter.yml +++ b/roles/web-app-wordpress/meta/addons/mcp-adapter.yml @@ -3,7 +3,7 @@ enabled: "{{ lookup('config', 'web-app-wordpress', 'mcp.enabled') | bool }}" required: true mechanism: plugin source: upstream -version: v0.5.0 +version: v0.7.0 update: monitored: true catalog: github-releases diff --git a/roles/web-app-wordpress/templates/upload.ini.j2 b/roles/web-app-wordpress/templates/upload.ini.j2 index a14ff008b0..e02d303ec0 100644 --- a/roles/web-app-wordpress/templates/upload.ini.j2 +++ b/roles/web-app-wordpress/templates/upload.ini.j2 @@ -1,5 +1,5 @@ file_uploads = On -memory_limit = {{ WORDPRESS_MAX_UPLOAD_SIZE }} +memory_limit = {{ WORDPRESS_PHP_MEMORY_LIMIT }} upload_max_filesize = {{ WORDPRESS_MAX_UPLOAD_SIZE }} post_max_size = {{ WORDPRESS_MAX_UPLOAD_SIZE }} max_execution_time = 300 diff --git a/roles/web-app-wordpress/vars/main.yml b/roles/web-app-wordpress/vars/main.yml index eac46649e7..8e384834a0 100644 --- a/roles/web-app-wordpress/vars/main.yml +++ b/roles/web-app-wordpress/vars/main.yml @@ -5,6 +5,7 @@ entity_name: "{{ application_id | get_entity_name }}" WORDPRESS_URL: "{{ lookup('tls', application_id, 'url.base') }}" WORDPRESS_TITLE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.title') }}" WORDPRESS_MAX_UPLOAD_SIZE: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.max_upload_size') }}" +WORDPRESS_PHP_MEMORY_LIMIT: "{{ lookup('service_memory_mb', application_id, entity_name, 0.25) }}M" WORDPRESS_DOCKER_HTML_PATH: "{{ lookup('volume', 'web-app-wordpress', 'data').target }}" WORDPRESS_DOCKER_CONF_PATH: "{{ WORDPRESS_CONFIG_PATH }}" WORDPRESS_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name ~ '.version') }}" diff --git a/roles/web-app-xwiki/files/extension_installer_b64.groovy b/roles/web-app-xwiki/files/extension_installer_b64.groovy index 631b51497c..4d6e1d45c9 100644 --- a/roles/web-app-xwiki/files/extension_installer_b64.groovy +++ b/roles/web-app-xwiki/files/extension_installer_b64.groovy @@ -20,7 +20,7 @@ wanted.each { e -> if (!id) { println "ERROR::::Empty extension id in wanted list"; return } def already = ext.getInstalledExtension(id, ns) - if (already) { println "ALREADY_INSTALLED::${id}::${already.id?.version}"; return } + if (already && (!ver || already.id?.version?.toString() == ver)) { println "ALREADY_INSTALLED::${id}::${already.id?.version}"; return } println "INSTALL_START::${id}::${ver ? ver : 'latest'}" def job = null @@ -39,7 +39,7 @@ wanted.each { e -> def errMsg = err ? (err?.message ?: err?.toString()) : null def now = ext.getInstalledExtension(id, ns) - if (now) { + if (now && (!ver || now.id?.version?.toString() == ver)) { // Race-safe: Extension Manager can report "Failed to create install plan" // while the extension gets installed by the concurrent distribution job. if (caughtErr) println "WARN::${id}::${caughtErr}" @@ -51,6 +51,6 @@ wanted.each { e -> if (!caughtErr && !errMsg && st && st != 'FINISHED') { println "ERROR::${id}::Unexpected install state ${st}" } - println "INSTALLED_MISSING::${id}" + println now ? "ERROR::${id}::Still on ${now.id?.version}, wanted ${ver}" : "INSTALLED_MISSING::${id}" } } diff --git a/roles/web-app-xwiki/filter_plugins/xwiki_filters.py b/roles/web-app-xwiki/filter_plugins/xwiki_filters.py index 0a914d474d..4b7eea5c69 100644 --- a/roles/web-app-xwiki/filter_plugins/xwiki_filters.py +++ b/roles/web-app-xwiki/filter_plugins/xwiki_filters.py @@ -3,18 +3,18 @@ from __future__ import annotations import re -def xwiki_extension_status(raw: str) -> int: +def xwiki_extension_status(raw: str, version: str = "") -> int: """ Parse the output of the Groovy CheckExtension page. - Strips HTML tags and entities ( ) - - Returns 200 if extension is INSTALLED, otherwise 404 Args: raw: Raw HTTP body from the checker page. + version: The pinned version; empty accepts any installed version. Returns: - 200 if installed, 404 if missing/unknown. + 200 if installed in the pinned version, otherwise 404. """ if raw is None: return 404 @@ -23,7 +23,8 @@ def xwiki_extension_status(raw: str) -> int: text = text.replace(" ", " ").replace("\u00a0", " ") text = text.strip() - if text.startswith("INSTALLED::"): + suffix = f"::{version}" if version else "" + if text.startswith("INSTALLED::") and text.endswith(suffix): return 200 return 404 diff --git a/roles/web-app-xwiki/meta/addons/ai-llm.yml b/roles/web-app-xwiki/meta/addons/ai-llm.yml index 18e7bdec6c..5fa3d267ec 100644 --- a/roles/web-app-xwiki/meta/addons/ai-llm.yml +++ b/roles/web-app-xwiki/meta/addons/ai-llm.yml @@ -5,7 +5,7 @@ mechanism: extension source: upstream bridges: - litellm -version: "0.7" +version: "0.10" update: type: http_regex url: https://maven.xwiki.org/releases/org/xwiki/contrib/llm/application-ai-llm-models-ui/maven-metadata.xml diff --git a/roles/web-app-xwiki/meta/addons/ldap-authenticator.yml b/roles/web-app-xwiki/meta/addons/ldap-authenticator.yml index 3a6372c637..89c20d8112 100644 --- a/roles/web-app-xwiki/meta/addons/ldap-authenticator.yml +++ b/roles/web-app-xwiki/meta/addons/ldap-authenticator.yml @@ -5,7 +5,7 @@ mechanism: extension source: upstream bridges: - ldap -version: "9.15.7" +version: "9.16.6" update: type: http_regex url: https://maven.xwiki.org/releases/org/xwiki/contrib/ldap/ldap-authenticator/maven-metadata.xml diff --git a/roles/web-app-xwiki/meta/addons/oidc-authenticator.yml b/roles/web-app-xwiki/meta/addons/oidc-authenticator.yml index e80ea23ca7..16f95f37ce 100644 --- a/roles/web-app-xwiki/meta/addons/oidc-authenticator.yml +++ b/roles/web-app-xwiki/meta/addons/oidc-authenticator.yml @@ -5,7 +5,7 @@ mechanism: extension source: upstream bridges: - sso -version: "2.19.6" +version: "2.28.1" update: type: http_regex url: https://maven.xwiki.org/releases/org/xwiki/contrib/oidc/oidc-authenticator/maven-metadata.xml diff --git a/roles/web-app-xwiki/tasks/04_extensions.yml b/roles/web-app-xwiki/tasks/04_extensions.yml index f93d0eea3d..75d9d8a3be 100644 --- a/roles/web-app-xwiki/tasks/04_extensions.yml +++ b/roles/web-app-xwiki/tasks/04_extensions.yml @@ -72,6 +72,7 @@ label: "{{ plugin.id }}" vars: ext_id: "{{ plugin.id }}" + ext_version: "{{ plugin.version }}" result_var: "probe_{{ plugin.id | regex_replace('[^A-Za-z0-9_]', '_') }}" - name: "πŸ“Š XWIKI | Collect probe results" @@ -83,11 +84,11 @@ loop_var: plugin changed_when: false -- name: "βœ… XWIKI | Assert all requested extensions are installed" +- name: "βœ… XWIKI | Assert all requested extensions are on their pinned version" vars: missing: "{{ (_xwiki_probe_results | default([])) | selectattr('status','equalto',404) | map(attribute='id') | list }}" fail: - msg: "Missing extensions: {{ missing | join(', ') }}" + msg: "Extensions missing or not on their pinned version: {{ missing | join(', ') }}" when: missing | length > 0 - name: "πŸ—‘οΈ XWIKI | Delete installer page" diff --git a/roles/web-app-xwiki/tasks/_check_extension_via_groovy.yml b/roles/web-app-xwiki/tasks/_check_extension_via_groovy.yml index 5e81389e0c..cbbd210660 100644 --- a/roles/web-app-xwiki/tasks/_check_extension_via_groovy.yml +++ b/roles/web-app-xwiki/tasks/_check_extension_via_groovy.yml @@ -32,7 +32,7 @@ - name: "πŸ’Ύ XWIKI | Save Groovy check result for {{ ext_id }}" set_fact: "{{ result_var }}": - status: "{{ _check_output.content | xwiki_extension_status }}" + status: "{{ _check_output.content | xwiki_extension_status(ext_version) }}" raw: "{{ _check_output.content }}" - name: "πŸ—‘οΈ XWIKI | Delete checker page" diff --git a/roles/web-app-zammad/README.md b/roles/web-app-zammad/README.md index 164a05ae8d..eb01babf80 100644 --- a/roles/web-app-zammad/README.md +++ b/roles/web-app-zammad/README.md @@ -95,6 +95,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - **Mail-to-ticket:** When `web-app-stalwart` is present, the `helpdesk` mailbox is auto-provisioned and Zammad polls it to create tickets from incoming mail. - **Server-name alias:** `zammad.helpdesk.{{ DOMAIN_PRIMARY }}` is a true vhost alias of `helpdesk.{{ DOMAIN_PRIMARY }}` (not a 301 redirect). - **Bundled Elasticsearch:** Search engine ships with the role until a central `svc-db-elasticsearch` exists. +- **Search index per Elasticsearch major:** The index lives in a directory named after the Elasticsearch major inside the `zammad_search` volume. A new major starts on an empty directory and `zammad-init` rebuilds the index from the database on the same deploy. - **Wizard bypass:** First deploy seeds `auto_wizard.json` so no manual setup UI step is required. ## Quick Setup diff --git a/roles/web-app-zammad/files/playwright/test-rest-api-ticket-create.js b/roles/web-app-zammad/files/playwright/test-rest-api-ticket-create.js index ab1c9b92cd..c103b66368 100644 --- a/roles/web-app-zammad/files/playwright/test-rest-api-ticket-create.js +++ b/roles/web-app-zammad/files/playwright/test-rest-api-ticket-create.js @@ -1,7 +1,8 @@ const { test, expect, request } = require("@playwright/test"); +const { resolveTimeout } = require("./timeouts"); exports.register = function (shared) { - test("administrator: REST API POST /api/v1/tickets creates a ticket", async () => { + test("administrator: REST API POST /api/v1/tickets creates a ticket the search finds", async () => { shared.skipUnlessServiceEnabled("sso"); expect(shared.env.adminApiUsername, "ADMIN_USERNAME must be set").toBeTruthy(); expect(shared.env.adminApiPassword, "ADMIN_PASSWORD must be set").toBeTruthy(); @@ -44,6 +45,21 @@ exports.register = function (shared) { const getResp = await api.get(`${shared.env.zammadBaseUrl}/api/v1/tickets/${created.id}`); expect(getResp.status(), "Created ticket must be GETtable").toBeLessThan(300); + const searchUrl = `${shared.env.zammadBaseUrl}/api/v1/tickets/search?query=${encodeURIComponent(subject)}&limit=5`; + await expect + .poll( + async () => { + const found = await api.get(searchUrl); + const body = found.ok() ? await found.json() : []; + return Array.isArray(body) ? body.map((ticket) => ticket.id) : body.tickets || []; + }, + { + timeout: resolveTimeout(120_000), + message: "the search index must return the ticket that was just created", + }, + ) + .toContain(created.id); + await api.dispose(); }); }; diff --git a/roles/web-app-zammad/meta/services.yml b/roles/web-app-zammad/meta/services.yml index 47ccf4032e..bceafa4e8b 100644 --- a/roles/web-app-zammad/meta/services.yml +++ b/roles/web-app-zammad/meta/services.yml @@ -115,7 +115,7 @@ websocket: # nocheck: playwright-service-flag - internal sub-component (bundled search) search: image: docker.elastic.co/elasticsearch/elasticsearch - version: "8.13.4" + version: "9.5.5" update: type: registry_tags image: docker.elastic.co/elasticsearch/elasticsearch diff --git a/roles/web-app-zammad/templates/compose.yml.j2 b/roles/web-app-zammad/templates/compose.yml.j2 index bc0dc5169e..1891a8514c 100644 --- a/roles/web-app-zammad/templates/compose.yml.j2 +++ b/roles/web-app-zammad/templates/compose.yml.j2 @@ -54,7 +54,8 @@ environment: - discovery.type=single-node - xpack.security.enabled=false - - ES_JAVA_OPTS=-Xms512m -Xmx512m + - ES_JAVA_OPTS=-Xms{{ ZAMMAD_SEARCH_HEAP_MB }}m -Xmx{{ ZAMMAD_SEARCH_HEAP_MB }}m + - path.data={{ ZAMMAD_SEARCH_DATA_DIR }} {{ lookup('container_volumes', service_name) | indent(4) }} {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} @@ -65,7 +66,7 @@ {{ lookup('container_image', 'svc-db-memcached', 'memcached') }} {{ lookup('compose_only', 'container_name', ZAMMAD_MEMCACHED_CONTAINER) }} {% include 'roles/sys-svc-container/templates/base.yml.j2' %} - command: ["memcached", "-m", "256"] + command: ["memcached", "-m", "{{ lookup('service_memory_mb', application_id, service_name, 0.125) }}"] {{ lookup('container_extra_hosts') | indent(4) }} {{ lookup('container_networks') | indent(4) }} {% endif %} diff --git a/roles/web-app-zammad/vars/main.yml b/roles/web-app-zammad/vars/main.yml index ad45a8f4c8..8263ec6910 100644 --- a/roles/web-app-zammad/vars/main.yml +++ b/roles/web-app-zammad/vars/main.yml @@ -22,6 +22,9 @@ ZAMMAD_MEMCACHED_CONTAINER: "{{ lookup('engine', 'memcached', application_id, 'c ZAMMAD_RAILS_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_RAILS_SERVICE ~ '.ports.internal.http') }}" ZAMMAD_WEBSOCKET_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_WEBSOCKET_SERVICE ~ '.ports.internal.http') }}" ZAMMAD_SEARCH_PORT: "{{ lookup('config', application_id, 'services.' ~ ZAMMAD_SEARCH_SERVICE ~ '.ports.internal.http') }}" +ZAMMAD_SEARCH_HEAP_MB: "{{ lookup('service_memory_mb', application_id, ZAMMAD_SEARCH_SERVICE, 0.25) }}" +ZAMMAD_SEARCH_MAJOR: "{{ (lookup('config', application_id, 'services.search.version') | string).split('.') | first }}" +ZAMMAD_SEARCH_DATA_DIR: "{{ [lookup('volume', application_id, 'zammad_search').target, ZAMMAD_SEARCH_MAJOR] | path_join }}" # Exception: env.j2 must never set DATABASE_URL. The image's config/pre_initializers/database_url.rb # builds it from POSTGRESQL_* only while DATABASE_URL is blank, so presetting it drops diff --git a/roles/web-svc-collabora/README.md b/roles/web-svc-collabora/README.md index 45b628790e..11d6af36e0 100644 --- a/roles/web-svc-collabora/README.md +++ b/roles/web-svc-collabora/README.md @@ -9,7 +9,7 @@ This Ansible role deploys Collabora Online (CODE) in Docker to enable real-time, * **Dockerized Collabora CODE:** Uses the official `collabora/code` image. * **NGINX Reverse Proxy:** Configures a public-facing proxy with TLS termination and WebSocket support for `/cool/` paths. * **Docker Network Management:** Creates an isolated `/28` subnet for Collabora and connects containers securely. -* **Environment Configuration:** Generates a `.env` file with domain, credentials, and extra parameters for Collabora's WOPI server. +* **Environment Configuration:** Generates a `.env` file that names the Nextcloud origin as the only allowed WOPI host (`aliasgroup1`) and passes the extra parameters to coolwsd. ## Cosmos diff --git a/roles/web-svc-collabora/templates/env.j2 b/roles/web-svc-collabora/templates/env.j2 index f696c1518b..81817edc81 100644 --- a/roles/web-svc-collabora/templates/env.j2 +++ b/roles/web-svc-collabora/templates/env.j2 @@ -1,4 +1,4 @@ {% include 'roles/sys-svc-container/templates/env.j2' %} -domain={{ COLLABORA_ALLOWED_DOMAINS }} -extra_params=--o:ssl.enable=false --o:ssl.termination=true --o:net.service_root=/ --o:net.wopi_allowed_hosts={{ COLLABORA_ALLOWED_HOSTS }} --o:net.post_allow.host[99]={{ networks.internet.ip4 }}/32 +aliasgroup1={{ COLLABORA_WOPI_HOST }} +extra_params=--o:ssl.enable=false --o:ssl.termination={{ lookup('tls', application_id, 'enabled') | lower }} --o:net.service_root=/ --o:net.post_allow.host[99]={{ networks.internet.ip4 }}/32 diff --git a/roles/web-svc-collabora/vars/main.yml b/roles/web-svc-collabora/vars/main.yml index 3def230487..da503f54e2 100644 --- a/roles/web-svc-collabora/vars/main.yml +++ b/roles/web-svc-collabora/vars/main.yml @@ -6,6 +6,6 @@ domain: "{{ lookup('domain',application_id) }}" http_port: "{{ lookup('config', application_id, 'services.collabora.ports.local.http') }}" COLLABORA_CONTAINER: "{{ lookup('config', application_id, 'services.collabora.name') }}" -COLLABORA_ALLOWED_DOMAINS: "(.*\\.|){{ DOMAIN_PRIMARY | regex_replace('\\.', '\\\\.') }}" -COLLABORA_ALLOWED_HOSTS: "{{ lookup('domain','web-app-nextcloud') }}" +COLLABORA_WOPI_HOST: "{{ lookup('tls', lookup('domain', 'web-app-nextcloud'), 'protocols.web') }}://{{ lookup('domain', 'web-app-nextcloud') }}:{{ lookup('tls', lookup('domain', + 'web-app-nextcloud'), 'ports.web') }}" COLLABORA_DISCOVERY_PATH: "/hosting/discovery" diff --git a/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py b/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py index f7269a5a3c..e97744353b 100644 --- a/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py +++ b/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py @@ -22,7 +22,7 @@ import tempfile import unittest from pathlib import Path -from jinja2 import Template +from jinja2 import Template, select_autoescape from utils.cache.files import read_text @@ -62,7 +62,10 @@ class TestSshWrapperRsyncE2E(unittest.TestCase): (self.version_dir / "data" / "file2.txt").write_text("second") self.wrapper = self.work / "wrapper.sh" - rendered = Template(read_text(str(WRAPPER_TEMPLATE))).render( + rendered = Template( + read_text(str(WRAPPER_TEMPLATE)), + autoescape=select_autoescape(default_for_string=False), + ).render( DIR_BACKUPS=str(self.backups), BACKUP_REPOSITORIES=[BACKUP_TYPE], ) diff --git a/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py b/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py index 4ed72e9dd0..e69326de26 100644 --- a/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py +++ b/tests/integration/roles/svc-net-tor/test_container_dns_wiring.py @@ -1,7 +1,7 @@ import unittest from ansible.module_utils.parsing.convert_bool import boolean as ansible_boolean -from jinja2 import Environment, FileSystemLoader +from jinja2 import Environment, FileSystemLoader, select_autoescape from tests.integration.roles import PROJECT_ROOT from utils.cache.files import read_text @@ -37,7 +37,7 @@ def _render_dnsmasq(**overrides): variables.update(overrides) env = Environment( loader=FileSystemLoader(str(PROJECT_ROOT)), - autoescape=False, # noqa: S701 - dnsmasq config, html escaping would corrupt it + autoescape=select_autoescape(), ) template = env.get_template("roles/svc-net-tor/templates/dnsmasq-tor-onion.conf.j2") return template.render(**variables) @@ -146,7 +146,7 @@ class TestStaticBindSurvivesBoot(unittest.TestCase): self.assertLess(names.index(DROPIN_BLOCK), names.index(START_TASK)) reload_expression = start["ansible.builtin.systemd"]["daemon_reload"] - env = Environment(autoescape=False) # noqa: S701 - renders a boolean, not markup + env = Environment(autoescape=select_autoescape(default_for_string=False)) env.filters["bool"] = ansible_boolean env.tests["changed"] = lambda result: bool(result.get("changed", False)) @@ -192,7 +192,7 @@ class TestHostResolver(unittest.TestCase): task = next(t for t in tasks if t.get("name") == RESOLV_TASK) env = Environment( loader=FileSystemLoader(str(PROJECT_ROOT)), - autoescape=False, # noqa: S701 - resolv.conf, html escaping would corrupt it + autoescape=select_autoescape(), ) template = env.get_template( f"roles/svc-net-tor/templates/{task['ansible.builtin.template']['src']}" diff --git a/tests/lint/ansible/jinja/test_shell_templates_are_valid.py b/tests/lint/ansible/jinja/test_shell_templates_are_valid.py index 921e159c9e..be0ac4d734 100644 --- a/tests/lint/ansible/jinja/test_shell_templates_are_valid.py +++ b/tests/lint/ansible/jinja/test_shell_templates_are_valid.py @@ -100,7 +100,7 @@ class TestShellTemplatesAreValid(unittest.TestCase): environment = jinja2.Environment( undefined=_Placeholder, keep_trailing_newline=True, - autoescape=False, # noqa: S701 shell, not markup + autoescape=jinja2.select_autoescape(default_for_string=False), ) environment.filters = _PassthroughFilters(environment.filters) environment.filters["quote"] = shlex.quote diff --git a/tests/lint/ansible/roles/meta/test_role_subnet_pool.py b/tests/lint/ansible/roles/meta/test_role_subnet_pool.py index b18f584947..d45f12251f 100644 --- a/tests/lint/ansible/roles/meta/test_role_subnet_pool.py +++ b/tests/lint/ansible/roles/meta/test_role_subnet_pool.py @@ -37,7 +37,9 @@ def _declared_space() -> tuple[list[ipaddress.IPv4Network], list[str]]: data = load_yaml_any(str(NETWORKS_FILE), default_if_missing={}) or {} pool = data.get("NETWORK_ROLE_SUBNET_POOL") if isinstance(pool, str) and "{{" in pool: - pool = jinja2.Template(pool).render(**data) + pool = jinja2.Template( + pool, autoescape=jinja2.select_autoescape(default_for_string=False) + ).render(**data) roles = data.get("NETWORK_ROLE_SUBNET_EXCEPTION_ROLES") or [] if not isinstance(pool, str) or not isinstance(roles, list): raise TypeError( diff --git a/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py b/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py index 4ad33f9029..f2778df020 100644 --- a/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py +++ b/tests/lint/ansible/roles/meta/test_sso_access_token_optin.py @@ -45,7 +45,6 @@ GATE = PROJECT_ROOT / ( ) _HEADER_RE = re.compile(r"x[-_]forwarded[-_]access[-_]token", re.IGNORECASE) _EMITS_RE = re.compile(r"proxy_set_header|auth_request_set") -_SKIP_DIRS = {".git", "node_modules", "__pycache__"} _TEXT_SUFFIXES = { ".js", ".mjs", diff --git a/tests/lint/ansible/roles/web-app/integration/test_email.py b/tests/lint/ansible/roles/web-app/integration/test_email.py index c5d3e7e2c1..7197c8451b 100644 --- a/tests/lint/ansible/roles/web-app/integration/test_email.py +++ b/tests/lint/ansible/roles/web-app/integration/test_email.py @@ -168,12 +168,6 @@ class TestWebAppRolesIntegrateEmail(unittest.TestCase): missing.append("enabled: true") if not is_explicit_truth(svc.get("shared")): missing.append("shared: true") - if missing: - rel = ( - config.relative_to(root).as_posix() - if config.is_file() - else role_path.relative_to(root).as_posix() - ) if not _role_pins_the_mail_relay(role_path): errors.append( f"[{role_path.name}]: calls lookup('email', ...) but no " diff --git a/tests/lint/ansible/services/test_memory_parameters_use_lookup.py b/tests/lint/ansible/services/test_memory_parameters_use_lookup.py new file mode 100644 index 0000000000..70a725928d --- /dev/null +++ b/tests/lint/ansible/services/test_memory_parameters_use_lookup.py @@ -0,0 +1,546 @@ +"""Lint guard: a known memory parameter MUST follow the container's memory limit. + +A heap, a cache size or a per-request limit written as a literal drifts away +from the ``mem_limit`` its service declares in ``meta/services.yml``: raising +the limit leaves the parameter behind, lowering it lets the process outgrow its +container. Every parameter in ``PARAMETERS`` therefore has to reach +``lookup('service_memory_mb', ...)``, or ``lookup('node_max_old_space_size', ...)`` +for the V8 heap. + +The lookup may sit on the parameter's own line or behind the variables its value +reads. A value reads the names inside its ``{{ }}`` expressions, apart from string +literals, attribute access and filters, and its ``$NAME`` / ``${NAME}`` shell +references. Indirection is followed inside the role and ``group_vars``: a name +counts when one of its definitions (``NAME: value``, ``NAME=value``, +``{% set NAME = value %}``) reaches the lookup, however many names lie between. +A value that keeps a literal fallback (``${NAME:-512M}``, ``... else 512``, +``default(512)``) does not count. + +Only a value that starts like a size is a parameter: a digit, ``{{`` or ``$``. +That leaves prose, probes and the unlimited markers ``-1`` and ``0`` alone. A +block list under ``command:``, ``entrypoint:``, ``argv:``, ``args:`` or ``cmd:``, +a folded scalar, a backslash continuation and an expression wrapped over several +lines are each read as one line, so a flag and its value may be apart. + +A sidecar snippet (``roles//templates/service.yml.j2``) runs in another +role's stack. Its lookups MUST pass ``provider=''``, which keeps the size of +an engine from following the limit of the application it sits beside. + +The scan knows the spellings in ``PARAMETERS`` and the layouts above. A parameter +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.roles.mapping import ROLE_FILE_TEMPL_COMPOSE + +from . import PROJECT_ROOT + +if TYPE_CHECKING: + from collections.abc import Iterator, Mapping, Sequence + +_SEPARATOR = r"""[\]"']*\s*(?:=>?|:|,)?\s*(?:>[+-]?\s+)?(?:value:\s*)?["'\s]*""" +PARAMETERS = ( + r"-Xm[snx]", + r"-XX:(?:Max|Initial)HeapSize=", + r"-XX:MaxDirectMemorySize=", + r"\b\w*HEAP_SIZE" + _SEPARATOR, + r"\b\w*M(?:AX|IN)(?:IMUM)?_MEMORY" + _SEPARATOR, + r"(?i:memory[-_]limit)" + _SEPARATOR, + r"\bwgMemoryLimit" + _SEPARATOR, + r"(?i:memory_consumption)" + _SEPARATOR, + r"\bLDAP_MEM_LIM" + _SEPARATOR, + r"\blimit[-_]memory[-_](?:hard|soft)" + _SEPARATOR, + r"\bmaxmemory" + _SEPARATOR, + r"\bmemcached\b[^&|;]*?[\s\"']-m" + _SEPARATOR, + r"(?(?=\d|\{\{|\$)(?:\{\{.*?\}\}|\$\{[^}]*\}|\S)+)" +) +_UNLIMITED = re.compile(r"0(?![\w.])") +_LOOKUP = re.compile( + r"(?:lookup|query)\(\s*['\"](?:service_memory_mb|node_max_old_space_size)['\"]" +) +_FALLBACK = re.compile(r"\$\{\w+:-\s*[\"']?\d|\belse\s+[\"']?\d|\bdefault\(\s*[\"']?\d") +_EXPRESSION = re.compile(r"\{\{(.*?)\}\}", re.DOTALL) +_NOT_A_NAME = re.compile(r"'[^']*'|\"[^\"]*\"|\.\s*[A-Za-z_]\w*|\|\s*[A-Za-z_]\w*") +_NAME = re.compile(r"[A-Za-z_]\w*") +_SHELL_NAME = re.compile(r"\$\{?([A-Za-z_]\w*)") +_DEFINITION = re.compile( + r"^\s*(?:-\s+)?(?:(?:export|local|readonly|ARG|ENV)\s+)?" + r"[\"']?([A-Za-z_]\w*)[\"']?\s*(?::(?=\s|$)|=)(.*)$" +) +_JINJA_SET = re.compile(r"\{%-?\s*set\s+(\w+)\s*=(.*?)-?%\}") +_BLOCK_SCALAR = re.compile(r"[>|][+-]?\d*") +_ARGV_KEY = re.compile(r"^\s*(?:-\s+)?(?:command|entrypoint|argv|args|cmd)\s*:\s*$") +_FOLDED = re.compile(r":\s*>[+-]?\d*\s*$") +_ITEM = re.compile(r"^\s*-\s+") +_TRAILING_COMMENT = re.compile(r"\s#.*$") +_SIDECAR = re.compile(r"roles/([^/]+)/templates/service\.yml\.j2") +_SIZING = re.compile(r"lookup\(\s*['\"]service_memory_mb['\"][^)]*\)") +_COMMENT = ("#", ";", "//", "{#") +_SHARED_SCOPE = "group_vars" +_WRAP = 20 + + +def _indent(line: str) -> int: + return len(line) - len(line.lstrip()) + + +def _code(lines: Sequence[str]) -> list[str]: + return [_TRAILING_COMMENT.sub("", line) for line in lines] + + +def _open(lines: Sequence[str]) -> bool: + return sum(line.count("{{") for line in lines) > sum( + line.count("}}") for line in lines + ) + + +def _block_end(lines: Sequence[str], start: int) -> int: + end = start + 1 + while end < len(lines) and ( + not lines[end].strip() or _indent(lines[end]) > _indent(lines[start]) + ): + end += 1 + return end + + +def definitions(lines: Sequence[str]) -> Iterator[tuple[str, str]]: + """Yield every ``(name, value)`` a file defines. + + Args: + lines: the file's lines. Trailing comments are cut. A value continues over + the deeper indented lines below its key when it is a YAML block scalar + or leaves a ``{{`` open. + """ + lines = _code(lines) + for number, line in enumerate(lines): + for name, expression in _JINJA_SET.findall(line): + yield name, "{{" + expression + "}}" + match = _DEFINITION.match(line) + if not match: + continue + value = match[2] + if _BLOCK_SCALAR.fullmatch(value.strip()) or _open([value]): + value = " ".join([value, *lines[number + 1 : _block_end(lines, number)]]) + yield match[1], value + + +def references(value: str) -> set[str]: + """Return the names *value* reads. + + Args: + value: text that is rendered later. Names inside ``{{ }}`` and shell + references count; bare words, string literals, attributes and + filters do not. + """ + names = set(_SHELL_NAME.findall(value)) + for expression in _EXPRESSION.findall(value): + names.update(_NAME.findall(_NOT_A_NAME.sub(" ", expression))) + return names + + +def reaches_lookup(value: str, known: Mapping[str, Sequence[str]]) -> bool: + """Whether *value* calls the lookup itself or reads a variable that does. + + Args: + value: the expression a parameter is set to. + known: variable name to every value it is defined with. + """ + pending, seen = [value], set() + while pending: + current = pending.pop() + if _FALLBACK.search(current): + continue + if _LOOKUP.search(current): + return True + for name in references(current) - seen: + seen.add(name) + pending.extend(known.get(name, ())) + return False + + +def _logical_lines(lines: Sequence[str]) -> Iterator[tuple[str, list[int], list[int]]]: + """Yield ``(text, offsets, numbers)``: one logical line and where each source line starts in it. + + Args: + lines: the file's lines, trailing comments already cut. + """ + index = 0 + while index < len(lines): + end = index + 1 + if _ARGV_KEY.match(lines[index]) or _FOLDED.search(lines[index]): + end = _block_end(lines, index) + while ( + end < len(lines) + and end - index < _WRAP + and (lines[end - 1].rstrip().endswith("\\") or _open(lines[index:end])) + ): + end += 1 + text, offsets, numbers = "", [], [] + for number in range(index, end): + piece = lines[number] + if number > index: + piece = _ITEM.sub("", piece).strip() + if piece.startswith(_COMMENT): + continue + offsets.append(len(text)) + numbers.append(number + 1) + text += piece.rstrip("\\") + " " + yield text, offsets, numbers + index = end + + +def parameters(text: str) -> list[tuple[int, str, str]]: + """Return ``(line number, parameter with value, value)`` per known parameter. + + Args: + text: a file's content. Comments and the unlimited marker ``0`` are skipped. + """ + found = [] + for line, offsets, numbers in _logical_lines(_code(text.splitlines())): + if line.lstrip().startswith(_COMMENT): + continue + for match in _PARAMETER.finditer(line): + if not _UNLIMITED.match(match.group("value")): + number = numbers[bisect_right(offsets, match.start()) - 1] + found.append((number, match.group(0), match.group("value"))) + return found + + +def detached(text: str, known: Mapping[str, Sequence[str]]) -> list[tuple[int, str]]: + """Return ``(line number, parameter with value)`` for every parameter that never reaches the lookup. + + Args: + text: a file's content. + known: variable name to every value it is defined with. + """ + return [ + (number, parameter) + for number, parameter, value in parameters(text) + if not reaches_lookup(value, known) + ] + + +def unprovided(rel: str, text: str) -> list[int]: + """Return the lines of a sidecar snippet whose lookup does not name its own role as provider. + + Args: + rel: repository-relative path of the file. + text: its content. + """ + sidecar = _SIDECAR.fullmatch(rel) + if not sidecar: + return [] + provider = re.compile(rf"provider\s*=\s*['\"]{re.escape(sidecar[1])}['\"]") + return [ + number + for number, line in enumerate(text.splitlines(), 1) + for call in _SIZING.findall(line) + if not provider.search(call) + ] + + +def merged(*scopes: Mapping[str, Sequence[str]]) -> dict[str, list[str]]: + """Return one name-to-values map holding every definition of every scope. + + Args: + scopes: name-to-values maps; a name defined in several keeps all its values. + """ + union: dict[str, list[str]] = defaultdict(list) + for scope in scopes: + for name, values in scope.items(): + union[name].extend(values) + return union + + +def _scope(rel: str) -> str: + parts = rel.split("/") + return "/".join(parts[:2]) if parts[0] == "roles" else _SHARED_SCOPE + + +@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"): + continue + try: + texts[rel] = read_text(str(PROJECT_ROOT / rel)) + except (OSError, UnicodeDecodeError): + continue + return texts + + +class TestMemoryParametersUseLookup(unittest.TestCase): + def test_every_memory_parameter_follows_the_container_limit(self) -> None: + texts = _tracked_texts() + index: dict[str, dict[str, list[str]]] = defaultdict(lambda: defaultdict(list)) + for rel, text in texts.items(): + for name, value in definitions(text.splitlines()): + index[_scope(rel)][name].append(value) + known = { + scope: merged(*(index[name] for name in {_SHARED_SCOPE, scope})) + for scope in list(index) + } + + seen = 0 + offenders: list[str] = [] + for rel, text in sorted(texts.items()): + seen += len(parameters(text)) + offenders.extend( + f" {rel}:{number}: {parameter}" + for number, parameter in detached(text, known.get(_scope(rel), {})) + ) + + self.assertGreater(seen, 0, "the scan matched no memory parameter at all") + self.assertFalse( + offenders, + "Memory parameters that do not follow their container's mem_limit " + f"({len(offenders)}):\n" + + "\n".join(offenders) + + "\n\nSet the value with lookup('service_memory_mb', application_id, " + ", ), directly or through a variable of the role.", + ) + + def test_every_sidecar_lookup_names_its_provider(self) -> None: + texts = _tracked_texts() + sized = sum( + len(_SIZING.findall(text)) + for rel, text in texts.items() + if _SIDECAR.fullmatch(rel) + ) + offenders = [ + f" {rel}:{number}" + for rel, text in sorted(texts.items()) + for number in unprovided(rel, text) + ] + + self.assertGreater(sized, 0, "no sidecar snippet sizes memory with the lookup") + self.assertFalse( + offenders, + "Sidecar lookups without provider='':\n" + "\n".join(offenders), + ) + + +class TestResolution(unittest.TestCase): + _SIZED: ClassVar[str] = "{{ lookup('service_memory_mb', 'app', 'php', 0.5) }}" + + def test_literal_is_reported(self) -> None: + self.assertEqual( + detached("ES_JAVA_OPTS=-Xms512m -Xmx512m", {}), + [(1, "-Xms512m"), (1, "-Xmx512m")], + ) + + def test_literal_next_to_a_resolved_value_is_still_reported(self) -> None: + self.assertEqual( + detached("ES_JAVA_OPTS=-Xms512m -Xmx{{ HEAP }}m", {"HEAP": [self._SIZED]}), + [(1, "-Xms512m")], + ) + + def test_direct_lookup_passes(self) -> None: + self.assertEqual(detached(f"memory_limit = {self._SIZED}M", {}), []) + + def test_chain_of_variables_passes(self) -> None: + known = dict( + definitions( + [ + 'PHP_LIMIT="${INIT_LIMIT:?INIT_LIMIT must be set}"', + " INIT_LIMIT: \"{{ ROLE_LIMIT ~ 'M' }}\"", + "ROLE_LIMIT: >-", + " {{ lookup('service_memory_mb', application_id, 'init', 0.5) }}", + ] + ) + ) + self.assertEqual( + detached( + 'php -d memory_limit="$PHP_LIMIT" bin/console', + {k: [v] for k, v in known.items()}, + ), + [], + ) + + def test_variable_that_never_reaches_the_lookup_is_reported(self) -> None: + known = {"A": ["{{ B }}"], "B": ["{{ A }}"], "OTHER": ["512M"]} + self.assertEqual( + detached("--maxmemory {{ A }}mb\nshared_buffers={{ OTHER }}", known), + [(1, "maxmemory {{ A }}mb"), (2, "shared_buffers={{ OTHER }}")], + ) + + def test_a_name_inside_a_string_literal_is_not_followed(self) -> None: + sized = [self._SIZED] + known = {"config": sized, "limit": sized, "int": sized, "item": ["512M"]} + value = "{{ lookup('config', item.limit, 'php.limit') | int }}" + self.assertEqual( + detached(f"PHP_MEMORY_LIMIT={value}", known), + [(1, f"MEMORY_LIMIT={value}")], + ) + + def test_a_literal_fallback_does_not_count(self) -> None: + known = {"INIT": [self._SIZED]} + for line in ( + 'PHP_MEMORY_LIMIT="${INIT:-1024M}"', + "-Xmx{{ INIT if swarm else 512 }}m", + "memory_limit = {{ INIT | default(512) }}M", + ): + with self.subTest(line=line): + self.assertEqual(len(detached(line, known)), 1) + + def test_a_lookup_named_in_a_comment_does_not_count(self) -> None: + known = { + name: [value] + for name, value in definitions( + ["HEAP: 1024 # lookup('service_memory_mb', ...) rounds too low"] + ) + } + self.assertEqual(detached("-Xmx{{ HEAP }}m", known), [(1, "-Xmx{{ HEAP }}m")]) + + def test_a_role_definition_does_not_hide_the_shared_one(self) -> None: + known = merged({"SIZE": [self._SIZED]}, {"SIZE": ["{{ SIZE }}"]}) + self.assertEqual(detached("work_mem={{ SIZE }}", known), []) + + def test_flag_and_value_apart_are_one_parameter(self) -> None: + sized = {"SIZE": [self._SIZED]} + for block, line in ( + ( + ' command:\n - memcached\n - -m\n - "{{ SIZE }}"\n image: x', + 2, + ), + ( + ' argv:\n - redis-server\n - "--maxmemory"\n - "{{ SIZE }}mb"', + 3, + ), + ('command: ["redis-server", "--maxmemory", "{{ SIZE }}mb"]', 1), + ("shell: >-\n redis-server\n --maxmemory\n {{ SIZE }}mb", 3), + ("exec memcached \\\n -m {{ SIZE }} \\\n -p 11211", 1), + ): + with self.subTest(block=block): + self.assertEqual(detached(block, sized), []) + self.assertEqual( + [number for number, _ in detached(block, {"SIZE": ["64"]})], [line] + ) + + def test_a_value_wrapped_over_lines_is_one_value(self) -> None: + wrapped = ( + "X_MEMORY_LIMIT: \"{{ [ (lookup('service_memory_mb', application_id,\n" + " 'php', 0.5) | int), 64 ] | max }}M\"" + ) + for text in (wrapped, f"X_MEMORY_LIMIT: >-\n {self._SIZED}M"): + with self.subTest(text=text): + self.assertEqual(len(parameters(text)), 1) + self.assertEqual(detached(text, {}), []) + self.assertEqual(len(detached("X_MEMORY_LIMIT: >-\n 512M", {})), 1) + + def test_every_spelling_of_a_parameter_is_known(self) -> None: + for line in ( + "php_admin_value[memory_limit] = 1G", + "php_value memory_limit 512M", + "@ini_set('memory_limit', '512M');", + "'memory_limit' => '512M',", + '"memory_limit": "512M",', + '- { key: "WP_MEMORY_LIMIT", value: "256M" }', + '$wgMemoryLimit = "512M";', + "JVM_MAXIMUM_MEMORY: 4096m", + "JICOFO_MAX_MEMORY=3072m", + "ES_HEAP_SIZE=1g", + "JAVA_OPTS=-XX:MaxHeapSize=7g", + "JAVA_OPTS=-Xmn256m", + "LDAP_MEM_LIM=500M", + " - --memory-limit=512M", + 'command: ["--memory-limit", "512M"]', + "opcache.memory_consumption=256", + "limit_memory_hard = 2684354560", + "odoo --limit-memory-hard 2684354560", + ' db_shared_buffers: "4096MB"', + ' - "effective_cache_size=4GB"', + ' - "--innodb-buffer-pool-size=1G"', + "NODE_OPTIONS=--max-old-space-size=4096", + ): + with self.subTest(line=line): + self.assertEqual(len(detached(line, {})), 1) + + def test_unrelated_lines_are_ignored(self) -> None: + for line in ( + " # -Xmx512m", + "; memory_limit = 512M", + "- --maxmemory-policy allkeys-lru", + "- --maxmemory 0", + 'RUN : "${PHP_MEMORY_LIMIT:?}"', + "bootstrap.memory_lock=true", + "mem_limit: 2g", + "network_mem: 512", + "php -d memory_limit=-1 artisan migrate", + "RUN COMPOSER_MEMORY_LIMIT=-1 composer install", + ' - "autovacuum_work_mem=-1"', + "retries: 3 # was php -d memory_limit=512M", + "retries: 3 #was php -d memory_limit=512M", + '- name: "Tune the JVM heap (-Xms/-Xmx)"', + "php -i | grep -E '^memory_limit => '", + 'f"--max-old-space-size={megabytes}"', + "memcached && install -m 0755 /src /dst", + ): + with self.subTest(line=line): + self.assertEqual(detached(line, {}), []) + + +class TestSidecarProvider(unittest.TestCase): + _SNIPPET: ClassVar[str] = "roles/svc-db-redis/templates/service.yml.j2" + + def _line(self, options: str) -> str: + return ( + " - --maxmemory {{ lookup('service_memory_mb', application_id, " + f"'redis', 0.8{options}) }}}}mb" + ) + + def test_a_sidecar_lookup_without_its_own_provider_is_reported(self) -> None: + for options in ( + "", + ", provider='svc-db-memcached'", + ", providr='svc-db-redis'", + ): + with self.subTest(options=options): + self.assertEqual(unprovided(self._SNIPPET, self._line(options)), [1]) + + def test_a_sidecar_lookup_naming_its_role_passes(self) -> None: + line = self._line(", provider='svc-db-redis'") + + self.assertEqual(unprovided(self._SNIPPET, line), []) + + def test_other_files_are_not_sidecars(self) -> None: + path = f"roles/svc-db-redis/{ROLE_FILE_TEMPL_COMPOSE}" + + self.assertEqual(unprovided(path, self._line("")), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/filter/test_dotenv_quote.py b/tests/unit/python/plugins/filter/test_dotenv_quote.py index 9d61bddbdd..f05d3e37da 100644 --- a/tests/unit/python/plugins/filter/test_dotenv_quote.py +++ b/tests/unit/python/plugins/filter/test_dotenv_quote.py @@ -68,7 +68,9 @@ class TestDotenvQuoteModeAware(unittest.TestCase): """ def setUp(self): - env = jinja2.Environment(autoescape=False) # noqa: S701 - test renders a .env value, not HTML + env = jinja2.Environment( + autoescape=jinja2.select_autoescape(default_for_string=False) + ) env.filters["dotenv_quote"] = FilterModule().filters()["dotenv_quote"] self.env = env diff --git a/tests/unit/python/plugins/filter/test_memory_filters.py b/tests/unit/python/plugins/filter/test_memory_filters.py deleted file mode 100644 index 002eecd3fd..0000000000 --- a/tests/unit/python/plugins/filter/test_memory_filters.py +++ /dev/null @@ -1,234 +0,0 @@ -import importlib -import unittest -from unittest.mock import patch - -memory_filters = importlib.import_module("plugins.filter.memory_filters") - - -class TestMemoryFilters(unittest.TestCase): - def setUp(self): - self.apps = {"whatever": True} - self.app_id = "web-app-confluence" # entity_name will be mocked - - # ----------------------------- - # Helpers - # ----------------------------- - def _with_conf(self, mem_limit: str, mem_res: str): - """ - Patch get/get_entity_name so that mem_limit and mem_reservation - can be controlled in tests. - """ - patches = [ - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - mem_limit - if key.endswith(".mem_limit") - else mem_res - if key.endswith(".mem_reservation") - else None - ), - ), - ] - mocks = [p.start() for p in patches] - self.addCleanup(lambda: [p.stop() for p in patches]) - return mocks - - # ----------------------------- - # Tests: jvm_max_mb / jvm_min_mb sizing - # ----------------------------- - def test_sizing_8g_limit_6g_reservation(self): - self._with_conf("8g", "6g") - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertEqual(xmx, 5734) - self.assertEqual(xms, 2867) - - def test_sizing_6g_limit_4g_reservation(self): - self._with_conf("6g", "4g") - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertEqual(xmx, 4300) - self.assertEqual(xms, 2150) - - def test_sizing_16g_limit_12g_reservation_cap_12288(self): - self._with_conf("16g", "12g") - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertEqual(xmx, 11468) - self.assertEqual(xms, 5734) - - def test_floor_small_limit_results_in_min_1024(self): - self._with_conf("1g", "512m") - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - self.assertEqual(xmx, 1024) - - def test_floor_small_reservation_results_in_min_512(self): - self._with_conf("4g", "128m") - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertEqual(xms, 512) - - # ----------------------------- - # Tests: JVM failure cases / validation - # ----------------------------- - def test_invalid_unit_raises(self): - with ( - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "8Q" if key.endswith(".mem_limit") else "4g" - ), - ), - self.assertRaises(memory_filters.AnsibleFilterError), - ): - memory_filters.jvm_max_mb(self.apps, self.app_id) - - def test_zero_limit_raises(self): - with ( - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "0" if key.endswith(".mem_limit") else "4g" - ), - ), - self.assertRaises(memory_filters.AnsibleFilterError), - ): - memory_filters.jvm_max_mb(self.apps, self.app_id) - - def test_zero_reservation_raises(self): - with ( - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "8g" if key.endswith(".mem_limit") else "0" - ), - ), - self.assertRaises(memory_filters.AnsibleFilterError), - ): - memory_filters.jvm_min_mb(self.apps, self.app_id) - - def test_entity_name_is_derived_not_passed(self): - """ - Ensure get_entity_name() is called internally and the app_id is not - passed around manually from the template. - """ - with ( - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ) as mock_entity, - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "8g" if key.endswith(".mem_limit") else "6g" - ), - ), - ): - xmx = memory_filters.jvm_max_mb(self.apps, self.app_id) - xms = memory_filters.jvm_min_mb(self.apps, self.app_id) - self.assertGreater(xmx, 0) - self.assertGreater(xms, 0) - self.assertEqual(mock_entity.call_count, 3) - for call in mock_entity.call_args_list: - self.assertEqual(call.args[0], self.app_id) - - # ----------------------------- - # Tests: redis_maxmemory_mb - # ----------------------------- - def test_redis_maxmemory_default_factor_uses_80_percent_of_limit(self): - self._with_conf("1g", "512m") - maxmem = memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - self.assertEqual(maxmem, 819) - - def test_redis_maxmemory_custom_factor_and_min_mb(self): - self._with_conf("1g", "512m") - maxmem = memory_filters.redis_maxmemory_mb( - self.apps, - self.app_id, - factor=0.5, - min_mb=128, - ) - self.assertEqual(maxmem, 512) - - def test_redis_maxmemory_honors_minimum_floor(self): - self._with_conf("32m", "16m") - maxmem = memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - self.assertEqual(maxmem, 64) - - def test_redis_maxmemory_zero_limit_raises(self): - self._with_conf("0", "512m") - with self.assertRaises(memory_filters.AnsibleFilterError): - memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - - def test_redis_maxmemory_invalid_unit_raises(self): - self._with_conf("8Q", "512m") - with self.assertRaises(memory_filters.AnsibleFilterError): - memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - - def test_redis_maxmemory_does_not_call_get_entity_name(self): - """ - Ensure redis_maxmemory_mb does NOT rely on entity name resolution - (it should always use the hard-coded 'redis' service name). - """ - patches = [ - patch("plugins.filter.memory_filters.get_entity_name"), - patch( - "plugins.filter.memory_filters.get", - side_effect=lambda apps, app_id, key, required=True, **kwargs: ( - "4g" if key.endswith(".mem_limit") else "2g" - ), - ), - ] - mocks = [p.start() for p in patches] - self.addCleanup(lambda: [p.stop() for p in patches]) - - entity_mock = mocks[0] - - maxmem = memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - self.assertEqual(maxmem, 3276) - entity_mock.assert_not_called() - - def test_redis_maxmemory_uses_default_when_mem_limit_missing(self): - """ - When services.redis.mem_limit is not configured, the filter - should fall back to its internal default (256m). - """ - - def fake_get(apps, app_id, key, required=True, **kwargs): - if key.endswith(".mem_limit"): - return kwargs.get("default") - return None - - with ( - patch( - "plugins.filter.memory_filters.get", - side_effect=fake_get, - ), - patch( - "plugins.filter.memory_filters.get_entity_name", - return_value="confluence", - ), - ): - maxmem = memory_filters.redis_maxmemory_mb(self.apps, self.app_id) - - self.assertEqual(maxmem, 204) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_alert_rule_roles.py b/tests/unit/python/plugins/lookup/test_alert_rule_roles.py index 09953d117e..92cf702dbb 100644 --- a/tests/unit/python/plugins/lookup/test_alert_rule_roles.py +++ b/tests/unit/python/plugins/lookup/test_alert_rule_roles.py @@ -17,7 +17,6 @@ import unittest.mock as mock from pathlib import Path import plugins.lookup.alert_rule_roles as module -from plugins.lookup.alert_rule_roles import LookupModule class _Templar: @@ -29,7 +28,7 @@ class _Templar: def _make_lookup(vars_=None): - lm = LookupModule() + lm = module.LookupModule() lm._templar = _Templar(vars_ or {}) lm._loader = mock.MagicMock() return lm diff --git a/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py b/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py index 4cb4765aca..28a633ccec 100644 --- a/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py +++ b/tests/unit/python/plugins/lookup/test_compose_volumes_realign.py @@ -40,7 +40,9 @@ def _render(**answers) -> str: def _lookup(_plugin, _app, key): return values[key] - env = jinja2.Environment(autoescape=False) # noqa: S701 - renders SQL, HTML escaping would corrupt the literals + env = jinja2.Environment( + autoescape=jinja2.select_autoescape(default_for_string=False) + ) return env.from_string(read_text(str(_TEMPLATE))).render( lookup=_lookup, application_id="web-app-x" ) diff --git a/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py b/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py index cfbc4d0e3a..72afc969bf 100644 --- a/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py +++ b/tests/unit/python/plugins/lookup/test_mcp_client_bearer.py @@ -10,8 +10,7 @@ from __future__ import annotations import importlib.util import unittest -from unittest import mock -from unittest.mock import patch +from unittest.mock import MagicMock, patch from ansible.errors import AnsibleError @@ -40,7 +39,7 @@ class TestMcpClientBearerLookup(unittest.TestCase): def _run(self, terms, credential, role_credentials=None, users=None): lookup = self.mod.LookupModule() lookup._templar = _DummyTemplar() - lookup._loader = mock.MagicMock() + lookup._loader = MagicMock() class _StubConfig: def run(self, terms_, variables=None, **kwargs): diff --git a/tests/unit/python/plugins/lookup/test_mcp_credential.py b/tests/unit/python/plugins/lookup/test_mcp_credential.py index fc67f6fb62..4c1b83d4b3 100644 --- a/tests/unit/python/plugins/lookup/test_mcp_credential.py +++ b/tests/unit/python/plugins/lookup/test_mcp_credential.py @@ -9,8 +9,7 @@ from __future__ import annotations import importlib.util import unittest -from unittest import mock -from unittest.mock import patch +from unittest.mock import MagicMock, patch from ansible.errors import AnsibleError @@ -39,7 +38,7 @@ class TestMcpCredentialLookup(unittest.TestCase): def _run(self, terms, owner="mcp-web-app-gitea", users=None): lookup = self.mod.LookupModule() lookup._templar = _DummyTemplar() - lookup._loader = mock.MagicMock() + lookup._loader = MagicMock() class _StubConfig: def run(self, terms_, variables=None, **kwargs): diff --git a/tests/unit/python/plugins/lookup/test_redirect_uris.py b/tests/unit/python/plugins/lookup/test_redirect_uris.py index 9a4772ea9a..ec7d98dc24 100644 --- a/tests/unit/python/plugins/lookup/test_redirect_uris.py +++ b/tests/unit/python/plugins/lookup/test_redirect_uris.py @@ -1,7 +1,7 @@ from __future__ import annotations import unittest -from unittest import mock +import unittest.mock as mock from ansible.errors import AnsibleError diff --git a/tests/unit/python/plugins/lookup/test_service_memory_mb.py b/tests/unit/python/plugins/lookup/test_service_memory_mb.py new file mode 100644 index 0000000000..152eba62ed --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_service_memory_mb.py @@ -0,0 +1,188 @@ +from __future__ import annotations + +import unittest +from unittest.mock import MagicMock, patch + +from ansible.errors import AnsibleError + +from plugins.lookup.service_memory_mb import LookupModule, docker_bytes, share_mb + +_APP = "web-app-demo" +_PROVIDER = "svc-db-cache" + + +class TestDockerBytes(unittest.TestCase): + def test_suffixes_are_binary(self) -> None: + self.assertEqual(docker_bytes("512m"), 512 * 1024**2) + self.assertEqual(docker_bytes("2g"), 2 * 1024**3) + self.assertEqual(docker_bytes("1.5g"), 1536 * 1024**2) + self.assertEqual(docker_bytes("64K"), 64 * 1024) + self.assertEqual(docker_bytes("1gb"), 1024**3) + + def test_a_bare_number_is_bytes(self) -> None: + self.assertEqual(docker_bytes(1048576), 1024**2) + self.assertEqual(docker_bytes("2048"), 2048) + + def test_an_unreadable_size_raises(self) -> None: + for size in ("", "lots", "2x", "-1g", None): + with self.subTest(size=size), self.assertRaises(AnsibleError): + docker_bytes(size) + + +class TestShareMb(unittest.TestCase): + def test_share_of_the_limit_in_whole_mebibytes(self) -> None: + cases = ( + ("2g", 0.5, 1024), + ("4g", 0.5, 2048), + ("8g", 0.7, 5734), + ("8g", 0.35, 2867), + ("6g", 0.7, 4300), + ("512m", 0.8, 409), + ("256m", 0.75, 192), + ("1.5g", 0.5, 768), + ("1g", 1, 1024), + ) + for mem_limit, share, expected in cases: + with self.subTest(mem_limit=mem_limit, share=share): + self.assertEqual(share_mb(mem_limit, share), expected) + + def test_a_share_outside_the_limit_raises(self) -> None: + for share in (0, -0.5, 1.01, "half", None): + with self.subTest(share=share), self.assertRaises(AnsibleError): + share_mb("2g", share) + + def test_a_result_below_one_mebibyte_raises(self) -> None: + with self.assertRaises(AnsibleError): + share_mb("1m", 0.5) + + +class _LookupCase(unittest.TestCase): + def _run( + self, + services: dict, + variables: dict, + terms: list, + provided: dict | None = None, + **kwargs, + ) -> int: + templar = MagicMock() + templar.available_variables = variables + templar.template.side_effect = lambda value: {"{{ HOST }}": "1.5g"}.get( + value, value + ) + applications = MagicMock() + applications.run.return_value = [ + { + _APP: {"services": services}, + _PROVIDER: {"services": provided or {}}, + } + ] + lookup = LookupModule(loader=None, templar=templar) + with patch( + "plugins.lookup.service_memory_mb.lookup_loader.get", + return_value=applications, + ): + return lookup.run(terms, variables=variables, **kwargs)[0] + + +class TestLookupResolvesTheContainerLimit(_LookupCase): + def test_the_named_service_wins(self) -> None: + services = {"search": {"mem_limit": "2g"}, "demo": {"mem_limit": "8g"}} + + self.assertEqual(self._run(services, {}, [_APP, "search", 0.5]), 1024) + + def test_the_primary_entity_backs_an_undeclared_service(self) -> None: + services = {"search": {}, "demo": {"mem_limit": "8g"}} + + self.assertEqual(self._run(services, {}, [_APP, "search", 0.5]), 4096) + + def test_the_host_default_backs_an_undeclared_role(self) -> None: + variables = {"RESOURCE_MEM_LIMIT": "{{ HOST }}"} + + self.assertEqual( + self._run({"search": {}}, variables, [_APP, "search", 0.5]), 768 + ) + + def test_no_limit_anywhere_raises(self) -> None: + with self.assertRaises(AnsibleError): + self._run({"search": {}}, {}, [_APP, "search", 0.5]) + + def test_the_term_count_is_checked(self) -> None: + with self.assertRaises(AnsibleError): + self._run({"search": {"mem_limit": "2g"}}, {}, [_APP, "search"]) + + +class TestProviderCapsAnInheritedLimit(_LookupCase): + def _sidecar( + self, + services: dict, + provided: dict | None = None, + share: float = 0.8, + variables: dict | None = None, + **kwargs, + ) -> int: + if provided is None: + provided = {"cache": {"mem_limit": "512m"}} + return self._run( + services, + variables or {}, + [_APP, "cache", share], + provided=provided, + **(kwargs or {"provider": _PROVIDER}), + ) + + def test_an_inherited_limit_is_capped_at_the_providers(self) -> None: + for inherited, expected in (("4g", 409), ("1g", 409), ("512m", 409)): + with self.subTest(inherited=inherited): + self.assertEqual( + self._sidecar({"demo": {"mem_limit": inherited}}), expected + ) + + def test_a_small_inherited_limit_stays_below_its_own_container(self) -> None: + self.assertEqual(self._sidecar({"demo": {"mem_limit": "256m"}}), 204) + + def test_the_cap_uses_the_share_of_the_call(self) -> None: + self.assertEqual(self._sidecar({"demo": {"mem_limit": "4g"}}, share=0.25), 128) + + def test_the_host_default_is_capped_as_well(self) -> None: + variables = {"RESOURCE_MEM_LIMIT": "{{ HOST }}"} + + self.assertEqual(self._sidecar({}, variables=variables), 409) + + def test_a_declared_limit_is_not_capped(self) -> None: + services = {"cache": {"mem_limit": "1g"}, "demo": {"mem_limit": "4g"}} + + self.assertEqual(self._sidecar(services), 819) + + def test_a_provider_without_a_limit_raises_even_when_nothing_is_capped( + self, + ) -> None: + for services in ( + {"demo": {"mem_limit": "4g"}}, + {"cache": {"mem_limit": "1g"}}, + ): + with self.subTest(services=services), self.assertRaises(AnsibleError): + self._sidecar(services, provided={"cache": {}}) + + def test_only_the_providers_limit_for_that_very_service_counts(self) -> None: + with self.assertRaises(AnsibleError): + self._run( + {"demo": {"mem_limit": "4g"}}, + {}, + [_APP, "store", 0.8], + provided={"cache": {"mem_limit": "512m"}}, + provider=_PROVIDER, + ) + + def test_a_provider_that_is_no_role_raises(self) -> None: + for provider in ("", None, "svc-db-missing"): + with self.subTest(provider=provider), self.assertRaises(AnsibleError): + self._sidecar({"cache": {"mem_limit": "1g"}}, provider=provider) + + def test_a_misspelled_option_raises(self) -> None: + with self.assertRaises(AnsibleError): + self._sidecar({"demo": {"mem_limit": "4g"}}, providr=_PROVIDER) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/agents/test_mcp_tool_filter.py b/tests/unit/python/roles/agents/test_mcp_tool_filter.py index d4d8fa0149..4a09f37952 100644 --- a/tests/unit/python/roles/agents/test_mcp_tool_filter.py +++ b/tests/unit/python/roles/agents/test_mcp_tool_filter.py @@ -20,7 +20,7 @@ import json import unittest import yaml -from jinja2 import Environment, FileSystemLoader +from jinja2 import Environment, FileSystemLoader, select_autoescape from . import PROJECT_ROOT @@ -82,7 +82,9 @@ def _yaml(text: str): def _render(directory, name, **context) -> str: - env = Environment(loader=FileSystemLoader(str(directory)), autoescape=False) # noqa: S701 - renders configuration, not markup + env = Environment( + loader=FileSystemLoader(str(directory)), autoescape=select_autoescape() + ) env.filters.update(_filters()) return env.get_template(name).render(**context) diff --git a/tests/unit/python/roles/agents/test_openclaw_model_provider.py b/tests/unit/python/roles/agents/test_openclaw_model_provider.py index d7939d8710..4ce39d8ee8 100644 --- a/tests/unit/python/roles/agents/test_openclaw_model_provider.py +++ b/tests/unit/python/roles/agents/test_openclaw_model_provider.py @@ -16,7 +16,7 @@ import importlib.util import json import unittest -from jinja2 import Environment, FileSystemLoader +from jinja2 import Environment, FileSystemLoader, select_autoescape from . import PROJECT_ROOT @@ -51,7 +51,9 @@ def _render(**overrides) -> dict: Args: overrides: context values replacing the defaults. """ - env = Environment(loader=FileSystemLoader(str(OPENCLAW)), autoescape=False) # noqa: S701 - renders configuration, not markup + env = Environment( + loader=FileSystemLoader(str(OPENCLAW)), autoescape=select_autoescape() + ) env.filters.update(_filters()) return json.loads( env.get_template("openclaw.json.j2").render(**{**CONTEXT, **overrides}) diff --git a/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py b/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py index e1728d0e72..3f21f05fe5 100644 --- a/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py +++ b/tests/unit/python/roles/svc-ai-litellm/templates/test_config_model_list.py @@ -12,7 +12,7 @@ from __future__ import annotations import unittest import yaml -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -72,7 +72,10 @@ def render(*, ollama=(), lmstudio=(), keys=None): lmstudio: preload entries svc-ai-lmstudio declares; empty means not deployed. keys: env-name -> provider key for the remote backends. """ - env = Environment(undefined=StrictUndefined, autoescape=False) # noqa: S701 - YAML, not markup + env = Environment( + undefined=StrictUndefined, + autoescape=select_autoescape(default_for_string=False), + ) env.filters["bool"] = _ansible_bool rendered = env.from_string(read_text(str(TEMPLATE))).render( LITELLM_OLLAMA_BACKEND=str(bool(ollama)), diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py index 376ac03ab3..c04c092e7a 100644 --- a/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/files/test_policy.py @@ -4,6 +4,7 @@ from __future__ import annotations import importlib.util import json +import time import unittest from . import PROJECT_ROOT @@ -234,6 +235,26 @@ class TestDeclaredArguments(unittest.TestCase): self.assertEqual("GET", method) +class TestPathArguments(unittest.TestCase): + def call(self, **arguments): + return policy.authorize_call(contract(), "checkmk_get_host_status", arguments) + + def test_a_value_made_only_of_dots_is_refused(self): + for dots in range(4): + with self.subTest(dots=dots): + with self.assertRaises(PermissionError) as caught: + self.call(host="." * dots) + self.assertIn(policy.DENY_PATH_ARGUMENT, str(caught.exception)) + + def test_dots_inside_a_segment_pass(self): + for value in ("web-01.example", "..web", "web.."): + with self.subTest(value=value): + self.call(host=value) + + def test_a_query_argument_may_be_made_only_of_dots(self): + self.call(host="web-01", columns="." * 2) + + RANGE_TOOLS = { "prometheus_query_range": { "method": "GET", @@ -326,6 +347,22 @@ class TestDurationGrammar(unittest.TestCase): with self.assertRaises(ValueError): policy.parse_duration("1h30") + def test_anything_but_number_unit_pairs_is_refused(self): + for text in ("", "h", "1hh", "1.5h", "-1h", "1 h", "1sm", "abc"): + with self.subTest(text=text), self.assertRaises(ValueError): + policy.parse_duration(text) + + def test_a_long_digit_run_is_refused_in_linear_time(self): + started = time.monotonic() + with self.assertRaises(ValueError): + policy.parse_duration("0" * 20_000 + "!") + self.assertLess( + time.monotonic() - started, + 1.0, + "parsing must not rescan the digit run from every start position; " + "a backtracking pattern needs several seconds for this input", + ) + class TestAudit(unittest.TestCase): def test_the_event_names_both_sides_and_the_outcome(self): diff --git a/tests/unit/python/roles/svc-net-firewall/test_fragments.py b/tests/unit/python/roles/svc-net-firewall/test_fragments.py index 99152196b5..ecadb860ef 100644 --- a/tests/unit/python/roles/svc-net-firewall/test_fragments.py +++ b/tests/unit/python/roles/svc-net-firewall/test_fragments.py @@ -129,7 +129,7 @@ def _render(path: str, mode: str = "swarm") -> str: environment = jinja2.Environment( keep_trailing_newline=True, trim_blocks=True, - autoescape=False, # noqa: S701 nftables, not markup + autoescape=jinja2.select_autoescape(default_for_string=False), ) return environment.from_string(read_text(path)).render( DEPLOYMENT_MODE=mode, **COMMON diff --git a/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py b/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py index 67634ed302..a64c68528e 100644 --- a/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py +++ b/tests/unit/python/roles/svc-net-tor-smtp/files/test_tor_smtp_gateway.py @@ -14,7 +14,7 @@ import os import sys import types import unittest -from unittest import mock +import unittest.mock as mock from . import PROJECT_ROOT diff --git a/tests/unit/python/roles/svc-net-tor/test_chutney_worker_check.py b/tests/unit/python/roles/svc-net-tor/test_chutney_worker_check.py new file mode 100644 index 0000000000..b520ffe58e --- /dev/null +++ b/tests/unit/python/roles/svc-net-tor/test_chutney_worker_check.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import os +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +from . import PROJECT_ROOT + +TEST_SH = PROJECT_ROOT / "roles" / "svc-net-tor" / "files" / "test" / "test.sh" +BOUNDED = "DataDirectory /data\nNumCPUs 1\n" +UNBOUNDED = "DataDirectory /data\n" +CONTAINER_STUB = """\ +in_container=/opt/chutney/net/nodes +exec sh -c "${5//"${in_container}"/"${NODES_DIR}"}" +""" + + +def _stub(path: Path, body: str) -> None: + path.write_text(f"#!/usr/bin/env bash\n{body}\n", encoding="utf-8") + path.chmod(0o755) + + +def _run( + torrcs: dict[str, str], flavor: str = "chutney", unreadable: str = "" +) -> subprocess.CompletedProcess[str]: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + nodes = root / "nodes" + nodes.mkdir() + for node, torrc in torrcs.items(): + (nodes / node).mkdir() + (nodes / node / "torrc").write_text(torrc, encoding="utf-8") + if unreadable: + (nodes / unreadable / "torrc").mkdir(parents=True) + shutil.copy(TEST_SH, root / "test.sh") + _stub(root / "onion_ports.py", "exit 0") + bin_dir = root / "bin" + bin_dir.mkdir() + _stub(bin_dir / "curl", "printf 200") + _stub(bin_dir / "container", CONTAINER_STUB) + return subprocess.run( + ["bash", str(root / "test.sh"), "example.onion"], + env={ + "PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}", + "NODES_DIR": str(nodes), + "TOR_SOCKS": "127.0.0.1:9050", + "NGINX_SERVERS_DIR": str(root), + "RETRIES": "1", + "SLEEP_SECONDS": "0", + "TOR_DNSMASQ_CONF": str(root / "tor-onion.conf"), + "TOR_CONTAINER": "tor", + "TOR_FLAVOR": flavor, + }, + capture_output=True, + text=True, + check=False, + ) + + +def _verdict(result: subprocess.CompletedProcess[str]) -> str: + return result.stdout.splitlines()[-1] + + +class TestChutneyWorkerCheck(unittest.TestCase): + def test_nodes_that_all_carry_the_limit_pass(self) -> None: + result = _run({"000a": BOUNDED, "001a": BOUNDED}) + self.assertEqual(_verdict(result), "[OK] every chutney node runs one worker") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_a_node_without_the_limit_is_named_and_fails(self) -> None: + result = _run({"000a": BOUNDED, "001a": UNBOUNDED}) + self.assertIn("start one worker per host core", _verdict(result)) + self.assertTrue(_verdict(result).endswith("/001a/torrc"), _verdict(result)) + self.assertNotIn("000a", _verdict(result)) + self.assertEqual(result.returncode, 1) + + def test_nodes_that_all_lack_the_limit_fail(self) -> None: + result = _run({"000a": UNBOUNDED, "001a": UNBOUNDED}) + self.assertIn("/000a/torrc", _verdict(result)) + self.assertIn("/001a/torrc", _verdict(result)) + self.assertEqual(result.returncode, 1) + + def test_no_torrc_to_inspect_fails(self) -> None: + result = _run({}) + self.assertEqual( + _verdict(result), "[FAIL] cannot read the chutney node torrcs in tor" + ) + self.assertEqual(result.returncode, 1) + + def test_a_torrc_that_cannot_be_read_fails_beside_bounded_nodes(self) -> None: + result = _run({"000a": BOUNDED}, unreadable="001a") + self.assertEqual( + _verdict(result), "[FAIL] cannot read the chutney node torrcs in tor" + ) + self.assertEqual(result.returncode, 1) + + def test_the_public_flavor_does_not_run_the_check(self) -> None: + result = _run({}, flavor="public") + self.assertEqual(_verdict(result), "[INFO] 1 probed, 0 failed") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-net-tor/test_egress_clients.py b/tests/unit/python/roles/svc-net-tor/test_egress_clients.py index 52a558a9a9..7b04c193dd 100644 --- a/tests/unit/python/roles/svc-net-tor/test_egress_clients.py +++ b/tests/unit/python/roles/svc-net-tor/test_egress_clients.py @@ -16,7 +16,7 @@ from __future__ import annotations import importlib.util import sys import unittest -from unittest import mock +import unittest.mock as mock import jinja2 @@ -46,7 +46,9 @@ class _Templar: def template(self, value): return ( - jinja2.Environment(autoescape=False) # noqa: S701 - renders CIDRs, not markup + jinja2.Environment( + autoescape=jinja2.select_autoescape(default_for_string=False) + ) .from_string(str(value)) .render(**self.available_variables) ) diff --git a/tests/unit/python/roles/svc-net-tor/test_extra_ports.py b/tests/unit/python/roles/svc-net-tor/test_extra_ports.py index 4deb747de1..98528445a8 100644 --- a/tests/unit/python/roles/svc-net-tor/test_extra_ports.py +++ b/tests/unit/python/roles/svc-net-tor/test_extra_ports.py @@ -16,8 +16,8 @@ from __future__ import annotations import importlib.util import sys import unittest +import unittest.mock as mock from typing import Any -from unittest import mock from ansible.errors import AnsibleError diff --git a/tests/unit/python/roles/svc-net-tor/test_test_env_sourcing.py b/tests/unit/python/roles/svc-net-tor/test_test_env_sourcing.py index e0a3f8ed8c..ddb45113bd 100644 --- a/tests/unit/python/roles/svc-net-tor/test_test_env_sourcing.py +++ b/tests/unit/python/roles/svc-net-tor/test_test_env_sourcing.py @@ -26,6 +26,7 @@ PORTS = [25, 80, 587] def _lookup(name: str, *_args: str) -> object: return { "config": "example.onion", + "container_address": "tor", "nginx": "/etc/nginx/conf.d/servers", "tor_ports": [ {"onion_port": port, "target": f"127.0.0.1:{port}"} for port in PORTS @@ -42,8 +43,10 @@ def _render(mode: str) -> str: env.filters.update(FilterModule().filters()) return env.from_string(read_text(str(TEMPLATE))).render( lookup=_lookup, + application_id="svc-net-tor", DEPLOYMENT_MODE=mode, TOR_DNSMASQ_CONF="/etc/dnsmasq.d/tor-onion.conf", + TOR_FLAVOR="chutney", ) diff --git a/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py b/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py index 3e7e435f11..43acfc794f 100644 --- a/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py +++ b/tests/unit/python/roles/sys-svc-mail-msmtp/test_msmtprc_ca_trust.py @@ -18,7 +18,7 @@ import re import unittest from typing import Any, ClassVar -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -46,7 +46,7 @@ def _env() -> Environment: trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - a config file, and Ansible's templar does not escape either + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool env.filters["on_off"] = lambda value: "on" if value else "off" diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py index 8c6880baec..ee2610af0a 100644 --- a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py +++ b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_edge_limits.py @@ -12,7 +12,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from utils.cache.applications import get_application_defaults from utils.cache.yaml import load_yaml @@ -44,7 +44,7 @@ def render(name: str, **context) -> str: env = Environment( loader=FileSystemLoader(str(TEMPLATE_DIR)), undefined=StrictUndefined, - autoescape=False, # noqa: S701 - nginx config, not markup; Ansible renders it the same way and HTML-escaping `$binary_remote_addr` would break it + autoescape=select_autoescape(), ) return env.get_template(name).render(**context) diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py index cc2eaea1c3..7d2a7611e6 100644 --- a/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py +++ b/tests/unit/python/roles/sys-svc-proxy/templates/test_mcp_vhost_exposure.py @@ -22,7 +22,7 @@ from __future__ import annotations import re import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from utils.cache.yaml import load_yaml from utils.roles.mapping import ROLE_FILE_META_MCP @@ -80,7 +80,7 @@ def render(role: str, *, exposure: str, sso_gated: bool = False) -> str: env = Environment( loader=FileSystemLoader(str(TEMPLATE_DIR)), undefined=StrictUndefined, - autoescape=False, # noqa: S701 - nginx config, not markup; HTML-escaping would corrupt the directives + autoescape=select_autoescape(), ) env.filters["regex_replace"] = lambda value, pattern, repl="": re.sub( pattern, repl, value diff --git a/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py b/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py index f4fdf6163f..70086add9d 100644 --- a/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py +++ b/tests/unit/python/roles/test-e2e-cli/files/shared/mcp/test_contract.py @@ -659,5 +659,79 @@ class TestSseSessionProbe(unittest.TestCase): self.assertIn("absent from the probed URL", stderr.getvalue()) +NEGOTIATED = "2025-03-26" + + +class StrictProvider: + def __init__(self): + self.seen = [] + self._server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler()) + threading.Thread(target=self._server.serve_forever, daemon=True).start() + + @property + def url(self): + host, port = self._server.server_address[:2] + return f"http://{host}:{port}/mcp" + + def stop(self): + self._server.shutdown() + self._server.server_close() + + def _handler(self): + provider = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length", "0")) + payload = json.loads(self.rfile.read(length) or b"{}") + method = payload.get("method") + version = self.headers.get("MCP-Protocol-Version") + status, answer = 200, {"jsonrpc": "2.0", "id": payload.get("id")} + if self.headers.get("Authorization") != "Bearer real": + status, answer["error"] = 401, {"code": -32001, "message": "no"} + elif method == "initialize": + answer["result"] = {"protocolVersion": NEGOTIATED} + elif version != NEGOTIATED: + status = 400 + answer["error"] = { + "code": -32600, + "message": "MCP-Protocol-Version header is required", + } + elif method == "tools/list": + answer["result"] = { + "tools": [{"name": "a_get"}, {"name": "a_list"}] + } + else: + answer["result"] = {"isError": False, "content": []} + if method != "initialize": + provider.seen.append((method, version)) + body = json.dumps(answer).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + return Handler + + +class TestProtocolVersionHeader(unittest.TestCase): + def test_every_request_after_initialize_names_the_negotiated_version(self): + provider = StrictProvider() + self.addCleanup(provider.stop) + load({"MCP_URL": provider.url}).main() + self.assertEqual( + provider.seen, + [ + ("notifications/initialized", NEGOTIATED), + ("tools/list", NEGOTIATED), + ("tools/call", NEGOTIATED), + ], + ) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py b/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py index 4fb7076704..d924d3c71b 100644 --- a/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py +++ b/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py @@ -2,7 +2,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment +from jinja2 import Environment, select_autoescape from utils.cache.yaml import load_yaml_any @@ -21,9 +21,9 @@ def until_expression() -> str: def settles(result: dict) -> bool: - template = Environment(autoescape=False).from_string( # noqa: S701 - ansible condition, not markup - "{{ " + until_expression() + " }}" - ) + template = Environment( + autoescape=select_autoescape(default_for_string=False) + ).from_string("{{ " + until_expression() + " }}") return template.render(_wait_result=result) == "True" diff --git a/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py b/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py index 4198036cc3..ac76ffb055 100644 --- a/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py +++ b/tests/unit/python/roles/web-app-gitlab/test_smtp_settings.py @@ -17,7 +17,7 @@ from __future__ import annotations import re import unittest -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -50,7 +50,7 @@ def _render(email: dict, ca_file: str = "") -> str: trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - a Ruby config file, and Ansible's templar does not escape either + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool env.filters["ruby_dq"] = lambda value: '"' + str(value).replace('"', '\\"') + '"' diff --git a/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py b/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py index 008a48bd8f..249189de47 100644 --- a/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py +++ b/tests/unit/python/roles/web-app-keycloak/templates/test_realm_import_json.py @@ -5,7 +5,7 @@ import json import re import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from . import PROJECT_ROOT @@ -102,7 +102,7 @@ def render(saml_apps: list[str], client_apps: list[str] | None = None) -> str: trim_blocks=True, keep_trailing_newline=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - renders JSON, where HTML escaping corrupts the value + autoescape=select_autoescape(), ) env.filters["path_join"] = path_join env.filters["to_json"] = json.dumps 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 new file mode 100644 index 0000000000..927e3ff774 --- /dev/null +++ b/tests/unit/python/roles/web-app-keycloak/test_async_kcadm_jobs.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +import re +import unittest + +from utils.cache.files import PROJECT_ROOT, iter_project_files +from utils.cache.yaml import load_yaml_any + +TASKS_DIR = str(PROJECT_ROOT / "roles/web-app-keycloak/tasks") + "/" +LOCK_RETRYING_MODULE = "keycloak_kcadm_update" +SET_FACT_MODULES = ("set_fact", "ansible.builtin.set_fact") + + +def tasks_of(node): + for task in node or []: + if not isinstance(task, dict): + continue + yield task + for nested in ("block", "rescue", "always"): + yield from tasks_of(task.get(nested)) + + +def role_tasks(): + for path in iter_project_files(extensions=(".yml",)): + if path.startswith(TASKS_DIR): + for task in tasks_of(load_yaml_any(path)): + yield path[len(TASKS_DIR) :], task + + +def async_kcadm_jobs(): + for path, task in role_tasks(): + if "async" in task and "kcadm" in str(task).lower(): + yield f"{path}: {task.get('name')}", task + + +def reaped_expressions() -> list[str]: + return [ + str(task["vars"]["async_reap_jobs"]) + for _path, task in role_tasks() + if "async_reap_jobs" in (task.get("vars") or {}) + ] + + +def collected_facts() -> dict[str, str]: + facts: dict[str, str] = {} + for _path, task in role_tasks(): + for module in SET_FACT_MODULES: + for name, value in (task.get(module) or {}).items(): + facts[name] = str(value) + return facts + + +def names(variable: str, expression: str) -> bool: + return re.search(rf"\b{re.escape(variable)}\b", expression) is not None + + +def reaches_a_reap(result: str, facts: dict[str, str], reaped: list[str]) -> bool: + carriers = [ + result, + *(fact for fact, source in facts.items() if names(result, source)), + ] + return any( + names(carrier, expression) for carrier in carriers for expression in reaped + ) + + +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): + self.assertIn( + LOCK_RETRYING_MODULE, + task, + "kcadm gives up its config lock to a concurrent kcadm at once; " + "only keycloak_kcadm_update repeats such a call, so no other " + "kcadm task may run async", + ) + + def test_every_async_kcadm_job_is_registered_for_the_reap(self): + for label, task in async_kcadm_jobs(): + with self.subTest(task=label): + self.assertIn( + "register", + task, + "an async job without a register cannot be reaped, so nobody " + "sees it fail", + ) + + def test_every_registered_async_kcadm_result_reaches_a_reap(self): + reaped = reaped_expressions() + facts = collected_facts() + for label, task in async_kcadm_jobs(): + with self.subTest(task=label): + self.assertTrue( + reaches_a_reap(task["register"], facts, reaped), + f"'{task['register']}' is registered and never handed to " + "async_reap_jobs, directly or through a collected list, so the " + "reap neither polls the job nor sees it fail", + ) + + def test_a_result_that_is_never_collected_does_not_reach_the_reap(self): + reaped = ["{{ kc_declared_client_jobs | default([]) }}"] + self.assertFalse(reaches_a_reap("kc_declared_client", {}, reaped)) + self.assertTrue( + reaches_a_reap( + "kc_declared_client", + {"kc_declared_client_jobs": "{{ [kc_declared_client] }}"}, + reaped, + ) + ) + + def test_a_collected_list_that_no_reap_consumes_does_not_count(self): + facts = {"kc_declared_client_jobs": "{{ [kc_declared_client] }}"} + self.assertFalse(reaches_a_reap("kc_declared_client", facts, [])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-moodle/__init__.py b/tests/unit/python/roles/web-app-moodle/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-moodle/files/__init__.py b/tests/unit/python/roles/web-app-moodle/files/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-moodle/files/build/__init__.py b/tests/unit/python/roles/web-app-moodle/files/build/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py b/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py new file mode 100644 index 0000000000..9ed0c5bcb0 --- /dev/null +++ b/tests/unit/python/roles/web-app-moodle/files/build/test_moodle_entrypoint.py @@ -0,0 +1,124 @@ +import os +import pwd +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +from utils import PROJECT_ROOT +from utils.cache.files import read_text + +ENTRYPOINT = PROJECT_ROOT / "roles/web-app-moodle/files/build/moodle-entrypoint.sh" + +FPM_STUB = "#!/usr/bin/env bash\nexit 0\n" + +LAYOUT_4 = {"version.php": "4.5.11", "auth/oidc/version.php": "4.5.8"} +LAYOUT_5 = {"public/version.php": "5.3.0", "public/auth/oidc/version.php": "5.2.1"} + + +class TestMoodleEntrypoint(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.source = self.root / "source" + self.code = self.root / "code" + bin_dir = self.root / "bin" + bin_dir.mkdir() + stub = bin_dir / "php-fpm" + stub.write_text(FPM_STUB) + stub.chmod(0o755) + self.env = dict(os.environ) + self.env.update( + PATH=f"{bin_dir}{os.pathsep}{self.env['PATH']}", + MOODLE_CODE_DIR=str(self.code), + MOODLE_DATA_DIR=str(self.root / "data"), + MOODLE_LOCAL_CACHE_DIR=str(self.root / "localcache"), + MOODLE_SOURCE_DIR=str(self.source), + MOODLE_RUNTIME_USER=pwd.getpwuid(os.getuid()).pw_name, + MOODLE_VERSION_FILE="public/version.php", + ) + + def write(self, tree, files): + for name, content in files.items(): + path = tree / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + + def ship(self, files): + shutil.rmtree(self.source, ignore_errors=True) + self.write(self.source, files) + + def run_entrypoint(self, release): + return subprocess.run( + ["bash", str(ENTRYPOINT), "php-fpm"], + env={**self.env, "MOODLE_RELEASE": release}, + capture_output=True, + text=True, + check=False, + ) + + def start(self, release): + done = self.run_entrypoint(release) + self.assertEqual(done.returncode, 0, done.stderr) + + def shipped_files_in_the_volume(self): + return { + name for name in {*LAYOUT_4, *LAYOUT_5} if (self.code / name).is_file() + } + + def test_the_first_start_fills_the_code_volume(self): + self.ship(LAYOUT_5) + self.start("5.3.0") + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + + def test_a_restart_on_the_same_release_keeps_what_the_volume_holds(self): + self.ship(LAYOUT_5) + self.start("5.3.0") + added = {"public/local/extra/version.php": "added after the bootstrap"} + self.write(self.code, added) + self.start("5.3.0") + self.assertTrue((self.code / "public/local/extra/version.php").is_file()) + + def test_another_release_replaces_the_tree_and_drops_what_it_no_longer_ships(self): + self.ship(LAYOUT_4) + self.start("4.5.11") + self.ship(LAYOUT_5) + self.start("5.3.0") + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + + def test_a_volume_the_previous_entrypoint_marked_done_is_replaced(self): + self.write(self.code, LAYOUT_4) + (self.code / ".bootstrap.done").touch() + self.ship(LAYOUT_5) + self.start("5.3.0") + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + + def test_a_missing_source_tree_fails_and_leaves_the_volume_unmarked(self): + done = self.run_entrypoint("5.3.0") + self.assertNotEqual(done.returncode, 0) + self.assertFalse((self.code / ".bootstrap.done").exists()) + + def test_a_failed_copy_keeps_the_tree_the_volume_held(self): + self.ship(LAYOUT_4) + self.start("4.5.11") + shutil.rmtree(self.source) + done = self.run_entrypoint("5.3.0") + self.assertNotEqual(done.returncode, 0) + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_4)) + self.assertEqual(read_text(str(self.code / ".bootstrap.done")), "4.5.11") + + def test_an_image_older_than_the_recorded_release_refuses_to_replace_it(self): + self.ship(LAYOUT_5) + self.start("5.10.0") + self.ship(LAYOUT_4) + done = self.run_entrypoint("5.9.2") + self.assertNotEqual(done.returncode, 0) + self.assertIn("5.10.0", done.stderr) + self.assertEqual(self.shipped_files_in_the_volume(), set(LAYOUT_5)) + self.assertEqual(read_text(str(self.code / ".bootstrap.done")), "5.10.0") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-odoo/__init__.py b/tests/unit/python/roles/web-app-odoo/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-odoo/test_addon_manifest_version.py b/tests/unit/python/roles/web-app-odoo/test_addon_manifest_version.py new file mode 100644 index 0000000000..e379a4ed49 --- /dev/null +++ b/tests/unit/python/roles/web-app-odoo/test_addon_manifest_version.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import ast +import unittest + +from utils.cache.files import PROJECT_ROOT, read_text + +MANIFEST = ( + PROJECT_ROOT / "roles/web-app-odoo/files/addons/auth_oauth_https/__manifest__.py" +) + + +def manifest_version() -> str: + return ast.literal_eval(read_text(str(MANIFEST)))["version"] + + +def installable_on(series: str, version: str) -> bool: + parts = version.split(".") + if not 2 <= len(parts) <= 5 or not all(part.isdigit() for part in parts): + return False + if len(parts) <= 3 and not version.startswith(series): + version = f"{series}.{version}" + return version.startswith(series + ".") + + +class TestAddonManifestVersion(unittest.TestCase): + def test_odoo_installs_the_addon_on_every_series(self): + for series in ("19.0", "20.0", "21.0"): + with self.subTest(series=series): + self.assertTrue( + installable_on(series, manifest_version()), + f"Odoo {series} marks a module whose version names another " + "series as not installable and only warns about it; keep the " + "version in the form x.y.z so Odoo prefixes its own series", + ) + + def test_a_version_that_names_a_series_is_refused_by_the_next_one(self): + self.assertTrue(installable_on("19.0", "19.0.1.8.0")) + self.assertFalse(installable_on("20.0", "19.0.1.8.0")) + + +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 4beccfb7b3..582607a82d 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 @@ -12,7 +12,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment, FileSystemLoader, StrictUndefined +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any @@ -44,7 +44,7 @@ def jinja_env(searchpath) -> Environment: env = Environment( loader=FileSystemLoader(str(searchpath)), undefined=StrictUndefined, - autoescape=False, # noqa: S701 - renders HCL and dotenv, not markup + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool env.filters["dotenv_quote"] = lambda value: f'"{value}"' diff --git a/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py b/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py index 65304f0539..97205be309 100644 --- a/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py +++ b/tests/unit/python/roles/web-app-openwebui/files/test_provision_mcp_grants.py @@ -465,7 +465,7 @@ class TestResolveApiKey(unittest.TestCase): modules = {} backend.install(modules) with patch.dict("sys.modules", modules): - return module, asyncio.run(module.resolve_api_key()) + return asyncio.run(module.resolve_api_key()) def test_an_existing_administrator_key_is_reused_and_kept(self) -> None: backend = FakeBackend( @@ -473,7 +473,7 @@ class TestResolveApiKey(unittest.TestCase): keys={"admin1": "sk-operator"}, ) - _module, (user_id, key, minted) = self._resolve(backend) + user_id, key, minted = self._resolve(backend) self.assertEqual("admin1", user_id) self.assertEqual("sk-operator", key) @@ -483,7 +483,7 @@ class TestResolveApiKey(unittest.TestCase): def test_a_missing_key_is_minted_and_marked_for_removal(self) -> None: backend = FakeBackend([FakeUser("admin1", "admin")]) - _module, (user_id, key, minted) = self._resolve(backend) + user_id, key, minted = self._resolve(backend) self.assertEqual("admin1", user_id) self.assertTrue(key.startswith("sk-")) @@ -493,7 +493,7 @@ class TestResolveApiKey(unittest.TestCase): def test_an_instance_without_users_gets_one_administrator(self) -> None: backend = FakeBackend([]) - _module, (user_id, _key, minted) = self._resolve(backend) + user_id, _key, minted = self._resolve(backend) self.assertEqual(["admin"], [user.role for user in backend.created]) self.assertEqual(backend.created[0].id, user_id) @@ -512,9 +512,8 @@ class TestResolveApiKey(unittest.TestCase): admin_id, _key, minted = asyncio.run(module.resolve_api_key()) self.assertTrue(minted) try: - exploding_grant(_key) - except RuntimeError: - pass + with self.assertRaises(RuntimeError): + exploding_grant(_key) finally: asyncio.run(module.drop_api_key(admin_id)) diff --git a/tests/unit/python/roles/web-app-penpot/__init__.py b/tests/unit/python/roles/web-app-penpot/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-penpot/test_frontend_start_guard.py b/tests/unit/python/roles/web-app-penpot/test_frontend_start_guard.py new file mode 100644 index 0000000000..bd8eb4c67d --- /dev/null +++ b/tests/unit/python/roles/web-app-penpot/test_frontend_start_guard.py @@ -0,0 +1,99 @@ +import os +import re +import subprocess +import tempfile +import unittest +from pathlib import Path + +from jinja2 import Environment, StrictUndefined, select_autoescape + +from utils import PROJECT_ROOT +from utils.cache.files import read_text +from utils.cache.yaml import load_yaml +from utils.roles.mapping import ROLE_FILE_TEMPL_COMPOSE, ROLE_FILE_VARS_MAIN + +ROLE_DIR = PROJECT_ROOT / "roles/web-app-penpot" + +GETENT_STUB = """#!/usr/bin/env bash +name="${2:-}" +if [[ "${name}" != *. ]]; then +\techo "172.30.0.10 ${name}.infinito.test" +\texit 0 +fi +echo "${name}" >>"${STUB_DIR}/absolute-names" +lookups=$(( $(cat "${STUB_DIR}/absolute-lookups" 2>/dev/null || echo 0) + 1 )) +echo "${lookups}" >"${STUB_DIR}/absolute-lookups" +if [ "${lookups}" -le "${STUB_UNKNOWN_LOOKUPS}" ]; then +\texit 2 +fi +echo "192.168.48.5 ${name%.}" +""" + +NGINX_STUB = """#!/usr/bin/env bash +cat "${STUB_DIR}/absolute-lookups" 2>/dev/null || echo 0 +""" + +QUIET_STUB = """#!/usr/bin/env bash +exit 0 +""" + + +def start_guard() -> str: + template = read_text(str(ROLE_DIR / ROLE_FILE_TEMPL_COMPOSE)) + guard = re.search(r"^\s+- '(until getent hosts .+)'$", template, re.MULTILINE) + names = load_yaml(str(ROLE_DIR / ROLE_FILE_VARS_MAIN)) + env = Environment( + undefined=StrictUndefined, + autoescape=select_autoescape(default_for_string=False), + ) + return env.from_string(guard.group(1)).render( + PENPOT_BACKEND_SERVICE=names["PENPOT_BACKEND_SERVICE"], + PENPOT_EXPORTER_SERVICE=names["PENPOT_EXPORTER_SERVICE"], + ) + + +class TestFrontendStartGuard(unittest.TestCase): + def absolute_lookups_until_nginx_starts(self, failing_absolute_lookups: int) -> int: + with tempfile.TemporaryDirectory() as tmp: + bin_dir = Path(tmp) + stubs = ( + ("getent", GETENT_STUB), + ("nginx", NGINX_STUB), + ("sleep", QUIET_STUB), + ) + for name, body in stubs: + stub = bin_dir / name + stub.write_text(body) + stub.chmod(0o755) + env = {k: v for k, v in os.environ.items() if k != "BASH_ENV"} + env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}" + env["STUB_DIR"] = tmp + env["STUB_UNKNOWN_LOOKUPS"] = str(failing_absolute_lookups) + done = subprocess.run( + ["bash", "-c", start_guard()], + env=env, + capture_output=True, + text=True, + check=False, + timeout=30, + ) + self.assertEqual(done.returncode, 0, done.stderr) + names = load_yaml(str(ROLE_DIR / ROLE_FILE_VARS_MAIN)) + self.assertEqual( + set(read_text(str(bin_dir / "absolute-names")).split()), + { + f"{names['PENPOT_BACKEND_SERVICE']}.", + f"{names['PENPOT_EXPORTER_SERVICE']}.", + }, + ) + return int(done.stdout) + + def test_nginx_waits_until_the_services_resolve_without_the_search_domain(self): + self.assertEqual(self.absolute_lookups_until_nginx_starts(3), 5) + + def test_nginx_starts_at_once_when_the_services_are_known(self): + self.assertEqual(self.absolute_lookups_until_nginx_starts(0), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py b/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py index 3c57b00f2e..1ef49c2119 100644 --- a/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py +++ b/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py @@ -5,8 +5,8 @@ import struct import sys import tempfile import unittest +import unittest.mock as mock from pathlib import Path -from unittest import mock from . import PROJECT_ROOT 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 cf6ad49854..296133e61b 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 @@ -12,7 +12,7 @@ from __future__ import annotations import json import unittest -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text from utils.cache.yaml import load_yaml_any @@ -34,7 +34,7 @@ def _render(template_path, **variables) -> str: trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - JMAP request bodies, never HTML + autoescape=select_autoescape(default_for_string=False), ) env.filters["to_json"] = json.dumps env.filters["int"] = int diff --git a/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py b/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py index 164ce94b0c..8261829975 100644 --- a/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py +++ b/tests/unit/python/roles/web-app-stalwart/test_roundcube_oauth_scheme.py @@ -16,7 +16,7 @@ from __future__ import annotations import unittest -from jinja2 import Environment, StrictUndefined +from jinja2 import Environment, StrictUndefined, select_autoescape from utils.cache.files import read_text @@ -41,7 +41,7 @@ def _render(base_url: str, *, sso_enabled: bool = True, socks_proxy: str = "") - trim_blocks=True, lstrip_blocks=True, undefined=StrictUndefined, - autoescape=False, # noqa: S701 - a PHP config file, and Ansible's templar does not escape either + autoescape=select_autoescape(default_for_string=False), ) env.filters["bool"] = bool return env.from_string(read_text(TEMPLATE)).render( diff --git a/tests/unit/python/roles/web-app-xwiki/__init__.py b/tests/unit/python/roles/web-app-xwiki/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-xwiki/filter_plugins/__init__.py b/tests/unit/python/roles/web-app-xwiki/filter_plugins/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-app-xwiki/filter_plugins/test_xwiki_filters.py b/tests/unit/python/roles/web-app-xwiki/filter_plugins/test_xwiki_filters.py new file mode 100644 index 0000000000..87142501ea --- /dev/null +++ b/tests/unit/python/roles/web-app-xwiki/filter_plugins/test_xwiki_filters.py @@ -0,0 +1,42 @@ +import importlib.util +import unittest + +from utils import PROJECT_ROOT + +_spec = importlib.util.spec_from_file_location( + "xwiki_filters", + PROJECT_ROOT / "roles/web-app-xwiki/filter_plugins/xwiki_filters.py", +) +_mod = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(_mod) +xwiki_extension_status = _mod.xwiki_extension_status + +EXTENSION = "org.xwiki.contrib.oidc:oidc-authenticator" + + +class TestExtensionStatus(unittest.TestCase): + def test_the_pinned_version_counts_as_installed(self): + page = f"

INSTALLED::{EXTENSION}::2.28.1

" + self.assertEqual(xwiki_extension_status(page, "2.28.1"), 200) + + def test_another_installed_version_is_not_the_pinned_one(self): + page = f"INSTALLED::{EXTENSION}::2.19.6" + self.assertEqual(xwiki_extension_status(page, "2.28.1"), 404) + + def test_a_version_does_not_pass_for_one_it_only_starts_or_ends_like(self): + self.assertEqual( + xwiki_extension_status(f"INSTALLED::{EXTENSION}::0.10", "0.1"), 404 + ) + self.assertEqual( + xwiki_extension_status(f"INSTALLED::{EXTENSION}::10.1", "0.1"), 404 + ) + + def test_no_pin_accepts_any_installed_version(self): + self.assertEqual(xwiki_extension_status(f"INSTALLED::{EXTENSION}::2.19.6"), 200) + + def test_a_missing_extension_is_not_installed(self): + self.assertEqual(xwiki_extension_status(f"MISSING::{EXTENSION}", "2.28.1"), 404) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web-svc-collabora/__init__.py b/tests/unit/python/roles/web-svc-collabora/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/web-svc-collabora/test_wopi_host.py b/tests/unit/python/roles/web-svc-collabora/test_wopi_host.py new file mode 100644 index 0000000000..1751e10d67 --- /dev/null +++ b/tests/unit/python/roles/web-svc-collabora/test_wopi_host.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +import sys +import unittest +import unittest.mock as mock +from unittest.mock import patch + +from jinja2 import Environment, StrictUndefined, select_autoescape + +import utils.tls_common as _tls_common +from plugins.lookup.tls import LookupModule +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_str +from utils.roles.mapping import ROLE_FILE_VARS_MAIN + +sys.modules.setdefault("ansible.module_utils.tls_common", _tls_common) + +VARS = PROJECT_ROOT / "roles/web-svc-collabora" / ROLE_FILE_VARS_MAIN +NEXTCLOUD_ONION = "next.cloud." + "a" * 56 + ".onion" +COLLABORA_ONION = "collabora." + "a" * 56 + ".onion" + + +def wopi_host(domains: dict[str, list[str]]) -> str: + variables = { + "domains": domains, + "applications": {}, + "TLS_ENABLED": True, + "TLS_MODE": "letsencrypt", + "application_id": "web-svc-collabora", + } + tls = LookupModule() + tls._loader = mock.MagicMock() + + def _get(name, *_args, **_kwargs): + return mock.MagicMock( + run=lambda _terms, variables=None, **_: [(variables or {}).get(name, {})] + ) + + def lookup(name, *terms): + if name == "domain": + return domains[terms[0]][0] + if name == "tls": + return tls.run(list(terms), variables=variables)[0] + raise AssertionError(f"the expression calls an unexpected lookup: {name!r}") + + expression = load_yaml_str(read_text(str(VARS)))["COLLABORA_WOPI_HOST"] + env = Environment( + undefined=StrictUndefined, + autoescape=select_autoescape(default_for_string=False), + ) + with patch("plugins.lookup.tls.lookup_loader") as loader: + loader.get.side_effect = _get + return env.from_string(expression).render(lookup=lookup) + + +class TestWopiHost(unittest.TestCase): + def test_an_onion_primary_nextcloud_beside_a_clearnet_collabora(self): + self.assertEqual( + wopi_host( + { + "web-app-nextcloud": [NEXTCLOUD_ONION, "next.cloud.example"], + "web-svc-collabora": ["collabora.example"], + } + ), + f"http://{NEXTCLOUD_ONION}:80", + ) + + def test_both_apps_behind_tor(self): + self.assertEqual( + wopi_host( + { + "web-app-nextcloud": [NEXTCLOUD_ONION], + "web-svc-collabora": [COLLABORA_ONION], + } + ), + f"http://{NEXTCLOUD_ONION}:80", + ) + + def test_both_apps_on_clearnet(self): + self.assertEqual( + wopi_host( + { + "web-app-nextcloud": ["next.cloud.example"], + "web-svc-collabora": ["collabora.example"], + } + ), + "https://next.cloud.example:443", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/web_app_keycloak/test_library_keycloak_kcadm_update.py b/tests/unit/python/roles/web_app_keycloak/test_library_keycloak_kcadm_update.py index f1e9195b3a..920e3bfc44 100644 --- a/tests/unit/python/roles/web_app_keycloak/test_library_keycloak_kcadm_update.py +++ b/tests/unit/python/roles/web_app_keycloak/test_library_keycloak_kcadm_update.py @@ -15,6 +15,10 @@ if TYPE_CHECKING: ROLE_DIR = PROJECT_ROOT / "roles" / "web-app-keycloak" LIB_PATH = PROJECT_ROOT / "library" / "keycloak_kcadm_update.py" MODUTILS_PATH = PROJECT_ROOT / "utils" / "kcadm_json.py" +LOCK_ERROR = ( + "Failed to refresh access token - " + "Failed to get lock on /opt/keycloak/.keycloak/kcadm.config" +) def _load_py_module(name: str, path: Path): @@ -214,6 +218,46 @@ class TestKeycloakKcadmUpdate(unittest.TestCase): self.assertEqual(rc, 1) self.assertEqual(len(calls), 1) + def test_run_kcadm_repeats_a_call_that_lost_the_config_lock(self): + m = self.mod + outcomes = [ + DummyCompleted(1, "", LOCK_ERROR), + DummyCompleted(1, "", LOCK_ERROR), + DummyCompleted(0, "[]", ""), + ] + calls = [] + + def fake_run(cmd, **kwargs): + calls.append(cmd) + return outcomes[len(calls) - 1] + + with ( + patch.object(m.subprocess, "run", side_effect=fake_run), + patch.object(m.time, "sleep", return_value=None) as sleep, + ): + rc, out, _err = m.run_kcadm(DummyModule(), "kcadm get clients") + + self.assertEqual((rc, out), (0, "[]")) + self.assertEqual(calls, ["kcadm get clients"] * 3) + self.assertEqual(sleep.call_count, 2) + + def test_run_kcadm_gives_up_on_a_config_lock_that_never_frees(self): + m = self.mod + calls = [] + + def fake_run(cmd, **kwargs): + calls.append(cmd) + return DummyCompleted(1, "", LOCK_ERROR) + + with ( + patch.object(m.subprocess, "run", side_effect=fake_run), + patch.object(m.time, "sleep", return_value=None), + self.assertRaises(m.subprocess.CalledProcessError), + ): + m.run_kcadm(DummyModule(), "kcadm get clients") + + self.assertEqual(len(calls), m.CONFIG_LOCK_MAX_RETRIES + 1) + def test_get_current_object_parses_noisy(self): m = self.mod dummy = DummyModule() diff --git a/tests/unit/python/utils/roles/test_guide.py b/tests/unit/python/utils/roles/test_guide.py index 49c3bcf1de..387edc71fd 100644 --- a/tests/unit/python/utils/roles/test_guide.py +++ b/tests/unit/python/utils/roles/test_guide.py @@ -1,6 +1,6 @@ import unittest +import unittest.mock as mock from typing import ClassVar -from unittest import mock from utils.cache.applications import get_variants from utils.roles.guide import guide_deployable, guide_variant, smallest_variant diff --git a/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py b/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py index 4f27992dcb..b0773bf61e 100644 --- a/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py +++ b/tests/unit/python/utils/tests/swarm/test_matrix_run_reporting.py @@ -1,7 +1,7 @@ import contextlib import io import unittest -from unittest import mock +import unittest.mock as mock from utils.tests.swarm import matrix