diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 85c7fa0..a955899 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -44,6 +44,9 @@ jobs: ruff format --check . sh -n tests/web-node/smoke.sh sh -n deploy/certbot/reload-apache.sh + sh -n deploy/debian/postinst + sh -n deploy/debian/prerm + sh -n deploy/debian/coulobre-install - name: Check Django configuration and migrations run: | @@ -61,3 +64,8 @@ jobs: python -m pip install build python -m build python tools/check_core_release.py dist/*.tar.gz dist/*.whl + python tools/build_deb.py dist/*.tar.gz dist/*.whl + umask 077 + python tools/build_deb.py dist/*.tar.gz dist/*.whl --output rebuilt + cmp dist/*.deb rebuilt/*.deb + dpkg-deb --info dist/*.deb diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 13aedeb..7e7e7c5 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -75,6 +75,39 @@ subsequent changes. instructions, and known limitations. Mark a release candidate as a prerelease. Close the milestone when its target version is published. +### Build and publish the Debian package + +Build from the same verified source distribution and wheel used for the +release. The builder reads the package version and timestamp from the reviewed +Git revision, and rejects inputs which differ from it. + +```sh +python tools/build_deb.py dist/*.tar.gz dist/*.whl --ref "$tag" +sha256sum dist/coulobre-panel_*.deb +``` + +Verify a fresh installation and an upgrade with existing data on Ubuntu 26.04 +and Debian 13. Include the checked package and its SHA-256 checksum in the +release. After release review, publish the same file to each supported suite +in the [Hippogrief Debian registry][debian-registry]. Use `resolute` and +`trixie` as the suites, `main` as the component for final versions, and +`candidate` for release candidates. + +```sh +registry=https://code.hosting.hippogrief.nl/api/packages/hippogrief/debian +for suite in resolute trixie; do + curl --fail-with-body --user "$GITEA_USER" --upload-file "$deb" \ + "$registry/pool/$suite/$component/upload" +done +``` + +Set `deb` to the checked artifact. When prompted by curl, use a Gitea token +with permission to publish packages. In the registry, link the package to +`hippogrief/coulobre` and verify that clients can install it using the +[documented signed APT configuration][apt-installation]. + +### Prepare a web update + For a release tested through the web updater, generate and attach `web-update.json` alongside the matching wheel. List each tested starting package version after the wheel path. Only list versions that can upgrade @@ -169,3 +202,5 @@ python tools/web_update_manifest.py dist/coulobre_panel-0.10.2rc1-py3-none-any.w Run the development checks before submitting a pull request. Gitea Actions checks Python 3.12 and 3.14. [Development checks](docs/development.md#checks) +[debian-registry]: https://docs.gitea.com/usage/packages/debian/ +[apt-installation]: docs/deployment.md#use-the-gitea-apt-repository diff --git a/deploy/debian/coulobre-install b/deploy/debian/coulobre-install new file mode 100644 index 0000000..a8a48c8 --- /dev/null +++ b/deploy/debian/coulobre-install @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +exec /usr/bin/python3 /usr/share/coulobre-panel/source/deploy/install-panel.py "$@" diff --git a/deploy/debian/postinst b/deploy/debian/postinst new file mode 100644 index 0000000..2321b6b --- /dev/null +++ b/deploy/debian/postinst @@ -0,0 +1,14 @@ +#!/bin/sh +set -eu + +if [ "$1" != configure ] || [ ! -e /etc/coulobre/panel.env ]; then + exit 0 +fi + +systemd-run --quiet --wait --pipe --collect \ + --property=EnvironmentFile=/etc/coulobre/panel.env \ + --setenv=PYTHONPATH=/usr/share/coulobre-panel/source/src \ + /opt/coulobre/bin/python -P -m coulobre.package_upgrade + +systemctl daemon-reload +systemctl enable --now coulobre-remote-deploy.socket diff --git a/deploy/debian/prerm b/deploy/debian/prerm new file mode 100644 index 0000000..1d94808 --- /dev/null +++ b/deploy/debian/prerm @@ -0,0 +1,6 @@ +#!/bin/sh +set -eu + +if [ "$1" = remove ] && [ -d /run/systemd/system ]; then + systemctl disable --now coulobre-remote-deploy.socket +fi diff --git a/deploy/panel_installer/engine.py b/deploy/panel_installer/engine.py index 9f09a13..a95b319 100644 --- a/deploy/panel_installer/engine.py +++ b/deploy/panel_installer/engine.py @@ -279,6 +279,14 @@ def install_release(release, *, step=nullcontext): if installed and ready == "1": return with_extras = f"{SOURCE}[server,mariadb]" + if Path("/usr/share/coulobre-panel/source") == SOURCE: + bundled = ( + SOURCE.parent + / "wheel" + / (f"coulobre_panel-{release}-py3-none-any.whl") + ) + root_file(bundled, 0o644) + with_extras = f"{bundled}[server,mariadb]" pip_env = { key: os.environ[key] for key in ("PIP_NO_INDEX", "PIP_FIND_LINKS") @@ -887,6 +895,8 @@ class Installer: install_unit("coulobre-update.socket") install_unit("coulobre-update@.service") workers.append("coulobre-update.socket") + if Path("/usr/share/coulobre-panel/source") == SOURCE: + workers.append("coulobre-remote-deploy.socket") systemctl("daemon-reload") systemctl( "enable", "--now", *PANEL_UNITS, *workers, "apache2.service" diff --git a/pyproject.toml b/pyproject.toml index 5ac231e..1dcff53 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "coulobre-panel" -version = "0.12.0" +version = "0.13.0rc1" description = "A web hosting control panel for hosting providers and resellers." readme = "README.md" requires-python = ">=3.12" diff --git a/src/coulobre/hosting/templates/hosting/updates.html b/src/coulobre/hosting/templates/hosting/updates.html index 94be3a3..d33c04e 100644 --- a/src/coulobre/hosting/templates/hosting/updates.html +++ b/src/coulobre/hosting/templates/hosting/updates.html @@ -17,7 +17,9 @@ {% endif %} {% endif %} - {% if not updater_enabled %} + {% if apt_managed %} +

This panel is managed by APT. Apply Coulobre package updates from the server console.

+ {% elif not updater_enabled %}

Enable the local updater socket on an installer-managed panel to use web updates.

{% elif catalog_problem %}

{{ catalog_problem }}

diff --git a/src/coulobre/hosting/update_views.py b/src/coulobre/hosting/update_views.py index 1c5c5ef..b4a9929 100644 --- a/src/coulobre/hosting/update_views.py +++ b/src/coulobre/hosting/update_views.py @@ -89,6 +89,9 @@ class UpdateView(UserPassesTestMixin, FormView): context["update_status"] = topology.get("status", {}) context["linked_nodes"] = nodes context["preflight_problem"] = topology.get("problem") + context["apt_managed"] = topology.get("apt_managed", False) + if context["apt_managed"]: + return context try: context["releases"] = cache.get_or_set( f"coulobre-updates:{installed}", diff --git a/src/coulobre/local_update.py b/src/coulobre/local_update.py index 4d0980d..bcad5ca 100644 --- a/src/coulobre/local_update.py +++ b/src/coulobre/local_update.py @@ -18,6 +18,7 @@ from tempfile import TemporaryDirectory from .linked_updates import linked_roles, receiver_status, staged_for_release from .release_updates import ( SHA256, + Release, UpdateError, download_wheel, selected_release, @@ -57,6 +58,7 @@ MANAGED_UNITS = frozenset( "coulobre-offsite-worker.service", "coulobre-operator-apply.socket", "coulobre-operator-worker.service", + "coulobre-remote-deploy.socket", "coulobre-folder-sftp.socket", "coulobre-provisioner.service", "coulobre-service-credentials.socket", @@ -73,6 +75,7 @@ VENV = Path("/opt/coulobre") PYTHON = VENV / "bin/python" CONFIG = Path("/etc/coulobre/panel.env") INSTALLATION = Path("/var/lib/coulobre-installer/installation.json") +DEB_WHEEL = Path("/usr/share/coulobre-panel/wheel") ROOT_COMMAND_ENV = { "PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C.UTF-8", @@ -319,7 +322,7 @@ def check_dependencies(wheel, log): ) from None -def apply_update(status, request, hostname): +def apply_update(status, request, hostname, *, package_wheel=None): backup = STATE / datetime.now(UTC).strftime("recovery-%Y%m%dT%H%M%S%fZ") backup.mkdir(mode=0o700) status["recovery"] = backup.name @@ -330,13 +333,17 @@ def apply_update(status, request, hostname): TemporaryDirectory(dir=STATE) as download, ): try: - release = selected_release( - request["version"], - status["installed_version"], - request["sha256"], - ) publish_status(status, "running", "Verifying the release package.") - wheel = download_wheel(release, download) + if package_wheel is None: + release = selected_release( + request["version"], + status["installed_version"], + request["sha256"], + ) + wheel = download_wheel(release, download) + else: + release = Release(request["version"], "", False, "") + wheel = package_wheel check_dependencies(wheel, log) check_installation(release.version) active = active_units(log) @@ -496,8 +503,16 @@ def handle_request(peer): problem=str(error), ) else: - reply(peer, accepted=True, status=display_status(), nodes=nodes) + reply( + peer, + accepted=True, + status=display_status(), + nodes=nodes, + apt_managed=DEB_WHEEL.is_dir(), + ) return + if DEB_WHEEL.is_dir(): + raise UpdateError("Upgrade this APT-managed panel from the host.") with LOCK.open("a") as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) diff --git a/src/coulobre/operator_node.py b/src/coulobre/operator_node.py index 5354d20..4dae787 100644 --- a/src/coulobre/operator_node.py +++ b/src/coulobre/operator_node.py @@ -132,6 +132,14 @@ def packages(request): raise ValueError( "Review this package update from the server console." ) + if any( + line.split()[1:2] == ["coulobre-panel"] + or line.startswith("Inst coulobre-panel:") + for line in plan["packages"] + ): + raise ValueError( + "Apply Coulobre package updates from the server console." + ) if plan["count"]: command( APT, diff --git a/src/coulobre/package_upgrade.py b/src/coulobre/package_upgrade.py new file mode 100644 index 0000000..1e62665 --- /dev/null +++ b/src/coulobre/package_upgrade.py @@ -0,0 +1,64 @@ +"""Apply the packaged wheel using the panel recovery workflow.""" + +import fcntl +import os +from importlib.metadata import version + +from . import local_update +from .release_updates import UpdateError, version_key, wheel_name + +PREFIX = "coulobre_panel-" +SUFFIX = "-py3-none-any.whl" + + +def upgrade_package(): + if os.geteuid() != 0: + raise UpdateError("Run the package upgrade as root.") + directory = local_update.DEB_WHEEL + wheels = list(directory.glob(f"{PREFIX}*{SUFFIX}")) + if len(wheels) != 1 or not all( + local_update.root_controlled(path) + for path in (directory.parent, directory, *wheels) + ): + raise UpdateError("The packaged release wheel is unavailable.") + wheel = wheels[0] + target = wheel.name.removeprefix(PREFIX).removesuffix(SUFFIX) + if wheel_name(target) != wheel.name or not wheel.is_file(): + raise UpdateError("The packaged release wheel is invalid.") + state = local_update.STATE + state.mkdir(mode=0o700, exist_ok=True) + if not local_update.root_controlled(state): + raise UpdateError("The upgrade state directory is not protected.") + with local_update.LOCK.open("a") as lock: + os.fchmod(lock.fileno(), 0o600) + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if local_update.read_status().get("state") in { + "running", + "recovery_required", + }: + raise UpdateError("Resolve the previous update before retrying.") + installed = version("coulobre-panel") + if installed == target: + return + if version_key(installed) >= version_key(target): + raise UpdateError("Use the recovery procedure to downgrade.") + hostname = local_update.check_installation(target) + status = { + "installed_version": installed, + "target_version": target, + "actor": "APT", + } + local_update.apply_update( + status, {"version": target}, hostname, package_wheel=wheel + ) + if status.get("state") != "succeeded": + raise UpdateError( + status.get("message", "The package upgrade failed.") + ) + + +if __name__ == "__main__": + try: + upgrade_package() + except (OSError, UpdateError) as error: + raise SystemExit(str(error)) from None diff --git a/tools/build_deb.py b/tools/build_deb.py new file mode 100644 index 0000000..449718f --- /dev/null +++ b/tools/build_deb.py @@ -0,0 +1,112 @@ +"""Build a Debian package from reviewed Coulobre release artifacts.""" + +import argparse +import os +import shutil +import subprocess +import tarfile +import tomllib +from pathlib import Path +from tempfile import TemporaryDirectory + +from check_core_release import ROOT, git_files, verify_release + + +def build_package(source, wheel, ref, output): + verify_release(source, wheel, ref) + project = tomllib.loads(git_files(ref)["pyproject.toml"].decode())[ + "project" + ] + version = project["version"].replace("rc", "~rc") + epoch = subprocess.check_output( + ["git", "show", "-s", "--format=%ct", ref], cwd=ROOT, text=True + ).strip() + output.mkdir(parents=True, exist_ok=True) + target = output / f"coulobre-panel_{version}_all.deb" + with TemporaryDirectory() as temporary: + root = Path(temporary) / "package" + assets = root / "usr/share/coulobre-panel" + source_dir = assets / "source" + source_dir.mkdir(parents=True) + with tarfile.open(source, "r:gz") as archive: + prefix = source.name.removesuffix(".tar.gz") + for member in archive: + if member.isfile(): + destination = source_dir / member.name.removeprefix( + f"{prefix}/" + ) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(archive.extractfile(member).read()) + destination.chmod(0o755 if member.mode & 0o111 else 0o644) + (assets / "wheel").mkdir() + packaged_wheel = assets / "wheel" / wheel.name + shutil.copyfile(wheel, packaged_wheel) + packaged_wheel.chmod(0o644) + control = root / "DEBIAN" + control.mkdir() + metadata = control / "control" + metadata.write_text( + f"Package: coulobre-panel\nVersion: {version}\n" + "Architecture: all\nSection: web\nPriority: optional\n" + "Maintainer: Hippogrief \n" + "Depends: python3 (>= 3.12), python3-venv, ca-certificates, " + "openssh-client\n" + "Description: Coulobre web hosting control panel\n" + " Deployment assets for supported Ubuntu and Debian systems.\n" + ) + metadata.chmod(0o644) + sbin = root / "usr/sbin" + sbin.mkdir() + for name, directory in ( + ("postinst", control), + ("prerm", control), + ("coulobre-install", sbin), + ): + path = directory / name + shutil.copyfile(source_dir / "deploy/debian" / name, path) + path.chmod(0o755) + units = root / "usr/lib/systemd/system" + units.mkdir(parents=True) + for name in ( + "coulobre-remote-deploy.socket", + "coulobre-remote-deploy@.service", + ): + path = units / name + shutil.copyfile(source_dir / "deploy/systemd" / name, path) + path.chmod(0o644) + doc = root / "usr/share/doc/coulobre-panel" + doc.mkdir(parents=True) + shutil.copyfile(source_dir / "LICENSE", doc / "copyright") + (doc / "copyright").chmod(0o644) + root.chmod(0o755) + for path in root.rglob("*"): + if path.is_dir(): + path.chmod(0o755) + os.utime(path, (int(epoch), int(epoch))) + subprocess.run( + [ + "dpkg-deb", + "--root-owner-group", + "-Zxz", + "--build", + root, + target, + ], + env=os.environ | {"SOURCE_DATE_EPOCH": epoch}, + check=True, + ) + return target + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("source", type=Path) + parser.add_argument("wheel", type=Path) + parser.add_argument("--ref", default="HEAD") + parser.add_argument("--output", type=Path, default=Path("dist")) + args = parser.parse_args() + print(build_package(args.source, args.wheel, args.ref, args.output)) + + +if __name__ == "__main__": + main()