From fa39151f1f16f015d476e223a82d1092bb13275f Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Sat, 7 Nov 2026 15:29:52 +0000 Subject: [PATCH] fix(svc-db-redis): keep the replaced password valid until the server pass redeployed its consumers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every shared Redis consumer authenticates as the default user with REDIS_PASSWORD (plugins/lookup/engine.py). The rotation gate between PASS 1 and PASS 2 changes that password, the engine restarts with only the new one, and every consumer deployed later in the pass keeps the old secret. In fork run 42305502796, Nextcloud#7 direct then crash-looped Nextcloud and Weblate from 02:50:31 until the deploy cap killed the job (about 2600-2700 WRONGPASS lines per node, host CPU pressure from 25 % to 80 %). 00_core now reads the password hashes a healthy engine accepts before the restart and adds the replaced ones back after it. Once every server role has redeployed, tasks/stages/02_server.yml retires them before the end-to-end tests: only the current password is left, the ACL log is reset and every client is disconnected. After the tests, a verify step in the test runtimes fails the pass on every authentication Redis refused since the retire, so a consumer that never picked up the new secret still fails loudly. The rotation gate is unchanged. The README no longer describes per-consumer ACL users that never existed. ๐ŸŽฏ Fix: 88 % ๐Ÿ’ฅ Break: 6 % ๐Ÿ’ธ Cost: โ€“ โฑ๏ธ Time: โ€“ ๐Ÿ›ก๏ธ Security: 100 % ๐Ÿ† Score: 83 ๐Ÿšฆ Gate: โ›” fix 88 % < 90, break 6 % > 5 Co-Authored-By: Claude Opus 5.5 --- roles/svc-db-redis/Administration.md | 15 +- roles/svc-db-redis/README.md | 12 +- roles/svc-db-redis/tasks/00_core.yml | 49 ++++++ .../tasks/utils/rotation/retire.yml | 32 ++++ .../tasks/utils/rotation/verify.yml | 23 +++ tasks/stages/02_server.yml | 23 +++ .../test_redis_password_retire_placement.py | 140 ++++++++++++++++++ .../python/roles/svc-db-redis/__init__.py | 0 .../roles/svc-db-redis/test_carry_command.py | 48 ++++++ .../roles/svc-db-redis/test_retired_hashes.py | 76 ++++++++++ 10 files changed, 411 insertions(+), 7 deletions(-) create mode 100644 roles/svc-db-redis/tasks/utils/rotation/retire.yml create mode 100644 roles/svc-db-redis/tasks/utils/rotation/verify.yml create mode 100644 tests/lint/repository/structure/test_redis_password_retire_placement.py create mode 100644 tests/unit/python/roles/svc-db-redis/__init__.py create mode 100644 tests/unit/python/roles/svc-db-redis/test_carry_command.py create mode 100644 tests/unit/python/roles/svc-db-redis/test_retired_hashes.py diff --git a/roles/svc-db-redis/Administration.md b/roles/svc-db-redis/Administration.md index cfdf2b6178..84836089bf 100644 --- a/roles/svc-db-redis/Administration.md +++ b/roles/svc-db-redis/Administration.md @@ -9,10 +9,19 @@ To administer the central Redis instance via the `default` user, execute the fol docker exec -it redis sh -c 'REDISCLI_AUTH="$REDIS_PASSWORD" exec redis-cli' ``` -## Inspect a consumer ACL user +## Inspect the accepted passwords ```bash -docker exec -it redis sh -c 'REDISCLI_AUTH="$REDIS_PASSWORD" exec redis-cli ACL GETUSER ' +docker exec -it redis sh -c 'REDISCLI_AUTH="$REDIS_PASSWORD" exec redis-cli ACL LIST' ``` -A consumer user named `` is restricted to keys matching `:*`. +Every shared consumer authenticates as `default`, so this is the only user. Its rule line carries one `#` per accepted password: more than one means a deploy rotated `REDIS_PASSWORD` and has not retired the replaced password yet. + +## Retire a replaced password by hand + +```bash +docker exec -it redis sh -c 'printf "%s" ">$REDIS_PASSWORD" | REDISCLI_AUTH="$REDIS_PASSWORD" redis-cli -x ACL SETUSER default resetpass' +docker exec -it redis sh -c 'REDISCLI_AUTH="$REDIS_PASSWORD" exec redis-cli CLIENT KILL USER default' +``` + +The first command leaves only the current password; the second makes every open connection authenticate again, since removing a password does not close the connections it opened. diff --git a/roles/svc-db-redis/README.md b/roles/svc-db-redis/README.md index 3785caf538..012bb1e546 100644 --- a/roles/svc-db-redis/README.md +++ b/roles/svc-db-redis/README.md @@ -4,7 +4,7 @@ This Ansible role provides Redis in two interchangeable shapes, selected per consumer with the `shared` flag (mirroring `svc-db-postgres`): -- **Central** (`enabled: true`, `shared: true`): a standalone, manager-pinned Redis stack that many roles share. Each consumer gets its own ACL user restricted to the key-prefix `{entity}:*`. +- **Central** (`enabled: true`, `shared: true`): a standalone, manager-pinned Redis stack that many roles share. Every consumer authenticates as the `default` user and keeps its keys under its own prefix `{entity}:`. - **Embedded** (`enabled: true`, `shared: false`): a Redis sidecar rendered into the consumer's own compose stack via `templates/service.yml.j2`. ## Overview @@ -16,15 +16,19 @@ The central stack (`templates/compose.yml.j2`) runs `redis:alpine` with: - A `maxmemory` ceiling derived from the service `mem_limit` with an `allkeys-lru` policy. - A bind on `127.0.0.1:6379` plus the shared cross-stack overlay network for consumers. -Per-consumer provisioning (`tasks/01_init.yml`) runs with `application_id=svc-db-redis` and `database_consumer_id=`; it resolves the consumer's username, password and key-prefix via `lookup('engine', 'redis', , ...)` and reconciles an idempotent `ACL SETUSER` restricted to `~{entity}:*`. The ACL users are recreated by the consumer's `01_init` on every deploy, so a container restart that drops the in-memory ACL set is healed on the next run. +A shared consumer resolves its connection via `lookup('engine', 'redis', , ...)`, which hands every consumer the `default` user, the `REDIS_PASSWORD` credential and the key prefix `{entity}`. There are no per-consumer ACL users: `sys-svc-engine` provisions no Redis consumer, so `tasks/01_init.yml` runs on no deploy path. + +A changed `REDIS_PASSWORD` restarts the engine, and the restart drops every password but the new one while the consumers deployed later in the same pass still hold the old one. `tasks/00_core.yml` therefore reads the password hashes a healthy engine accepts before the restart and adds the replaced ones back after it. Once every server role has redeployed, `tasks/stages/02_server.yml` runs `tasks/utils/rotation/retire.yml` before the end-to-end tests: it leaves only the current password, empties the `ACL LOG` and disconnects every client. After the tests, `tasks/utils/rotation/verify.yml` fails the pass on every authentication Redis refused since then, so a consumer that never picked up the new secret fails loudly even when no test exercises it. The check runs only in the test runtimes, like the end-to-end tests. + +The replaced password stays valid for the rest of the server pass. A pass that aborts before the retire, or a deploy that leaves this role out, keeps it valid until a later deploy of this role reaches the retire step: every deploy carries it again, also across its own restart. When a rotation answers a leaked password, retire it by hand as described in `Administration.md`. The embedded snippet (`templates/service.yml.j2`) keeps the previous single-host behaviour: an unauthenticated in-memory Redis attached to the consumer stack's default network. Its `maxmemory` is 80 % of the consumer's `services.redis.mem_limit`; a consumer that declares none gets 80 % of the limit its container inherits, at most 80 % of this role's own `mem_limit`. ## Features - **Central or embedded** selected per consumer via `services.redis.shared`. -- **ACL isolation** one Redis user per consumer, scoped to `{entity}:*` keys. -- **Idempotent provisioning** ACL users reconciled on every deploy via `ACL SETUSER`. +- **Key prefixes** one prefix per consumer, `{entity}:`, on the shared `default` user. +- **Rotation without a crash loop** the replaced password stays accepted until every server role has redeployed. - **Manager-pinned** central on-disk state stays node-local (never on NFS) in swarm. - **Built-in healthcheck** authenticated `redis-cli ping`. diff --git a/roles/svc-db-redis/tasks/00_core.yml b/roles/svc-db-redis/tasks/00_core.yml index ad7e91b86f..89f5b2e62b 100644 --- a/roles/svc-db-redis/tasks/00_core.yml +++ b/roles/svc-db-redis/tasks/00_core.yml @@ -1,6 +1,28 @@ --- - include_tasks: utils/once/flag.yml +# Exception: a first deploy has no container and a crash-looping one is no healthy engine; both mean nothing to carry, and the routine below still has to run to heal them. +- name: "๐Ÿ“– REDIS | Read whether an earlier deploy left a healthy engine" + ansible.builtin.shell: > + container inspect --type container --format '{{ "{{.State.Status}} {{.State.Health.Status}}" }}' {{ REDIS_CONTAINER_ADDRESS }} + register: redis_health_before + delegate_to: "{{ STACK_HOST }}" + run_once: true + changed_when: false + failed_when: false + +- name: "๐Ÿ“– REDIS | Read the passwords the healthy engine accepts" + ansible.builtin.shell: > + {{ REDIS_EXEC_SHELL }} + '{{ REDIS_CLI }} ACL LIST' + register: redis_acl_before_restart + delegate_to: "{{ STACK_HOST }}" + run_once: true + changed_when: false + failed_when: redis_acl_before_restart.rc != 0 or redis_acl_before_restart.stdout_lines | select('match', '^user default ') | list | length != 1 + when: redis_health_before.stdout | trim == 'running healthy' + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + - name: "๐Ÿ”ง Setup container network for {{ application_id }}" include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/network/routine.yml') }}" vars: @@ -33,3 +55,30 @@ until: redis_ping_ready.stdout is search('PONG') changed_when: false no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐Ÿงฎ REDIS | Pick the passwords a rotated REDIS_PASSWORD replaced" + ansible.builtin.set_fact: + redis_retired_password_hashes: >- + {{ + (redis_acl_before_restart.stdout_lines if redis_acl_before_restart.stdout_lines is defined else []) + | select('match', '^user default ') + | join(' ') + | regex_findall('(?:^|\s)#([0-9a-f]{64})(?=\s|$)') + | difference([REDIS_PASSWORD | hash('sha256')]) + | sort + }} + changed_when: false + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +# Exception: the restart dropped every password but the new one, while the shared consumers deployed later in this pass still hold the old one. tasks/utils/rotation/retire.yml drops them once every server role has redeployed. +- name: "๐Ÿ” REDIS | Keep accepting the replaced passwords until the roles redeployed" + ansible.builtin.shell: > + {{ REDIS_EXEC_SHELL }} + '{{ REDIS_CLI }} ACL SETUSER default{% for retired_hash in redis_retired_password_hashes %} "#{{ retired_hash }}"{% endfor %}' + register: redis_acl_carried + delegate_to: "{{ STACK_HOST }}" + run_once: true + changed_when: true + failed_when: redis_acl_carried.rc != 0 or redis_acl_carried.stdout | trim != 'OK' + when: redis_retired_password_hashes | length > 0 + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" diff --git a/roles/svc-db-redis/tasks/utils/rotation/retire.yml b/roles/svc-db-redis/tasks/utils/rotation/retire.yml new file mode 100644 index 0000000000..1bed04bdd7 --- /dev/null +++ b/roles/svc-db-redis/tasks/utils/rotation/retire.yml @@ -0,0 +1,32 @@ +--- +- name: "๐Ÿ”‘ REDIS | Retire the passwords the rotated REDIS_PASSWORD replaced" + ansible.builtin.shell: > + {{ REDIS_EXEC_SHELL }} + 'printf "%s" ">$REDIS_PASSWORD" | {{ REDIS_CLI }} -x ACL SETUSER default resetpass' + register: redis_acl_retired + delegate_to: "{{ STACK_HOST }}" + run_once: true + changed_when: true + failed_when: redis_acl_retired.rc != 0 or redis_acl_retired.stdout | trim != 'OK' + no_log: "{{ MASK_CREDENTIALS_IN_LOGS | bool }}" + +- name: "๐Ÿงน REDIS | Start the refused-authentication log at the retire" + ansible.builtin.shell: > + {{ REDIS_EXEC_SHELL }} + '{{ REDIS_CLI }} ACL LOG RESET' + register: redis_acl_log_reset + delegate_to: "{{ STACK_HOST }}" + run_once: true + changed_when: false + failed_when: redis_acl_log_reset.rc != 0 or redis_acl_log_reset.stdout | trim != 'OK' + +# Exception: removing a password leaves the connections it authenticated open, so a consumer still on the old secret would pass every later check without authenticating again. +- name: "๐Ÿ”Œ REDIS | Make every client authenticate again with the current password" + ansible.builtin.shell: > + {{ REDIS_EXEC_SHELL }} + '{{ REDIS_CLI }} CLIENT KILL USER default' + register: redis_clients_killed + delegate_to: "{{ STACK_HOST }}" + run_once: true + changed_when: redis_clients_killed.stdout | trim != '0' + failed_when: redis_clients_killed.rc != 0 or redis_clients_killed.stdout | trim is not match('^[0-9]+$') diff --git a/roles/svc-db-redis/tasks/utils/rotation/verify.yml b/roles/svc-db-redis/tasks/utils/rotation/verify.yml new file mode 100644 index 0000000000..4581a4fe90 --- /dev/null +++ b/roles/svc-db-redis/tasks/utils/rotation/verify.yml @@ -0,0 +1,23 @@ +--- +- name: "๐Ÿ“– REDIS | Read the authentications the engine refused since the retire" + ansible.builtin.shell: > + {{ REDIS_EXEC_SHELL }} + '{{ REDIS_CLI }} ACL LOG' + register: redis_acl_log + delegate_to: "{{ STACK_HOST }}" + run_once: true + changed_when: false + failed_when: >- + redis_acl_log.rc != 0 or + (redis_acl_log.stdout_lines | length > 0 and redis_acl_log.stdout_lines[0] != 'count') + +- name: "โœ… REDIS | Assert no consumer still presents a retired password" + ansible.builtin.assert: + that: + - redis_acl_log.stdout_lines | select('match', '^id=') | list | length == 0 + fail_msg: >- + Redis refused authentications after the rotated REDIS_PASSWORD was retired: + a consumer still holds the old secret. Redis groups repeated refusals, so + only the latest client of each group is named: + {{ redis_acl_log.stdout_lines | select('match', '^id=') | map('regex_search', 'addr=\S+') | list | unique | join(', ') }} + run_once: true diff --git a/tasks/stages/02_server.yml b/tasks/stages/02_server.yml index 8181a4d4bf..69a853d7cb 100644 --- a/tasks/stages/02_server.yml +++ b/tasks/stages/02_server.yml @@ -33,6 +33,17 @@ loop_var: role_group label: "{{ role_group }}" +- name: "๐Ÿ”‘ Retire the Redis passwords a rotation replaced, once consumers redeployed" + ansible.builtin.include_role: + name: svc-db-redis + tasks_from: utils/rotation/retire.yml + vars: + application_id: svc-db-redis + when: + - "'svc-db-redis' in group_names" + - redis_retired_password_hashes is defined + - redis_retired_password_hashes | length > 0 + - name: "๐Ÿ” Probe the vhosts the server roles queued, in one parallel batch" ansible.builtin.include_role: name: sys-stk-front-proxy @@ -52,3 +63,15 @@ include_role: name: "test-e2e-playwright" when: RUNTIME in ['dev', 'act', 'github'] + +- name: "โœ… Fail on every Redis consumer that still presents a retired password" + ansible.builtin.include_role: + name: svc-db-redis + tasks_from: utils/rotation/verify.yml + vars: + application_id: svc-db-redis + when: + - "'svc-db-redis' in group_names" + - RUNTIME in ['dev', 'act', 'github'] + - redis_retired_password_hashes is defined + - redis_retired_password_hashes | length > 0 diff --git a/tests/lint/repository/structure/test_redis_password_retire_placement.py b/tests/lint/repository/structure/test_redis_password_retire_placement.py new file mode 100644 index 0000000000..a8a710dc51 --- /dev/null +++ b/tests/lint/repository/structure/test_redis_password_retire_placement.py @@ -0,0 +1,140 @@ +"""A rotated Redis password is carried across the restart and retired before the checks. + +A changed ``REDIS_PASSWORD`` restarts the central engine, while the shared +consumers deployed later in the pass still hold the old password. The engine +therefore keeps accepting the replaced password from its restart until every +server role has redeployed, drops it before the end-to-end tests, and fails the +pass on every client it refuses afterwards. Every edge of that window is silent +when crossed: read after the restart, nothing is left to carry and the +consumers crash-loop again; retired before the app pass ends, the same; retired +after the tests, or in the destructor that ``any_errors_fatal`` skips, a stale +consumer passes; retired without disconnecting the clients, a connection the old +password opened stays usable; verified before the retire, there is nothing to +refuse yet. + +Suppression (see ``docs/contributing/actions/testing/suppression.md``): + +* ``# nocheck: redis-password-retire-placement`` on, or directly above, the + retire include in the server stage. +""" + +from __future__ import annotations + +import unittest + +from utils.annotations.suppress import is_suppressed_at +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +_RULE = "redis-password-retire-placement" +_ROLE_DIR = PROJECT_ROOT / "roles" / "svc-db-redis" / "tasks" +_CORE = _ROLE_DIR / "00_core.yml" +_RETIRE = _ROLE_DIR / "utils" / "rotation" / "retire.yml" +_STAGE = PROJECT_ROOT / "tasks" / "stages" / "02_server.yml" +_DESTRUCTOR = PROJECT_ROOT / "tasks" / "stages" / "03_destructor.yml" +_RETIRE_REF = "utils/rotation/retire.yml" +_VERIFY_REF = "utils/rotation/verify.yml" +_APP_PASS = "tasks/utils/setup/group.yml" +_E2E = "test-e2e-playwright" + + +def _line_of(lines: list[str], needle: str) -> int | None: + return next((i for i, raw in enumerate(lines, 1) if needle in raw), None) + + +class TestRedisPasswordRetirePlacement(unittest.TestCase): + def test_the_accepted_passwords_are_read_before_the_restart(self) -> None: + lines = read_text(str(_CORE)).splitlines() + read = _line_of(lines, "ACL LIST") + restart = _line_of(lines, "network/routine.yml") + self.assertIsNotNone(read, f"{_CORE.name} no longer reads the passwords") + self.assertIsNotNone(restart, f"{_CORE.name} no longer deploys the stack") + self.assertLess( + read, + restart, + "after the restart the engine accepts only the new password, so " + "nothing is left to carry", + ) + + def test_the_replaced_passwords_are_added_back_once_the_engine_answers( + self, + ) -> None: + lines = read_text(str(_CORE)).splitlines() + ping = _line_of(lines, "REDIS_CLI }} ping") + carry = _line_of(lines, "ACL SETUSER default") + self.assertIsNotNone(ping, f"{_CORE.name} no longer waits for the engine") + self.assertIsNotNone(carry, f"{_CORE.name} no longer carries the passwords") + self.assertLess( + ping, + carry, + "the carry has to reach the restarted engine, not the one it replaces", + ) + + def test_the_retire_sits_between_the_app_pass_and_the_tests(self) -> None: + lines = read_text(str(_STAGE)).splitlines() + retire = _line_of(lines, _RETIRE_REF) + self.assertIsNotNone( + retire, + f"{_STAGE.name} never retires a replaced Redis password, so a stale " + "consumer passes every check", + ) + if is_suppressed_at(lines, retire, _RULE): + return + app_pass = _line_of(lines, _APP_PASS) + e2e = _line_of(lines, _E2E) + verify = _line_of(lines, _VERIFY_REF) + self.assertIsNotNone(app_pass, f"{_STAGE.name} no longer includes the app pass") + self.assertIsNotNone(e2e, f"{_STAGE.name} no longer runs {_E2E}") + self.assertIsNotNone( + verify, f"{_STAGE.name} never fails on a client the retire refused" + ) + self.assertLess( + app_pass, + retire, + "retired before the app pass ends, the consumers still on the old " + "password crash-loop until their own redeploy", + ) + self.assertLess( + retire, + e2e, + f"{_E2E} has to meet a stale consumer, so the replaced password must " + "be gone before it runs", + ) + self.assertLess( + e2e, + verify, + "the refused-authentication log is read last, so every client had the " + "whole test run to authenticate again", + ) + + def test_nothing_of_the_rotation_is_deferred_to_the_destructor(self) -> None: + destructor = read_text(str(_DESTRUCTOR)) + for ref in (_RETIRE_REF, _VERIFY_REF): + self.assertNotIn( + ref, + destructor, + "the destructor runs after the end-to-end tests, and " + "any_errors_fatal skips it entirely once one of them is red", + ) + + def test_the_retire_makes_every_client_authenticate_again(self) -> None: + lines = read_text(str(_RETIRE)).splitlines() + reset = _line_of(lines, "resetpass") + log_reset = _line_of(lines, "ACL LOG RESET") + kill = _line_of(lines, "CLIENT KILL USER default") + self.assertIsNotNone(reset, f"{_RETIRE.name} no longer drops the passwords") + self.assertIsNotNone( + kill, "removing a password leaves the connections it opened usable" + ) + self.assertIsNotNone(log_reset, f"{_RETIRE.name} no longer resets the log") + self.assertLess( + log_reset, + kill, + "the log has to be empty before the kill, or it either keeps the " + "refusals from before the carry or misses the stale reconnects", + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-db-redis/__init__.py b/tests/unit/python/roles/svc-db-redis/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/roles/svc-db-redis/test_carry_command.py b/tests/unit/python/roles/svc-db-redis/test_carry_command.py new file mode 100644 index 0000000000..153faed39a --- /dev/null +++ b/tests/unit/python/roles/svc-db-redis/test_carry_command.py @@ -0,0 +1,48 @@ +import shlex +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar, trust_as_template + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any + +_CORE = PROJECT_ROOT / "roles" / "svc-db-redis" / "tasks" / "00_core.yml" +_CARRY = "Keep accepting the replaced passwords" +_HASHES = ["a" * 64, "b" * 64] + + +def _carry_command() -> str: + tasks = load_yaml_any(str(_CORE)) + task = next(task for task in tasks if _CARRY in str(task.get("name", ""))) + return task["ansible.builtin.shell"] + + +class TestCarryCommand(unittest.TestCase): + def _inner_words(self, hashes: list[str]) -> list[str]: + variables = { + "REDIS_EXEC_SHELL": "container exec redis sh -lc", + "REDIS_CLI": 'REDISCLI_AUTH="$REDIS_PASSWORD" redis-cli', + "redis_retired_password_hashes": hashes, + } + rendered = Templar(loader=DataLoader(), variables=variables).template( + trust_as_template(_carry_command()) + ) + outer = shlex.split(rendered) + self.assertEqual(outer[:5], ["container", "exec", "redis", "sh", "-lc"]) + self.assertEqual(len(outer), 6, "the in-container script must stay one word") + return shlex.split(outer[5], comments=True) + + def test_every_replaced_hash_reaches_redis_as_its_own_argument(self): + words = self._inner_words(_HASHES) + self.assertEqual( + words[words.index("SETUSER") + 1 :], + ["default", *(f"#{value}" for value in _HASHES)], + ) + + def test_a_single_hash_is_not_read_as_a_shell_comment(self): + self.assertEqual(self._inner_words(_HASHES[:1])[-1], f"#{_HASHES[0]}") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/svc-db-redis/test_retired_hashes.py b/tests/unit/python/roles/svc-db-redis/test_retired_hashes.py new file mode 100644 index 0000000000..af9656dc49 --- /dev/null +++ b/tests/unit/python/roles/svc-db-redis/test_retired_hashes.py @@ -0,0 +1,76 @@ +import hashlib +import unittest + +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar, trust_as_template + +from utils.cache.files import PROJECT_ROOT +from utils.cache.yaml import load_yaml_any + +_CORE = PROJECT_ROOT / "roles" / "svc-db-redis" / "tasks" / "00_core.yml" +_PICK = "Pick the passwords a rotated REDIS_PASSWORD replaced" + + +def _sha(password: str) -> str: + return hashlib.sha256(password.encode()).hexdigest() + + +CURRENT = "example-new" +OLDER = _sha("example-older") +OLD = _sha("example-old") +NEW = _sha(CURRENT) + + +def _default_line(*hashes: str) -> str: + accepted = " ".join(f"#{value}" for value in hashes) + return f"user default on sanitize-payload {accepted} ~* &* +@all" + + +def _expression() -> str: + tasks = load_yaml_any(str(_CORE)) + task = next(task for task in tasks if _PICK in str(task.get("name", ""))) + return task["ansible.builtin.set_fact"]["redis_retired_password_hashes"] + + +class TestRetiredHashes(unittest.TestCase): + def _retired(self, acl_list): + read = {"skipped": True} if acl_list is None else {"stdout_lines": acl_list} + variables = {"redis_acl_before_restart": read, "REDIS_PASSWORD": CURRENT} + return list( + Templar(loader=DataLoader(), variables=variables).template( + trust_as_template(_expression()) + ) + ) + + def test_an_unchanged_password_retires_nothing(self): + self.assertEqual(self._retired([_default_line(NEW)]), []) + + def test_a_rotated_password_retires_the_one_the_engine_accepted(self): + self.assertEqual(self._retired([_default_line(OLD)]), [OLD]) + + def test_passwords_an_aborted_pass_left_behind_are_retired_too(self): + self.assertEqual( + self._retired([_default_line(OLD, OLDER)]), sorted([OLD, OLDER]) + ) + + def test_the_current_password_is_kept_when_the_engine_already_accepts_it(self): + self.assertEqual(self._retired([_default_line(NEW, OLD)]), [OLD]) + + def test_an_engine_that_was_not_read_retires_nothing(self): + self.assertEqual(self._retired(None), []) + + def test_only_the_default_user_is_read(self): + lines = [ + f"user cloud on #{OLD} ~cloud:* &* +@all", + f"user default2 on #{OLDER} ~* &* +@all", + _default_line(NEW), + ] + self.assertEqual(self._retired(lines), []) + + def test_tokens_that_are_no_password_hash_are_ignored(self): + line = f"user default on #{OLD[:-1]} %R~#{OLDER} #{NEW} ~* &* +@all" + self.assertEqual(self._retired([line]), []) + + +if __name__ == "__main__": + unittest.main()