From 4b36259d119f47c4d51e472e0bc7c3351a908b6c Mon Sep 17 00:00:00 2001 From: "shipmill-romamo[bot]" <338557544+shipmill-romamo[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:05:12 +0200 Subject: [PATCH 1/2] Keep Kibana's dashboards through a snapshot restore and a rebuild (S-024-10, S-024-11) S-012's snapshots already hold every feature state; with a Kibana service reading the cluster, the backup script now also checks that the snapshot it took lists the feature state kibana and fails the run when it does not, so a backup that would not bring the dashboards back is never reported as one that does. The snapshot request is unchanged, and the script of a cluster without Kibana renders byte-identical. The new Kibana service guide gives the restore (stop Kibana, restore the feature state kibana alone, start Kibana) and what a rebuilt Kibana server gets: the store's three encryption keys, never new ones, and a new token in the rebuilt node's own service_tokens file. Tests prove both on stand-ins. Fixes #580 Co-Authored-By: Claude Opus 5.5 --- changelog.d/580-kibana-dashboards-survive.md | 3 + docs/kibana-service-guide.md | 113 +++++++ engine/ansible/playbooks/services.yml | 14 + .../cloudfall_elasticsearch/defaults/main.yml | 5 + .../meta/argument_specs.yml | 6 + .../templates/snapshots.py.j2 | 19 ++ .../test_s012_elasticsearch_snapshots.py | 13 + .../test_s024_10_11_kibana_dashboards.py | 277 ++++++++++++++++++ sdk/tests/test_s024_11_kibana_rebuild_keys.py | 84 ++++++ 9 files changed, 534 insertions(+) create mode 100644 changelog.d/580-kibana-dashboards-survive.md create mode 100644 docs/kibana-service-guide.md create mode 100644 engine/tests/test_s024_10_11_kibana_dashboards.py create mode 100644 sdk/tests/test_s024_11_kibana_rebuild_keys.py diff --git a/changelog.d/580-kibana-dashboards-survive.md b/changelog.d/580-kibana-dashboards-survive.md new file mode 100644 index 00000000..84c77457 --- /dev/null +++ b/changelog.d/580-kibana-dashboards-survive.md @@ -0,0 +1,3 @@ +### Added + +- Kibana's dashboards survive a snapshot restore and a rebuilt server (S-024-10, S-024-11): when a Kibana service reads an Elasticsearch service, `cloudfall-elasticsearch-backup` checks that the snapshot it took lists the feature state `kibana`, where Kibana keeps its saved objects, and fails the run when it does not; the snapshot request is unchanged, and a cluster without Kibana renders and runs its backup script as before. The new `docs/kibana-service-guide.md` gives the restore (stop Kibana, restore the feature state `kibana` alone from a snapshot, start Kibana) and what a rebuilt Kibana server gets: the same three encryption keys from the project's store, so encrypted saved objects still decrypt, and a new service token in the rebuilt node's own `service_tokens` file (#580) diff --git a/docs/kibana-service-guide.md b/docs/kibana-service-guide.md new file mode 100644 index 00000000..c74585cb --- /dev/null +++ b/docs/kibana-service-guide.md @@ -0,0 +1,113 @@ +# Run a Kibana service + +Status: this guide covers where Kibana's dashboards are backed up, how to +restore them, and what a rebuilt Kibana server gets. The backup check and the +keys of a rebuilt server are proven against stand-ins of Elasticsearch and of +Kibana's keystore, not yet on a live Debian 13 host. The other sections the +spec names (declaring Kibana, its users, publishing it with a Domain, an SSH +forward, a version change and licences) come with later releases. + +A Kibana `Service` runs on a node of the Elasticsearch service it reads and +holds no data of its own: dashboards, data views, saved searches and every +other saved object are documents in the cluster's system indices. The +behaviour is specified in [spec 024](specs/024-kibana-service.md). + +## Where the dashboards are backed up + +Elasticsearch groups Kibana's system indices as the feature state `kibana`. +The snapshots of the Elasticsearch service hold the cluster state and every +feature state, so the backup of the cluster is also the backup of the +dashboards. The Kibana service has no `backup`, timer or receipt of its own: + +```console +uv run cloudfall backup run search-main +``` + +When a Kibana service reads the cluster, `cloudfall-elasticsearch-backup` +also checks that the snapshot it took lists the feature state `kibana`, and +fails the run when it does not: Kibana then never started against the +cluster, or its system indices are gone. The snapshot itself is unchanged: it +asks for the cluster state and every feature state, as for a cluster without +Kibana. The restore drill of the Elasticsearch service restores renamed +copies of data indices only and never touches a feature state. + +To see the feature states a snapshot holds, ask the node (on the Kibana +server, which is a node of its cluster): + +```console +curl --user cloudfall http://127.0.0.1:9200/_snapshot/cloudfall/cloudfall-20261124-032000 +``` + +`curl` asks for the password of Cloudfall's account, which is in +`/etc/elasticsearch/cloudfall-password` on the node (`sudo cat` it). Each +snapshot lists `feature_states`, one of them `"feature_name": "kibana"`. With +`remoteAccess`, use `https://:9200` and +`--cacert /etc/elasticsearch/certs/ca.crt` instead. + +## Restore the dashboards + +The restore is three steps on the Kibana server: stop Kibana, restore the +feature state `kibana` from a snapshot, start Kibana. It brings back every +saved object as the snapshot holds it, and drops those made since. Nothing +else in the cluster changes: no data index and no other feature state is +restored. + +1. Stop Kibana, so it writes nothing while its indices are replaced: + + ```console + sudo systemctl stop kibana.service + ``` + +2. Restore the feature state `kibana` alone. `"indices": "-*"` restores no + data index, and `include_global_state: false` leaves the cluster's + settings, templates and other feature states as they are. Elasticsearch + deletes Kibana's current system indices and restores the snapshot's: + + ```console + curl --user cloudfall -X POST \ + -H 'Content-Type: application/json' \ + 'http://127.0.0.1:9200/_snapshot/cloudfall/cloudfall-20261124-032000/_restore?wait_for_completion=true' \ + -d '{"indices": "-*", "include_global_state": false, "feature_states": ["kibana"]}' + ``` + + The answer lists the restored shards under `snapshot.shards`; `failed` + must be `0` + +3. Start Kibana again: + + ```console + sudo systemctl start kibana.service + ``` + + Kibana reports itself available once it has read the restored indices. + A services converge also starts it and waits for that + +Encrypted saved objects, such as an alert connector's credentials, open +again because Kibana still has the three encryption keys they were encrypted +with: the keys are in the project's secret store, not only on the server. + +## A rebuilt Kibana server + +Kibana encrypts sessions, saved objects and reports with three keys, +`xpack.security.encryptionKey`, `xpack.encryptedSavedObjects.encryptionKey` +and `xpack.reporting.encryptionKey`. `cloudfall secrets generate` makes each +once and stores it sops-encrypted in `secrets//services/.env`; it never overwrites a stored key. Every services converge puts +the stored keys in Kibana's keystore and never makes new ones on the server. + +So when the Kibana server is rebuilt empty, converging its baseline and its +services brings Kibana back as it was: + +- the node of the Elasticsearch service is converged first and rejoins its + cluster, whose other nodes still hold Kibana's saved objects. A cluster of + one lost them with the server: restore the feature state `kibana` from a + snapshot in the cluster's repository as above, with Kibana stopped +- Kibana gets the same three keys from the store, so the saved objects + encrypted before the rebuild still decrypt, and the dashboards open for the + same users with the same passwords +- Kibana gets a new token of the `elastic/kibana` service account, created + in the `service_tokens` file of the rebuilt node. The old token lived only + in the old node's file, so it went with the old server and is valid nowhere + +Keep the secrets repository: a key lost from the store can't be recovered, +and Kibana can no longer read what was encrypted with it. diff --git a/engine/ansible/playbooks/services.yml b/engine/ansible/playbooks/services.yml index 5f01cbc9..d8c3a0ba 100644 --- a/engine/ansible/playbooks/services.yml +++ b/engine/ansible/playbooks/services.yml @@ -254,6 +254,20 @@ | flatten(levels=1) | items2dict(key_name='name', value_name='access') }} + # The ids of the Kibana services that read the cluster (S-024-10): + # each snapshot must then hold the feature state kibana, Kibana's + # saved objects. Read from every server's services, as above. + cloudfall_elasticsearch_kibana_services: >- + {{ + groups['cloudfall_servers'] | default([]) + | map('extract', hostvars) + | map(attribute='cloudfall_services', default=[]) + | flatten(levels=1) + | selectattr('serviceKind', 'equalto', 'kibana') + | selectattr('kibana.elasticsearch', 'equalto', cloudfall_service_item.id) + | map(attribute='id') + | unique | list + }} loop: >- {{ cloudfall_services | default([]) diff --git a/engine/ansible/roles/cloudfall_elasticsearch/defaults/main.yml b/engine/ansible/roles/cloudfall_elasticsearch/defaults/main.yml index 945a9fc4..0498cb4f 100644 --- a/engine/ansible/roles/cloudfall_elasticsearch/defaults/main.yml +++ b/engine/ansible/roles/cloudfall_elasticsearch/defaults/main.yml @@ -7,6 +7,11 @@ cloudfall_elasticsearch_account_files: {} # kibana.users, by user name, as services.yml finds it (S-024); a user not # named here holds its own role alone. cloudfall_elasticsearch_kibana_access: {} +# The ids of the Kibana services that read the cluster, as services.yml finds +# them (S-024-10): each snapshot must then hold the feature state kibana. +cloudfall_elasticsearch_kibana_services: [] +# The feature state Elasticsearch groups Kibana's system indices under. +cloudfall_elasticsearch_kibana_feature_state: kibana cloudfall_elasticsearch_repository_key_url: https://artifacts.elastic.co/GPG-KEY-elasticsearch cloudfall_elasticsearch_repository_key_path: /etc/apt/keyrings/elasticsearch.asc cloudfall_elasticsearch_repository_url: https://artifacts.elastic.co/packages diff --git a/engine/ansible/roles/cloudfall_elasticsearch/meta/argument_specs.yml b/engine/ansible/roles/cloudfall_elasticsearch/meta/argument_specs.yml index 9334730a..e8f054a0 100644 --- a/engine/ansible/roles/cloudfall_elasticsearch/meta/argument_specs.yml +++ b/engine/ansible/roles/cloudfall_elasticsearch/meta/argument_specs.yml @@ -18,6 +18,12 @@ argument_specs: The access, view or edit, of each user the service's Kibana names in kibana.users, by user name (S-024); the user converge gives that user the role cloudfall-kibana-view or cloudfall-kibana-edit next to its own + cloudfall_elasticsearch_kibana_services: + type: list + elements: str + description: >- + The ids of the Kibana services that read the cluster (S-024-10); with + one, a snapshot that holds no feature state kibana fails the backup cloudfall_elasticsearch_service: type: dict required: true diff --git a/engine/ansible/roles/cloudfall_elasticsearch/templates/snapshots.py.j2 b/engine/ansible/roles/cloudfall_elasticsearch/templates/snapshots.py.j2 index 159ba69d..08c2aba5 100644 --- a/engine/ansible/roles/cloudfall_elasticsearch/templates/snapshots.py.j2 +++ b/engine/ansible/roles/cloudfall_elasticsearch/templates/snapshots.py.j2 @@ -46,6 +46,10 @@ RETENTION_DAYS = {{ cloudfall_elasticsearch_service.backup.retentionDays | int } RESTORE_CHECK_INDICES = {{ cloudfall_elasticsearch_service.elasticsearch.restoreCheckIndices | default([]) | to_json }} POLL_SECONDS = {{ cloudfall_elasticsearch_snapshot_poll_seconds | int }} WAIT_SECONDS = {{ cloudfall_elasticsearch_snapshot_wait_seconds | int }} +{% if cloudfall_elasticsearch_kibana_services | length > 0 %} +KIBANA_SERVICES = {{ cloudfall_elasticsearch_kibana_services | join(', ') | to_json }} +KIBANA_FEATURE_STATE = {{ cloudfall_elasticsearch_kibana_feature_state | to_json }} +{% endif %} SNAPSHOT_NAME = re.compile(r"cloudfall-[0-9]{8}-[0-9]{6}") RESTORE_PREFIX = "cloudfall-restore-check-" @@ -270,6 +274,21 @@ def backup(): ) if COUNTS_INDEX not in snapshot["indices"]: raise Failure(f"snapshot {name} does not hold {COUNTS_INDEX}") +{% if cloudfall_elasticsearch_kibana_services | length > 0 %} + # Kibana service {{ cloudfall_elasticsearch_kibana_services | join(', ') }} keeps its + # dashboards and other saved objects in the feature state kibana, which a + # snapshot of the cluster state holds (S-024-10). + features = [ + state.get("feature_name") for state in snapshot.get("feature_states", []) + ] + if KIBANA_FEATURE_STATE not in features: + raise Failure( + f"snapshot {name} of {SERVICE} holds no feature state " + f"{KIBANA_FEATURE_STATE}, where Kibana service {KIBANA_SERVICES} keeps " + "its saved objects; check that Kibana runs and has started once" + ) + print(f"snapshot {name} holds the feature state {KIBANA_FEATURE_STATE}") +{% endif %} print( f"snapshot {name} of {SERVICE}: SUCCESS, {len(snapshot['indices'])} " f"indices, {shards.get('successful', 0)} of {shards.get('total', 0)} shards" diff --git a/engine/tests/test_s012_elasticsearch_snapshots.py b/engine/tests/test_s012_elasticsearch_snapshots.py index 6064a7b7..154fdc22 100644 --- a/engine/tests/test_s012_elasticsearch_snapshots.py +++ b/engine/tests/test_s012_elasticsearch_snapshots.py @@ -93,6 +93,9 @@ class FakeElasticsearch: calls: list[tuple[str, str, object]] = field(default_factory=list) authorizations: set[str] = field(default_factory=set) created: list[tuple[str, object]] = field(default_factory=list) + # The feature states a new snapshot of the cluster state holds, as a node + # lists them; none unless a test gives them (S-024-10). + feature_states: list[str] = field(default_factory=list) def snapshot( self, @@ -273,6 +276,16 @@ def _snapshot_route( # noqa: C901, PLR0911, PLR0912 - the snapshot API of the f "documents": copy.deepcopy(fake.documents), "polls_left": fake.polls, "shards": {"total": 4, "failed": 0, "successful": 4}, + **( + { + "feature_states": [ + {"feature_name": name, "indices": [f".{name}_1"]} + for name in fake.feature_states + ] + } + if fake.feature_states + else {} + ), } ) return {"accepted": True} diff --git a/engine/tests/test_s024_10_11_kibana_dashboards.py b/engine/tests/test_s024_10_11_kibana_dashboards.py new file mode 100644 index 00000000..41514b5d --- /dev/null +++ b/engine/tests/test_s024_10_11_kibana_dashboards.py @@ -0,0 +1,277 @@ +"""Kibana's dashboards survive a snapshot restore and a rebuilt server (S-024, #580). + +S-024-10: the snapshot script of the Elasticsearch role, rendered with +Ansible's own templating, runs for real against the fake node of +``test_s012_elasticsearch_snapshots``; the guide's restore steps are read from +``docs/kibana-service-guide.md``. S-024-11: the Kibana role's keystore tasks run +for real twice, on a converged host and on a rebuilt empty one, against the +stand-ins of ``kibana_node``. Restoring the feature state on a live cluster, +Kibana starting on it, and ``analyst`` opening the dashboard need a live host +and are listed in the pull request as unverified. +""" + +from __future__ import annotations + +import json +import re +import subprocess +import sys +from pathlib import Path +from typing import cast + +import pytest +import yaml +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar, trust_as_template +from test_s012_elasticsearch_snapshots import ( + PASSWORD, + FakeElasticsearch, + _render, + _service, + _variables, +) +from test_s012_elasticsearch_snapshots import ( + fake as fake, # noqa: PLC0414 - the fixture, used by name +) +from test_s024_kibana_role import KEYS, SETTINGS, TOKEN_SETTING, Node, requires_ansible + +ROOT = Path(__file__).parents[2] +SERVICES = ROOT / "engine" / "ansible" / "playbooks" / "services.yml" +GUIDE = ROOT / "docs" / "kibana-service-guide.md" + + +def _script(tmp_path: Path, port: int, kibana: list[str]) -> Path: + """Render the backup script as the converge does with ``kibana`` reading it.""" + password = tmp_path / "cloudfall-password" + password.write_text(PASSWORD + "\n", encoding="utf-8") + rendered = _render( + "snapshots.py.j2", + _variables( + _service(port), + cloudfall_elasticsearch_snapshot_action="backup", + cloudfall_elasticsearch_password_path=str(password), + cloudfall_elasticsearch_kibana_services=kibana, + ), + ) + script = tmp_path / "cloudfall-elasticsearch-backup" + script.write_text( + rendered.replace("#!/usr/bin/python3", f"#!{sys.executable}", 1), + encoding="utf-8", + ) + return script + + +def _backup( + tmp_path: Path, port: int, kibana: list[str] +) -> subprocess.CompletedProcess[str]: + done = subprocess.run( # noqa: S603 - the rendered script under test. + [sys.executable, str(_script(tmp_path, port, kibana))], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert PASSWORD not in done.stdout + done.stderr + return done + + +# proves: S-024-10 +def test_s024_10_the_snapshot_lists_the_feature_state_kibana( + tmp_path: Path, fake: tuple[FakeElasticsearch, int] +) -> None: + state, port = fake + state.feature_states = ["kibana", "security"] + + done = _backup(tmp_path, port, ["search-kibana"]) + + assert done.returncode == 0, done.stderr + (taken,) = state.snapshots + features = cast("list[dict[str, object]]", taken["feature_states"]) + assert "kibana" in [feature["feature_name"] for feature in features] + assert f"snapshot {taken['snapshot']} holds the feature state kibana" in done.stdout + # The request is S-012's: the cluster state and every feature state, not + # the feature state kibana alone + assert state.body("PUT", "/_snapshot/") == { + "include_global_state": True, + "metadata": {"takenBy": "cloudfall", "service": "search-main"}, + } + + +# proves: S-024-10 +def test_s024_10_a_snapshot_without_the_feature_state_kibana_fails_the_backup( + tmp_path: Path, fake: tuple[FakeElasticsearch, int] +) -> None: + state, port = fake + state.feature_states = ["security"] + state.snapshot("cloudfall-20260101-000000", age_days=60) + + done = _backup(tmp_path, port, ["search-kibana"]) + + assert done.returncode == 1 + assert "holds no feature state kibana" in done.stderr + assert "Kibana service search-kibana" in done.stderr + # No retention after a failed run: the old snapshot stays + assert state.requests("DELETE") == [] + assert "cloudfall-20260101-000000" in state.names() + + +def test_a_cluster_without_kibana_backs_up_and_renders_as_before( + tmp_path: Path, fake: tuple[FakeElasticsearch, int] +) -> None: + _, port = fake + + done = _backup(tmp_path, port, []) + + assert done.returncode == 0, done.stderr + assert "feature state" not in done.stdout + text = _script(tmp_path, port, []).read_text(encoding="utf-8") + assert "KIBANA" not in text + assert "feature_state" not in text + # With Kibana, the script gains its check and nothing else changes + with_kibana = _script(tmp_path, port, ["search-kibana"]).read_text("utf-8") + without = text.splitlines() + added = [line for line in with_kibana.splitlines() if line not in without] + assert [line for line in without if line not in with_kibana.splitlines()] == [] + assert any("KIBANA_FEATURE_STATE" in line for line in added) + + +# proves: S-024-10 +def test_s024_10_services_yml_tells_each_cluster_which_kibana_reads_it() -> None: + nodes, _ = yaml.safe_load(SERVICES.read_text(encoding="utf-8")) + deploy = next( + task + for task in nodes["tasks"] + if task.get("ansible.builtin.include_role", {}).get("name") + == "cloudfall_elasticsearch" + ) + expression = deploy["vars"]["cloudfall_elasticsearch_kibana_services"] + kibana = { + "id": "search-kibana", + "serviceKind": "kibana", + "server": "h2", + "kibana": {"elasticsearch": "search-main", "users": []}, + } + other = {**kibana, "id": "logs-kibana", "kibana": {"elasticsearch": "logs-main"}} + hostvars = { + "h1": {"cloudfall_services": [{"id": "search-main", "serviceKind": "x"}]}, + # The Kibana of the cluster runs on another node than the home + "h2": {"cloudfall_services": [kibana, other]}, + "h3": {}, + } + + def found(cluster: str) -> object: + templar = Templar( + loader=DataLoader(), + variables={ + "groups": {"cloudfall_servers": ["h1", "h2", "h3"]}, + "hostvars": hostvars, + "cloudfall_service_item": {"id": cluster}, + }, + ) + return templar.template(trust_as_template(expression)) + + assert found("search-main") == ["search-kibana"] + assert found("crm-main") == [] + + +def _guide_commands() -> list[str]: + """Return the console blocks of the guide's restore section, in order.""" + text = GUIDE.read_text(encoding="utf-8") + section = text.split("## Restore the dashboards", 1)[1].split("\n## ", 1)[0] + return [ + " ".join( + line.strip().rstrip("\\").strip() for line in block.splitlines() + ).strip() + for block in re.findall(r"```console\n(.*?)```", section, flags=re.DOTALL) + ] + + +# proves: S-024-10 +def test_s024_10_the_guide_stops_kibana_restores_the_feature_state_and_starts_it() -> ( + None +): + stop, restore, start = _guide_commands() + + assert stop == "sudo systemctl stop kibana.service" + assert start == "sudo systemctl start kibana.service" + request = re.search(r"'(http://[^']+)'", restore) + assert request is not None + assert re.fullmatch( + r"http://127\.0\.0\.1:9200/_snapshot/cloudfall/cloudfall-[0-9]{8}-[0-9]{6}" + r"/_restore\?wait_for_completion=true", + request[1], + ) + assert "-X POST" in restore + body = re.search(r"-d '(\{.*\})'", restore) + assert body is not None + # Only the feature state: no data index and not the cluster state + assert json.loads(body[1]) == { + "indices": "-*", + "include_global_state": False, + "feature_states": ["kibana"], + } + # Cloudfall's account, its password asked for, never on the command line + assert "--user cloudfall " in restore + assert PASSWORD not in restore + + +@pytest.fixture +def rebuilt(tmp_path: Path) -> tuple[Node, Node]: + """Two hosts of the same Kibana service: the first, and the rebuilt one.""" + first, second = tmp_path / "first", tmp_path / "rebuilt" + first.mkdir() + second.mkdir() + return Node(first), Node(second) + + +# proves: S-024-11 +@requires_ansible +def test_s024_11_a_rebuilt_server_gets_the_stores_keys_and_a_new_token( + rebuilt: tuple[Node, Node], +) -> None: + before, after = rebuilt + before.converge() + old_token = before.keystore[TOKEN_SETTING] + + # The rebuilt server is empty: no keystore, no digest, no service_tokens + assert not (after.kibana_conf / "kibana.keystore").exists() + assert not (after.elasticsearch_conf / "service_tokens").exists() + done, changed = after.converge() + + assert changed > 0 + # The three keys in the keystore are the store's, the ones the old + # server had, so saved objects encrypted before still decrypt + stored = {SETTINGS[name]: value for name, value in KEYS.items()} + assert {setting: after.keystore[setting] for setting in SETTINGS.values()} == ( + stored + ) + assert {setting: before.keystore[setting] for setting in SETTINGS.values()} == ( + stored + ) + # No task makes a key on the server: each comes from the staged store + assert all( + call[:2] != ["kibana-keystore", "add"] or call[-1] != "--generate" + for call in after.writes() + ) + # A new token of elastic/kibana in the rebuilt node's own file + (line,) = after.service_tokens.splitlines() + assert line.startswith("elastic/kibana/search-kibana:") + assert after.keystore[TOKEN_SETTING] != old_token + for secret in (after.keystore[TOKEN_SETTING], *KEYS.values()): + assert secret not in done.stdout + assert secret not in done.stderr + + +# proves: S-024-11 +@requires_ansible +def test_s024_11_a_second_converge_of_the_rebuilt_server_keeps_its_keys( + rebuilt: tuple[Node, Node], +) -> None: + _, after = rebuilt + after.converge() + keystore = after.keystore + + _, changed = after.converge() + + assert changed == 0 + assert after.keystore == keystore diff --git a/sdk/tests/test_s024_11_kibana_rebuild_keys.py b/sdk/tests/test_s024_11_kibana_rebuild_keys.py new file mode 100644 index 00000000..9f866968 --- /dev/null +++ b/sdk/tests/test_s024_11_kibana_rebuild_keys.py @@ -0,0 +1,84 @@ +"""A rebuilt Kibana server gets the store's keys, not new ones (S-024-11, #580). + +The controller side: every services converge stages the three keys the +project's store holds, and the store never replaces a held key, so a server +converged empty after a rebuild gets the keys its saved objects were +encrypted with. The host side is tested in +``engine/tests/test_s024_10_11_kibana_dashboards.py``. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest +from cloudfall.inventory import PlatformInventory +from cloudfall.lifecycle import converge_services +from cloudfall.requirements import requirements_of +from cloudfall.secret_store import ( + ERROR_KEY_EXISTS, + SecretStore, + secret_requirements, +) +from cloudfall.secrets import SecretsError +from cloudfall.validation import validate_config +from kibana_project import SCHEMAS +from test_s024_kibana_converge import KEYS, Recorder, _context, _project, _provider + +if TYPE_CHECKING: + from pathlib import Path + +STAGED = { + "securityKey": KEYS["SECURITY_ENCRYPTION_KEY"], + "savedObjectsKey": KEYS["SAVED_OBJECTS_ENCRYPTION_KEY"], + "reportingKey": KEYS["REPORTING_ENCRYPTION_KEY"], +} + + +def _staged(recorder: Recorder) -> dict[str, str]: + return { + name: recorder.staged[f"search-kibana.{name}"][1] + for name in ("securityKey", "savedObjectsKey", "reportingKey") + } + + +# proves: S-024-11 +def test_s024_11_every_converge_stages_the_keys_the_store_holds( + tmp_path: Path, +) -> None: + project = _project(tmp_path) + store_file = project / "secrets" / "production" / "services" / "search-kibana.env" + stored = store_file.read_bytes() + + first, rebuilt = Recorder(), Recorder() + converge_services(_context(project, first), _provider(project)) + # The server is rebuilt empty and converged again: the same keys + converge_services(_context(project, rebuilt), _provider(project)) + + assert _staged(first) == STAGED + assert _staged(rebuilt) == STAGED + assert store_file.read_bytes() == stored + + +# proves: S-024-11 +def test_s024_11_the_store_never_replaces_a_held_key(tmp_path: Path) -> None: + project = _project(tmp_path) + store = SecretStore( + project / "secrets", + decrypt=lambda path: path.read_text(encoding="utf-8"), + encrypt=lambda _path, text: text, + ) + inventory = PlatformInventory.from_state(validate_config(project, SCHEMAS)) + wanted = [ + spec + for spec in secret_requirements(requirements_of(inventory)) + if spec.reference.path.value == "/services/search-kibana" + ] + + assert len(wanted) == len(KEYS) + for spec in wanted: + assert store.holds(spec.reference) + with pytest.raises(SecretsError) as error: + store.generate(spec.reference) + assert error.value.code == ERROR_KEY_EXISTS + assert store.value(spec.reference) == KEYS[spec.reference.key.value] From 6520df90041ac34ffcd6573fb8c6e584666d5a6d Mon Sep 17 00:00:00 2001 From: "shipmill-romamo[bot]" <338557544+shipmill-romamo[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:08:14 +0200 Subject: [PATCH 2/2] Drop the backup's feature state check for Kibana clusters (S-024-10) Spec 024 gives Kibana no backup of its own: the S-012 snapshot already asks for the cluster state and every feature state. Failing cloudfall backup run when a declared Kibana's feature state is missing, also for a Kibana that never started, went beyond the spec, so the backup script, the role's variables and services.yml are back to main's. S-024-10 is now proved by the snapshot request asking for every feature state and the taken snapshot listing kibana on a node that has it; the guide and the changelog follow. Part of #580 Co-Authored-By: Claude Opus 5.5 --- changelog.d/580-kibana-dashboards-survive.md | 2 +- docs/kibana-service-guide.md | 18 ++- engine/ansible/playbooks/services.yml | 14 -- .../cloudfall_elasticsearch/defaults/main.yml | 5 - .../meta/argument_specs.yml | 6 - .../templates/snapshots.py.j2 | 19 --- .../test_s024_10_11_kibana_dashboards.py | 136 ++++++------------ 7 files changed, 50 insertions(+), 150 deletions(-) diff --git a/changelog.d/580-kibana-dashboards-survive.md b/changelog.d/580-kibana-dashboards-survive.md index 84c77457..e3701a0d 100644 --- a/changelog.d/580-kibana-dashboards-survive.md +++ b/changelog.d/580-kibana-dashboards-survive.md @@ -1,3 +1,3 @@ ### Added -- Kibana's dashboards survive a snapshot restore and a rebuilt server (S-024-10, S-024-11): when a Kibana service reads an Elasticsearch service, `cloudfall-elasticsearch-backup` checks that the snapshot it took lists the feature state `kibana`, where Kibana keeps its saved objects, and fails the run when it does not; the snapshot request is unchanged, and a cluster without Kibana renders and runs its backup script as before. The new `docs/kibana-service-guide.md` gives the restore (stop Kibana, restore the feature state `kibana` alone from a snapshot, start Kibana) and what a rebuilt Kibana server gets: the same three encryption keys from the project's store, so encrypted saved objects still decrypt, and a new service token in the rebuilt node's own `service_tokens` file (#580) +- How Kibana's dashboards survive a snapshot restore and a rebuilt server (S-024-10, S-024-11): the new `docs/kibana-service-guide.md` explains that the snapshots of `cloudfall backup run ` already hold every feature state, `kibana` among them, and gives the restore (stop Kibana, restore the feature state `kibana` alone from a snapshot, start Kibana) and what a rebuilt Kibana server gets: the same three encryption keys from the project's store, so encrypted saved objects still decrypt, and a new service token in the rebuilt node's own `service_tokens` file (#580) diff --git a/docs/kibana-service-guide.md b/docs/kibana-service-guide.md index c74585cb..0149c09d 100644 --- a/docs/kibana-service-guide.md +++ b/docs/kibana-service-guide.md @@ -1,9 +1,9 @@ # Run a Kibana service Status: this guide covers where Kibana's dashboards are backed up, how to -restore them, and what a rebuilt Kibana server gets. The backup check and the -keys of a rebuilt server are proven against stand-ins of Elasticsearch and of -Kibana's keystore, not yet on a live Debian 13 host. The other sections the +restore them, and what a rebuilt Kibana server gets. The snapshot request and +the keys of a rebuilt server are proven against stand-ins of Elasticsearch and +of Kibana's keystore, not yet on a live Debian 13 host. The other sections the spec names (declaring Kibana, its users, publishing it with a Domain, an SSH forward, a version change and licences) come with later releases. @@ -23,13 +23,11 @@ dashboards. The Kibana service has no `backup`, timer or receipt of its own: uv run cloudfall backup run search-main ``` -When a Kibana service reads the cluster, `cloudfall-elasticsearch-backup` -also checks that the snapshot it took lists the feature state `kibana`, and -fails the run when it does not: Kibana then never started against the -cluster, or its system indices are gone. The snapshot itself is unchanged: it -asks for the cluster state and every feature state, as for a cluster without -Kibana. The restore drill of the Elasticsearch service restores renamed -copies of data indices only and never touches a feature state. +The snapshot asks for the cluster state with no list of feature states, +which Elasticsearch takes as every feature state, so once Kibana has started +against the cluster each snapshot lists the feature state `kibana`. The +restore drill of the Elasticsearch service restores renamed copies of data +indices only and never touches a feature state. To see the feature states a snapshot holds, ask the node (on the Kibana server, which is a node of its cluster): diff --git a/engine/ansible/playbooks/services.yml b/engine/ansible/playbooks/services.yml index d8c3a0ba..5f01cbc9 100644 --- a/engine/ansible/playbooks/services.yml +++ b/engine/ansible/playbooks/services.yml @@ -254,20 +254,6 @@ | flatten(levels=1) | items2dict(key_name='name', value_name='access') }} - # The ids of the Kibana services that read the cluster (S-024-10): - # each snapshot must then hold the feature state kibana, Kibana's - # saved objects. Read from every server's services, as above. - cloudfall_elasticsearch_kibana_services: >- - {{ - groups['cloudfall_servers'] | default([]) - | map('extract', hostvars) - | map(attribute='cloudfall_services', default=[]) - | flatten(levels=1) - | selectattr('serviceKind', 'equalto', 'kibana') - | selectattr('kibana.elasticsearch', 'equalto', cloudfall_service_item.id) - | map(attribute='id') - | unique | list - }} loop: >- {{ cloudfall_services | default([]) diff --git a/engine/ansible/roles/cloudfall_elasticsearch/defaults/main.yml b/engine/ansible/roles/cloudfall_elasticsearch/defaults/main.yml index 0498cb4f..945a9fc4 100644 --- a/engine/ansible/roles/cloudfall_elasticsearch/defaults/main.yml +++ b/engine/ansible/roles/cloudfall_elasticsearch/defaults/main.yml @@ -7,11 +7,6 @@ cloudfall_elasticsearch_account_files: {} # kibana.users, by user name, as services.yml finds it (S-024); a user not # named here holds its own role alone. cloudfall_elasticsearch_kibana_access: {} -# The ids of the Kibana services that read the cluster, as services.yml finds -# them (S-024-10): each snapshot must then hold the feature state kibana. -cloudfall_elasticsearch_kibana_services: [] -# The feature state Elasticsearch groups Kibana's system indices under. -cloudfall_elasticsearch_kibana_feature_state: kibana cloudfall_elasticsearch_repository_key_url: https://artifacts.elastic.co/GPG-KEY-elasticsearch cloudfall_elasticsearch_repository_key_path: /etc/apt/keyrings/elasticsearch.asc cloudfall_elasticsearch_repository_url: https://artifacts.elastic.co/packages diff --git a/engine/ansible/roles/cloudfall_elasticsearch/meta/argument_specs.yml b/engine/ansible/roles/cloudfall_elasticsearch/meta/argument_specs.yml index e8f054a0..9334730a 100644 --- a/engine/ansible/roles/cloudfall_elasticsearch/meta/argument_specs.yml +++ b/engine/ansible/roles/cloudfall_elasticsearch/meta/argument_specs.yml @@ -18,12 +18,6 @@ argument_specs: The access, view or edit, of each user the service's Kibana names in kibana.users, by user name (S-024); the user converge gives that user the role cloudfall-kibana-view or cloudfall-kibana-edit next to its own - cloudfall_elasticsearch_kibana_services: - type: list - elements: str - description: >- - The ids of the Kibana services that read the cluster (S-024-10); with - one, a snapshot that holds no feature state kibana fails the backup cloudfall_elasticsearch_service: type: dict required: true diff --git a/engine/ansible/roles/cloudfall_elasticsearch/templates/snapshots.py.j2 b/engine/ansible/roles/cloudfall_elasticsearch/templates/snapshots.py.j2 index 08c2aba5..159ba69d 100644 --- a/engine/ansible/roles/cloudfall_elasticsearch/templates/snapshots.py.j2 +++ b/engine/ansible/roles/cloudfall_elasticsearch/templates/snapshots.py.j2 @@ -46,10 +46,6 @@ RETENTION_DAYS = {{ cloudfall_elasticsearch_service.backup.retentionDays | int } RESTORE_CHECK_INDICES = {{ cloudfall_elasticsearch_service.elasticsearch.restoreCheckIndices | default([]) | to_json }} POLL_SECONDS = {{ cloudfall_elasticsearch_snapshot_poll_seconds | int }} WAIT_SECONDS = {{ cloudfall_elasticsearch_snapshot_wait_seconds | int }} -{% if cloudfall_elasticsearch_kibana_services | length > 0 %} -KIBANA_SERVICES = {{ cloudfall_elasticsearch_kibana_services | join(', ') | to_json }} -KIBANA_FEATURE_STATE = {{ cloudfall_elasticsearch_kibana_feature_state | to_json }} -{% endif %} SNAPSHOT_NAME = re.compile(r"cloudfall-[0-9]{8}-[0-9]{6}") RESTORE_PREFIX = "cloudfall-restore-check-" @@ -274,21 +270,6 @@ def backup(): ) if COUNTS_INDEX not in snapshot["indices"]: raise Failure(f"snapshot {name} does not hold {COUNTS_INDEX}") -{% if cloudfall_elasticsearch_kibana_services | length > 0 %} - # Kibana service {{ cloudfall_elasticsearch_kibana_services | join(', ') }} keeps its - # dashboards and other saved objects in the feature state kibana, which a - # snapshot of the cluster state holds (S-024-10). - features = [ - state.get("feature_name") for state in snapshot.get("feature_states", []) - ] - if KIBANA_FEATURE_STATE not in features: - raise Failure( - f"snapshot {name} of {SERVICE} holds no feature state " - f"{KIBANA_FEATURE_STATE}, where Kibana service {KIBANA_SERVICES} keeps " - "its saved objects; check that Kibana runs and has started once" - ) - print(f"snapshot {name} holds the feature state {KIBANA_FEATURE_STATE}") -{% endif %} print( f"snapshot {name} of {SERVICE}: SUCCESS, {len(snapshot['indices'])} " f"indices, {shards.get('successful', 0)} of {shards.get('total', 0)} shards" diff --git a/engine/tests/test_s024_10_11_kibana_dashboards.py b/engine/tests/test_s024_10_11_kibana_dashboards.py index 41514b5d..01fc4fdd 100644 --- a/engine/tests/test_s024_10_11_kibana_dashboards.py +++ b/engine/tests/test_s024_10_11_kibana_dashboards.py @@ -1,8 +1,9 @@ """Kibana's dashboards survive a snapshot restore and a rebuilt server (S-024, #580). -S-024-10: the snapshot script of the Elasticsearch role, rendered with -Ansible's own templating, runs for real against the fake node of -``test_s012_elasticsearch_snapshots``; the guide's restore steps are read from +S-024-10: S-012's backup script, rendered with Ansible's own templating as for +any cluster, runs for real against the fake node of +``test_s012_elasticsearch_snapshots``, which lists the feature states of a +cluster with Kibana; the guide's restore steps are read from ``docs/kibana-service-guide.md``. S-024-11: the Kibana role's keystore tasks run for real twice, on a converged host and on a rebuilt empty one, against the stand-ins of ``kibana_node``. Restoring the feature state on a live cluster, @@ -12,17 +13,16 @@ from __future__ import annotations +import base64 import json import re import subprocess import sys +import urllib.request from pathlib import Path from typing import cast import pytest -import yaml -from ansible.parsing.dataloader import DataLoader -from ansible.template import Templar, trust_as_template from test_s012_elasticsearch_snapshots import ( PASSWORD, FakeElasticsearch, @@ -36,12 +36,11 @@ from test_s024_kibana_role import KEYS, SETTINGS, TOKEN_SETTING, Node, requires_ansible ROOT = Path(__file__).parents[2] -SERVICES = ROOT / "engine" / "ansible" / "playbooks" / "services.yml" GUIDE = ROOT / "docs" / "kibana-service-guide.md" -def _script(tmp_path: Path, port: int, kibana: list[str]) -> Path: - """Render the backup script as the converge does with ``kibana`` reading it.""" +def _backup(tmp_path: Path, port: int) -> subprocess.CompletedProcess[str]: + """Render and run S-012's backup script, as the converge installs it.""" password = tmp_path / "cloudfall-password" password.write_text(PASSWORD + "\n", encoding="utf-8") rendered = _render( @@ -50,7 +49,6 @@ def _script(tmp_path: Path, port: int, kibana: list[str]) -> Path: _service(port), cloudfall_elasticsearch_snapshot_action="backup", cloudfall_elasticsearch_password_path=str(password), - cloudfall_elasticsearch_kibana_services=kibana, ), ) script = tmp_path / "cloudfall-elasticsearch-backup" @@ -58,14 +56,8 @@ def _script(tmp_path: Path, port: int, kibana: list[str]) -> Path: rendered.replace("#!/usr/bin/python3", f"#!{sys.executable}", 1), encoding="utf-8", ) - return script - - -def _backup( - tmp_path: Path, port: int, kibana: list[str] -) -> subprocess.CompletedProcess[str]: done = subprocess.run( # noqa: S603 - the rendered script under test. - [sys.executable, str(_script(tmp_path, port, kibana))], + [sys.executable, str(script)], capture_output=True, text=True, timeout=60, @@ -75,103 +67,57 @@ def _backup( return done +def _listed(port: int, name: str) -> dict[str, object]: + """Read a snapshot as the guide does: GET /_snapshot/cloudfall/.""" + request = urllib.request.Request( + f"http://127.0.0.1:{port}/_snapshot/cloudfall/{name}", + headers={ + "Authorization": "Basic " + + base64.b64encode(f"cloudfall:{PASSWORD}".encode()).decode() + }, + ) + with urllib.request.urlopen(request, timeout=10) as answer: # noqa: S310 + body = json.loads(answer.read()) + (snapshot,) = body["snapshots"] + return cast("dict[str, object]", snapshot) + + # proves: S-024-10 -def test_s024_10_the_snapshot_lists_the_feature_state_kibana( +def test_s024_10_the_snapshot_asks_for_every_feature_state( tmp_path: Path, fake: tuple[FakeElasticsearch, int] ) -> None: state, port = fake - state.feature_states = ["kibana", "security"] - done = _backup(tmp_path, port, ["search-kibana"]) + done = _backup(tmp_path, port) assert done.returncode == 0, done.stderr - (taken,) = state.snapshots - features = cast("list[dict[str, object]]", taken["feature_states"]) - assert "kibana" in [feature["feature_name"] for feature in features] - assert f"snapshot {taken['snapshot']} holds the feature state kibana" in done.stdout - # The request is S-012's: the cluster state and every feature state, not - # the feature state kibana alone - assert state.body("PUT", "/_snapshot/") == { + # The cluster state with no feature_states list: Elasticsearch then takes + # every feature state, kibana among them. Naming kibana alone would drop + # the others, so the request stays S-012's + body = state.body("PUT", "/_snapshot/") + assert body == { "include_global_state": True, "metadata": {"takenBy": "cloudfall", "service": "search-main"}, } + assert "feature_states" not in body # proves: S-024-10 -def test_s024_10_a_snapshot_without_the_feature_state_kibana_fails_the_backup( +def test_s024_10_after_backup_run_the_snapshot_lists_the_feature_state_kibana( tmp_path: Path, fake: tuple[FakeElasticsearch, int] ) -> None: state, port = fake - state.feature_states = ["security"] - state.snapshot("cloudfall-20260101-000000", age_days=60) - - done = _backup(tmp_path, port, ["search-kibana"]) - - assert done.returncode == 1 - assert "holds no feature state kibana" in done.stderr - assert "Kibana service search-kibana" in done.stderr - # No retention after a failed run: the old snapshot stays - assert state.requests("DELETE") == [] - assert "cloudfall-20260101-000000" in state.names() - - -def test_a_cluster_without_kibana_backs_up_and_renders_as_before( - tmp_path: Path, fake: tuple[FakeElasticsearch, int] -) -> None: - _, port = fake + # A cluster Kibana has started on holds its system indices + state.feature_states = ["kibana", "security"] - done = _backup(tmp_path, port, []) + done = _backup(tmp_path, port) assert done.returncode == 0, done.stderr - assert "feature state" not in done.stdout - text = _script(tmp_path, port, []).read_text(encoding="utf-8") - assert "KIBANA" not in text - assert "feature_state" not in text - # With Kibana, the script gains its check and nothing else changes - with_kibana = _script(tmp_path, port, ["search-kibana"]).read_text("utf-8") - without = text.splitlines() - added = [line for line in with_kibana.splitlines() if line not in without] - assert [line for line in without if line not in with_kibana.splitlines()] == [] - assert any("KIBANA_FEATURE_STATE" in line for line in added) - - -# proves: S-024-10 -def test_s024_10_services_yml_tells_each_cluster_which_kibana_reads_it() -> None: - nodes, _ = yaml.safe_load(SERVICES.read_text(encoding="utf-8")) - deploy = next( - task - for task in nodes["tasks"] - if task.get("ansible.builtin.include_role", {}).get("name") - == "cloudfall_elasticsearch" - ) - expression = deploy["vars"]["cloudfall_elasticsearch_kibana_services"] - kibana = { - "id": "search-kibana", - "serviceKind": "kibana", - "server": "h2", - "kibana": {"elasticsearch": "search-main", "users": []}, - } - other = {**kibana, "id": "logs-kibana", "kibana": {"elasticsearch": "logs-main"}} - hostvars = { - "h1": {"cloudfall_services": [{"id": "search-main", "serviceKind": "x"}]}, - # The Kibana of the cluster runs on another node than the home - "h2": {"cloudfall_services": [kibana, other]}, - "h3": {}, - } - - def found(cluster: str) -> object: - templar = Templar( - loader=DataLoader(), - variables={ - "groups": {"cloudfall_servers": ["h1", "h2", "h3"]}, - "hostvars": hostvars, - "cloudfall_service_item": {"id": cluster}, - }, - ) - return templar.template(trust_as_template(expression)) - - assert found("search-main") == ["search-kibana"] - assert found("crm-main") == [] + (taken,) = state.snapshots + listed = _listed(port, str(taken["snapshot"])) + assert listed["state"] == "SUCCESS" + features = cast("list[dict[str, object]]", listed["feature_states"]) + assert [feature["feature_name"] for feature in features] == ["kibana", "security"] def _guide_commands() -> list[str]: