diff --git a/README.md b/README.md index 363c013..9e2dbf6 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,12 @@ Create a cron job: $ schedls new cleanup --cron --cron-expr '0 4 * * 0' -- /usr/local/bin/cleanup ``` +Create a system cron drop-in as root (runs as `root` unless `--run-as` is given): + +```console +$ sudo schedls new updates --cron --system --daily 03:00 -- /usr/local/bin/updates +``` + Prefer to be guided? Add `-i`/`--interactive` to `new` or `edit` and any omitted field is prompted for. Flags you do pass become pre-filled defaults: @@ -73,9 +79,12 @@ $ schedls new backup -i $ schedls edit backup -i ``` -Interactive mode is line-based (no external editor or pager), requires a -terminal, and cannot be combined with `--json`. The collected values are shown -in the usual preview and still require confirmation before anything is written. +For `new`, the wizard asks for the scope (user or system) unless `--user` or +`--system` was given; a system cron job then asks which user it should run as +(default `root`). Interactive mode is line-based (no external editor or pager), +requires a terminal, and cannot be combined with `--json`. The collected values +are shown in the usual preview and still require confirmation before anything +is written. Inspect, change, disable, remove: diff --git a/docs/architecture.md b/docs/architecture.md index 938f8c9..8c5627a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -82,9 +82,9 @@ Plan ``` The caller previews the plan, obtains confirmation, then calls `apply`. Plans -snapshot existing content so a failed step can be rolled back. Cron plans also -record the previous crontab text and re-check it at apply time to detect -concurrent edits. +snapshot existing content so a failed step can be rolled back. Cron plans +record the previous crontab text or drop-in content and re-check it at apply +time to detect concurrent edits. ## Exit codes @@ -124,4 +124,7 @@ The schema version is `1`. ``` Rules: no ANSI sequences; ISO 8601 timestamps with explicit offsets; stable -field names; missing data is `null`, never invented. +field names; missing data is `null`, never invented. Jobs whose `backend` is +`cron` additionally carry a `cron` object (`expression`, `shell`, `mailto`, +`line`, `user`, `environment`), where `user` is the run-as account for system +entries and `null` for the current user's crontab. diff --git a/docs/cli.md b/docs/cli.md index d617127..4ddc754 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -63,12 +63,20 @@ systemd extras (persistent, jitter, accuracy, working directory, environment). ```console $ schedls new backup --timer --daily 02:00 --persistent -- /usr/local/bin/backup /srv/data $ schedls new cleanup --cron --cron-expr '0 4 * * 0' -- /usr/local/bin/cleanup +$ sudo schedls new updates --cron --system --daily 03:00 -- /usr/local/bin/updates +$ sudo schedls new report --cron --system --daily 04:00 --run-as www-data -- /usr/local/bin/report $ schedls new backup -i ``` Creates a scheduled job. `NAME` and a backend (`--timer` or `--cron`) are required unless `--interactive` is used. +Cron jobs are created for the current user's crontab. With `--system` (root +only) the job is created as an `/etc/cron.d/schedls-NAME` drop-in and runs as +`root` unless `--run-as USER` is given. System cron names may contain letters, +digits, `_` and `-` only, because cron ignores `cron.d` file names containing a +period. `--run-as` is valid only together with `--cron --system`. + The command to run is everything after `--`: ```console @@ -112,6 +120,8 @@ $ schedls rm backup --dry-run ``` Removes a schedls-managed job and its files. Unmanaged jobs cannot be removed. +For a system cron job this removes the `/etc/cron.d/schedls-NAME` drop-in and +refuses to touch anything whose markers no longer match. ### `enable NAME` / `disable NAME` @@ -257,6 +267,9 @@ $ schedls edit backup -i ``` - Prompts use stdin only; no external editor or pager is ever launched. +- `new` asks for the scope (user or system) unless `--user`/`--system` was + given. Choosing system for a cron job also asks which user it should run as + (`--run-as`, default `root`). - A terminal is required. With piped or redirected input, `schedls` exits `3` and asks you to pass flags instead. - Interactive mode cannot be combined with `--json` (exit `2`). diff --git a/docs/cron.md b/docs/cron.md index 8c9dfeb..f59ee73 100644 --- a/docs/cron.md +++ b/docs/cron.md @@ -1,11 +1,25 @@ # cron backend -`schedls` reads and edits the **current user's crontab** through the `crontab` -utility. It never writes to `/var/spool/cron*` directly. +`schedls` reads every cron source visible to it: + +- the **current user's crontab**, through the `crontab` utility; +- **system crontabs**: `/etc/crontab`, `/etc/cron.d/*`; +- **periodic directories**: `/etc/cron.{hourly,daily,weekly,monthly}/*`; +- **other users' crontabs** (`/var/spool/cron/crontabs/*` on Debian-style + systems, `/var/spool/cron/*` elsewhere) when running as root. + +Cron jobs are named after where they live: system entries are `:`, +periodic scripts are named after the script, spool entries are `:`, +and the current user's crontab entries are `cron-`. Jobs created by +`schedls` are listed under their schedule name instead. + +`schedls` writes either through the `crontab` utility (current user) or as an +`/etc/cron.d/schedls-` drop-in (system, root only). It never writes to +`/var/spool/cron*` directly. ## Reading -The crontab is read with `crontab -l` and parsed losslessly into lines: +The user crontab is read with `crontab -l` and parsed losslessly into lines: - blank lines; - comments; @@ -13,12 +27,18 @@ The crontab is read with `crontab -l` and parsed losslessly into lines: - five-field entries and `@` nicknames; - `schedls:begin` / `schedls:end` managed-block markers. +System crontabs add a user field between the schedule and the command +(`min hour dom mon dow USER command`). Files in `/etc/cron.d` whose names +contain a period, and hidden files, are ignored because cron ignores them too. +Periodic directories only contribute executable, run-parts-style file names. + Every unrelated line is preserved exactly. `schedls` does not reformat, sort, normalize, or rewrite crontab content it did not create. ## Managed blocks -Jobs created by `schedls` live in a delimited block: +Jobs created by `schedls` in the current user's crontab live in a delimited +block: ```cron # schedls:begin name=backup @@ -29,6 +49,30 @@ Jobs created by `schedls` live in a delimited block: If markers are malformed or a `begin` has no matching `end`, mutations refuse to proceed rather than guess. +## System drop-ins + +A system cron job is a file named after the schedule: + +```cron +# Managed by schedls +# schedls:begin name=backup +0 2 * * * root /usr/local/bin/backup /srv/data +# schedls:end name=backup +``` + +Only `/etc/cron.d/schedls-` files carrying a matching managed block are +treated as managed. A `schedls-` prefixed file whose markers are missing or +malformed is listed as unmanaged (`schedls-:`) and cannot be +removed. Creating system jobs requires root and a trusted `/etc/cron.d` +directory: not a symlink, owned by root, and not group- or other-writable. +Removal deletes only the drop-in file, after re-checking that it still matches +the snapshot and markers. Cron picks up `/etc/cron.d` changes by itself, so no +daemon reload is issued. + +Use `--run-as USER` to run a system job as another account (default `root`). +The interactive wizard (`schedls new -i`) asks for the scope, and choosing the +system scope for a cron job then prompts for the run-as user. + ## Command rendering Cron executes command text through a shell. `schedls` keeps an argv internally @@ -56,11 +100,16 @@ shell mode from characters such as `|`, `>`, `&&` or `$()`. ## Installation and validation -When the local `crontab` supports syntax testing (`crontab -T`), the new +When the local `crontab` supports syntax testing (`crontab -T`), a new user crontab is validated before installation. The native `crontab` install remains authoritative. The previous crontab text is retained and restored if installation fails or the crontab changed since the plan was prepared. +System drop-ins are validated when they are rendered and written atomically; +`crontab -T` only understands user-format crontabs, so it is not used for them. +A file written by `schedls` is re-read and its managed block verified before +the command reports success. + Capabilities are feature-detected, never assumed: ```python @@ -85,6 +134,8 @@ command-line compatibility but have no effect on cron jobs; see ## Not yet supported -- system cron (`/etc/crontab`, `/etc/cron.d`, periodic directories); -- editing existing cron jobs; -- cross-user crontabs. +- editing cron jobs (user or system); +- token-level updates of `/etc/crontab` (read-only, shared file); +- anacron (`/etc/anacrontab`); +- removing or editing periodic directory scripts; +- modifying other users' spool crontabs (read-only, root only). diff --git a/docs/security-model.md b/docs/security-model.md index 001ba6d..0ad288b 100644 --- a/docs/security-model.md +++ b/docs/security-model.md @@ -58,7 +58,11 @@ never uses it to build a filesystem path: unit names are always derived from the validated job name (`schedls-.timer` / `.service`). Generated unit names are re-validated before they are written to a temporary directory, so a crafted unit cannot redirect writes or removals outside the trusted unit -directory. +directory. System cron drop-ins follow the same rule: the path is always +`/etc/cron.d/schedls-` from the validated schedule name, with letters, +digits, `_` and `-` only, and removal refuses any path that is not exactly the +expected one. System names never contain a period, because cron ignores +`cron.d` files with dots. ### Untrusted output @@ -89,14 +93,18 @@ Configuration is treated as opaque data. Malformed `schedls` cron markers cause mutation to fail closed rather than guess. Unknown crontab lines are preserved byte-for-byte. A systemd unit whose name starts with `schedls-` is only treated as managed when its file carries the `# Managed by schedls` and `# Name:` -markers, so a same-named foreign unit is not modified. +markers, so a same-named foreign unit is not modified. Likewise a +`/etc/cron.d/schedls-` drop-in is only managed when its begin/end markers +match the file name; otherwise it is listed as unmanaged and left alone. ### Partial operations systemd creation writes both units, reloads the manager, and enables the timer; if a later step fails, or the operation is interrupted, the previous state is restored and a partially enabled timer is disabled again. Cron installs are -validated first and restored from the previous crontab text on failure. +validated first and restored from the previous crontab text on failure. System +cron drop-ins are written atomically and a failed multi-file apply restores or +removes whatever it had already written. ### Supply chain @@ -105,6 +113,6 @@ in CI. ## Availability, privacy -`0.1.0` requires `systemd-analyze` to create or validate calendar expressions +`0.2.0` requires `systemd-analyze` to create or validate calendar expressions and refuses the operation if it is unavailable. `schedls` makes no network requests and collects no telemetry. diff --git a/pyproject.toml b/pyproject.toml index 5378de9..b4ea1f0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "schedls" -version = "0.1.0" +version = "0.2.0" description = "Inspect and manage Linux scheduled jobs" authors = [ { name = "Marco D'Aleo", email = "marco@marcodaleo.com" } diff --git a/src/schedls/backends/cron.py b/src/schedls/backends/cron.py index d58ab5c..8d9ea39 100644 --- a/src/schedls/backends/cron.py +++ b/src/schedls/backends/cron.py @@ -4,7 +4,9 @@ from __future__ import annotations import contextlib import os +import pwd import re +import stat import tempfile from collections.abc import Sequence from dataclasses import dataclass, field @@ -28,10 +30,16 @@ from ..models import ( ) from ..renderers import cron as renderer from ..runner import CommandRunner -from ..security import validate_name +from ..security import ( + atomic_write_text, + check_trusted_directory, + remove_file, + validate_name, +) from .base import ( Capabilities, CommandPlan, + FileChange, MutationResult, Plan, SchedulerBackend, @@ -42,6 +50,31 @@ _META_RE = re.compile(r"(?P[A-Za-z_][A-Za-z0-9_]*)=(?P\S+)") _ENV_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*\s*=") _NICKNAME_RE = re.compile(r"^@[A-Za-z]+") +_MANAGED_PREFIX = "schedls-" +_CRON_D_NAME_RE = re.compile(r"\A[A-Za-z0-9_-]+\Z") + + +@dataclass(frozen=True) +class CronPaths: + """Filesystem locations of system cron sources (injectable for tests).""" + + crontab: str = "/etc/crontab" + cron_d: str = "/etc/cron.d" + hourly: str = "/etc/cron.hourly" + daily: str = "/etc/cron.daily" + weekly: str = "/etc/cron.weekly" + monthly: str = "/etc/cron.monthly" + spool_crontabs: str = "/var/spool/cron/crontabs" + spool: str = "/var/spool/cron" + + def periodic_dirs(self) -> dict[str, str]: + return { + "@hourly": self.hourly, + "@daily": self.daily, + "@weekly": self.weekly, + "@monthly": self.monthly, + } + @dataclass class CronCapabilities: @@ -58,6 +91,7 @@ class CrontabEntry: name: str | None = None expression: str | None = None command: str | None = None + user: str | None = None marker_name: str | None = None extra: dict[str, str] = field(default_factory=dict) @@ -72,20 +106,26 @@ class ManagedBlock: class CrontabDocument: - """An exact, line-preserving view of a crontab.""" + """An exact, line-preserving view of a crontab. - def __init__(self, text: str) -> None: + ``system=True`` parses system crontabs (``/etc/crontab``, + ``/etc/cron.d/*``), whose entries carry a user field between the schedule + and the command. + """ + + def __init__(self, text: str, *, system: bool = False) -> None: self.had_trailing_newline = text.endswith("\n") if text else False body = text[:-1] if self.had_trailing_newline else text self.lines: list[str] = body.split("\n") if body != "" else [] + self.system = system self.entries: list[CrontabEntry] = [] self.warnings: list[str] = [] self._blocks: dict[str, ManagedBlock] = {} self._parse() @classmethod - def parse(cls, text: str) -> CrontabDocument: - return cls(text) + def parse(cls, text: str, *, system: bool = False) -> CrontabDocument: + return cls(text, system=system) @property def text(self) -> str: @@ -161,10 +201,10 @@ class CrontabDocument: return CrontabEntry(number, raw, "comment") if _ENV_RE.match(stripped): return CrontabEntry(number, raw, "env") - expression, command = _split_job(stripped) + expression, command, user = _split_job(stripped, system=self.system) if expression is None: return CrontabEntry(number, raw, "comment") - return CrontabEntry(number, raw, "job", expression=expression, command=command) + return CrontabEntry(number, raw, "job", expression=expression, command=command, user=user) # -- queries -------------------------------------------------------------- @@ -212,17 +252,26 @@ class CrontabDocument: return "\n".join(keep) + "\n" -def _split_job(stripped: str) -> tuple[str | None, str | None]: +def _split_job(stripped: str, *, system: bool = False) -> tuple[str | None, str | None, str | None]: nickname = _NICKNAME_RE.match(stripped) if nickname: rest = stripped[nickname.end() :].strip() if not rest: - return None, None - return nickname.group(0), rest - parts = stripped.split(None, 5) - if len(parts) < 6: - return None, None - return " ".join(parts[:5]), parts[5] + return None, None, None + if system: + parts = rest.split(None, 1) + if len(parts) < 2: + return None, None, None + return nickname.group(0), parts[1], parts[0] + return nickname.group(0), rest, None + maxsplit = 6 if system else 5 + parts = stripped.split(None, maxsplit) + needed = maxsplit + 1 + if len(parts) < needed: + return None, None, None + if system: + return " ".join(parts[:5]), parts[6], parts[5] + return " ".join(parts[:5]), parts[5], None class CronBackend(SchedulerBackend): @@ -235,18 +284,32 @@ class CronBackend(SchedulerBackend): validation=True, ) - def __init__(self, runner: CommandRunner) -> None: + def __init__(self, runner: CommandRunner, paths: CronPaths | None = None) -> None: self.runner = runner + self.paths = paths or CronPaths() self._capabilities: CronCapabilities | None = None - def available(self) -> bool: + def crontab_available(self) -> bool: return self.runner.has("crontab") + def file_sources_available(self) -> bool: + candidates = ( + self.paths.crontab, + self.paths.cron_d, + *self.paths.periodic_dirs().values(), + self.paths.spool_crontabs, + self.paths.spool, + ) + return any(os.path.exists(path) for path in candidates) + + def available(self) -> bool: + return self.crontab_available() or self.file_sources_available() + def capabilities_info(self) -> CronCapabilities: if self._capabilities is not None: return self._capabilities info = CronCapabilities() - if self.available(): + if self.crontab_available(): completed = self.runner.run(["crontab", "-V"], env_policy="identity", check=False) output = (completed.stdout or completed.stderr).strip() if completed.returncode != 0 or not output: @@ -289,8 +352,20 @@ class CronBackend(SchedulerBackend): raise OperationalError("could not read the current user's crontab", hint=detail or None) return CrontabDocument(completed.stdout) + # -- discovery ------------------------------------------------------------ + def discover(self, scopes: Sequence[Scope]) -> list[ScheduledJob]: - if Scope.USER not in scopes or not self.available(): + jobs: list[ScheduledJob] = [] + if Scope.USER in scopes: + jobs.extend(self._discover_user_crontab()) + jobs.extend(self._discover_spool_crontabs()) + if Scope.SYSTEM in scopes: + jobs.extend(self._discover_system_crontabs()) + jobs.extend(self._discover_periodic_directories()) + return jobs + + def _discover_user_crontab(self) -> list[ScheduledJob]: + if not self.crontab_available(): return [] document = self.read() jobs: list[ScheduledJob] = [] @@ -337,13 +412,187 @@ class CronBackend(SchedulerBackend): ) return jobs + def _discover_system_crontabs(self) -> list[ScheduledJob]: + jobs: list[ScheduledJob] = [] + jobs.extend(self._discover_system_file(self.paths.crontab, managed_drop_in=False)) + for name in self._list_dir(self.paths.cron_d): + if not _CRON_D_NAME_RE.match(name): + continue + path = os.path.join(self.paths.cron_d, name) + jobs.extend(self._discover_system_file(path, managed_drop_in=True)) + return jobs + + def _discover_system_file(self, path: str, *, managed_drop_in: bool) -> list[ScheduledJob]: + text = _read_text(path) + if text is None: + return [] + document = CrontabDocument(text, system=True) + base = os.path.basename(path) + blocks = document.managed_blocks() + managed_name: str | None = None + warnings: list[str] = [] + if managed_drop_in and base.startswith(_MANAGED_PREFIX): + expected = base[len(_MANAGED_PREFIX) :] + if expected in blocks and not document.warnings: + managed_name = expected + else: + warnings.append( + f"{path} looks like a schedls drop-in but its managed block is missing or " + "malformed; treating its jobs as unmanaged." + ) + elif blocks: + warnings.append( + f"{path} contains schedls block markers but is not a schedls-owned drop-in; " + "treating its jobs as unmanaged." + ) + + jobs: list[ScheduledJob] = [] + managed_range: set[int] = set() + if managed_name is not None: + block = blocks[managed_name] + managed_range = set(range(block.begin_index, block.end_index + 1)) + job_line = next((line for line in block.job_lines if line.kind == "job"), None) + jobs.append( + ScheduledJob( + name=managed_name, + backend=Backend.CRON, + scope=Scope.SYSTEM, + managed=True, + enabled=None, + schedule=Schedule(ScheduleKind.CRON, (job_line.expression or "") if job_line else ""), + command=Command(argv=(), raw=job_line.command if job_line else ""), + source=JobSource("system cron drop-in", path=path, line=block.begin_index), + cron=CronDetails( + expression=job_line.expression if job_line else None, + raw_line=job_line.raw if job_line else None, + line=block.begin_index, + user=job_line.user if job_line else None, + ), + ) + ) + for entry in document.entries: + if entry.kind != "job" or entry.index in managed_range: + continue + jobs.append( + ScheduledJob( + name=f"{base}:{entry.index}", + backend=Backend.CRON, + scope=Scope.SYSTEM, + managed=False, + enabled=None, + schedule=Schedule(ScheduleKind.CRON, entry.expression or ""), + command=Command(argv=(), raw=entry.command or ""), + source=JobSource("system cron", path=path, line=entry.index), + cron=CronDetails( + expression=entry.expression, + raw_line=entry.raw, + line=entry.index, + user=entry.user, + ), + warnings=tuple(warnings), + ) + ) + return jobs + + def _discover_periodic_directories(self) -> list[ScheduledJob]: + jobs: list[ScheduledJob] = [] + for expression, directory in self.paths.periodic_dirs().items(): + for name in self._list_dir(directory): + if not _CRON_D_NAME_RE.match(name): + continue + path = os.path.join(directory, name) + try: + st = os.stat(path) + except OSError: + continue + if not stat.S_ISREG(st.st_mode) or not st.st_mode & 0o111: + continue + jobs.append( + ScheduledJob( + name=name, + backend=Backend.CRON, + scope=Scope.SYSTEM, + managed=False, + enabled=None, + schedule=Schedule(ScheduleKind.CRON, expression), + command=Command(argv=(), raw=path), + source=JobSource(f"{os.path.basename(directory)} (run-parts)", path=path, line=None), + cron=CronDetails(expression=expression, user="root"), + ) + ) + return jobs + + def _discover_spool_crontabs(self) -> list[ScheduledJob]: + if os.geteuid() != 0: + return [] + directory = self._spool_directory() + if directory is None: + return [] + current_user = self._current_user() + jobs: list[ScheduledJob] = [] + for name in self._list_dir(directory): + if name.startswith(".") or name == current_user: + continue + path = os.path.join(directory, name) + if not os.path.isfile(path): + continue + text = _read_text(path) + if text is None: + continue + document = CrontabDocument(text) + for entry in document.entries: + if entry.kind != "job": + continue + jobs.append( + ScheduledJob( + name=f"{name}:{entry.index}", + backend=Backend.CRON, + scope=Scope.USER, + managed=False, + enabled=None, + schedule=Schedule(ScheduleKind.CRON, entry.expression or ""), + command=Command(argv=(), raw=entry.command or ""), + source=JobSource(f"user crontab ({name})", path=path, line=entry.index), + cron=CronDetails( + expression=entry.expression, + raw_line=entry.raw, + line=entry.index, + user=name, + ), + ) + ) + return jobs + + def _spool_directory(self) -> str | None: + if os.path.isdir(self.paths.spool_crontabs): + return self.paths.spool_crontabs + if os.path.isdir(self.paths.spool): + return self.paths.spool + return None + + @staticmethod + def _current_user() -> str: + try: + return pwd.getpwuid(os.geteuid()).pw_name + except KeyError: + return "" + + @staticmethod + def _list_dir(directory: str) -> list[str]: + try: + return sorted(os.listdir(directory)) + except OSError: + return [] + # -- planning ------------------------------------------------------------- def plan_create(self, spec: JobSpec) -> Plan: validate_name(spec.name) + if spec.scope is Scope.SYSTEM: + return self._plan_create_system(spec) if spec.scope is not Scope.USER: - raise SafetyRefusalError("system cron management is not supported.") - if not self.available(): + raise SafetyRefusalError("unsupported cron scope.") + if not self.crontab_available(): raise OperationalError("crontab is not available") expression = renderer.validate_expression(spec.cron_expression or "") line = renderer.render_line(expression, spec.command) @@ -360,6 +609,7 @@ class CronBackend(SchedulerBackend): plan.commands = self._install_commands(new_text) plan.warnings.append("Cron executes command text through /bin/sh (or the crontab's configured SHELL).") plan.payload = { + "mode": "crontab", "action": "create", "name": spec.name, "old_text": document.text, @@ -367,12 +617,55 @@ class CronBackend(SchedulerBackend): } return plan + def _plan_create_system(self, spec: JobSpec) -> Plan: + if os.geteuid() != 0: + raise SafetyRefusalError( + "creating a system cron job requires appropriate privileges.", + hint="Run the command under sudo yourself if that is your intention:\n sudo schedls new ... --system", + ) + renderer.validate_system_name(spec.name) + directory = self.paths.cron_d + if not os.path.isdir(directory): + raise OperationalError(f"system cron directory does not exist: {directory}") + check_trusted_directory(directory, expected_uid=0) + expression = renderer.validate_expression(spec.cron_expression or "") + run_as = renderer.validate_run_as(spec.run_as or "root") + line = renderer.render_system_line(expression, spec.command, run_as) + content = renderer.render_system_file(spec.name, [line]) + path = os.path.join(directory, f"{_MANAGED_PREFIX}{spec.name}") + if os.path.lexists(path): + raise ConflictError( + f"schedule {spec.name!r} already exists ({path}).", + hint="Use 'schedls rm' instead.", + ) + plan = Plan(backend=self.name, action="create") + plan.summary = [ + ("Backend", "cron (system)"), + ("Schedule", expression), + ("Run as", run_as), + ("Command", spec.command.display()), + ("File", path), + ] + plan.files = [FileChange(path=path, content=content, mode=0o644, expected_uid=0)] + plan.warnings.append("Cron executes command text through /bin/sh (or the crontab's configured SHELL).") + plan.payload = { + "mode": "file", + "action": "create", + "name": spec.name, + "path": path, + "expected_uid": 0, + "snapshots": {path: None}, + } + return plan + def plan_remove(self, job: ScheduledJob) -> Plan: if not job.managed: raise SafetyRefusalError( f"{job.name} was not created by schedls.", hint="schedls will not modify unmanaged schedules by default.", ) + if job.scope is Scope.SYSTEM: + return self._plan_remove_system(job) document = self.read() new_text = document.without_block(job.name) plan = Plan(backend=self.name, action="remove") @@ -382,6 +675,7 @@ class CronBackend(SchedulerBackend): ] plan.commands = self._install_commands(new_text) plan.payload = { + "mode": "crontab", "action": "remove", "name": job.name, "old_text": document.text, @@ -389,12 +683,49 @@ class CronBackend(SchedulerBackend): } return plan + def _plan_remove_system(self, job: ScheduledJob) -> Plan: + if os.geteuid() != 0: + raise SafetyRefusalError( + "removing a system cron job requires appropriate privileges.", + hint="Run the command under sudo yourself if that is your intention:\n sudo schedls rm ...", + ) + path = job.source.path + expected_path = os.path.join(self.paths.cron_d, f"{_MANAGED_PREFIX}{job.name}") + if path != expected_path: + raise SafetyRefusalError(f"refusing to remove unexpected system cron file: {path!r}") + content = _read_text(path) + if content is None: + raise OperationalError(f"could not read {path}") + document = CrontabDocument(content, system=True) + if document.warnings or document.find_block(job.name) is None: + raise SafetyRefusalError(f"{path} is no longer a valid schedls-managed drop-in; refusing to remove it.") + plan = Plan(backend=self.name, action="remove") + plan.summary = [ + ("Backend", "cron (system)"), + ("Will remove", path), + ] + plan.files = [FileChange(path=path, content=None, expected_uid=0)] + plan.payload = { + "mode": "file", + "action": "remove", + "name": job.name, + "path": path, + "expected_uid": 0, + "snapshots": {path: content}, + } + return plan + def _install_commands(self, new_text: str) -> list[CommandPlan]: return [CommandPlan(("crontab", "-"), "install crontab", "identity", input_text=new_text)] # -- applying ------------------------------------------------------------- def apply(self, plan: Plan) -> MutationResult: + if plan.payload.get("mode") == "file": + return self._apply_file(plan) + return self._apply_crontab(plan) + + def _apply_crontab(self, plan: Plan) -> MutationResult: old_text = plan.payload.get("old_text", "") new_text = plan.payload.get("new_text", "") current_document = self.read() @@ -417,6 +748,53 @@ class CronBackend(SchedulerBackend): messages=["Crontab updated."], ) + def _apply_file(self, plan: Plan) -> MutationResult: + snapshots: dict[str, str | None] = plan.payload.get("snapshots", {}) + expected_uid = plan.payload.get("expected_uid", 0) + written: list[str] = [] + try: + for change in plan.files: + if _read_text(change.path) != snapshots.get(change.path): + raise SafetyRefusalError( + f"{change.path} changed on disk after the plan was prepared; refusing to apply." + ) + if change.content is None: + if remove_file(change.path, expected_uid=expected_uid): + written.append(change.path) + else: + atomic_write_text( + change.path, + change.content, + mode=change.mode, + expected_uid=expected_uid, + ) + written.append(change.path) + except BaseException as exc: + self._rollback_file(written, snapshots, expected_uid) + if isinstance(exc, KeyboardInterrupt | SystemExit): + raise + if isinstance(exc, OperationalError | SafetyRefusalError): + raise + raise OperationalError(str(exc)) from exc + self._verify_installed(plan) + action = plan.payload.get("action") + message = "System cron drop-in installed." if action == "create" else "System cron drop-in removed." + return MutationResult(changed=bool(written), messages=[message]) + + def _rollback_file( + self, + written: list[str], + snapshots: dict[str, str | None], + expected_uid: int | None, + ) -> None: + for path in reversed(written): + previous = snapshots.get(path) + with contextlib.suppress(Exception): + if previous is None: + remove_file(path, expected_uid=expected_uid) + else: + atomic_write_text(path, previous, mode=0o644, expected_uid=expected_uid) + def _validate(self, text: str) -> None: if not self.capabilities_info().supports_validation: return @@ -433,11 +811,26 @@ class CronBackend(SchedulerBackend): os.unlink(name) def _verify_installed(self, plan: Plan) -> None: - document = self.read() name = plan.payload.get("name") + if plan.payload.get("mode") == "file": + if plan.payload.get("action") != "create" or not name: + return + document = CrontabDocument(_read_text(plan.payload.get("path", "")) or "", system=True) + if name not in document.managed_blocks(): + raise OperationalError("the drop-in was written but the schedls block could not be verified.") + return + document = self.read() if plan.payload.get("action") == "create" and name and name not in document.managed_blocks(): raise OperationalError("the crontab was installed but the schedls block could not be verified.") def _restore(self, text: str) -> None: with contextlib.suppress(Exception): self.runner.run(["crontab", "-"], env_policy="identity", check=False, input_text=text) + + +def _read_text(path: str) -> str | None: + try: + with open(path, encoding="utf-8") as handle: + return handle.read() + except OSError: + return None diff --git a/src/schedls/cli.py b/src/schedls/cli.py index ba0bdcf..240a755 100644 --- a/src/schedls/cli.py +++ b/src/schedls/cli.py @@ -172,6 +172,11 @@ def _add_schedule_options(parser: argparse.ArgumentParser, *, creation: bool) -> def _add_creation_options(parser: argparse.ArgumentParser) -> None: _add_schedule_options(parser, creation=True) + parser.add_argument( + "--run-as", + metavar="USER", + help="run a system cron job as USER (default: root)", + ) _add_mutation_flags(parser) @@ -496,6 +501,8 @@ def _spec_for_new(args: argparse.Namespace, tail: list[str]) -> JobSpec: if args.timer: if args.cron_expr: raise UsageError("--cron-expr is a cron option; use --calendar for systemd timers.") + if args.run_as: + raise UsageError("--run-as is a system cron option.") calendar = _calendar_from_args(args) if not calendar: raise UsageError("no schedule given.", hint="Use --calendar or a convenience flag such as --daily.") @@ -517,14 +524,20 @@ def _spec_for_new(args: argparse.Namespace, tail: list[str]) -> JobSpec: raise UsageError("--jitter/--accuracy/--persistent/--working-directory are systemd options.") if args.env: raise UsageError("--env is a systemd option; cron environment variables are not supported yet.") - if _resolve_scope(args) is Scope.SYSTEM: - raise UsageError( - "--system is not supported for cron jobs.", - hint="Cron jobs are always created for the current user.", - ) expression = _cron_expression_from_args(args) if not expression: raise UsageError("no schedule given.", hint="Use --cron-expr or a convenience flag such as --daily.") + if scope is Scope.SYSTEM: + return JobSpec( + name=args.name, + backend=Backend.CRON, + scope=Scope.SYSTEM, + command=command, + cron_expression=expression, + run_as=args.run_as or "root", + ) + if args.run_as: + raise UsageError("--run-as requires --system for cron jobs.", hint="Cron jobs run as the current user.") return JobSpec( name=args.name, backend=Backend.CRON, @@ -607,6 +620,22 @@ def _wizard_backend(args: argparse.Namespace, prompter: Prompter) -> Backend: return Backend.CRON +def _wizard_scope(args: argparse.Namespace, backend: Backend, prompter: Prompter) -> Scope: + provided = getattr(args, "scope_group", None) or getattr(args, "scope_filter", None) + if provided is not None: + return Scope(provided) + if backend is Backend.SYSTEMD: + options = [("user", "user timer"), ("system", "system timer (root)")] + else: + options = [ + ("user", "current user's crontab"), + ("system", "system drop-in /etc/cron.d (root)"), + ] + selected = prompter.choice("Scope:", options, default="user") + args.scope_group = Scope.SYSTEM if selected == "system" else Scope.USER + return Scope(args.scope_group) + + def _wizard_command(args: argparse.Namespace, tail: list[str], prompter: Prompter) -> list[str]: if args.shell or tail: return tail @@ -622,6 +651,9 @@ def _wizard_new(args: argparse.Namespace, tail: list[str], prompter: Prompter) - if args.name is None: args.name = prompter.text("Schedule name", validator=validate_name) backend = _wizard_backend(args, prompter) + scope = _wizard_scope(args, backend, prompter) + if backend is Backend.CRON and scope is Scope.SYSTEM and args.run_as is None: + args.run_as = prompter.text("Run as user", default="root", validator=cron_renderer.validate_run_as) tail = _wizard_command(args, tail, prompter) if not _has_schedule(args): _apply_schedule(args, prompter.schedule(backend)) diff --git a/src/schedls/models.py b/src/schedls/models.py index 5bbe234..9fe3b87 100644 --- a/src/schedls/models.py +++ b/src/schedls/models.py @@ -99,6 +99,7 @@ class CronDetails: raw_line: str | None = None line: int | None = None environment: tuple[tuple[str, str], ...] = () + user: str | None = None @dataclass(frozen=True) @@ -134,6 +135,7 @@ class JobSpec: command: Command calendar: tuple[str, ...] = () cron_expression: str | None = None + run_as: str | None = None persistent: bool = False jitter: str | None = None accuracy: str | None = None diff --git a/src/schedls/operations/doctor.py b/src/schedls/operations/doctor.py index 2deba0f..741eb0c 100644 --- a/src/schedls/operations/doctor.py +++ b/src/schedls/operations/doctor.py @@ -21,7 +21,7 @@ def run_doctor( ) -> None: systemd = _systemd_report(runner, systemd_backend) cron = _cron_report(runner, cron_backend) - usable = systemd["available"] or cron["crontab_available"] + usable = systemd["available"] or cron["crontab_available"] or cron["file_sources"] if output.json_mode: output.emit_json( @@ -54,6 +54,7 @@ def run_doctor( output.key_values( [ ("crontab", _yes_no(cron["crontab_available"])), + ("system cron files", _yes_no(cron["file_sources"])), ("implementation", cron["implementation"] or "unknown"), ("current user allowed", _yes_no(cron["user_allowed"])), ("syntax validation", _yes_no(cron["validation"])), @@ -80,18 +81,24 @@ def _systemd_report(runner: CommandRunner, systemd_backend: SystemdBackend) -> d def _cron_report(runner: CommandRunner, cron_backend: CronBackend) -> dict[str, Any]: + crontab_available = cron_backend.crontab_available() + file_sources = cron_backend.file_sources_available() if not cron_backend.available(): return { "crontab_available": False, + "file_sources": file_sources, "implementation": None, "user_allowed": False, "validation": False, } info = cron_backend.capabilities_info() - completed = runner.run(["crontab", "-l"], env_policy="identity", check=False) - allowed = completed.returncode == 0 or "no crontab" in (completed.stderr + completed.stdout).lower() + allowed = False + if crontab_available: + completed = runner.run(["crontab", "-l"], env_policy="identity", check=False) + allowed = completed.returncode == 0 or "no crontab" in (completed.stderr + completed.stdout).lower() return { - "crontab_available": True, + "crontab_available": crontab_available, + "file_sources": file_sources, "implementation": info.implementation, "user_allowed": allowed, "validation": info.supports_validation, diff --git a/src/schedls/operations/inspect.py b/src/schedls/operations/inspect.py index 2441815..4576cc6 100644 --- a/src/schedls/operations/inspect.py +++ b/src/schedls/operations/inspect.py @@ -139,6 +139,10 @@ def render_show(output: Output, job: ScheduledJob) -> None: if job.cron is not None: output.line() output.key_values([("Source", job.source.detail)]) + if job.source.path: + output.key_values([("File", job.source.path)]) + if job.cron.user: + output.key_values([("Run as", job.cron.user)]) if job.cron.shell: output.key_values([("SHELL", job.cron.shell)]) if job.cron.mailto: diff --git a/src/schedls/output.py b/src/schedls/output.py index b6e60de..6f244c4 100644 --- a/src/schedls/output.py +++ b/src/schedls/output.py @@ -164,6 +164,7 @@ def job_to_dict(job: ScheduledJob) -> dict[str, Any]: "shell": job.cron.shell, "mailto": job.cron.mailto, "line": job.cron.line, + "user": job.cron.user, "environment": [list(item) for item in job.cron.environment], } return data diff --git a/src/schedls/renderers/cron.py b/src/schedls/renderers/cron.py index 860f4d2..66d1abf 100644 --- a/src/schedls/renderers/cron.py +++ b/src/schedls/renderers/cron.py @@ -13,7 +13,7 @@ import shlex from ..errors import InvalidScheduleError, SafetyRefusalError from ..models import Command -from ..security import has_unsafe_control_characters +from ..security import MANAGED_COMMENT, has_unsafe_control_characters BLOCK_BEGIN = "# schedls:begin name={name}{extra}" BLOCK_END = "# schedls:end name={name}" @@ -31,6 +31,8 @@ _NICKNAMES = { "@hourly", } _RANGE_RE = re.compile(r"^[0-9]{1,2}-[0-9]{1,2}$") +_SYSTEM_NAME_RE = re.compile(r"\A[A-Za-z0-9][A-Za-z0-9_-]{0,63}\Z") +_USER_RE = re.compile(r"\A[A-Za-z0-9_][A-Za-z0-9_.-]{0,31}\Z") def escape_percent(text: str) -> str: @@ -122,6 +124,38 @@ def render_line(expression: str, command: Command) -> str: return f"{validate_expression(expression)} {render_command(command)}" +def validate_run_as(user: str) -> str: + if not _USER_RE.match(user): + raise InvalidScheduleError( + f"invalid run-as user: {user!r}", + hint="User names start alphanumeric or '_', then letters, digits, '_', '.' or '-'.", + ) + return user + + +def validate_system_name(name: str) -> str: + """Validate a name for an ``/etc/cron.d/schedls-`` drop-in. + + Cron ignores files whose names contain a period, so this is stricter than + the general schedule-name grammar. + """ + if not _SYSTEM_NAME_RE.match(name): + raise InvalidScheduleError( + f"invalid system schedule name: {name!r}", + hint="System cron names allow letters, digits, '_' and '-' only.", + ) + return name + + +def render_system_line(expression: str, command: Command, user: str) -> str: + return f"{validate_expression(expression)} {validate_run_as(user)} {render_command(command)}" + + def render_block(name: str, lines: list[str], *, extra: str = "") -> str: body = [BLOCK_BEGIN.format(name=name, extra=extra), *lines, BLOCK_END.format(name=name)] return "\n".join(body) + "\n" + + +def render_system_file(name: str, lines: list[str]) -> str: + """Render a complete schedls-owned drop-in for ``/etc/cron.d``.""" + return f"{MANAGED_COMMENT}\n{render_block(name, lines)}" diff --git a/tests/integration/test_cron_lifecycle.py b/tests/integration/test_cron_lifecycle.py index e31de19..cf051bd 100644 --- a/tests/integration/test_cron_lifecycle.py +++ b/tests/integration/test_cron_lifecycle.py @@ -11,6 +11,7 @@ from schedls.runner import CommandRunner pytestmark = pytest.mark.integration NAME = "schedls-it-cron" +SYSTEM_NAME = "schedls-it-system" def _backend_or_skip() -> CronBackend: @@ -62,3 +63,50 @@ def test_cron_lifecycle_preserves_content() -> None: assert backend.find(NAME) is None finally: _restore(backend, original) + + +def test_system_cron_discovery_never_executes() -> None: + if not os.path.isdir("/etc/cron.d"): + pytest.skip("/etc/cron.d not present") + backend = CronBackend(CommandRunner()) + jobs = backend.discover([Scope.SYSTEM]) + for job in jobs: + assert job.backend is Backend.CRON + assert job.scope is Scope.SYSTEM + assert not job.command.argv + assert job.cron is not None + + +def test_system_cron_lifecycle() -> None: + if os.geteuid() != 0: + pytest.skip("system cron mutation requires root") + if os.environ.get("SCHEDLS_RUN_CRON_TESTS") != "1": + pytest.skip("set SCHEDLS_RUN_CRON_TESTS=1 to allow cron.d mutation") + if not os.path.isdir("/etc/cron.d"): + pytest.skip("/etc/cron.d not present") + backend = CronBackend(CommandRunner()) + path = f"/etc/cron.d/schedls-{SYSTEM_NAME}" + spec = JobSpec( + name=SYSTEM_NAME, + backend=Backend.CRON, + scope=Scope.SYSTEM, + command=Command(argv=("/usr/bin/true",)), + cron_expression="15 2 * * *", + run_as="root", + ) + try: + plan = backend.plan_create(spec) + assert path in [change.path for change in plan.files] + backend.apply(plan) + + job = backend.find(SYSTEM_NAME) + assert job is not None + assert job.managed is True + assert job.cron is not None and job.cron.user == "root" + + backend.apply(backend.plan_remove(job)) + assert not os.path.exists(path) + assert backend.find(SYSTEM_NAME) is None + finally: + if os.path.exists(path): + os.unlink(path) diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py index f716224..5bfb8d4 100644 --- a/tests/unit/test_cli.py +++ b/tests/unit/test_cli.py @@ -102,8 +102,27 @@ def test_spec_for_new_rejects_cron_expr_for_timer() -> None: _spec_for_new(args, ["/bin/true"]) -def test_spec_for_new_rejects_system_scope_for_cron() -> None: +def test_spec_for_new_system_cron() -> None: args = build_parser().parse_args(["new", "x", "--cron", "--daily", "02:00", "--system"]) + spec = _spec_for_new(args, ["/bin/true"]) + assert spec.scope is Scope.SYSTEM + assert spec.run_as == "root" + + +def test_spec_for_new_system_cron_run_as() -> None: + args = build_parser().parse_args(["new", "x", "--cron", "--daily", "02:00", "--system", "--run-as", "www-data"]) + spec = _spec_for_new(args, ["/bin/true"]) + assert spec.run_as == "www-data" + + +def test_spec_for_new_rejects_run_as_for_user_cron() -> None: + args = build_parser().parse_args(["new", "x", "--cron", "--daily", "02:00", "--run-as", "www-data"]) + with pytest.raises(UsageError): + _spec_for_new(args, ["/bin/true"]) + + +def test_spec_for_new_rejects_run_as_for_timer() -> None: + args = build_parser().parse_args(["new", "x", "--timer", "--daily", "02:00", "--run-as", "www-data"]) with pytest.raises(UsageError): _spec_for_new(args, ["/bin/true"]) diff --git a/tests/unit/test_cron_system.py b/tests/unit/test_cron_system.py new file mode 100644 index 0000000..ae52343 --- /dev/null +++ b/tests/unit/test_cron_system.py @@ -0,0 +1,304 @@ +from __future__ import annotations + +import os + +import pytest + +from schedls.backends.base import FileChange, Plan +from schedls.backends.cron import CronBackend, CronPaths +from schedls.errors import ConflictError, InvalidScheduleError, SafetyRefusalError +from schedls.models import Backend, Command, JobSpec, Scope +from schedls.renderers import cron as renderer + + +def _make_paths(tmp_path) -> CronPaths: + root = tmp_path / "etc" + root.mkdir() + return CronPaths( + crontab=str(root / "crontab"), + cron_d=str(root / "cron.d"), + hourly=str(root / "cron.hourly"), + daily=str(root / "cron.daily"), + weekly=str(root / "cron.weekly"), + monthly=str(root / "cron.monthly"), + spool_crontabs=str(tmp_path / "var" / "spool" / "cron" / "crontabs"), + spool=str(tmp_path / "var" / "spool" / "cron"), + ) + + +def _write(path, text: str, mode: int = 0o644): + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + path.chmod(mode) + return path + + +def test_available_without_crontab_uses_file_sources(tmp_path, fake_runner) -> None: + paths = _make_paths(tmp_path) + assert CronBackend(fake_runner, paths).available() is False + _write(tmp_path / "etc/cron.d/backup", "0 2 * * * root /usr/bin/backup\n") + assert CronBackend(fake_runner, paths).available() is True + + +def test_discovers_system_crontabs(tmp_path, fake_runner) -> None: + paths = _make_paths(tmp_path) + _write( + tmp_path / "etc/crontab", + "SHELL=/bin/sh\n17 * * * * root /usr/bin/hourly\n@daily www-data /usr/bin/report\n", + ) + _write(tmp_path / "etc/cron.d/backup", "0 2 * * * root /usr/bin/backup\n") + _write( + tmp_path / "etc/cron.d/schedls-cleanup", + renderer.render_system_file("cleanup", ["30 3 * * 0 deploy /usr/bin/cleanup"]), + ) + _write(tmp_path / "etc/cron.d/with.dot", "0 2 * * * root /usr/bin/ignored\n") + _write(tmp_path / "etc/cron.d/.placeholder", "") + + jobs = CronBackend(fake_runner, paths).discover([Scope.SYSTEM]) + by_name = {job.name: job for job in jobs} + assert set(by_name) == {"crontab:2", "crontab:3", "backup:1", "cleanup"} + + assert by_name["crontab:2"].scope is Scope.SYSTEM + assert by_name["crontab:2"].cron.user == "root" + assert by_name["crontab:2"].command.raw == "/usr/bin/hourly" + assert by_name["crontab:3"].cron.user == "www-data" + assert by_name["backup:1"].managed is False + assert by_name["backup:1"].schedule.expression == "0 2 * * *" + assert by_name["backup:1"].source.path == paths.cron_d + "/backup" + + managed = by_name["cleanup"] + assert managed.managed is True + assert managed.cron.user == "deploy" + assert managed.schedule.expression == "30 3 * * 0" + assert managed.source.path == paths.cron_d + "/schedls-cleanup" + + +def test_discovers_periodic_directories(tmp_path, fake_runner) -> None: + paths = _make_paths(tmp_path) + _write(tmp_path / "etc/cron.daily/logrotate", "#!/bin/sh\n", mode=0o755) + _write(tmp_path / "etc/cron.daily/README", "text\n", mode=0o644) + _write(tmp_path / "etc/cron.hourly/.hidden", "#!/bin/sh\n", mode=0o755) + + jobs = CronBackend(fake_runner, paths).discover([Scope.SYSTEM]) + assert [job.name for job in jobs] == ["logrotate"] + job = jobs[0] + assert job.schedule.expression == "@daily" + assert job.command.display() == paths.daily + "/logrotate" + assert job.cron.user == "root" + assert job.managed is False + assert "cron.daily" in job.source.detail + + +def test_spool_crontabs_require_root(tmp_path, fake_runner, monkeypatch) -> None: + paths = _make_paths(tmp_path) + _write(tmp_path / "var/spool/cron/crontabs/alice", "5 4 * * * /usr/bin/alice\n") + _write(tmp_path / "var/spool/cron/crontabs/root", "5 4 * * * /usr/bin/root\n") + backend = CronBackend(fake_runner, paths) + + monkeypatch.setattr(os, "geteuid", lambda: 1000) + assert backend.discover([Scope.USER]) == [] + + monkeypatch.setattr(os, "geteuid", lambda: 0) + monkeypatch.setattr(CronBackend, "_current_user", staticmethod(lambda: "root")) + jobs = backend.discover([Scope.USER]) + assert [job.name for job in jobs] == ["alice:1"] + assert jobs[0].scope is Scope.USER + assert jobs[0].cron.user == "alice" + assert jobs[0].source.path.endswith("crontabs/alice") + + +def test_spool_falls_back_to_flat_layout(tmp_path, fake_runner, monkeypatch) -> None: + paths = _make_paths(tmp_path) + _write(tmp_path / "var/spool/cron/alice", "5 4 * * * /usr/bin/alice\n") + (tmp_path / "var/spool/cron/atjobs").mkdir(parents=True) + monkeypatch.setattr(os, "geteuid", lambda: 0) + monkeypatch.setattr(CronBackend, "_current_user", staticmethod(lambda: "root")) + + jobs = CronBackend(fake_runner, paths).discover([Scope.USER]) + assert [job.name for job in jobs] == ["alice:1"] + + +def test_malformed_drop_in_is_unmanaged(tmp_path, fake_runner) -> None: + paths = _make_paths(tmp_path) + _write(tmp_path / "etc/cron.d/schedls-broken", "0 2 * * * root /bin/true\n") + + jobs = CronBackend(fake_runner, paths).discover([Scope.SYSTEM]) + assert [job.name for job in jobs] == ["schedls-broken:1"] + assert jobs[0].managed is False + assert jobs[0].warnings + + +def _system_spec(**overrides) -> JobSpec: + values = { + "name": "backup", + "backend": Backend.CRON, + "scope": Scope.SYSTEM, + "command": Command(argv=("/usr/bin/backup", "/srv/data")), + "cron_expression": "0 2 * * *", + "run_as": "www-data", + } + values.update(overrides) + return JobSpec(**values) + + +def test_plan_create_system_cron(tmp_path, fake_runner, monkeypatch) -> None: + paths = _make_paths(tmp_path) + (tmp_path / "etc/cron.d").mkdir(parents=True, exist_ok=True) + monkeypatch.setattr(os, "geteuid", lambda: 0) + monkeypatch.setattr("schedls.backends.cron.check_trusted_directory", lambda path, *, expected_uid: None) + + plan = CronBackend(fake_runner, paths).plan_create(_system_spec()) + assert plan.payload["mode"] == "file" + assert plan.payload["expected_uid"] == 0 + assert not plan.commands + change = plan.files[0] + assert change.path == paths.cron_d + "/schedls-backup" + assert "0 2 * * * www-data /usr/bin/backup /srv/data" in change.content + assert "# schedls:begin name=backup" in change.content + assert ("Run as", "www-data") in plan.summary + + +def test_plan_create_system_cron_requires_root(tmp_path, fake_runner, monkeypatch) -> None: + paths = _make_paths(tmp_path) + monkeypatch.setattr(os, "geteuid", lambda: 1000) + with pytest.raises(SafetyRefusalError): + CronBackend(fake_runner, paths).plan_create(_system_spec()) + + +def test_plan_create_system_cron_rejects_dotted_name(tmp_path, fake_runner, monkeypatch) -> None: + paths = _make_paths(tmp_path) + monkeypatch.setattr(os, "geteuid", lambda: 0) + with pytest.raises(InvalidScheduleError): + CronBackend(fake_runner, paths).plan_create(_system_spec(name="my.job")) + + +def test_plan_create_system_cron_conflict(tmp_path, fake_runner, monkeypatch) -> None: + paths = _make_paths(tmp_path) + _write(tmp_path / "etc/cron.d/schedls-backup", "0 2 * * * root /bin/true\n") + monkeypatch.setattr(os, "geteuid", lambda: 0) + monkeypatch.setattr("schedls.backends.cron.check_trusted_directory", lambda path, *, expected_uid: None) + with pytest.raises(ConflictError): + CronBackend(fake_runner, paths).plan_create(_system_spec()) + + +def test_apply_file_mode_create_and_remove(tmp_path, fake_runner) -> None: + paths = _make_paths(tmp_path) + (tmp_path / "etc/cron.d").mkdir(parents=True, exist_ok=True) + backend = CronBackend(fake_runner, paths) + uid = os.getuid() + path = tmp_path / "etc/cron.d/schedls-backup" + content = renderer.render_system_file("backup", ["0 2 * * * root /usr/bin/backup"]) + + create = Plan(backend="cron", action="create") + create.files = [FileChange(path=str(path), content=content, mode=0o644, expected_uid=uid)] + create.payload = { + "mode": "file", + "action": "create", + "name": "backup", + "path": str(path), + "expected_uid": uid, + "snapshots": {str(path): None}, + } + result = backend.apply(create) + assert result.changed + assert path.read_text() == content + + remove = Plan(backend="cron", action="remove") + remove.files = [FileChange(path=str(path), content=None, expected_uid=uid)] + remove.payload = { + "mode": "file", + "action": "remove", + "name": "backup", + "path": str(path), + "expected_uid": uid, + "snapshots": {str(path): content}, + } + result = backend.apply(remove) + assert result.changed + assert not path.exists() + + +def test_apply_file_mode_refuses_changed_snapshot(tmp_path, fake_runner) -> None: + paths = _make_paths(tmp_path) + _write(tmp_path / "etc/cron.d/schedls-backup", "changed\n") + backend = CronBackend(fake_runner, paths) + path = tmp_path / "etc/cron.d/schedls-backup" + + plan = Plan(backend="cron", action="remove") + plan.files = [FileChange(path=str(path), content=None, expected_uid=os.getuid())] + plan.payload = { + "mode": "file", + "action": "remove", + "name": "backup", + "path": str(path), + "expected_uid": os.getuid(), + "snapshots": {str(path): "expected\n"}, + } + with pytest.raises(SafetyRefusalError): + backend.apply(plan) + assert path.exists() + + +def test_apply_file_mode_rolls_back_on_failure(tmp_path, fake_runner) -> None: + paths = _make_paths(tmp_path) + (tmp_path / "etc/cron.d").mkdir(parents=True, exist_ok=True) + backend = CronBackend(fake_runner, paths) + uid = os.getuid() + first = tmp_path / "etc/cron.d/schedls-one" + second = tmp_path / "etc/cron.d/schedls-two" + _write(second, "conflict\n") + + plan = Plan(backend="cron", action="create") + plan.files = [ + FileChange(path=str(first), content=renderer.render_system_file("one", ["0 2 * * * root /bin/true"])), + FileChange(path=str(second), content=renderer.render_system_file("two", ["0 3 * * * root /bin/true"])), + ] + plan.payload = { + "mode": "file", + "action": "create", + "name": "one", + "path": str(first), + "expected_uid": uid, + "snapshots": {str(first): None, str(second): None}, + } + with pytest.raises(SafetyRefusalError): + backend.apply(plan) + assert not first.exists() + + +def test_plan_remove_system_cron(tmp_path, fake_runner, monkeypatch) -> None: + paths = _make_paths(tmp_path) + _write( + tmp_path / "etc/cron.d/schedls-cleanup", + renderer.render_system_file("cleanup", ["30 3 * * 0 root /usr/bin/cleanup"]), + ) + backend = CronBackend(fake_runner, paths) + job = backend.discover([Scope.SYSTEM])[0] + monkeypatch.setattr(os, "geteuid", lambda: 0) + + plan = backend.plan_remove(job) + assert plan.payload["mode"] == "file" + assert plan.files[0].path == paths.cron_d + "/schedls-cleanup" + assert plan.files[0].content is None + + +def test_plan_remove_system_cron_requires_root(tmp_path, fake_runner, monkeypatch) -> None: + paths = _make_paths(tmp_path) + _write( + tmp_path / "etc/cron.d/schedls-cleanup", + renderer.render_system_file("cleanup", ["30 3 * * 0 root /usr/bin/cleanup"]), + ) + backend = CronBackend(fake_runner, paths) + job = backend.discover([Scope.SYSTEM])[0] + monkeypatch.setattr(os, "geteuid", lambda: 1000) + with pytest.raises(SafetyRefusalError): + backend.plan_remove(job) + + +def test_plan_remove_refuses_unmanaged(tmp_path, fake_runner) -> None: + paths = _make_paths(tmp_path) + _write(tmp_path / "etc/cron.d/backup", "0 2 * * * root /usr/bin/backup\n") + backend = CronBackend(fake_runner, paths) + job = backend.discover([Scope.SYSTEM])[0] + with pytest.raises(SafetyRefusalError): + backend.plan_remove(job) diff --git a/tests/unit/test_crontab.py b/tests/unit/test_crontab.py index 8e24aa3..a1dff68 100644 --- a/tests/unit/test_crontab.py +++ b/tests/unit/test_crontab.py @@ -93,3 +93,48 @@ def test_empty_crontab() -> None: updated = document.with_block("x", ["0 0 * * * /bin/true"]) assert updated.endswith("\n") assert "name=x" in updated + + +SYSTEM_SAMPLE = ( + "SHELL=/bin/sh\n" + "PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin\n" + "\n" + "# system jobs\n" + "17 * * * * root cd / && run-parts --report /etc/cron.hourly\n" + "@daily www-data /usr/local/bin/report\n" + "\n" + "# schedls:begin name=cleanup\n" + "30 3 * * 0 root /usr/local/bin/cleanup\n" + "# schedls:end name=cleanup\n" +) + + +def test_system_crontab_parses_user_field() -> None: + document = CrontabDocument(SYSTEM_SAMPLE, system=True) + jobs = [entry for entry in document.entries if entry.kind == "job"] + assert jobs[0].expression == "17 * * * *" + assert jobs[0].user == "root" + assert jobs[0].command == "cd / && run-parts --report /etc/cron.hourly" + assert jobs[1].expression == "@daily" + assert jobs[1].user == "www-data" + assert jobs[1].command == "/usr/local/bin/report" + + +def test_system_crontab_detects_managed_block() -> None: + document = CrontabDocument(SYSTEM_SAMPLE, system=True) + block = document.find_block("cleanup") + assert block is not None + assert block.job_lines[0].user == "root" + assert document.render() == SYSTEM_SAMPLE + + +def test_user_crontab_still_parses_five_fields() -> None: + document = CrontabDocument("15 7 * * * ~/bin/foo\n", system=False) + assert document.entries[0].expression == "15 7 * * *" + assert document.entries[0].user is None + assert document.entries[0].command == "~/bin/foo" + + +def test_system_entry_without_user_is_not_a_job() -> None: + document = CrontabDocument("15 7 * * * ~/bin/foo\n", system=True) + assert document.entries[0].kind == "comment" diff --git a/tests/unit/test_prompt.py b/tests/unit/test_prompt.py index 97948f0..ce1f871 100644 --- a/tests/unit/test_prompt.py +++ b/tests/unit/test_prompt.py @@ -150,12 +150,13 @@ def test_eof_raises_confirmation_required() -> None: def test_wizard_new_systemd(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr("sys.stdin", FakeStdin(isatty=True)) args = build_parser().parse_args(["new", "-i"]) - answers = ["backup", "", "n", "/usr/local/bin/backup /srv/data", "", "02:00", "n"] + answers = ["backup", "", "", "n", "/usr/local/bin/backup /srv/data", "", "02:00", "n"] prompter, _ = make_prompter(answers) args, tail = _wizard_new(args, [], prompter) spec = _spec_for_new(args, tail) assert spec.name == "backup" assert spec.backend is Backend.SYSTEMD + assert spec.scope is Scope.USER assert spec.calendar == ("*-*-* 02:00:00",) assert spec.command.argv == ("/usr/local/bin/backup", "/srv/data") @@ -163,17 +164,19 @@ def test_wizard_new_systemd(monkeypatch: pytest.MonkeyPatch) -> None: def test_wizard_new_cron(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr("sys.stdin", FakeStdin(isatty=True)) args = build_parser().parse_args(["new", "-i"]) - answers = ["cleanup", "2", "n", "/usr/local/bin/cleanup", "", "04:00"] + answers = ["cleanup", "2", "", "n", "/usr/local/bin/cleanup", "", "04:00"] prompter, _ = make_prompter(answers) args, tail = _wizard_new(args, [], prompter) spec = _spec_for_new(args, tail) assert spec.backend is Backend.CRON + assert spec.scope is Scope.USER assert spec.cron_expression == "0 4 * * *" + assert spec.run_as is None def test_wizard_new_skips_provided_fields(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr("sys.stdin", FakeStdin(isatty=True)) - args = build_parser().parse_args(["new", "backup", "-i", "--timer", "--daily", "02:00"]) + args = build_parser().parse_args(["new", "backup", "-i", "--timer", "--daily", "02:00", "--user"]) prompter, fake = make_prompter(["n"]) args, tail = _wizard_new(args, ["/bin/true"], prompter) spec = _spec_for_new(args, tail) @@ -181,6 +184,71 @@ def test_wizard_new_skips_provided_fields(monkeypatch: pytest.MonkeyPatch) -> No assert fake.prompts == ["Set advanced timer options? [y/N] "] +def test_wizard_new_scope_prompt_defaults_to_user(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("sys.stdin", FakeStdin(isatty=True)) + args = build_parser().parse_args(["new", "cleanup", "-i", "--cron", "--daily", "04:00"]) + prompter, fake = make_prompter(["", "n", "/usr/local/bin/cleanup"]) + args, tail = _wizard_new(args, [], prompter) + spec = _spec_for_new(args, tail) + assert spec.scope is Scope.USER + assert spec.run_as is None + assert any(prompt.startswith("Scope:") for prompt in fake.prompts) + assert not any(prompt.startswith("Run as user") for prompt in fake.prompts) + + +def test_wizard_new_system_cron_prompts_run_as(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("sys.stdin", FakeStdin(isatty=True)) + args = build_parser().parse_args(["new", "report", "-i", "--cron", "--daily", "04:00"]) + prompter, _ = make_prompter(["2", "www-data", "n", "/usr/local/bin/report"]) + args, tail = _wizard_new(args, [], prompter) + spec = _spec_for_new(args, tail) + assert spec.scope is Scope.SYSTEM + assert spec.run_as == "www-data" + + +def test_wizard_new_system_cron_run_as_defaults_to_root(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("sys.stdin", FakeStdin(isatty=True)) + args = build_parser().parse_args(["new", "report", "-i", "--cron", "--daily", "04:00"]) + prompter, _ = make_prompter(["2", "", "n", "/usr/local/bin/report"]) + args, tail = _wizard_new(args, [], prompter) + spec = _spec_for_new(args, tail) + assert spec.scope is Scope.SYSTEM + assert spec.run_as == "root" + + +def test_wizard_new_system_cron_run_as_reprompts(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("sys.stdin", FakeStdin(isatty=True)) + args = build_parser().parse_args(["new", "report", "-i", "--cron", "--daily", "04:00"]) + prompter, fake = make_prompter(["2", "bad user", "www-data", "n", "/usr/local/bin/report"]) + args, tail = _wizard_new(args, [], prompter) + spec = _spec_for_new(args, tail) + assert spec.run_as == "www-data" + assert fake.prompts.count("Run as user [root]: ") == 2 + + +def test_wizard_new_provided_scope_and_run_as_are_not_reasked(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("sys.stdin", FakeStdin(isatty=True)) + args = build_parser().parse_args( + ["new", "report", "-i", "--cron", "--system", "--run-as", "root", "--daily", "04:00"] + ) + prompter, fake = make_prompter(["n", "/usr/local/bin/report"]) + args, tail = _wizard_new(args, [], prompter) + spec = _spec_for_new(args, tail) + assert spec.scope is Scope.SYSTEM + assert spec.run_as == "root" + assert all("Scope:" not in prompt and "Run as user" not in prompt for prompt in fake.prompts) + + +def test_wizard_new_systemd_scope_prompt(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("sys.stdin", FakeStdin(isatty=True)) + args = build_parser().parse_args(["new", "backup", "-i", "--timer", "--daily", "02:00"]) + prompter, _ = make_prompter(["2", "n", "/usr/local/bin/backup", "n"]) + args, tail = _wizard_new(args, [], prompter) + spec = _spec_for_new(args, tail) + assert spec.scope is Scope.SYSTEM + assert spec.calendar == ("*-*-* 02:00:00",) + + def test_wizard_edit_changes_schedule(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr("sys.stdin", FakeStdin(isatty=True)) job = _systemd_job() diff --git a/tests/unit/test_renderers_cron.py b/tests/unit/test_renderers_cron.py index 67607fc..5612576 100644 --- a/tests/unit/test_renderers_cron.py +++ b/tests/unit/test_renderers_cron.py @@ -125,5 +125,38 @@ def test_managed_block() -> None: assert block == ("# schedls:begin name=backup\n0 2 * * * /bin/true\n# schedls:end name=backup\n") +def test_render_system_line() -> None: + line = renderer.render_system_line("0 2 * * *", Command(argv=("/bin/echo", "100%")), "www-data") + assert line == "0 2 * * * www-data /bin/echo 100\\%" + + +def test_render_system_file_has_marker() -> None: + content = renderer.render_system_file("backup", ["0 2 * * * root /bin/true"]) + assert content.startswith("# Managed by schedls\n# schedls:begin name=backup\n") + assert content.endswith("# schedls:end name=backup\n") + + +@pytest.mark.parametrize("name", ["backup", "my-job", "job_1"]) +def test_system_name_accepts(name: str) -> None: + assert renderer.validate_system_name(name) == name + + +@pytest.mark.parametrize("name", ["my.job", ".hidden", "-leading", "with space", ""]) +def test_system_name_rejects(name: str) -> None: + with pytest.raises(InvalidScheduleError): + renderer.validate_system_name(name) + + +@pytest.mark.parametrize("user", ["root", "www-data", "nginx", "user.name", "_svc"]) +def test_run_as_accepts(user: str) -> None: + assert renderer.validate_run_as(user) == user + + +@pytest.mark.parametrize("user", ["", "-root", "a b", "a;b", "a$b", "x" * 33]) +def test_run_as_rejects(user: str) -> None: + with pytest.raises(InvalidScheduleError): + renderer.validate_run_as(user) + + def test_shlex_reference() -> None: assert shlex.quote("a b") == "'a b'"