diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 0d8d6a1a..8b469a81 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -225,8 +225,9 @@ add software RAID1 and the hybrid storage layout, while cloud VPS types do not. Any server can run any declared service or component: - Infrastructure services (PostgreSQL, Redis and MariaDB today, MariaDB with - manually promoted primary and replica pairs; Elasticsearch and friends as - the catalog grows) stay pinned to declared servers + manually promoted primary and replica pairs, and Kibana on a node of the + Elasticsearch service it reads; Elasticsearch and friends as the catalog + grows) stay pinned to declared servers - Application components are movable: reassigning `crm-backend` from `h1,h2` to `h3` is a config change followed by convergence - Failover is manual with easy reassignment rather than automated @@ -301,7 +302,10 @@ and their current status: - **Catalog breadth** — Elasticsearch, RabbitMQ, and Node runtime services following the PostgreSQL, Redis and MariaDB pattern: pinned installs, loopback-only binds, backup policies, audited evidence. MariaDB is built - ([spec 019](docs/specs/019-mariadb-service.md)); MySQL and Percona Server + ([spec 019](docs/specs/019-mariadb-service.md)), and so is Kibana over an + Elasticsearch service, on loopback at its cluster's version with its saved + objects in the cluster's snapshots + ([spec 024](docs/specs/024-kibana-service.md)); MySQL and Percona Server as a kind of their own are not - **Multi-server assignment at scale** — components spread across many servers and moved by editing the config; the model exists, fleet-scale diff --git a/ROADMAP.md b/ROADMAP.md index 0827030f..836aaf68 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -184,8 +184,12 @@ routine and widen what it can carry, in rough priority order: loopback-only binds, backup policies, audited evidence (Redis ✔ with RDB backups, restore checks, and Alloy metrics; MariaDB ✔ with primary and replica pairs, promotion, dumps that record their GTID position, restore - drills, and metrics ([spec 019](docs/specs/019-mariadb-service.md)); MySQL - and Percona Server as a kind of their own, and the rest, pending) + drills, and metrics ([spec 019](docs/specs/019-mariadb-service.md)); Kibana + ✔ over an Elasticsearch service, at its cluster's version, with view and + edit access for declared users, publishing through a Domain, its + dashboards in the cluster's snapshots, and audit + ([spec 024](docs/specs/024-kibana-service.md)); MySQL and Percona Server + as a kind of their own, and the rest, pending) - **Render API import** ✔ — `cloudfall import render-api` maps a live workspace with real environment values and database-URL rewriting; cron jobs arrive with their schedules in the gap report, and modeling them as diff --git a/changelog.d/582-kibana-audit.md b/changelog.d/582-kibana-audit.md new file mode 100644 index 00000000..fa038776 --- /dev/null +++ b/changelog.d/582-kibana-audit.md @@ -0,0 +1,3 @@ +### Added + +- `cloudfall audit` checks a Kibana service (S-024-13): `kibana.version` (the installed `kibana` package against the Elasticsearch service's declared `version`), `kibana.unit` (`kibana.service` enabled and running), `kibana.configuration` (`/etc/kibana/kibana.yml` against the rendered settings, with a setting the role does not write named without its value, and the heap in `node.options`), `kibana.status` (the overall level of `GET /api/status` is `available`), `kibana.roles` (`cloudfall-kibana-view` and `cloudfall-kibana-edit` as the role writes them), `kibana.users` (each declared user of the Elasticsearch service holds the Kibana role of its `access` and no other; an undeclared user holding one is listed as unmanaged, not drift) and `kibana.keystore` (the three encryption keys, its S-011 secret requirements, by setting name). A Kibana listening off loopback is drift of the existing `services.bind` check. Inspect reads the evidence on the Kibana server as the `cloudfall` account in `no_log` tasks and keeps names and privileges only: no token, key, password or hash reaches the observation. A project without Kibana audits as before. `docs/kibana-service-guide.md` now covers declaring Kibana and its users, an SSH forward, publishing with a Domain and what that exposes, a version change, the licence and the Kibana features that need a paid one, and the audit (#582) diff --git a/config/schemas/v1/observed-server.schema.json b/config/schemas/v1/observed-server.schema.json index 1d2180b3..34b27da4 100644 --- a/config/schemas/v1/observed-server.schema.json +++ b/config/schemas/v1/observed-server.schema.json @@ -937,6 +937,156 @@ ], "additionalProperties": false }, + "kibana": { + "description": "The Kibana service of the server (S-024): its managed kibana.yml and node.options as text, null when missing; the names of the settings its keystore holds, null when it could not be listed; the overall level Kibana reports; its two roles as Kibana's role API answers them; and the Kibana roles each user of the cluster holds. Names and privileges only: never a token, key, password or hash", + "type": "object", + "properties": { + "service": { + "$ref": "common.schema.json#/$defs/resourceId" + }, + "configurationPath": { + "$ref": "common.schema.json#/$defs/absolutePath" + }, + "configuration": { + "$ref": "#/$defs/nullableString" + }, + "nodeOptions": { + "$ref": "#/$defs/nullableString" + }, + "keystore": { + "anyOf": [ + { + "type": "array", + "maxItems": 256, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 256 + } + }, + { + "type": "null" + } + ] + }, + "status": { + "type": "object", + "properties": { + "read": { + "description": "Whether Kibana was asked: false when the cloudfall account's password is not on the server", + "type": "boolean" + }, + "level": { + "description": "status.overall.level of GET /api/status, null when Kibana did not answer", + "anyOf": [ + { + "type": "string", + "minLength": 1, + "maxLength": 64 + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "read", + "level" + ], + "additionalProperties": false + }, + "roles": { + "description": "The two roles the Kibana role keeps, as GET /api/security/role/ answers them; null when Kibana's role API was not read", + "anyOf": [ + { + "type": "array", + "maxItems": 2, + "items": { + "type": "object", + "properties": { + "name": { + "enum": [ + "cloudfall-kibana-view", + "cloudfall-kibana-edit" + ] + }, + "found": { + "type": "boolean" + }, + "elasticsearch": { + "type": [ + "object", + "null" + ] + }, + "kibana": { + "type": [ + "array", + "null" + ], + "maxItems": 64, + "items": { + "type": "object" + } + }, + "metadata": { + "type": [ + "object", + "null" + ] + } + }, + "required": [ + "name", + "found", + "elasticsearch", + "kibana", + "metadata" + ], + "additionalProperties": false + } + }, + { + "type": "null" + } + ] + }, + "userRoles": { + "description": "Each user of the cluster that is not built in, with the Kibana roles it holds (cloudfall-kibana-view, cloudfall-kibana-edit), possibly none; null when the node was not read", + "anyOf": [ + { + "type": "object", + "maxProperties": 4096, + "additionalProperties": { + "type": "array", + "maxItems": 2, + "items": { + "enum": [ + "cloudfall-kibana-view", + "cloudfall-kibana-edit" + ] + } + } + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "service", + "configurationPath", + "configuration", + "nodeOptions", + "keystore", + "status", + "roles", + "userRoles" + ], + "additionalProperties": false + }, "mariadbAccounts": { "description": "The databases and users of each MariaDB service of the server (S-019); the lists are absent when the server could not be read", "type": "array", diff --git a/docs/kibana-service-guide.md b/docs/kibana-service-guide.md index 0149c09d..674cd1e1 100644 --- a/docs/kibana-service-guide.md +++ b/docs/kibana-service-guide.md @@ -1,17 +1,290 @@ # 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. +Status: declaring Kibana, its users, publishing it with a Domain, a version +change, the backup and restore of the dashboards, a rebuilt server and the +audit are built. The role and inspect are proven by replaying their tasks +against stand-ins of Kibana's keystore, of the node's token tool and of the +answers Kibana and Elasticsearch give, not yet on a live Debian 13 host. 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 +other saved object are documents in the cluster's system indices. It has no +version of its own either: it runs at the version of its cluster. The behaviour is specified in [spec 024](specs/024-kibana-service.md). +## Safety boundary + +- Kibana listens on loopback only, in plain HTTP. Nothing off the server + reaches it unless a `Domain` publishes it +- Kibana logs in to its node with a token of the `elastic/kibana` service + account, made on that node and kept in Kibana's keystore. The password of + the built-in `kibana_system` user is never set or changed +- The token and the three encryption keys are in Kibana's keystore, never in + `kibana.yml`, a playbook's output, a command's answer or an audit finding +- Kibana has no accounts of its own: a person logs in with a user of the + Elasticsearch service and sees only the indices that user may read +- When the node Kibana runs on is down, Kibana is down, whatever the other + nodes of the cluster do. Kibana talks to that node only + +## Licence + +The role installs Elastic's own `kibana` package from the same Elastic +repository as the node, which Elastic distributes under the Elastic License +2.0, as the Elasticsearch packages are. Check that licence against your use: +offering Kibana to third parties as a service is the case it restricts. + +Cloudfall configures only what the free licence of that distribution gives. +These features of Kibana need a paid Elastic licence, and Cloudfall neither +configures nor refuses them: + +- Single sign-on (SAML, OpenID Connect): people log in with Kibana's own form +- PDF and PNG reports of dashboards and visualisations +- Most alert connectors, such as email, Slack, webhooks and PagerDuty +- Privileges narrower than a whole feature (sub-feature privileges): the + two roles below give a base privilege on all of Kibana + +## Declare Kibana next to a one-node Elasticsearch service + +Kibana reads one Elasticsearch service and runs on one of its nodes. Here +`search-main` is a one-node cluster on `h1`, with a user `analyst` who may +read the `crm-*` indices: + +```yaml +apiVersion: cloudfall/v1 +kind: Service +metadata: + id: search-main + description: Product search +spec: + serviceKind: elasticsearch + environment: production + server: h1 + bind: + address: 127.0.0.1 + port: 9200 + elasticsearch: + version: 9.2.4 + heapMb: 4096 + users: + - name: analyst + access: read + indexPatterns: ["crm-*"] + passwordRef: { environment: production, path: /services/search-main, key: ANALYST_PASSWORD } + backup: + directory: /var/backups/cloudfall/search-main + onCalendar: "*-*-* 03:20:00 UTC" + restoreCheckOnCalendar: "Sun *-*-* 05:00:00 UTC" + retentionDays: 14 +``` + +The Kibana service on the same server: + +```yaml +apiVersion: cloudfall/v1 +kind: Service +metadata: + id: search-kibana + description: Dashboards over product search +spec: + serviceKind: kibana + environment: production + server: h1 + bind: + address: 127.0.0.1 + port: 5601 + kibana: + elasticsearch: search-main + heapMb: 1024 + users: + - name: analyst + access: edit +``` + +| Field | Meaning | +| --- | --- | +| `bind.address` | A loopback address; any other is refused (`service_kibana_bind`) | +| `kibana.elasticsearch` | The Elasticsearch service Kibana reads, of the same environment, with `spec.server` one of its nodes | +| `kibana.heapMb` | `--max-old-space-size` of Kibana's Node.js process, 1024 to 8192, written to `/etc/kibana/node.options` | +| `kibana.domain` | The `Domain` that publishes Kibana (see Publish Kibana with a Domain); absent, Kibana answers on loopback only | +| `kibana.users` | Which users of the Elasticsearch service may work in Kibana, each with `access` of `view` or `edit` (see the next section) | + +The kind declares no `version`, no `backup`, no `metrics` and no +`remoteAccess`; `config validate` refuses each of the last three +(`service_kibana_field_refused`). One server holds at most one Kibana, and +one Elasticsearch service has at most one (`service_kibana_duplicate`). An +Elasticsearch service that declares `existingCluster` can't have a Kibana +service (`service_kibana_existing_cluster`): that cluster's own Kibana still +writes its indices, with keys Cloudfall does not hold. Declare Kibana once the +old nodes are gone and `existingCluster` is removed. + +Validate, see what the server needs, and generate the keys: + +```console +uv run cloudfall config validate +uv run cloudfall requirements show +uv run cloudfall secrets generate +``` + +`requirements show` lists the `kibana` package at the Elasticsearch service's +version and three generated secrets: the keys Kibana encrypts sessions, +saved objects and reports with. `secrets generate` makes each once and stores +it sops-encrypted in `secrets//services/search-kibana.env`; it +never overwrites a stored key. + +Then converge the services, as for any service: the `converge_services` tool +of `cloudfall mcp serve`, or `cloudfall operator approve` of a services +proposal. The converge reads the keys from `--secrets-dir` first, so a +missing one stops it with `PRECONDITION` before any host changes. It +converges every node of the cluster first, then Kibana: it installs +`kibana=` and holds it, writes `/etc/kibana/kibana.yml` and the heap, +puts the token and the keys in the keystore, and waits until Kibana reports +itself available. A `heapMb` that together with the node's Elasticsearch heap +is above three quarters of the server's memory stops the converge before +anything changes. + +## Declare who may view and who may build dashboards + +A person who builds dashboards is two declarations: a user of the +Elasticsearch service, with a password and the indices it may read, and its +line in `kibana.users`. Add a second user, `support`, to `search-main`: + +```yaml + elasticsearch: + users: + - name: analyst + access: read + indexPatterns: ["crm-*"] + passwordRef: { environment: production, path: /services/search-main, key: ANALYST_PASSWORD } + - name: support + access: read + indexPatterns: ["crm-*"] + passwordRef: { environment: production, path: /services/search-main, key: SUPPORT_PASSWORD } +``` + +and give `analyst` edit access and `support` view access in `search-kibana`: + +```yaml + kibana: + elasticsearch: search-main + heapMb: 1024 + users: + - name: analyst + access: edit + - name: support + access: view +``` + +Store each password at its `passwordRef` as the [secrets +guide](secrets-guide.md) describes, and converge the services. + +| `access` | Role | What the person may do | +| --- | --- | --- | +| `view` | `cloudfall-kibana-view` | Open dashboards, Discover and saved objects; change nothing | +| `edit` | `cloudfall-kibana-edit` | Also create and change data views, visualisations, dashboards and every other saved object | + +The Kibana role keeps both roles through Kibana's own role API: Kibana's base +privilege `read` or `all` on every space, and no privilege in Elasticsearch. +The user converge gives each user named in `kibana.users` the role of its +`access` next to its own role, which stays as it is, so a dashboard shows +that person only the indices its `indexPatterns` name. Neither role can +manage users or roles. Dev Tools sends requests as the logged-in user, so it +reaches what that user's role reaches. + +- A user of the Elasticsearch service that `kibana.users` does not name can + log in and gets Kibana's page for an account with no access. An + application's user has no reason to be listed +- Removing a line from `kibana.users` and converging takes the Kibana role + from the user; the user and its index privileges stay +- A person may change their own password in Kibana. The user converge sets a + password only when the stored one changes, so the person's choice stays + until then, and the secrets store no longer holds the password in use +- `elastic` is the cluster's break-glass account. Nothing here uses it; don't + work in Kibana with it + +## Open Kibana through an SSH forward + +Without `domain`, Kibana answers on `127.0.0.1:5601` of its server only. +Forward that port to your machine: + +```console +ssh -N -L 5601:127.0.0.1:5601 admin@h1.example.test +``` + +and open `http://127.0.0.1:5601` in a browser. Log in with a user of the +Elasticsearch service, such as `analyst`, and its password. Kibana's links +start with `http://127.0.0.1:5601` too, so keep the same local port. + +## Publish Kibana with a Domain + +A `Domain` whose proxy is the Kibana server, whose upstream is the service's +`bind`, and whose `tls.mode` is `required` publishes Kibana under its own +hostname, with the certificate and nginx site Cloudfall already manages: + +```yaml +apiVersion: cloudfall/v1 +kind: Domain +metadata: + id: search-kibana-site +spec: + primaryName: kibana.example.test + aliases: [] + proxy: + server: h1 + configurationPath: /etc/nginx/sites-available/kibana.example.test.conf + service: nginx.service + upstream: { address: 127.0.0.1, port: 5601 } + origin: + server: h1 + configurationPath: /etc/nginx/sites-available/kibana-origin.conf + service: nginx.service + scheme: http + port: 5601 + serverName: kibana.example.test + edge: { provider: cloudflare, mode: dns-only } + tls: + mode: required + healthCheck: + scheme: https + path: /login + expectedStatuses: [200] + timeoutSeconds: 5 +``` + +Name it in the Kibana service with `domain: search-kibana-site`. Kibana takes +the whole hostname: a Domain with `routes`, another proxy server or upstream, +or another `tls.mode` is refused (`service_kibana_domain`). Apply the Domain +with `cloudfall domains apply` and converge the services: the role sets +`server.publicBaseUrl` to `https://kibana.example.test`, so the links Kibana +generates start with that address, and marks the session cookie secure. +Kibana itself still listens on loopback. + +What that exposes: the login is Kibana's own form, checked against the users +of the cluster, and nothing else stands between the internet and that form. +Every declared password is then open to guessing from anywhere, so make each +one long. `config validate` warns `KIBANA_PUBLISHED` for a published Kibana +to say so. Limiting who may reach it by address, and a login in front of +Kibana's own, are not part of this service. + +## A version change + +Kibana runs at the `version` of the Elasticsearch service and follows a +change of it, in the order Elastic gives: every node first, then Kibana. +Change `version` in `search-main` to a later patch or minor of the same major +and converge the services: + +- every node of the cluster moves to the new version first +- before Kibana's package changes, the role reads the version of every node + (`GET /_nodes`). While a node is still older, Kibana stays as it is and the + converge stops with `PRECONDITION` (`service_kibana_node_older`), naming the + nodes behind. Converge them, then run the command again +- Kibana restarts on the new version and migrates its saved objects; the + converge waits until Kibana reports itself available, and stops when it + does not + +A Kibana newer than the declared version, or of another major, is refused +before anything changes: Elastic does not support Kibana newer than a node, +nor against a cluster of another major. + ## Where the dashboards are backed up Elasticsearch groups Kibana's system indices as the feature state `kibana`. @@ -109,3 +382,35 @@ services brings Kibana back as it was: 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. + +## Audit + +`cloudfall audit` reads each Kibana service from the observation of its +server. Inspect reads Kibana and its node as the `cloudfall` account, and +keeps names and privileges only: the keystore by setting name, never a +value, and of each user only the Kibana roles it holds. + +| Check | Drift when | +| --- | --- | +| `kibana.version[]` | The installed `kibana` package is not the Elasticsearch service's declared `version` | +| `kibana.unit[]` | `kibana.service` is not enabled and running | +| `kibana.configuration[]` | `/etc/kibana/kibana.yml` differs from the rendered one (a changed or removed setting, or one the role does not write, named without its value), or `node.options` gives another heap | +| `services.bind[]` | Kibana listens on an address that is not loopback, such as after `server.host` was changed by hand and Kibana restarted | +| `kibana.status[]` | The overall level of `GET /api/status` is not `available`, or Kibana does not answer | +| `kibana.roles[]` | `cloudfall-kibana-view` or `cloudfall-kibana-edit` is missing or differs from what the role writes: another base privilege, a feature privilege, another space, a privilege in Elasticsearch, or another marker | +| `kibana.users[]` | A declared user of the Elasticsearch service holds another Kibana role than its `access` gives, such as `support` given `cloudfall-kibana-edit` by hand, or a user with no `access` given one | +| `kibana.keystore[]` | One of the three encryption keys is not in Kibana's keystore: an unmet S-011 requirement (the package requirement is `kibana.version`) | + +A user the Elasticsearch service does not declare is not Cloudfall's: one +that holds a Kibana role is listed as unmanaged in the message, not counted +as drift. A check whose evidence inspect could not read, for example when the +`cloudfall` password is not on the server, is `unknown`, not drift. + +```console +uv run cloudfall-engine inventory render --output tmp/ansible-inventory.json +uv run cloudfall-engine playbook run inspect --inventory tmp/ansible-inventory.json --extra-vars cloudfall_inspect_output_directory=$PWD/tmp/observed +uv run cloudfall audit --observed tmp/observed +``` + +Kibana's log goes to the journal (`journalctl -u kibana.service`), which the +logging collector already ships. The kind has no metrics. diff --git a/docs/specs/024-kibana-service.md b/docs/specs/024-kibana-service.md index 88bb1ab6..89ab2e52 100644 --- a/docs/specs/024-kibana-service.md +++ b/docs/specs/024-kibana-service.md @@ -1,6 +1,6 @@ # S-024: Kibana service -status: approved +status: built serves: G-1, G-3 ## Problem @@ -366,4 +366,93 @@ Touches `config/schemas/v1/service.schema.json`, `config/examples/services/`, ## Verification -No criterion is verified yet. +Checked on main at 785d7a0 with the audit of #582 on top. No criterion about a live host has +run on one: Kibana and Elasticsearch were not installed on a Debian 13 host for any of them. +They are proven by evaluating the role's conditions, templates and host variables with +Ansible's own templating, and by replaying the role's tasks in `ansible-playbook` on +localhost against stand-ins: `kibana-keystore` and `elasticsearch-service-tokens` +(`engine/tests/kibana_node.py`), an HTTP stand-in answering Elasticsearch's security API and +Kibana's role API (`test_s024_kibana_access.py`), a stand-in node answering `GET /_nodes` +(`test_s024_9_kibana_version_change.py`), and the fake node of the S-012 snapshot tests. A +live proving run is still owed before the stable release. Per criterion: + +- S-024-1: `test_s024_1_the_declaration_validates` runs `cloudfall config validate` on the + declaration (exit 0), and `test_s024_1_render_carries_kibana_the_cluster_and_analyst` runs + `cloudfall-engine inventory render`: the Kibana service, `search-main` and `analyst` with its + Kibana access are in it (`test_s024_1_*` in `test_s024_kibana.py` cover the inventory too). + Holds +- S-024-2: `test_s024_2_examples_without_kibana_render_byte_identical` renders + `config/examples` and compares it with the golden inventory byte for byte; `cloudfall config + validate --project config/examples` exits 0. Holds +- S-024-3: on templates and stand-ins only, not on a fresh Debian 13 host: the package task + installs `kibana=` and holds it, `kibana.yml` answers on loopback and + reads the node, `node.options` gets the declared heap, a listener off loopback and a + dashboard request not sent to the login form stop the converge, and the converge waits until + Kibana reports itself available at the version (`test_s024_3_*` in + `test_s024_kibana_role.py`); the server's requirements are the package at the cluster's + version and three keys (`test_s024_3_the_server_needs_kibana_at_the_clusters_version_and_three_keys`). + A real Kibana's status, Node.js process, listener and login page were not observed +- S-024-4: replayed on the stand-ins: a second run of the keystore and token tasks gives + `changed=0` and notifies no restart + (`test_s024_4_a_second_converge_changes_nothing_and_restarts_nothing`), and the heap refusal + and every other refusal come before any task that changes the host + (`test_s024_4_*`). A whole `services.yml` run with no restart was not checked on a live host +- S-024-5: on the stand-ins: Kibana gets a token of `elastic/kibana` from the node's + `service_tokens` file, made again when the keystore lost it, every task that sees a secret is + `no_log`, no secret is in `kibana.yml`, and no task touches `kibana_system` + (`test_s024_5_*` in `test_s024_kibana_role.py`); the keys are generated secrets of the store, + staged `0600`, in no output, and a missing one stops before any playbook (`test_s024_5_*` in + `test_s024_kibana_converge.py`); the node read is `no_log` + (`test_s024_5_the_node_read_is_no_log`), and inspect keeps no password or digest in the + evidence audit reads (`test_s024_5_inspect_keeps_no_password_or_digest_in_the_evidence`; a + hand-written setting's value is in no finding, + `test_kibana_yml_changed_by_hand_is_drift`). The journal and the `kibana_system` hash of a + live node were not read +- S-024-6: replayed against the HTTP stand-in, not a live Kibana: both roles are written + through Kibana's role API with no index privilege, `analyst` holds the edit role and + `support` the view role next to their own roles, and a second converge puts nothing + (`test_s024_6_*`). Logging in, building a data view and a dashboard, not seeing `billing-1`, + and the refused save were not tried +- S-024-7: replayed against the same stand-in: a user `kibana.users` does not name keeps its + own role alone, removing `analyst` takes only its Kibana role, and `services.yml` hands the + cluster's home the access its Kibana names (`test_s024_7_*`). Opening Kibana as such a user + and the search of `crm-1` were not tried live +- S-024-8: on templates: `kibana.yml` links to `https://kibana.example.test` with secure + cookies, an unpublished Kibana keeps its loopback settings, a Domain the server does not + hold is refused, and the Domain's nginx site fronts Kibana with the certificate of its name + (`test_s024_8_*`). The certificate, a login through it and the cookie in a browser were not + checked live +- S-024-9: replayed against the stand-in node: the nodes older than the declared version are + named and the converge stops with `PRECONDITION` and Kibana's package unchanged, every node + is read before the package changes, the held package moves only once every node is on the + new version, Kibana converges after every node, and the converge waits for its migration + (`test_s024_9_*`). A real package upgrade, the saved-object migration and the dashboard + afterwards were not run on a live host +- S-024-10: S-012's backup script runs against the fake node, whose snapshot then lists the + feature state `kibana`, and asks for every feature state; the guide's restore steps stop + Kibana, restore the feature state `kibana` alone and start Kibana (`test_s024_10_*`). A + restore on a live cluster and the dashboard opening again were not tried +- S-024-11: on the stand-ins: a rebuilt empty host gets the store's three keys in its keystore + and a new token, and a second converge keeps them (`test_s024_11_*` in + `test_s024_10_11_kibana_dashboards.py`); every converge stages the stored keys and the store + never replaces a held key (`test_s024_11_*` in `test_s024_11_kibana_rebuild_keys.py`). + `analyst` logging in on a rebuilt live server was not tried +- S-024-12: every refusal under Validation runs `cloudfall config validate` and asserts + `CONFIG_INVALID` and its code, and a declaration with `domain` validates with + `KIBANA_PUBLISHED` (`test_s024_12_*`). Holds +- S-024-13: `audit` over observation fixtures reports drift for a Kibana version other than + the Elasticsearch service's declared one, a stopped or disabled unit, `server.host` changed + by hand to `0.0.0.0` (`kibana.configuration`, and `services.bind` once Kibana listens + there), and `support` given `cloudfall-kibana-edit` by hand, while a Kibana converged as + declared, its `kibana.yml` rendered from the role's own template in every shape, is + compliant (`test_s024_13_*` in `test_s024_13_kibana_audit.py`); the other Audit cases + (Kibana's status, the two roles, a user without access given a role, the heap, the keystore) + are covered there too, and an Elasticsearch-only project gets no `kibana.` check. Inspect's + reading of Kibana's files, keystore, status, roles and users runs through Ansible's + templating (`test_s024_13_inspect_reads_kibanas_files_keystore_status_roles_and_users`). + Not against a live inspect + +Still open before the stable release: + +- S-024-3 to S-024-11, S-024-13: a proving run on a live Debian 13 host with Elasticsearch and + Kibana, which none of these criteria has had diff --git a/engine/ansible/playbooks/inspect.yml b/engine/ansible/playbooks/inspect.yml index 4ea23705..a12c3b07 100644 --- a/engine/ansible/playbooks/inspect.yml +++ b/engine/ansible/playbooks/inspect.yml @@ -44,6 +44,21 @@ | selectattr('server', 'equalto', cloudfall_server_id) | list }} + # A Kibana service is read on its server, a node of the cluster it + # reads (S-024), which the server's Elasticsearch services hold + cloudfall_inspect_kibana_services: >- + {{ + cloudfall_services | default([]) + | selectattr('serviceKind', 'equalto', 'kibana') + | selectattr('server', 'equalto', cloudfall_server_id) + | list + }} + cloudfall_inspect_kibana_elasticsearch_services: >- + {{ + cloudfall_services | default([]) + | selectattr('serviceKind', 'equalto', 'elasticsearch') + | list + }} # A RabbitMQ service's accounts are the cluster's, read on its home cloudfall_inspect_rabbitmq_services: >- {{ diff --git a/engine/ansible/roles/cloudfall_inspect/defaults/main.yml b/engine/ansible/roles/cloudfall_inspect/defaults/main.yml index a930e1cc..2b7ee299 100644 --- a/engine/ansible/roles/cloudfall_inspect/defaults/main.yml +++ b/engine/ansible/roles/cloudfall_inspect/defaults/main.yml @@ -79,5 +79,40 @@ cloudfall_inspect_mariadb_queries: SELECT DISTINCT REPLACE(d.Db, '\\_', '_') FROM mysql.db d JOIN mysql.roles_mapping m ON m.User = d.User AND m.Host = d.Host WHERE m.Role = 'cloudfall-managed' AND m.Admin_option = 'N' +# The Kibana services of this server (S-024), at most one, and the +# Elasticsearch services of the server, among which each one's cluster is +cloudfall_inspect_kibana_services: [] +cloudfall_inspect_kibana_elasticsearch_services: [] +cloudfall_inspect_kibana_configuration_directory: /etc/kibana +cloudfall_inspect_kibana_keystore_tool: /usr/share/kibana/bin/kibana-keystore +# The two roles the Kibana role keeps (cloudfall.kibana.ROLE_NAMES) +cloudfall_inspect_kibana_role_names: + - cloudfall-kibana-view + - cloudfall-kibana-edit +# The Elasticsearch service the Kibana service reads, found by its id +cloudfall_inspect_kibana_elasticsearch: >- + {{ + cloudfall_inspect_kibana_elasticsearch_services + | selectattr('id', 'equalto', cloudfall_inspect_kibana_service.kibana.elasticsearch) + | first | default({}) + }} +# Where the Kibana role reaches Kibana, and Kibana reaches the node +cloudfall_inspect_kibana_url: >- + http://{{ + ('[' ~ cloudfall_inspect_kibana_service.bind.address ~ ']') + if ':' in cloudfall_inspect_kibana_service.bind.address + else cloudfall_inspect_kibana_service.bind.address + }}:{{ cloudfall_inspect_kibana_service.bind.port }} +cloudfall_inspect_kibana_elasticsearch_url: >- + {%- set remote = cloudfall_inspect_kibana_elasticsearch.elasticsearch.remoteAccess + | default(none) -%} + {%- if remote is none -%} + http://{{ cloudfall_inspect_kibana_elasticsearch.bind.address }}:{{ + cloudfall_inspect_kibana_elasticsearch.bind.port }} + {%- else -%} + https://{{ ('[' ~ remote.listenAddress ~ ']') if ':' in remote.listenAddress + else remote.listenAddress }}:{{ + cloudfall_inspect_kibana_elasticsearch.bind.port }} + {%- endif -%} # The bundled Grafana dashboards on a logging backend (S-016); the backend role writes here cloudfall_inspect_grafana_dashboards: /etc/grafana/dashboards/cloudfall diff --git a/engine/ansible/roles/cloudfall_inspect/meta/argument_specs.yml b/engine/ansible/roles/cloudfall_inspect/meta/argument_specs.yml index a8dcd3fb..20a12dd2 100644 --- a/engine/ansible/roles/cloudfall_inspect/meta/argument_specs.yml +++ b/engine/ansible/roles/cloudfall_inspect/meta/argument_specs.yml @@ -45,3 +45,13 @@ argument_specs: elements: dict default: [] description: The MariaDB services of this server, whose accounts are read + cloudfall_inspect_kibana_services: + type: list + elements: dict + default: [] + description: The Kibana services of this server, at most one + cloudfall_inspect_kibana_elasticsearch_services: + type: list + elements: dict + default: [] + description: The Elasticsearch services of this server, one of them the cluster Kibana reads diff --git a/engine/ansible/roles/cloudfall_inspect/tasks/kibana.yml b/engine/ansible/roles/cloudfall_inspect/tasks/kibana.yml new file mode 100644 index 00000000..11d1f28d --- /dev/null +++ b/engine/ansible/roles/cloudfall_inspect/tasks/kibana.yml @@ -0,0 +1,199 @@ +--- +# The Kibana service of the server (S-024), for audit: the managed kibana.yml +# and node.options as text, so a hand edit is drift before Kibana restarts +# with it; the names of the settings its keystore holds, never their values; +# the overall level Kibana reports; the two roles the Kibana role keeps, as +# Kibana's role API answers them; and which Kibana roles each user of the +# cluster holds. Kibana and the node are read as the cloudfall account, whose +# password is read on the node and used in no_log tasks only. No token, key, +# password or hash leaves the host: the user answer is reduced to names and +# Kibana roles before it is attached. +- name: Look for the managed Kibana configuration + ansible.builtin.stat: + path: "{{ cloudfall_inspect_kibana_configuration_directory }}/kibana.yml" + get_checksum: false + register: cloudfall_inspect_kibana_file + +- name: Read the managed Kibana configuration + ansible.builtin.slurp: + src: "{{ cloudfall_inspect_kibana_configuration_directory }}/kibana.yml" + register: cloudfall_inspect_kibana_content + when: cloudfall_inspect_kibana_file.stat.isreg | default(false) + +- name: Look for Kibana's Node.js options + ansible.builtin.stat: + path: "{{ cloudfall_inspect_kibana_configuration_directory }}/node.options" + get_checksum: false + register: cloudfall_inspect_kibana_options_file + +- name: Read Kibana's Node.js options + ansible.builtin.slurp: + src: "{{ cloudfall_inspect_kibana_configuration_directory }}/node.options" + register: cloudfall_inspect_kibana_options + when: cloudfall_inspect_kibana_options_file.stat.isreg | default(false) + +- name: List the settings Kibana's keystore holds + ansible.builtin.command: + argv: + - "{{ cloudfall_inspect_kibana_keystore_tool }}" + - list + environment: + KBN_PATH_CONF: "{{ cloudfall_inspect_kibana_configuration_directory }}" + register: cloudfall_inspect_kibana_keystore + failed_when: false + changed_when: false + check_mode: false + +- name: Look for the cloudfall account password for Kibana + ansible.builtin.stat: + path: "{{ cloudfall_inspect_elasticsearch_password_path }}" + get_checksum: false + register: cloudfall_inspect_kibana_password_file + +- name: Read the cloudfall account password for Kibana + ansible.builtin.slurp: + src: "{{ cloudfall_inspect_elasticsearch_password_path }}" + register: cloudfall_inspect_kibana_password + no_log: true + when: cloudfall_inspect_kibana_password_file.stat.exists + +- name: Read the level Kibana reports + ansible.builtin.uri: + url: "{{ cloudfall_inspect_kibana_url }}/api/status" + url_username: cloudfall + url_password: "{{ cloudfall_inspect_kibana_password.content | b64decode }}" + force_basic_auth: true + status_code: [200, 503] + register: cloudfall_inspect_kibana_status + failed_when: false + no_log: true + when: cloudfall_inspect_kibana_password_file.stat.exists + +- name: Read the roles Kibana keeps + ansible.builtin.uri: + url: "{{ cloudfall_inspect_kibana_url }}/api/security/role/{{ item }}" + url_username: cloudfall + url_password: "{{ cloudfall_inspect_kibana_password.content | b64decode }}" + force_basic_auth: true + status_code: [200, 404] + loop: "{{ cloudfall_inspect_kibana_role_names }}" + register: cloudfall_inspect_kibana_roles + failed_when: false + no_log: true + when: cloudfall_inspect_kibana_password_file.stat.exists + +# Reached as the Kibana role reaches the node: plain HTTP on loopback, or with +# remoteAccess HTTPS on the listen address, verified against the project CA. +- name: Read the users of Kibana's cluster + ansible.builtin.uri: + url: "{{ cloudfall_inspect_kibana_elasticsearch_url }}/_security/user" + ca_path: >- + {{ + cloudfall_inspect_elasticsearch_ca_path + if cloudfall_inspect_kibana_elasticsearch.elasticsearch.remoteAccess is defined + else omit + }} + url_username: cloudfall + url_password: "{{ cloudfall_inspect_kibana_password.content | b64decode }}" + force_basic_auth: true + status_code: 200 + register: cloudfall_inspect_kibana_users + failed_when: false + no_log: true + when: cloudfall_inspect_kibana_password_file.stat.exists + +- name: Attach Kibana evidence + ansible.builtin.set_fact: + cloudfall_inspect_snapshot: >- + {{ + cloudfall_inspect_snapshot | combine( + {'spec': {'kibana': cloudfall_inspect_kibana_evidence}}, + recursive=true + ) + }} + vars: + cloudfall_inspect_kibana_asked: >- + {{ cloudfall_inspect_kibana_password_file.stat.exists | default(false) }} + cloudfall_inspect_kibana_role_answers: >- + {{ + cloudfall_inspect_kibana_roles.results | default([]) + | selectattr('status', 'defined') + | selectattr('status', 'in', [200, 404]) + | list + }} + cloudfall_inspect_kibana_user_answer: >- + {{ + cloudfall_inspect_kibana_users.json + if cloudfall_inspect_kibana_users.status | default(0) == 200 + and cloudfall_inspect_kibana_users.json is mapping + else none + }} + cloudfall_inspect_kibana_evidence: + service: "{{ cloudfall_inspect_kibana_service.id }}" + configurationPath: >- + {{ cloudfall_inspect_kibana_configuration_directory }}/kibana.yml + configuration: >- + {{ + cloudfall_inspect_kibana_content.content | b64decode + if cloudfall_inspect_kibana_file.stat.isreg | default(false) + else none + }} + nodeOptions: >- + {{ + cloudfall_inspect_kibana_options.content | b64decode + if cloudfall_inspect_kibana_options_file.stat.isreg | default(false) + else none + }} + keystore: >- + {{ + cloudfall_inspect_kibana_keystore.stdout_lines + | map('trim') | select | list + if cloudfall_inspect_kibana_keystore.rc | default(1) == 0 + else none + }} + status: + read: "{{ cloudfall_inspect_kibana_asked }}" + level: >- + {{ + cloudfall_inspect_kibana_status.json.status.overall.level + if cloudfall_inspect_kibana_asked + and cloudfall_inspect_kibana_status.status | default(0) in [200, 503] + and cloudfall_inspect_kibana_status.json.status.overall.level + | default(none) is string + else none + }} + # The role's own fields only: its privileges and its metadata + roles: >- + {%- set found = namespace(roles=[]) -%} + {%- for answer in cloudfall_inspect_kibana_role_answers -%} + {%- set role = answer.json | default({}) + if answer.status == 200 and answer.json is defined + and answer.json is mapping else {} -%} + {%- set found.roles = found.roles + [{ + 'name': answer.item, + 'found': answer.status == 200, + 'elasticsearch': role.elasticsearch | default(none), + 'kibana': role.kibana | default(none), + 'metadata': role.metadata | default(none), + }] -%} + {%- endfor -%} + {{ + found.roles + if cloudfall_inspect_kibana_role_answers | length + == cloudfall_inspect_kibana_role_names | length + else none + }} + # Each user that is not built in, with the Kibana roles among its roles: + # never its metadata, which holds Cloudfall's password digest. + userRoles: >- + {%- set held = namespace(users={}) -%} + {%- if cloudfall_inspect_kibana_user_answer is not none -%} + {%- for user in cloudfall_inspect_kibana_user_answer | dict2items + | rejectattr('value.metadata._reserved', 'defined') -%} + {%- set held.users = held.users | combine({ + user.key: user.value.roles | default([]) + | select('in', cloudfall_inspect_kibana_role_names) | list + }) -%} + {%- endfor -%} + {%- endif -%} + {{ held.users if cloudfall_inspect_kibana_user_answer is not none else none }} diff --git a/engine/ansible/roles/cloudfall_inspect/tasks/main.yml b/engine/ansible/roles/cloudfall_inspect/tasks/main.yml index 641ce531..57f1e1e0 100644 --- a/engine/ansible/roles/cloudfall_inspect/tasks/main.yml +++ b/engine/ansible/roles/cloudfall_inspect/tasks/main.yml @@ -742,6 +742,13 @@ }} when: cloudfall_inspect_mariadb_services | length > 0 +- name: Collect Kibana evidence + ansible.builtin.include_tasks: kibana.yml + loop: "{{ cloudfall_inspect_kibana_services }}" + loop_control: + loop_var: cloudfall_inspect_kibana_service + label: "{{ cloudfall_inspect_kibana_service.id }}" + - name: Collect RabbitMQ account evidence ansible.builtin.include_tasks: rabbitmq_accounts.yml loop: "{{ cloudfall_inspect_rabbitmq_services }}" diff --git a/engine/tests/test_s024_13_kibana_inspect.py b/engine/tests/test_s024_13_kibana_inspect.py new file mode 100644 index 00000000..e03b2fc5 --- /dev/null +++ b/engine/tests/test_s024_13_kibana_inspect.py @@ -0,0 +1,389 @@ +"""The Kibana evidence inspect collects for audit (S-024-13). + +Inspect needs a host with Kibana and a node to answer, so the evidence it +attaches is evaluated with Ansible's own templating from what Kibana, the +node and ``kibana-keystore`` answer; the tasks that send the cloudfall +account's password are read for ``no_log``. A live inspect of a Kibana +server is listed in the pull request as unverified. +""" + +from __future__ import annotations + +import base64 +import json +from pathlib import Path +from typing import Any, cast + +import pytest +import yaml +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar, trust_as_template + +ROOT = Path(__file__).parents[2] +INSPECT = ROOT / "engine" / "ansible" / "roles" / "cloudfall_inspect" +PLAYBOOK = ROOT / "engine" / "ansible" / "playbooks" / "inspect.yml" +VIEW = "cloudfall-kibana-view" +EDIT = "cloudfall-kibana-edit" +PASSWORD = "synthetic-cloudfall-value" # noqa: S105 - grepped for +DIGEST = "synthetic-password-digest-77ab" +KIBANA_YML = 'server.host: "127.0.0.1"\nserver.port: 5601\n' +NODE_OPTIONS = "--max-old-space-size=1024\n" + + +def _yaml(path: Path) -> Any: # noqa: ANN401 - a YAML document of any shape. + return yaml.safe_load(path.read_text(encoding="utf-8")) + + +def _trusted(value: object) -> object: + """Trust the role's own files as templates, as Ansible trusts them.""" + if isinstance(value, str): + return trust_as_template(value) + if isinstance(value, dict): + return {key: _trusted(item) for key, item in value.items()} + if isinstance(value, list): + return [_trusted(item) for item in value] + return value + + +def _tasks() -> list[dict[str, Any]]: + tasks = DataLoader().load_from_file(str(INSPECT / "tasks" / "kibana.yml")) + assert isinstance(tasks, list) + return cast("list[dict[str, Any]]", tasks) + + +def _task(name: str) -> dict[str, Any]: + return next(task for task in _tasks() if task["name"] == name) + + +def _kibana(**bind: object) -> dict[str, object]: + return { + "id": "search-kibana", + "serviceKind": "kibana", + "server": "h1", + "bind": {"address": "127.0.0.1", "port": 5601, **bind}, + "kibana": {"elasticsearch": "search-main", "heapMb": 1024, "users": []}, + } + + +def _search_main(**elasticsearch: object) -> dict[str, object]: + return { + "id": "search-main", + "serviceKind": "elasticsearch", + "server": "h1", + "bind": {"address": "127.0.0.1", "port": 9200}, + "elasticsearch": {"version": "9.2.4", "nodes": ["h1"], **elasticsearch}, + } + + +def _encoded(text: str) -> str: + return base64.b64encode(text.encode()).decode() + + +def _role_answer(name: str, base: str) -> dict[str, object]: + return { + "item": name, + "status": 200, + "json": { + "name": name, + "elasticsearch": {"cluster": [], "indices": [], "run_as": []}, + "kibana": [{"base": [base], "feature": {}, "spaces": ["*"]}], + "metadata": {"cloudfall_managed_by": "search-kibana"}, + "transient_metadata": {"enabled": True}, + }, + } + + +def _user(*roles: str, reserved: bool = False) -> dict[str, object]: + metadata: dict[str, object] = ( + {"_reserved": True} + if reserved + else { + "cloudfall_managed_by": "search-main", + "cloudfall_password_digest": DIGEST, + } + ) + return {"roles": list(roles), "enabled": True, "metadata": metadata} + + +ANSWERS: dict[str, object] = { + "cloudfall_inspect_kibana_file": {"stat": {"isreg": True}}, + "cloudfall_inspect_kibana_content": {"content": _encoded(KIBANA_YML)}, + "cloudfall_inspect_kibana_options_file": {"stat": {"isreg": True}}, + "cloudfall_inspect_kibana_options": {"content": _encoded(NODE_OPTIONS)}, + "cloudfall_inspect_kibana_keystore": { + "rc": 0, + "stdout_lines": [ + "elasticsearch.serviceAccountToken", + "xpack.security.encryptionKey", + ], + }, + "cloudfall_inspect_kibana_password_file": {"stat": {"exists": True}}, + "cloudfall_inspect_kibana_password": {"content": _encoded(PASSWORD)}, + "cloudfall_inspect_kibana_status": { + "status": 200, + "json": {"status": {"overall": {"level": "available"}}}, + }, + "cloudfall_inspect_kibana_roles": { + "results": [_role_answer(VIEW, "read"), _role_answer(EDIT, "all")] + }, + "cloudfall_inspect_kibana_users": { + "status": 200, + "json": { + "analyst": _user("analyst", EDIT), + "support": _user("support", VIEW, EDIT), + "crm": _user("crm"), + "elastic": _user("superuser", reserved=True), + }, + }, +} + + +def _variables(**answers: object) -> dict[str, object]: + attach = _task("Attach Kibana evidence") + return { + **cast("dict[str, object]", _trusted(_yaml(INSPECT / "defaults" / "main.yml"))), + **cast("dict[str, object]", _trusted(attach["vars"])), + "omit": "__omit__", + "cloudfall_inspect_kibana_service": _kibana(), + "cloudfall_inspect_kibana_elasticsearch_services": [_search_main()], + **ANSWERS, + **answers, + } + + +def _template(expression: str, variables: dict[str, object]) -> object: + templar = Templar(loader=DataLoader(), variables=variables) + return templar.template(trust_as_template(expression)) + + +def _evidence(**answers: object) -> dict[str, object]: + evidence = _template( + "{{ cloudfall_inspect_kibana_evidence }}", _variables(**answers) + ) + assert isinstance(evidence, dict) + return cast("dict[str, object]", evidence) + + +# proves: S-024-13 +def test_s024_13_inspect_reads_kibanas_files_keystore_status_roles_and_users() -> None: + evidence = _evidence() + + assert evidence == { + "service": "search-kibana", + "configurationPath": "/etc/kibana/kibana.yml", + "configuration": KIBANA_YML, + "nodeOptions": NODE_OPTIONS, + "keystore": [ + "elasticsearch.serviceAccountToken", + "xpack.security.encryptionKey", + ], + "status": {"read": True, "level": "available"}, + "roles": [ + { + "name": VIEW, + "found": True, + "elasticsearch": {"cluster": [], "indices": [], "run_as": []}, + "kibana": [{"base": ["read"], "feature": {}, "spaces": ["*"]}], + "metadata": {"cloudfall_managed_by": "search-kibana"}, + }, + { + "name": EDIT, + "found": True, + "elasticsearch": {"cluster": [], "indices": [], "run_as": []}, + "kibana": [{"base": ["all"], "feature": {}, "spaces": ["*"]}], + "metadata": {"cloudfall_managed_by": "search-kibana"}, + }, + ], + # support was given the edit role by hand; elastic is built in + "userRoles": {"analyst": [EDIT], "support": [VIEW, EDIT], "crm": []}, + } + + +# proves: S-024-5 +def test_s024_5_inspect_keeps_no_password_or_digest_in_the_evidence() -> None: + evidence = json.dumps(_evidence()) + + assert PASSWORD not in evidence + assert DIGEST not in evidence + # Every task that sends the cloudfall password, or reads it, logs nothing + for task in _tasks(): + module = next( + ( + value + for key, value in task.items() + if key in {"ansible.builtin.uri", "ansible.builtin.slurp"} + ), + None, + ) + if module is None: + continue + sends = "url_password" in module + reads = "elasticsearch_password_path" in str(module.get("src", "")) + if sends or reads: + assert task.get("no_log") is True, task["name"] + + +@pytest.mark.parametrize( + ("answers", "expected"), + [ + pytest.param( + { + "cloudfall_inspect_kibana_password_file": {"stat": {"exists": False}}, + "cloudfall_inspect_kibana_status": {"skipped": True}, + "cloudfall_inspect_kibana_roles": {"skipped": True}, + "cloudfall_inspect_kibana_users": {"skipped": True}, + }, + { + "status": {"read": False, "level": None}, + "roles": None, + "userRoles": None, + }, + id="no cloudfall password on the server", + ), + pytest.param( + { + "cloudfall_inspect_kibana_status": {"status": -1, "msg": "refused"}, + "cloudfall_inspect_kibana_roles": { + "results": [ + {"item": VIEW, "status": -1}, + {"item": EDIT, "status": -1}, + ] + }, + }, + {"status": {"read": True, "level": None}, "roles": None}, + id="Kibana does not answer", + ), + pytest.param( + { + "cloudfall_inspect_kibana_status": { + "status": 503, + "json": {"status": {"overall": {"level": "unavailable"}}}, + } + }, + {"status": {"read": True, "level": "unavailable"}}, + id="Kibana reports itself unavailable", + ), + pytest.param( + { + "cloudfall_inspect_kibana_roles": { + "results": [ + {"item": VIEW, "status": 404, "json": {}}, + _role_answer(EDIT, "all"), + ] + } + }, + { + "roles": [ + { + "name": VIEW, + "found": False, + "elasticsearch": None, + "kibana": None, + "metadata": None, + }, + { + "name": EDIT, + "found": True, + "elasticsearch": {"cluster": [], "indices": [], "run_as": []}, + "kibana": [{"base": ["all"], "feature": {}, "spaces": ["*"]}], + "metadata": {"cloudfall_managed_by": "search-kibana"}, + }, + ] + }, + id="a deleted role", + ), + pytest.param( + { + "cloudfall_inspect_kibana_file": {"stat": {"exists": False}}, + "cloudfall_inspect_kibana_content": {"skipped": True}, + "cloudfall_inspect_kibana_options_file": {"stat": {"exists": False}}, + "cloudfall_inspect_kibana_options": {"skipped": True}, + "cloudfall_inspect_kibana_keystore": { + "rc": 1, + "stdout_lines": [], + }, + "cloudfall_inspect_kibana_users": {"status": 401, "json": {}}, + }, + { + "configuration": None, + "nodeOptions": None, + "keystore": None, + "userRoles": None, + }, + id="no files, no keystore, and the node refusing", + ), + ], +) +def test_inspect_reads_a_kibana_it_cannot_fully_read( + answers: dict[str, object], expected: dict[str, object] +) -> None: + evidence = _evidence(**answers) + + assert {key: evidence[key] for key in expected} == expected + + +@pytest.mark.parametrize( + ("kibana", "elasticsearch", "urls"), + [ + pytest.param( + {}, + {}, + ("http://127.0.0.1:5601", "http://127.0.0.1:9200"), + id="loopback", + ), + pytest.param( + {"address": "::1"}, + {"remoteAccess": {"listenAddress": "10.0.0.11"}}, + ("http://[::1]:5601", "https://10.0.0.11:9200"), + id="IPv6 loopback and a node with remote access", + ), + ], +) +def test_inspect_reaches_kibana_and_the_node_as_the_kibana_role_does( + kibana: dict[str, object], + elasticsearch: dict[str, object], + urls: tuple[str, str], +) -> None: + variables = _variables( + cloudfall_inspect_kibana_service=_kibana(**kibana), + cloudfall_inspect_kibana_elasticsearch_services=[ + _search_main(nodes=["h1"], **elasticsearch) + ], + ) + + assert ( + _template("{{ cloudfall_inspect_kibana_url }}", variables), + _template("{{ cloudfall_inspect_kibana_elasticsearch_url }}", variables), + ) == urls + + +def test_inspect_reads_the_kibana_service_of_the_server_only() -> None: + (play,) = _yaml(PLAYBOOK) + (role,) = play["roles"] + services = [ + _kibana(), + {**_kibana(), "id": "other-kibana", "server": "h2"}, + _search_main(), + {"id": "jobs", "serviceKind": "rabbitmq", "server": "h1"}, + ] + variables: dict[str, object] = { + "cloudfall_services": services, + "cloudfall_server_id": "h1", + } + + kibana = _template(role["cloudfall_inspect_kibana_services"], variables) + clusters = _template( + role["cloudfall_inspect_kibana_elasticsearch_services"], variables + ) + + assert [service["id"] for service in cast("list[dict[str, str]]", kibana)] == [ + "search-kibana" + ] + assert [service["id"] for service in cast("list[dict[str, str]]", clusters)] == [ + "search-main" + ] + # A project without Kibana reads nothing more + assert _template( + role["cloudfall_inspect_kibana_services"], + {"cloudfall_services": [_search_main()], "cloudfall_server_id": "h1"}, + ) == [] diff --git a/sdk/src/cloudfall/audit.py b/sdk/src/cloudfall/audit.py index 37fae9b1..48eacb21 100644 --- a/sdk/src/cloudfall/audit.py +++ b/sdk/src/cloudfall/audit.py @@ -24,6 +24,10 @@ remote_access_rules_for_server, service_remote_access, ) +from cloudfall.kibana import EDIT_ROLE as KIBANA_EDIT_ROLE +from cloudfall.kibana import ROLE_NAMES as KIBANA_ROLE_NAMES +from cloudfall.kibana import VIEW_ROLE as KIBANA_VIEW_ROLE +from cloudfall.kibana import KibanaEncryptionKey from cloudfall.mariadb import RESERVED_USER_NAMES as RESERVED_MARIADB_USER_NAMES from cloudfall.mariadb import SYSTEM_DATABASES as MARIADB_SYSTEM_DATABASES from cloudfall.mariadb import MariadbReplicationRole @@ -44,6 +48,7 @@ from cloudfall.rabbitmq_cluster import node_name as rabbitmq_node_name from cloudfall.requirements import ( ELASTICSEARCH_PACKAGE, + KIBANA_PACKAGE, MARIADB_CA_PATH, MARIADB_CERTIFICATE_PATH, MARIADB_KEY_PATH, @@ -69,6 +74,7 @@ BaselineInventory, ComponentInventory, ConfigurationFileRequirement, + DomainInventory, ElasticsearchService, FirewallRequirement, LoggingStackInventory, @@ -98,6 +104,15 @@ _MARIADB_UPSTREAM_VERSION = re.compile(r"^(?:\d+:)?(\d+\.\d+\.\d+)") _MARIADB_SETTINGS_SECTION = "mariadbd" _MARIADB_THREAD_RUNNING = "Yes" +KIBANA_UNIT = "kibana.service" +KIBANA_CONFIGURATION_DIRECTORY = "/etc/kibana" +KIBANA_CA_PATH = f"{KIBANA_CONFIGURATION_DIRECTORY}/elasticsearch-ca.crt" +"""Where the Kibana role copies the project CA the node's HTTPS is verified against.""" +KIBANA_AVAILABLE_LEVEL = "available" +_KIBANA_HEAP_OPTION = "--max-old-space-size" +_KIBANA_ROLE_BASES = {KIBANA_VIEW_ROLE: "read", KIBANA_EDIT_ROLE: "all"} +"""Kibana's base privilege each role the Kibana role keeps holds on every space.""" +_KIBANA_ELASTICSEARCH_PRIVILEGES = ("cluster", "indices", "run_as", "remote_indices") class AuditStatus(StrEnum): @@ -238,6 +253,7 @@ def audit_inventory( for service in inventory.services if service.rabbitmq is not None and is_rabbitmq_cluster(service) } + kibana = _kibana_contexts(inventory) audits = tuple( _audit_server( server, @@ -267,6 +283,11 @@ def audit_inventory( and server.resource_id in service.elasticsearch.nodes ), rabbitmq_nodes=rabbitmq_nodes, + kibana=tuple( + context + for context in kibana + if context.service.server_id == server.resource_id + ), ) for server in inventory.servers ) @@ -301,6 +322,7 @@ def _audit_server( # noqa: PLR0913 - one audit, many evidence sources. dashboards: Mapping[str, str] | None = None, elasticsearch_nodes: tuple[ServiceInventory, ...] = (), rabbitmq_nodes: Mapping[ResourceId, tuple[str, ...]] | None = None, + kibana: tuple[_KibanaContext, ...] = (), ) -> ServerAudit: if snapshot is None: check = AuditCheck( @@ -354,6 +376,8 @@ def _audit_server( # noqa: PLR0913 - one audit, many evidence sources. for service in services: checks.extend(_audit_mariadb_server(service, snapshot)) checks.extend(_audit_mariadb_accounts(services, snapshot)) + for context in kibana: + checks.extend(_audit_kibana(context, snapshot)) checks.extend(_audit_rabbitmq_accounts(services, snapshot)) checks.extend(_audit_rabbitmq_cluster(services, rabbitmq_nodes, snapshot)) checks.extend(_audit_alert_rules(alert_rules, snapshot)) @@ -1449,6 +1473,448 @@ def _audit_elasticsearch_users( return tuple(checks) +@dataclass(frozen=True, slots=True) +class _KibanaContext: + """A Kibana service, the Elasticsearch service it reads, and its Domain.""" + + service: ServiceInventory + cluster: ServiceInventory + domain: DomainInventory | None + + +def _kibana_contexts(inventory: PlatformInventory) -> tuple[_KibanaContext, ...]: + """Pair each Kibana service with its cluster and Domain, which validation found.""" + services = {service.resource_id: service for service in inventory.services} + domains = {domain.resource_id: domain for domain in inventory.domains} + contexts: list[_KibanaContext] = [] + for service in inventory.services: + kibana = service.kibana + if kibana is None: + continue + contexts.append( + _KibanaContext( + service=service, + cluster=services[kibana.elasticsearch], + domain=None if kibana.domain is None else domains[kibana.domain], + ) + ) + return tuple(contexts) + + +def _url_host(address: str) -> str: + """Return ``address`` as a URL's host: an IPv6 address in brackets.""" + return f"[{address}]" if ":" in address else address + + +def kibana_managed_settings( + service: ServiceInventory, + cluster: ServiceInventory, + domain: DomainInventory | None, +) -> dict[str, object]: + """Return the settings the Kibana role writes to ``kibana.yml`` (S-024). + + The file holds these and nothing else: the token and the encryption keys + are in Kibana's keystore. Kibana reaches the node as the role's own calls + do, over plain HTTP on loopback, or over HTTPS verified against the + project CA when the cluster declares ``remoteAccess``. + """ + elasticsearch = cluster.elasticsearch + if service.kibana is None or elasticsearch is None: + message = ( + "not a Kibana service and its Elasticsearch service: " + f"{service.resource_id.value}, {cluster.resource_id.value}" + ) + raise ValueError(message) + address = service.bind.address.value + port = service.bind.port.value + remote_access = elasticsearch.remote_access + node = ( + f"http://{cluster.bind.address.value}:{cluster.bind.port.value}" + if remote_access is None + else f"https://{_url_host(remote_access.listen_address.value)}:" + f"{cluster.bind.port.value}" + ) + settings: dict[str, object] = { + "server.host": address, + "server.port": port, + "server.publicBaseUrl": ( + f"http://{_url_host(address)}:{port}" + if domain is None + else f"https://{domain.primary_name.value}" + ), + } + if domain is not None: + settings["xpack.security.secureCookies"] = True + settings["elasticsearch.hosts"] = [node] + if remote_access is not None: + settings["elasticsearch.ssl.certificateAuthorities"] = [KIBANA_CA_PATH] + settings["elasticsearch.ssl.verificationMode"] = "full" + settings["telemetry.optIn"] = False + return settings + + +def _audit_kibana( + context: _KibanaContext, snapshot: ObservedServerSnapshot +) -> tuple[AuditCheck, ...]: + """Check one Kibana service; every check only reads (S-024, Audit). + + The installed package against the Elasticsearch service's ``version``, + the unit, the managed files, the level Kibana reports, the two roles it + keeps, the Kibana roles of the cluster's declared users, and its S-011 + secret requirements: the three keys in its keystore. A listener off + loopback is the ``services.bind`` check every service has. + """ + service = context.service + elasticsearch = cast("ElasticsearchService", context.cluster.elasticsearch) + service_id = service.resource_id.value + version = elasticsearch.version.value + installed = [ + _string(entry, "version") + for entry in _mapping_sequence(snapshot.spec, "packages") + if _string(entry, "name") == KIBANA_PACKAGE.value + ] + unit = _optional_mapping(_mapping(snapshot.spec, "services").get(KIBANA_UNIT)) + unit_observed = ( + None + if unit is None + else {"state": _string(unit, "state"), "status": _string(unit, "status")} + ) + unit_desired = {"state": "running", "status": "enabled"} + evidence = _optional_mapping(snapshot.spec.get("kibana")) + if evidence is not None and _string(evidence, "service") != service_id: + evidence = None + return ( + _comparison( + f"kibana.version[{service_id}]", + { + "version": version, + "elasticsearch": context.cluster.resource_id.value, + }, + {"versions": installed} if installed else None, + matches=installed == [version], + ), + _comparison( + f"kibana.unit[{service_id}]", + {"unit": KIBANA_UNIT, **unit_desired}, + unit_observed, + matches=unit_observed == unit_desired, + ), + _audit_kibana_configuration(context, evidence), + _audit_kibana_status(service, evidence), + _audit_kibana_roles(service, evidence), + _audit_kibana_users(context, evidence), + _audit_kibana_keystore(service, evidence), + ) + + +def _kibana_unknown(check: str, desired: object, reason: str) -> AuditCheck: + return AuditCheck( + check=check, + status=AuditStatus.UNKNOWN, + desired=desired, + observed=None, + message=reason, + ) + + +_KIBANA_NO_EVIDENCE = ( + "the observation carries no Kibana evidence; inspect again with this release" +) + + +def _audit_kibana_configuration( + context: _KibanaContext, evidence: Mapping[str, object] | None +) -> AuditCheck: + """Compare ``kibana.yml`` and the heap in ``node.options`` with the rendered. + + ``kibana.yml`` is the role's alone: a setting it does not write is drift, + listed by name only, since a hand-written value may be a secret. + """ + service = context.service + kibana = service.kibana + if kibana is None: + message = f"not a Kibana service: {service.resource_id.value}" + raise ValueError(message) + settings = kibana_managed_settings(service, context.cluster, context.domain) + heap = {_KIBANA_HEAP_OPTION: kibana.heap_mb.value} + desired = {"kibana.yml": settings, "node.options": heap} + check = f"kibana.configuration[{service.resource_id.value}]" + if evidence is None: + return _kibana_unknown(check, desired, _KIBANA_NO_EVIDENCE) + observed: dict[str, object] = {} + problems: list[str] = [] + content = evidence.get("configuration") + found = _elasticsearch_settings(content) if isinstance(content, str) else None + if not isinstance(content, str): + observed["kibana.yml"] = {"present": False} + problems.append("kibana.yml is missing") + elif found is None: + observed["kibana.yml"] = {"present": True, "readable": False} + problems.append("kibana.yml is no YAML mapping") + else: + observed["kibana.yml"] = {key: found.get(key) for key in settings} + changed = sorted(key for key in settings if found.get(key) != settings[key]) + unmanaged = sorted(key for key in found if key not in settings) + if unmanaged: + observed["unmanagedSettings"] = unmanaged + problems.extend(f"{key} differs" for key in changed) + if unmanaged: + problems.append( + "kibana.yml holds settings the role does not write: " + + ", ".join(unmanaged) + ) + options = evidence.get("nodeOptions") + heaps = _kibana_heaps(options) if isinstance(options, str) else None + observed["node.options"] = ( + {"present": False} + if heaps is None + else {_KIBANA_HEAP_OPTION: heaps[0] if len(heaps) == 1 else heaps} + ) + if heaps != [kibana.heap_mb.value]: + problems.append( + "node.options is missing" + if heaps is None + else f"node.options gives {_KIBANA_HEAP_OPTION} " + f"{', '.join(str(item) for item in heaps) or 'nowhere'}" + ) + return AuditCheck( + check=check, + status=AuditStatus.DRIFT if problems else AuditStatus.COMPLIANT, + desired=desired, + observed=observed, + message="; ".join(problems) if problems else "desired state matches", + ) + + +def _kibana_heaps(content: str) -> list[int | str]: + """Return each ``--max-old-space-size`` an active line of ``node.options`` sets.""" + found: list[int | str] = [] + prefix = f"{_KIBANA_HEAP_OPTION}=" + for raw in content.splitlines(): + line = raw.strip() + if not line.startswith(prefix): + continue + value = line.removeprefix(prefix).strip() + found.append(int(value) if value.isdigit() else value) + return found + + +def _audit_kibana_status( + service: ServiceInventory, evidence: Mapping[str, object] | None +) -> AuditCheck: + """Report a Kibana whose ``GET /api/status`` overall level is not available.""" + check = f"kibana.status[{service.resource_id.value}]" + desired = {"level": KIBANA_AVAILABLE_LEVEL} + if evidence is None: + return _kibana_unknown(check, desired, _KIBANA_NO_EVIDENCE) + status = _mapping(evidence, "status") + if status.get("read") is not True: + return _kibana_unknown( + check, + desired, + "Kibana was not asked: the cloudfall account's password is not on " + "the server", + ) + level = status.get("level") + available = level == KIBANA_AVAILABLE_LEVEL + return AuditCheck( + check=check, + status=AuditStatus.COMPLIANT if available else AuditStatus.DRIFT, + desired=desired, + observed={"level": level}, + message=( + "Kibana reports itself available" + if available + else "Kibana did not answer GET /api/status" + if level is None + else f"Kibana reports itself {level}" + ), + ) + + +def _kibana_role_desired(service_id: str, role: str) -> dict[str, object]: + """Return a role the Kibana role keeps, as its PUT body defines it.""" + return { + "elasticsearchPrivileges": [], + "kibana": [ + {"base": [_KIBANA_ROLE_BASES[role]], "features": [], "spaces": ["*"]} + ], + "metadata": {"cloudfall_managed_by": service_id}, + } + + +def _kibana_role_observed(entry: Mapping[str, object]) -> dict[str, object] | None: + """Reduce Kibana's answer for a role to what the role compares; None if absent.""" + if entry.get("found") is not True: + return None + elasticsearch = _optional_mapping(entry.get("elasticsearch")) or {} + privileges = sorted( + key + for key in _KIBANA_ELASTICSEARCH_PRIVILEGES + if elasticsearch.get(key) not in (None, []) + ) + kibana = [ + { + "base": item.get("base"), + "features": sorted(_optional_mapping(item.get("feature")) or {}), + "spaces": item.get("spaces"), + } + for item in _mapping_values_sequence(entry.get("kibana")) + ] + return { + "elasticsearchPrivileges": privileges, + "kibana": kibana, + "metadata": dict(_optional_mapping(entry.get("metadata")) or {}), + } + + +def _audit_kibana_roles( + service: ServiceInventory, evidence: Mapping[str, object] | None +) -> AuditCheck: + """Compare the two Kibana roles with what the Kibana role writes (S-024). + + Each holds Kibana's base privilege ``read`` or ``all`` on every space, + no feature privilege, no privilege in Elasticsearch, and the service's + marker. + """ + service_id = service.resource_id.value + check = f"kibana.roles[{service_id}]" + roles = sorted(KIBANA_ROLE_NAMES) + desired = {role: _kibana_role_desired(service_id, role) for role in roles} + if evidence is None: + return _kibana_unknown(check, desired, _KIBANA_NO_EVIDENCE) + entries = evidence.get("roles") + if entries is None: + return _kibana_unknown( + check, + desired, + "the roles were not read; inspect again once Kibana answers as the " + "cloudfall account", + ) + answered = { + _string(entry, "name"): entry for entry in _mapping_values_sequence(entries) + } + observed = { + role: None if role not in answered else _kibana_role_observed(answered[role]) + for role in roles + } + differing = [role for role in roles if observed[role] != desired[role]] + return AuditCheck( + check=check, + status=AuditStatus.DRIFT if differing else AuditStatus.COMPLIANT, + desired=desired, + observed=observed, + message=( + "; ".join( + f"{role} is missing" + if observed[role] is None + else f"{role} differs from what the role writes" + for role in differing + ) + if differing + else "desired state matches" + ), + ) + + +def _audit_kibana_users( + context: _KibanaContext, evidence: Mapping[str, object] | None +) -> AuditCheck: + """Compare the Kibana roles each declared user holds with its ``access``. + + A user of the Elasticsearch service that ``kibana.users`` names holds the + role of its access and no other; every other declared user holds none. A + user the service does not declare is not Cloudfall's: one holding a + Kibana role is listed as unmanaged without counting as drift. + """ + service = context.service + kibana = service.kibana + elasticsearch = context.cluster.elasticsearch + if kibana is None or elasticsearch is None: + message = f"not a Kibana service: {service.resource_id.value}" + raise ValueError(message) + check = f"kibana.users[{service.resource_id.value}]" + access = {user.name.value: user.access.role for user in kibana.users} + desired = { + name: [access[name]] if name in access else [] + for name in sorted(user.name.value for user in elasticsearch.users) + } + if evidence is None: + return _kibana_unknown(check, desired, _KIBANA_NO_EVIDENCE) + raw = evidence.get("userRoles") + held = _optional_mapping(raw) + if held is None: + return _kibana_unknown( + check, + desired, + "the cluster's users were not read; inspect again once the node " + "answers as the cloudfall account", + ) + holding = {name: sorted(_strings(held, name)) for name in held} + observed = {name: holding.get(name, []) for name in desired} + differing = [name for name in desired if observed[name] != desired[name]] + unmanaged = sorted( + name for name, roles in holding.items() if name not in desired and roles + ) + problems = [ + f"{name} holds {', '.join(observed[name]) or 'no Kibana role'} where its " + f"access gives {', '.join(desired[name]) or 'none'}" + for name in differing + ] + message = "; ".join(problems) if problems else "desired state matches" + if unmanaged: + message += ( + "; unmanaged (not declared, left as they are): " + + "; ".join( + f"{name} holds {', '.join(holding[name])}" for name in unmanaged + ) + ) + return AuditCheck( + check=check, + status=AuditStatus.DRIFT if differing else AuditStatus.COMPLIANT, + desired=desired, + observed=observed, + message=message, + ) + + +def _audit_kibana_keystore( + service: ServiceInventory, evidence: Mapping[str, object] | None +) -> AuditCheck: + """Check the S-011 secret requirements: the three keys in Kibana's keystore. + + Read by setting name only; the package requirement is ``kibana.version``. + """ + check = f"kibana.keystore[{service.resource_id.value}]" + keys = sorted(key.value for key in KibanaEncryptionKey) + desired = {"settings": keys} + if evidence is None: + return _kibana_unknown(check, desired, _KIBANA_NO_EVIDENCE) + listed = evidence.get("keystore") + if listed is None: + return AuditCheck( + check=check, + status=AuditStatus.DRIFT, + desired=desired, + observed=None, + message="Kibana's keystore could not be listed", + ) + held = set(_strings(evidence, "keystore")) + present = [key for key in keys if key in held] + missing = [key for key in keys if key not in held] + return AuditCheck( + check=check, + status=AuditStatus.DRIFT if missing else AuditStatus.COMPLIANT, + desired=desired, + observed={"settings": present}, + message=( + "the keystore lacks " + ", ".join(missing) + if missing + else "desired state matches" + ), + ) + + def _audit_mariadb_accounts( services: tuple[ServiceInventory, ...], snapshot: ObservedServerSnapshot, diff --git a/sdk/tests/test_s024_13_kibana_audit.py b/sdk/tests/test_s024_13_kibana_audit.py new file mode 100644 index 00000000..51514b20 --- /dev/null +++ b/sdk/tests/test_s024_13_kibana_audit.py @@ -0,0 +1,705 @@ +"""S-024: audit drift of a Kibana service (S-024-13). + +The installed version against the Elasticsearch service's ``version``, the +unit, the managed files, the level Kibana reports, the two Kibana roles, the +Kibana roles of the declared users, and the keys in Kibana's keystore, from +the evidence inspect collects. A listener off loopback is the +``services.bind`` check every service has. The compliant ``kibana.yml`` is +the role's own template rendered with Ansible's templating, so the audit +compares against what a converge writes. +""" + +from __future__ import annotations + +import copy +import json +from pathlib import Path +from typing import TYPE_CHECKING, cast + +import pytest +import yaml +from ansible.parsing.dataloader import DataLoader +from ansible.template import Templar, trust_as_template +from cloudfall.audit import AuditCheck, AuditReport, AuditStatus, audit_inventory +from cloudfall.inventory import PlatformInventory +from cloudfall.observation import load_observations +from cloudfall.validation import validate_config +from elasticsearch_project import elasticsearch_service +from elasticsearch_project import write_project as write_elasticsearch_project +from kibana_project import ( + ANALYST, + SCHEMAS, + kibana_domain, + kibana_service, + search_main, + write_project, +) + +if TYPE_CHECKING: + from collections.abc import Callable + +ROOT = Path(__file__).parents[2] +COMPLIANT = ROOT / "config" / "tests" / "observed" / "compliant" +ROLE = ROOT / "engine" / "ansible" / "roles" / "cloudfall_kibana" +VIEW = "cloudfall-kibana-view" +EDIT = "cloudfall-kibana-edit" +KEYS = [ + "xpack.encryptedSavedObjects.encryptionKey", + "xpack.reporting.encryptionKey", + "xpack.security.encryptionKey", +] +TOKEN_SETTING = "elasticsearch.serviceAccountToken" # noqa: S105 - a setting name +SUPPORT: dict[str, object] = { + **ANALYST, + "name": "support", + "passwordRef": { + "environment": "production", + "path": "/services/search-main", + "key": "SUPPORT_PASSWORD", + }, +} +# A declared user of the cluster with no Kibana access: an application's +APPLICATION: dict[str, object] = { + **ANALYST, + "name": "crm", + "passwordRef": { + "environment": "production", + "path": "/services/search-main", + "key": "CRM_PASSWORD", + }, +} +LISTENERS = ( + "tcp LISTEN 0 511 127.0.0.1:9200 0.0.0.0:*\n" + "tcp LISTEN 0 511 127.0.0.1:5601 0.0.0.0:*" +) +SECRET = "synthetic-hand-written-secret-4f1c9a" # noqa: S105 - grepped for + + +def _inventory( + tmp_path: Path, *, domain: bool = False, **elasticsearch: object +) -> PlatformInventory: + """Return the spec's declaration: analyst edits, support views, crm has none.""" + users = [copy.deepcopy(ANALYST), copy.deepcopy(SUPPORT), copy.deepcopy(APPLICATION)] + kibana = kibana_service( + users=[ + {"name": "analyst", "access": "edit"}, + {"name": "support", "access": "view"}, + ], + domain="search-kibana-site" if domain else None, + ) + project = write_project( + tmp_path / "project", + search_main(users=users, **elasticsearch), + kibana, + domains=(kibana_domain(),) if domain else (), + ) + return PlatformInventory.from_state(validate_config(project, SCHEMAS)) + + +def _trusted(value: object) -> object: + """Trust the role's own files as templates, as Ansible trusts a role's files.""" + if isinstance(value, str): + return trust_as_template(value) + if isinstance(value, dict): + return {key: _trusted(item) for key, item in value.items()} + if isinstance(value, list): + return [_trusted(item) for item in value] + return value + + +def _rendered(inventory: PlatformInventory) -> str: + """Render ``kibana.yml`` as the Kibana role writes it for the inventory.""" + services = {service.resource_id.value: service for service in inventory.services} + kibana = services["search-kibana"] + assert kibana.kibana is not None + domains = {domain.resource_id.value: domain for domain in inventory.domains} + defaults = yaml.safe_load((ROLE / "defaults" / "main.yml").read_text("utf-8")) + variables: dict[str, object] = { + **cast("dict[str, object]", _trusted(defaults)), + "cloudfall_kibana_service": kibana.as_dict(), + "cloudfall_kibana_elasticsearch_service": services["search-main"].as_dict(), + "cloudfall_kibana_domain": ( + {} + if kibana.kibana.domain is None + else domains[kibana.kibana.domain.value].as_dict() + ), + } + templar = Templar(loader=DataLoader(), variables=variables) + text = (ROLE / "templates" / "kibana.yml.j2").read_text(encoding="utf-8") + return str(templar.template(trust_as_template(text))) + + +def _role(base: str) -> dict[str, object]: + """Return a Kibana role as Kibana's role API answers it after a converge.""" + return { + "elasticsearch": {"cluster": [], "indices": [], "run_as": []}, + "kibana": [{"base": [base], "feature": {}, "spaces": ["*"]}], + "metadata": {"cloudfall_managed_by": "search-kibana"}, + } + + +def _evidence(inventory: PlatformInventory) -> dict[str, object]: + """Return what inspect reads from a Kibana server converged as declared.""" + return { + "service": "search-kibana", + "configurationPath": "/etc/kibana/kibana.yml", + "configuration": _rendered(inventory), + "nodeOptions": ( + "## Kibana's own options\n--unhandled-rejections=warn\n" + "--max-old-space-size=1024\n" + ), + "keystore": [TOKEN_SETTING, *KEYS], + "status": {"read": True, "level": "available"}, + "roles": [ + {"name": VIEW, "found": True, **_role("read")}, + {"name": EDIT, "found": True, **_role("all")}, + ], + "userRoles": { + "analyst": [EDIT], + "support": [VIEW], + "crm": [], + "cloudfall": [], + }, + } + + +def _report( + tmp_path: Path, + inventory: PlatformInventory, + evidence: dict[str, object] | None, + host: dict[str, object] | None = None, +) -> AuditReport: + """Audit h1 with the compliant fixture, the node, Kibana and its evidence. + + ``host`` replaces the installed versions (``kibana``, ``elasticsearch``), + fields of Kibana's unit (``unit``), or the listeners (``listeners``). + """ + host = host or {} + document = json.loads((COMPLIANT / "h1.json").read_text(encoding="utf-8")) + spec = document["spec"] + for name in ("kibana", "elasticsearch"): + spec["packages"].append( + { + "name": name, + "version": host.get(name, "9.2.4"), + "source": "apt", + "arch": "amd64", + } + ) + for unit, fields in ( + ("kibana.service", host.get("unit", {})), + ("elasticsearch.service", {}), + ): + spec["services"][unit] = { + "name": unit, + "state": "running", + "status": "enabled", + "source": "systemd", + **cast("dict[str, str]", fields), + } + network = spec["network"] + network["listeningSockets"] += "\n" + cast( + "str", host.get("listeners", LISTENERS) + ) + if evidence is not None: + spec["kibana"] = evidence + observations = tmp_path / "observed" + observations.mkdir(parents=True) + (observations / "h1.json").write_text(json.dumps(document), encoding="utf-8") + return audit_inventory(inventory, load_observations(observations, SCHEMAS)) + + +def _checks( + tmp_path: Path, + inventory: PlatformInventory, + evidence: dict[str, object] | None, + host: dict[str, object] | None = None, +) -> dict[str, AuditCheck]: + """Return the Kibana checks of h1, and its listener check.""" + report = _report(tmp_path, inventory, evidence, host) + (audit,) = (item for item in report.servers if item.server_id == "h1") + return { + check.check: check + for check in audit.checks + if check.check.startswith("kibana.") + or check.check == "services.bind[search-kibana]" + } + + +def _statuses(checks: dict[str, AuditCheck]) -> dict[str, AuditStatus]: + return {name: check.status for name, check in checks.items()} + + +ALL_COMPLIANT = { + "kibana.version[search-kibana]": AuditStatus.COMPLIANT, + "kibana.unit[search-kibana]": AuditStatus.COMPLIANT, + "kibana.configuration[search-kibana]": AuditStatus.COMPLIANT, + "kibana.status[search-kibana]": AuditStatus.COMPLIANT, + "kibana.roles[search-kibana]": AuditStatus.COMPLIANT, + "kibana.users[search-kibana]": AuditStatus.COMPLIANT, + "kibana.keystore[search-kibana]": AuditStatus.COMPLIANT, + "services.bind[search-kibana]": AuditStatus.COMPLIANT, +} + + +# proves: S-024-13 +def test_s024_13_a_kibana_converged_as_declared_is_compliant(tmp_path: Path) -> None: + inventory = _inventory(tmp_path) + + checks = _checks(tmp_path, inventory, _evidence(inventory)) + + assert _statuses(checks) == ALL_COMPLIANT + users = checks["kibana.users[search-kibana]"] + # crm has no Kibana access and holds no Kibana role: nothing to report + assert users.desired == {"analyst": [EDIT], "crm": [], "support": [VIEW]} + + +# proves: S-024-13 +@pytest.mark.parametrize( + "elasticsearch", + [ + pytest.param({}, id="loopback"), + pytest.param( + { + "remoteAccess": { + "listenAddress": "10.0.0.11", + "allowedSources": ["10.0.0.0/24"], + } + }, + id="remote access", + ), + ], +) +@pytest.mark.parametrize("domain", [False, True], ids=["unpublished", "published"]) +def test_s024_13_the_rendered_kibana_yml_of_every_shape_is_compliant( + tmp_path: Path, + elasticsearch: dict[str, object], + domain: bool, # noqa: FBT001 - the parametrized shape +) -> None: + inventory = _inventory(tmp_path, domain=domain, **elasticsearch) + + checks = _checks(tmp_path, inventory, _evidence(inventory)) + + configuration = checks["kibana.configuration[search-kibana]"] + assert configuration.status is AuditStatus.COMPLIANT, configuration.message + settings = cast("dict[str, object]", configuration.desired)["kibana.yml"] + assert isinstance(settings, dict) + assert ("xpack.security.secureCookies" in settings) is domain + assert ("elasticsearch.ssl.verificationMode" in settings) is bool(elasticsearch) + + +# proves: S-024-13 +def test_s024_13_a_kibana_version_other_than_the_elasticsearch_services_is_drift( + tmp_path: Path, +) -> None: + inventory = _inventory(tmp_path) + + checks = _checks(tmp_path, inventory, _evidence(inventory), {"kibana": "9.2.3"}) + + version = checks["kibana.version[search-kibana]"] + assert version.status is AuditStatus.DRIFT + assert version.desired == {"version": "9.2.4", "elasticsearch": "search-main"} + assert version.observed == {"versions": ["9.2.3"]} + + +def test_kibana_is_compared_with_the_declared_version_not_the_nodes( + tmp_path: Path, +) -> None: + inventory = _inventory(tmp_path) + + checks = _checks( + tmp_path, inventory, _evidence(inventory), {"elasticsearch": "9.2.5"} + ) + + # The node drifted, not Kibana: Kibana runs the service's declared version + assert checks["kibana.version[search-kibana]"].status is AuditStatus.COMPLIANT + + +def test_a_missing_kibana_package_is_drift(tmp_path: Path) -> None: + inventory = _inventory(tmp_path) + _report(tmp_path, inventory, _evidence(inventory)) + document = json.loads((tmp_path / "observed" / "h1.json").read_text("utf-8")) + document["spec"]["packages"] = [ + item for item in document["spec"]["packages"] if item["name"] != "kibana" + ] + again = tmp_path / "again" + again.mkdir() + (again / "h1.json").write_text(json.dumps(document), encoding="utf-8") + + report = audit_inventory(inventory, load_observations(again, SCHEMAS)) + + (audit,) = report.servers + (version,) = (c for c in audit.checks if c.check.startswith("kibana.version")) + assert version.status is AuditStatus.DRIFT + assert version.observed is None + + +# proves: S-024-13 +@pytest.mark.parametrize( + "unit", + [ + pytest.param({"state": "stopped"}, id="stopped"), + pytest.param({"status": "disabled"}, id="disabled"), + ], +) +def test_s024_13_a_stopped_or_disabled_kibana_unit_is_drift( + tmp_path: Path, unit: dict[str, str] +) -> None: + inventory = _inventory(tmp_path) + + checks = _checks(tmp_path, inventory, _evidence(inventory), {"unit": unit}) + + assert checks["kibana.unit[search-kibana]"].status is AuditStatus.DRIFT + + +# proves: S-024-13 +def test_s024_13_server_host_changed_by_hand_to_a_non_loopback_address_is_drift( + tmp_path: Path, +) -> None: + inventory = _inventory(tmp_path) + evidence = _evidence(inventory) + evidence["configuration"] = cast("str", evidence["configuration"]).replace( + 'server.host: "127.0.0.1"', 'server.host: "0.0.0.0"' + ) + assert "0.0.0.0" in cast("str", evidence["configuration"]) # noqa: S104 + listeners = LISTENERS.replace("127.0.0.1:5601", "0.0.0.0:5601") + + # Before Kibana restarts: the file is drift + before = _checks(tmp_path / "before", inventory, evidence) + # After it restarts with it: the listener is drift too + after = _checks( + tmp_path / "after", inventory, evidence, {"listeners": listeners} + ) + + configuration = before["kibana.configuration[search-kibana]"] + assert configuration.status is AuditStatus.DRIFT + assert configuration.observed is not None + kibana_yml = cast("dict[str, dict[str, object]]", configuration.observed) + assert kibana_yml["kibana.yml"]["server.host"] == "0.0.0.0" # noqa: S104 + assert "server.host differs" in configuration.message + assert before["services.bind[search-kibana]"].status is AuditStatus.COMPLIANT + bind = after["services.bind[search-kibana]"] + assert bind.status is AuditStatus.DRIFT + assert bind.observed == {"listeners": ["0.0.0.0:5601"]} + assert cast("dict[str, object]", bind.desired)["loopbackOnly"] is True + + +# proves: S-024-13 +@pytest.mark.parametrize( + "held", + [ + pytest.param([VIEW, EDIT], id="next to its view role"), + pytest.param([EDIT], id="instead of its view role"), + ], +) +def test_s024_13_support_given_the_edit_role_by_hand_is_drift( + tmp_path: Path, held: list[str] +) -> None: + inventory = _inventory(tmp_path) + evidence = _evidence(inventory) + cast("dict[str, list[str]]", evidence["userRoles"])["support"] = held + + checks = _checks(tmp_path, inventory, evidence) + + users = checks["kibana.users[search-kibana]"] + assert users.status is AuditStatus.DRIFT + assert cast("dict[str, object]", users.observed)["support"] == sorted(held) + assert users.message == ( + f"support holds {', '.join(sorted(held))} where its access gives {VIEW}" + ) + # Every other check stays as it was + assert { + name: status + for name, status in _statuses(checks).items() + if name != "kibana.users[search-kibana]" + } == { + name: status + for name, status in ALL_COMPLIANT.items() + if name != "kibana.users[search-kibana]" + } + + +@pytest.mark.parametrize( + ("user", "held", "message"), + [ + pytest.param( + "analyst", + [], + f"analyst holds no Kibana role where its access gives {EDIT}", + id="a user that lost its role", + ), + pytest.param( + "crm", + [VIEW], + f"crm holds {VIEW} where its access gives none", + id="a user without access given a role", + ), + ], +) +def test_a_declared_users_kibana_roles_other_than_its_access_are_drift( + tmp_path: Path, user: str, held: list[str], message: str +) -> None: + inventory = _inventory(tmp_path) + evidence = _evidence(inventory) + cast("dict[str, list[str]]", evidence["userRoles"])[user] = held + + checks = _checks(tmp_path, inventory, evidence) + + users = checks["kibana.users[search-kibana]"] + assert users.status is AuditStatus.DRIFT + assert users.message == message + + +def test_an_undeclared_user_with_a_kibana_role_is_listed_not_drift( + tmp_path: Path, +) -> None: + inventory = _inventory(tmp_path) + evidence = _evidence(inventory) + cast("dict[str, list[str]]", evidence["userRoles"])["hand-made"] = [EDIT] + + checks = _checks(tmp_path, inventory, evidence) + + users = checks["kibana.users[search-kibana]"] + assert users.status is AuditStatus.COMPLIANT + assert users.message == ( + "desired state matches; unmanaged (not declared, left as they are): " + f"hand-made holds {EDIT}" + ) + assert "hand-made" not in cast("dict[str, object]", users.observed) + + +@pytest.mark.parametrize( + ("edit", "message"), + [ + pytest.param( + lambda text: text.replace( + "telemetry.optIn: false", "telemetry.optIn: true" + ), + "telemetry.optIn differs", + id="a changed setting", + ), + pytest.param( + lambda text: text.replace( + 'server.publicBaseUrl: "http://127.0.0.1:5601"\n', "" + ), + "server.publicBaseUrl differs", + id="a removed setting", + ), + pytest.param( + lambda text: text + f"elasticsearch.password: {SECRET}\n", + "kibana.yml holds settings the role does not write: elasticsearch.password", + id="an added setting", + ), + ], +) +def test_kibana_yml_changed_by_hand_is_drift( + tmp_path: Path, edit: Callable[[str], str], message: str +) -> None: + inventory = _inventory(tmp_path) + evidence = _evidence(inventory) + evidence["configuration"] = edit(cast("str", evidence["configuration"])) + + report = _report(tmp_path, inventory, evidence) + + (audit,) = report.servers + (configuration,) = ( + c for c in audit.checks if c.check == "kibana.configuration[search-kibana]" + ) + assert configuration.status is AuditStatus.DRIFT + assert configuration.message == message + # A hand-written setting is named, its value is in no finding (S-024-5) + assert SECRET not in json.dumps(report.as_dict()) + + +@pytest.mark.parametrize( + ("options", "observed", "message"), + [ + pytest.param( + "--max-old-space-size=2048\n", + {"--max-old-space-size": 2048}, + "node.options gives --max-old-space-size 2048", + id="another heap", + ), + pytest.param( + "#--max-old-space-size=1024\n", + {"--max-old-space-size": []}, + "node.options gives --max-old-space-size nowhere", + id="the heap commented out", + ), + pytest.param( + None, + {"present": False}, + "node.options is missing", + id="no node.options", + ), + ], +) +def test_a_heap_changed_by_hand_is_drift( + tmp_path: Path, + options: str | None, + observed: dict[str, object], + message: str, +) -> None: + inventory = _inventory(tmp_path) + evidence = _evidence(inventory) + evidence["nodeOptions"] = options + + checks = _checks(tmp_path, inventory, evidence) + + configuration = checks["kibana.configuration[search-kibana]"] + assert configuration.status is AuditStatus.DRIFT + assert cast("dict[str, object]", configuration.observed)["node.options"] == ( + observed + ) + assert configuration.message == message + + +def test_a_missing_kibana_yml_is_drift(tmp_path: Path) -> None: + inventory = _inventory(tmp_path) + evidence = _evidence(inventory) + evidence["configuration"] = None + + checks = _checks(tmp_path, inventory, evidence) + + configuration = checks["kibana.configuration[search-kibana]"] + assert configuration.status is AuditStatus.DRIFT + assert configuration.message == "kibana.yml is missing" + + +@pytest.mark.parametrize( + ("level", "message"), + [ + pytest.param("degraded", "Kibana reports itself degraded", id="degraded"), + pytest.param(None, "Kibana did not answer GET /api/status", id="no answer"), + ], +) +def test_a_kibana_that_does_not_report_itself_available_is_drift( + tmp_path: Path, level: str | None, message: str +) -> None: + inventory = _inventory(tmp_path) + evidence = _evidence(inventory) + evidence["status"] = {"read": True, "level": level} + + checks = _checks(tmp_path, inventory, evidence) + + status = checks["kibana.status[search-kibana]"] + assert status.status is AuditStatus.DRIFT + assert status.message == message + + +def test_a_kibana_inspect_could_not_ask_is_unknown(tmp_path: Path) -> None: + inventory = _inventory(tmp_path) + evidence = _evidence(inventory) + evidence["status"] = {"read": False, "level": None} + evidence["roles"] = None + evidence["userRoles"] = None + + checks = _checks(tmp_path, inventory, evidence) + + for name in ("status", "roles", "users"): + assert checks[f"kibana.{name}[search-kibana]"].status is AuditStatus.UNKNOWN + + +def _feature_privilege(role: dict[str, object]) -> None: + kibana = cast("list[dict[str, object]]", role["kibana"]) + kibana[0]["base"] = [] + kibana[0]["feature"] = {"dashboard": ["all"]} + + +def _index_privilege(role: dict[str, object]) -> None: + elasticsearch = cast("dict[str, object]", role["elasticsearch"]) + elasticsearch["indices"] = [{"names": ["*"], "privileges": ["read"]}] + + +def _one_space(role: dict[str, object]) -> None: + cast("list[dict[str, object]]", role["kibana"])[0]["spaces"] = ["default"] + + +def _missing(role: dict[str, object]) -> None: + role.update(found=False, elasticsearch=None, kibana=None, metadata=None) + + +@pytest.mark.parametrize( + ("change", "message"), + [ + pytest.param( + _feature_privilege, + f"{VIEW} differs from what the role writes", + id="a feature privilege", + ), + pytest.param( + _index_privilege, + f"{VIEW} differs from what the role writes", + id="an index privilege", + ), + pytest.param( + _one_space, f"{VIEW} differs from what the role writes", id="one space" + ), + pytest.param(_missing, f"{VIEW} is missing", id="deleted"), + ], +) +def test_a_kibana_role_changed_by_hand_is_drift( + tmp_path: Path, change: Callable[[dict[str, object]], None], message: str +) -> None: + inventory = _inventory(tmp_path) + evidence = _evidence(inventory) + roles = cast("list[dict[str, object]]", evidence["roles"]) + change(roles[0]) + + checks = _checks(tmp_path, inventory, evidence) + + check = checks["kibana.roles[search-kibana]"] + assert check.status is AuditStatus.DRIFT + assert check.message == message + + +@pytest.mark.parametrize( + ("keystore", "message"), + [ + pytest.param( + [TOKEN_SETTING, *KEYS[1:]], + "the keystore lacks xpack.encryptedSavedObjects.encryptionKey", + id="a key missing", + ), + pytest.param(None, "Kibana's keystore could not be listed", id="no keystore"), + ], +) +def test_a_key_missing_from_the_keystore_is_an_unmet_requirement( + tmp_path: Path, keystore: list[str] | None, message: str +) -> None: + inventory = _inventory(tmp_path) + evidence = _evidence(inventory) + evidence["keystore"] = keystore + + checks = _checks(tmp_path, inventory, evidence) + + check = checks["kibana.keystore[search-kibana]"] + assert check.status is AuditStatus.DRIFT + assert check.message == message + + +def test_an_observation_without_kibana_evidence_is_unknown_not_drift( + tmp_path: Path, +) -> None: + inventory = _inventory(tmp_path) + + checks = _checks(tmp_path, inventory, None) + + assert { + name: status + for name, status in _statuses(checks).items() + if status is not AuditStatus.COMPLIANT + } == { + f"kibana.{name}[search-kibana]": AuditStatus.UNKNOWN + for name in ("configuration", "status", "roles", "users", "keystore") + } + + +def test_an_elasticsearch_only_project_has_no_kibana_check(tmp_path: Path) -> None: + project = write_elasticsearch_project(tmp_path / "project", elasticsearch_service()) + inventory = PlatformInventory.from_state(validate_config(project, SCHEMAS)) + + report = _report(tmp_path, inventory, None) + + (audit,) = report.servers + assert not [check for check in audit.checks if check.check.startswith("kibana.")]