Files
coulobre/tests/test_cluster_installer.py
T

341 lines
13 KiB
Python
Raw Normal View History

import json
import tempfile
import tomllib
import unittest
from contextlib import nullcontext, redirect_stdout
from io import StringIO
from pathlib import Path
from unittest.mock import Mock, patch
from deploy.panel_installer import cluster, remote, ssh_keys
from deploy.panel_installer.cli import (
interactive_configuration,
main,
write_interactive_plan,
)
from deploy.panel_installer.cluster_wizard import (
collect_cluster,
panel_defaults,
)
from deploy.panel_installer.config import InstallError, parse_plan
from deploy.panel_installer.terminal import PlainTerminal
class ClusterInstallerTests(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
self.folder = Path(directory.name)
self.pin = self.folder / "host.pub"
self.pin.write_text("ssh-ed25519 fixture-public-key\n")
self.config = {
"cluster": {
"mail": self.connection("192.0.2.24")
| {
"mail_hostname": "mail.example.net",
"tls": "acme",
"sending_addresses": ["93.184.215.14"],
},
"panels": [
self.panel("one"),
self.panel("two") | {"ssh": self.connection("192.0.2.22")},
self.panel("three")
| {"ssh": self.connection("192.0.2.23")},
],
}
}
def connection(self, host):
return {
"host": host,
"host_key": str(self.pin),
"ssh_user": "root",
"ssh_identity": "/root/cluster-admin",
}
def panel(self, name):
return {
"name": name,
"panel": {"hostname": f"{name}.example.net", "access": "acme"},
"admin": {
"email": "ops@example.net",
"password_file": f"/root/{name}-password",
},
"domains": [],
}
def test_cluster_toml_round_trip_preserves_panel_and_receiver_settings(
self,
):
path = self.folder / "cluster.toml"
write_interactive_plan(path, self.config, None, replace=False)
stored = tomllib.loads(path.read_text())
self.assertEqual(stored, self.config)
topology = cluster.parse_cluster(stored)
self.assertEqual(
[p.plan.hostname for p in topology.panels],
["one.example.net", "two.example.net", "three.example.net"],
)
panel = topology.panels[1]
self.assertEqual(panel.scopes, {"mail": "two"})
self.assertEqual(panel.plan.mail.mode, "remote")
self.assertEqual(panel.plan.mail.mail_hostname, "mail.example.net")
self.assertEqual(
panel.plan.hosting.mail_sending_addresses, ("93.184.215.14",)
)
self.assertEqual(panel.domains, [])
def test_rejects_overlapping_domains_on_shared_dns(self):
self.config["cluster"]["dns"] = self.connection("192.0.2.24")
first, second, _ = self.config["cluster"]["panels"]
first["domains"] = ["example.net"]
second["domains"] = ["customer.example.net"]
with self.assertRaisesRegex(InstallError, "single|one panel"):
cluster.parse_cluster(self.config)
def test_hydrates_remote_plan_using_only_public_receiver_keys(self):
topology = cluster.parse_cluster(self.config)
panel = topology.panels[1]
payload = {"plan": panel.parameters, "pins": panel.pins}
self.assertEqual(cluster.parse_remote_panel(payload), panel.plan)
self.assertNotIn("ssh_identity", payload["plan"]["mail"])
def test_checks_all_destinations_before_changes_and_resumes_failed_panel(
self,
):
topology = cluster.parse_cluster(self.config)
local = Mock(plan=topology.panels[0].plan, release="1.0.0rc1")
local.prepare_cluster_keys.return_value = {"mail": "public-one"}
events = []
fail_third = True
machines = {"192.0.2.22": "2", "192.0.2.23": "3", "192.0.2.24": "4"}
def request(target, settings, *, result=False):
action = settings["role"]
events.append((action, target.host))
if action == "cluster-check":
return {"machine": machines[target.host] * 32}
if action == "cluster-keys":
return {"mail": f"public-{target.host}"}
if action == "mail":
self.assertEqual(settings["domains"], [])
self.assertIn(settings["scope"], {"one", "two", "three"})
self.assertNotIn("password", settings)
if action == "cluster-panel":
self.assertNotIn("ssh_identity", settings)
if target.host == "192.0.2.23" and fail_third:
raise InstallError("Installation interrupted.")
def state_file(path, payload, **kwargs):
path.write_text(payload)
with (
patch.object(cluster, "STATE", self.folder),
patch.object(cluster, "cluster_lock", return_value=nullcontext()),
patch.object(cluster, "preserve_pins"),
patch.object(cluster, "cluster_request", side_effect=request),
patch.object(cluster.remote, "check_panel_destination"),
patch.object(cluster.engine, "Installer", return_value=local),
patch.object(cluster.engine, "root_file"),
patch.object(cluster.engine, "put_file", side_effect=state_file),
):
installer = cluster.ClusterInstaller(
topology,
dict.fromkeys(("one", "two", "three"), "fixture"),
Mock(),
)
with self.assertRaisesRegex(InstallError, "interrupted"):
installer.install()
self.assertEqual(
events[:3],
[("cluster-check", endpoint) for endpoint in machines],
)
self.assertEqual(
json.loads((self.folder / "installation.json").read_text())[
"complete"
],
["one", "two"],
)
fail_third = False
events.clear()
installer.install()
self.assertIn(("cluster-panel", "192.0.2.23"), events)
self.assertNotIn(("cluster-panel", "192.0.2.22"), events)
local.install.assert_called_once()
self.assertEqual(
json.loads((self.folder / "installation.json").read_text())[
"complete"
],
["one", "two", "three"],
)
def test_refuses_two_endpoints_with_the_same_machine_identity(self):
topology = cluster.parse_cluster(self.config)
local = Mock(plan=topology.panels[0].plan, release="1.0.0rc1")
with (
patch.object(
cluster, "cluster_request", return_value={"machine": "2" * 32}
),
patch.object(cluster.remote, "check_panel_destination"),
patch.object(cluster.engine, "Installer", return_value=local),
):
installer = cluster.ClusterInstaller(
topology,
dict.fromkeys(("one", "two", "three"), "fixture"),
Mock(),
)
with self.assertRaisesRegex(InstallError, "distinct machine ID"):
installer.check()
local.install.assert_not_called()
def test_automated_check_does_not_open_the_terminal_or_install(self):
path = self.folder / "cluster.toml"
write_interactive_plan(path, self.config, None, replace=False)
with (
patch("deploy.panel_installer.cli.platform_settings"),
patch.object(cluster, "read_password", return_value="fixture"),
patch("deploy.panel_installer.cli.ClusterInstaller") as installer,
patch("deploy.panel_installer.cli.configure_terminal") as terminal,
redirect_stdout(StringIO()),
):
self.assertEqual(main(["--config", str(path), "--check"]), 0)
installer.return_value.check.assert_called_once()
installer.return_value.install.assert_not_called()
terminal.assert_not_called()
def test_single_plan_rejects_cluster_inventory(self):
with self.assertRaises(InstallError):
parse_plan(self.config)
def test_new_panels_inherit_only_reusable_defaults(self):
draft = self.config["cluster"]
previous = draft["panels"][1]
previous["dns"] = "local"
previous["hosting"] = {
"nameservers": ["ns.example.net"],
"public_addresses": ["192.0.2.22"],
}
defaults = panel_defaults(draft, 2)
self.assertEqual(defaults["panel"], {"access": "acme"})
self.assertEqual(defaults["admin"], {"email": "ops@example.net"})
self.assertEqual(defaults["dns"], "local")
self.assertEqual(
defaults["hosting"], {"nameservers": ["ns.example.net"]}
)
self.assertEqual(
defaults["ssh"],
{
"ssh_user": "root",
"ssh_identity": "/root/cluster-admin",
},
)
self.assertNotIn("domains", defaults)
def test_review_retries_a_failed_preflight_before_offering_install(self):
terminal = Mock(spec=PlainTerminal)
terminal.choose.side_effect = ("check connections", "retry", "install")
with (
patch(
"deploy.panel_installer.cluster_wizard.collect_inventory",
return_value=self.config["cluster"],
),
patch(
"deploy.panel_installer.cluster_wizard.ClusterInstaller"
) as installer,
):
installer.return_value.check.side_effect = (
InstallError("Check sudo."),
None,
)
self.assertIsNotNone(collect_cluster(terminal))
self.assertEqual(installer.return_value.check.call_count, 2)
installer.return_value.install.assert_not_called()
choices = [call.args[1] for call in terminal.choose.call_args_list]
self.assertNotIn("install", choices[0])
self.assertIn("install", choices[-1])
terminal.error.assert_called_once()
def test_known_hosts_only_offers_trusted_unrevoked_keys(self):
entries = (
"# Host [192.0.2.22]:2222 found: line 1\n"
"|1|hash ssh-ed25519 revoked\n"
"@revoked [192.0.2.22]:2222 ssh-ed25519 revoked\n"
"@cert-authority [192.0.2.22]:2222 ssh-ed25519 ca\n"
"|1|hash ssh-ed25519 accepted\n"
)
with (
patch.object(ssh_keys, "root_controlled", return_value=True),
patch.object(
ssh_keys.engine, "run", return_value=entries
) as command,
patch.object(
ssh_keys,
"fingerprint",
side_effect=("SHA256:revoked", "SHA256:valid"),
),
):
keys = ssh_keys.trusted_keys("192.0.2.22", 2222)
self.assertEqual(
keys, {"ssh-ed25519 SHA256:valid": "ssh-ed25519 accepted"}
)
self.assertIn("[192.0.2.22]:2222", command.call_args.args)
def test_preflight_distinguishes_ssh_authentication_and_sudo_failures(
self,
):
self.assertIn(
"authorize the matching public key",
remote.ssh_failure(
255, b"root@host: Permission denied (publickey)."
),
)
self.assertIn(
"noninteractive sudo",
remote.ssh_failure(1, b"sudo: a password is required"),
)
self.assertIn(
"host key did not match",
remote.ssh_failure(255, b"Host key verification failed."),
)
def test_cluster_is_a_topology_in_the_interactive_entry_point(self):
inputs = [
"cluster",
"2",
"no",
"no",
"one",
"one.example.net",
"",
"",
"ops@example.net",
"",
"",
"",
"two",
"192.0.2.22",
"",
str(self.pin),
"root",
"/root/ssh-key",
"two.example.net",
"",
"",
"ops@example.net",
"",
"",
"",
"cancel",
]
output = StringIO()
with (
patch("builtins.input", side_effect=inputs),
patch("deploy.panel_installer.interactive.root_file"),
redirect_stdout(output),
):
self.assertIsNone(interactive_configuration(PlainTerminal(), None))
self.assertIn("=== Review cluster ===", output.getvalue())
self.assertIn("one.example.net (this server)", output.getvalue())
self.assertIn(
"two.example.net (SSH 192.0.2.22:22)", output.getvalue()
)