From e68e54288f55d5e5853bd36c03fea2982edd506a Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sun, 22 Nov 2026 21:21:39 +0100 Subject: [PATCH 1/5] Streamline authenticator enrollment and recovery code copying --- docs/deployment.md | 7 +++--- pyproject.toml | 1 + src/coulobre/hosting/sign_in.py | 23 ++++++++++++++++--- src/coulobre/hosting/static/hosting/panel.css | 18 +++++++++++++++ .../hosting/authentication_card.html | 17 ++++++++++++-- .../hosting/factor_recovery_codes.html | 12 ++++++---- .../hosting/test_panel_authentication.py | 20 +++++++++++++++- 7 files changed, 85 insertions(+), 13 deletions(-) diff --git a/docs/deployment.md b/docs/deployment.md index 09fbba0..9a069b9 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -281,8 +281,9 @@ restarting the panel, worker, and scheduler. A privileged user signs in with a password to start first-time setup. The setup session can only enroll a second factor or sign out. Choose an -authenticator app, enter the displayed time-based key, and confirm a code -from the app. Use the authenticator's code at future sign-ins. Keep the +authenticator app, scan the QR code, and confirm a code from the app. The +setup page also provides a link and a copyable setup key for manual entry. +Use the authenticator's code at future sign-ins. Keep the panel host and authenticator device clocks synchronized. If an SMTP relay is configured and the account already has a valid email @@ -291,7 +292,7 @@ the address assigned to the account at enrollment. These codes expire in five minutes and can be requested once a minute. An authenticator is the preferred option for privileged accounts. -Save the recovery codes shown after enrollment. Each code works once and +Use **Copy recovery codes** to save the codes shown after enrollment. Each code works once and can be entered after the account password. If the user loses the factor and all recovery codes, verify their identity and issue a replacement enrollment code on the panel host. diff --git a/pyproject.toml b/pyproject.toml index 554c288..b6e3b98 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,6 +16,7 @@ dependencies = [ "cryptography>=45", "dnspython>=2.7,<3", "idna>=3,<4", + "qrcode>=8.2,<9", ] [project.scripts] diff --git a/src/coulobre/hosting/sign_in.py b/src/coulobre/hosting/sign_in.py index e7b8924..7bef1d9 100644 --- a/src/coulobre/hosting/sign_in.py +++ b/src/coulobre/hosting/sign_in.py @@ -1,5 +1,6 @@ import base64 +import qrcode from django import forms from django.contrib.auth import logout from django.contrib.auth.views import LoginView, redirect_to_login @@ -13,6 +14,7 @@ from django.views.decorators.debug import ( ) from django.views.generic import FormView from django_otp.plugins.otp_email.models import EmailDevice +from qrcode.image.svg import SvgPathFillImage from .panel_factors import ( SETUP_SESSION, @@ -94,6 +96,11 @@ class PanelLoginView(LoginView): return redirect("panel:factor_verify") super().form_valid(form) start_initial_setup(self.request, destination) + if not email_factor_available(user): + device = begin_enrollment(user, "authenticator") + if device is not None: + self.request.session[SETUP_SESSION] = device.persistent_id + return redirect("panel:factor_confirm") return redirect("panel:factor_enroll") @@ -244,6 +251,10 @@ class EnrollFactorView(FactorView): def get(self, request, *args, **kwargs): if confirmed_device(self.user): return redirect("panel:factor_verify") + if self.initial_setup and device_for_user( + self.user, request.session.get(SETUP_SESSION), confirmed=False + ): + return redirect("panel:factor_confirm") return super().get(request, *args, **kwargs) def get_form_kwargs(self): @@ -277,7 +288,7 @@ class EnrollFactorView(FactorView): class ConfirmFactorView(FactorView): heading = "Confirm your second factor" - instructions = "Enter a code to complete setup." + instructions = "Enter a verification code to complete setup." submit_label = "Confirm" form_class = ConfirmFactorForm @@ -291,15 +302,21 @@ class ConfirmFactorView(FactorView): return redirect("panel:factor_enroll") return super().get(request, *args, **kwargs) + @sensitive_variables("context", "configuration_url") def get_context_data(self, **kwargs): device = self.current_device() context = {} if isinstance(device, EmailDevice): context["email_factor"] = True elif device: + configuration_url = device.config_url + qr = qrcode.make( + configuration_url, image_factory=SvgPathFillImage + ).to_string(encoding="utf-8") context = { "setup_key": base64.b32encode(device.bin_key).decode(), - "configuration_url": device.config_url, + "configuration_url": configuration_url, + "qr_image": base64.b64encode(qr).decode("ascii"), } return super().get_context_data(**context, **kwargs) @@ -318,5 +335,5 @@ class ConfirmFactorView(FactorView): return render( self.request, "hosting/factor_recovery_codes.html", - {"codes": codes, "destination": destination}, + {"recovery_codes": "\n".join(codes), "destination": destination}, ) diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index 91767ad..c5e557b 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -701,6 +701,24 @@ dd { font-size: 2rem; } +.authenticator-setup { + display: grid; + gap: 0.55rem; + margin-block: 0.75rem 1rem; +} + +.authenticator-qr { + max-width: 100%; + height: auto; + justify-self: center; +} + +.recovery-codes { + width: 100%; + margin-block: 0.75rem; + font-family: monospace; +} + @media (max-width: 780px) { .panel { display: block; diff --git a/src/coulobre/hosting/templates/hosting/authentication_card.html b/src/coulobre/hosting/templates/hosting/authentication_card.html index ba36a51..365d15c 100644 --- a/src/coulobre/hosting/templates/hosting/authentication_card.html +++ b/src/coulobre/hosting/templates/hosting/authentication_card.html @@ -1,9 +1,22 @@ +{% load static %}

{{ heading }}

{% if instructions %}

{{ instructions }}

{% endif %} {% if code_notice %}

{{ code_notice }}

{% endif %} {% if configuration_url %} -

Open in an authenticator app or add a time-based account using this key.

-

{{ setup_key }}

+
+

Scan this QR code with your authenticator app.

+ Authenticator setup QR code +

Open in an authenticator app

+
+ Enter the setup key manually +
+ + +
+

+
+
+ {% endif %} {% if form %}
diff --git a/src/coulobre/hosting/templates/hosting/factor_recovery_codes.html b/src/coulobre/hosting/templates/hosting/factor_recovery_codes.html index 011066c..017b03e 100644 --- a/src/coulobre/hosting/templates/hosting/factor_recovery_codes.html +++ b/src/coulobre/hosting/templates/hosting/factor_recovery_codes.html @@ -1,12 +1,16 @@ {% extends "hosting/base.html" %} +{% load static %} {% block title %}Save your recovery codes · Coulobre Panel{% endblock %} {% block content %}

Save your recovery codes

Keep these codes somewhere safe. Each code lets you sign in once if you lose access to your second factor.

-
    - {% for code in codes %}
  • {{ code }}
  • {% endfor %} -
- Continue to the panel + +
+ + Continue to the panel +
+

+
{% endblock %} diff --git a/src/coulobre/hosting/test_panel_authentication.py b/src/coulobre/hosting/test_panel_authentication.py index 35bb6a9..20047fe 100644 --- a/src/coulobre/hosting/test_panel_authentication.py +++ b/src/coulobre/hosting/test_panel_authentication.py @@ -77,7 +77,25 @@ class PanelAuthenticationTests(TestCase): ) self.assertContains(response, "Save your recovery codes") self.assertIn("no-store", response.headers["Cache-Control"]) - return response.context["codes"] + self.assertContains(response, "Copy recovery codes") + return response.context["recovery_codes"].splitlines() + + @override_settings(EMAIL_HOST="") + def test_authenticator_only_opens_qr_setup_directly(self): + confirm = reverse("panel:factor_confirm") + self.assertRedirects(self.login(self.operator), confirm) + + response = self.client.get(confirm) + self.assertContains(response, "data:image/svg+xml;base64,") + self.assertContains(response, "Enter the setup key manually") + self.assertIn("no-store", response.headers["Cache-Control"]) + device = TOTPDevice.objects.get(user=self.operator) + + self.assertRedirects( + self.client.get(reverse("panel:factor_enroll")), confirm + ) + self.assertEqual(TOTPDevice.objects.get(user=self.operator), device) + self.assertRedirects(Client().get(confirm), reverse("panel:login")) def test_first_password_login_enrolls_and_later_logins_require_a_factor( self, -- 2.43.0 From 23adbe7b2d583e503020f3b32f0141f3c9979dc8 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sun, 22 Nov 2026 21:27:29 +0100 Subject: [PATCH 2/5] Guide full-service installs and report installer progress --- deploy/panel_installer/cli.py | 203 +++++++++++++++++++++++++------ deploy/panel_installer/engine.py | 111 +++++++++++------ deploy/panel_installer/web.py | 71 +++++++++-- tests/test_panel_installer.py | 23 ++++ 4 files changed, 327 insertions(+), 81 deletions(-) diff --git a/deploy/panel_installer/cli.py b/deploy/panel_installer/cli.py index f878df0..2446a93 100644 --- a/deploy/panel_installer/cli.py +++ b/deploy/panel_installer/cli.py @@ -1,7 +1,10 @@ import argparse +import json import os import sys from getpass import getpass +from pathlib import Path +from tempfile import TemporaryDirectory from .config import ( REMOTE_MODES, @@ -27,55 +30,99 @@ def number(value, label): raise InstallError(f"Enter a numeric port for {label}.") from None -def interactive_plan(): - panel = {"hostname": prompt("Panel hostname")} - access = panel["access"] = prompt( - "Panel access (tls, acme, or proxy)", "tls" +def interactive_plan(previous=None): + if previous is None: + preset = prompt( + "Installation profile (full-service or custom)", "full-service" + ) + if preset not in {"full-service", "custom"}: + raise InstallError("Choose full-service or custom.") + defaults = {} + else: + preset = "custom" + defaults = export_parameters(previous, None) + + def ask(label, section, name, fallback=""): + return prompt( + label, str(defaults.get(section, {}).get(name, fallback)) + ) + + full_service = preset == "full-service" + panel = {"hostname": ask("Panel hostname", "panel", "hostname")} + access = panel["access"] = ask( + "Panel access (tls, acme, or proxy)", + "panel", + "access", + "acme" if full_service else "tls", ) if access == "tls": - panel["certificate"] = prompt("Panel certificate path") - panel["key"] = prompt("Panel private key path") + panel["certificate"] = ask( + "Panel certificate path", "panel", "certificate" + ) + panel["key"] = ask("Panel private key path", "panel", "key") elif access == "proxy": - panel["origin_ip"] = prompt("Private origin address") - panel["proxy_ip"] = prompt("Trusted proxy address") + panel["origin_ip"] = ask( + "Private origin address", "panel", "origin_ip" + ) + panel["proxy_ip"] = ask("Trusted proxy address", "panel", "proxy_ip") panel["origin_port"] = number( - prompt("Origin port", "8080"), "the origin" + ask("Origin port", "panel", "origin_port", "8080"), "the origin" ) data = { "panel": panel, "admin": { - "username": prompt("Administrator username", "operator"), - "email": prompt("Administrator email"), + "username": ask( + "Administrator username", "admin", "username", "operator" + ), + "email": ask("Administrator email", "admin", "email"), }, } for name in ("dns", "mail"): - mode = prompt( + mode = ask( f"{name.upper()} role (off, local, remote, or remote-install)", - "off", + name, + "mode", + "local" if full_service else "off", ) target = data[name] = {"mode": mode} if mode in REMOTE_MODES: - target["host"] = prompt( - f"{name.upper()} node SSH hostname or address" + target["host"] = ask( + f"{name.upper()} node SSH hostname or address", name, "host" ) target["port"] = number( - prompt("SSH port", "22"), f"the {name} node" + ask("SSH port", name, "port", "22"), f"the {name} node" + ) + target["host_key"] = ask( + "Verified SSH host public key file", name, "host_key" ) - target["host_key"] = prompt("Verified SSH host public key file") if mode == "remote-install": - target["ssh_user"] = prompt("SSH administrator username") - target["ssh_identity"] = prompt( - "SSH administrator private key file" + target["ssh_user"] = ask( + "SSH administrator username", name, "ssh_user" + ) + target["ssh_identity"] = ask( + "SSH administrator private key file", name, "ssh_identity" ) if name == "mail" and mode in {"local", "remote-install"}: field = "host" if mode == "local" else "mail_hostname" - target[field] = prompt("Public mail hostname") - target["tls"] = prompt("Mail TLS (provided or acme)", "provided") + target[field] = ask( + "Public mail hostname", + name, + field, + panel["hostname"] if mode == "local" else "", + ) + target["tls"] = ask( + "Mail TLS (provided or acme)", + name, + "tls", + "acme" if access == "acme" and mode == "local" else "provided", + ) if target["tls"] == "provided": - target["certificate"] = prompt( - "Certificate path on the mail host" + target["certificate"] = ask( + "Certificate path on the mail host", name, "certificate" + ) + target["key"] = ask( + "Private key path on the mail host", name, "key" ) - target["key"] = prompt("Private key path on the mail host") return parse_plan(data) @@ -86,10 +133,81 @@ def get_password(path): raise InstallError( "Use a terminal or provide a private password file." ) - password = check_password(getpass("Administrator password: ")) - if getpass("Repeat the administrator password: ") != password: - raise InstallError("The administrator passwords differ.") - return password + while True: + try: + password = check_password(getpass("Administrator password: ")) + if getpass("Repeat the administrator password: ") == password: + return password + raise InstallError("The administrator passwords differ.") + except InstallError as error: + print(error, file=sys.stderr) + + +def export_parameters(plan, password_path): + panel = {"hostname": plan.hostname, "access": plan.access} + if plan.access == "tls": + panel.update(certificate=plan.certificate, key=plan.key) + elif plan.access == "proxy": + panel.update( + origin_ip=plan.origin_ip, + origin_port=plan.origin_port, + proxy_ip=plan.proxy_ip, + ) + admin = {"username": plan.admin_username, "email": plan.admin_email} + if password_path: + admin["password_file"] = password_path + parameters = {"panel": panel, "admin": admin} + for name, role in (("dns", plan.dns), ("mail", plan.mail)): + fields = parameters[name] = {"mode": role.mode} + if role.mode in REMOTE_MODES: + fields.update( + host=role.host, host_key=role.host_key, port=role.port + ) + if role.mode == "remote-install": + fields.update( + ssh_user=role.ssh_user, ssh_identity=role.ssh_identity + ) + if name == "mail" and role.mode in {"local", "remote-install"}: + host_key = "host" if role.mode == "local" else "mail_hostname" + fields[host_key] = role.mail_hostname + fields["tls"] = role.tls + if role.tls == "provided": + fields.update(certificate=role.certificate, key=role.key) + return parameters + + +def save_interactive_plan(plan, password_path): + destination = prompt("Save settings to a TOML path (Enter to skip)") + if not destination: + return + path = Path(destination).expanduser() + exists = os.path.lexists(path) + if exists and prompt(f"Replace {path} (yes or no)", "no") != "yes": + return + with TemporaryDirectory(dir=path.parent) as directory: + temporary = Path(directory) / "installation.toml" + with temporary.open("w", encoding="utf-8") as output: + temporary.chmod(0o600) + for section, fields in export_parameters( + plan, password_path + ).items(): + output.write(f"[{section}]\n") + for name, value in fields.items(): + encoded = json.dumps(value, ensure_ascii=False).replace( + "\x7f", "\\u007f" + ) + output.write(f"{name} = {encoded}\n") + output.write("\n") + if exists: + os.replace(temporary, path) + else: + os.link(temporary, path) + print(f"Saved installation settings to {path}.") + if not password_path: + print( + "Provide a private administrator password file " + "when reusing the plan." + ) def main(argv=None): @@ -154,19 +272,32 @@ def main(argv=None): ) password = read_password(password_path) else: - plan = interactive_plan() - print(plan.description(), flush=True) - if ( - prompt("Install with these settings (yes or no)", "no").lower() - != "yes" - ): + plan = None + while True: + plan = interactive_plan(plan) + print(plan.description(), flush=True) + if plan.access == "acme" or plan.mail.tls == "acme": + print( + "Let's Encrypt requires public DNS and inbound HTTP " + "for each selected hostname." + ) + decision = prompt( + "Install with these settings (yes, edit, or no)", "no" + ).lower() + if decision != "edit": + break + if decision != "yes": return 0 + save_interactive_plan(plan, options.admin_password_file) password = get_password(options.admin_password_file) if options.check: print(plan.description()) return 0 installer = Installer( - plan, password, lambda message: print(message, flush=True) + plan, + password, + lambda message: print(message, flush=True), + heartbeat=sys.stdout.isatty(), ) installer.install() return 0 diff --git a/deploy/panel_installer/engine.py b/deploy/panel_installer/engine.py index 882e052..24e3e27 100644 --- a/deploy/panel_installer/engine.py +++ b/deploy/panel_installer/engine.py @@ -10,9 +10,10 @@ import subprocess import sys import time import tomllib -from contextlib import contextmanager +from contextlib import contextmanager, nullcontext from pathlib import Path from tempfile import TemporaryDirectory +from threading import Event, Thread from . import certificates, roles from .config import REMOTE_MODES, InstallError, platform_settings @@ -198,7 +199,7 @@ def systemctl(*args): ) -def install_packages(packages, *, mail_host=""): +def install_packages(packages, *, mail_host="", step=nullcontext): status = subprocess.run( ["dpkg-query", "-W", "-f=${db:Status-Status} ${Package}\n", *packages], stdin=subprocess.DEVNULL, @@ -224,26 +225,28 @@ def install_packages(packages, *, mail_host=""): source=answers.encode(), label="Choose the local Postfix installation profile", ) - run( - "apt-get", - "update", - label="Refresh the configured APT repositories", - env=apt_env, - timeout=600, - ) - run( - "apt-get", - "install", - "--yes", - "--no-upgrade", - *packages, - label="Install the required APT packages", - env=apt_env, - timeout=1800, - ) + with step("Refreshing APT repositories"): + run( + "apt-get", + "update", + label="Refresh the configured APT repositories", + env=apt_env, + timeout=600, + ) + with step("Installing system packages"): + run( + "apt-get", + "install", + "--yes", + "--no-upgrade", + *packages, + label="Install the required APT packages", + env=apt_env, + timeout=1800, + ) -def install_release(release): +def install_release(release, *, step=nullcontext): root_directory(VENV.parent) if os.path.lexists(VENV): root_directory(VENV) @@ -276,15 +279,16 @@ def install_release(release): for key in ("PIP_NO_INDEX", "PIP_FIND_LINKS") if key in os.environ } - run( - BINDIR / "pip", - "install", - "--disable-pip-version-check", - with_extras, - label="Install Coulobre and its Python dependencies", - env=pip_env, - timeout=1200, - ) + with step("Installing Coulobre and its Python dependencies"): + run( + BINDIR / "pip", + "install", + "--disable-pip-version-check", + with_extras, + label="Install Coulobre and its Python dependencies", + env=pip_env, + timeout=1200, + ) @contextmanager @@ -308,15 +312,45 @@ def install_lock(): class Installer: - def __init__(self, plan, password, progress): + def __init__(self, plan, password, progress, *, heartbeat=False): self.plan = plan self.password = password self.progress = progress + self.heartbeat = heartbeat self.state_file = STATE / "installation.json" self.php, self.modern_mail = platform_settings() with (SOURCE / "pyproject.toml").open("rb") as project: self.release = tomllib.load(project)["project"]["version"] + @contextmanager + def step(self, label): + started = time.monotonic() + finished = Event() + self.progress(f"{label}.") + + def report_elapsed(): + while not finished.wait(15): + elapsed = int(time.monotonic() - started) + self.progress(f"{label}… {elapsed}s elapsed.") + + thread = Thread(target=report_elapsed) if self.heartbeat else None + if thread is not None: + thread.start() + try: + yield + except (InstallError, OSError, ValueError): + self.progress( + f"{label} failed after {int(time.monotonic() - started)}s." + ) + raise + finally: + finished.set() + if thread is not None: + thread.join() + self.progress( + f"{label} completed in {int(time.monotonic() - started)}s." + ) + def save_state(self): put_file( self.state_file, @@ -421,10 +455,13 @@ class Installer: "Environment=RABBITMQ_CONFIG_FILE=/etc/coulobre-rabbitmq.conf\n", ) systemctl("daemon-reload") - systemctl( - "enable", "--now", "mariadb.service", "rabbitmq-server.service" - ) - systemctl("restart", "mariadb.service", "rabbitmq-server.service") + for name, unit in ( + ("MariaDB", "mariadb.service"), + ("RabbitMQ", "rabbitmq-server.service"), + ): + with self.step(f"Starting {name} on loopback"): + systemctl("enable", "--now", unit) + systemctl("restart", unit) def mariadb(sql): return run( @@ -679,11 +716,13 @@ class Installer: install_packages( self.packages(), mail_host=mail.host if mail.mode == "local" else "", + step=self.step, ) - install_release(self.release) + install_release(self.release, step=self.step) self.install_certificates() self.progress("Preparing MariaDB and RabbitMQ on loopback.") - self.configure_stores() + with self.step("Configuring database and message broker access"): + self.configure_stores() self.progress( "Configuring hosting service identities and provisioning." ) diff --git a/deploy/panel_installer/web.py b/deploy/panel_installer/web.py index 77bcc93..5f34a0a 100644 --- a/deploy/panel_installer/web.py +++ b/deploy/panel_installer/web.py @@ -1,4 +1,5 @@ import hmac +import re import secrets import time from dataclasses import dataclass, field @@ -15,11 +16,14 @@ from .engine import Installer COOKIE = "coulobre_installer" MAX_FORM = 16384 FORM = """ +

Full-service setup is recommended for a public single server. The panel, +websites, databases, DNS and mail run locally. Adjust the settings below +for a different deployment.

Panel @@ -49,8 +53,9 @@ def role_form(name): "' '' + "" "' "