Files
coulobre/src/coulobre/local_feature_setup.py
T

452 lines
15 KiB
Python

"""Install the local services used by the panel's feature controls."""
import argparse
import fcntl
import grp
import os
import pwd
import re
import subprocess
from contextlib import contextmanager
from dataclasses import dataclass
from importlib.metadata import version
from pathlib import Path
from tempfile import TemporaryDirectory
from . import local_update
from .linked_updates import REMOTE_MODES, receiver_status
from .node_files import (
check_root_file,
read_root_file,
replace_configuration,
require_root_directory,
write_new_file,
)
from .release_updates import Release, UpdateError
PACKAGE_ASSETS = Path("/usr/share/coulobre-panel/source/deploy")
SYSTEMD = Path("/etc/systemd/system")
SYSTEMCTL = "/usr/bin/systemctl"
CERTBOT = Path("/usr/bin/certbot")
SSHD = Path("/usr/sbin/sshd")
SFTP_SSHD_CONFIG = Path("/etc/ssh/sshd_config.d/00-coulobre-sftp.conf")
class UnsupportedFolderSftpError(ValueError):
pass
@dataclass(frozen=True)
class LocalFeature:
setting: str
group: str
socket: str
worker: str = ""
drop_in: str = ""
extra_units: tuple[str, ...] = ()
@property
def units(self):
return (
f"{self.socket}.socket",
f"{self.socket}@.service",
*((f"{self.worker}.service",) if self.worker else ()),
*((self.drop_in,) if self.drop_in else ()),
*self.extra_units,
)
@property
def activation_unit(self):
if self.worker:
return f"{self.worker}.service"
return f"{self.socket}.socket"
LOCAL_FEATURES = {
"website-files": LocalFeature(
"WEB_FILE_MANAGER",
"coulobre-file-requests",
"coulobre-website-files",
drop_in="coulobre-panel.service.d/website-files.conf",
),
"website-jobs": LocalFeature(
"WEBSITE_JOBS",
"coulobre-website-job-requests",
"coulobre-website-jobs",
worker="coulobre-website-job-worker",
),
"website-sftp": LocalFeature(
"LOCAL_WEB_SFTP",
"coulobre-sftp-provisioning",
"coulobre-sftp-apply",
worker="coulobre-sftp-provisioner",
),
"folder-sftp": LocalFeature(
"LOCAL_FOLDER_SFTP",
"coulobre-sftp-provisioning",
"coulobre-folder-sftp",
extra_units=("coulobre-folder-sftp-mounts.service",),
),
"account-backups": LocalFeature(
"LOCAL_ACCOUNT_BACKUPS",
"coulobre-backup-requests",
"coulobre-account-backup",
worker="coulobre-backup-worker",
),
"website-https": LocalFeature(
"LOCAL_WEB_HTTPS",
"coulobre-https-provisioning",
"coulobre-https-apply",
worker="coulobre-https-provisioner",
),
"mailbox-passwords": LocalFeature(
"MAILBOX_PASSWORD_CHANGES",
"coulobre-mail-passwords",
"coulobre-mail-passwords",
drop_in="coulobre-panel.service.d/mailbox-passwords.conf",
),
}
def install_files(files, *, package_assets):
to_create = []
for source, destination, mode in files:
if package_assets:
require_root_directory(source.parent)
content = read_root_file(source)
else:
content = source.read_text(encoding="utf-8")
require_root_directory(destination.parent, create_mode=0o755)
try:
installed = read_root_file(destination, mode=mode)
except FileNotFoundError:
to_create.append((destination, content, mode))
else:
if installed != content:
raise ValueError(f"Review the existing file at {destination}.")
for destination, content, mode in to_create:
write_new_file(destination, content, mode=mode)
def create_service_identity(group, worker, command):
groups = (group, worker) if worker else (group,)
for name in dict.fromkeys(groups):
try:
grp.getgrnam(name)
except KeyError:
command("/usr/sbin/groupadd", "--system", name)
if not worker:
return
primary = grp.getgrnam(worker).gr_gid
try:
account = pwd.getpwnam(worker)
except KeyError:
command(
"/usr/sbin/useradd",
"--system",
"--gid",
worker,
"--no-create-home",
"--home-dir",
"/nonexistent",
"--shell",
"/usr/sbin/nologin",
worker,
)
else:
if (
account.pw_uid == 0
or account.pw_gid != primary
or account.pw_dir != "/nonexistent"
or account.pw_shell != "/usr/sbin/nologin"
or set(os.getgrouplist(worker, primary)) != {primary}
):
raise ValueError(f"Review the existing service user {worker}.")
def prepare_https(assets, command):
from .web_node_tls import ACME_WEBROOT, CERTBOT_ROOT
if not CERTBOT.is_file() or not (CERTBOT_ROOT / "accounts").is_dir():
raise ValueError(
"Set up Certbot with an ACME account for hosted websites first."
)
files = (
(
assets / "apache/acme.conf.example",
Path("/etc/apache2/conf-available/coulobre-acme.conf"),
0o644,
),
(
assets / "certbot/reload-apache.sh",
CERTBOT_ROOT / "renewal-hooks/deploy/coulobre-apache",
0o755,
),
)
for path in (
ACME_WEBROOT,
ACME_WEBROOT / ".well-known",
ACME_WEBROOT / ".well-known/acme-challenge",
CERTBOT_ROOT / "renewal-hooks",
):
require_root_directory(path, create_mode=0o755)
install_files(files, package_assets=assets == PACKAGE_ASSETS)
command("/usr/sbin/a2enmod", "ssl")
command("/usr/sbin/a2enconf", "coulobre-acme")
command("/usr/sbin/apache2ctl", "configtest")
def prepare_sftp(assets, command):
from .web_node_sftp import AUTHORIZED_KEYS, SFTP_GROUP
if not SSHD.is_file():
raise ValueError("Install OpenSSH Server before enabling SFTP.")
require_root_directory(Path("/run/sshd"), create_mode=0o755)
try:
command(str(SSHD), "-t")
except ValueError:
raise ValueError(
"The existing OpenSSH configuration failed sshd -t."
) from None
require_root_directory(AUTHORIZED_KEYS, create_mode=0o755)
create_service_identity(SFTP_GROUP, "", command)
created = not os.path.lexists(SFTP_SSHD_CONFIG)
install_files(
(
(
assets / "openssh/coulobre-sftp.conf.example",
SFTP_SSHD_CONFIG,
0o644,
),
),
package_assets=assets == PACKAGE_ASSETS,
)
try:
command(str(SSHD), "-t")
if active("ssh.service"):
command(SYSTEMCTL, "reload", "ssh.service")
except (OSError, ValueError) as error:
if created:
SFTP_SSHD_CONFIG.unlink()
raise ValueError(
"Could not validate or reload the Coulobre OpenSSH configuration."
) from error
def check_folder_sftp_filesystem():
from .web_node_apply import WEB_ROOT
from .web_node_folder_sftp import (
JAIL_ROOT,
bind_folder,
is_bound,
run_mount,
)
require_root_directory(WEB_ROOT.parent, create_mode=0o755)
require_root_directory(WEB_ROOT, create_mode=0o755)
require_root_directory(JAIL_ROOT, create_mode=0o755)
with (
TemporaryDirectory(dir=WEB_ROOT) as source,
TemporaryDirectory(dir=JAIL_ROOT) as target,
):
mountpoint = Path(target)
fd = os.open(source, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
bind_folder(fd, os.fstat(fd), mountpoint, 65534, 65534)
except ValueError:
raise UnsupportedFolderSftpError(
"The filesystem or kernel does not support ID-mapped SFTP "
"mounts for the website directory."
) from None
finally:
os.close(fd)
if is_bound(mountpoint):
run_mount("/usr/bin/umount", str(mountpoint))
def prepare_feature(key, assets, command):
feature = LOCAL_FEATURES[key]
if key == "website-sftp":
prepare_sftp(assets, command)
if key == "folder-sftp":
check_folder_sftp_filesystem()
install_files(
(
(assets / "systemd" / unit, SYSTEMD / unit, 0o644)
for unit in feature.units
),
package_assets=assets == PACKAGE_ASSETS,
)
if key == "website-https":
prepare_https(assets, command)
create_service_identity(feature.group, feature.worker, command)
return feature
def enable_setting(text, setting):
entry = f"COULOBRE_{setting}"
pattern = rf"^[ \t]*{entry}[ \t]*=.*$"
matches = re.findall(pattern, text, flags=re.MULTILINE)
if not matches:
if text.rstrip("\n").endswith("\\"):
raise ValueError(f"Review the end of {local_update.CONFIG}.")
if text and not text.endswith("\n"):
text += "\n"
return text + f"{entry}=1\n"
if matches == [f"{entry}=1"]:
return text
if matches == [f"{entry}=0"]:
return re.sub(pattern, f"{entry}=1", text, flags=re.MULTILINE)
raise ValueError(f"Review the existing {entry} setting.")
def active(unit):
return (
subprocess.run(
[SYSTEMCTL, "is-active", "--quiet", unit],
stdin=subprocess.DEVNULL,
env=local_update.ROOT_COMMAND_ENV,
timeout=15,
check=False,
).returncode
== 0
)
def restart_panel(command, hostname):
units = (local_update.PANEL, local_update.WORKER, local_update.BEAT)
command(SYSTEMCTL, "restart", *units, timeout=600)
with open(os.devnull, "wb") as log:
release = Release(version("coulobre-panel"), "", False, "")
local_update.verify_panel(hostname, release, log)
def enable_feature(key, command):
try:
plan = local_update.installation_plan()
except UpdateError as error:
raise ValueError(str(error)) from None
if key == "mailbox-passwords":
if os.environ.get("COULOBRE_LOCAL_MAILBOX_PROVISIONING") != "1":
raise ValueError("Enable mailbox provisioning first.")
if not active("coulobre-mail-apply.socket"):
raise ValueError("Start the mailbox provisioning socket first.")
mail = plan["mail"]
if mail["mode"] in REMOTE_MODES:
node = receiver_status("mail", mail["host"])
if node["state"] != "configured" or node["release"] != version(
"coulobre-panel"
):
raise ValueError(
"The linked mail receiver must be ready and on the "
"same release."
)
elif os.environ.get("COULOBRE_LOCAL_WEB_ACTIVATION") != "1":
raise ValueError("Enable local website provisioning first.")
if key == "account-backups" and (
os.environ.get("COULOBRE_LOCAL_DATABASE_PROVISIONING") != "1"
):
raise ValueError("Enable local database provisioning first.")
if key == "folder-sftp" and (
os.environ.get("COULOBRE_LOCAL_WEB_SFTP") != "1"
or not active("coulobre-sftp-apply.socket")
):
raise ValueError("Enable website SFTP access first.")
with installation_configuration() as config:
apply_feature(key, plan["hostname"], config, command)
return {"enabled": True}
@contextmanager
def installation_configuration():
require_root_directory(PACKAGE_ASSETS)
config = local_update.CONFIG
require_root_directory(config.parent)
check_root_file(config, mode=0o600)
lock = local_update.LOCK
require_root_directory(lock.parent, create_mode=0o700)
fd = os.open(lock, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
with os.fdopen(fd, "rb") as stream:
try:
fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise ValueError(
"An installation update is running. Try again."
) from None
if local_update.read_status().get("state") in {
"running",
"recovery_required",
}:
raise ValueError("Resolve the current installation update first.")
yield config
def apply_feature(key, hostname, config, command):
original = read_root_file(config, mode=0o600)
updated = enable_setting(original, LOCAL_FEATURES[key].setting)
feature = prepare_feature(key, PACKAGE_ASSETS, command)
unit = feature.activation_unit
units = tuple(
dict.fromkeys((unit, f"{feature.socket}.socket", *feature.extra_units))
)
inactive = tuple(name for name in units if not active(name))
already_running = bool(feature.worker and unit not in inactive)
panel_restart_started = False
command(SYSTEMCTL, "daemon-reload")
try:
replace_configuration(config, updated, mode=0o600)
command(
SYSTEMCTL,
"restart" if already_running else "start",
unit,
timeout=600,
)
if key == "website-https":
command(SYSTEMCTL, "reload", "apache2.service")
panel_restart_started = True
restart_panel(command, hostname)
if not all(active(name) for name in units):
raise ValueError("The feature service did not start.")
command(SYSTEMCTL, "enable", unit)
except (OSError, ValueError, UpdateError) as error:
try:
replace_configuration(config, original, mode=0o600)
if inactive:
command(SYSTEMCTL, "stop", *inactive)
if already_running:
command(SYSTEMCTL, "restart", unit, timeout=600)
if panel_restart_started:
restart_panel(command, hostname)
except (OSError, ValueError, UpdateError):
raise ValueError(
"Feature setup failed. Check the panel and service journal."
) from None
raise ValueError(str(error)) from None
def main():
from .operator_node import command
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--skip-unsupported-folder-sftp", action="store_true")
parser.add_argument("assets", type=Path)
parser.add_argument("feature", choices=LOCAL_FEATURES, nargs="+")
args = parser.parse_args()
if os.geteuid() != 0:
parser.exit(1, "Run local feature setup as root.\n")
try:
for key in args.feature:
try:
feature = prepare_feature(key, args.assets.resolve(), command)
except UnsupportedFolderSftpError:
if not args.skip_unsupported_folder_sftp:
raise
continue
print(feature.activation_unit)
except (OSError, ValueError) as error:
parser.exit(1, f"{error}\n")
if __name__ == "__main__":
main()