driver / standard (pull_request) Successful in 25s
driver / lint (pull_request) Successful in 26s
driver / types (pull_request) Failing after 35s
driver / test (3.13) (pull_request) Failing after 18s
driver / test (3.12) (pull_request) Failing after 21s
driver / lowest (pull_request) Failing after 17s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Failing after 40s
CI / driver (pull_request) Failing after 1m25s
driver / publish (pull_request) Skipped
OPNsense keeps its cron jobs in its configuration and runs each as a configd action, so the POSIX implementation does not fit: the driver has no shell, and a job's command is not a shell line. The cron API reads and writes them instead. get_scheduled_jobs reads every job in one request (/api/cron/settings/get, which carries the selected action rather than its display text). A job another component registered is platform, one written by put_scheduled_job carries the napalm-scheduled-job marker in its description and is application, the rest admin. Every job can be enabled and disabled; only an application's job is edited or deleted. put_scheduled_job takes a configd action as command and refuses one configd does not offer; get_scheduled_job_commands lists them. Running a job now is refused: the API cannot run a configd action. Every write reads the job again and refuses one whose digest changed. Parameters are written one per line and only without blanks, quotes or backslashes: OPNsense up to 26.1 splits them as a shell would, 26.7 takes a line per argument, and only such arguments mean the same to both. Requires napalm-device-types 4.26.0. Closes #43
496 lines
19 KiB
Python
496 lines
19 KiB
Python
"""Scheduled jobs on OPNsense: the cron jobs of config.xml, over the REST API (#43).
|
|
|
|
OPNsense keeps its cron jobs in its configuration (``System > Settings > Cron``)
|
|
and runs each as a configd action. ``/api/cron/settings/get`` answers with every
|
|
job, the action as the option its ``command`` list has selected;
|
|
``get_job`` without a uuid is a blank job, and its ``command`` options are the
|
|
actions configd offers. The fixtures are synthetic, in the shape of an OPNsense
|
|
26.7 answer: an admin's job, one the intrusion detection registered (origin
|
|
``IDS``), one an application wrote, one with parameters, and one whose marker
|
|
names no valid job.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import copy
|
|
import json
|
|
from pathlib import Path
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
from napalm_device_types import ScheduledJobsMixin
|
|
from napalm_device_types.scheduled_jobs import (
|
|
ScheduledJobChanged,
|
|
ScheduledJobRefused,
|
|
job_digest,
|
|
)
|
|
|
|
from napalm_opnsense.opnsense import OPNsenseDriver
|
|
|
|
FIXTURES = Path(__file__).parent / "fixtures"
|
|
SETTINGS = json.loads((FIXTURES / "cron_settings_get.json").read_text())
|
|
BLANK_JOB = json.loads((FIXTURES / "cron_settings_get_job.json").read_text())
|
|
|
|
ADMIN = "opnsense:0b6e3c52-6a1e-4c7a-9a0e-2f0a1d6c3b11"
|
|
PLATFORM = "opnsense:1f2d8e04-93b7-4f4e-8c55-7d1e0c9a2b22"
|
|
OWN = "opnsense:2a7c9b16-4d3e-4b8f-a1c2-5e6f7a8b9c33"
|
|
OWN_UUID = OWN.removeprefix("opnsense:")
|
|
WITH_PARAMETERS = "opnsense:3c8d0e27-5f4a-4c9b-b2d3-6f7a8b9c0d44"
|
|
BAD_MARKER = "opnsense:4d9e1f38-6a5b-4dac-83e4-7a8b9c0d1e55"
|
|
|
|
SAVED = {"result": "saved"}
|
|
RELOADED = {"status": "ok"}
|
|
|
|
|
|
class Firewall:
|
|
"""Answers the cron API as a firewall would, and records every POST."""
|
|
|
|
def __init__(self, settings=SETTINGS, blank=BLANK_JOB, answers=None):
|
|
self.settings = copy.deepcopy(settings)
|
|
self.blank = blank
|
|
self.answers = answers or {}
|
|
self.posts: list[tuple[str, dict | None]] = []
|
|
|
|
def get(self, path: str):
|
|
if path == "/api/cron/settings/get":
|
|
return self.settings
|
|
if path == "/api/cron/settings/get_job":
|
|
return self.blank
|
|
raise AssertionError(f"unexpected GET {path}")
|
|
|
|
def post(self, path: str, data=None):
|
|
self.posts.append((path, data))
|
|
for prefix, answer in self.answers.items():
|
|
if path.startswith(prefix):
|
|
return answer
|
|
if path == "/api/cron/service/reconfigure":
|
|
return RELOADED
|
|
if path.startswith("/api/cron/settings/toggle_job/"):
|
|
return {"result": "Enabled" if path.endswith("/1") else "Disabled", "changed": True}
|
|
if path.startswith("/api/cron/settings/del_job/"):
|
|
return {"result": "deleted"}
|
|
if path == "/api/cron/settings/add_job":
|
|
return {"result": "saved", "uuid": "5eaf2049-7b6c-4ebd-94f5-8b9c0d1e2f66"}
|
|
if path.startswith("/api/cron/settings/set_job/"):
|
|
return SAVED
|
|
raise AssertionError(f"unexpected POST {path}")
|
|
|
|
@property
|
|
def paths(self) -> list[str]:
|
|
return [path for path, _ in self.posts]
|
|
|
|
|
|
def _driver(firewall: Firewall) -> OPNsenseDriver:
|
|
with patch("napalm_opnsense.opnsense.requests.Session"):
|
|
drv = OPNsenseDriver(hostname="fw", username="k", password="s")
|
|
drv.session = MagicMock()
|
|
drv._get = firewall.get # type: ignore[method-assign]
|
|
drv._post = firewall.post # type: ignore[method-assign]
|
|
return drv
|
|
|
|
|
|
def _jobs(firewall: Firewall | None = None) -> dict[str, dict]:
|
|
reading = _driver(firewall or Firewall()).get_scheduled_jobs()
|
|
return {job["key"]: job for job in reading["jobs"]}
|
|
|
|
|
|
def _digest(key: str) -> str:
|
|
return _jobs()[key]["digest"]
|
|
|
|
|
|
def _spec(**over) -> dict:
|
|
spec = {
|
|
"name": "alias-refresh",
|
|
"schedule": "*/30 * * * *",
|
|
"run_as": "root",
|
|
"command": "filter refresh_aliases",
|
|
"enabled": True,
|
|
"description": "Keep the aliases fresh",
|
|
}
|
|
spec.update(over)
|
|
return spec
|
|
|
|
|
|
def test_the_driver_offers_every_verb():
|
|
assert issubclass(OPNsenseDriver, ScheduledJobsMixin)
|
|
for verb in (
|
|
"get_scheduled_jobs",
|
|
"manage_scheduled_job",
|
|
"put_scheduled_job",
|
|
"delete_scheduled_job",
|
|
"get_scheduled_job_commands",
|
|
):
|
|
assert callable(getattr(OPNsenseDriver, verb))
|
|
|
|
|
|
class TestReading:
|
|
def test_every_job_of_the_configuration(self):
|
|
reading = _driver(Firewall()).get_scheduled_jobs()
|
|
|
|
assert reading["time_zone"] is None
|
|
assert [job["key"] for job in reading["jobs"]] == [
|
|
ADMIN,
|
|
PLATFORM,
|
|
OWN,
|
|
WITH_PARAMETERS,
|
|
BAD_MARKER,
|
|
]
|
|
|
|
def test_an_admins_job(self):
|
|
job = _jobs()[ADMIN]
|
|
|
|
assert job == {
|
|
"key": ADMIN,
|
|
"kind": "cron",
|
|
"source": "config.xml",
|
|
"run_as": "root",
|
|
"schedule": "0 3 * * 1-5",
|
|
"schedule_kind": "cron",
|
|
"command": "system remote backup",
|
|
"enabled": True,
|
|
"managed_by": "admin",
|
|
"actions": ["enable", "disable"],
|
|
"description": "Nightly configuration backup",
|
|
"digest": job["digest"],
|
|
}
|
|
assert job["digest"] == job_digest(job)
|
|
|
|
def test_a_job_another_service_registered_is_the_platforms(self):
|
|
job = _jobs()[PLATFORM]
|
|
|
|
assert (job["managed_by"], job["enabled"], job["command"]) == (
|
|
"platform",
|
|
False,
|
|
"ids update",
|
|
)
|
|
assert job["actions"] == ["enable", "disable"]
|
|
|
|
def test_a_job_an_application_wrote_carries_its_name(self):
|
|
job = _jobs()[OWN]
|
|
|
|
assert job["managed_by"] == "application"
|
|
assert job["name"] == "dnsbl-refresh"
|
|
assert job["description"] == "Refresh the DNS blocklists"
|
|
assert job["actions"] == ["enable", "disable", "edit", "delete"]
|
|
|
|
def test_a_marker_without_a_valid_name_is_an_admins_job(self):
|
|
job = _jobs()[BAD_MARKER]
|
|
|
|
assert job["managed_by"] == "admin"
|
|
assert "name" not in job
|
|
assert job["description"] == "napalm-scheduled-job: Not_A_Name written by hand"
|
|
|
|
def test_a_marker_on_another_services_job_is_still_the_platforms(self):
|
|
firewall = Firewall()
|
|
node = firewall.settings["job"]["jobs"]["job"][PLATFORM.removeprefix("opnsense:")]
|
|
node["description"] = "napalm-scheduled-job: ids-update taken over"
|
|
|
|
job = _jobs(firewall)[PLATFORM]
|
|
|
|
assert job["managed_by"] == "platform"
|
|
assert "name" not in job
|
|
|
|
def test_the_parameters_follow_the_action(self):
|
|
assert _jobs()[WITH_PARAMETERS]["command"] == "filter refresh_aliases --quiet --all"
|
|
|
|
def test_a_job_with_no_description_has_none(self):
|
|
firewall = Firewall()
|
|
firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]["description"] = ""
|
|
|
|
assert "description" not in _jobs(firewall)[ADMIN]
|
|
|
|
def test_an_action_configd_no_longer_offers_reads_as_no_command(self):
|
|
firewall = Firewall()
|
|
node = firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]
|
|
node["command"] = {k: {**v, "selected": 0} for k, v in node["command"].items()}
|
|
|
|
assert _jobs(firewall)[ADMIN]["command"] == ""
|
|
|
|
def test_a_command_given_as_a_plain_value_is_taken_as_it_is(self):
|
|
firewall = Firewall()
|
|
node = firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]
|
|
node["command"] = "system remote backup"
|
|
|
|
assert _jobs(firewall)[ADMIN]["command"] == "system remote backup"
|
|
|
|
def test_enabling_a_job_changes_its_digest(self):
|
|
firewall = Firewall()
|
|
firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]["enabled"] = "0"
|
|
|
|
assert _jobs(firewall)[ADMIN]["digest"] != _digest(ADMIN)
|
|
|
|
def test_no_jobs_is_an_empty_list(self):
|
|
firewall = Firewall(settings={"job": {"jobs": {"job": []}}})
|
|
|
|
assert _driver(firewall).get_scheduled_jobs()["jobs"] == []
|
|
|
|
@pytest.mark.parametrize(
|
|
"answer",
|
|
[{}, [], {"job": {}}, {"job": {"jobs": {}}}, {"job": {"jobs": {"job": "x"}}}],
|
|
)
|
|
def test_an_answer_without_the_jobs_raises(self, answer):
|
|
with pytest.raises(ValueError, match="jobs"):
|
|
_driver(Firewall(settings=answer)).get_scheduled_jobs()
|
|
|
|
def test_a_job_without_its_schedule_raises(self):
|
|
firewall = Firewall()
|
|
del firewall.settings["job"]["jobs"]["job"][ADMIN.removeprefix("opnsense:")]["hours"]
|
|
|
|
with pytest.raises(ValueError, match="schedule"):
|
|
_driver(firewall).get_scheduled_jobs()
|
|
|
|
|
|
class TestCommands:
|
|
def test_the_actions_configd_offers(self):
|
|
commands = _driver(Firewall()).get_scheduled_job_commands()
|
|
|
|
assert commands[0] == {
|
|
"command": "filter refresh_aliases",
|
|
"description": "Update and reload firewall aliases",
|
|
}
|
|
assert [c["command"] for c in commands] == [
|
|
"filter refresh_aliases",
|
|
"firmware auto-update",
|
|
"ids update",
|
|
"system ha_reconfigure_backup",
|
|
"system remote backup",
|
|
"unbound dnsbl",
|
|
]
|
|
|
|
def test_the_blank_placeholder_is_no_action(self):
|
|
blank = copy.deepcopy(BLANK_JOB)
|
|
blank["job"]["command"][""] = {"value": "None", "selected": 1}
|
|
|
|
commands = _driver(Firewall(blank=blank)).get_scheduled_job_commands()
|
|
|
|
assert "" not in [c["command"] for c in commands]
|
|
|
|
@pytest.mark.parametrize(
|
|
"answer", [{}, [], {"job": []}, {"job": {"command": {}}}, {"job": {"command": "x"}}]
|
|
)
|
|
def test_no_actions_raises(self, answer):
|
|
# configd that did not answer leaves the list empty: that is no reading.
|
|
with pytest.raises(ValueError, match="configd"):
|
|
_driver(Firewall(blank=answer)).get_scheduled_job_commands()
|
|
|
|
|
|
class TestManage:
|
|
@pytest.mark.parametrize(
|
|
"action, flag, word", [("enable", "1", "enabled"), ("disable", "0", "disabled")]
|
|
)
|
|
def test_switching_a_job_toggles_it_and_reloads_cron(self, action, flag, word):
|
|
firewall = Firewall()
|
|
|
|
result = _driver(firewall).manage_scheduled_job(PLATFORM, action, digest=_digest(PLATFORM))
|
|
|
|
assert result == {"success": True, "output": f"{PLATFORM} {word}"}
|
|
assert firewall.paths == [
|
|
f"/api/cron/settings/toggle_job/{PLATFORM.removeprefix('opnsense:')}/{flag}",
|
|
"/api/cron/service/reconfigure",
|
|
]
|
|
|
|
def test_running_a_job_now_is_refused(self):
|
|
firewall = Firewall()
|
|
|
|
with pytest.raises(ScheduledJobRefused, match="run"):
|
|
_driver(firewall).manage_scheduled_job(ADMIN, "run", digest=_digest(ADMIN))
|
|
assert firewall.posts == []
|
|
|
|
def test_an_unknown_action_is_refused(self):
|
|
with pytest.raises(ScheduledJobRefused, match="unknown action"):
|
|
_driver(Firewall()).manage_scheduled_job(ADMIN, "edit", digest=_digest(ADMIN))
|
|
|
|
def test_an_unknown_job_raises_lookup_error(self):
|
|
with pytest.raises(LookupError):
|
|
_driver(Firewall()).manage_scheduled_job("opnsense:nope", "enable", digest="x")
|
|
|
|
def test_a_job_changed_since_it_was_read_is_not_touched(self):
|
|
firewall = Firewall()
|
|
|
|
with pytest.raises(ScheduledJobChanged):
|
|
_driver(firewall).manage_scheduled_job(ADMIN, "disable", digest="0" * 16)
|
|
assert firewall.posts == []
|
|
|
|
def test_a_refused_toggle_raises_and_cron_is_not_reloaded(self):
|
|
firewall = Firewall(answers={"/api/cron/settings/toggle_job/": {"result": "failed"}})
|
|
|
|
with pytest.raises(RuntimeError, match="failed"):
|
|
_driver(firewall).manage_scheduled_job(ADMIN, "disable", digest=_digest(ADMIN))
|
|
assert "/api/cron/service/reconfigure" not in firewall.paths
|
|
|
|
def test_a_cron_that_does_not_reload_raises(self):
|
|
firewall = Firewall(answers={"/api/cron/service/reconfigure": {"status": "failed"}})
|
|
|
|
with pytest.raises(RuntimeError, match="reload"):
|
|
_driver(firewall).manage_scheduled_job(ADMIN, "disable", digest=_digest(ADMIN))
|
|
|
|
|
|
class TestPut:
|
|
def test_a_new_job_is_added_with_its_marker_and_cron_reloads(self):
|
|
firewall = Firewall()
|
|
|
|
result = _driver(firewall).put_scheduled_job(_spec())
|
|
|
|
assert result == {
|
|
"success": True,
|
|
"output": "opnsense:5eaf2049-7b6c-4ebd-94f5-8b9c0d1e2f66 created",
|
|
}
|
|
assert firewall.posts == [
|
|
(
|
|
"/api/cron/settings/add_job",
|
|
{
|
|
"job": {
|
|
"enabled": "1",
|
|
"minutes": "*/30",
|
|
"hours": "*",
|
|
"days": "*",
|
|
"months": "*",
|
|
"weekdays": "*",
|
|
"command": "filter refresh_aliases",
|
|
"parameters": "",
|
|
"description": "napalm-scheduled-job: alias-refresh Keep the aliases fresh",
|
|
}
|
|
},
|
|
),
|
|
("/api/cron/service/reconfigure", None),
|
|
]
|
|
|
|
def test_an_application_job_is_changed_in_place(self):
|
|
firewall = Firewall()
|
|
spec = _spec(name="dnsbl-refresh", command="unbound dnsbl", enabled=False)
|
|
del spec["description"]
|
|
|
|
result = _driver(firewall).put_scheduled_job(spec, digest=_digest(OWN))
|
|
|
|
assert result == {"success": True, "output": f"{OWN} changed"}
|
|
path, data = firewall.posts[0]
|
|
assert path == f"/api/cron/settings/set_job/{OWN_UUID}"
|
|
assert data["job"]["enabled"] == "0"
|
|
assert data["job"]["description"] == "napalm-scheduled-job: dnsbl-refresh"
|
|
assert firewall.paths[-1] == "/api/cron/service/reconfigure"
|
|
|
|
def test_the_words_after_the_action_are_its_parameters_one_per_line(self):
|
|
firewall = Firewall()
|
|
|
|
_driver(firewall).put_scheduled_job(
|
|
_spec(command=" filter refresh_aliases --quiet --all ")
|
|
)
|
|
|
|
job = firewall.posts[0][1]["job"]
|
|
assert (job["command"], job["parameters"]) == ("filter refresh_aliases", "--quiet\n--all")
|
|
|
|
def test_the_longest_action_the_command_starts_with_wins(self):
|
|
blank = copy.deepcopy(BLANK_JOB)
|
|
blank["job"]["command"]["filter"] = {"value": "Reload the filter", "selected": 0}
|
|
firewall = Firewall(blank=blank)
|
|
|
|
_driver(firewall).put_scheduled_job(_spec(command="filter refresh_aliases"))
|
|
|
|
job = firewall.posts[0][1]["job"]
|
|
assert (job["command"], job["parameters"]) == ("filter refresh_aliases", "")
|
|
|
|
@pytest.mark.parametrize(
|
|
"schedule, fields",
|
|
[
|
|
("@daily", ("0", "0", "*", "*", "*")),
|
|
("@hourly", ("0", "*", "*", "*", "*")),
|
|
("0 6 * jan-Mar MON-fri", ("0", "6", "*", "1-3", "1-5")),
|
|
("5 4 1,15 * sun,7", ("5", "4", "1,15", "*", "0,7")),
|
|
],
|
|
)
|
|
def test_the_schedule_is_written_as_its_five_fields(self, schedule, fields):
|
|
firewall = Firewall()
|
|
|
|
_driver(firewall).put_scheduled_job(_spec(schedule=schedule))
|
|
|
|
job = firewall.posts[0][1]["job"]
|
|
assert tuple(job[f] for f in ("minutes", "hours", "days", "months", "weekdays")) == fields
|
|
|
|
@pytest.mark.parametrize(
|
|
"over, match",
|
|
[
|
|
({"schedule": "@reboot"}, "@reboot"),
|
|
({"run_as": "nobody"}, "root"),
|
|
({"command": "rm -rf /"}, "configd offers no action"),
|
|
({"command": "filter refresh_aliases\nids update"}, "one line"),
|
|
({"command": "filter refresh_aliases 'a b'"}, "parameter"),
|
|
({"command": "filter refresh_aliases a\\b"}, "parameter"),
|
|
({"name": "Not A Name"}, "job name"),
|
|
({"schedule": "61 * * * *"}, "range"),
|
|
],
|
|
)
|
|
def test_what_opnsense_cannot_take_is_refused_before_anything_is_written(self, over, match):
|
|
firewall = Firewall()
|
|
|
|
with pytest.raises(ScheduledJobRefused, match=match):
|
|
_driver(firewall).put_scheduled_job(_spec(**over))
|
|
assert firewall.posts == []
|
|
|
|
def test_a_new_job_whose_name_is_taken_is_not_written(self):
|
|
firewall = Firewall()
|
|
|
|
with pytest.raises(ScheduledJobChanged, match="dnsbl-refresh"):
|
|
_driver(firewall).put_scheduled_job(_spec(name="dnsbl-refresh"))
|
|
assert firewall.posts == []
|
|
|
|
def test_a_change_to_a_job_that_is_gone_raises_lookup_error(self):
|
|
with pytest.raises(LookupError, match="alias-refresh"):
|
|
_driver(Firewall()).put_scheduled_job(_spec(), digest="0" * 16)
|
|
|
|
def test_a_change_to_a_job_changed_since_it_was_read_is_not_written(self):
|
|
firewall = Firewall()
|
|
|
|
with pytest.raises(ScheduledJobChanged):
|
|
_driver(firewall).put_scheduled_job(_spec(name="dnsbl-refresh"), digest="0" * 16)
|
|
assert firewall.posts == []
|
|
|
|
def test_what_opnsense_refuses_to_save_is_refused(self):
|
|
refusal = {"result": "failed", "validations": {"job.description": "Text too long"}}
|
|
firewall = Firewall(answers={"/api/cron/settings/add_job": refusal})
|
|
|
|
with pytest.raises(ScheduledJobRefused, match="Text too long"):
|
|
_driver(firewall).put_scheduled_job(_spec())
|
|
assert "/api/cron/service/reconfigure" not in firewall.paths
|
|
|
|
def test_a_failed_save_without_a_reason_raises(self):
|
|
firewall = Firewall(answers={"/api/cron/settings/set_job/": {"result": "failed"}})
|
|
|
|
with pytest.raises(RuntimeError, match="failed"):
|
|
_driver(firewall).put_scheduled_job(_spec(name="dnsbl-refresh"), digest=_digest(OWN))
|
|
assert "/api/cron/service/reconfigure" not in firewall.paths
|
|
|
|
|
|
class TestDelete:
|
|
def test_an_application_job_is_deleted_and_cron_reloads(self):
|
|
firewall = Firewall()
|
|
|
|
result = _driver(firewall).delete_scheduled_job(OWN, digest=_digest(OWN))
|
|
|
|
assert result == {"success": True, "output": f"{OWN} deleted"}
|
|
assert firewall.paths == [
|
|
f"/api/cron/settings/del_job/{OWN_UUID}",
|
|
"/api/cron/service/reconfigure",
|
|
]
|
|
|
|
@pytest.mark.parametrize("key", [ADMIN, PLATFORM, BAD_MARKER])
|
|
def test_a_job_no_application_wrote_is_only_switched(self, key):
|
|
firewall = Firewall()
|
|
|
|
with pytest.raises(ScheduledJobRefused, match="only switched"):
|
|
_driver(firewall).delete_scheduled_job(key, digest=_digest(key))
|
|
assert firewall.posts == []
|
|
|
|
def test_a_job_changed_since_it_was_read_is_not_deleted(self):
|
|
firewall = Firewall()
|
|
|
|
with pytest.raises(ScheduledJobChanged):
|
|
_driver(firewall).delete_scheduled_job(OWN, digest="0" * 16)
|
|
assert firewall.posts == []
|
|
|
|
def test_a_delete_opnsense_did_not_do_raises(self):
|
|
firewall = Firewall(answers={"/api/cron/settings/del_job/": {"result": "not found"}})
|
|
|
|
with pytest.raises(RuntimeError, match="not found"):
|
|
_driver(firewall).delete_scheduled_job(OWN, digest=_digest(OWN))
|
|
assert "/api/cron/service/reconfigure" not in firewall.paths
|