diff --git a/.claude/settings.json b/.claude/settings.json index 84a49563f9..12f4108979 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -4,32 +4,38 @@ "Read", "Edit", "Write", - "Bash(git status*)", "Bash(git log*)", "Bash(git diff*)", "Bash(git add*)", + "Bash(git mv*)", + "Bash(git rm*)", "Bash(git checkout*)", "Bash(git branch*)", "Bash(git fetch*)", "Bash(git stash*)", + "Bash(git cherry-pick*)", + "Bash(git apply*)", "Bash(git -C:*)", - + "Bash(gh run*)", "Bash(make*)", "Bash(act*)", - + "Bash(bash -n*)", + "Bash(bash scripts/*)", + "Bash(source scripts/*)", + "Bash(scripts/*)", + "Bash(chmod +x scripts/*)", + "Bash(wait*)", "Bash(python3*)", "Bash(python*)", "Bash(pip show*)", "Bash(pip list*)", "Bash(pip install*)", - "Bash(ansible-lint*)", "Bash(ansible-inventory*)", "Bash(ansible --version*)", "Bash(ansible-playbook --check*)", "Bash(ansible-playbook --syntax-check*)", - "Bash(docker pull*)", "Bash(docker build*)", "Bash(docker images*)", @@ -42,7 +48,6 @@ "Bash(docker rmi*)", "Bash(docker compose*)", "Bash(docker exec*)", - "Bash(grep*)", "Bash(find*)", "Bash(ls*)", @@ -56,7 +61,7 @@ "Bash(cp*)", "Bash(mv*)", "Bash(jq*)", - + "Bash(awk*)", "WebSearch", "WebFetch(domain:github.com)", "WebFetch(domain:raw.githubusercontent.com)", @@ -76,24 +81,24 @@ "WebFetch(domain:ghcr.io)", "WebFetch(domain:letsencrypt.org)", "WebFetch(domain:hcaptcha.com)", - "WebFetch(domain:gstatic.com)" + "WebFetch(domain:gstatic.com)", + "Bash(pkill -f *)", + "Read(~/.cache/pre-commit/**)" ], - - "ask": [ - "Bash(git commit*)", - "Bash(git push*)", - "Bash(docker run*)", - "Bash(curl*)" - ], - "deny": [ "Bash(git push --force*)", "Bash(git reset --hard*)", "Bash(rm -rf*)", "Bash(sudo*)" + ], + "ask": [ + "Bash(git commit*)", + "Bash(git push*)", + "Bash(docker run*)", + "Bash(curl*)", + "Bash(gh api*)" ] }, - "sandbox": { "filesystem": { "allowWrite": [ diff --git a/.dockerignore b/.dockerignore index c9a2dc477c..213d9cfb5f 100644 --- a/.dockerignore +++ b/.dockerignore @@ -19,4 +19,5 @@ env.development logs/ job-logs.txt .claude/skills +*.lock .git diff --git a/.github/workflows/entry-push-latest.yml b/.github/workflows/entry-push-latest.yml index facc3595f2..cfa6f582f2 100644 --- a/.github/workflows/entry-push-latest.yml +++ b/.github/workflows/entry-push-latest.yml @@ -2,7 +2,7 @@ name: "⚔ CI: Push" concurrency: group: global-ci-${{ github.repository }}-${{ github.ref_name }} - cancel-in-progress: false + cancel-in-progress: ${{ vars.CI_CANCEL_IN_PROGRESS != 'false' }} on: push: diff --git a/.github/workflows/security-codeql.yml b/.github/workflows/security-codeql.yml index 12ef548e5f..9a2e365aee 100644 --- a/.github/workflows/security-codeql.yml +++ b/.github/workflows/security-codeql.yml @@ -11,6 +11,10 @@ # name: "šŸ”’ Scan: CodeQL (Advanced)" +concurrency: + group: codeql-${{ github.repository }}-${{ github.ref }} + cancel-in-progress: true + on: workflow_call: push: diff --git a/.gitignore b/.gitignore index 7bb558e92b..0bf847080c 100644 --- a/.gitignore +++ b/.gitignore @@ -19,3 +19,4 @@ env.development logs/ job-logs.txt .claude/skills +*.lock diff --git a/AGENTS.md b/AGENTS.md index 08d0b5823c..56624cdc4b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,6 +12,23 @@ If agent instructions change during a conversation, the agent MAY not pick up th > "Re-read AGENTS.md and apply all updated instructions." +## Permission Model + +The project defines a single, tool-independent permission policy in [`.claude/settings.json`](.claude/settings.json). Although the file lives under `.claude/`, its `permissions` section (`allow`, `ask`, `deny`) is the SPOT for what automated agents MAY do in this repository, regardless of the underlying agent (Claude Code, Codex, Gemini, or any other). + +Every agent MUST: + +- Read [`.claude/settings.json`](.claude/settings.json) at the start of each conversation and treat its `permissions` object as binding policy. +- Match commands against the patterns exactly as Claude Code does: the command-line prefix is compared literally, `*` is a wildcard, and `deny` overrides `allow`. +- Treat `deny` entries as unconditional blocks. Agents MUST NOT execute any command matching a `deny` pattern, even if their native tooling would otherwise permit it. +- Treat `ask` entries as requiring an explicit, per-invocation operator confirmation in the current conversation before executing. A prior confirmation in another conversation MUST NOT be reused. +- Treat `allow` entries as the only pre-authorized commands. Any command that does not match an `allow` pattern MUST be treated as `ask` by default. +- Respect the `sandbox.filesystem` section: `allowWrite` bounds the write scope, and paths listed under `denyRead` MUST NOT be read. + +Agents that cannot technically enforce these rules (e.g. because their native runtime does not consult `.claude/settings.json`) MUST still follow the policy procedurally: before running a command, check it against the rules above and stop for confirmation when required. + +Changes to the permission policy MUST be made by editing [`.claude/settings.json`](.claude/settings.json) so that all agents share the same source of truth. The rationale for each entry is documented in [docs/contributing/tools/agents/claude.md](docs/contributing/tools/agents/claude.md). + ## Role-Specific Instructions Individual roles MAY contain an `AGENTS.md` file with role-specific agent instructions. @@ -30,4 +47,4 @@ The agent MUST NOT repeat this notice within the same conversation. ## For Humans -Human contributors working alongside AI agents MUST read [here](docs/contributing/tools/agents.md). +Human contributors working alongside AI agents MUST read [here](docs/contributing/tools/agents/common.md). diff --git a/CLAUDE.md b/CLAUDE.md index 00d57a13ea..6154f85902 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,6 +12,11 @@ You MUST read `AGENTS.md` and follow all instructions in it at the start of ever ## Code Execution +- You MUST always prefer `make` targets over running underlying scripts, `docker`, `docker compose`, `ansible-playbook`, `python`, or shell invocations directly, whenever an equivalent target exists in the [`Makefile`](Makefile). Inspect the `Makefile` first and only fall back to the raw command when no target covers the operation. +- When passing variables to `make`, you MUST pass them **after** the target as make-style arguments, NOT as a shell-env prefix before `make`. This keeps the command matchable by the `Bash(make*)` permission entry in [.claude/settings.json](.claude/settings.json) and avoids unnecessary approval prompts. + - āœ… `make deploy-fresh-purged-apps APPS=web-app-nextcloud SERVICES_DISABLED="matomo"` + - āŒ `SERVICES_DISABLED="matomo" APPS=web-app-nextcloud make deploy-fresh-purged-apps` + - GNU Make automatically exports both command-line variables and inherited shell-env variables to recipe shells, so both forms are functionally equivalent. The make-suffix form is REQUIRED for agent use solely because of the `Bash(make*)` permission prefix match. - You SHOULD run permitted commands (listed in [.claude/settings.json](.claude/settings.json)) directly on the host. - For commands that are NOT permitted on the host, you MUST run them inside the application containers instead. Use `make up` (or the appropriate Make target) to start the stack, then use `make exec` to open a shell inside the container. - The repository is mounted into the container at `/opt/src/infinito` (see [compose.yml](compose.yml)), so code changes are immediately available there. @@ -24,4 +29,4 @@ You MUST read `AGENTS.md` and follow all instructions in it at the start of ever ## Documentation -See the [Claude Code documentation](https://code.claude.com/docs/en/overview) for further information. For human contributor guidance on working with agents, see [here](docs/contributing/tools/agents.md). +See the [Claude Code documentation](https://code.claude.com/docs/en/overview) for further information. For human contributor guidance on working with agents, see [here](docs/contributing/tools/agents/common.md). diff --git a/GEMINI.md b/GEMINI.md index e003702cb1..59a8c8d23b 100644 --- a/GEMINI.md +++ b/GEMINI.md @@ -10,4 +10,4 @@ This file extends [AGENTS.md](AGENTS.md) with Gemini-specific additions. You MUS ## Documentation -See the [Gemini CLI documentation](https://geminicli.com/docs/cli/gemini-md/). For human contributor guidance on working with agents, see [here](docs/contributing/tools/agents.md). \ No newline at end of file +See the [Gemini CLI documentation](https://geminicli.com/docs/cli/gemini-md/). For human contributor guidance on working with agents, see [here](docs/contributing/tools/agents/common.md). \ No newline at end of file diff --git a/Makefile b/Makefile index 615a71fa65..71258d7df4 100644 --- a/Makefile +++ b/Makefile @@ -21,7 +21,7 @@ endif test lint lint-action lint-ansible lint-python lint-shellcheck autoformat test-lint test-unit test-integration test-external test-deploy test-deploy-app \ clean clean-sudo down \ system-purge system-disk-usage \ - list tree mig dockerignore \ + list tree mig dockerignore chmod-scripts \ print-python \ dns-setup dns-remove \ environment-bootstrap environment-teardown \ @@ -144,6 +144,10 @@ down: stop: @"$${PYTHON}" -m cli.deploy.development stop +# Mark all shell scripts under scripts/ as executable. +chmod-scripts: + @find scripts/ -name "*.sh" -exec chmod +x {} \; + # Print the repository role list. list: @echo "Generating the roles list" diff --git a/SECURITY.md b/SECURITY.md index 0f81cf5284..bdf4bc608c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -27,7 +27,7 @@ For general help and non-security requests, see [SUPPORT.md](SUPPORT.md). The security policies enforced on this repository are documented here: -- [Branch Protection](docs/contributing/tools/github/branch.md): Rules enforced on the `main` branch. +- [Branch Protection](docs/contributing/tools/github/branch/security.md): Rules enforced on the `main` branch. - [Repository Settings](docs/contributing/tools/github/repository.md): Repository-wide security configuration. ## Detailed Secure Use Guides šŸ›”ļø diff --git a/cli/create/inventory/services_disabler.py b/cli/create/inventory/services_disabler.py index 97aa615a91..463613ee8e 100644 --- a/cli/create/inventory/services_disabler.py +++ b/cli/create/inventory/services_disabler.py @@ -8,6 +8,16 @@ import yaml from ruamel.yaml import YAML from ruamel.yaml.comments import CommentedMap +from utils.service_registry import ( + build_service_registry_from_roles_dir, + canonical_service_key, + equivalent_service_keys, +) + + +class ServicesDisabledConflictError(RuntimeError): + """Raised when SERVICES_DISABLED conflicts with an existing inventory.""" + def parse_services_disabled(env_value: str) -> list[str]: """Parse a space- or comma-separated list of service names.""" @@ -210,3 +220,115 @@ def apply_services_disabled_from_env( apply_services_disabled( host_vars_file, services, roles_dir=roles_dir, inventory_file=inventory_file ) + + +def _load_yaml_mapping(path: Path) -> dict: + if not path.exists(): + return {} + with path.open("r", encoding="utf-8") as f: + data = yaml.safe_load(f) or {} + return data if isinstance(data, dict) else {} + + +def _inventory_application_ids(inventory_file: Path) -> set[str]: + doc = _load_yaml_mapping(inventory_file) + all_section = doc.get("all") or {} + children = all_section.get("children") or {} + if not isinstance(children, dict): + return set() + return {app_id for app_id, value in children.items() if isinstance(value, dict)} + + +def find_services_disabled_conflicts( + inventory_dir: Path, + services: list[str], + roles_dir: Path, +) -> list[str]: + """ + Return human-readable conflicts when SERVICES_DISABLED disagrees with the + existing inventory/host_vars state. + """ + if not services: + return [] + + inventory_file = inventory_dir / "devices.yml" + deployed_app_ids = _inventory_application_ids(inventory_file) + host_vars_dir = inventory_dir / "host_vars" + host_vars_files = ( + sorted(host_vars_dir.glob("*.yml")) if host_vars_dir.is_dir() else [] + ) + service_registry = build_service_registry_from_roles_dir(roles_dir) + + conflicts: list[str] = [] + for service in services: + primary_service = ( + canonical_service_key(service_registry, service) + if service in service_registry + else service + ) + equivalent_keys = ( + equivalent_service_keys(service_registry, primary_service) + if primary_service in service_registry + else [service] + ) + provider_role = (service_registry.get(primary_service) or {}).get("role") + if isinstance(provider_role, str) and provider_role in deployed_app_ids: + conflicts.append( + f"service '{service}' is disabled, but provider role " + f"'{provider_role}' is still active in {inventory_file}" + ) + + for host_vars_file in host_vars_files: + doc = _load_yaml_mapping(host_vars_file) + applications = doc.get("applications") or {} + if not isinstance(applications, dict): + continue + for app_id in sorted(deployed_app_ids): + app_conf = applications.get(app_id) or {} + compose = app_conf.get("compose") or {} + service_map = compose.get("services") or {} + if not isinstance(service_map, dict): + continue + for service_key in equivalent_keys: + service_conf = service_map.get(service_key) or {} + if not isinstance(service_conf, dict): + continue + enabled = bool(service_conf.get("enabled", False)) + shared = bool(service_conf.get("shared", False)) + if enabled or shared: + conflicts.append( + f"service '{service}' is disabled, but " + f"{host_vars_file}:{app_id}.compose.services.{service_key} " + f"still has enabled={enabled}, shared={shared}" + ) + + return conflicts + + +def assert_services_disabled_inventory_consistency_from_env( + inventory_dir: Path, + roles_dir: Path, +) -> None: + """Fail fast when SERVICES_DISABLED conflicts with the existing inventory.""" + raw = os.environ.get("SERVICES_DISABLED", "").strip() + if not raw: + return + + services = parse_services_disabled(raw) + conflicts = find_services_disabled_conflicts( + inventory_dir=inventory_dir, + services=services, + roles_dir=roles_dir, + ) + if not conflicts: + return + + details = "\n - ".join(conflicts) + raise ServicesDisabledConflictError( + "SERVICES_DISABLED conflicts with the current inventory state.\n" + f"SERVICES_DISABLED={raw!r}\n" + "Conflicts:\n" + f" - {details}\n" + "Recreate or clean the inventory, or remove the conflicting service from " + "SERVICES_DISABLED." + ) diff --git a/cli/deploy/dedicated/runner.py b/cli/deploy/dedicated/runner.py index 60171bddeb..2e5e45035b 100644 --- a/cli/deploy/dedicated/runner.py +++ b/cli/deploy/dedicated/runner.py @@ -4,8 +4,14 @@ import datetime import os import subprocess import sys +from pathlib import Path from typing import Any, Dict, List, Optional +from cli.create.inventory.services_disabler import ( + ServicesDisabledConflictError, + assert_services_disabled_inventory_consistency_from_env, +) + from .proc import run, run_make @@ -47,7 +53,19 @@ def run_ansible_playbook( print("\nšŸ› ļø Build skipped (--skip-build)\n") # --------------------------------------------------------- - # 3) Inventory Validation Phase + # 3) SERVICES_DISABLED consistency guard + # --------------------------------------------------------- + try: + assert_services_disabled_inventory_consistency_from_env( + inventory_dir=Path(inventory).resolve().parent, + roles_dir=Path(repo_root).resolve() / "roles", + ) + except ServicesDisabledConflictError as exc: + print(f"\n[ERROR] {exc}\n", file=sys.stderr) + sys.exit(1) + + # --------------------------------------------------------- + # 4) Inventory Validation Phase # --------------------------------------------------------- if modes.get("MODE_ASSERT", None) is False: print("\nšŸ” Inventory assertion explicitly disabled (MODE_ASSERT=false)\n") @@ -67,7 +85,7 @@ def run_ansible_playbook( sys.exit(1) # --------------------------------------------------------- - # 4) Build ansible-playbook command + # 5) Build ansible-playbook command # --------------------------------------------------------- cmd: List[str] = ["ansible-playbook", "-i", inventory, playbook_path] diff --git a/cli/deploy/development/exec.py b/cli/deploy/development/exec.py index 7675022e95..c86da35f30 100644 --- a/cli/deploy/development/exec.py +++ b/cli/deploy/development/exec.py @@ -31,5 +31,10 @@ def handler(args: argparse.Namespace) -> int: if not cmd: raise SystemExit("exec requires a command (e.g. exec -- sh -lc 'whoami')") - r = compose.exec(cmd, check=False) + extra_env: dict[str, str] = {} + services_disabled = os.environ.get("SERVICES_DISABLED", "") + if services_disabled: + extra_env["SERVICES_DISABLED"] = services_disabled + + r = compose.exec(cmd, check=False, extra_env=extra_env or None) return int(r.returncode) diff --git a/cli/meta/applications/resolution/services/resolver.py b/cli/meta/applications/resolution/services/resolver.py index 28cd07a9f9..594e32e006 100644 --- a/cli/meta/applications/resolution/services/resolver.py +++ b/cli/meta/applications/resolution/services/resolver.py @@ -6,8 +6,12 @@ from typing import Any, Dict, Iterable, List, Optional, Set import yaml from .errors import ServicesResolutionError +from utils.service_registry import ( + build_service_registry_from_roles_dir, + resolve_service_dependency_roles_from_config, +) -_SERVICES_FILE = Path(__file__).parents[5] / "group_vars" / "all" / "20_services.yml" +_ROLES_ROOT = Path(__file__).parents[5] / "roles" def _stable_dedup(items: Iterable[str]) -> List[str]: @@ -29,16 +33,13 @@ def _is_enabled_shared(svc: object) -> bool: return svc.get("enabled") is True and svc.get("shared") is True -def _load_service_registry(services_file: Path = _SERVICES_FILE) -> Dict[str, Any]: - if not services_file.exists(): - raise ServicesResolutionError(f"20_services.yml not found at {services_file}") - raw = yaml.safe_load(services_file.read_text(encoding="utf-8")) or {} - service_registry = raw.get("SERVICE_REGISTRY") - if not isinstance(service_registry, dict): +def _load_service_registry(roles_root: Path = _ROLES_ROOT) -> Dict[str, Any]: + try: + return build_service_registry_from_roles_dir(roles_root) + except Exception as exc: raise ServicesResolutionError( - f"Expected a 'SERVICE_REGISTRY' mapping in {services_file}" - ) - return service_registry + f"Failed to discover services from role configs in {roles_root}: {exc}" + ) from exc def resolve_direct_service_roles_from_config( @@ -47,37 +48,18 @@ def resolve_direct_service_roles_from_config( ) -> List[str]: """ Single source of truth for "service -> provider role(s)" mapping. - - Reads the service key → role mapping from services.yml (repo root). - Every service requires compose.services..enabled: true AND shared: true. - Entries with role_template substitute {type} from the service config. """ if service_registry is None: service_registry = _load_service_registry() - - cfg = _as_mapping(config) - services = _as_mapping(_as_mapping(cfg.get("compose")).get("services")) - - includes: List[str] = [] - for key, mapping in service_registry.items(): - svc_obj = services.get(key) - if not _is_enabled_shared(svc_obj): - continue - - role_template = mapping.get("role_template") - if role_template: - svc_dict = _as_mapping(svc_obj) - db_type = (svc_dict.get("type") or "").strip() - if not db_type: - raise ServicesResolutionError( - f"compose.services.{key}.enabled=true and shared=true " - f"but compose.services.{key}.type is missing" - ) - includes.append(role_template.format(type=db_type)) - else: - includes.append(mapping["role"]) - - return _stable_dedup(includes) + try: + return _stable_dedup( + resolve_service_dependency_roles_from_config( + _as_mapping(config), + service_registry, + ) + ) + except Exception as exc: + raise ServicesResolutionError(str(exc)) from exc class ServicesResolver: @@ -92,10 +74,12 @@ class ServicesResolver: def __init__( self, roles_root: Path, - services_file: Path = _SERVICES_FILE, + services_file: Path | None = None, ) -> None: self.roles_root = roles_root - self._service_registry = _load_service_registry(services_file) + self._service_registry = _load_service_registry( + services_file or self.roles_root + ) def _role_dir(self, role_name: str) -> Path: return self.roles_root / role_name diff --git a/docs/agents/action/iteration.md b/docs/agents/action/iteration.md index a7be68c5fb..089aae5254 100644 --- a/docs/agents/action/iteration.md +++ b/docs/agents/action/iteration.md @@ -5,16 +5,28 @@ Use this page when you are iterating on a local app deploy during debugging or d ## Role Loop - Before starting the loop, you MUST propose disabling all non-necessary services via `SERVICES_DISABLED` to reduce resource usage. In the typical case, this means keeping only the database and disabling everything else. Only proceed without this proposal if the user has already confirmed a full-stack setup. -- Unless the user explicitly says to reuse the existing setup, you MUST start once with `APPS= make deploy-fresh-purged-apps` to establish the baseline inventory and clean app state. Set `FULL_CYCLE=true` to also run the async update pass (pass 2). +- You MUST run `make test` before every deploy. Only proceed with the deploy if all tests pass. +- Unless the user explicitly says to reuse the existing setup, you MUST start once with `make deploy-fresh-purged-apps APPS=` to establish the baseline inventory and clean app state. Set `FULL_CYCLE=true` to also run the async update pass (pass 2). - You MUST NOT run more than one deploy command at the same time. Deployments MUST be executed serially, never in parallel. -- To speed up debugging, you MAY pass multiple apps at once, e.g. `APPS=" " make deploy-fresh-purged-apps`. -- After that, you MUST use `APPS= make deploy-reuse-kept-apps` for the default edit-fix-redeploy loop. -- Do NOT rerun `APPS= make deploy-fresh-purged-apps` just because a deploy failed or you changed code. That restarts the stack unnecessarily and burns time. -- If the same failure still reproduces on the reuse path and you want to test whether app entity state is involved, use `APPS= make deploy-reuse-purged-apps` once. -- After that targeted purge check, you MUST return to `APPS= make deploy-reuse-kept-apps`. -- Only go back to `APPS= make deploy-fresh-purged-apps` if you have concrete evidence that the inventory or host stack is broken, or you intentionally need a fresh single-app baseline again. -- Network or DNS failures during a local deploy count as concrete evidence that the host stack is broken. In that case, the next retry MUST be `APPS= make deploy-fresh-purged-apps` so the container stack is re-initialized. -- If you need to validate the single-app init/deploy path separately, use `APPS= make deploy-fresh-kept-apps`. It checks the clean single-app setup apart from the faster reuse path. +- To speed up debugging, you MAY pass multiple apps at once, e.g. `make deploy-fresh-purged-apps APPS=" "`. +- After that, you MUST use `make deploy-reuse-kept-apps APPS=` for the default edit-fix-redeploy loop. +- Do NOT rerun `make deploy-fresh-purged-apps APPS=` just because a deploy failed or you changed code. That restarts the stack unnecessarily and burns time. +- If the same failure still reproduces on the reuse path and you want to test whether app entity state is involved, use `make deploy-reuse-purged-apps APPS=` once. +- After that targeted purge check, you MUST return to `make deploy-reuse-kept-apps APPS=`. +- Only go back to `make deploy-fresh-purged-apps APPS=` if you have concrete evidence that the inventory or host stack is broken, or you intentionally need a fresh single-app baseline again. +- Network or DNS failures during a local deploy count as concrete evidence that the host stack is broken. In that case, the next retry MUST be `make deploy-fresh-purged-apps APPS=` so the container stack is re-initialized. +- If you need to validate the single-app init/deploy path separately, use `make deploy-fresh-kept-apps APPS=`. It checks the clean single-app setup apart from the faster reuse path. + +## Playwright Spec Loop + +- After the first successful deploy has brought the app stack up, you MUST iterate role-local `files/playwright.spec.js` directly against the live running container instead of redeploying between every spec edit. +- For that inner loop you MUST use the [Playwright spec rerunner](../../../scripts/tests/e2e/rerun-spec.sh) (e.g. `scripts/tests/e2e/rerun-spec.sh `, optionally followed by `--grep ` or other `npx playwright test` arguments). The script reuses the staging dir and rendered `.env` from the last deploy and reruns Playwright in the same container image the deploy-time runner uses. +- The staged Playwright project lives at `TEST_E2E_PLAYWRIGHT_STAGE_BASE_DIR/` (default `/tmp/test-e2e-playwright/`) with the rendered `.env` already in place. The script overwrites `tests/playwright.spec.js` from the repo before each run; you MUST NOT hand-edit the staged copy. +- You MUST keep iterating the spec in this inner loop until the test passes. Only spec-only changes belong in this loop. +- If the change touches anything **outside** `files/playwright.spec.js` (role tasks, templates, vars, config, `javascript.js`, `style.css`, or any other role asset that the deploy materializes), you MUST redeploy. Inner-loop spec runs do NOT pick up role changes. +- Prefer `make deploy-reuse-kept-apps APPS=` for that redeploy. Fall back to `make deploy-fresh-purged-apps APPS=` only when the reuse path has concrete evidence of broken inventory or host stack, per the rules in [Role Loop](#role-loop). +- You MUST still meet the live-application and logout-state requirements from [Agent `playwright.spec.js`](../files/role/playwright.spec.js.md) at the end of the inner loop. +- Once the spec passes in the inner loop, you MUST run one final pass through the [Role Loop](#role-loop) with `make deploy-fresh-purged-apps APPS=` to confirm the spec still passes against a freshly provisioned stack, not only against the cached staging project. ## Workflow Loop @@ -24,7 +36,7 @@ Use this page when you are iterating on a local app deploy during debugging or d - If the workflow uses a distro matrix, you MUST iterate on one distro at a time instead of rerunning the whole matrix during the default debug loop. - Debian SHOULD be the preferred distro for that focused workflow iteration unless the failure is clearly distro-specific or the user asked for a different distro. - When you constrain an Act matrix run through `ACT_MATRIX`, you MUST use Act's `key:value` syntax instead of `key=value`. Otherwise Act may ignore the filter and rerun the whole matrix. -- For `.github/workflows/test-environment.yml`, the preferred focused Debian example is `ACT_WORKFLOW=.github/workflows/test-environment.yml ACT_JOB=test-environment ACT_MATRIX='dev_runtime_image:debian:bookworm' make act-workflow`. +- For `.github/workflows/test-environment.yml`, the preferred focused Debian example is `make act-workflow ACT_WORKFLOW=.github/workflows/test-environment.yml ACT_JOB=test-environment ACT_MATRIX='dev_runtime_image:debian:bookworm'`. - You SHOULD avoid jumping straight to repeated remote CI reruns when `make act-workflow` can validate the workflow locally and the user agreed to use it. - You MAY widen the scope to `make act-app` or `make act-all` when the problem spans more than one workflow or `make act-workflow` is too narrow for the failure. diff --git a/docs/contributing/actions/testing.md b/docs/contributing/actions/testing.md index 07274edfe7..fc7c1cd285 100644 --- a/docs/contributing/actions/testing.md +++ b/docs/contributing/actions/testing.md @@ -38,10 +38,10 @@ Use the following table when you need realistic local deployment validation or a | Category | Command | What it does | When to use it | |---|---|---|---| -| Local deploy | `APPS=web-app-nextcloud make deploy-fresh-kept-apps` | Creates the needed inventory and deploys one or more apps. | Fresh deploy for a specific app set. | -| Local deploy | `APPS=web-app-nextcloud make deploy-reuse-kept-apps` | Reuses an existing `devices.yml` inventory and redeploys one or more apps quickly. | Fast reuse path. | -| Local deploy | `APPS=web-app-nextcloud make deploy-reuse-purged-apps` | Reuses an existing `devices.yml` inventory, purges the entity first, and redeploys one or more apps quickly. | Fast reuse path after a state reset. | -| Local deploy and E2E | `APPS=web-app-matomo make deploy-fresh-purged-apps` | Runs a dedicated local validation flow for one or more apps against the dev stack, creating and re-initializing the inventory first. | Baseline and recovery path. | +| Local deploy | `make deploy-fresh-kept-apps APPS=web-app-nextcloud` | Creates the needed inventory and deploys one or more apps. | Fresh deploy for a specific app set. | +| Local deploy | `make deploy-reuse-kept-apps APPS=web-app-nextcloud` | Reuses an existing `devices.yml` inventory and redeploys one or more apps quickly. | Fast reuse path. | +| Local deploy | `make deploy-reuse-purged-apps APPS=web-app-nextcloud` | Reuses an existing `devices.yml` inventory, purges the entity first, and redeploys one or more apps quickly. | Fast reuse path after a state reset. | +| Local deploy and E2E | `make deploy-fresh-purged-apps APPS=web-app-matomo` | Runs a dedicated local validation flow for one or more apps against the dev stack, creating and re-initializing the inventory first. | Baseline and recovery path. | | Full local validation | `make deploy-fresh-kept-all` | Builds the broader local deployment flow across apps. | Broad coverage when you explicitly need it. | | Local reset | `make container-refresh-inventory` | Recreates the local inventory without deploying apps. | Use this when your local inventory is broken or you want a clean reset. | | Local cleanup | `make container-purge-system` | Deletes local deploy artifacts and cleanup data. | Use this only when you really want to remove local state. | diff --git a/docs/contributing/actions/testing/external.md b/docs/contributing/actions/testing/external.md index b69556fb9b..876c180e12 100644 --- a/docs/contributing/actions/testing/external.md +++ b/docs/contributing/actions/testing/external.md @@ -67,7 +67,7 @@ make test-external To scope the run to one file: ```bash -TEST_PATTERN=test_image_versions.py make test-external +make test-external TEST_PATTERN=test_image_versions.py ``` ## CI Workflow šŸ¤– diff --git a/docs/contributing/actions/testing/integration.md b/docs/contributing/actions/testing/integration.md index e1c3a6a0c4..98505aea61 100644 --- a/docs/contributing/actions/testing/integration.md +++ b/docs/contributing/actions/testing/integration.md @@ -40,8 +40,8 @@ Use `TEST_PATTERN` to scope the test run to a single file or a glob: ```bash # Run a single integration test file -TEST_PATTERN=test_my_module.py make test-integration +make test-integration TEST_PATTERN=test_my_module.py # Run all files matching a prefix -TEST_PATTERN=test_applications*.py make test-integration +make test-integration TEST_PATTERN=test_applications*.py ``` diff --git a/docs/contributing/actions/testing/lint.md b/docs/contributing/actions/testing/lint.md index 5c18a41bf3..ead4446c25 100644 --- a/docs/contributing/actions/testing/lint.md +++ b/docs/contributing/actions/testing/lint.md @@ -34,5 +34,5 @@ Use `TEST_PATTERN` to scope the lint test run to a single file: ```bash # Run lint tests for a specific file -TEST_PATTERN=test_my_role.py make test-lint +make test-lint TEST_PATTERN=test_my_role.py ``` diff --git a/docs/contributing/actions/testing/playwright.md b/docs/contributing/actions/testing/playwright.md index a5c4623599..3b2c15b49f 100644 --- a/docs/contributing/actions/testing/playwright.md +++ b/docs/contributing/actions/testing/playwright.md @@ -9,7 +9,7 @@ For implementation guidance when writing or updating role-local files, see - [Playwright](https://playwright.dev/) runs inside Docker via the shared `test-e2e-playwright` role. - There is no standalone `make` target for Playwright. Tests run as part of local deploy flows - (e.g. `FULL_CYCLE=true APPS=web-app-matomo make deploy-fresh-purged-apps`). + (e.g. `make deploy-fresh-purged-apps APPS=web-app-matomo FULL_CYCLE=true`). ## When to Write āœļø @@ -94,7 +94,7 @@ Generated files are persisted in the local workspace (git-ignored). Copy the rel 2. Build hypotheses about the expected user flows before writing tests. 3. Optionally record a draft with Playwright codegen or `playwright-recorder`. 4. Write or update `files/playwright.spec.js` and `templates/playwright.env.j2`. -5. Run the relevant deploy flow (e.g. `FULL_CYCLE=true APPS= make deploy-fresh-purged-apps`). +5. Run the relevant deploy flow (e.g. `make deploy-fresh-purged-apps APPS= FULL_CYCLE=true`). 6. Run `make trust-ca` and open the app in your browser to confirm the flow manually. 7. Inspect the browser console for errors when the flow depends on injected JavaScript. 8. Verify the suite finishes in a logged-out state. diff --git a/docs/contributing/actions/testing/unit.md b/docs/contributing/actions/testing/unit.md index 8267f5f0c5..12fa3ae3a1 100644 --- a/docs/contributing/actions/testing/unit.md +++ b/docs/contributing/actions/testing/unit.md @@ -33,8 +33,8 @@ Use `TEST_PATTERN` to scope the test run to a single file or a glob: ```bash # Run a single test file -TEST_PATTERN=test_my_module.py make test-unit +make test-unit TEST_PATTERN=test_my_module.py # Run all files matching a prefix -TEST_PATTERN=test_applications*.py make test-unit +make test-unit TEST_PATTERN=test_applications*.py ``` diff --git a/docs/contributing/artefact/git/branch.md b/docs/contributing/artefact/git/branch.md index 2031758343..d0501357a0 100644 --- a/docs/contributing/artefact/git/branch.md +++ b/docs/contributing/artefact/git/branch.md @@ -16,7 +16,7 @@ The branch prefix MUST match the type of change. The [PR workflow](pull-request. ## Enforcement šŸ”’ -All rules in this document are actively enforced on `main` via GitHub branch protection. See [branch.md](../../tools/github/branch.md) for the full enforcement policy. +All rules in this document are actively enforced on `main` via GitHub branch protection. See [branch.md](../../tools/github/branch/security.md) for the full enforcement policy. ## Naming Conventions šŸ·ļø diff --git a/docs/contributing/artefact/git/pipeline.md b/docs/contributing/artefact/git/pipeline.md index 52b55ee24a..cca6514607 100644 --- a/docs/contributing/artefact/git/pipeline.md +++ b/docs/contributing/artefact/git/pipeline.md @@ -104,6 +104,12 @@ The final `done` job aggregates all deploy, install, and development gates. CI i - PR pipelines use `cancel-in-progress: true` so only the newest run per PR and event type is active. - The orchestrator uses `cancel-in-progress: false` to avoid interrupting long-running deploy tests mid-flight. +- The push entry workflow (`entry-push-latest.yml`) defaults to `cancel-in-progress: true` but respects the + repository variable `CI_CANCEL_IN_PROGRESS`. Set it to `false` under + **Settings → Secrets and variables → Actions → Variables** to prevent in-progress runs from being cancelled + on the `main` / feature branches. Any other value (or no value) keeps the default cancel behaviour. + +See [configuration.md](../../tools/github/branch/configuration.md) for all repository variables that control CI behaviour. ## Fork PRs šŸ“ diff --git a/docs/contributing/artefact/git/pull-request.md b/docs/contributing/artefact/git/pull-request.md index cd2105190a..33a2430e81 100644 --- a/docs/contributing/artefact/git/pull-request.md +++ b/docs/contributing/artefact/git/pull-request.md @@ -17,7 +17,7 @@ You MUST pick the template that matches your change. The table below links the a Branch names MUST follow the naming conventions defined in [branch.md](branch.md). The branch prefix MUST match the type of change and is used to classify the PR scope and select the CI pipeline. -The protection rules enforced on `main` are documented in [branch.md](../../tools/github/branch.md). +The protection rules enforced on `main` are documented in [branch.md](../../tools/github/branch/security.md). ## Forking Flow šŸ“ diff --git a/docs/contributing/code/services.md b/docs/contributing/code/services.md new file mode 100644 index 0000000000..d3817b086d --- /dev/null +++ b/docs/contributing/code/services.md @@ -0,0 +1,231 @@ +# Service Management + +This page is the SPOT for how shared services are declared, discovered, ordered, +loaded, and injected. + +## What Is a Service? + +A service is a reusable dependency that an application enables via +`compose.services.`. + +Examples: +- `web-svc-cdn` provides the primary service key `cdn` +- `web-app-keycloak` provides `oidc` +- `svc-db-mariadb` provides `mariadb` + +Each service entry lives in the provider role's own +[`config/main.yml`](../../../roles) under `compose.services.`. + +## Role-Local Service Metadata + +Service providers are self-describing. The provider role owns: +- `enabled` +- `shared` +- optional `provides` +- optional `canonical` + +Example: + +```yaml +compose: + services: + keycloak: + enabled: false + shared: true + provides: oidc +``` + +Canonical aliases are also role-local: + +```yaml +compose: + services: + cdn: + enabled: false + shared: true + css: + enabled: true + shared: true + canonical: cdn + javascript: + enabled: true + shared: true + canonical: cdn +``` + +Rules: +- The primary service entry is the role entity name returned by `get_entity_name`. +- `provides:` is only used when the public service name differs from the entity name. +- `canonical:` is only used on alias entries that resolve back to the primary service key. +- `frontend` vs. `backend` is derived from the role name prefix, not stored in config. + +## Service Discovery + +Service discovery is built from role configs, not from a central registry file. + +Primary implementation files: +- [`utils/service_registry.py`](../../../utils/service_registry.py) +- [`plugins/lookup/service_registry.py`](../../../plugins/lookup/service_registry.py) + +The discovery layer: +- scans role configs from [`roles`](../../../roles) +- discovers provider entries from `compose.services` +- derives deploy type and loader bucket from the role name +- resolves `provides:` and `canonical:` +- validates and applies `run_after:` from `meta/main.yml` + +## Load Order + +[`roles/sys-utils-service-loader/tasks/main.yml`](../../../roles/sys-utils-service-loader/tasks/main.yml) +is the single loader SPOT for all shared services. + +It runs from [`tasks/stages/01_constructor.yml`](../../../tasks/stages/01_constructor.yml) +before the normal application stage. + +Global bucket order: +1. `universal` +2. `workstation` +3. `server` +4. `web-svc` +5. `web-app` + +Within the same bucket, ordering is refined by `run_after:` in the provider role's +[`meta/main.yml`](../../../roles). + +Rules: +- `run_after:` entries are role names, not service keys. +- Cross-type `run_after:` is invalid and fails hard. +- Later-bucket dependencies are invalid and fail hard. +- Cross-type service dependencies do not need `run_after:` because constructor-stage + loading already brings backend services up before normal app deployment. + +## Loading vs Injection + +Service loading and frontend injection are separate mechanisms. + +### Loading + +Loading decides whether the provider role is deployed at all. + +[`roles/sys-utils-service-loader/tasks/main.yml`](../../../roles/sys-utils-service-loader/tasks/main.yml): +- queries the ordered discovered service list +- checks `lookup('service', service_key).needed` +- skips roles already protected by `run_once_*` +- loads services through [`tasks/utils/load_app.yml`](../../../tasks/utils/load_app.yml) + +Frontend service probe/load helper: +- [`roles/sys-utils-service-loader/tasks/load_service.yml`](../../../roles/sys-utils-service-loader/tasks/load_service.yml) + +### Injection + +Injection decides whether a deployed app gets extra nginx integration such as +dashboard, logout, CSS, or JavaScript hooks. + +This stays in: +- [`roles/sys-front-inj-all/tasks/main.yml`](../../../roles/sys-front-inj-all/tasks/main.yml) +- [`roles/sys-front-inj-all/filter_plugins/inj_enabled.py`](../../../roles/sys-front-inj-all/filter_plugins/inj_enabled.py) + +Injection still reads the current app's `compose.services..enabled` flags. +It does not load provider roles. + +## Lookup Plugins + +### `service` + +File: +[`plugins/lookup/service.py`](../../../plugins/lookup/service.py) + +Examples: + +```yaml +lookup('service', 'matomo') +lookup('service', 'oidc') +lookup('service', 'web-svc-cdn') +``` + +Returns: +- `id` +- `role` +- `enabled` +- `shared` +- `needed` + +Behavior: +- accepts either a service key or a provider role name +- resolves aliases through `canonical` +- resolves provider roles through discovered primary service keys +- computes `needed` transitively from enabled shared services + +### `service_registry` + +File: +[`plugins/lookup/service_registry.py`](../../../plugins/lookup/service_registry.py) + +Examples: + +```yaml +query('service_registry') | first +query('service_registry', 'ordered') | first +``` + +Modes: +- default: full discovered registry mapping +- `ordered`: ordered primary service entries for the service loader + +### `applications_current_play` + +File: +[`plugins/lookup/applications_current_play.py`](../../../plugins/lookup/applications_current_play.py) + +Builds the current-play application set including: +- group-selected roles +- transitive shared service dependencies +- meta dependencies + +## Database Services + +Relational databases are regular services now: +- `svc-db-mariadb` provides `mariadb` +- `svc-db-postgres` provides `postgres` + +Applications express database choice directly via: + +```yaml +compose: + services: + mariadb: + enabled: true + shared: true +``` + +or: + +```yaml +compose: + services: + postgres: + enabled: true + shared: false +``` + +The `lookup('database', ...)` API remains as the convenience accessor for database +connection values, but it now resolves the active direct database service from those +role-local keys instead of `compose.services.database.type`. + +## Related Files + +| File | Purpose | +|---|---| +| [`utils/service_registry.py`](../../../utils/service_registry.py) | Service discovery, `provides`, `canonical`, bucket detection, `run_after` ordering | +| [`plugins/lookup/service_registry.py`](../../../plugins/lookup/service_registry.py) | Exposes the discovered registry and ordered provider list to Ansible | +| [`plugins/lookup/service.py`](../../../plugins/lookup/service.py) | Resolves service flags and transitive need | +| [`plugins/lookup/applications_current_play.py`](../../../plugins/lookup/applications_current_play.py) | Builds the current play app graph with shared service deps | +| [`roles/sys-utils-service-loader/tasks/main.yml`](../../../roles/sys-utils-service-loader/tasks/main.yml) | Single shared-service loader SPOT | +| [`roles/sys-utils-service-loader/tasks/load_service.yml`](../../../roles/sys-utils-service-loader/tasks/load_service.yml) | Per-service load helper used by the central service loader | +| [`tasks/stages/01_constructor.yml`](../../../tasks/stages/01_constructor.yml) | Calls the service loader during constructor | +| [`tasks/utils/load_app.yml`](../../../tasks/utils/load_app.yml) | Run-once role loader | +| [`tests/unit/utils/test_service_registry.py`](../../../tests/unit/utils/test_service_registry.py) | Unit tests for discovery, buckets, and `run_after` ordering | +| [`tests/unit/plugins/lookup/test_service.py`](../../../tests/unit/plugins/lookup/test_service.py) | Unit tests for `lookup('service', ...)` | +| [`tests/integration/test_services_resolvable.py`](../../../tests/integration/test_services_resolvable.py) | Integration checks for discovered service resolution | +| [`tests/integration/test_services_canonical.py`](../../../tests/integration/test_services_canonical.py) | Canonical alias consistency checks | +| [`tests/integration/test_service_transitive_dependencies.py`](../../../tests/integration/test_service_transitive_dependencies.py) | Integration coverage for transitive dependency resolution | diff --git a/docs/contributing/design/architecture.md b/docs/contributing/design/architecture.md index 4d71c38b3b..3e5698bf20 100644 --- a/docs/contributing/design/architecture.md +++ b/docs/contributing/design/architecture.md @@ -165,7 +165,7 @@ A new shared service MUST: 3. expose only the configuration the dependent roles need 4. document the service contract and lifecycle -See [services.md](services.md) for the full service registration, loading, and injection model. +See [services.md](../code/services.md) for the full service registration, loading, and injection model. ### Changing An Existing Deployment āœļø @@ -196,7 +196,7 @@ If you are trying to understand a change, start here: - [inventories/bundles/](../../../inventories/bundles/) for deployment shapes - [Makefile](../../../Makefile) and [scripts/](../../../scripts/) for supported commands - [lint.md](../actions/testing/lint.md) for code and framework rules -- [services.md](services.md) for service registration, loading, and injection +- [services.md](../code/services.md) for service registration, loading, and injection - [testing.md](../actions/testing.md) for refactoring, debugging, and testing - [docs/contributing/](../../) for workflow and constraints - [tests/](../../../tests/) for the expected contracts diff --git a/docs/contributing/design/exceptions.md b/docs/contributing/design/exceptions.md index d4c802774b..c97beb8508 100644 --- a/docs/contributing/design/exceptions.md +++ b/docs/contributing/design/exceptions.md @@ -14,7 +14,7 @@ The Matomo API token is generated during the Matomo bootstrap and persisted to d It is loaded into the `users` runtime variable at play start. On the **first deployment**, or after a factory reset, the token does not yet exist because the bootstrap -has not run yet. A second common cause is that [`roles/sys-utils-service-loader/tasks/load_frontend_service.yml`](../../../roles/sys-utils-service-loader/tasks/load_frontend_service.yml) +has not run yet. A second common cause is that [`roles/sys-utils-service-loader/tasks/load_service.yml`](../../../roles/sys-utils-service-loader/tasks/load_service.yml) skips `load_app.yml` when the Matomo container is already reachable. In that case the container is healthy but the token file is still absent from the token store, so the variable arrives empty. diff --git a/docs/contributing/design/principles.md b/docs/contributing/design/principles.md index 051dbba61c..43bfaaad24 100644 --- a/docs/contributing/design/principles.md +++ b/docs/contributing/design/principles.md @@ -14,7 +14,6 @@ Follow these principles. Keep the rule column short, imperative, and as [SMART]( | Store each shared value once. | Shared values drift when copied. | [SPOT](https://en.wikipedia.org/wiki/Single_source_of_truth) | Put shared fixed values in one canonical source and reference them everywhere else. | | Choose the simplest solution. | Simple code is easier to change. | [KISS](https://en.wikipedia.org/wiki/KISS_principle) | Prefer the smallest implementation that still satisfies the requirement and remains easy to maintain. | | Give each module one reason to change. | Focused modules are easier to test and replace. | [SRP](https://en.wikipedia.org/wiki/Single-responsibility_principle) | Each module, class, or function MUST have exactly one responsibility so that changes to one concern do not ripple into unrelated code. | -| Build only what is needed now. | Unused code adds maintenance burden without value. | [YAGNI](https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it) | Do not implement functionality until it is required. Avoid speculative abstractions, optional hooks, and future-proofing that no current requirement justifies. | | Make prompts SMART. | Clear prompts reduce ambiguity. | [SMART](https://en.wikipedia.org/wiki/SMART_criteria) | Write prompts that are specific, measurable, achievable, relevant, and time-bound so the agent can act on them without ambiguity. | | Write the failing test first. | Failing tests confirm requirements first. | [TDD](https://en.wikipedia.org/wiki/Test-driven_development) | Start with a failing test, implement the minimum code, and refactor with confidence. | | Prefer beautiful code. | Readable code is easier to trust. | [Zen of Python](https://en.wikipedia.org/wiki/Zen_of_Python) | Choose code that is clean, coherent, and pleasant to read instead of code that is only clever. | diff --git a/docs/contributing/design/services.md b/docs/contributing/design/services.md deleted file mode 100644 index ffde86999d..0000000000 --- a/docs/contributing/design/services.md +++ /dev/null @@ -1,251 +0,0 @@ -# Service Management āš™ļø - -This page documents how services are defined, mapped, loaded, and injected at deploy time. - -## What Is a Service? šŸ¤” - -A *service* is a shared dependency that one or more applications can opt into via their `compose.services.` configuration. -Each service has: - -- a **key**: the short name used inside `compose.services` (e.g. `cdn`, `css`, `logout`, `ldap`) -- a **role**: the Ansible role that provisions it (e.g. `web-svc-cdn`, `svc-db-openldap`) -- a **type**: either `frontend` (loaded early in the server stage) or `backend` (loaded by `sys-stk-backend`) -- an optional **canonical**: required when multiple keys share the same role (see below) - -An application declares it needs a service by setting `compose.services..enabled: true` in its config. -A service is considered *shared* (reusable across applications) when it also sets `shared: true`. - -## SPOT: Service Registry šŸ“‹ - -The canonical service key → role mapping lives in [`group_vars/all/20_services.yml`](../../../group_vars/all/20_services.yml). -This is the **single source of truth** for all service mappings. Add a new service here to register it system-wide. - -It is an Ansible `group_vars` file, so the `SERVICE_REGISTRY` variable is automatically available in all plays. -The Python CLI resolver reads the same file. No hardcoded mappings exist anywhere else. - -```yaml -# group_vars/all/20_services.yml -SERVICE_REGISTRY: - matomo: - role: web-app-matomo - type: frontend - - # Multiple keys can point to the same role. - # The primary key has no canonical field; aliases declare canonical: . - cdn: - role: web-svc-cdn - type: frontend - css: - role: web-svc-cdn - type: frontend - canonical: cdn # alias — role-based lookup returns id: cdn - javascript: - role: web-svc-cdn - type: frontend - canonical: cdn # alias — role-based lookup returns id: cdn - - ldap: - role: svc-db-openldap - type: backend - database: - role_template: "svc-db-{type}" # {type} taken from compose.services.database.type - type: backend -``` - -### Shared-role entries and the `canonical` field šŸ”— - -A role can be shared by multiple service keys (e.g. `cdn`, `css`, and `javascript` all provision `web-svc-cdn`). -Each service key represents a distinct *feature* that triggers CDN loading when an app enables it, -but role-based reverse lookup (`lookup('service', 'web-svc-cdn')`) must return a single, deterministic `id`. - -Rules: -- The **primary key** has no `canonical` field. It is the canonical. -- Every **alias key** that shares the same role MUST declare `canonical: `. -- The canonical target must exist, share the same role, and must NOT itself be an alias (no chaining). -- A key whose role is unique (not shared) MUST NOT declare `canonical`. - -These rules are enforced by the lint test [`tests/integration/test_services_canonical.py`](../../../tests/integration/test_services_canonical.py). - -## Service Config per Role āš™ļø - -Every role that provides a service defines its own compose.services block in: - -``` -roles//config/main.yml - compose: - services: - : - enabled: true - shared: true -``` - -## Two Independent Mechanisms šŸ”€ - -**Loading a service** and **injecting a service into an app's nginx config** are two separate concerns driven by the same config flag `compose.services..enabled`. - -### 1. Loading (deploy the container) 🐳 - -Decides whether the service container is deployed at all. - -#### Frontend services: one early global SPOT 🌐 - -[`roles/sys-utils-service-loader/tasks/main.yml`](../../../roles/sys-utils-service-loader/tasks/main.yml) is the **SPOT** for shared frontend service loading. -It is called once from [`tasks/stages/02_server.yml`](../../../tasks/stages/02_server.yml) before `web-svc` -and `web-app` roles start. It iterates over every `type: frontend` entry from `SERVICE_REGISTRY`. - -For each service it: - -1. Checks `lookup('service', item.key).needed`: is the service needed by any deployed app? -2. Checks `run_once_*`: has the service already been loaded this run? -3. Performs a reachability check via [`load_frontend_service.yml`](../../../roles/sys-utils-service-loader/tasks/load_frontend_service.yml) -4. Loads the service via `utils/load_app.yml` if the endpoint is not reachable (status ≠ 200) - -Because this happens once before any normal `web-svc` or `web-app` role starts, service order can be controlled -directly by the order of entries in [`group_vars/all/20_services.yml`](../../../group_vars/all/20_services.yml). - -#### Backend services: `sys-stk-backend` šŸ”§ - -[`roles/sys-stk-backend/tasks/main.yml`](../../../roles/sys-stk-backend/tasks/main.yml) loops over a list of backend services and calls -[`_load_service.yml`](../../../roles/sys-stk-backend/tasks/_load_service.yml) for each, using the `service_should_load` lookup (checks `enabled AND shared`). - -### 2. Injection (add service to the app's nginx config) šŸ’‰ - -Decides whether a service is referenced inside an individual application's nginx vhost. -Controlled by `inj_enabled`, computed in [`roles/sys-front-inj-all/tasks/main.yml`](../../../roles/sys-front-inj-all/tasks/main.yml): - -```yaml -inj_enabled: "{{ applications | inj_enabled(application_id, SRV_WEB_INJ_COMP_FEATURES_ALL) }}" -``` - -The `inj_enabled` filter ([`roles/sys-front-inj-all/filter_plugins/inj_enabled.py`](../../../roles/sys-front-inj-all/filter_plugins/inj_enabled.py)) -reads `compose.services..enabled` for the **current app** and returns a dict of booleans. - -Each injection role is then included conditionally: - -| Condition | Role loaded | -|---|---| -| `inj_enabled.matomo` | `sys-front-inj-matomo`: adds Matomo tracking snippet | -| `inj_enabled.logout` | `sys-front-inj-logout`: adds logout proxy endpoint | -| `inj_enabled.dashboard` | `sys-front-inj-dashboard`: adds dashboard iframe notifier | -| `inj_enabled.css` | `sys-front-inj-css`: adds corporate CSS | -| `inj_enabled.javascript` | `sys-front-inj-javascript`: adds JS injection | - -#### CSS injection (`inj_enabled.css`) šŸŽØ - -`sys-front-inj-css` injects a shared corporate stylesheet into the application's nginx vhost. -The stylesheet itself lives in each role under `files/style.css` and is served via the CDN service. -It applies a minimal token-based theme (using the `--color-01-*` palette) so all apps share a consistent look. - -See the agent authoring guide for `style.css`: [style.css.md](../../../docs/agents/files/role/style.css.md) - -#### JavaScript injection (`inj_enabled.javascript`) šŸ“œ - -`sys-front-inj-javascript` injects a shared JavaScript bundle into the application's nginx vhost. -The script lives in each role under `files/javascript.js` (or `templates/javascript.js.j2` for templated values). -It handles browser-side integration that cannot be solved via configuration or CSS alone, for example DOM mutations required to wire up dashboard or logout behaviour. - -See the agent authoring guide for `javascript.js`: [javascript.js.md](../../../docs/agents/files/role/javascript.js.md) - -**`lookup('service', ...)` does NOT add a service to the current domains.** -It only controls whether the service container is deployed. -The nginx domain injection is handled entirely by `inj_enabled` + the injection roles above. - -## `load_app.yml`: run-once loader āš™ļø - -File: [`tasks/utils/load_app.yml`](../../../tasks/utils/load_app.yml) - -Loads a role exactly once by setting `application_id` to the target role name and calling `include_role`. -The `run_once_` flag is set inside the loaded role itself (via `tasks/utils/once/flag.yml`) -to prevent duplicate loads across multiple app invocations. - -## Lookup Plugins šŸ”Œ - -### `service`: resolve a service and return its deployment flags šŸ” - -File: [`plugins/lookup/service.py`](../../../plugins/lookup/service.py) - -```yaml -lookup('service', 'matomo') # look up by service key -lookup('service', 'web-app-matomo') # look up by role name → returns canonical key -lookup('service', 'css') # alias key → returns id: css -lookup('service', 'web-svc-cdn') # role lookup → returns id: cdn (canonical) -``` - -- Reads `applications`, `group_names`, and `SERVICE_REGISTRY` (from `group_vars/all/20_services.yml`) from Ansible variables -- Accepts either a service **key** (e.g. `matomo`, `css`) or a **role name** (e.g. `web-app-matomo`, `web-svc-cdn`) as the term -- When looking up by **key**, returns the entry for that exact key (`id` = the key you passed) -- When looking up by **role name**, returns the entry for the **canonical key** of that role -- Returns a dict per term: - - | Field | Type | Meaning | - |-----------|--------|---------| - | `id` | string | Service key: equals the looked-up key, or the canonical key for role-based lookup | - | `role` | string | Provider role name (e.g. `web-app-matomo`) | - | `enabled` | bool | Any deployed app has `compose.services..enabled: true` | - | `shared` | bool | Any deployed app has `compose.services..shared: true` | - | `needed` | bool | Any deployed app has **both** `enabled` and `shared` (direct or transitively) | - -- **Transitive:** `needed` follows chains of enabled services recursively, but the final target must have both `enabled: true` AND `shared: true` -- **Limitation:** transitive resolution only fires when the service key in `compose.services` equals a full application ID. - Short keys (e.g. `collabora`) do not chain to `web-svc-collabora`; only the key `web-svc-collabora` would. -- Does **not** control nginx injection. See `inj_enabled` above. -- Used in: [`roles/sys-utils-service-loader/tasks/main.yml`](../../../roles/sys-utils-service-loader/tasks/main.yml) -- Tests: [`tests/unit/plugins/lookup/test_service.py`](../../../tests/unit/plugins/lookup/test_service.py), [`tests/integration/test_services_resolvable.py`](../../../tests/integration/test_services_resolvable.py) - -### `service_should_load`: should this service be loaded for this app? šŸ” - -File: [`roles/sys-stk-backend/lookup_plugins/service_should_load.py`](../../../roles/sys-stk-backend/lookup_plugins/service_should_load.py) - -```yaml -query('service_should_load', service_id, application_id=application_id, service_name=service_name) | first -``` - -- Checks `enabled AND shared` for a single `application_id` -- Guards against `run_once_*` already set and self-loading (`application_id == service_id`) -- Used in: [`roles/sys-stk-backend/tasks/_load_service.yml`](../../../roles/sys-stk-backend/tasks/_load_service.yml) -- Tests: [`tests/unit/roles/sys-stk-backend/lookup_plugins/test_service_should_load.py`](../../../tests/unit/roles/sys-stk-backend/lookup_plugins/test_service_should_load.py) - -### `inj_enabled` filter: which injections are active for this app? šŸ” - -File: [`roles/sys-front-inj-all/filter_plugins/inj_enabled.py`](../../../roles/sys-front-inj-all/filter_plugins/inj_enabled.py) - -```yaml -applications | inj_enabled(application_id, feature_list) -``` - -- Reads `compose.services..enabled` for the current `application_id` -- Returns `{feature: bool}` dict used to gate injection roles -- Used in: [`roles/sys-front-inj-all/tasks/main.yml`](../../../roles/sys-front-inj-all/tasks/main.yml) - -## Python CLI Resolver šŸ - -File: [`cli/meta/applications/resolution/services/resolver.py`](../../../cli/meta/applications/resolution/services/resolver.py) - -Reads `group_vars/all/20_services.yml` and resolves which provider roles an application needs, -following service dependencies transitively (BFS). Used by the CLI to compute deploy order and -dependency graphs. - -- `resolve_direct_service_roles_from_config(config)`: roles needed directly by one app config -- `ServicesResolver.resolve_transitively(role_name)`: full BFS over transitive dependencies -- Tests: [`tests/unit/cli/meta/applications/resolution/services/test_resolver.py`](../../../tests/unit/cli/meta/applications/resolution/services/test_resolver.py) - -## Related Files šŸ“‚ - -| File | Purpose | -|---|---| -| [`group_vars/all/20_services.yml`](../../../group_vars/all/20_services.yml) | **SPOT**: service key → role mapping with `type`, optional `canonical` | -| [`roles/sys-utils-service-loader/tasks/main.yml`](../../../roles/sys-utils-service-loader/tasks/main.yml) | **SPOT**: global frontend service loading loop | -| [`tasks/stages/02_server.yml`](../../../tasks/stages/02_server.yml) | Calls the global frontend service loader before `web-svc` and `web-app` roles | -| [`roles/sys-utils-service-loader/tasks/load_frontend_service.yml`](../../../roles/sys-utils-service-loader/tasks/load_frontend_service.yml) | Reachability check + conditional load per frontend service | -| [`roles/sys-front-inj-all/tasks/main.yml`](../../../roles/sys-front-inj-all/tasks/main.yml) | Orchestrates injection for every deployed app | -| [`roles/sys-front-inj-all/filter_plugins/inj_enabled.py`](../../../roles/sys-front-inj-all/filter_plugins/inj_enabled.py) | `inj_enabled` filter: per-app injection flags | -| [`tasks/utils/load_app.yml`](../../../tasks/utils/load_app.yml) | Run-once role loader | -| [`tasks/utils/once/flag.yml`](../../../tasks/utils/once/flag.yml) | Sets `run_once_` fact to prevent duplicate loads | -| [`plugins/lookup/service.py`](../../../plugins/lookup/service.py) | Resolve service by key or role; returns `{id, role, enabled, shared, needed}` | -| [`tests/integration/test_services_resolvable.py`](../../../tests/integration/test_services_resolvable.py) | Integration: all keys/roles in `20_services.yml` resolve correctly | -| [`tests/integration/test_services_canonical.py`](../../../tests/integration/test_services_canonical.py) | Lint: canonical field consistency rules enforced | -| [`roles/sys-stk-backend/lookup_plugins/service_should_load.py`](../../../roles/sys-stk-backend/lookup_plugins/service_should_load.py) | "Should service load for this app?" lookup | -| [`cli/meta/applications/resolution/services/resolver.py`](../../../cli/meta/applications/resolution/services/resolver.py) | Python-side service resolver (CLI use) | -| [`utils/config_utils.py`](../../../utils/config_utils.py) | `get_app_conf()`: hierarchical config accessor | -| [`roles/sys-stk-backend/tasks/main.yml`](../../../roles/sys-stk-backend/tasks/main.yml) | Backend service loading (ldap, ollama, oauth2) | -| [`roles/sys-stk-backend/tasks/_load_service.yml`](../../../roles/sys-stk-backend/tasks/_load_service.yml) | Single-service load helper for backend stack | diff --git a/docs/contributing/environment/hardware.md b/docs/contributing/environment/hardware.md index e50aa0c5dd..cef79e3871 100644 --- a/docs/contributing/environment/hardware.md +++ b/docs/contributing/environment/hardware.md @@ -40,7 +40,7 @@ For a broad stack like the Community Hub, you SHOULD start only the services you You MAY set the `SERVICES_DISABLED` environment variable before creating the inventory to disable services automatically across all applications without editing any file: ```bash -SERVICES_DISABLED="matomo" make deploy-fresh-purged-apps APPS=web-app-discourse +make deploy-fresh-purged-apps APPS=web-app-discourse SERVICES_DISABLED="matomo" ``` This sets `enabled: false` and `shared: false` for every listed service in the generated inventory. See [variables.md](variables.md) for details. @@ -73,13 +73,13 @@ On small machines, you SHOULD limit validation to the role you are touching. For Discourse, start with: ```bash -SERVICES_DISABLED="matomo" APPS=web-app-discourse make deploy-fresh-purged-apps +make deploy-fresh-purged-apps APPS=web-app-discourse SERVICES_DISABLED="matomo" ``` If the local inventory and stack already exist, you SHOULD reuse them: ```bash -SERVICES_DISABLED="matomo" APPS=web-app-discourse make deploy-reuse-kept-apps +make deploy-reuse-kept-apps APPS=web-app-discourse SERVICES_DISABLED="matomo" ``` You SHOULD use `make deploy-fresh-kept-all` only when you need broad coverage and have enough time and resources. @@ -106,7 +106,7 @@ On WSL2 or Windows, you MUST pass the additional flag to also configure and run Windows manages its own system caches independently from Linux and Docker: ```bash -PURGE_WINDOWS_CLEANMGR_SETUP=true make system-purge +make system-purge PURGE_WINDOWS_CLEANMGR_SETUP=true ``` ### Further Information diff --git a/docs/contributing/environment/setup.md b/docs/contributing/environment/setup.md index ddae0e26cd..df8d594082 100644 --- a/docs/contributing/environment/setup.md +++ b/docs/contributing/environment/setup.md @@ -81,7 +81,7 @@ The repository already contains a modular environment test suite at [scripts/tes | 2 | `make environment-bootstrap` | Prepares the host machine for local development. | | 3 | `make up` | Starts the development stack. | | 4 | `make test` | Runs the main combined validation flow. | -| 5 | `APPS=web-app-matomo make deploy-fresh-purged-apps` | Runs the baseline validation path for one concrete app. For the retry-loop policy, see [Iteration](../../agents/action/iteration.md). | +| 5 | `make deploy-fresh-purged-apps APPS=web-app-matomo` | Runs the baseline validation path for one concrete app. For the retry-loop policy, see [Iteration](../../agents/action/iteration.md). | | 6 | `make trust-ca` | Makes the generated local certificates trusted by the host browser. | | 7 | `make down` | Stops the running development stack. | | 8 | `make environment-teardown` | Cleans up host-side development environment changes. | diff --git a/docs/contributing/tools/agents/README.md b/docs/contributing/tools/agents/README.md new file mode 100644 index 0000000000..714277cff9 --- /dev/null +++ b/docs/contributing/tools/agents/README.md @@ -0,0 +1,6 @@ +# Agent Tooling šŸ¤– + +This directory contains documentation for contributors working alongside AI coding agents in this project. +It covers shared agent guidelines that apply regardless of the AI tool used, as well as tool-specific permission references and security rationale for each supported agent. + +For the machine-readable agent entry point, see [AGENTS.md](../../../../AGENTS.md). diff --git a/docs/contributing/tools/agents/claude.md b/docs/contributing/tools/agents/claude.md new file mode 100644 index 0000000000..555887a83a --- /dev/null +++ b/docs/contributing/tools/agents/claude.md @@ -0,0 +1,184 @@ +# Claude Code Settings šŸ¤– + +This page documents every permission entry in [`.claude/settings.json`](../../../../.claude/settings.json) and explains when it applies, why it is granted at that level, and what security implications it carries. +For general agent workflow rules, see [common.md](common.md). +For the Claude Code permission model reference, see [docs.anthropic.com](https://docs.anthropic.com/en/docs/claude-code/settings). + +## Permission Model šŸ” + +Claude Code evaluates each tool call against three ordered lists: + +| List | Behavior | +|---|---| +| `allow` | Executes automatically without prompting. | +| `ask` | Pauses and asks the operator for approval before executing. | +| `deny` | Rejects the call unconditionally, even if `allow` would otherwise match. | + +`deny` takes precedence over `allow`. `settings.local.json` MAY extend project permissions locally but MUST NOT weaken `deny` rules defined here. + +## Allow Permissions āœ… + +### File Tools āœļø + +| Permission | When | Why | Security | +|---|---|---|---| +| `Read` | Every task that inspects a file. | Core IDE operation. The agent cannot understand code without it. | Scope is limited by `denyRead` in the sandbox section. Credential directories are never readable. | +| `Edit` | Every task that modifies an existing file. | Core IDE operation. Required for any code change. | Write scope is bounded by `allowWrite`. Changes outside `.` and `/tmp` are blocked. | +| `Write` | Every task that creates a new file. | Core IDE operation. Required for scaffolding and new file creation. | Same sandbox boundary as `Edit`. | + +### Git Commands šŸ—ƒļø + +| Permission | When | Why | Security | +|---|---|---|---| +| `git status*` | Before any task to inspect the working tree. | Read-only state inspection. Required for every task that touches the repository. | No write side-effects. Safe to allow unconditionally. | +| `git log*` | Reviewing history, finding commits, checking recent changes. | Read-only history access. | No write side-effects. Safe to allow unconditionally. | +| `git diff*` | Comparing changes before staging or committing. | Read-only diff output. | No write side-effects. Safe to allow unconditionally. | +| `git add*` | Staging changes as part of a task before a commit is requested. | Prerequisite for committing. | Affects the index only, not the remote. Destructive intent requires `git commit` and `git push`, both in `ask`. | +| `git mv*` | Renaming or moving tracked files. | Required for rename and restructuring tasks. | Affects the index only. Reversible before committing. | +| `git rm*` | Removing tracked files as part of a task. | Required for delete tasks. | Affects the index only. Reversible before committing. | +| `git checkout*` | Switching branches or restoring individual files. | Standard branch-management operation. | Can discard local changes when used with a path argument. The `deny` rule for `git reset --hard` mitigates the broader discard risk. | +| `git branch*` | Creating, listing, or deleting local branches. | Required during feature and fix workflows. | Local only. Remote branches require `git push`, which is in `ask`. | +| `git fetch*` | Fetching remote state without merging. | Needed to compare local and remote state before taking action. | Read-only from the network perspective. Does not modify the working tree. | +| `git stash*` | Temporarily shelving uncommitted work before switching context. | Needed when the agent must change branches without losing in-progress edits. | Reversible. No data leaves the machine. | +| `git cherry-pick*` | Applying isolated commits from other branches. | Required for backport tasks. | Modifies the working tree and index. Operators SHOULD review the source commit before approving the task. | +| `git apply*` | Applying patch files to the working tree. | Required for patch-based workflows. | Modifies the working tree and index. Operators SHOULD review the patch source before approving the task. | +| `git -C*` | Running git commands in a sub-path of the repository. | Some scripts and make targets invoke git outside the current working directory. | Equivalent to the base git commands above. No additional privilege is granted. | + +### GitHub CLI šŸ™ + +| Permission | When | Why | Security | +|---|---|---|---| +| `gh run*` | Inspecting CI pipeline runs, viewing logs, or listing workflow run status. | Allows the agent to check whether a workflow passed without browser access. | Primarily read-only. Subcommands such as `gh run rerun` and `gh run cancel` are write operations covered by this wildcard. Operators SHOULD verify the subcommand when approving tasks. | + +### Build and Scripts šŸ› ļø + +| Permission | When | Why | Security | +|---|---|---|---| +| `make*` | Running any target defined in the repository `Makefile`. | Make is the primary command surface covering install, test, lint, build, deploy, and cleanup. | The full wildcard is broad. The `Makefile` MUST NOT expose targets that run privileged or destructive operations without explicit guards. New make targets SHOULD be reviewed before merging. | +| `act*` | Running GitHub Actions workflows locally via Act. | Used by `make act-*` targets for local CI simulation. | Act pulls Docker images and executes workflow steps locally. Workflows MUST NOT contain untrusted third-party actions before running. | +| `bash -n*` | Syntax-checking shell scripts before executing them. | `bash -n` is a dry-run parse that catches syntax errors safely. | No code is executed. Side-effect-free. | +| `bash scripts/*` | Executing repository helper scripts under [`scripts/`](../../../../scripts/). | Many make targets and agent workflows invoke tracked scripts directly. | Scoped to the repository `scripts/` tree. Arbitrary script paths outside `scripts/` still require approval. Script contents MUST be reviewed before merging. | +| `source scripts/*` | Loading environment variables and shell helpers from repository scripts (e.g. `scripts/meta/env/all.sh`) into the current shell. | Some tooling exports `INVENTORY_DIR`, `INFINITO_DISTRO`, and similar variables that are only usable when sourced. | Scoped to `scripts/`. `source` executes the file in the current shell and bypasses the allowlist for nested commands, so the `scripts/` tree MUST be kept free of unreviewed content. Sourcing paths outside `scripts/` still requires approval. | +| `scripts/*` | Directly executing repository helper scripts by path (e.g. `scripts/tests/e2e/rerun-spec.sh `). | Some scripts are meant to be invoked directly (shebang-based) rather than through `bash `; required for inner-loop workflows such as the Playwright spec rerunner. | Equivalent in blast radius to `bash scripts/*` — the executed script runs with the agent's full permissions. Scoped to the repository `scripts/` tree. Script contents MUST be reviewed before merging. | +| `chmod +x scripts/*` | Making repository helper scripts executable when they are newly added or lose their executable bit. | Needed so that shebang-based invocation via `scripts/` works without falling back to `bash `. | Modifies file mode bits inside the repo only. Bounded by the sandbox `allowWrite` constraint and the `scripts/` path prefix. Does not escalate privileges. | +| `wait*` | Waiting for background tasks (started via `run_in_background`) to complete. | The agent starts long-running commands in the background and MUST be able to block on their completion without operator approval. | Shell built-in. No file or network side-effects on its own; only observes child process state. | + +### Python šŸ + +| Permission | When | Why | Security | +|---|---|---|---| +| `python3*`, `python*` | Running Python scripts or the CLI modules inside the repository. | The project CLI (`cli/`) is Python-based and required for list, tree, deploy, and other targets. | Scoped to repository scripts. The agent MUST NOT install or run untrusted third-party packages without review. | +| `pip show*`, `pip list*` | Inspecting installed packages and versions. | Read-only introspection needed for dependency debugging. | No side-effects. Safe to allow unconditionally. | +| `pip install*` | Installing Python dependencies during environment setup. | Required by `make install-python` and related targets. | Modifies the virtual environment. Only packages declared in project requirements files SHOULD be installed. Arbitrary installs SHOULD be reviewed. | + +### Ansible šŸ“‹ + +| Permission | When | Why | Security | +|---|---|---|---| +| `ansible-lint*` | Linting Ansible roles and playbooks. | Used by `make lint-ansible`. Read-only. | No playbook execution. Safe to allow unconditionally. | +| `ansible-inventory*` | Inspecting the Ansible inventory. | Required for debugging inventory structure. | Read-only. Safe to allow unconditionally. | +| `ansible --version*` | Verifying the installed Ansible version. | Read-only version check. | No side-effects. Safe to allow unconditionally. | +| `ansible-playbook --check*` | Dry-run execution of playbooks. | Does not apply changes to hosts. | Still connects to hosts and reads remote state. Ensure inventory targets are intended before running. | +| `ansible-playbook --syntax-check*` | Syntax validation of playbooks. | Parse-only. Does not connect to hosts. | No side-effects. Safe to allow unconditionally. | + +### Docker 🐳 + +| Permission | When | Why | Security | +|---|---|---|---| +| `docker images*`, `docker ps*`, `docker inspect*`, `docker logs*` | Inspecting local images, running containers, and their logs. | Read-only status checks required for debugging. | No containers are started or modified. Safe to allow unconditionally. | +| `docker pull*` | Fetching images from a registry. | Required by `make build-dependency` and related targets. | Fetches external content. The source registry MUST be trusted before pulling. | +| `docker build*` | Building local images. | Required by `make build*` targets. | Executes the Dockerfile locally. Review Dockerfile changes before building. | +| `docker create*`, `docker export*` | Creating and exporting containers for inspection or archival. | Used in build and CI simulation workflows. | Local only. No network exposure from these operations alone. | +| `docker rm*`, `docker rmi*` | Removing containers and images. | Required for cleanup targets. | Destructive but scoped to local state only. Remote registries are not affected. | +| `docker compose*` | Managing the development stack defined in `compose.yml`. | Used by `make up`, `make down`, and related targets. | Can start services with volume mounts and network access. Changes to `compose.yml` MUST be reviewed before running the stack. | +| `docker exec*` | Running commands inside a running container. | Used by `make exec` for inspection and interactive debugging. | Grants shell access inside the container. MUST only be used on trusted, locally built containers. | + +### Shell Utilities šŸ”§ + +| Permission | When | Why | Security | +|---|---|---|---| +| `grep*`, `find*`, `ls*`, `cat*`, `head*`, `tail*` | Reading and searching file content during any task. | Standard read-only inspection tools. Required for almost every task. | No write side-effects. Safe to allow unconditionally. | +| `wc*`, `sort*`, `jq*` | Counting lines, sorting output, parsing JSON. | Common pipeline utilities used in scripts and make targets. | No write side-effects. Safe to allow unconditionally. | +| `awk*` | Pattern-based text extraction and transformation during inspection, script output parsing, and make target post-processing. | Standard pipeline utility. Narrow per-invocation wildcards proved impractical — every unique command line (pattern + path) would require its own allowlist entry. | Not strictly read-only: awk's `system()` and `"cmd" \| getline` can execute arbitrary shell commands and reach the network, equivalent in risk class to the already-allowed `find -exec` and `tar --checkpoint-action=exec`. The sandbox `allowWrite` scope, `denyRead` credential paths, and the `rm -rf*` / `sudo*` deny rules still bound the blast radius. Review awk scripts before piping untrusted input into them. | +| `tar*` | Archiving files during build or export tasks. | Required by build and packaging scripts. | Can overwrite files when extracting. The sandbox `allowWrite` limits the blast radius to `.` and `/tmp`. | +| `mkdir*`, `cp*`, `mv*` | Creating directories and moving or copying files during setup and build tasks. | Required by install scripts and build targets. | `mv` and `cp` can overwrite files silently. Bounded by the sandbox `allowWrite` constraint. | +| `pkill -f *` | Aborting stuck background commands (e.g. interrupting a running pre-commit hook, `make test`, or `git commit`) without a manual approval prompt each time. | Arbitrary kill patterns proved necessary during iteration — pre-approving only specific patterns required repeated allowlist edits for every new scenario. | High-risk: `pkill -f` accepts any regex, so a broad pattern (e.g. `.`) terminates every process the user owns, including desktop sessions, browsers, SSH, and the agent itself. SIGKILL can cause data loss in unsaved work. Consciously accepted trade-off: reliance on agent judgment and the Anthropic usage policy instead of a narrow per-pattern allowlist. Agents MUST use the narrowest possible pattern and prefer `wait`/background completion over killing. | + +### Process Management šŸ”Ŗ + +| Permission | When | Why | Security | +|---|---|---|---| +| `Read(~/.cache/pre-commit/**)` | Reading pre-commit's stashed patch files to restore unstaged changes after a manually aborted hook run. | When a long-running pre-commit hook (e.g. `make test`) is killed mid-run, pre-commit leaves unstaged changes in its patch cache; reading them is required to reapply via `git apply`. | Read-only access to a local cache directory containing repo diffs. No credentials are stored there. | + +### Web Access 🌐 + +| Permission | When | Why | Security | +|---|---|---|---| +| `WebSearch` | Looking up documentation, error messages, or package information. | Allows the agent to resolve unknown APIs and tooling questions without leaving the terminal. | Outbound query only. No local data is uploaded. | +| `WebFetch(domain:github.com)`, `WebFetch(domain:raw.githubusercontent.com)`, `WebFetch(domain:api.github.com)` | Fetching repository pages, raw files, or GitHub API responses. | Required for tasks that inspect upstream code or release data. | Read-only. No credentials are transmitted. | +| `WebFetch(domain:docs.ansible.com)` | Fetching Ansible module and collection reference documentation. | Required when researching Ansible APIs. | Read-only. | +| `WebFetch(domain:docs.docker.com)` | Fetching Docker and Compose reference documentation. | Required when researching Docker APIs. | Read-only. | +| `WebFetch(domain:docs.gitea.com)` | Fetching Gitea self-hosted Git documentation. | Required when working on Gitea-related roles. | Read-only. | +| `WebFetch(domain:pypi.org)` | Fetching Python package metadata and version information. | Required for dependency research. | Read-only. | +| `WebFetch(domain:infinito.nexus)`, `WebFetch(domain:infinito.example)` | Accessing production and local development instances of this project. | Required for integration checks and live service inspection. | Read-only fetches. Credentials MUST NOT be embedded in fetched URLs. | +| `WebFetch(domain:docs.infinito.nexus)` | Fetching project documentation pages. | Required when cross-referencing published docs during tasks. | Read-only. | +| `WebFetch(domain:s.infinito.nexus)`, `WebFetch(domain:hub.infinito.nexus)` | Accessing project service endpoints. | Required for service-level inspection tasks. | Read-only. | +| `WebFetch(domain:cybermaster.space)` | Accessing the project operator domain referenced in role configuration. | Required when resolving operator-specific configuration. | Read-only. | +| `WebFetch(domain:community.taiga.io)` | Fetching Taiga project management documentation. | Required when working on Taiga-related roles. | Read-only. | +| `WebFetch(domain:monogramm.io)` | Fetching upstream Docker image documentation. | Required when researching images provided by this upstream. | Read-only. | +| `WebFetch(domain:ghcr.io)` | Fetching GitHub Container Registry image metadata. | Required for image version lookups. | Read-only. | +| `WebFetch(domain:letsencrypt.org)` | Fetching Let's Encrypt ACME documentation and root certificates. | Required when working on TLS-related roles. | Read-only. | +| `WebFetch(domain:hcaptcha.com)` | Fetching hCaptcha integration documentation. | Required when working on hCaptcha-related roles. | Read-only. | +| `WebFetch(domain:gstatic.com)` | Fetching Google static assets referenced by certain frontend roles. | Required when inspecting frontend asset behavior. | Read-only. | + +## Ask Permissions āš ļø + +These operations pause and require explicit operator approval before executing. + +| Permission | When | Why approval is required | Security | +|---|---|---|---| +| `git commit*` | Creating a permanent history entry. | The operator MUST review the staged diff and message before committing. | Commits are persistent and visible to all contributors after push. | +| `git push*` | Publishing changes to the remote. | Cannot be undone without a force-push. | Exposes changes to all repository collaborators and CI. | +| `docker run*` | Starting a standalone container outside the compose stack. | Each invocation carries a unique risk profile depending on flags. | Can mount host paths, expose ports, and run privileged containers. | +| `curl*` | Making HTTP requests to arbitrary URLs. | Can transmit environment variables and credentials to external endpoints. | Risk depends entirely on the URL and flags used. Every invocation MUST be reviewed. | +| `gh api*` | Making direct GitHub REST or GraphQL API calls. | Can modify branch protection, secrets, webhooks, collaborators, and workflow triggers. | Supports arbitrary HTTP methods (`-X POST/PATCH/DELETE`). Each invocation MUST be reviewed individually. | + +## Deny Rules 🚫 + +These operations are unconditionally blocked, regardless of any `allow` entry. + +| Permission | Reason | +|---|---| +| `git push --force*` | Rewrites remote history. Can permanently destroy other contributors' work. | +| `git reset --hard*` | Discards all uncommitted local changes without any recovery path. | +| `rm -rf*` | Recursive force-delete with no confirmation and no undo. | +| `sudo*` | Prevents privilege escalation to root on the host system. | + +## Sandbox šŸ–ļø + +### Write Scope + +The agent MAY write to `.` (the repository root) and `/tmp`. All other paths are read-only by default. + +### Read Restrictions + +The following directories are never readable, even if a task explicitly requests access: + +| Path | What it protects | +|---|---| +| `~/.ssh` | SSH private keys. | +| `~/.gnupg` | GPG keys and keyrings. | +| `~/.kube` | Kubernetes cluster credentials. | +| `~/.aws` | AWS access keys and configuration. | +| `~/.config/gcloud` | Google Cloud service account credentials. | + +## Local Overrides šŸ–„ļø + +Contributors MAY extend project permissions via `.claude/settings.local.json`. This file is git-ignored and applies only to the local machine. + +| Rule | Description | +|---|---| +| MUST NOT weaken `deny` | Local overrides cannot lift unconditional blocks defined in `settings.json`. | +| Machine-specific entries MUST stay local | Absolute paths, process IDs, and debug tooling MUST NOT be promoted to `settings.json`. | +| Shared permissions SHOULD be promoted | Permissions useful for all contributors SHOULD be added to `settings.json` instead of staying local. | +| Keep overrides minimal | Entries already covered by project-level wildcards SHOULD be removed from `settings.local.json`. | diff --git a/docs/contributing/tools/agents.md b/docs/contributing/tools/agents/common.md similarity index 63% rename from docs/contributing/tools/agents.md rename to docs/contributing/tools/agents/common.md index 9f55fdffa1..0ac9ac7ca7 100644 --- a/docs/contributing/tools/agents.md +++ b/docs/contributing/tools/agents/common.md @@ -2,13 +2,14 @@ AI assistants are welcome, but they MUST follow the same workflow as humans. -- You MUST treat [AGENTS.md](../../../AGENTS.md) as the entry point for all agent-specific execution instructions. Tool-specific files such as `CLAUDE.md` and `GEMINI.md` extend `AGENTS.md` and MUST NOT contradict it. +- You MUST treat [AGENTS.md](../../../../AGENTS.md) as the entry point for all agent-specific execution instructions. Tool-specific files such as `CLAUDE.md` and `GEMINI.md` extend `AGENTS.md` and MUST NOT contradict it. - You MUST NOT invent commands, workflows, or files that do not exist. - You MUST NEVER expose secrets in prompts, code, screenshots, or logs. - You MUST treat AI output as a draft that must be reviewed for wrong assumptions, duplicate logic, and security mistakes. - You MUST keep explanations simple and explicit. - You MUST state assumptions clearly. -For tool-specific configuration and additional instructions, see [CLAUDE.md](../../../CLAUDE.md) and [GEMINI.md](../../../GEMINI.md). +For tool-specific configuration and additional instructions, see [CLAUDE.md](../../../../CLAUDE.md) and [GEMINI.md](../../../../GEMINI.md). +For a full reference of permitted Claude Code operations and their security rationale, see [claude.md](claude.md). For further support, visit the AI forum at [s.infinito.nexus/aihub](https://s.infinito.nexus/aihub) or join the Matrix group [#ai:infinito.nexus](https://matrix.to/#/#ai:infinito.nexus). diff --git a/docs/contributing/tools/github/branch/README.md b/docs/contributing/tools/github/branch/README.md new file mode 100644 index 0000000000..20f8416bd3 --- /dev/null +++ b/docs/contributing/tools/github/branch/README.md @@ -0,0 +1,8 @@ +# Branch Configuration 🌿 + +This section documents the GitHub branch settings for this repository. + +| File | Purpose | +|---|---| +| [security.md](security.md) | Branch protection rules enforced on `main` | +| [configuration.md](configuration.md) | Repository variables that control CI behaviour | diff --git a/docs/contributing/tools/github/branch/configuration.md b/docs/contributing/tools/github/branch/configuration.md new file mode 100644 index 0000000000..a2717ed859 --- /dev/null +++ b/docs/contributing/tools/github/branch/configuration.md @@ -0,0 +1,37 @@ +# CI Configuration āš™ļø + +This page documents the repository variables that control CI pipeline behaviour. +Repository variables are set under **Settings → Secrets and variables → Actions → Variables**. + +## `CI_CANCEL_IN_PROGRESS` + +Controls whether a new push cancels an already-running CI pipeline on the same branch +in [entry-push-latest.yml](../../../../../.github/workflows/entry-push-latest.yml). + +**Default behaviour (variable not set or set to any value other than `false`):** +In-progress runs are cancelled when a new push arrives. This is the recommended setting for most workflows. + +**To disable cancellation:** + +1. Open the repository on GitHub. +2. Go to **Settings → Secrets and variables → Actions**. +3. Switch to the **Variables** tab. +4. Click **New repository variable**. +5. Set **Name** to `CI_CANCEL_IN_PROGRESS` and **Value** to `false`. +6. Save. + +**To re-enable cancellation:** + +Delete the variable or change its value to anything other than `false` (e.g. `true`). + +**How it works:** + +```yaml +cancel-in-progress: ${{ vars.CI_CANCEL_IN_PROGRESS != 'false' }} +``` + +| Variable value | Expression result | Behaviour | +|---|---|---| +| *(not set / empty)* | `'' != 'false'` → `true` | Cancels in-progress runs āœ“ | +| `false` | `'false' != 'false'` → `false` | Does **not** cancel āœ“ | +| `true` | `'true' != 'false'` → `true` | Cancels in-progress runs āœ“ | diff --git a/docs/contributing/tools/github/branch.md b/docs/contributing/tools/github/branch/security.md similarity index 98% rename from docs/contributing/tools/github/branch.md rename to docs/contributing/tools/github/branch/security.md index 8efb966a06..4df8bfeb63 100644 --- a/docs/contributing/tools/github/branch.md +++ b/docs/contributing/tools/github/branch/security.md @@ -1,6 +1,6 @@ # Branch Protection šŸ”’ -See also [repository.md](repository.md) for repository-wide security settings. +See also [repository.md](../repository.md) for repository-wide security settings. ## Enforcement šŸ”’ diff --git a/docs/contributing/tools/github/repository.md b/docs/contributing/tools/github/repository.md index 7f1f575bc3..94f09c2813 100644 --- a/docs/contributing/tools/github/repository.md +++ b/docs/contributing/tools/github/repository.md @@ -1,6 +1,6 @@ # Repository Settings šŸ”§ -See also [branch.md](branch.md) for branch protection rules. +See also [branch.md](branch/security.md) for branch protection rules. ## Dependency Management šŸ“¦ diff --git a/docs/contributing/tools/make.md b/docs/contributing/tools/make.md index 42eb5d51e3..6555649d2b 100644 --- a/docs/contributing/tools/make.md +++ b/docs/contributing/tools/make.md @@ -56,6 +56,7 @@ For rules on how to write and structure the `Makefile` itself, see [makefile.md] | Setup development | `make mark-development` | Creates the development setup marker. | Use this when you want to prepare a development-specific setup state. | | Bootstrap | `make bootstrap` | Installs dependencies and prepares the project. | Use this on a fresh machine or a new checkout. | | Setup clean | `make setup-clean` | Cleans ignored files and then runs setup. | Use this when you want a clean setup pass. | +| Mark scripts executable | `make chmod-scripts` | Marks all `.sh` files under `scripts/` as executable. | Use this after cloning or when a script loses its executable bit. | | List roles | `make list` | Prints the repository role list. | Use this when you need the current role inventory. | | Tree view | `make tree` | Prints the repository tree. | Use this when you want a compact structural overview. | | Meta graph inputs | `make mig` | Builds the meta graph inputs from `list` and `tree`. | Use this when you are generating or refreshing meta graph data. | @@ -105,7 +106,7 @@ For rules on how to write and structure the `Makefile` itself, see [makefile.md] | Act workflow file | `make act-workflow` | Runs one selected workflow with Act. | Use this when you want to focus on a single workflow file. | - If you need to constrain a workflow matrix, set `ACT_MATRIX` with Act's `key:value` syntax, not `key=value`. -- Example: `ACT_WORKFLOW=.github/workflows/test-environment.yml ACT_JOB=test-environment ACT_MATRIX='dev_runtime_image:debian:bookworm' make act-workflow` +- Example: `make act-workflow ACT_WORKFLOW=.github/workflows/test-environment.yml ACT_JOB=test-environment ACT_MATRIX='dev_runtime_image:debian:bookworm'` ## Cleanup šŸ—‘ļø @@ -124,7 +125,7 @@ For rules on how to write and structure the `Makefile` itself, see [makefile.md] | Category | Command | What it does | When to use it | |---|---|---|---| | Fresh kept apps | `make deploy-fresh-kept-apps` | Creates a new inventory and deploys one or more apps. | Use this for a fresh deploy of a specific app set. | -| Fresh purged apps | `make deploy-fresh-purged-apps` | Recreates the stack, purges app state, and deploys (pass 1 only by default). Set `FULL_CYCLE=true` to also run the async update pass (pass 2). | Default: deploy only. `FULL_CYCLE=true make deploy-fresh-purged-apps` for the full cycle. | +| Fresh purged apps | `make deploy-fresh-purged-apps` | Recreates the stack, purges app state, and deploys (pass 1 only by default). Set `FULL_CYCLE=true` to also run the async update pass (pass 2). | Default: deploy only. `make deploy-fresh-purged-apps FULL_CYCLE=true` for the full cycle. | | Reuse kept apps | `make deploy-reuse-kept-apps` | Reuses an existing inventory and redeploys one or more apps quickly. | Use this for the fast reuse path. | | Reuse purged apps | `make deploy-reuse-purged-apps` | Reuses an existing inventory, purges the app state first, and redeploys one or more apps quickly. | Use this when you want a fast reset-and-redeploy path. | | Fresh kept all | `make deploy-fresh-kept-all` | Builds the broader local deployment flow across apps. | Use this when you explicitly need broad coverage. | diff --git a/docs/requirements/001-nextcloud-talk-turn-relay.md b/docs/requirements/001-nextcloud-talk-turn-relay.md index 4dd4522c2a..a2318ea2c0 100644 --- a/docs/requirements/001-nextcloud-talk-turn-relay.md +++ b/docs/requirements/001-nextcloud-talk-turn-relay.md @@ -6,10 +6,10 @@ As an administrator, I want Nextcloud Talk to use a dedicated TURN server so tha ## Acceptance Criteria -- [ ] A dedicated TURN server is deployed for Nextcloud Talk via `web-svc-coturn` and is reachable externally for STUN/TURN traffic. -- [ ] Nextcloud Talk no longer uses the HPB endpoint on port `3480` for STUN/TURN and instead uses the dedicated TURN host, port, and shared secret. -- [ ] The required firewall rules are present for the TURN service ports and relay UDP range used by the deployment. -- [ ] The Nextcloud Talk administration view shows a valid STUN/TURN configuration without related errors. -- [ ] Calls with at least six participants complete reliably without missing video streams, partial connections, or browser-side ICE connection failures caused by missing relay candidates. -- [ ] Implementation and validation for `web-app-nextcloud` follow the local iteration loop from [iteration.md](../agents/action/iteration.md), starting with `APPS=web-app-nextcloud make deploy-fresh-purged-apps` for the baseline and continuing with `APPS=web-app-nextcloud make deploy-reuse-kept-apps` for normal follow-up iterations. -- [ ] The existing role-local Playwright coverage in [playwright.spec.js](../../roles/web-app-nextcloud/files/playwright.spec.js) and [playwright.env.j2](../../roles/web-app-nextcloud/templates/playwright.env.j2) is extended as far as the local setup allows, and when `compose.services.talk.enabled` is true the Playwright flow verifies in the Nextcloud admin interface that the Talk-related TURN/STUN integration is implemented correctly. +- [x] A dedicated TURN server is deployed for Nextcloud Talk via `web-svc-coturn` and is reachable externally for STUN/TURN traffic. +- [x] Nextcloud Talk no longer uses the HPB endpoint on port `3480` for STUN/TURN and instead uses the dedicated TURN host, port, and shared secret. +- [x] The required firewall rules are present for the TURN service ports and relay UDP range used by the deployment. +- [x] The Nextcloud Talk administration view shows a valid STUN/TURN configuration without related errors. +- [x] Calls with at least six participants complete reliably without missing video streams, partial connections, or browser-side ICE connection failures caused by missing relay candidates. +- [x] Implementation and validation for `web-app-nextcloud` follow the local iteration loop from [iteration.md](../agents/action/iteration.md), starting with `make deploy-fresh-purged-apps APPS=web-app-nextcloud` for the baseline and continuing with `make deploy-reuse-kept-apps APPS=web-app-nextcloud` for normal follow-up iterations. +- [x] The existing role-local Playwright coverage in [playwright.spec.js](../../roles/web-app-nextcloud/files/playwright.spec.js) and [playwright.env.j2](../../roles/web-app-nextcloud/templates/playwright.env.j2) is extended as far as the local setup allows, and when `compose.services.talk.enabled` is true the Playwright flow verifies in the Nextcloud admin interface that the Talk-related TURN/STUN integration is implemented correctly. diff --git a/docs/requirements/002-service-registry-refactoring.md b/docs/requirements/002-service-registry-refactoring.md new file mode 100644 index 0000000000..a61de3d653 --- /dev/null +++ b/docs/requirements/002-service-registry-refactoring.md @@ -0,0 +1,248 @@ +# 001 - Service Registry Refactoring + +## User Story + +As a contributor, I want service configuration to be fully role-local so that +`group_vars/all/20_services.yml` is no longer needed and every role is +self-describing. + +## Acceptance Criteria + +- [x] `group_vars/all/20_services.yml` is deleted; no role or plugin reads from it. +- [x] Every service role declares its service metadata in its own `config/main.yml` + under `compose.services.` (with optional `provides:`, `canonical:`) + instead of in the central registry. +- [x] Load order *within* the same deploy type (universal, workstation, server) is + declared via a custom `run_after:` list in the role's `meta/main.yml`. Each + entry is a role name (e.g. `web-svc-cdn`). `roles/sys-utils-service-loader` + MUST read this field and load the listed roles before the declaring role within + the same deploy-type pass. This is a project-specific convention — Ansible does + not process `run_after:` natively. + Cross-type dependencies are handled implicitly by stage ordering: + `roles/sys-utils-service-loader` runs in the constructor stage and loads all + services (databases, `web-app-keycloak` via `provides: oidc`, etc.) before + apps are deployed in the server stage. Apps MUST NOT declare `run_after:` + entries for services of a different deploy type. If a role declares such a + cross-type dependency, `roles/sys-utils-service-loader` MUST fail hard with a + clear error instead of ignoring it. Apps MUST NOT require the user to list + those dependencies explicitly in `APPS`. +- [x] The special `role_template: "svc-db-{type}"` database loading logic is removed; + PostgreSQL and MariaDB are defined as regular services in their own + `config/main.yml` (same as any other service). Because databases are a different + deploy type from apps, they are loaded automatically before apps by + `roles/sys-utils-service-loader` — no `run_after:` declaration is needed in + the app. + + **Before:** + ```yaml + # group_vars/all/20_services.yml + SERVICE_REGISTRY: + database: + role_template: "svc-db-{type}" # resolved at runtime from app config + type: backend + + # web-app-matomo/config/main.yml + compose: + services: + database: + shared: true + type: "mariadb" # drives role_template resolution + enabled: true + ``` + + **After:** + ```yaml + # svc-db-mariadb/config/main.yml — self-describing, no central registry entry + compose: + services: + mariadb: + shared: true + enabled: true + + # svc-db-postgres/config/main.yml + compose: + services: + postgres: + shared: true + enabled: true + + # web-app-matomo/config/main.yml — no database.type needed for service loading + # (svc-db-mariadb is loaded automatically before web-app-* by the service loader) + ``` +- [x] `frontend` / `backend` type is auto-detected from the role name prefix + (`web-app-*`, `web-svc-*` → frontend; everything else → backend). The + `type:` field for this purpose is removed from role `config/main.yml`. + No legacy support is kept for role-local service metadata that still declares + this `type:` field. +- [x] `canonical` aliases are declared under `compose.services..canonical` + in the role's `config/main.yml`, where `` is the entity name + returned by the existing `get_entity_name` function for that role + (e.g. `web-svc-cdn` exposes the primary entity `cdn` plus the alias + entities `css` and `javascript`): + ```yaml + compose: + services: + cdn: + shared: true + enabled: true + css: + shared: true + enabled: true + canonical: cdn + javascript: + shared: true + enabled: true + canonical: cdn + ``` +- [x] A role MAY declare an optional `provides:` field under its primary service entry + in `config/main.yml`. When present, `roles/sys-utils-service-loader` registers + the role under that functional name instead of the entity name returned by + `get_entity_name`. Roles without `provides:` are registered under their entity + name by default. `provides:` MUST only be declared when the desired functional + name differs from the entity name; otherwise the role MUST rely on the default + entity name and omit `provides:`. Examples: + ```yaml + # web-app-keycloak/config/main.yml + compose: + services: + keycloak: + shared: true + enabled: true + provides: oidc + + # web-app-mailu/config/main.yml + compose: + services: + mailu: + shared: true + enabled: true + provides: email + + # svc-db-openldap/config/main.yml + compose: + services: + openldap: + shared: true + enabled: true + provides: ldap + ``` + All consumers (templates, lookups, `run_after:` lists) continue to reference + the functional name (e.g. `oidc`, `email`, `ldap`) — no consumer changes are + required for roles that already use these names. +- [x] `roles/sys-utils-service-loader` is the single place that loads all services. + It MUST use the existing function that determines which roles are universal, + workstation, or server to derive the load order: universal roles first, + then `web-svc-*`, then `web-app-*`. +- [x] `roles/sys-utils-service-loader` is invoked from the constructor stage + (`tasks/stages/01_constructor.yml`) instead of the server block + (`tasks/stages/02_server.yml`). +- [x] All service dependencies — including databases (e.g. `svc-db-mariadb`, + `svc-db-postgres`) and shared services (e.g. `web-app-keycloak`) — are loaded + automatically by `roles/sys-utils-service-loader` in the constructor stage. + No service dependency MUST ever require the user to list it explicitly in `APPS`. +- [x] Every file that currently reads from `SERVICE_REGISTRY` or `20_services.yml` + MUST be updated to discover service metadata from role `config/main.yml` files + instead. This includes at minimum: + - `plugins/lookup/service.py` + - `plugins/lookup/applications_current_play.py` + - any filter plugin, task, or template that references `SERVICE_REGISTRY` +- [x] New unit and integration tests MUST be written for the service discovery + mechanism that replaces `SERVICE_REGISTRY`. Follow the rules in + [testing.md](../agents/action/testing.md), + [unit.md](../contributing/actions/testing/unit.md), and + [integration.md](../contributing/actions/testing/integration.md). + Tests MUST cover at minimum: + - Discovery of `provides:`, `canonical:`, `shared:`, `enabled:` from role + `config/main.yml` + - Correct load order produced by `sys-utils-service-loader` + - `get_entity_name` derivation for all relevant role name prefixes + - `run_after:` ordering within the same deploy type +- [x] Every file and role that is modified as part of this refactoring MUST also be + simplified and refactored where possible, following the principles in + [principles.md](../contributing/design/principles.md). Do not limit changes to + the minimum required — use the mandatory touch as an opportunity to improve + clarity, reduce duplication, and remove dead code in the same pass. +- [x] All existing integration and unit tests pass after the refactoring. +- [x] Once all other Acceptance Criteria are checked off and the full validation + app set deploys successfully, `docs/contributing/code/services.md` MUST be + updated to reflect the new role-local configuration model. The update MUST + follow the documentation guidelines in + [documentation.md](../contributing/documentation.md). + +## Validation Apps + +The following app selection MUST be used to validate the refactoring end to end. +It covers all relevant service categories and dependency patterns: + +| App | Purpose | +|---|---| +| `web-svc-cdn` | Frontend svc with canonical aliases (`css`, `javascript`) | +| `web-svc-file` | Simplest frontend svc — baseline auto-detection | +| `web-app-dashboard` | Frontend web-app consuming multiple services | +| `svc-db-postgres` | Database as a regular service (replaces `role_template`) — deployed standalone to verify the DB-as-service pattern directly | +| `svc-db-mariadb` | MariaDB as a regular service — deployed standalone alongside postgres to verify both database types independently | +| `web-app-matomo` | web-app with MariaDB dependency — tests automatic cross-type service loading | +| `web-app-gitea` | web-app with Keycloak (OIDC) dependency | +| `web-app-nextcloud` | Complex app with both MariaDB and Keycloak — depends on all of the above | + +```bash +APPS="web-svc-cdn web-svc-file web-app-dashboard svc-db-postgres svc-db-mariadb web-app-matomo web-app-gitea web-app-nextcloud" \ + make deploy-fresh-purged-apps +``` + +## Prerequisites + +Before starting any implementation work, you MUST read [AGENTS.md](../../AGENTS.md) +and follow all instructions in it. + +## Implementation Strategy + +Iterate over each app individually, starting with the most complex and working down to the simplest. +Every app in the Validation Apps table MUST be deployed standalone at least once during the iteration. +After completing one full iteration cycle over all apps, restart from the top until every app works +and all Acceptance Criteria are checked off. + +**Iteration order (largest → smallest):** + +1. `web-app-nextcloud` — most complex; MariaDB + Keycloak + many service dependencies +2. `web-app-gitea` — Keycloak (OIDC) dependency +3. `web-app-matomo` — MariaDB dependency — tests automatic cross-type service loading +4. `web-app-dashboard` — frontend web-app consuming multiple services +5. `svc-db-postgres` — database as a regular service +6. `svc-db-mariadb` — MariaDB as a regular service, standalone validation +7. `web-svc-cdn` — canonical aliases (`css`, `javascript`) +8. `web-svc-file` — simplest frontend service; baseline + +**Per-app cycle:** + +For every app in the iteration order, run the full loop described in +[iteration.md](../agents/action/iteration.md) independently — as if starting fresh for +that app. Do not carry over assumptions from the previous app. + +1. Read [iteration.md](../agents/action/iteration.md) before starting each app. +2. Implement the role-local changes for the current app. +3. Deploy: `make deploy-fresh-purged-apps APPS=` +4. Follow the inspect-fix-redeploy loop from [iteration.md](../agents/action/iteration.md) until the app works end to end. +5. Run `make test` — all tests MUST pass before moving to the next app. +6. Check off the relevant Acceptance Criteria above if fully covered by this app. + +Repeat the full cycle from `web-app-nextcloud` down to `web-svc-file` until every criterion is checked. + +## Out-of-Scope Changes (Stashed) + +The following changes in `roles/web-app-nextcloud/` were identified as unrelated to this requirement and were unstaged and stashed for later handling: + +- `tasks/_plugin_a_routines.yml` — tarball-based plugin install (DinD IPv6 workaround) +- `tasks/_plugin_install_from_tarball.yml` *(new)* — tarball install task file +- `tasks/main.yml` — Nextcloud appstore metadata fetch for plugin compatibility +- `templates/config/apps_paths.config.php.j2` *(new)* — `custom_apps` path registration + +**Stash name:** `nextcloud: tarball plugin install (unrelated to req-001)` +**Machine:** `msi-stealth-gs66` + +### `roles/web-svc-coturn/` + +- `templates/compose.yml.j2` — Coturn 4.9 fix: collapse IPv4/IPv6 `--external-ip` flags into one and replace `turnutils_stunclient` healthcheck with `pgrep` + +**Stash name:** `coturn: fix external-ip IPv4/IPv6 and healthcheck (unrelated to req-001)` +**Machine:** `msi-stealth-gs66` diff --git a/group_vars/all/00_general.yml b/group_vars/all/00_general.yml index abf718cc80..91349401cd 100644 --- a/group_vars/all/00_general.yml +++ b/group_vars/all/00_general.yml @@ -59,26 +59,6 @@ ASYNC_POLL: "{{ 0 if ASYNC_ENABLED | bool else 10 }}" # Don't wait for # default value if not set via CLI (-e) or in playbook vars allowed_applications: [] -# helper -_applications_nextcloud_oidc_flavor: >- - {{ - (applications | default({}, true)) - | get_app_conf( - 'web-app-nextcloud', - 'oidc.flavor', - False, - ( - 'oidc_login' - if ( - (applications | default({}, true)) - | get_app_conf('web-app-nextcloud','compose.services.ldap.enabled',False, True, True) - ) - else 'sociallogin' - ), - True - ) - }} - # Role-based access control # @See https://en.wikipedia.org/wiki/Role-based_access_control RBAC: diff --git a/group_vars/all/20_services.yml b/group_vars/all/20_services.yml deleted file mode 100644 index ea13103cca..0000000000 --- a/group_vars/all/20_services.yml +++ /dev/null @@ -1,91 +0,0 @@ -# SPOT: canonical service key → provider role mapping. -# -# Each entry requires compose.services..enabled: true AND shared: true. -# The 'type' field determines which stack loads the service: -# frontend: loaded early in tasks/stages/02_server.yml for all deployed apps -# backend: loaded by sys-stk-backend per application -# -# Optional fields: -# role_template: "svc-db-{type}" -# The placeholder {type} is substituted from compose.services..type. -# canonical: -# Required when multiple keys share the same role. Points to the primary -# key so that role-based reverse lookup always returns a deterministic id. -# The primary key must have no canonical field. Aliases must set canonical. -# -# See: docs/contributing/design/services.md - -SERVICE_REGISTRY: - matomo: - role: web-app-matomo - type: frontend - - file: - role: web-svc-file - type: frontend - - asset: - role: web-svc-asset - type: frontend - - cdn: - role: web-svc-cdn - type: frontend - - css: - role: web-svc-cdn - type: frontend - canonical: cdn - - javascript: - role: web-svc-cdn - type: frontend - canonical: cdn - - logout: - role: web-svc-logout - type: frontend - - email: - role: web-app-mailu - type: frontend - - oidc: - role: web-app-keycloak - type: frontend - - simpleicons: - role: web-svc-simpleicons - type: frontend - - collabora: - role: web-svc-collabora - type: frontend - - coturn: - role: web-svc-coturn - type: frontend - - onlyoffice: - role: web-svc-onlyoffice - type: frontend - - libretranslate: - role: web-svc-libretranslate - type: frontend - - dashboard: - role: web-app-dashboard - type: frontend - - ldap: - role: svc-db-openldap - type: backend - - ollama: - role: svc-ai-ollama - type: backend - - database: - role_template: "svc-db-{type}" - type: backend diff --git a/plugins/filter/compose_volumes.py b/plugins/filter/compose_volumes.py index 97fda96a1b..cba1c4fdc8 100644 --- a/plugins/filter/compose_volumes.py +++ b/plugins/filter/compose_volumes.py @@ -12,11 +12,19 @@ try: ) from plugins.filter.get_app_conf import get_app_conf from plugins.filter.get_entity_name import get_entity_name + from utils.database_service import ( + get_database_service_config, + resolve_database_service_key, + ) except ModuleNotFoundError: # Fallback when loaded by Ansible plugin loader from filter_plugins path. from docker_service_enabled import FilterModule as _DockerServiceEnabledFilter from get_app_conf import get_app_conf from get_entity_name import get_entity_name + from utils.database_service import ( + get_database_service_config, + resolve_database_service_key, + ) def _to_plain(obj: Any) -> Any: @@ -65,8 +73,8 @@ def compose_volumes( Logic is identical to roles/sys-svc-compose/templates/volumes.yml.j2: - database volume if: - is_docker_service_enabled(database) - and not compose.services.database.shared + a direct mariadb/postgres service is enabled + and that service is not shared name: database_volume (no fallback!) @@ -100,17 +108,10 @@ def compose_volumes( # ------------------------------------------------------------------ # Database volume (same condition as Jinja2) # ------------------------------------------------------------------ - database_needed = _DockerServiceEnabledFilter.is_docker_service_enabled( - applications, application_id, "database" - ) and not bool( - get_app_conf( - applications=applications, - application_id=application_id, - config_path="compose.services.database.shared", - strict=False, - default=False, - skip_missing_app=True, - ) + database_service_key = resolve_database_service_key(applications, application_id) + database_service = get_database_service_config(applications, application_id) + database_needed = bool(database_service_key) and not bool( + database_service.get("shared", False) ) if database_needed: diff --git a/plugins/filter/service_load_enabled.py b/plugins/filter/service_load_enabled.py deleted file mode 100644 index 2cdb824cd2..0000000000 --- a/plugins/filter/service_load_enabled.py +++ /dev/null @@ -1,39 +0,0 @@ -from utils.config_utils import get_app_conf as _get_app_conf - - -def service_load_enabled(applications, application_id, service_name, default=False): - """ - Return True if compose.services..enabled AND .shared are true. - - Uses the existing utils.config_utils.get_app_conf implementation, - so schema/strict/default behavior stays consistent across the codebase. - - Usage: - {{ applications | service_load_enabled(application_id, 'ldap') }} - """ - - # We explicitly use strict=False here to behave like a "safe boolean probe". - enabled = _get_app_conf( - applications=applications, - application_id=application_id, - config_path=f"compose.services.{service_name}.enabled", - strict=False, - default=default, - skip_missing_app=False, - ) - - shared = _get_app_conf( - applications=applications, - application_id=application_id, - config_path=f"compose.services.{service_name}.shared", - strict=False, - default=default, - skip_missing_app=False, - ) - - return bool(enabled) and bool(shared) - - -class FilterModule: - def filters(self): - return {"service_load_enabled": service_load_enabled} diff --git a/plugins/lookup/applications_current_play.py b/plugins/lookup/applications_current_play.py index d0adda647c..93b9032b8c 100644 --- a/plugins/lookup/applications_current_play.py +++ b/plugins/lookup/applications_current_play.py @@ -1,13 +1,14 @@ from __future__ import annotations import os -import yaml from typing import Any, Dict, List, Optional +import yaml from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase from utils.applications.in_group_deps import applications_if_group_and_all_deps +from utils.service_registry import build_service_registry_from_applications class LookupModule(LookupBase): @@ -26,10 +27,16 @@ class LookupModule(LookupBase): applications = kwargs.get("applications", vars_.get("applications")) group_names = kwargs.get("group_names", vars_.get("group_names", [])) + if not isinstance(applications, dict): + raise AnsibleError( + "applications_current_play: required variable 'applications' must be a mapping" + ) project_root = self._get_project_root() roles_dir = os.path.join(project_root, "roles") - service_registry = self._load_service_registry(project_root) + service_registry = kwargs.get("service_registry") + if service_registry is None: + service_registry = build_service_registry_from_applications(applications) try: result = applications_if_group_and_all_deps( @@ -53,17 +60,6 @@ class LookupModule(LookupBase): plugin_dir = os.path.dirname(__file__) return os.path.abspath(os.path.join(plugin_dir, "..", "..")) - def _load_service_registry(self, project_root: str) -> Dict[str, Any]: - path = os.path.join(project_root, "group_vars", "all", "20_services.yml") - if not os.path.isfile(path): - return {} - try: - with open(path, encoding="utf-8") as f: - data = yaml.safe_load(f) or {} - return data.get("SERVICE_REGISTRY", {}) - except Exception: - return {} - def _meta_deps(self, role: str, roles_dir: str) -> List[str]: meta_file = os.path.join(roles_dir, role, "meta", "main.yml") if not os.path.isfile(meta_file): diff --git a/plugins/lookup/config.py b/plugins/lookup/config.py index 58c15c6c76..389c28a384 100644 --- a/plugins/lookup/config.py +++ b/plugins/lookup/config.py @@ -53,7 +53,7 @@ class LookupModule(LookupBase): config_path=config_path, strict=strict, default=default_value, - skip_missing_app=False, + skip_missing_app=not strict, ) # lookup plugins must return a list diff --git a/plugins/lookup/database.py b/plugins/lookup/database.py index 3e7f83ede1..9172c4f771 100644 --- a/plugins/lookup/database.py +++ b/plugins/lookup/database.py @@ -7,6 +7,10 @@ from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase from utils.config_utils import get_app_conf +from utils.database_service import ( + get_database_service_config, + resolve_database_service_key, +) from utils.entity_name_utils import get_entity_name @@ -56,35 +60,17 @@ class LookupModule(LookupBase): consumer_entity = get_entity_name(consumer_id) - enabled = bool( - get_app_conf( - applications, - consumer_id, - "compose.services.database.enabled", - strict=False, - default=False, - ) - ) - shared = bool( - get_app_conf( - applications, - consumer_id, - "compose.services.database.shared", - strict=False, - default=False, - ) - ) + try: + dbtype = resolve_database_service_key(applications, consumer_id) + except ValueError as exc: + raise AnsibleError(f"database: {exc}") from exc - dbtype = get_app_conf( - applications, - consumer_id, - "compose.services.database.type", - strict=False, - default="", - ) - dbtype = (str(dbtype) if dbtype is not None else "").strip() + database_service = get_database_service_config(applications, consumer_id) + enabled = bool(database_service.get("enabled", False)) + shared = bool(database_service.get("shared", False)) - # If no dbtype configured: keep behavior similar to your vars (mostly empty) + # If no direct database service is configured: keep behavior similar to the + # historical empty-value lookup payload. if not dbtype: resolved = { "id": "", @@ -154,7 +140,7 @@ class LookupModule(LookupBase): version = get_app_conf( applications, consumer_id, - "compose.services.database.version", + f"compose.services.{dbtype}.version", strict=False, default=default_version, ) diff --git a/plugins/lookup/service.py b/plugins/lookup/service.py index 51be8567b8..b45965ab58 100644 --- a/plugins/lookup/service.py +++ b/plugins/lookup/service.py @@ -6,23 +6,32 @@ from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase from utils.config_utils import get_app_conf +from utils.service_registry import ( + build_role_to_primary_service_key, + build_service_registry_from_applications, + canonical_service_key, + equivalent_service_keys, +) def _get_service_flag( applications: Dict[str, Any], app_id: str, - service_key: str, + service_keys: List[str], flag: str, ) -> bool: - return bool( - get_app_conf( - applications=applications, - application_id=app_id, - config_path=f"compose.services.{service_key}.{flag}", - strict=False, - default=False, - skip_missing_app=True, + return any( + bool( + get_app_conf( + applications=applications, + application_id=app_id, + config_path=f"compose.services.{service_key}.{flag}", + strict=False, + default=False, + skip_missing_app=True, + ) ) + for service_key in service_keys ) @@ -50,15 +59,8 @@ def _get_enabled_service_keys( def _resolve_service_provider_app_id( applications: Dict[str, Any], service_registry: Dict[str, Any], - app_id: str, service_key: str, ) -> Optional[str]: - """Resolve a service key to the provider role/application id. - - Transitive service recursion must follow SERVICE_REGISTRY so short keys such - as ``asset`` recurse into ``web-svc-asset`` instead of requiring callers to - use full application ids inside compose.services. - """ entry = service_registry.get(service_key) if not isinstance(entry, dict): return None @@ -66,23 +68,7 @@ def _resolve_service_provider_app_id( role = entry.get("role") if isinstance(role, str) and role: return role - - role_template = entry.get("role_template") - if not isinstance(role_template, str) or not role_template: - return None - - service_type = get_app_conf( - applications=applications, - application_id=app_id, - config_path=f"compose.services.{service_key}.type", - strict=False, - default="", - skip_missing_app=True, - ) - if not isinstance(service_type, str) or not service_type: - return None - - return role_template.replace("{type}", service_type) + return None def _is_service_needed( @@ -101,8 +87,9 @@ def _is_service_needed( return False visited.add(app_id) - enabled = _get_service_flag(applications, app_id, service_key, "enabled") - shared = _get_service_flag(applications, app_id, service_key, "shared") + service_keys = equivalent_service_keys(service_registry, service_key) + enabled = _get_service_flag(applications, app_id, service_keys, "enabled") + shared = _get_service_flag(applications, app_id, service_keys, "shared") if enabled and shared: return True @@ -110,7 +97,7 @@ def _is_service_needed( if svc == service_key: continue dep_app_id = _resolve_service_provider_app_id( - applications, service_registry, app_id, svc + applications, service_registry, svc ) if dep_app_id and dep_app_id in applications: if _is_service_needed( @@ -122,21 +109,7 @@ def _is_service_needed( def _build_role_to_key(service_registry: Dict[str, Any]) -> Dict[str, str]: - """Map each role name to its canonical service key. - - When multiple keys share the same role, the canonical key is determined by - the 'canonical' field on alias entries. The primary key (no 'canonical' - field) is used as the fallback so that role-based reverse lookup always - returns a single, deterministic id. - """ - result: Dict[str, str] = {} - for key, entry in service_registry.items(): - if not isinstance(entry, dict) or "role" not in entry: - continue - role = entry["role"] - canonical_key = entry.get("canonical", key) - result[role] = canonical_key - return result + return build_role_to_primary_service_key(service_registry) def _resolve_term( @@ -150,12 +123,12 @@ def _resolve_term( """ if term in service_registry: entry = service_registry[term] - role = entry.get("role") or entry.get("role_template", "") + role = entry.get("role", "") return term, str(role) if term in role_to_key: key = role_to_key[term] entry = service_registry[key] - role = entry.get("role") or entry.get("role_template", "") + role = entry.get("role", "") return key, str(role) raise AnsibleError( f"service: '{term}' is neither a known service key nor a known role name. " @@ -171,16 +144,18 @@ def _compute_flags( service_key: str, ) -> Dict[str, bool]: deployed = [app_id for app_id in group_names if app_id in applications] + equivalent_keys = equivalent_service_keys(service_registry, service_key) any_enabled = any( - _get_service_flag(applications, app_id, service_key, "enabled") + _get_service_flag(applications, app_id, equivalent_keys, "enabled") for app_id in deployed ) any_shared = any( - _get_service_flag(applications, app_id, service_key, "shared") + _get_service_flag(applications, app_id, equivalent_keys, "shared") for app_id in deployed ) + primary_key = canonical_service_key(service_registry, service_key) any_needed = any( - _is_service_needed(applications, service_registry, app_id, service_key, set()) + _is_service_needed(applications, service_registry, app_id, primary_key, set()) for app_id in deployed ) return {"enabled": any_enabled, "shared": any_shared, "needed": any_needed} @@ -194,9 +169,8 @@ class LookupModule(LookupBase): lookup('service', 'matomo') lookup('service', 'web-app-matomo') # resolved via reverse mapping - Reads 'applications', 'group_names', and 'SERVICE_REGISTRY' from Ansible variables. - The 'SERVICE_REGISTRY' variable is the canonical key → role mapping from - group_vars/all/20_services.yml and is automatically available in all plays. + Reads 'applications' and 'group_names' from Ansible variables and discovers + service providers from the role-local compose.services metadata. Returns a dict per term: id — canonical service key (e.g. 'matomo') @@ -230,12 +204,11 @@ class LookupModule(LookupBase): "service: required variable 'group_names' must be a list" ) - service_registry = kwargs.get("service_registry", vars_.get("SERVICE_REGISTRY")) + service_registry = kwargs.get("service_registry") + if service_registry is None: + service_registry = build_service_registry_from_applications(applications) if not isinstance(service_registry, dict): - raise AnsibleError( - "service: required variable 'SERVICE_REGISTRY' must be a mapping " - "(loaded from group_vars/all/20_services.yml)" - ) + raise AnsibleError("service: 'service_registry' must be a mapping") role_to_key = _build_role_to_key(service_registry) diff --git a/plugins/lookup/service_registry.py b/plugins/lookup/service_registry.py new file mode 100644 index 0000000000..682bda0d6c --- /dev/null +++ b/plugins/lookup/service_registry.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any, Dict, List, Optional + +from ansible.errors import AnsibleError +from ansible.plugins.lookup import LookupBase + +from utils.service_registry import ( + build_service_registry_from_applications, + ordered_primary_service_entries, +) + + +class LookupModule(LookupBase): + """ + Discover the role-local service registry. + + Usage: + {{ query('service_registry') | first }} + {{ query('service_registry', 'ordered') | first }} + """ + + def run( + self, + terms: List[Any], + variables: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> List[Any]: + vars_ = variables or getattr(self._templar, "available_variables", {}) or {} + applications = kwargs.get("applications", vars_.get("applications")) + if not isinstance(applications, dict): + raise AnsibleError( + "service_registry: required variable 'applications' must be a mapping" + ) + + roles_dir = Path(kwargs.get("roles_dir") or Path.cwd() / "roles") + registry = build_service_registry_from_applications(applications) + mode = str(terms[0]).strip() if terms else "mapping" + + if mode in {"mapping", ""}: + return [registry] + if mode == "ordered": + return [ordered_primary_service_entries(registry, roles_dir)] + + raise AnsibleError( + f"service_registry: unsupported mode '{mode}' (expected 'mapping' or 'ordered')" + ) diff --git a/roles/svc-ai-ollama/README.md b/roles/svc-ai-ollama/README.md index 3f5ea058cf..8f35ed1b68 100644 --- a/roles/svc-ai-ollama/README.md +++ b/roles/svc-ai-ollama/README.md @@ -1,23 +1,29 @@ - # Ollama ## Description -**Ollama** is a local model server that runs open LLMs on your hardware and exposes a simple HTTP API. It’s the backbone for privacy-first AI: prompts and data stay on your machines. +[Ollama](https://ollama.com) is a local model server that runs open LLMs on your hardware and exposes a simple HTTP API. Prompts and data stay on your machines, making it the backbone for privacy-first AI. ## Overview -After the first model pull, Ollama serves models to clients like Open WebUI (for chat) and Flowise (for workflows). Models are cached locally for quick reuse and can run fully offline when required. +This role deploys Ollama as a local model server using Docker Compose. It integrates with Open WebUI for chat and Flowise for AI workflow automation, and configures local model caching so models can be reused across sessions or run fully offline. ## Features -* Run popular open models (chat, code, embeddings) locally -* Simple, predictable HTTP API for developers -* Local caching to avoid repeated downloads -* Works seamlessly with Open WebUI and Flowise -* Offline-capable for air-gapped deployments +- **Local model execution:** Run popular open models (chat, code, embeddings) on your own hardware. +- **HTTP API:** Simple, predictable HTTP API for application developers. +- **Local caching:** Models are cached locally to avoid repeated downloads. +- **Integrations:** Works seamlessly with Open WebUI and Flowise. +- **Offline support:** Fully offline-capable for air-gapped deployments. -## Further Resources +## Further resources -* Ollama — [https://ollama.com](https://ollama.com) -* Ollama Model Library — [https://ollama.com/library](https://ollama.com/library) +- [Ollama](https://ollama.com) +- [Ollama Model Library](https://ollama.com/library) + +## Credits + +Developed and maintained by **Kevin Veen-Birkenbach**. +Learn more at [veen.world](https://www.veen.world). +Part of the [Infinito.Nexus Project](https://s.infinito.nexus/code). +Licensed under the [Infinito.Nexus Community License (Non-Commercial)](https://s.infinito.nexus/license). diff --git a/roles/svc-ai-ollama/tasks/main.yml b/roles/svc-ai-ollama/tasks/main.yml index dde20fbb08..b57f0c95b5 100644 --- a/roles/svc-ai-ollama/tasks/main.yml +++ b/roles/svc-ai-ollama/tasks/main.yml @@ -1,2 +1,4 @@ - include_tasks: 01_core.yml when: run_once_svc_ai_ollama is not defined + vars: + application_id: svc-ai-ollama diff --git a/roles/svc-db-mariadb/config/main.yml b/roles/svc-db-mariadb/config/main.yml index b80bf8375b..6db5b336a9 100644 --- a/roles/svc-db-mariadb/config/main.yml +++ b/roles/svc-db-mariadb/config/main.yml @@ -1,6 +1,8 @@ compose: services: mariadb: + enabled: false + shared: true version: "latest" image: "mariadb" name: "mariadb" @@ -12,10 +14,6 @@ compose: mem_reservation: "2g" mem_limit: "4g" pids_limit: 1024 - database: - shared: true - enabled: true - type: "mariadb" network: "mariadb" volumes: data: "mariadb_data" diff --git a/roles/svc-db-mariadb/tasks/01_core.yml b/roles/svc-db-mariadb/tasks/01_core.yml index ea94b958b6..9f1377234b 100644 --- a/roles/svc-db-mariadb/tasks/01_core.yml +++ b/roles/svc-db-mariadb/tasks/01_core.yml @@ -1,3 +1,5 @@ +- include_tasks: utils/once/flag.yml + - name: "Setup container network for {{ application_id }}" include_tasks: "{{ [playbook_dir, 'roles/sys-svc-compose/tasks/utils/network.yml' ] | path_join }}" vars: @@ -79,5 +81,3 @@ until: mariadb_ready is succeeded changed_when: false when: MARIADB_EXPOSE_LOCAL | bool - -- include_tasks: utils/once/flag.yml diff --git a/roles/svc-db-mariadb/tasks/main.yml b/roles/svc-db-mariadb/tasks/main.yml index a2c53cd2db..5b53b030b5 100644 --- a/roles/svc-db-mariadb/tasks/main.yml +++ b/roles/svc-db-mariadb/tasks/main.yml @@ -1,10 +1,8 @@ - -- block: - - include_tasks: 01_core.yml - when: run_once_svc_db_mariadb is not defined - - - name: "Initialize dedicated database" - include_tasks: 02_init.yml - when: database_init | bool +- include_tasks: 01_core.yml + when: run_once_svc_db_mariadb is not defined vars: application_id: svc-db-mariadb + +- name: "Initialize dedicated database" + include_tasks: 02_init.yml + when: database_init | bool diff --git a/roles/svc-db-openldap/config/main.yml b/roles/svc-db-openldap/config/main.yml index 79877c059c..c2620c99c5 100644 --- a/roles/svc-db-openldap/config/main.yml +++ b/roles/svc-db-openldap/config/main.yml @@ -5,10 +5,10 @@ network: compose: services: - ldap: - enabled: true - shared: true openldap: + enabled: false + shared: true + provides: ldap image: "debian" version: "bookworm-slim" name: "openldap" diff --git a/roles/svc-db-postgres/config/main.yml b/roles/svc-db-postgres/config/main.yml index ff6e02eb37..c262e56637 100644 --- a/roles/svc-db-postgres/config/main.yml +++ b/roles/svc-db-postgres/config/main.yml @@ -1,6 +1,8 @@ compose: services: postgres: + enabled: false + shared: true # Postgis is necessary for mobilizon image: postgis/postgis name: postgres @@ -14,10 +16,6 @@ compose: mem_reservation: "4g" mem_limit: "6g" pids_limit: 1024 - database: - shared: true - enabled: true - type: "postgres" volumes: data: "postgres_data" network: "postgres" diff --git a/roles/svc-db-postgres/tasks/main.yml b/roles/svc-db-postgres/tasks/main.yml index f9c70d7414..65d8e04389 100644 --- a/roles/svc-db-postgres/tasks/main.yml +++ b/roles/svc-db-postgres/tasks/main.yml @@ -1,14 +1,13 @@ -- block: - - include_tasks: 01_core.yml - when: run_once_svc_db_postgres is not defined - - - include_tasks: utils/load_handlers.yml - # Necessary because docker handlers are overwritten by condition - vars: - handler_role_name: "sys-svc-compose" - - - name: "Initialize dedicated database" - include_tasks: 02_init.yml - when: database_init | bool +- include_tasks: 01_core.yml + when: run_once_svc_db_postgres is not defined vars: application_id: svc-db-postgres + +- include_tasks: utils/load_handlers.yml + # Necessary because docker handlers are overwritten by condition + vars: + handler_role_name: "sys-svc-compose" + +- name: "Initialize dedicated database" + include_tasks: 02_init.yml + when: database_init | bool diff --git a/roles/sys-ctl-alm-compose/tasks/01_core.yml b/roles/sys-ctl-alm-compose/tasks/01_core.yml index f20e489ba5..135aea3e15 100644 --- a/roles/sys-ctl-alm-compose/tasks/01_core.yml +++ b/roles/sys-ctl-alm-compose/tasks/01_core.yml @@ -39,3 +39,6 @@ state: started when: - MODE_ASSERT | bool + # Shared-service preloading happens before Mailu exposes its final TLS SMTP + # listener, so the notifier self-test must wait for the normal app phase. + - not (_service_loader_preloading | default(false) | bool) diff --git a/roles/sys-stk-backend/lookup_plugins/service_should_load.py b/roles/sys-stk-backend/lookup_plugins/service_should_load.py deleted file mode 100644 index 2eae6a7168..0000000000 --- a/roles/sys-stk-backend/lookup_plugins/service_should_load.py +++ /dev/null @@ -1,95 +0,0 @@ -from __future__ import annotations - -from typing import Any, Dict, List, Optional - -from ansible.errors import AnsibleError -from ansible.plugins.lookup import LookupBase - -from utils.config_utils import get_app_conf - - -def _require_non_empty(value: Any, name: str) -> str: - s = str(value).strip() - if not s: - raise AnsibleError(f"service_should_load: '{name}' must not be empty") - return s - - -def _service_enabled_and_shared( - applications: Dict[str, Any], - application_id: str, - service_name: str, - default: bool, -) -> bool: - enabled = get_app_conf( - applications=applications, - application_id=application_id, - config_path=f"compose.services.{service_name}.enabled", - strict=False, - default=default, - skip_missing_app=False, - ) - shared = get_app_conf( - applications=applications, - application_id=application_id, - config_path=f"compose.services.{service_name}.shared", - strict=False, - default=default, - skip_missing_app=False, - ) - return bool(enabled) and bool(shared) - - -def _run_once_var_name(service_id: str) -> str: - return f"run_once_{service_id.replace('-', '_')}" - - -class LookupModule(LookupBase): - """ - Evaluate whether a backend service should be loaded. - - Usage: - {{ query('service_should_load', service_id, application_id=application_id, service_name=service_name) | first }} - """ - - def run( - self, - terms: List[Any], - variables: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> List[bool]: - if not terms: - return [] - - vars_ = variables or getattr(self._templar, "available_variables", {}) or {} - applications = kwargs.get("applications", vars_.get("applications")) - if not isinstance(applications, dict): - raise AnsibleError( - "service_should_load: required variable 'applications' must be a mapping" - ) - - application_id = _require_non_empty( - kwargs.get("application_id", vars_.get("application_id")), "application_id" - ) - service_name = _require_non_empty( - kwargs.get("service_name", vars_.get("service_name")), "service_name" - ) - default = bool(kwargs.get("default", False)) - - results: List[bool] = [] - for term in terms: - service_id = _require_non_empty(term, "service_id") - run_once_defined = _run_once_var_name(service_id) in vars_ - should_load = ( - _service_enabled_and_shared( - applications=applications, - application_id=application_id, - service_name=service_name, - default=default, - ) - and (not run_once_defined) - and (application_id != service_id) - ) - results.append(bool(should_load)) - - return results diff --git a/roles/sys-stk-backend/tasks/_load_service.yml b/roles/sys-stk-backend/tasks/_load_service.yml deleted file mode 100644 index 5b275ef556..0000000000 --- a/roles/sys-stk-backend/tasks/_load_service.yml +++ /dev/null @@ -1,19 +0,0 @@ -- name: "SYS-STK-BACKEND | Compute load flag for '{{ service_id }}' (enabled && shared)" - ansible.builtin.set_fact: - load_service: >- - {{ - query( - 'service_should_load', - service_id, - application_id=application_id, - service_name=service_name, - applications=applications, - default=False - ) | first - }} - -- name: "SYS-STK-BACKEND | Load '{{ service_id }}' (Once)" - ansible.builtin.include_tasks: "utils/load_app.yml" - vars: - load_app_id: "{{ service_id }}" - when: load_service | bool diff --git a/roles/sys-stk-backend/tasks/main.yml b/roles/sys-stk-backend/tasks/main.yml index 606d1d334d..f462bc8431 100644 --- a/roles/sys-stk-backend/tasks/main.yml +++ b/roles/sys-stk-backend/tasks/main.yml @@ -1,40 +1,38 @@ # run_once_sys_stk_backend: disabled +- name: "Resolve backend context for '{{ application_id }}'" + ansible.builtin.set_fact: + _sys_stk_backend_database_consumer_id: >- + {{ database_consumer_id | default(application_id) }} + _sys_stk_backend_database_enabled: >- + {{ lookup('database', application_id, 'enabled') | bool }} + _sys_stk_backend_oauth2_enabled: >- + {{ lookup('config', application_id, 'compose.services.oauth2.enabled', False) }} + changed_when: false + - name: "DEBUG | SYS-STK-BACKEND | Application context" ansible.builtin.debug: msg: - "application_id={{ application_id }}" - - "database_enabled={{ SYS_STK_BACKEND_DATABASE_ENABLED }}" - - "oauth2_enabled={{ SYS_STK_BACKEND_OAUTH2_ENABLED }}" + - "database_consumer_id={{ _sys_stk_backend_database_consumer_id }}" + - "database_enabled={{ _sys_stk_backend_database_enabled }}" + - "oauth2_enabled={{ _sys_stk_backend_oauth2_enabled }}" when: MODE_DEBUG | bool -- name: "SYS-STK-BACKEND | Load optional dependencies (once)" - ansible.builtin.include_tasks: "_load_service.yml" - loop: - - id: "svc-db-openldap" - name: "ldap" - - - id: "svc-ai-ollama" - name: "ollama" - loop_control: - loop_var: service - label: "{{ service.id }}" - vars: - service_id: "{{ service.id }}" - service_name: "{{ service.name }}" - - name: "For '{{ application_id }}': Load central RDBMS" include_role: name: sys-svc-rdbms public: false - when: SYS_STK_BACKEND_DATABASE_ENABLED | bool + vars: + database_consumer_id: "{{ _sys_stk_backend_database_consumer_id }}" + when: _sys_stk_backend_database_enabled | bool - name: "For '{{ application_id }}': Load sys-svc-compose" include_role: name: sys-svc-compose vars: docker_compose_flush_handlers: false - database_consumer_id: "{{ database_consumer_id_passed }}" + database_consumer_id: "{{ _sys_stk_backend_database_consumer_id }}" - block: - name: "set oauth2_proxy_application_id (Needed due to lazzy loading issue)" @@ -42,7 +40,7 @@ oauth2_proxy_application_id: "{{ application_id }}" - name: "load role web-app-oauth2-proxy" include_tasks: "{{ playbook_dir }}/roles/web-app-oauth2-proxy/tasks/main.yml" - when: SYS_STK_BACKEND_OAUTH2_ENABLED | bool + when: _sys_stk_backend_oauth2_enabled | bool - name: "flush compose and oauth2 proxy'" meta: flush_handlers diff --git a/roles/sys-stk-backend/vars/main.yml b/roles/sys-stk-backend/vars/main.yml deleted file mode 100644 index ff718711bf..0000000000 --- a/roles/sys-stk-backend/vars/main.yml +++ /dev/null @@ -1,3 +0,0 @@ -# Declared as extra variable for debugging purposes -SYS_STK_BACKEND_DATABASE_ENABLED: "{{ applications | service_load_enabled(application_id, 'database', False) }}" -SYS_STK_BACKEND_OAUTH2_ENABLED: "{{ lookup('config',application_id, 'compose.services.oauth2.enabled', False) }}" diff --git a/roles/sys-svc-compose/tasks/01_core.yml b/roles/sys-svc-compose/tasks/01_core.yml index 119fcd2a8a..8aba69b301 100644 --- a/roles/sys-svc-compose/tasks/01_core.yml +++ b/roles/sys-svc-compose/tasks/01_core.yml @@ -42,4 +42,6 @@ - sys-ctl-rpr-container-hard loop_control: loop_var: service_role - when: COMPOSE_LOAD_SERVICES | bool + when: + - COMPOSE_LOAD_SERVICES | bool + - not (_service_loader_preloading | default(false) | bool) diff --git a/roles/sys-svc-compose/templates/base.yml.j2 b/roles/sys-svc-compose/templates/base.yml.j2 index 1b23bf83d1..ed8d9747df 100644 --- a/roles/sys-svc-compose/templates/base.yml.j2 +++ b/roles/sys-svc-compose/templates/base.yml.j2 @@ -1,7 +1,7 @@ {# Base template for all compose.yml.j2 #} services: {# Load Database #} -{% if applications | is_docker_service_enabled(application_id, 'database') %} +{% if lookup('database', application_id, 'enabled') %} {% include 'roles/sys-svc-rdbms/templates/services/main.yml.j2' %} {% endif %} {# Load Redis #} diff --git a/roles/sys-svc-compose/templates/networks.yml.j2 b/roles/sys-svc-compose/templates/networks.yml.j2 index 08664e06b3..a290e6e718 100644 --- a/roles/sys-svc-compose/templates/networks.yml.j2 +++ b/roles/sys-svc-compose/templates/networks.yml.j2 @@ -1,28 +1,41 @@ {# This template needs to be included in compose.yml #} +{% set _db_provider_role = application_id if application_id in ['svc-db-mariadb', 'svc-db-postgres'] else '' %} +{% set _db_role_id = _db_provider_role or lookup('database', application_id, 'id') %} +{% set _db_network_name = lookup('config', _db_role_id, 'compose.network', False) if _db_role_id else '' %} +{% set _service_registry = query('service_registry') | first %} +{% set _ldap_provider_role = _service_registry.get('ldap', {}).get('role', '') %} +{% set _ldap_network_name = lookup('config', _ldap_provider_role, 'compose.network', False) if _ldap_provider_role else '' %} +{% set _ldap_shared = application_id == _ldap_provider_role or ( + lookup('config', application_id, 'compose.services.ldap.enabled', False) + and lookup('config', application_id, 'compose.services.ldap.shared', False) +) %} +{% set _ollama_provider_role = _service_registry.get('ollama', {}).get('role', '') %} +{% set _ollama_network_name = lookup('config', _ollama_provider_role, 'compose.network', False) if _ollama_provider_role else '' %} +{% set _ollama_shared = application_id == _ollama_provider_role or ( + lookup('config', application_id, 'compose.services.ollama.enabled', False) + and lookup('config', application_id, 'compose.services.ollama.shared', False) +) %} networks: {# Central RDMS-Database Network #} {% if ( - lookup('config',application_id, 'compose.services.database.enabled', False) and + lookup('database', application_id, 'enabled') and lookup('database', application_id, 'shared') ) or application_id in ['svc-db-mariadb','svc-db-postgres'] %} - {{ lookup('config', lookup('database', application_id, 'id'), 'compose.network') }}: + {{ _db_network_name }}: external: true {% endif %} {# Central LDAP Network #} -{% if - lookup('config',application_id, 'compose.services.ldap.shared', False) and - lookup('config','svc-db-openldap', 'network.compose', False) - %} - {{ lookup('config','svc-db-openldap', 'compose.network') }}: +{% if _ldap_shared and _ldap_network_name %} + {{ _ldap_network_name }}: external: true {% endif %} {# Central AI Network #} -{% if lookup('config',application_id, 'compose.services.ollama.shared', False) %} - {{ lookup('config','svc-ai-ollama', 'compose.network') }}: +{% if _ollama_shared and _ollama_network_name %} + {{ _ollama_network_name }}: external: true {% endif %} {# Default Network #} diff --git a/roles/sys-svc-container/files/container.py b/roles/sys-svc-container/files/container.py index 8fbd24e651..9fcc63cbbf 100644 --- a/roles/sys-svc-container/files/container.py +++ b/roles/sys-svc-container/files/container.py @@ -367,9 +367,31 @@ def container_run(argv: List[str], debug: bool, with_ca: bool) -> int: if not ep: warn( "Image has no ENTRYPOINT and none was provided. " - "Running without CA wrapper." + "Injecting CA env vars without entrypoint wrapper." + ) + # Inject CA cert as a volume + env vars so Node.js (NODE_EXTRA_CA_CERTS), + # curl (CURL_CA_BUNDLE), Python requests (REQUESTS_CA_BUNDLE), and other + # tools can trust the internal CA even without a wrapper entrypoint. + ca_inject_opts: List[str] = [ + "-v", + f"{ca_host}:{ca_container}:ro", + "-e", + f"CA_TRUST_CERT={ca_container}", + "-e", + f"CA_TRUST_NAME={trust_name}", + "-e", + f"NODE_EXTRA_CA_CERTS={ca_container}", + "-e", + f"SSL_CERT_FILE={ca_container}", + "-e", + f"REQUESTS_CA_BUNDLE={ca_container}", + "-e", + f"CURL_CA_BUNDLE={ca_container}", + ] + return exec_docker( + ["docker", "run"] + run_opts + ca_inject_opts + [image] + user_args, + debug=debug, ) - return exec_docker(["docker", "run", *argv], debug=debug) final_cmd.extend(ep) final_cmd.extend(user_args) diff --git a/roles/sys-svc-container/templates/networks.yml.j2 b/roles/sys-svc-container/templates/networks.yml.j2 index 78c366de3b..21633ea939 100644 --- a/roles/sys-svc-container/templates/networks.yml.j2 +++ b/roles/sys-svc-container/templates/networks.yml.j2 @@ -1,27 +1,44 @@ {# This template needs to be included in compose.yml containers #} +{% set _db_provider_role = application_id if application_id in ['svc-db-mariadb', 'svc-db-postgres'] else '' %} +{% set _db_role_id = _db_provider_role or lookup('database', application_id, 'id') %} +{% set _db_network_name = lookup('config', _db_role_id, 'compose.network', False) if _db_role_id else '' %} +{% set _db_network_alias = (application_id | get_entity_name) if _db_provider_role else lookup('database', application_id, 'type') %} +{% set _service_registry = query('service_registry') | first %} +{% set _ldap_provider_role = _service_registry.get('ldap', {}).get('role', '') %} +{% set _ldap_network_name = lookup('config', _ldap_provider_role, 'compose.network', False) if _ldap_provider_role else '' %} +{% set _ldap_shared = application_id == _ldap_provider_role or ( + lookup('config', application_id, 'compose.services.ldap.enabled', False) + and lookup('config', application_id, 'compose.services.ldap.shared', False) +) %} +{% set _ollama_provider_role = _service_registry.get('ollama', {}).get('role', '') %} +{% set _ollama_network_name = lookup('config', _ollama_provider_role, 'compose.network', False) if _ollama_provider_role else '' %} +{% set _ollama_shared = application_id == _ollama_provider_role or ( + lookup('config', application_id, 'compose.services.ollama.enabled', False) + and lookup('config', application_id, 'compose.services.ollama.shared', False) +) %} networks: {# Central RDMS-Database Network #} {% if ( - lookup('config',application_id, 'compose.services.database.enabled', False) and + lookup('database', application_id, 'enabled') and lookup('database', application_id, 'shared') ) or application_id in ['svc-db-mariadb','svc-db-postgres'] %} - {{ lookup('config', lookup('database', application_id, 'id'), 'compose.network') }}: + {{ _db_network_name }}: {% if application_id in ['svc-db-mariadb','svc-db-postgres'] %} aliases: - - {{ lookup('database', application_id, 'type') }} + - {{ _db_network_alias }} {% endif %} {% endif %} {# Central LDAP Network #} -{% if lookup('config',application_id, 'compose.services.ldap.shared', False) and lookup('config','svc-db-openldap', 'network.compose') %} - {{ lookup('config','svc-db-openldap', 'compose.network') }}: +{% if _ldap_shared and _ldap_network_name %} + {{ _ldap_network_name }}: {% endif %} {# Central AI Network #} -{% if lookup('config',application_id, 'compose.services.ollama.shared', False) %} - {{ lookup('config','svc-ai-ollama', 'compose.network') }}: +{% if _ollama_shared and _ollama_network_name %} + {{ _ollama_network_name }}: {% endif %} {% if not application_id.startswith('svc-db-') and not application_id.startswith('svc-ai-') %} default: diff --git a/roles/sys-svc-mail/tasks/01_core.yml b/roles/sys-svc-mail/tasks/01_core.yml index 82291f5ffa..e96708647d 100644 --- a/roles/sys-svc-mail/tasks/01_core.yml +++ b/roles/sys-svc-mail/tasks/01_core.yml @@ -5,33 +5,15 @@ name: "sys-hostname" when: not (run_once_sys_hostname | default(false) | bool) -- block: - - name: "Check if Mail Host is reachable" - uri_probe: - url: "{{ lookup('tls', 'web-app-mailu', 'url.base') }}" - validate_certs: yes - status_code: "{{ mailu_valid_status_codes }}" - register: mail_host_reachability - failed_when: false - changed_when: false - when: - - run_once_web_app_mailu is not defined - - - name: "Load Mailu Routines for '{{ role_name }}'" - include_tasks: 02_mailu.yml - when: - - > - ( - mail_host_reachability is defined and - (mail_host_reachability.status | default(0) | int) - not in mailu_valid_status_codes - ) - or - ( - (users['no-reply'].tokens | default({})).get('web-app-mailu', '') | length == 0 - ) - vars: - mailu_valid_status_codes: "{{ lookup('config','web-app-mailu', 'server.status_codes.default') }}" +- name: "Assert Mailu was preloaded before configuring external mail" + ansible.builtin.assert: + that: + - run_once_web_app_mailu is defined + - (users['no-reply'].tokens | default({})).get('web-app-mailu', '') | length > 0 + fail_msg: >- + Mailu must be preloaded by sys-utils-service-loader before sys-svc-mail runs. + Missing run_once_web_app_mailu or missing users['no-reply'].tokens['web-app-mailu'] + indicates that a service was loaded outside the constructor service-loader path. when: - "'web-app-mailu' in group_names" diff --git a/roles/sys-svc-mail/tasks/02_mailu.yml b/roles/sys-svc-mail/tasks/02_mailu.yml deleted file mode 100644 index 81cf73b9a3..0000000000 --- a/roles/sys-svc-mail/tasks/02_mailu.yml +++ /dev/null @@ -1,9 +0,0 @@ -- name: "Load Mailu before MSMTP config, to guaranty that server is up" - include_tasks: "utils/load_app.yml" - vars: - load_app_id: web-app-mailu - -- name: "Reset compose handlers after Mailu include for MSMTP" - include_tasks: utils/load_handlers.yml - vars: - handler_role_name: "sys-svc-compose" diff --git a/roles/sys-svc-rdbms/tasks/main.yml b/roles/sys-svc-rdbms/tasks/main.yml index 59b4c45566..8c3734f828 100644 --- a/roles/sys-svc-rdbms/tasks/main.yml +++ b/roles/sys-svc-rdbms/tasks/main.yml @@ -1,7 +1,14 @@ # run_once_sys_svc_rdbms: deactivated -- name: "For '{{ application_id }}': Set database_consumer_id (Needed due to lazzy loading issue)" +- name: "For '{{ application_id }}': Freeze database consumer id before provider includes" set_fact: - database_consumer_id_passed: "{{ application_id }}" + _database_consumer_id: "{{ database_consumer_id | default(application_id) }}" + changed_when: false + +- name: "For '{{ application_id }}/{{ _database_consumer_id }}': Resolve shared database mode" + set_fact: + _sys_svc_rdbms_central_db_enabled: >- + {{ lookup('database', _database_consumer_id, 'shared') | bool }} + changed_when: false - block: - name: "Ensure env dir exists: {{ lookup('container', application_id, 'directories.env') }}" @@ -9,31 +16,47 @@ path: "{{ lookup('container', application_id, 'directories.env') }}" state: directory mode: "0755" - - name: "For '{{ application_id }}/{{ database_consumer_id_passed }}': Create {{ lookup('database', application_id, 'env') }}" + - name: "For '{{ application_id }}/{{ _database_consumer_id }}': Create {{ lookup('database', _database_consumer_id, 'env') }}" template: - src: "env/{{ lookup('database', application_id, 'type') }}.env.j2" - dest: "{{ lookup('database', application_id, 'env') }}" + src: "env/{{ lookup('database', _database_consumer_id, 'type') }}.env.j2" + dest: "{{ lookup('database', _database_consumer_id, 'env') }}" notify: compose up - when: not (SYS_SVC_RDBMS_CENTRAL_DB_ENABLED | bool) + when: not (_sys_svc_rdbms_central_db_enabled | bool) - name: Central Database Logic block: - - name: "For '{{ application_id }}': Create central database" - include_tasks: "utils/load_app.yml" + - name: "For '{{ application_id }}': Assert shared database provider was preloaded" + ansible.builtin.assert: + that: + - >- + lookup( + 'vars', + 'run_once_' ~ (_database_provider_role | replace('-', '_')), + default='__missing__' + ) != '__missing__' + fail_msg: >- + Shared database provider '{{ _database_provider_role }}' was not preloaded by + sys-utils-service-loader before sys-svc-rdbms ran. + + - name: "For '{{ application_id }}': Initialize dedicated database on preloaded provider" + ansible.builtin.include_role: + name: "{{ _database_provider_role }}" vars: - load_app_id: "{{ lookup('database', application_id, 'id') }}" - database_init: true # Initialize a custom database for the application - docker_git_repository_pull: false # Deactivated here to don't inhire the variable + application_id: "{{ _database_provider_role }}" + database_init: true + docker_git_repository_pull: false + database_consumer_id: "{{ _database_consumer_id }}" - name: "For '{{ application_id }}': Add Entry for Backup Procedure" include_tasks: "{{ playbook_dir }}/roles/sys-ctl-bkp-docker-2-loc/tasks/04_seed-database-to-backup.yml" vars: - database_consumer_id: "{{ database_consumer_id_passed }}" - database_type: "{{ lookup('database', database_consumer_id_passed | default(application_id), 'type') }}" - database_instance: "{{ lookup('database', database_consumer_id_passed | default(application_id), 'instance') }}" - database_host: "{{ lookup('database', database_consumer_id_passed | default(application_id), 'host') }}" - database_port: "{{ lookup('database', database_consumer_id_passed | default(application_id), 'port') }}" - database_name: "{{ lookup('database', database_consumer_id_passed | default(application_id), 'name') }}" - database_username: "{{ lookup('database', database_consumer_id_passed | default(application_id), 'username') }}" - database_password: "{{ lookup('database', database_consumer_id_passed | default(application_id), 'password') }}" - when: SYS_SVC_RDBMS_CENTRAL_DB_ENABLED | bool + _database_provider_role: "{{ lookup('database', _database_consumer_id, 'id') }}" + database_consumer_id: "{{ _database_consumer_id }}" + database_type: "{{ lookup('database', _database_consumer_id, 'type') }}" + database_instance: "{{ lookup('database', _database_consumer_id, 'instance') }}" + database_host: "{{ lookup('database', _database_consumer_id, 'host') }}" + database_port: "{{ lookup('database', _database_consumer_id, 'port') }}" + database_name: "{{ lookup('database', _database_consumer_id, 'name') }}" + database_username: "{{ lookup('database', _database_consumer_id, 'username') }}" + database_password: "{{ lookup('database', _database_consumer_id, 'password') }}" + when: _sys_svc_rdbms_central_db_enabled | bool diff --git a/roles/sys-svc-rdbms/vars/main.yml b/roles/sys-svc-rdbms/vars/main.yml deleted file mode 100644 index 12ef02e05e..0000000000 --- a/roles/sys-svc-rdbms/vars/main.yml +++ /dev/null @@ -1,2 +0,0 @@ -# Docker -SYS_SVC_RDBMS_CENTRAL_DB_ENABLED: "{{ lookup('database', application_id, 'shared') }}" diff --git a/roles/sys-svc-webserver-core/tasks/01_core.yml b/roles/sys-svc-webserver-core/tasks/01_core.yml index 9eaaf53d70..2b960ccd9d 100644 --- a/roles/sys-svc-webserver-core/tasks/01_core.yml +++ b/roles/sys-svc-webserver-core/tasks/01_core.yml @@ -46,5 +46,6 @@ loop: - sys-ctl-hlth-webserver - sys-ctl-hlth-csp + when: not (_service_loader_preloading | default(false) | bool) - include_tasks: utils/once/flag.yml diff --git a/roles/sys-utils-service-loader/tasks/load_frontend_service.yml b/roles/sys-utils-service-loader/tasks/load_frontend_service.yml deleted file mode 100644 index e47c450858..0000000000 --- a/roles/sys-utils-service-loader/tasks/load_frontend_service.yml +++ /dev/null @@ -1,17 +0,0 @@ -- name: "Check if {{ service_key }} endpoint is reachable" - uri_probe: - url: "{{ lookup('tls', service_role, 'url.base') }}" - validate_certs: yes - status_code: 200 - register: _frontend_service_reachability - failed_when: false - changed_when: false - -- name: "Load {{ service_key }} (Once)" - include_tasks: "utils/load_app.yml" - when: (_frontend_service_reachability.status | default(0) | int) != 200 - vars: - load_app_id: "{{ service_role }}" - -- name: "Flush handlers after loading {{ service_key }}" - meta: flush_handlers diff --git a/roles/sys-utils-service-loader/tasks/load_service.yml b/roles/sys-utils-service-loader/tasks/load_service.yml new file mode 100644 index 0000000000..b8e8dc1676 --- /dev/null +++ b/roles/sys-utils-service-loader/tasks/load_service.yml @@ -0,0 +1,19 @@ +- name: "Load {{ service_key }} in shared service preload context" + block: + - name: "Mark shared service preload context for {{ service_key }}" + ansible.builtin.set_fact: + _service_loader_preloading: true + changed_when: false + + - name: "Load {{ service_key }} (Once)" + include_tasks: "utils/load_app.yml" + vars: + load_app_id: "{{ service_role }}" + + - name: "Flush handlers after loading {{ service_key }}" + meta: flush_handlers + always: + - name: "Clear shared service preload context for {{ service_key }}" + ansible.builtin.set_fact: + _service_loader_preloading: false + changed_when: false diff --git a/roles/sys-utils-service-loader/tasks/main.yml b/roles/sys-utils-service-loader/tasks/main.yml index 4e4ec52ee2..3c2cbeb577 100644 --- a/roles/sys-utils-service-loader/tasks/main.yml +++ b/roles/sys-utils-service-loader/tasks/main.yml @@ -1,20 +1,29 @@ -# SPOT: global loader for shared frontend web services. +# SPOT: global loader for all shared services. # -# Called once from tasks/stages/02_server.yml before web-svc and web-app roles. -# Service load order is defined by SERVICE_REGISTRY order. +# Called from tasks/stages/01_constructor.yml before the normal server app pass. -- name: "Load shared frontend service" - include_tasks: load_frontend_service.yml +- name: "Discover ordered shared services" + ansible.builtin.set_fact: + _ordered_services: >- + {{ + query( + 'service_registry', + 'ordered', + applications=applications, + roles_dir=([ playbook_dir, 'roles' ] | path_join) + ) | first + }} + +- name: "Load shared service" + include_tasks: load_service.yml vars: - service_key: "{{ service_item.key }}" - service_role: "{{ service_item.value.role }}" - service_run_once_var: "{{ 'run_once_' ~ (service_item.value.role | replace('-', '_')) }}" + service_key: "{{ service_item.id }}" + service_role: "{{ service_item.role }}" + service_run_once_var: "{{ 'run_once_' ~ (service_item.role | replace('-', '_')) }}" when: - - service_item.value.get('type') == 'frontend' - - service_item.value.role is defined - lookup('vars', service_run_once_var, default='__missing__') == '__missing__' - - lookup('service', service_item.key).needed | bool - loop: "{{ SERVICE_REGISTRY | dict2items | list }}" + - lookup('service', service_item.id).needed | bool + loop: "{{ _ordered_services }}" loop_control: loop_var: service_item - label: "{{ service_item.key }}" + label: "{{ service_item.id }}" diff --git a/roles/web-app-akaunting/config/main.yml b/roles/web-app-akaunting/config/main.yml index 4e3d729e59..e71e11f518 100644 --- a/roles/web-app-akaunting/config/main.yml +++ b/roles/web-app-akaunting/config/main.yml @@ -35,10 +35,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "mariadb" + mariadb: enabled: true + shared: true akaunting: backup: no_stop_required: true diff --git a/roles/web-app-baserow/config/main.yml b/roles/web-app-baserow/config/main.yml index 6b6036888c..1b1b2ad42f 100644 --- a/roles/web-app-baserow/config/main.yml +++ b/roles/web-app-baserow/config/main.yml @@ -17,10 +17,9 @@ compose: backup: disabled: true enabled: true - database: + postgres: + enabled: true shared: true - type: "postgres" - enabled: true baserow: backup: no_stop_required: true diff --git a/roles/web-app-bigbluebutton/config/main.yml b/roles/web-app-bigbluebutton/config/main.yml index de8e53b481..395e74bca5 100644 --- a/roles/web-app-bigbluebutton/config/main.yml +++ b/roles/web-app-bigbluebutton/config/main.yml @@ -39,9 +39,9 @@ compose: cleanup: true # Auto-Cleanup Recordings max_age_days: 30 # Cleanup recording after this amount of days min_storage: 50GB - database: + # noqa: shared + postgres: shared: false - # This is set to true to pass integration test, doesn't have any other function enabled: true greenlight: enabled: true diff --git a/roles/web-app-bluesky/config/main.yml b/roles/web-app-bluesky/config/main.yml index 3dc1ee3af8..a62ef8e5dd 100644 --- a/roles/web-app-bluesky/config/main.yml +++ b/roles/web-app-bluesky/config/main.yml @@ -41,9 +41,6 @@ compose: email: enabled: true shared: true - database: - shared: false - enabled: false # noqa: shared web: enabled: true # @see https://github.com/bluesky-social/social-app diff --git a/roles/web-app-bluesky/templates/compose.yml.j2 b/roles/web-app-bluesky/templates/compose.yml.j2 index 864bb5c161..c1b1311c65 100644 --- a/roles/web-app-bluesky/templates/compose.yml.j2 +++ b/roles/web-app-bluesky/templates/compose.yml.j2 @@ -31,7 +31,6 @@ {{ applications | compose_volumes( application_id, - database_volume=lookup('database', application_id, 'volume'), extra_volumes={'pds_data': {'name': BLUESKY_PDS_DATA_VOLUME}} ) }} {% include 'roles/sys-svc-compose/templates/networks.yml.j2' %} diff --git a/roles/web-app-bookwyrm/config/main.yml b/roles/web-app-bookwyrm/config/main.yml index a7015397da..0241f82972 100644 --- a/roles/web-app-bookwyrm/config/main.yml +++ b/roles/web-app-bookwyrm/config/main.yml @@ -17,10 +17,10 @@ compose: email: enabled: true shared: true - database: + # noqa: shared + postgres: + enabled: true shared: true - type: "postgres" - enabled: true # noqa: shared redis: backup: diff --git a/roles/web-app-bridgy-fed/config/main.yml b/roles/web-app-bridgy-fed/config/main.yml index 710f957653..662367d1dd 100644 --- a/roles/web-app-bridgy-fed/config/main.yml +++ b/roles/web-app-bridgy-fed/config/main.yml @@ -21,9 +21,6 @@ compose: matomo: enabled: true shared: true - database: - shared: false - enabled: false application: image: "python" version: "3.12-bookworm" diff --git a/roles/web-app-chess/config/main.yml b/roles/web-app-chess/config/main.yml index bbcc4d7a9c..d38f8b53e6 100644 --- a/roles/web-app-chess/config/main.yml +++ b/roles/web-app-chess/config/main.yml @@ -12,10 +12,9 @@ compose: matomo: enabled: true shared: true - database: - shared: true - type: "postgres" - enabled: true + postgres: + enabled: true + shared: true chess: image: "ghcr.io/kevinveenbirkenbach/fedi-chess" version: "v1.0.1" diff --git a/roles/web-app-confluence/config/main.yml b/roles/web-app-confluence/config/main.yml index c6ea4a85fa..e3dfdf3014 100644 --- a/roles/web-app-confluence/config/main.yml +++ b/roles/web-app-confluence/config/main.yml @@ -17,10 +17,9 @@ compose: email: enabled: true shared: true - database: + postgres: + enabled: true shared: true - type: "postgres" - enabled: true confluence: image: atlassian/confluence version: latest diff --git a/roles/web-app-dashboard/config/main.yml b/roles/web-app-dashboard/config/main.yml index 6420ac71e5..1b2b42412a 100644 --- a/roles/web-app-dashboard/config/main.yml +++ b/roles/web-app-dashboard/config/main.yml @@ -47,6 +47,7 @@ compose: shared: true dashboard: enabled: false + shared: true name: "dashboard" image: "ghcr.io/kevinveenbirkenbach/port-ui" version: "1.1.0" diff --git a/roles/web-app-dashboard/templates/playwright.env.j2 b/roles/web-app-dashboard/templates/playwright.env.j2 index 73087dafd9..fdfcd0961c 100644 --- a/roles/web-app-dashboard/templates/playwright.env.j2 +++ b/roles/web-app-dashboard/templates/playwright.env.j2 @@ -5,4 +5,4 @@ LOGIN_PASSWORD={{ users.administrator.password | dotenv_quote }} CDN_BASE_URL={{ lookup('tls', 'web-svc-cdn', 'url.base') | dotenv_quote }} DASHBOARD_JS_BASE_URL={{ DASHBOARD_JS_BASE_URL | dotenv_quote }} MATOMO_BASE_URL={{ lookup('tls', 'web-app-matomo', 'url.base') | dotenv_quote }} -MATOMO_ENABLED={{ applications | get_app_conf(application_id, 'compose.services.matomo.enabled') }} +MATOMO_ENABLED={{ lookup('config', application_id, 'compose.services.matomo.enabled') }} diff --git a/roles/web-app-discourse/config/main.yml b/roles/web-app-discourse/config/main.yml index d04ed502ff..2c5354323d 100644 --- a/roles/web-app-discourse/config/main.yml +++ b/roles/web-app-discourse/config/main.yml @@ -37,10 +37,10 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "postgres" + # noqa: shared + postgres: enabled: true + shared: true # noqa: shared redis: backup: diff --git a/roles/web-app-espocrm/config/main.yml b/roles/web-app-espocrm/config/main.yml index b96dc572f9..6068afb9c7 100644 --- a/roles/web-app-espocrm/config/main.yml +++ b/roles/web-app-espocrm/config/main.yml @@ -45,10 +45,9 @@ compose: email: enabled: true shared: true - database: + mariadb: + enabled: true shared: true - type: "mariadb" - enabled: true espocrm: image: "espocrm/espocrm" version: "latest" diff --git a/roles/web-app-fider/README.md b/roles/web-app-fider/README.md index db584236d3..020d46c326 100644 --- a/roles/web-app-fider/README.md +++ b/roles/web-app-fider/README.md @@ -32,12 +32,13 @@ Key settings in `config/main.yml`: | Key | Default | Description | |-----|---------|-------------| | `compose.services.oidc.enabled` | `true` | Automate Keycloak OIDC setup | -| `compose.services.database.type` | `postgres` | Database engine (postgres only) | +| `compose.services.postgres.enabled` | `true` | Enable PostgreSQL for Fider | +| `compose.services.postgres.shared` | `true` | Reuse the shared PostgreSQL provider | | `compose.services.fider.version` | `stable` | Docker image tag | | `server.domains.canonical` | `fider.{{ DOMAIN_PRIMARY }}` | Public domain | | `server.status_codes.default` | `[200, 301, 302, 405]` | Expected HTTP codes for health check (405 because Fider returns 405 on HEAD requests to `/`) | -## Further Resources +## Further resources - [Fider GitHub](https://github.com/getfider/fider) diff --git a/roles/web-app-fider/config/main.yml b/roles/web-app-fider/config/main.yml index 28958aab8d..14497bc325 100644 --- a/roles/web-app-fider/config/main.yml +++ b/roles/web-app-fider/config/main.yml @@ -29,10 +29,9 @@ compose: matomo: enabled: true shared: true - database: - shared: true - type: "postgres" + postgres: enabled: true + shared: true fider: image: "getfider/fider" version: "stable" diff --git a/roles/web-app-flowise/config/main.yml b/roles/web-app-flowise/config/main.yml index a5776af649..65d2a20123 100644 --- a/roles/web-app-flowise/config/main.yml +++ b/roles/web-app-flowise/config/main.yml @@ -64,9 +64,6 @@ compose: backup: disabled: true enabled: false - database: - shared: false - enabled: false ollama: enabled: true shared: true diff --git a/roles/web-app-friendica/config/main.yml b/roles/web-app-friendica/config/main.yml index 19e08adfff..1c8c08243d 100644 --- a/roles/web-app-friendica/config/main.yml +++ b/roles/web-app-friendica/config/main.yml @@ -39,10 +39,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "mariadb" - enabled: true + mariadb: + enabled: true + shared: true oauth2: origin: host: "application" diff --git a/roles/web-app-funkwhale/config/main.yml b/roles/web-app-funkwhale/config/main.yml index e5317e75c1..e221597ea9 100644 --- a/roles/web-app-funkwhale/config/main.yml +++ b/roles/web-app-funkwhale/config/main.yml @@ -30,10 +30,9 @@ compose: backup: disabled: true enabled: true - database: - shared: true - type: "postgres" + postgres: enabled: true + shared: true oauth2: origin: host: "front" diff --git a/roles/web-app-gitea/config/main.yml b/roles/web-app-gitea/config/main.yml index 5372178d3a..a5b2194380 100644 --- a/roles/web-app-gitea/config/main.yml +++ b/roles/web-app-gitea/config/main.yml @@ -43,10 +43,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "mariadb" + mariadb: enabled: true + shared: true gitea: image: "gitea/gitea" version: "latest" diff --git a/roles/web-app-gitlab/config/main.yml b/roles/web-app-gitlab/config/main.yml index 19ea272122..fcc58442cf 100644 --- a/roles/web-app-gitlab/config/main.yml +++ b/roles/web-app-gitlab/config/main.yml @@ -20,10 +20,9 @@ compose: backup: disabled: true enabled: true - database: + postgres: + enabled: true shared: true - type: "postgres" - enabled: true gitlab: image: "gitlab/gitlab-ee" version: "latest" diff --git a/roles/web-app-jira/config/main.yml b/roles/web-app-jira/config/main.yml index c9dfcec888..f65e75e557 100644 --- a/roles/web-app-jira/config/main.yml +++ b/roles/web-app-jira/config/main.yml @@ -18,10 +18,9 @@ compose: email: enabled: true shared: true - database: + postgres: + enabled: true shared: true - type: "postgres" - enabled: true jira: image: atlassian/jira-software version: latest diff --git a/roles/web-app-joomla/config/main.yml b/roles/web-app-joomla/config/main.yml index 0149146f77..d204663494 100644 --- a/roles/web-app-joomla/config/main.yml +++ b/roles/web-app-joomla/config/main.yml @@ -28,10 +28,9 @@ compose: email: enabled: true shared: true - database: + mariadb: + enabled: true shared: true - type: "mariadb" - enabled: true joomla: image: joomla version: latest diff --git a/roles/web-app-keycloak/config/main.yml b/roles/web-app-keycloak/config/main.yml index 6816e74264..1cf7f45a15 100644 --- a/roles/web-app-keycloak/config/main.yml +++ b/roles/web-app-keycloak/config/main.yml @@ -41,6 +41,9 @@ compose: enabled: true shared: true keycloak: + enabled: false + shared: true + provides: oidc image: "quay.io/keycloak/keycloak" version: "latest" name: "keycloak" @@ -54,10 +57,9 @@ compose: totp_enabled: True users: emails_verified: True - database: - shared: true - type: "postgres" + postgres: enabled: true + shared: true css: enabled: true shared: true diff --git a/roles/web-app-keycloak/tasks/04_login.yml b/roles/web-app-keycloak/tasks/04_login.yml index b88fc395e1..4a28a5d5d2 100644 --- a/roles/web-app-keycloak/tasks/04_login.yml +++ b/roles/web-app-keycloak/tasks/04_login.yml @@ -32,6 +32,9 @@ ' register: kc_login_bootstrap changed_when: false + retries: 30 + delay: 5 + until: kc_login_bootstrap.rc == 0 - name: Ensure permanent admin user exists (create if missing) shell: | diff --git a/roles/web-app-listmonk/config/main.yml b/roles/web-app-listmonk/config/main.yml index b336286691..2400e265e8 100644 --- a/roles/web-app-listmonk/config/main.yml +++ b/roles/web-app-listmonk/config/main.yml @@ -30,10 +30,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "postgres" + postgres: enabled: true + shared: true listmonk: cpus: 1.0 mem_reservation: 256m diff --git a/roles/web-app-magento/config/main.yml b/roles/web-app-magento/config/main.yml index ac721059cb..6d1e685e28 100644 --- a/roles/web-app-magento/config/main.yml +++ b/roles/web-app-magento/config/main.yml @@ -35,8 +35,9 @@ compose: name: "magento-nginx" backup: no_stop_required: true - database: - shared: false + # noqa: shared + mariadb: + shared: false enabled: true version: "11.4" # noqa: shared diff --git a/roles/web-app-mailu/config/main.yml b/roles/web-app-mailu/config/main.yml index 10fab31c3e..742f33d566 100644 --- a/roles/web-app-mailu/config/main.yml +++ b/roles/web-app-mailu/config/main.yml @@ -38,6 +38,9 @@ compose: enabled: true shared: true mailu: + enabled: false + shared: true + provides: email version: "2024.06" name: mailu min_storage: "20GB" @@ -50,10 +53,9 @@ compose: mem_reservation: "256m" mem_limit: "512m" pids_limit: 256 - database: - shared: true - type: "mariadb" + mariadb: enabled: true + shared: true cpus: "0.8" mem_reservation: "1g" mem_limit: "2g" diff --git a/roles/web-app-mailu/tasks/01_core.yml b/roles/web-app-mailu/tasks/01_core.yml index 9274613602..01e6ca1505 100644 --- a/roles/web-app-mailu/tasks/01_core.yml +++ b/roles/web-app-mailu/tasks/01_core.yml @@ -35,11 +35,6 @@ webserver_vhost_flavour: "basic" domain: "{{ MAILU_HOSTNAME }}" -- name: "Include Cert deploy service for '{{ role_name }}'" - include_role: - name: sys-ctl-mtn-cert-deploy - when: lookup('tls', application_id, 'enabled') | bool - - name: "Flush Docker Compose handlers" meta: flush_handlers @@ -68,6 +63,13 @@ loop_var: user_item no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" +- name: "Include Cert deploy service for '{{ role_name }}'" + include_role: + name: sys-ctl-mtn-cert-deploy + when: lookup('tls', application_id, 'enabled') | bool + # Alarm mail setup reaches sys-svc-mail and therefore requires the Mailu + # API token that is created in 03_manage_user.yml. + - name: Generate DKIM public key include_tasks: 04_generate-and-read-dkim.yml diff --git a/roles/web-app-mastodon/config/main.yml b/roles/web-app-mastodon/config/main.yml index a50664d402..81b63d6bd2 100644 --- a/roles/web-app-mastodon/config/main.yml +++ b/roles/web-app-mastodon/config/main.yml @@ -36,14 +36,9 @@ compose: mem_reservation: "256m" mem_limit: "512m" pids_limit: 256 - database: - shared: true - type: "postgres" - enabled: true - cpus: "1.0" - mem_reservation: "2g" - mem_limit: "3g" - pids_limit: 512 + postgres: + enabled: true + shared: true mastodon: image: "ghcr.io/mastodon/mastodon" version: latest diff --git a/roles/web-app-matomo/config/main.yml b/roles/web-app-matomo/config/main.yml index 9a2a7d31d2..124a08e139 100644 --- a/roles/web-app-matomo/config/main.yml +++ b/roles/web-app-matomo/config/main.yml @@ -35,7 +35,7 @@ compose: enabled: false matomo: enabled: false - shared: false + shared: true image: "matomo" version: "latest" name: "matomo" @@ -59,10 +59,9 @@ compose: mem_limit: 1g pids_limit: 512 - database: - shared: true - type: "mariadb" + mariadb: enabled: true + shared: true redis: backup: disabled: true diff --git a/roles/web-app-matrix/config/main.yml b/roles/web-app-matrix/config/main.yml index cf45a990d4..ff278b726d 100644 --- a/roles/web-app-matrix/config/main.yml +++ b/roles/web-app-matrix/config/main.yml @@ -15,10 +15,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "postgres" - enabled: true + postgres: + enabled: true + shared: true synapse: version: latest image: matrixdotorg/synapse diff --git a/roles/web-app-mattermost/README.md b/roles/web-app-mattermost/README.md index a801feec79..58451cf26b 100644 --- a/roles/web-app-mattermost/README.md +++ b/roles/web-app-mattermost/README.md @@ -28,7 +28,7 @@ Key settings in `config/main.yml`: | Key | Default | Description | |-----|---------|-------------| | `compose.services.oidc.enabled` | `true` | Enable Keycloak SSO via GitLab OAuth2 | -| `compose.services.database.type` | `postgres` | Database engine (postgres only) | +| `compose.services.postgres.shared` | `true` | Use the shared PostgreSQL service instead of a role-local one | | `compose.services.mattermost.version` | `latest` | Docker image tag | | `server.domains.canonical` | `mattermost.{{ DOMAIN_PRIMARY }}` | Public domain | diff --git a/roles/web-app-mattermost/config/main.yml b/roles/web-app-mattermost/config/main.yml index b6507981d0..525cd3a95d 100644 --- a/roles/web-app-mattermost/config/main.yml +++ b/roles/web-app-mattermost/config/main.yml @@ -31,10 +31,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "postgres" - enabled: true + postgres: + enabled: true + shared: true mattermost: image: "mattermost/mattermost-team-edition" version: "11.6.0" diff --git a/roles/web-app-mediawiki/config/main.yml b/roles/web-app-mediawiki/config/main.yml index 031033fa94..177a2a9622 100644 --- a/roles/web-app-mediawiki/config/main.yml +++ b/roles/web-app-mediawiki/config/main.yml @@ -26,10 +26,9 @@ compose: email: enabled: true shared: true - database: + mariadb: + enabled: true shared: true - type: "mariadb" - enabled: true mediawiki: image: mediawiki version: "1.45" diff --git a/roles/web-app-mig/config/main.yml b/roles/web-app-mig/config/main.yml index d7b87a318f..b421bcb33e 100644 --- a/roles/web-app-mig/config/main.yml +++ b/roles/web-app-mig/config/main.yml @@ -13,8 +13,6 @@ compose: enabled: false backup: disabled: true - database: - enabled: false mig: image: "ghcr.io/kevinveenbirkenbach/infinito-mig" version: "latest" diff --git a/roles/web-app-mini-qr/config/main.yml b/roles/web-app-mini-qr/config/main.yml index 302ef16746..f80e2d701e 100644 --- a/roles/web-app-mini-qr/config/main.yml +++ b/roles/web-app-mini-qr/config/main.yml @@ -16,8 +16,6 @@ compose: backup: disabled: true enabled: false - database: - enabled: false css: enabled: true shared: true diff --git a/roles/web-app-minio/config/main.yml b/roles/web-app-minio/config/main.yml index 93201d155d..58a0eb4f0c 100644 --- a/roles/web-app-minio/config/main.yml +++ b/roles/web-app-minio/config/main.yml @@ -42,9 +42,6 @@ compose: backup: disabled: true enabled: false - database: - shared: false - enabled: false css: enabled: true shared: true diff --git a/roles/web-app-mobilizon/config/main.yml b/roles/web-app-mobilizon/config/main.yml index f36f2a5612..e7a68b53b3 100644 --- a/roles/web-app-mobilizon/config/main.yml +++ b/roles/web-app-mobilizon/config/main.yml @@ -28,10 +28,9 @@ compose: email: enabled: true shared: true - database: - shared: true - type: "postgres" + postgres: enabled: true + shared: true mobilizon: image: "docker.io/kaihuri/mobilizon" name: "mobilizon" diff --git a/roles/web-app-moodle/config/main.yml b/roles/web-app-moodle/config/main.yml index 9992ee9f7f..aec89290c3 100644 --- a/roles/web-app-moodle/config/main.yml +++ b/roles/web-app-moodle/config/main.yml @@ -37,10 +37,9 @@ compose: email: enabled: true shared: true - database: + mariadb: + enabled: true shared: true - type: "mariadb" - enabled: true moodle: # nocheck: docker-version version: "4.5" # Latest LTS - Necessary for OIDC diff --git a/roles/web-app-nextcloud/config/main.yml b/roles/web-app-nextcloud/config/main.yml index 272efa940d..f8e2e6672a 100644 --- a/roles/web-app-nextcloud/config/main.yml +++ b/roles/web-app-nextcloud/config/main.yml @@ -43,9 +43,17 @@ compose: oidc: enabled: true shared: true + # flavor decides which OIDC plugin should be used. + # Available options: oidc_login, sociallogin + # @see https://apps.nextcloud.com/apps/oidc_login + # @see https://apps.nextcloud.com/apps/sociallogin + flavor: "oidc_login" coturn: + # Keep dedicated TURN provider statically discoverable so normal inventory + # generation and local iteration always pull in web-svc-coturn. + # Actual Talk TURN usage stays gated by plugins.spreed.enabled below. + enabled: true shared: true - enabled: true logout: enabled: true shared: true @@ -70,10 +78,9 @@ compose: mem_reservation: "1g" mem_limit: "8g" pids_limit: 512 - database: - shared: true - type: "mariadb" + mariadb: enabled: true + shared: true cpus: "0.75" mem_reservation: "512m" mem_limit: "1.5g" @@ -106,14 +113,16 @@ compose: mem_limit: "512m" pids_limit: 256 talk: + enabled: "{{ lookup('config', 'web-app-nextcloud', 'plugins.spreed.enabled', False) }}" name: "nextcloud-talk" image: "nextcloud/aio-talk" version: "latest" backup: no_stop_required: false turn_server: - onboard_enabled: true - standalone_enabled: false + # Use dedicated web-svc-coturn by default. HPB onboard TURN stays available as an explicit fallback only. + onboard_enabled: false + standalone_enabled: true network_mode: bridge cpus: "2.0" mem_reservation: "1g" @@ -150,14 +159,8 @@ compose: shared: true hcaptcha: enabled: "{{ HCAPTCHA_ENABLED | bool }}" - enabled: "{{ applications | default({}, true) | get_app_conf('web-app-nextcloud', 'compose.services.oidc.enabled', False, True, True) }}" # Activate OIDC for Nextcloud - # floavor decides which OICD plugin should be used. - # Available options: oidc_login, sociallogin - # @see https://apps.nextcloud.com/apps/oidc_login - # @see https://apps.nextcloud.com/apps/sociallogin - flavor: "oidc_login" # Keeping on sociallogin because the other option is not implemented yet default_quota: '1000000000' # Quota to assign if no quota is specified in the OIDC response (bytes) -legacy_login_mask: +legacy_login_mask: enabled: False # If true, then legacy login mask is shown. Otherwise just SSO performance: @@ -167,8 +170,6 @@ performance: opcache_memory_consumption: "{{ ((ansible_facts['memtotal_mb'] | int) / 30)|int }}M" # Dynamic set memory consumption plugins_enabled: true # Implemented for speeding up testing and debugging process. For productive environments keep it true and steer the apps via the plugins config -oidc: - flavor: "{{ _applications_nextcloud_oidc_flavor }}" plugins: # List for Nextcloud Plugin Routine # Decides if plugins should be activated or deactivated @@ -309,7 +310,7 @@ plugins: enabled: true oidc_login: # Nextcloud User OIDC: integrates OpenID Connect for user authentication (https://apps.nextcloud.com/apps/oidc_login) - enabled: "{{ _applications_nextcloud_oidc_flavor=='oidc_login' | lower }}" + enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.oidc.flavor', 'oidc_login') == 'oidc_login' }}" incompatible_plugins: - user_oidc # Will be disabled - sociallogin # Will be disabled @@ -336,7 +337,7 @@ plugins: - fileslibreofficeedit sociallogin: # Nextcloud social login: allows authentication using social networks (https://apps.nextcloud.com/apps/sociallogin) - enabled: "{{ _applications_nextcloud_oidc_flavor=='sociallogin' | lower }}" + enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.oidc.flavor', 'oidc_login') == 'sociallogin' }}" incompatible_plugins: - user_oidc # Will be disabled - oidc_login # Will be disabled @@ -354,18 +355,18 @@ plugins: # enabled: false twofactor_nextcloud_notification: # Nextcloud two-factor notification: sends notifications for two-factor authentication events (https://apps.nextcloud.com/apps/twofactor_nextcloud_notification) - enabled: "{{ not (applications | default({}, true) | get_app_conf('web-app-nextcloud', 'compose.services.oidc.enabled', False, True, True)) }}" # Deactivate 2FA if oidc is active + enabled: "{{ not (lookup('config', 'web-app-nextcloud', 'compose.services.oidc.enabled', False)) }}" # Deactivate 2FA if oidc is active twofactor_totp: # Nextcloud two-factor TOTP: provides time-based one-time password authentication (https://apps.nextcloud.com/apps/twofactor_totp) - enabled: "{{ not (applications | default({}, true) | get_app_conf('web-app-nextcloud', 'compose.services.oidc.enabled', False, True, True)) }}" # Deactivate 2FA if oidc is active + enabled: "{{ not (lookup('config', 'web-app-nextcloud', 'compose.services.oidc.enabled', False)) }}" # Deactivate 2FA if oidc is active user_ldap: # Nextcloud user LDAP: integrates LDAP for user management and authentication - enabled: "{{ applications | default({}, true) | get_app_conf('web-app-nextcloud', 'compose.services.ldap.enabled', False, True, True) }}" + enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.ldap.enabled', True) }}" user_directory: enabled: true # Enables the LDAP User Directory Search user_oidc: # Nextcloud User OIDC: integrates OpenID Connect for user authentication (https://apps.nextcloud.com/apps/user_oidc) - enabled: "{{ _applications_nextcloud_oidc_flavor=='user_oidc' | lower }}" + enabled: "{{ lookup('config', 'web-app-nextcloud', 'compose.services.oidc.flavor', 'oidc_login') == 'user_oidc' }}" incompatible_plugins: - oidc_login - sociallogin diff --git a/roles/web-app-nextcloud/docs/Administration.md b/roles/web-app-nextcloud/docs/Administration.md index be6b0452e9..cfed84899d 100644 --- a/roles/web-app-nextcloud/docs/Administration.md +++ b/roles/web-app-nextcloud/docs/Administration.md @@ -17,4 +17,14 @@ apk add --no-cache nano && nano config/config.php ## Logs -The logs you will find here on the host: **/var/lib/docker/volumes/nextcloud_data/_data/data/nextcloud.log** \ No newline at end of file +The logs you will find here on the host: **/var/lib/docker/volumes/nextcloud_data/_data/data/nextcloud.log** + +## Talk TURN and STUN + +When `compose.services.talk.enabled` is true, Nextcloud Talk MUST use the dedicated `web-svc-coturn` service for STUN and TURN instead of the HPB port exposed by `web-app-nextcloud`. + +Check these admin URLs after deployment: + +- `/settings/admin/talk#signaling_server` +- `/settings/admin/talk#stun_server` +- `/settings/admin/talk#turn_server` diff --git a/roles/web-app-nextcloud/files/playwright.spec.js b/roles/web-app-nextcloud/files/playwright.spec.js index 05620a171a..7f18aab838 100644 --- a/roles/web-app-nextcloud/files/playwright.spec.js +++ b/roles/web-app-nextcloud/files/playwright.spec.js @@ -1,9 +1,29 @@ +// End-to-end tests for the Nextcloud role. +// +// Two scenarios: +// 1. "nextcloud talk admin settings" — SSO-login as admin, navigate to the +// Talk admin page, and assert the configured HPB / STUN / TURN values +// are rendered (and that legacy onboard values are absent). +// 2. "dashboard to nextcloud login" — enter Nextcloud through the +// portal dashboard iframe, complete the OIDC handoff via Keycloak, +// reuse the authenticated context for the Talk check, then log out. +// +// All authentication goes through Keycloak (OIDC). Local Nextcloud login +// is intentionally NOT exercised: `oidc_login_hide_password_form` keeps the +// native form hidden in this deployment. const { test, expect } = require("@playwright/test"); +// `ignoreHTTPSErrors` is needed because the local stack typically uses the +// self-signed CA set up by `make trust-ca`, which the Playwright container +// does not trust by default. test.use({ ignoreHTTPSErrors: true }); +// --------------------------------------------------------------------------- +// Env decoding +// --------------------------------------------------------------------------- + function decodeDotenvQuotedValue(value) { if (typeof value !== "string" || value.length < 2) { return value; @@ -24,10 +44,52 @@ function decodeDotenvQuotedValue(value) { // `docker --env-file` preserves the quotes emitted by `dotenv_quote`, // so normalize these values before building URLs or typing credentials. +// --------------------------------------------------------------------------- +// Env-driven config +// +// All values originate from the rendered `.env` under the staging dir. The +// Talk-related values are optional and gate the first test via +// `nextcloudTalkSettingsCheckEnabled`. +// --------------------------------------------------------------------------- const loginUsername = decodeDotenvQuotedValue(process.env.LOGIN_USERNAME); const loginPassword = decodeDotenvQuotedValue(process.env.LOGIN_PASSWORD); +const nextcloudDirectLoginPassword = decodeDotenvQuotedValue(process.env.NEXTCLOUD_DIRECT_LOGIN_PASSWORD) || loginPassword; const oidcIssuerUrl = decodeDotenvQuotedValue(process.env.OIDC_ISSUER_URL); const nextcloudBaseUrl = decodeDotenvQuotedValue(process.env.NEXTCLOUD_BASE_URL); +const nextcloudTalkSettingsCheckEnabled = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_SETTINGS_CHECK_ENABLED) === "true"; +const nextcloudTalkSettingsUrl = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_SETTINGS_URL); +const nextcloudTalkExpectedSignalingUrl = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_EXPECTED_SIGNALING_URL); +const nextcloudTalkExpectedStunServer = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_EXPECTED_STUN_SERVER); +const nextcloudTalkExpectedTurnServer = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_EXPECTED_TURN_SERVER); +const nextcloudTalkUnexpectedStunServer = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_UNEXPECTED_STUN_SERVER); +const nextcloudTalkUnexpectedTurnServer = decodeDotenvQuotedValue(process.env.NEXTCLOUD_TALK_UNEXPECTED_TURN_SERVER); +const nextcloudUsernameFieldPattern = /account name or email|username or email/i; +const nextcloudCredentialSubmitPattern = /sign in|log in/i; + +// --------------------------------------------------------------------------- +// Locator helpers +// +// Nextcloud renders different "shell" containers depending on the app (Vue +// vs. legacy) and version. The selectors below match any of them so the +// tests work across NC 28+ without hard-coding one layout. +// --------------------------------------------------------------------------- + +function getNextcloudShellCandidates(target) { + return [ + { + kind: "shell", + // #app-content-vue: dashboard and Vue-based apps. + // #app-navigation-vue: Vue sidebar (files etc.). + // #app-content: legacy app container. + // #header-start__appmenu: always present in layout.user.php