From c944f9cb2343a9f5e44733f5c12aa4b3fc1a8688 Mon Sep 17 00:00:00 2001 From: Peter van Arkel Date: Sun, 22 Nov 2026 15:38:27 +0100 Subject: [PATCH] Run scheduled jobs under the provisioned website identity --- deploy/systemd/coulobre-website-jobs.socket | 14 ++++ deploy/systemd/coulobre-website-jobs@.service | 30 ++++++++ src/coulobre/web_node.py | 8 ++ src/coulobre/web_node_jobs.py | 74 +++++++++++++++++++ src/coulobre/website_job.py | 56 ++++++++++++++ 5 files changed, 182 insertions(+) create mode 100644 deploy/systemd/coulobre-website-jobs.socket create mode 100644 deploy/systemd/coulobre-website-jobs@.service create mode 100644 src/coulobre/web_node_jobs.py create mode 100644 src/coulobre/website_job.py diff --git a/deploy/systemd/coulobre-website-jobs.socket b/deploy/systemd/coulobre-website-jobs.socket new file mode 100644 index 0000000..76d3b50 --- /dev/null +++ b/deploy/systemd/coulobre-website-jobs.socket @@ -0,0 +1,14 @@ +[Unit] +Description=Coulobre website job socket + +[Socket] +ListenStream=/run/coulobre-website-jobs.sock +SocketUser=root +SocketGroup=coulobre-website-job-requests +SocketMode=0660 +Accept=yes +MaxConnections=4 +RemoveOnStop=true + +[Install] +WantedBy=sockets.target diff --git a/deploy/systemd/coulobre-website-jobs@.service b/deploy/systemd/coulobre-website-jobs@.service new file mode 100644 index 0000000..9657bff --- /dev/null +++ b/deploy/systemd/coulobre-website-jobs@.service @@ -0,0 +1,30 @@ +[Unit] +Description=Coulobre scheduled website job +CollectMode=inactive-or-failed + +[Service] +Type=exec +# The system service starts as root and switches to the website user. +WorkingDirectory=/opt/coulobre +ExecStart=/opt/coulobre/bin/coulobre-web-node job-request +StandardInput=socket +StandardOutput=socket +StandardError=journal +CapabilityBoundingSet=CAP_SETUID CAP_SETGID CAP_DAC_READ_SEARCH +NoNewPrivileges=true +PrivateTmp=true +PrivateDevices=true +ProtectSystem=strict +ProtectHome=true +ProtectProc=invisible +ProtectControlGroups=true +ReadWritePaths=/srv/coulobre/web +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 +RestrictNamespaces=true +RestrictSUIDSGID=true +MemoryMax=256M +TasksMax=32 +CPUQuota=100% +RuntimeMaxSec=75s +TimeoutStopSec=5s +KillMode=control-group diff --git a/src/coulobre/web_node.py b/src/coulobre/web_node.py index 9d975e7..59ec68e 100644 --- a/src/coulobre/web_node.py +++ b/src/coulobre/web_node.py @@ -497,6 +497,9 @@ def main(argv=None): commands.add_parser( "files-request", help="Handle a scoped website file operation." ) + commands.add_parser( + "job-request", help="Run a scheduled job as the website user." + ) args = parser.parse_args(argv) if args.command == "restore-site" and args.replace and args.file is None: parser.error("--replace requires --file.") @@ -506,6 +509,11 @@ def main(argv=None): return serve_website_files() + if args.command == "job-request": + from .web_node_jobs import serve_website_job + + return serve_website_job() + if args.command == "apply-request": return serve_apply_request( MANIFEST_VERSION, diff --git a/src/coulobre/web_node_jobs.py b/src/coulobre/web_node_jobs.py new file mode 100644 index 0000000..d53e985 --- /dev/null +++ b/src/coulobre/web_node_jobs.py @@ -0,0 +1,74 @@ +import fcntl +import os +import subprocess +import sys + +from . import web_node_apply as web +from .node_stream import encode_header, read_header +from .web_node_access import website_suspension_path +from .website_job import JOB_RUNTIME, WebsiteJobRequest + +MAX_REQUEST_HEADER = 16 * 1024 + + +def execute_website_job(request): + if os.geteuid() != 0: + raise ValueError("Run the website job receiver as root.") + site = request.site + with web.locked_web_node(fcntl.LOCK_SH): + if os.path.lexists(website_suspension_path(site)): + raise ValueError("The website is suspended.") + public, uid, _ = web.site_storage(site) + account = web.current_user(site.service_user) + if account is None or account.pw_uid != uid or uid == 0: + raise ValueError("The website user is unavailable.") + runtime = web.SitePaths.for_site(site).runtime + try: + process = subprocess.run( + ["/bin/sh", "-s"], + input=(request.command + "\n").encode("utf-8"), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + cwd=public, + env={ + "PATH": "/usr/local/bin:/usr/bin:/bin", + "HOME": str(public), + "USER": site.service_user, + "LOGNAME": site.service_user, + "LANG": "C.UTF-8", + "TZ": "UTC", + "PHP_CLI": f"/usr/bin/php{runtime.version}", + }, + user=uid, + group=account.pw_gid, + extra_groups=[], + umask=0o027, + timeout=JOB_RUNTIME, + check=False, + ) + except subprocess.TimeoutExpired: + return {"timed_out": True, "exit_code": None} + return {"timed_out": False, "exit_code": process.returncode} + + +def serve_website_job(): + run_id = "" + try: + request = WebsiteJobRequest.from_manifest( + read_header( + sys.stdin.buffer, + maximum=MAX_REQUEST_HEADER, + label="scheduled website job request", + ) + ) + run_id = request.run_id + result = execute_website_job(request) + response = {"state": "configured", "problem": None, **result} + except (OSError, ValueError): + response = { + "state": "failed", + "problem": "The web node could not start the website job.", + } + sys.stdout.buffer.write(encode_header({"run_id": run_id, **response})) + sys.stdout.buffer.flush() + return 0 diff --git a/src/coulobre/website_job.py b/src/coulobre/website_job.py new file mode 100644 index 0000000..0ec8e5c --- /dev/null +++ b/src/coulobre/website_job.py @@ -0,0 +1,56 @@ +from dataclasses import dataclass +from uuid import UUID + +from .web_node import WebSite + +JOB_SOCKET = "/run/coulobre-website-jobs.sock" +JOB_RUNTIME = 60 +MAX_JOB_COMMAND_LENGTH = 1000 + + +def validate_command(command): + if ( + not isinstance(command, str) + or not command.strip() + or len(command) > MAX_JOB_COMMAND_LENGTH + or any(not char.isprintable() for char in command) + ): + raise ValueError("Enter a single-line shell command.") + + +@dataclass(frozen=True) +class WebsiteJobRequest: + site: WebSite + run_id: str + command: str + + def __post_init__(self): + if ( + not isinstance(self.run_id, str) + or UUID(self.run_id).hex != self.run_id + ): + raise ValueError("Expected a scheduled job run identifier.") + validate_command(self.command) + + @classmethod + def from_manifest(cls, data): + if ( + not isinstance(data, dict) + or set(data) != {"version", "site", "run_id", "command"} + or type(data["version"]) is not int + or data["version"] != 1 + ): + raise ValueError("Expected a version 1 scheduled job request.") + return cls( + WebSite.from_manifest(data["site"]), + data["run_id"], + data["command"], + ) + + def manifest(self): + return { + "version": 1, + "site": self.site.manifest(), + "run_id": self.run_id, + "command": self.command, + }