Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion changelog.d/569-kibana-converge.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
### Added

- `services.yml` converges a Kibana service (S-024) with the new `cloudfall_kibana` role, on loopback and without a `domain`: in a play of its own, once every node of its cluster that the run converges has finished, it installs `kibana=<version>` of the Elasticsearch service from the node's Elastic repository and holds it, writes `/etc/kibana/kibana.yml` (`server.host`, `server.port`, `server.publicBaseUrl`, `elasticsearch.hosts`, the project CA with the node's `remoteAccess`, `telemetry.optIn: false`) and the declared heap into `/etc/kibana/node.options`, creates a token of the `elastic/kibana` service account named after the Kibana service in that node's `service_tokens` file, and puts the token and the three encryption keys in Kibana's keystore, never in a file a person reads. Each is put once: a second converge changes nothing and restarts nothing. The role waits until Kibana reports itself available at the service's version, and stops the converge when it does not, when the node holds no such token, when an unauthenticated request for a dashboard is not sent to the login form, or when Kibana listens outside loopback. A `heapMb` that with the node's heap is above three quarters of the server's memory stops the converge before any task changes the server, and so does a Kibana of another version than the cluster's; a declared `domain` is refused until a release publishes Kibana. The kind yields its S-011 requirements: the `kibana` package and three `generate` secrets (`kibana-security-encryption-key`, `kibana-saved-objects-encryption-key`, `kibana-reporting-encryption-key`, under `/services/<id>`), which `cloudfall secrets generate` makes and the services converge stages, failing before any playbook when one is missing. The `kibana_system` password is never set or changed (#569)
- `services.yml` converges a Kibana service (S-024) with the new `cloudfall_kibana` role, on loopback: in a play of its own, once every node of its cluster that the run converges has finished, it installs `kibana=<version>` of the Elasticsearch service from the node's Elastic repository and holds it, writes `/etc/kibana/kibana.yml` (`server.host`, `server.port`, `server.publicBaseUrl`, `elasticsearch.hosts`, the project CA with the node's `remoteAccess`, `telemetry.optIn: false`) and the declared heap into `/etc/kibana/node.options`, creates a token of the `elastic/kibana` service account named after the Kibana service in that node's `service_tokens` file, and puts the token and the three encryption keys in Kibana's keystore, never in a file a person reads. Each is put once: a second converge changes nothing and restarts nothing. The role waits until Kibana reports itself available at the service's version, and stops the converge when it does not, when the node holds no such token, when an unauthenticated request for a dashboard is not sent to the login form, or when Kibana listens outside loopback. A `heapMb` that with the node's heap is above three quarters of the server's memory stops the converge before any task changes the server, and so does a Kibana of another version than the cluster's. The kind yields its S-011 requirements: the `kibana` package and three `generate` secrets (`kibana-security-encryption-key`, `kibana-saved-objects-encryption-key`, `kibana-reporting-encryption-key`, under `/services/<id>`), which `cloudfall secrets generate` makes and the services converge stages, failing before any playbook when one is missing. The `kibana_system` password is never set or changed (#569)
3 changes: 3 additions & 0 deletions changelog.d/573-kibana-domain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Added

- A Kibana service with `kibana.domain` converges published through that `Domain` (S-024-8): `services.yml` hands the `cloudfall_kibana` role the Domain from its server's own Domains, and the role writes `server.publicBaseUrl: https://<primaryName>` and `xpack.security.secureCookies: true` to `kibana.yml`, so the links Kibana generates start with that address and the session cookie is sent over HTTPS only. Kibana keeps listening on loopback; the Domain's certificate and nginx site in front of it are the ones `cloudfall domains apply` already manages. The role no longer refuses a declared `domain`; it refuses, before any change, one its server does not hold proxying to the Kibana port with `tls.mode: required` and no `routes`. A Kibana without `domain` is unchanged (#573)
9 changes: 9 additions & 0 deletions engine/ansible/playbooks/services.yml
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,15 @@
cloudfall_service_item.kibana.elasticsearch)
| first | default({})
}}
# The Domain that publishes Kibana (S-024-8): its proxy server is
# this server, so it is among the server's own Domains.
cloudfall_kibana_domain: >-
{{
cloudfall_domains | default([])
| selectattr('id', 'equalto',
cloudfall_service_item.kibana.domain | default(''))
| first | default({})
}}
# Controller paths of the staged encryption keys cloudfall passes
# as cloudfall_services_kibana_files; never the values (S-024-5).
cloudfall_kibana_files: >-
Expand Down
12 changes: 12 additions & 0 deletions engine/ansible/roles/cloudfall_kibana/defaults/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ cloudfall_kibana_service: {}
# The Elasticsearch service the Kibana service reads, as services.yml finds it
# among the host's services by kibana.elasticsearch (S-024).
cloudfall_kibana_elasticsearch_service: {}
# The Domain that publishes Kibana, as services.yml finds it among the
# server's Domains by kibana.domain (S-024-8); empty without a domain.
cloudfall_kibana_domain: {}
# Controller paths of the three staged encryption keys (securityKey,
# savedObjectsKey, reportingKey) cloudfall passes as
# cloudfall_services_kibana_files; never the values.
Expand Down Expand Up @@ -63,6 +66,15 @@ cloudfall_kibana_url: >-
if ':' in cloudfall_kibana_service.bind.address
else cloudfall_kibana_service.bind.address
}}:{{ cloudfall_kibana_service.bind.port }}
# The address Kibana puts in the links it generates: its Domain's primaryName
# over HTTPS when a Domain publishes it (S-024-8), else where it listens.
cloudfall_kibana_published: "{{ cloudfall_kibana_service.kibana.domain is defined }}"
cloudfall_kibana_public_base_url: >-
{{
('https://' ~ cloudfall_kibana_domain.primaryName)
if cloudfall_kibana_published | bool
else cloudfall_kibana_url
}}
cloudfall_kibana_elasticsearch_url: >-
{%- set remote = cloudfall_kibana_elasticsearch_service.elasticsearch.remoteAccess
| default(none) -%}
Expand Down
5 changes: 5 additions & 0 deletions engine/ansible/roles/cloudfall_kibana/meta/argument_specs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ argument_specs:
description: >-
The Elasticsearch service the Kibana service reads, as the host's
services carry it
cloudfall_kibana_domain:
type: dict
description: >-
The Domain kibana.domain names, as the server's cloudfall_domains
carry it; empty without a domain
cloudfall_kibana_files:
type: dict
description: >-
Expand Down
33 changes: 24 additions & 9 deletions engine/ansible/roles/cloudfall_kibana/tasks/main.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
# Kibana runs on a node of the Elasticsearch service it reads and talks to
# that node only (S-024). This release converges it on loopback, without a
# Domain; the kibana_system user is never set or changed.
# that node only (S-024). It listens on loopback; a Domain may publish it
# (S-024-8). The kibana_system user is never set or changed.
- name: Validate Kibana service target and declaration
ansible.builtin.assert:
that:
Expand Down Expand Up @@ -47,17 +47,32 @@
{{ cloudfall_server_id }}: lower a heapMb, or move the services to a
server with more memory

# Publishing Kibana through a Domain comes with a later release (#573):
# refused rather than left unpublished by a converge that reports success.
- name: Refuse a Domain this release does not converge
# A published Kibana (S-024-8) is fronted by its Domain's certificate and
# nginx site, which domains.yml applies on this server, the Domain's proxy
# server. Here Kibana only learns its public address: the Domain must be one
# this server holds, proxying to the loopback listener.
- name: Refuse a Domain this server does not hold for Kibana
ansible.builtin.assert:
that:
- cloudfall_kibana_service.kibana.domain is not defined
- >-
cloudfall_kibana_service.kibana.domain is not defined
or (
cloudfall_kibana_domain.id | default('')
== cloudfall_kibana_service.kibana.domain
and cloudfall_kibana_domain.primaryName | default('') | length > 0
and cloudfall_kibana_domain.proxy.server | default('')
== cloudfall_server_id
and cloudfall_kibana_domain.proxy.upstream.port | default(0)
== cloudfall_kibana_service.bind.port
and cloudfall_kibana_domain.tls.mode | default('') == 'required'
and cloudfall_kibana_domain.routes is not defined
)
fail_msg: >-
Kibana service {{ cloudfall_kibana_service.id }} declares domain
{{ cloudfall_kibana_service.kibana.domain | default('') }}; this release
converges Kibana on loopback only, reached through an SSH forward:
remove domain, then converge again
{{ cloudfall_kibana_service.kibana.domain | default('') }}, which is not a
Domain of {{ cloudfall_server_id }} proxying to port
{{ cloudfall_kibana_service.bind.port }} with tls.mode required and no
routes; run cloudfall config validate

- name: Require the staged encryption keys and the cloudfall password
ansible.builtin.assert:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@
# kibana.keystore, never here.
server.host: "{{ cloudfall_kibana_service.bind.address }}"
server.port: {{ cloudfall_kibana_service.bind.port }}
server.publicBaseUrl: "{{ cloudfall_kibana_url }}"
server.publicBaseUrl: "{{ cloudfall_kibana_public_base_url }}"
{% if cloudfall_kibana_published | bool %}
# Published over HTTPS by its Domain: the session cookie is sent over it only.
xpack.security.secureCookies: true
{% endif %}
elasticsearch.hosts: ["{{ cloudfall_kibana_elasticsearch_url }}"]
{% if cloudfall_kibana_elasticsearch_service.elasticsearch.remoteAccess is defined %}
elasticsearch.ssl.certificateAuthorities: ["{{ cloudfall_kibana_ca_path }}"]
Expand Down
210 changes: 210 additions & 0 deletions engine/tests/test_s024_8_kibana_domain.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
"""Kibana published through an existing Domain (S-024-8, #573).

The spec's project, with ``domain: search-kibana-site``, is rendered through
the engine inventory; what ``services.yml`` hands the Kibana role, the role's
refusal and its ``kibana.yml``, and the Domain's nginx site are evaluated from
that server's host variables with Ansible's own templating. The certificate
the site names is the one the existing Domain apply path issues; a browser's
login through it is left for a live proving run.
"""

from __future__ import annotations

import re
from pathlib import Path
from typing import TYPE_CHECKING, Any, cast

import pytest
import yaml
from ansible.parsing.dataloader import DataLoader
from ansible.template import Templar, trust_as_template
from cloudfall.inventory import PlatformInventory
from cloudfall.validation import validate_config
from cloudfall_engine.ansible_inventory import render_ansible_inventory
from kibana_project import SCHEMAS, kibana_domain, kibana_service, search_main
from kibana_project import write_project as write_kibana_project

if TYPE_CHECKING:
from collections.abc import Iterable

ROOT = Path(__file__).parents[2]
ROLE = ROOT / "engine" / "ansible" / "roles" / "cloudfall_kibana"
SITE = ROOT / "engine" / "ansible" / "roles" / "cloudfall_nginx_site"
SERVICES = ROOT / "engine" / "ansible" / "playbooks" / "services.yml"
REFUSAL = "Refuse a Domain this server does not hold for Kibana"


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 _template(expression: str, variables: dict[str, object]) -> object:
templar = Templar(loader=DataLoader(), variables=variables)
return templar.template(trust_as_template(expression))


def _host(tmp_path: Path, *, domain: str | None) -> dict[str, Any]:
"""Return the host variables the engine inventory hands h1."""
project = write_kibana_project(
tmp_path / "project",
search_main(),
kibana_service(domain=domain),
domains=(kibana_domain(),),
)
inventory = render_ansible_inventory(
PlatformInventory.from_state(validate_config(project, SCHEMAS))
)
children = cast("dict[str, Any]", inventory["all"])["children"]
return cast("dict[str, Any]", children["cloudfall_servers"]["hosts"]["h1"])


def _role_variables(host: dict[str, Any]) -> dict[str, object]:
"""Return the variables the Kibana role sees, as services.yml hands them."""
play = yaml.safe_load(SERVICES.read_text(encoding="utf-8"))[1]
(block,) = play["tasks"]
_, deploy = block["block"]
(kibana,) = (
service for service in host["cloudfall_services"] if "kibana" in service
)
scope = {**host, "cloudfall_server_id": "h1", "cloudfall_service_item": kibana}
handed = {
name: _template(value, scope)
for name, value in deploy["vars"].items()
if name in {"cloudfall_kibana_service", "cloudfall_kibana_domain"}
}
defaults = yaml.safe_load((ROLE / "defaults" / "main.yml").read_text("utf-8"))
return {
**{key: _trusted(value) for key, value in defaults.items()},
**scope,
**handed,
"cloudfall_kibana_elasticsearch_service": next(
service
for service in host["cloudfall_services"]
if service["id"] == "search-main"
),
}


def _kibana_yml(variables: dict[str, object]) -> dict[str, object]:
text = (ROLE / "templates" / "kibana.yml.j2").read_text(encoding="utf-8")
settings = yaml.safe_load(str(_template(text, variables)))
assert isinstance(settings, dict)
return cast("dict[str, object]", settings)


def _task(name: str, tasks: Iterable[dict[str, Any]]) -> dict[str, Any]:
return next(task for task in tasks if task["name"] == name)


def _refusal_holds(variables: dict[str, object]) -> bool:
tasks = DataLoader().load_from_file(str(ROLE / "tasks" / "main.yml"))
that = _task(REFUSAL, tasks)["ansible.builtin.assert"]["that"]
templar = Templar(loader=DataLoader(), variables=variables)
return all(
templar.evaluate_conditional(trust_as_template(str(condition)))
for condition in that
)


# proves: S-024-8
def test_s024_8_kibana_links_to_its_domain_over_https_with_secure_cookies(
tmp_path: Path,
) -> None:
variables = _role_variables(_host(tmp_path, domain="search-kibana-site"))

# services.yml hands the role the Domain from the server's own Domains
domain = cast("dict[str, Any]", variables["cloudfall_kibana_domain"])
assert domain["id"] == "search-kibana-site"
assert _refusal_holds(variables)
settings = _kibana_yml(variables)
# Links start with the Domain's address, with no trailing slash
assert settings["server.publicBaseUrl"] == "https://kibana.example.test"
assert settings["xpack.security.secureCookies"] is True
# Kibana still answers on loopback only, behind the Domain's site
assert settings["server.host"] == "127.0.0.1"
assert settings["server.port"] == 5601
# The role's own calls still go to the loopback listener
assert _template("{{ cloudfall_kibana_url }}", variables) == (
"http://127.0.0.1:5601"
)


# proves: S-024-8
def test_s024_8_an_undomained_kibana_keeps_its_loopback_settings(
tmp_path: Path,
) -> None:
variables = _role_variables(_host(tmp_path, domain=None))

assert variables["cloudfall_kibana_domain"] == {}
assert _refusal_holds(variables)
settings = _kibana_yml(variables)
assert settings["server.publicBaseUrl"] == "http://127.0.0.1:5601"
assert "xpack.security.secureCookies" not in settings


# proves: S-024-8
@pytest.mark.parametrize(
"domain",
[
pytest.param({}, id="not a Domain of this server"),
pytest.param({"id": "other-site"}, id="another Domain"),
],
)
def test_s024_8_a_domain_the_server_does_not_hold_is_refused(
tmp_path: Path, domain: dict[str, object]
) -> None:
variables = _role_variables(_host(tmp_path, domain="search-kibana-site"))
held = cast("dict[str, Any]", variables["cloudfall_kibana_domain"])

assert not _refusal_holds({**variables, "cloudfall_kibana_domain": domain})
# A Domain whose site is not the loopback listener's over TLS, too
for changed in (
{**held, "tls": {"mode": "optional"}},
{**held, "proxy": {**held["proxy"], "server": "h2"}},
{**held, "proxy": {**held["proxy"], "upstream": {"port": 5602}}},
{**held, "routes": [{"path": "/"}]},
):
assert not _refusal_holds({**variables, "cloudfall_kibana_domain": changed})


# proves: S-024-8
def test_s024_8_the_domains_site_fronts_kibana_with_the_certificate_of_its_name(
tmp_path: Path,
) -> None:
host = _host(tmp_path, domain="search-kibana-site")
(domain,) = host["cloudfall_domains"]
defaults = yaml.safe_load((SITE / "defaults" / "main.yml").read_text("utf-8"))
text = (SITE / "templates" / "domain-site.conf.j2").read_text(encoding="utf-8")

site = str(
_template(
text,
{
**{key: _trusted(value) for key, value in defaults.items()},
"cloudfall_nginx_site_domain": domain,
"cloudfall_nginx_site_tls_active": True,
"cloudfall_nginx_site_version": "1.26.3",
},
)
)

plain, secure = re.split(r"\n(?=server \{)", site.split("\n", 1)[1].strip())
# Plain HTTP only redirects to HTTPS: the login form is never sent over it
assert "return 301 https://$host$request_uri;" in plain
assert "proxy_pass" not in plain
assert "server_name kibana.example.test;" in secure
assert (
"ssl_certificate /etc/letsencrypt/live/kibana.example.test/fullchain.pem;"
in secure
)
# To Kibana's loopback listener, telling it the request came over HTTPS
assert "proxy_pass http://127.0.0.1:5601;" in secure
assert "proxy_set_header X-Forwarded-Proto $scheme;" in secure
assert "proxy_set_header Host $host;" in secure
6 changes: 3 additions & 3 deletions engine/tests/test_s024_kibana_role.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
"Refuse a Kibana heap that with the node's is above three quarters of the "
"host's memory"
),
"Refuse a Domain this release does not converge",
"Refuse a Domain this server does not hold for Kibana",
"Require the staged encryption keys and the cloudfall password",
"Read the installed Kibana version",
"Refuse a Kibana of another version than the Elasticsearch service's",
Expand Down Expand Up @@ -422,8 +422,8 @@ def test_s024_4_every_refusal_comes_before_any_task_that_changes_the_host() -> N
assert (
names[len(REFUSALS)] == "Install the Elasticsearch service's version of Kibana"
)
# A Domain is refused until a release publishes Kibana (#573)
domain = _task("Refuse a Domain this release does not converge", main)
# A domain the server does not hold is refused before any change (#573)
domain = _task("Refuse a Domain this server does not hold for Kibana", main)
assert _holds(domain, _variables())
published = _kibana(domain="search-kibana-site")
assert not _holds(domain, _variables(cloudfall_kibana_service=published))
Expand Down