diff --git a/group_vars/all/18_swarm.yml b/group_vars/all/18_swarm.yml index 8b41a6f57d..72d92d3cd7 100644 --- a/group_vars/all/18_swarm.yml +++ b/group_vars/all/18_swarm.yml @@ -24,6 +24,9 @@ SWARM_INGRESS_GUARDED: "{{ swarm_ingress_endpoints.stdout_lines | swarm_ingress_ SWARM_INGRESS_PEERS: "{{ swarm_ingress_nodes.stdout_lines | swarm_node_addresses }}" +SWARM_MANAGER_PORT: 2377 +SWARM_LISTEN_ADDR: "0.0.0.0:{{ SWARM_MANAGER_PORT }}" + swarm: manager: advertise_addr: >- diff --git a/roles/svc-db-openldap/tasks/schemas/moodle.yml b/roles/svc-db-openldap/tasks/schemas/moodle.yml index bfe5cf53b6..b91fb9816d 100644 --- a/roles/svc-db-openldap/tasks/schemas/moodle.yml +++ b/roles/svc-db-openldap/tasks/schemas/moodle.yml @@ -16,18 +16,19 @@ objectclass_defs: - "( 1.3.6.1.4.1.99999.13 NAME 'infinitoMoodleUser' DESC 'Auxiliary class for Moodle-only user attributes' AUXILIARY MAY ( infinitoNamePhoneticGiven $ infinitoNamePhoneticFamily $ infinitoTimezone ) )" - command: > - ldapsm - -s {{ OPENLDAP_SERVER_URI }} - -D '{{ OPENLDAP_BIND_DN }}' - -W '{{ OPENLDAP_BIND_PW }}' - -n {{ schema_name }} - {% for at in attribute_defs %} - -a "{{ at }}" - {% endfor %} - {% for oc in objectclass_defs %} - -c "{{ oc }}" - {% endfor %} + command: + cmd: > + {{ OPENLDAP_LDAPSM_COMMAND }} + -s {{ OPENLDAP_SERVER_URI }} + -D '{{ OPENLDAP_BIND_DN }}' + -n {{ schema_name }} + {% for at in attribute_defs %} + -a "{{ at }}" + {% endfor %} + {% for oc in objectclass_defs %} + -c "{{ oc }}" + {% endfor %} + stdin: "{{ OPENLDAP_BIND_PW }}" register: ldapsm_moodle_result changed_when: "'Created schema entry' in ldapsm_moodle_result.stdout" check_mode: false diff --git a/roles/svc-db-openldap/tasks/schemas/nextcloud.yml b/roles/svc-db-openldap/tasks/schemas/nextcloud.yml index afd814f361..12c89f86de 100644 --- a/roles/svc-db-openldap/tasks/schemas/nextcloud.yml +++ b/roles/svc-db-openldap/tasks/schemas/nextcloud.yml @@ -8,18 +8,19 @@ objectclass_defs: - "( 1.3.6.1.4.1.99999.2 NAME '{{ LDAP.USER.OBJECTS.AUXILIARY.NEXTCLOUD_USER }}' DESC 'Auxiliary class for Nextcloud attributes' AUXILIARY MAY ( {{ LDAP.USER.ATTRIBUTES.NEXTCLOUD_QUOTA }} ) )" - command: > - ldapsm - -s {{ OPENLDAP_SERVER_URI }} - -D '{{ OPENLDAP_BIND_DN }}' - -W '{{ OPENLDAP_BIND_PW }}' - -n {{ schema_name }} - {% for at in attribute_defs %} - -a "{{ at }}" - {% endfor %} - {% for oc in objectclass_defs %} - -c "{{ oc }}" - {% endfor %} + command: + cmd: > + {{ OPENLDAP_LDAPSM_COMMAND }} + -s {{ OPENLDAP_SERVER_URI }} + -D '{{ OPENLDAP_BIND_DN }}' + -n {{ schema_name }} + {% for at in attribute_defs %} + -a "{{ at }}" + {% endfor %} + {% for oc in objectclass_defs %} + -c "{{ oc }}" + {% endfor %} + stdin: "{{ OPENLDAP_BIND_PW }}" register: ldapsm_result changed_when: "'Created schema entry' in ldapsm_result.stdout" check_mode: false diff --git a/roles/svc-db-openldap/tasks/schemas/openssh_lpk.yml b/roles/svc-db-openldap/tasks/schemas/openssh_lpk.yml index 4ad8992d49..046e7e2be2 100644 --- a/roles/svc-db-openldap/tasks/schemas/openssh_lpk.yml +++ b/roles/svc-db-openldap/tasks/schemas/openssh_lpk.yml @@ -14,18 +14,19 @@ SUP top AUXILIARY MAY ( {{ LDAP.USER.ATTRIBUTES.SSH_PUBLIC_KEY }} $ sshFingerprint ) ) - command: > - ldapsm - -s {{ OPENLDAP_SERVER_URI }} - -D '{{ OPENLDAP_BIND_DN }}' - -W '{{ OPENLDAP_BIND_PW }}' - -n {{ schema_name }} - {% for at in attribute_defs %} - -a "{{ at }}" - {% endfor %} - {% for oc in objectclass_defs %} - -c "{{ oc }}" - {% endfor %} + command: + cmd: > + {{ OPENLDAP_LDAPSM_COMMAND }} + -s {{ OPENLDAP_SERVER_URI }} + -D '{{ OPENLDAP_BIND_DN }}' + -n {{ schema_name }} + {% for at in attribute_defs %} + -a "{{ at }}" + {% endfor %} + {% for oc in objectclass_defs %} + -c "{{ oc }}" + {% endfor %} + stdin: "{{ OPENLDAP_BIND_PW }}" register: opensshlpk_ldapsm changed_when: "'Created schema entry' in opensshlpk_ldapsm.stdout" check_mode: false diff --git a/roles/svc-db-openldap/vars/main.yml b/roles/svc-db-openldap/vars/main.yml index 9d360bac95..ca4f80cd3d 100644 --- a/roles/svc-db-openldap/vars/main.yml +++ b/roles/svc-db-openldap/vars/main.yml @@ -20,6 +20,8 @@ OPENLDAP_VERSION: "{{ lookup('config', application_id, 'services.' ~ entity_name OPENLDAP_SERVICE: "{{ entity_name }}" OPENLDAP_BIND_DN: "{{ LDAP.DN.ADMINISTRATOR.DATA }}" OPENLDAP_BIND_PW: "{{ LDAP.BIND_CREDENTIAL }}" +OPENLDAP_LDAPSM_COMMAND: |- + {{ ansible_python_interpreter }} -c 'import sys; from ldapsm.__main__ import main; sys.argv = ["ldapsm", *sys.argv[1:], "-W", sys.stdin.readline().rstrip("\n")]; sys.exit(main())' OPENLDAP_NETWORK_SWITCH_PUBLIC: "{{ lookup('config', application_id, 'services.openldap.network.public') }}" OPENLDAP_NETWORK_SWITCH_LOCAL: "{{ lookup('config', application_id, 'services.openldap.network.local') }}" diff --git a/roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh b/roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh index fa937f0ded..56bee95f78 100644 --- a/roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh +++ b/roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh @@ -2,10 +2,8 @@ set -euo pipefail # Usage: -# set_postgres_superuser_password.sh -# POSTGRES_SUPERUSER_PASSWORD: the password to write, read from the -# environment only, so it reaches neither this script's argv nor that of the -# container exec calls it makes. +# set_postgres_superuser_password.sh < password +# stdin: the password to write. # # The role is the cluster's superuser: "postgres" for the shared engine, and # whatever POSTGRES_USER a dedicated one was initialised with. Both are reached @@ -15,15 +13,16 @@ set -euo pipefail container_raw="${1:-}" role="${2:-}" -new_pw="${POSTGRES_SUPERUSER_PASSWORD:-}" if [[ -z "$container_raw" || -z "$role" ]]; then - echo "Usage: $0 " >&2 + echo "Usage: $0 < password" >&2 exit 2 fi +new_pw="$(cat)" + if [[ -z "$new_pw" ]]; then - echo "[FAIL] POSTGRES_SUPERUSER_PASSWORD is empty; refusing to set an empty password." >&2 + echo "[FAIL] no password on stdin; refusing to set an empty password." >&2 exit 1 fi @@ -110,7 +109,8 @@ for _ in {1..30}; do # shellcheck disable=SC2016 if ! container exec -e NEW_POSTGRES_PASSWORD -e PG_ROLE="$role" "$container" bash -lc ' - psql -U "$PG_ROLE" -d postgres -v ON_ERROR_STOP=1 -v role="$PG_ROLE" -v password="$NEW_POSTGRES_PASSWORD" <<'"'"'SQL'"'"' + psql -U "$PG_ROLE" -d postgres -v ON_ERROR_STOP=1 -v role="$PG_ROLE" <<'"'"'SQL'"'"' +\set password `printenv NEW_POSTGRES_PASSWORD` ALTER USER :"role" WITH PASSWORD :'"'"'password'"'"'; SQL ' 2>/dev/null; then diff --git a/roles/svc-db-postgres/tasks/00_core.yml b/roles/svc-db-postgres/tasks/00_core.yml index d714d3567b..8e72fc7dcd 100644 --- a/roles/svc-db-postgres/tasks/00_core.yml +++ b/roles/svc-db-postgres/tasks/00_core.yml @@ -44,10 +44,15 @@ changed_when: false - name: "✅ POSTGRES | Ensure postgres superuser password matches inventory" - ansible.builtin.script: > # nocheck: container-address-quote script evals the fragment itself - shell/set_postgres_superuser_password.sh {{ POSTGRES_CONTAINER_ADDRESS | quote }} postgres - environment: - POSTGRES_SUPERUSER_PASSWORD: "{{ POSTGRES_PASSWORD }}" + ansible.builtin.command: + argv: + - bash + - -c + - "{{ lookup('file', 'shell/set_postgres_superuser_password.sh') }}" + - set_postgres_superuser_password.sh + - "{{ POSTGRES_CONTAINER_ADDRESS }}" + - postgres + stdin: "{{ POSTGRES_PASSWORD }}" register: postgres_pw_result delegate_to: "{{ STACK_HOST }}" run_once: true diff --git a/roles/svc-swarm-node/tasks/01_manager.yml b/roles/svc-swarm-node/tasks/01_manager.yml index 8b8c2fb70e..8df62372f6 100644 --- a/roles/svc-swarm-node/tasks/01_manager.yml +++ b/roles/svc-swarm-node/tasks/01_manager.yml @@ -26,7 +26,7 @@ changed_when: false - name: "⬇️ Fetch manager swarm-advertise address" - ansible.builtin.command: container info --format '{{ "{{" }}.Swarm.NodeAddr{{ "}}" }}:2377' + ansible.builtin.command: container info --format '{{ "{{" }}.Swarm.NodeAddr{{ "}}" }}:{{ SWARM_MANAGER_PORT }}' register: docker_swarm_manager_addr changed_when: false diff --git a/roles/svc-swarm-node/tasks/02_manager_join.yml b/roles/svc-swarm-node/tasks/02_manager_join.yml index 515f797297..2e89de9d5b 100644 --- a/roles/svc-swarm-node/tasks/02_manager_join.yml +++ b/roles/svc-swarm-node/tasks/02_manager_join.yml @@ -7,9 +7,17 @@ - name: "🐝 Join swarm cluster as manager (only when not already active)" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - ansible.builtin.command: >- - container swarm join - --token {{ svc_swarm_manager_token }} - {{ svc_swarm_manager_addr }} + uri_retry: + url: http://localhost/swarm/join + unix_socket: /var/run/docker.sock + method: POST + body_format: json + body: + ListenAddr: "{{ SWARM_LISTEN_ADDR }}" + RemoteAddrs: + - "{{ svc_swarm_manager_addr }}" + JoinToken: "{{ svc_swarm_manager_token }}" + status_code: 200 + timeout: "{{ lookup('timeout', 120) | int }}" when: docker_swarm_local_state.stdout != 'active' changed_when: true diff --git a/roles/svc-swarm-node/tasks/03_worker.yml b/roles/svc-swarm-node/tasks/03_worker.yml index 997df31374..356ab82f46 100644 --- a/roles/svc-swarm-node/tasks/03_worker.yml +++ b/roles/svc-swarm-node/tasks/03_worker.yml @@ -7,9 +7,17 @@ - name: "🐝 Join swarm cluster as worker (only when not already active)" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - ansible.builtin.command: >- - container swarm join - --token {{ svc_swarm_worker_token }} - {{ svc_swarm_manager_addr }} + uri_retry: + url: http://localhost/swarm/join + unix_socket: /var/run/docker.sock + method: POST + body_format: json + body: + ListenAddr: "{{ SWARM_LISTEN_ADDR }}" + RemoteAddrs: + - "{{ svc_swarm_manager_addr }}" + JoinToken: "{{ svc_swarm_worker_token }}" + status_code: 200 + timeout: "{{ lookup('timeout', 120) | int }}" when: docker_swarm_local_state.stdout != 'active' changed_when: true diff --git a/roles/sys-svc-rdbms/tasks/utils/realign_dedicated_db.yml b/roles/sys-svc-rdbms/tasks/utils/realign_dedicated_db.yml index 26ab836c36..5204f934bc 100644 --- a/roles/sys-svc-rdbms/tasks/utils/realign_dedicated_db.yml +++ b/roles/sys-svc-rdbms/tasks/utils/realign_dedicated_db.yml @@ -25,12 +25,15 @@ changed_when: false - name: "🔑 Realign the password a dedicated postgres kept from its initdb" - ansible.builtin.script: > # nocheck: container-address-quote script evals the fragment itself - {{ lookup('path_absolute', 'roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh') }} - {{ lookup('database', application_id, 'container') | quote }} - {{ lookup('database', application_id, 'username') | quote }} - environment: - POSTGRES_SUPERUSER_PASSWORD: "{{ lookup('database', application_id, 'password') }}" + ansible.builtin.command: + argv: + - bash + - -c + - "{{ lookup('file', lookup('path_absolute', 'roles/svc-db-postgres/files/shell/set_postgres_superuser_password.sh')) }}" + - set_postgres_superuser_password.sh + - "{{ lookup('database', application_id, 'container') }}" + - "{{ lookup('database', application_id, 'username') }}" + stdin: "{{ lookup('database', application_id, 'password') }}" register: _app_db_realign no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" changed_when: _app_db_realign.stdout is search('\\[CHANGED\\]') diff --git a/roles/web-app-mediawiki/files/install/or_update.sh b/roles/web-app-mediawiki/files/install/or_update.sh index cd8cd7628f..f0769242f7 100755 --- a/roles/web-app-mediawiki/files/install/or_update.sh +++ b/roles/web-app-mediawiki/files/install/or_update.sh @@ -5,10 +5,17 @@ set -euo pipefail NETWORK="$1"; MARIADB_VERSION="$2" -DB_HOST="$3"; DB_PORT="$4"; DB_USER="$5"; DB_PASSWORD="$6"; DB_NAME="$7" -MW_USER="$8"; MW_IMAGE="$9"; MW_VERSION="${10}"; MW_HTML_DIR="${11}" -MW_URL="${12}"; MW_SITENAME="${13}"; ADMIN_NAME="${14}"; ADMIN_PASSWORD="${15}" +DB_HOST="$3"; DB_PORT="$4"; DB_USER="$5"; DB_NAME="$6" +MW_USER="$7"; MW_IMAGE="$8"; MW_VERSION="$9"; MW_HTML_DIR="${10}" +MW_URL="${11}"; MW_SITENAME="${12}"; ADMIN_NAME="${13}" +{ IFS= read -r MW_DB_PASSWORD && IFS= read -r MW_ADMIN_PASSWORD; } || { + echo "the database and the admin password must arrive on stdin, one per line" >&2 + exit 1 +} +: "${MW_DB_PASSWORD:?the database password must be the first line on stdin}" +: "${MW_ADMIN_PASSWORD:?the admin password must be the second line on stdin}" +export MW_DB_PASSWORD MW_ADMIN_PASSWORD : "${MW_CUSTOM_IMAGE:?MW_CUSTOM_IMAGE env var required for update}" : "${MW_LOCALSETTINGS_HOST_PATH:?MW_LOCALSETTINGS_HOST_PATH env var required for update}" : "${MW_LOCALSETTINGS_CONTAINER_PATH:?MW_LOCALSETTINGS_CONTAINER_PATH env var required for update}" @@ -18,8 +25,9 @@ MW_URL="${12}"; MW_SITENAME="${13}"; ADMIN_NAME="${14}"; ADMIN_PASSWORD="${15}" : "${MW_VOLUME_EXTENSIONS:?MW_VOLUME_EXTENSIONS env var required for update}" has_tables=0 -if container run --rm --network "$NETWORK" "mariadb:${MARIADB_VERSION:-latest}" \ - mariadb -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASSWORD" \ +if MYSQL_PWD="$MW_DB_PASSWORD" container run --rm --network "$NETWORK" -e MYSQL_PWD \ + "mariadb:${MARIADB_VERSION:-latest}" \ + mariadb -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" \ -N -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$DB_NAME';" \ 2>/dev/null | grep -q -v '^0$'; then has_tables=1 @@ -27,22 +35,24 @@ fi if [ "$has_tables" -eq 0 ]; then echo "[mw] Fresh DB detected -> running install (one-shot)" + # shellcheck disable=SC2016 container run --rm \ --network "$NETWORK" \ -u "$MW_USER" \ + -e MW_DB_PASSWORD \ + -e MW_ADMIN_PASSWORD \ "$MW_IMAGE:$MW_VERSION" \ - php "$MW_HTML_DIR/maintenance/run.php" install \ + bash -c 'umask 077 && printf "%s" "$MW_DB_PASSWORD" > /tmp/dbpass && printf "%s" "$MW_ADMIN_PASSWORD" > /tmp/pass && exec php "$@" --dbpassfile /tmp/dbpass --passfile /tmp/pass' _ \ + "$MW_HTML_DIR/maintenance/run.php" install \ --confpath /tmp \ --dbtype mysql \ --dbserver "$DB_HOST:$DB_PORT" \ --dbname "$DB_NAME" \ --dbuser "$DB_USER" \ - --dbpass "$DB_PASSWORD" \ --server "$MW_URL" \ --scriptpath "" \ "$MW_SITENAME" \ - "$ADMIN_NAME" \ - --pass "$ADMIN_PASSWORD" + "$ADMIN_NAME" else echo "[mw] DB already initialized -> skipping install" fi diff --git a/roles/web-app-mediawiki/tasks/03_install.yml b/roles/web-app-mediawiki/tasks/03_install.yml index 3f5e8cf5d9..7c005d1964 100644 --- a/roles/web-app-mediawiki/tasks/03_install.yml +++ b/roles/web-app-mediawiki/tasks/03_install.yml @@ -1,14 +1,27 @@ --- - name: "🥾 MEDIAWIKI | Bootstrap DB (install if empty) then update" - ansible.builtin.script: >- - install/or_update.sh - "{{ MEDIAWIKI_NETWORK_DATABASE }}" "{{ lookup('database', application_id, 'version') | default('latest') }}" - "{{ lookup('database', application_id, 'host') }}" "{{ lookup('database', application_id, 'port') }}" - "{{ lookup('database', application_id, 'username') }}" "{{ lookup('database', application_id, 'password') }}" - "{{ lookup('database', application_id, 'name') }}" - "{{ MEDIAWIKI_USER }}" "{{ MEDIAWIKI_IMAGE }}" "{{ MEDIAWIKI_VERSION }}" "{{ MEDIAWIKI_HTML_DIR }}" - "{{ MEDIAWIKI_URL }}" "{{ MEDIAWIKI_SITENAME }}" - "{{ MEDIAWIKI_ADMINISTRATOR_NAME }}" "{{ MEDIAWIKI_ADMINISTRATOR_PASSWORD }}" + ansible.builtin.command: + argv: + - bash + - -c + - "{{ lookup('file', 'install/or_update.sh') }}" + - or_update.sh + - "{{ MEDIAWIKI_NETWORK_DATABASE }}" + - "{{ lookup('database', application_id, 'version') | default('latest') }}" + - "{{ lookup('database', application_id, 'host') }}" + - "{{ lookup('database', application_id, 'port') }}" + - "{{ lookup('database', application_id, 'username') }}" + - "{{ lookup('database', application_id, 'name') }}" + - "{{ MEDIAWIKI_USER }}" + - "{{ MEDIAWIKI_IMAGE }}" + - "{{ MEDIAWIKI_VERSION }}" + - "{{ MEDIAWIKI_HTML_DIR }}" + - "{{ MEDIAWIKI_URL }}" + - "{{ MEDIAWIKI_SITENAME }}" + - "{{ MEDIAWIKI_ADMINISTRATOR_NAME }}" + stdin: |- + {{ lookup('database', application_id, 'password') }} + {{ MEDIAWIKI_ADMINISTRATOR_PASSWORD }} environment: MW_CUSTOM_IMAGE: "{{ MEDIAWIKI_CUSTOM_IMAGE_REF }}" MW_LOCALSETTINGS_HOST_PATH: "{{ MEDIAWIKI_LOCALSETTINGS_HOST_PATH }}" diff --git a/roles/web-app-xwiki/files/shell/debug_superadmin.sh b/roles/web-app-xwiki/files/shell/debug_superadmin.sh index 53cd6b4919..6e55db9997 100755 --- a/roles/web-app-xwiki/files/shell/debug_superadmin.sh +++ b/roles/web-app-xwiki/files/shell/debug_superadmin.sh @@ -10,7 +10,8 @@ # Usage: # debug_superadmin.sh \ # STATUS REDIRECTED URL WWW_AUTHENTICATE CONTENT_TYPE CONTENT_HEAD \ -# XWIKI_CONTAINER ANSIBLE_PASSWORD +# XWIKI_CONTAINER < password +# stdin: the inventory's superadmin password. set -euo pipefail STATUS="$1" @@ -20,7 +21,8 @@ WWW_AUTHENTICATE="$4" CONTENT_TYPE="$5" CONTENT_HEAD="$6" XWIKI_CONTAINER="$7" -ANSIBLE_PASSWORD="$8" +ANSIBLE_PASSWORD="$(cat)" +: "${ANSIBLE_PASSWORD:?the superadmin password must arrive on stdin}" echo "=== superadmin check ===" echo "status=$STATUS" diff --git a/roles/web-app-xwiki/tasks/02_manager_ops.yml b/roles/web-app-xwiki/tasks/02_manager_ops.yml index 40e13d9981..338ace1cbc 100644 --- a/roles/web-app-xwiki/tasks/02_manager_ops.yml +++ b/roles/web-app-xwiki/tasks/02_manager_ops.yml @@ -18,16 +18,20 @@ - block: - name: "🐛 DEBUG | superadmin check + pw hash compare (condensed)" no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" - script: >- - shell/debug_superadmin.sh - "{{ _super_check_ext.status }}" - "{{ _super_check_ext.redirected | default('n/a') }}" - "{{ _super_check_ext.url | default('n/a') }}" - "{{ _super_check_ext.www_authenticate | default(_super_check_ext.headers['www-authenticate'] | default('n/a')) }}" - "{{ _super_check_ext.content_type | default(_super_check_ext.headers['content-type'] | default('n/a')) }}" - "{{ (_super_check_ext.content | default(''))[:600] | replace('\n','\\n') }}" - "{{ XWIKI_CONTAINER }}" - "{{ XWIKI_SUPERADMIN_PASSWORD }}" + ansible.builtin.command: + argv: + - bash + - -c + - "{{ lookup('file', 'shell/debug_superadmin.sh') }}" + - debug_superadmin.sh + - "{{ _super_check_ext.status }}" + - "{{ _super_check_ext.redirected | default('n/a') }}" + - "{{ _super_check_ext.url | default('n/a') }}" + - "{{ _super_check_ext.www_authenticate | default(_super_check_ext.headers['www-authenticate'] | default('n/a')) }}" + - "{{ _super_check_ext.content_type | default(_super_check_ext.headers['content-type'] | default('n/a')) }}" + - "{{ (_super_check_ext.content | default(''))[:600] | replace('\n','\\n') }}" + - "{{ XWIKI_CONTAINER }}" + stdin: "{{ XWIKI_SUPERADMIN_PASSWORD }}" register: _dbg_superadmin changed_when: false failed_when: false diff --git a/tests/lint/ansible/jinja/test_task_argv_no_secret.py b/tests/lint/ansible/jinja/test_task_argv_no_secret.py new file mode 100644 index 0000000000..9dbc179f4b --- /dev/null +++ b/tests/lint/ansible/jinja/test_task_argv_no_secret.py @@ -0,0 +1,165 @@ +from __future__ import annotations + +import re +import unittest +from pathlib import Path + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import iter_project_files_with_content + +from . import PROJECT_ROOT +from .test_compose_argv_no_secret import _CREDENTIAL, _EXPRESSION, _indent + +_RULE = "task-argv-secret" + +_MODULE_KEY = re.compile( + r"^(?P\s*(?:-\s+)?)(?:ansible\.builtin\.)?(?:script|command|shell)\s*:" +) +_STDIN_KEY = re.compile(r"^(?P\s*)stdin\s*:") +_EXEC = re.compile( + r"\b(?:container|docker)\b[\s\S]{0,80}?\b(?:exec|run)\b|_EXEC_[A-Z]|_EXEC\b" +) +_FILE_REFERENCE = re.compile( + r"^\s*lookup\(\s*['\"](?:file|path_absolute|template)['\"]" +) +_CREDENTIAL_SUFFIX = re.compile(r"(?i)_(?:pw|pass)\b") +_DESCRIBES_CREDENTIAL = re.compile( + r"(?i)(?:password|passwd|pwd|secret|token|api_?key|private_?key|credential)\w*" + r"_(?:file|path|dir|id|ids|name|names|user|username|owner|email|hash|length" + r"|days|description|url|uri|host|port|type|enabled)\b" +) + + +def _module_blocks(lines: list[str]) -> list[list[int]]: + """Group a task file's lines into the bodies of command-running modules. + + Args: + lines: the task file's lines. + + Returns: + one list of 0-based line indexes per ``script``, ``command`` or + ``shell`` module, its ``stdin:`` value left out. + """ + blocks: list[list[int]] = [] + index = 0 + while index < len(lines): + key = _MODULE_KEY.match(lines[index]) + if not key: + index += 1 + continue + indent = len(key.group("indent")) + block = [index] + stdin_indent: int | None = None + index += 1 + while index < len(lines): + line = lines[index] + if line.strip() and _indent(line) <= indent: + break + if ( + stdin_indent is not None + and line.strip() + and _indent(line) <= stdin_indent + ): + stdin_indent = None + stdin = _STDIN_KEY.match(line) + if stdin: + stdin_indent = len(stdin.group("indent")) + elif stdin_indent is None: + block.append(index) + index += 1 + blocks.append(block) + return blocks + + +def _argv_secret_lines(lines: list[str]) -> list[int]: + """Return the 1-based lines that render a credential into a task's argv. + + Args: + lines: the task file's lines. + + Returns: + every line of a ``script``, ``command`` or ``shell`` module whose Jinja + expression names a credential; modules that run ``container exec`` or + ``docker run`` are left to the exec-argv rules. + """ + found: list[int] = [] + for block in _module_blocks(lines): + if _EXEC.search("\n".join(lines[i] for i in block)): + continue + for i in block: + for expression in _EXPRESSION.findall(lines[i]): + if _FILE_REFERENCE.search(expression): + continue + names_credential = _CREDENTIAL.search( + expression + ) or _CREDENTIAL_SUFFIX.search(expression) + if names_credential and not _DESCRIBES_CREDENTIAL.search(expression): + found.append(i + 1) + break + return found + + +class TestArgvSecretLines(unittest.TestCase): + def test_a_positional_script_argument_is_flagged(self) -> None: + lines = [ + "- ansible.builtin.script: >-", + " set_pw.sh {{ ADDRESS | quote }}", + " {{ POSTGRES_PASSWORD | quote }}", + ] + self.assertEqual(_argv_secret_lines(lines), [3]) + + def test_a_pw_or_pass_suffix_is_flagged(self) -> None: + lines = [ + " command: >", + " ldapsm -W '{{ OPENLDAP_BIND_PW }}'", + " --admin {{ KEYCLOAK_ADMIN_PASS }}", + ] + self.assertEqual(_argv_secret_lines(lines), [2, 3]) + + def test_stdin_environment_and_exec_lines_pass(self) -> None: + lines = [ + "- ansible.builtin.command:", + " argv: [cli, login]", + " stdin: '{{ ADMIN_PASSWORD }}'", + " environment:", + " TOKEN: '{{ API_TOKEN }}'", + "- ansible.builtin.shell: >-", + " container exec app cli --pass {{ ADMIN_PASSWORD }}", + "- ansible.builtin.command: cli --lifetime {{ MCP_TOKEN_LIFETIME_DAYS }}", + ] + self.assertEqual(_argv_secret_lines(lines), []) + + +class TestTaskArgvNoSecret(unittest.TestCase): + def test_task_argv_renders_no_credential(self) -> None: + findings: list[str] = [] + for path_str, content in iter_project_files_with_content( + extensions=(".yml", ".yaml"), + exclude_tests=True, + ): + rel = Path(path_str).relative_to(PROJECT_ROOT).as_posix() + if not rel.startswith("roles/") or not ( + "/tasks/" in rel or "/handlers/" in rel + ): + continue + lines = content.splitlines() + findings.extend( + f"- {rel}:{line_no}: {lines[line_no - 1].strip()}" + for line_no in _argv_secret_lines(lines) + if not is_suppressed_at(lines, line_no, _RULE, mode="same-or-above") + ) + + self.assertFalse( + findings, + "A credential is rendered into the command line of a script, command " + "or shell task, where the host's `ps` shows it to every local account " + "while the call runs and `no_log` cannot mask it. Pass it on the " + "module's `stdin:` and read it there; a task-level `environment:` " + "does not help, Ansible prefixes it to its own `/bin/sh -c` command " + "line. Mark a deliberate exception with " + f"`# nocheck: {_RULE}`.\n\nOffenders:\n" + "\n".join(findings), + ) + + +if __name__ == "__main__": + unittest.main()