diff --git a/deploy/panel_installer/cli.py b/deploy/panel_installer/cli.py index db85fd4..8a465e1 100644 --- a/deploy/panel_installer/cli.py +++ b/deploy/panel_installer/cli.py @@ -187,15 +187,19 @@ def interactive_cluster(terminal, password_path): if configured is None: return None cluster, data = configured - passwords = { - entry["name"]: collect_password( + entries = data["cluster"]["panels"] + passwords = {} + for index, entry in enumerate(entries): + terminal.context = ( + f"Cluster / Passwords / Panel {index + 1} of {len(entries)}" + ) + passwords[entry["name"]] = collect_password( terminal, entry, default=password_path or "" if index == 0 else "", masked_password=get_password, ) - for index, entry in enumerate(data["cluster"]["panels"]) - } + terminal.context = "Cluster / Save configuration" terminal.heading("Save cluster settings") terminal.show( "For automated setup, supply a private password file for each panel." diff --git a/deploy/panel_installer/cluster.py b/deploy/panel_installer/cluster.py index e9c4db3..6e4e22c 100644 --- a/deploy/panel_installer/cluster.py +++ b/deploy/panel_installer/cluster.py @@ -293,10 +293,11 @@ def run_remote_step(settings): def cluster_request(target, settings, *, result=False): + destination = f"{target.ssh_user}@{target.host} (port {target.port})" try: reply = remote.ssh_bootstrap(target, settings, report=result) except (OSError, InstallError) as error: - raise InstallError(f"{target.host}: {error}") from error + raise InstallError(f"{destination}: {error}") from error if result: try: report = json.loads(reply) @@ -304,10 +305,12 @@ def cluster_request(target, settings, *, result=False): raise ValueError except (TypeError, ValueError): raise InstallError( - f"{target.host}: unexpected installation response." + f"{destination}: unexpected response from the installer. " + "Check that the SSH account can run commands without an " + "interactive login." ) from None if error := report.get("error"): - raise InstallError(f"{target.host}: {error}") + raise InstallError(f"{destination}: {error}") return report return None @@ -349,8 +352,10 @@ class ClusterInstaller: } def check(self): + self.progress("Checking the local panel.") self.local.check_state() remote.check_panel_destination() + self.progress("Local panel: ready.") machines = {self.origin} for panel in self.cluster.panels[1:]: self.progress( @@ -360,18 +365,22 @@ class ClusterInstaller: panel.ssh, self.settings(panel), result=True ) self.check_machine(report.get("machine"), machines) + self.progress( + f"{panel.name}: SSH, sudo and panel settings passed." + ) groups = {} for name, receiver in self.cluster.receivers.items(): identity = (receiver.host, receiver.port) groups.setdefault(identity, {})[name] = receiver for roles in groups.values(): target = roles.get("mail") or roles["dns"] + host_key = read_ssh_host_key(target.host_key, "receiver") for candidate in roles.values(): if ( - candidate.host_key, + read_ssh_host_key(candidate.host_key, "receiver"), candidate.ssh_user, candidate.ssh_identity, - ) != (target.host_key, target.ssh_user, target.ssh_identity): + ) != (host_key, target.ssh_user, target.ssh_identity): raise InstallError( "Use the same SSH credentials for both roles " "on a shared host." @@ -394,6 +403,9 @@ class ClusterInstaller: result=True, ) self.check_machine(report.get("machine"), machines) + self.progress( + f"{target.host}: SSH, sudo and receiver settings passed." + ) @staticmethod def check_machine(machine, seen): diff --git a/deploy/panel_installer/cluster_wizard.py b/deploy/panel_installer/cluster_wizard.py index 780201c..66393cb 100644 --- a/deploy/panel_installer/cluster_wizard.py +++ b/deploy/panel_installer/cluster_wizard.py @@ -15,6 +15,7 @@ from .interactive import ( local_path, validated_list, ) +from .terminal import PreviousStepError def panel_name(value): @@ -29,7 +30,7 @@ def count(value): return int(value) -def collect_receiver(terminal, name, previous): +def collect_receiver(terminal, name, previous, defaults=None): terminal.heading(f"Shared {name.upper()} receiver") selected = terminal.choose( "Configure a shared receiver", @@ -45,7 +46,8 @@ def collect_receiver(terminal, name, previous): "panel": {"access": "acme"}, } setup.answers.update( - ((name, field), value) for field, value in previous.items() + ((name, field), value) + for field, value in ((defaults or {}) | previous).items() ) setup.role_settings(name) result = setup.data[name] @@ -70,7 +72,10 @@ def collect_receiver(terminal, name, previous): return result -def collect_panel(terminal, index, previous, receivers): +def collect_panel(terminal, index, previous, receivers, defaults=None): + initial = defaults or {} + if previous: + initial = previous terminal.heading( "Local panel" if index == 0 else f"Remote panel {index + 1}" ) @@ -83,20 +88,50 @@ def collect_panel(terminal, index, previous, receivers): ) setup = InteractiveSetup(terminal) setup.data = { - key: previous[key] for key in ("panel", "admin") if key in previous + key: initial[key] for key in ("panel", "admin") if key in initial } for section in ("panel", "admin"): setup.answers.update( ((section, key), value) - for key, value in previous.get(section, {}).items() + for key, value in initial.get(section, {}).items() ) - if transport := previous.get("ssh"): + if transport := initial.get("ssh"): setup.answers.update( ((name, key), value) for key, value in transport.items() ) - ssh = setup.ssh_settings(name, "remote-install") if index else None - setup.panel(remote=bool(index)) - setup.admin() + stages = [] + connection = {} + if index: + + def ssh_settings(): + terminal.heading("SSH connection") + connection.update(setup.ssh_settings(name, "remote-install")) + + stages.append(ssh_settings) + hosting = {} + stages.extend( + ( + lambda: setup.panel(remote=bool(index)), + setup.admin, + lambda: hosting.update( + collect_hosting(terminal, name, hosting or initial, receivers) + ), + ) + ) + context = terminal.context + for_sections( + terminal, stages, f"{context} / {name}", back=terminal.can_go_back + ) + return { + "name": name, + "panel": setup.data["panel"], + "admin": setup.data["admin"], + **hosting, + **({"ssh": connection} if connection else {}), + } + + +def collect_hosting(terminal, name, previous, receivers): terminal.heading(f"Hosting on {name}") dns = terminal.choose( "DNS on this panel", @@ -120,15 +155,7 @@ def collect_panel(terminal, index, previous, receivers): lambda value, field=field: validated_list(field, value), hint=hint, ) - result = { - "name": name, - "panel": setup.data["panel"], - "admin": setup.data["admin"], - "hosting": hosting, - "dns": dns, - } - if ssh: - result["ssh"] = ssh + result = {"hosting": hosting, "dns": dns} if "mail" in receivers or dns == "shared": result["domains"] = ask_checked( terminal, @@ -143,6 +170,58 @@ def collect_panel(terminal, index, previous, receivers): return result +def shared_ssh_defaults(connection): + return { + field: connection[field] + for field in ("port", "ssh_user", "ssh_identity") + if field in connection + } + + +def panel_defaults(draft, index): + earlier = [panel for panel in draft["panels"][:index] if panel] + if not earlier: + return {} + previous = earlier[-1] + transport = ( + previous.get("ssh") or draft.get("mail") or draft.get("dns", {}) + ) + hosting = previous.get("hosting", {}) + return { + "panel": {"access": previous["panel"]["access"]}, + "admin": { + field: previous["admin"][field] + for field in ("username", "email") + if field in previous["admin"] + }, + "dns": previous["dns"], + "hosting": {"nameservers": hosting.get("nameservers", [])}, + "ssh": shared_ssh_defaults(transport), + } + + +def for_sections(terminal, sections, title, *, back=False): + previous_context, previous_back = terminal.context, terminal.can_go_back + index = 0 + try: + while index < len(sections): + terminal.context = f"{title} / {index + 1} of {len(sections)}" + terminal.can_go_back = index > 0 or back + try: + sections[index]() + except PreviousStepError: + if index == 0: + raise + index -= 1 + else: + index += 1 + finally: + terminal.context, terminal.can_go_back = ( + previous_context, + previous_back, + ) + + def assigned_domains(value): if value.lower() == "none": return [] @@ -155,6 +234,7 @@ def assigned_domains(value): def edit_inventory(terminal, draft): + terminal.context = "Cluster review" terminal.heading("Edit cluster") changed = terminal.choose( "Section", ("dns", "mail", "panels", "back"), "back" @@ -191,29 +271,65 @@ def edit_inventory(terminal, draft): panel = terminal.choose("Panel", (*choices, "back"), "back") if panel != "back": index = int(panel) - 1 + terminal.context = f"Cluster / Panel {index + 1} of {len(choices)}" draft["panels"][index] = collect_panel( terminal, index, draft["panels"][index], draft ) -def collect_cluster(terminal): +def collect_inventory(terminal): terminal.step = None + terminal.context = "Cluster / Topology" terminal.heading("Cluster topology") terminal.show( "Start on the first panel server. Provide SSH access from this server " "to the other panels and any shared receivers." ) size = ask_checked(terminal, "Number of panel servers", 3, count) - draft = {} - for name in ("dns", "mail"): - receiver = collect_receiver(terminal, name, {}) + draft = {"panels": [{} for _ in range(size)]} + + def receiver_section(name): + terminal.context = f"{terminal.context} / Shared {name.upper()}" + defaults = shared_ssh_defaults(draft.get("dns", {})) + receiver = collect_receiver( + terminal, name, draft.get(name, {}), defaults + ) if receiver: draft[name] = receiver - draft["panels"] = [ - collect_panel(terminal, index, {}, draft) for index in range(size) - ] + else: + draft.pop(name, None) + + def panel_section(index): + terminal.context = f"Cluster / Panel {index + 1} of {size}" + draft["panels"][index] = collect_panel( + terminal, + index, + draft["panels"][index], + draft, + panel_defaults(draft, index), + ) + + for_sections( + terminal, + ( + lambda: receiver_section("dns"), + lambda: receiver_section("mail"), + *( + lambda index=index: panel_section(index) + for index in range(size) + ), + ), + "Cluster configuration", + ) + return draft + + +def collect_cluster(terminal): + draft = collect_inventory(terminal) data = {"cluster": draft} + checked = False while True: + terminal.context = "Cluster / Review and preflight" terminal.heading("Review cluster") try: cluster = parse_cluster(data) @@ -223,11 +339,24 @@ def collect_cluster(terminal): else: for item in cluster.summary(): terminal.show(item) - choices = ("install", "edit", "cancel") + terminal.show( + "Preflight passed for all destinations." + if checked + else "Check connections to test SSH, sudo and destination " + "settings before starting installation." + ) + choices = ( + ("install", "check connections", "edit", "cancel") + if checked + else ("check connections", "edit", "cancel") + ) chosen = terminal.choose("Next step", choices, "cancel") if chosen == "cancel": return None if chosen == "install": + return cluster, data + while chosen == "check connections": + checked = False terminal.heading("Checking cluster destinations") try: ClusterInstaller( @@ -239,14 +368,18 @@ def collect_cluster(terminal): terminal.error(error) chosen = terminal.choose( "Cluster check failed", - ("edit", "review", "cancel"), + ("edit", "retry", "review", "cancel"), "edit", ) + if chosen == "retry": + chosen = "check connections" else: - return cluster, data + checked = True + chosen = "review" if chosen == "cancel": return None if chosen == "edit": + checked = False edit_inventory(terminal, draft) diff --git a/deploy/panel_installer/engine.py b/deploy/panel_installer/engine.py index ed3ebe9..3ccdc43 100644 --- a/deploy/panel_installer/engine.py +++ b/deploy/panel_installer/engine.py @@ -67,7 +67,7 @@ with transaction.atomic(): """ -def run(*args, label, source=None, timeout=120, env=None): +def run(*args, label, source=None, timeout=120, env=None, failure=None): try: result = subprocess.run( [os.fspath(value) for value in args], @@ -81,6 +81,8 @@ def run(*args, label, source=None, timeout=120, env=None): except (OSError, subprocess.TimeoutExpired): raise InstallError(f"{label} failed or timed out.") from None if result.returncode: + if failure: + raise InstallError(failure(result.returncode, result.stderr)) raise InstallError(f"{label} failed. Check the service and retry.") return result.stdout.decode("utf-8", errors="replace") diff --git a/deploy/panel_installer/interactive.py b/deploy/panel_installer/interactive.py index f8e73f0..ee89a5a 100644 --- a/deploy/panel_installer/interactive.py +++ b/deploy/panel_installer/interactive.py @@ -1,6 +1,6 @@ from pathlib import Path -from . import guidance +from . import guidance, ssh_keys from .config import ( REMOTE_MODES, InstallError, @@ -250,6 +250,9 @@ class InteractiveSetup: self.data[name] = target def ssh_settings(self, name, mode): + previous = tuple( + self.answers.get((name, field)) for field in ("host", "port") + ) target = { "host": self.ask( name, @@ -267,14 +270,21 @@ class InteractiveSetup: value, f"the {name} node", 22 ), ), - "host_key": self.ask( + } + if previous != (target["host"], target["port"]): + self.answers.pop((name, "host_key"), None) + if self.terminal.supports_key_picker: + target["host_key"] = self.choose_host_key( + name, target["host"], target["port"] + ) + else: + target["host_key"] = self.ask( name, "host_key", "Verified destination SSH host public key file", validate=lambda value: verified_key_path(value, name), hint=guidance.SSH_HOST_KEY, - ), - } + ) if mode == "remote-install": target["ssh_user"] = self.ask( name, @@ -282,14 +292,102 @@ class InteractiveSetup: "SSH administrator username", validate=lambda value: ssh_username(value, name), ) - target["ssh_identity"] = self.ask( - name, - "ssh_identity", - "SSH administrator private key file", - validate=private_key_path, + if self.terminal.supports_key_picker: + target["ssh_identity"] = self.choose_identity(name) + else: + target["ssh_identity"] = self.ask( + name, + "ssh_identity", + "SSH administrator private key file", + validate=private_key_path, + hint=guidance.SSH_IDENTITY, + ) + return target + + def choose_identity(self, name): + answer = (name, "ssh_identity") + paths = ssh_keys.available_identities() + previous = self.answers.get(answer) + if previous and previous not in paths: + paths = (previous, *paths) + terminal = self.terminal + manual = "Enter a private key path" + while paths: + selected = terminal.choose( + "SSH administrator private key", + (*paths, manual), + previous or paths[0], hint=guidance.SSH_IDENTITY, ) - return target + if selected == manual: + break + try: + path = private_key_path(selected) + except InstallError as error: + terminal.error(error) + paths = tuple(path for path in paths if path != selected) + previous = None + else: + self.answers[answer] = path + return path + return self.ask( + name, + "ssh_identity", + "SSH administrator private key file", + validate=private_key_path, + hint=guidance.SSH_IDENTITY, + ) + + def choose_host_key(self, name, host, port): + answer = (name, "host_key") + previous = self.answers.get(answer) + trusted = ssh_keys.trusted_keys(host, port) + terminal = self.terminal + keep = "Use the previously selected host key" + paste = "Paste a verified public key" + manual = "Use a file with the verified public key" + choices = (*((keep,) if previous else ()), *trusted, paste, manual) + while True: + selected = terminal.choose( + f"SSH host identity for {host}", + choices, + choices[0], + hint=( + "This key identifies the destination server. Use a key " + "already trusted in root's known_hosts or verify the " + "destination key through its console." + ), + ) + try: + if selected == keep: + path = verified_key_path(previous, name) + elif selected == manual: + path = self.ask( + name, + "host_key", + "Verified destination public key file", + validate=lambda value: verified_key_path(value, name), + hint=guidance.SSH_HOST_KEY, + ) + else: + key = trusted.get(selected) + if selected == paste: + key = " ".join( + terminal.prompt( + "Verified host public key", + hint=( + "Paste /etc/ssh/ssh_host_ed25519_key.pub " + "from the destination console." + ), + ).split()[:2] + ) + ssh_keys.fingerprint(key) + path = ssh_keys.store_host_key(host, port, key) + except (InstallError, OSError) as error: + terminal.error(error) + else: + self.answers[answer] = path + return path def hosting(self): self.terminal.heading("Hosting and DNS defaults") diff --git a/deploy/panel_installer/remote.py b/deploy/panel_installer/remote.py index 27c2096..37fbd43 100644 --- a/deploy/panel_installer/remote.py +++ b/deploy/panel_installer/remote.py @@ -64,6 +64,60 @@ def bootstrap_archive(settings): return output.getvalue() +def ssh_failure(code, stderr): + message = stderr.decode("utf-8", errors="replace").lower() + for clues, guidance in ( + ( + ("host key verification failed", "remote host identification"), + "The SSH host key did not match. Check the destination host key " + "on its console before updating the selected key.", + ), + ( + ("load key", "unprotected private key", "identity file"), + "SSH could not load the selected private key unattended. Check " + "the file, its permissions and whether it needs a passphrase.", + ), + ( + ("permission denied (", "too many authentication failures"), + "SSH rejected the administrator login. Check the username and " + "authorize the matching public key on the destination.", + ), + ( + ("sudo:",), + "SSH connected, but sudo failed. Give the selected administrator " + "noninteractive sudo access and retry.", + ), + ( + ("could not resolve hostname", "name or service not known"), + "The SSH hostname could not be resolved from this server. " + "Check DNS or use a reachable IP address.", + ), + ( + ( + "connection refused", + "connection timed out", + "no route", + "network is unreachable", + ), + "The SSH port could not be reached from this server. Check the " + "address, port, route and destination SSH service.", + ), + ( + ("/usr/bin/python3: not found", "no module named"), + "The remote installer could not start in Python. Check that " + "the destination has Python 3 and a supported OS.", + ), + ): + if any(clue in message for clue in clues): + return guidance + if code == 255: + return "The SSH connection closed. Check the destination SSH service." + return ( + f"The remote command exited with status {code}. Check sudo access " + "and whether another installer is running on the destination." + ) + + def ssh_bootstrap(target, settings, *, check=False, report=False): identity = Path(target.ssh_identity) engine.root_file(identity, 0o600) @@ -129,7 +183,17 @@ def ssh_bootstrap(target, settings, *, check=False, report=False): label=( "Check SSH host identity, administrator key and sudo access" if check - else "Install the destination. Check SSH, sudo and its journal" + else "Check destination over SSH" + if settings.get("role") == "cluster-check" + else "Install the destination over SSH" + ), + failure=lambda code, stderr: ( + ssh_failure(code, stderr) + + ( + "" + if report or check + else " See journalctl -t coulobre-bootstrap on the host." + ) ), timeout=( 25 diff --git a/deploy/panel_installer/ssh_keys.py b/deploy/panel_installer/ssh_keys.py new file mode 100644 index 0000000..8f743d1 --- /dev/null +++ b/deploy/panel_installer/ssh_keys.py @@ -0,0 +1,102 @@ +"""Select an installer identity and pin a trusted SSH destination.""" + +import pwd +import re +import stat +from hashlib import sha256 +from pathlib import Path + +from . import engine +from .config import InstallError + + +def root_ssh_directory(): + return Path(pwd.getpwuid(0).pw_dir) / ".ssh" + + +def root_controlled(path, kind): + try: + info = path.lstat() + except OSError: + return False + return kind(info.st_mode) and info.st_uid == 0 and not info.st_mode & 0o022 + + +def available_identities(): + directory = root_ssh_directory() + if not root_controlled(directory, stat.S_ISDIR): + return () + identities = [] + for path in sorted(directory.iterdir()): + try: + engine.root_file(path, 0o600) + with path.open("rb") as stream: + header = stream.readline(96) + except (InstallError, OSError): + continue + if re.fullmatch(rb"-----BEGIN [A-Z ]*PRIVATE KEY-----\r?\n", header): + identities.append(str(path)) + return tuple(identities) + + +def fingerprint(key): + if not re.fullmatch( + r"(?:ssh-|ecdsa-sha2-)[a-z0-9@.\-]+ [A-Za-z0-9+/=]+", key + ): + raise InstallError("Paste the verified SSH host public key.") + result = engine.run( + "ssh-keygen", + "-lf", + "-", + source=f"{key}\n".encode("ascii"), + label="Validate the SSH host public key", + ) + match = re.search(r"\bSHA256:[A-Za-z0-9+/]+", result) + if match is None: + raise InstallError("Read the fingerprint of the SSH host public key.") + return match[0] + + +def trusted_keys(host, port): + directory = root_ssh_directory() + path = directory / "known_hosts" + if not root_controlled(directory, stat.S_ISDIR) or not root_controlled( + path, stat.S_ISREG + ): + return {} + endpoint = host if port == 22 else f"[{host}]:{port}" + try: + entries = engine.run( + "ssh-keygen", + "-F", + endpoint, + "-f", + path, + label="Look up the destination in root's known_hosts", + ) + except InstallError: + return {} + trusted, revoked = {}, set() + for line in entries.splitlines(): + fields = line.split() + if len(fields) >= 4 and fields[0] == "@revoked": + revoked.add(" ".join(fields[2:4])) + if len(fields) < 3 or fields[0].startswith(("#", "@")): + continue + key = " ".join(fields[1:3]) + try: + label = f"{fields[1]} {fingerprint(key)}" + except InstallError: + continue + trusted[label] = key + return {label: key for label, key in trusted.items() if key not in revoked} + + +def store_host_key(host, port, key): + directory = engine.STATE / "ssh-host-keys" + engine.root_directory(engine.STATE, mode=0o700) + engine.root_directory(directory, mode=0o700) + digest = sha256(f"{host}:{port}\n{key}".encode("ascii")).hexdigest() + path = directory / f"{digest}.pub" + engine.put_file(path, key + "\n", mode=0o600) + return str(path) diff --git a/deploy/panel_installer/terminal.py b/deploy/panel_installer/terminal.py index 273da70..10df0a1 100644 --- a/deploy/panel_installer/terminal.py +++ b/deploy/panel_installer/terminal.py @@ -14,9 +14,12 @@ class PreviousStepError(Exception): class PlainTerminal: step = None can_go_back = False + context = "" + supports_key_picker = False def heading(self, title): - print(f"\n=== {title} ===", flush=True) + context = f"{self.context}\n" if self.context else "" + print(f"\n{context}=== {title} ===", flush=True) def show(self, message): print(message, flush=True) @@ -50,6 +53,8 @@ class PlainTerminal: class ScreenTerminal: + supports_key_picker = True + def __init__(self, window, curses): self.window = window self.curses = curses @@ -57,6 +62,7 @@ class ScreenTerminal: self.notes = [] self.problem = "" self.step = None + self.context = "" self.can_go_back = False self.scroll = 0 @@ -102,25 +108,33 @@ class ScreenTerminal: if self.step: title += f" Step {self.step[0]} of {self.step[1]}" self._line(0, title, width, self.curses.A_REVERSE) - self._line(2, self.title, width, self.curses.A_BOLD) - - problem = wrap(self.problem, width)[:2] - footer = height - 2 - problem_row = footer - len(problem) - 1 + self._line(2, self.context, width, self.curses.A_DIM) + self._line(3, self.title, width, self.curses.A_BOLD) choice_rows = min(len(choices), 5) - prompt_rows = choice_rows + 2 if choices else int(text is not None) + 2 - label_row = problem_row - prompt_rows + prompt_rows = choice_rows or int(text is not None) notes = [line for note in self.notes for line in wrap(note, width)] - notes.extend(wrap(hint, width)) - capacity = max(0, label_row - 4) + headers = [*wrap(self.problem, width), *wrap(hint, width)] + capacity = max(1, height - prompt_rows - 10) + if label: + capacity = min(capacity, max(9, len(headers))) + notes = headers + notes max_scroll = max(0, len(notes) - capacity) + if not label: + self.scroll = max_scroll self.scroll = min(self.scroll, max_scroll) - for row, line in enumerate( - notes[self.scroll : self.scroll + capacity], 3 - ): - self._line(row, line, width) + visible = notes[self.scroll : self.scroll + capacity] + problem_lines = len(wrap(self.problem, width)) + for index, line in enumerate(visible): + attr = ( + self.curses.A_BOLD + if self.scroll + index < problem_lines + else 0 + ) + self._line(index + 4, line, width, attr) + label_row = 5 + len(visible) if max_scroll: - self._line(label_row - 1, "Page Up / Page Down for details", width) + self._line(label_row, "Page Up / Page Down for details", width) + label_row += 1 self._line(label_row, label, width, self.curses.A_BOLD) cursor_position = None @@ -143,14 +157,18 @@ class ScreenTerminal: ) cursor_position = (label_row + 1, min(width, cursor - first + 1)) - for row, line in enumerate(problem, problem_row): - self._line(row, line, width, self.curses.A_BOLD) footer_text = "Enter Next Esc Cancel" if choices: footer_text = "↑/↓ Select " + footer_text if self.can_go_back: footer_text += " F2 Back" - self._line(footer, footer_text, width, self.curses.A_DIM) + if label: + self._line( + label_row + prompt_rows + 2, + footer_text, + width, + self.curses.A_DIM, + ) if cursor_position: with suppress(self.curses.error): win.move(*cursor_position) diff --git a/docs/deployment.md b/docs/deployment.md index 0a4252c..cca03d5 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -179,7 +179,15 @@ The first panel entry runs locally. Each other panel entry supplies its own public name, SSH destination, administrator and hosting defaults. Supply a verified host public key for each SSH destination and an account with noninteractive sudo. Keep the administrative SSH private keys on -the first server. +the first server. The terminal wizard lists compatible root-owned keys +in `/root/.ssh`. You can also enter a path to another private key with +mode `0600`. Authorize its matching public key on each destination. + +The destination host key identifies the server you are connecting to. +Choose an existing trust entry from root's `known_hosts`, paste the +destination key after verifying it through its console, or use a verified +public key file. The wizard saves selected or pasted host keys as public +key files for reuse with the exported TOML inventory. The inventory can include a shared mail receiver, a shared DNS receiver, or both roles on one dedicated host. A panel can publish DNS locally, use @@ -189,11 +197,18 @@ uses a separate scoped key on the receiver. Assign the hosted domains each panel owns. An empty domain list allows health checks and denies domain operations until you [assign domains to the panel](#limit-linked-provisioning-to-assigned-domains). -Review all hosts before installing. The wizard checks pinned SSH +The wizard carries SSH credentials, panel access mode, administrator +details, DNS mode, and nameservers forward as editable defaults where +applicable. Enter each host's address, hostname, host key and domains +separately. Press `F2` to go back between sections in the terminal wizard. + +Choose **Check connections** on the review screen. The wizard checks pinned SSH authentication and sudo, supported destination releases, distinct host identities, and whether existing panel or receiver settings are compatible. Local certificate files are checked on the host that will use them. -If a check fails, edit the inventory or correct access and retry. +If a check fails, the wizard shows the destination and the action to take. +Edit the inventory or correct access and retry. Choose **Install** once +all checks have passed. Use the [example cluster inventory](../deploy/cluster-install.toml.example) to automate the same process. Make each panel's `admin.password_file` a root-owned `0600` file on the first server. diff --git a/tests/test_cluster_installer.py b/tests/test_cluster_installer.py index 03ddeb1..0757356 100644 --- a/tests/test_cluster_installer.py +++ b/tests/test_cluster_installer.py @@ -7,12 +7,16 @@ from io import StringIO from pathlib import Path from unittest.mock import Mock, patch -from deploy.panel_installer import cluster +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 @@ -203,6 +207,97 @@ class ClusterInstallerTests(unittest.TestCase): 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", diff --git a/tests/test_panel_installer.py b/tests/test_panel_installer.py index c36f2dc..769955d 100644 --- a/tests/test_panel_installer.py +++ b/tests/test_panel_installer.py @@ -215,7 +215,7 @@ class InstallerParametersTests(unittest.TestCase): "edit", "192.0.2.34", "", - "", + str(host_key), "", "", "",