diff --git a/changelog.d/580-kibana-dashboards-survive.md b/changelog.d/580-kibana-dashboards-survive.md new file mode 100644 index 00000000..e3701a0d --- /dev/null +++ b/changelog.d/580-kibana-dashboards-survive.md @@ -0,0 +1,3 @@ +### Added + +- 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 new file mode 100644 index 00000000..0149c09d --- /dev/null +++ b/docs/kibana-service-guide.md @@ -0,0 +1,111 @@ +# 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 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. + +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 +``` + +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): + +```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/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..01fc4fdd --- /dev/null +++ b/engine/tests/test_s024_10_11_kibana_dashboards.py @@ -0,0 +1,223 @@ +"""Kibana's dashboards survive a snapshot restore and a rebuilt server (S-024, #580). + +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, +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 base64 +import json +import re +import subprocess +import sys +import urllib.request +from pathlib import Path +from typing import cast + +import pytest +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] +GUIDE = ROOT / "docs" / "kibana-service-guide.md" + + +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( + "snapshots.py.j2", + _variables( + _service(port), + cloudfall_elasticsearch_snapshot_action="backup", + cloudfall_elasticsearch_password_path=str(password), + ), + ) + script = tmp_path / "cloudfall-elasticsearch-backup" + script.write_text( + rendered.replace("#!/usr/bin/python3", f"#!{sys.executable}", 1), + encoding="utf-8", + ) + done = subprocess.run( # noqa: S603 - the rendered script under test. + [sys.executable, str(script)], + capture_output=True, + text=True, + timeout=60, + check=False, + ) + assert PASSWORD not in done.stdout + done.stderr + 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_asks_for_every_feature_state( + tmp_path: Path, fake: tuple[FakeElasticsearch, int] +) -> None: + state, port = fake + + done = _backup(tmp_path, port) + + assert done.returncode == 0, done.stderr + # 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_after_backup_run_the_snapshot_lists_the_feature_state_kibana( + tmp_path: Path, fake: tuple[FakeElasticsearch, int] +) -> None: + state, port = fake + # A cluster Kibana has started on holds its system indices + state.feature_states = ["kibana", "security"] + + done = _backup(tmp_path, port) + + assert done.returncode == 0, done.stderr + (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]: + """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]