feat(ansible): runs stay inside their source; controller-side vars are admin-only (#5034)
CI / lint (push) Successful in 2s
CI / unit (push) Successful in 1m12s
CI / integration (push) Successful in 59s
CI / publish (push) Successful in 1m3s

#5034 "Playbook runs: path and inventory checks in trigger_run, connection
vars admin-only, confirm enforced server-side, web actions audited".
Ansible runs inside the Steward container, so an operator who could name
any playbook path, set ansible_connection=local or ProxyCommand ssh args,
or put {{ lookup('pipe', …) }} in a value could run commands on Steward.

- steward/ansible/guards.py: check_playbook (the source must list it),
  check_inventory_scope (steward:* or an inventory file the source has),
  check_vars_for_role (ansible_* beyond host/port/user/password/become,
  and any Jinja in a value, are admin-only), changed_vars (an edit is
  held to the role only for what it changes).
- trigger_run applies the path checks, so every run path — web, MCP,
  alerts, schedules, plugins — gets them.
- Variables are checked by role on the web run form, host-page runs,
  schedule create/update, inventory group/target create/update, and MCP
  run_playbook / create_schedule / update_schedule.
- A steward:confirm playbook needs the confirmation ticked on the server
  side for a real (non-check) web run, as MCP already required.
- Audited: runs, cancel, schedule create/update/enable/disable/delete/
  run-now, playbook create/update/delete, inventory group and target
  create/update/delete (variable names only, never values). One
  audit_request helper serves the web routes.
- The CSRF form guard and the route guard now each test that they fail
  on a synthetic broken input (rule: a guard must be able to fail).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-06 10:57:34 -04:00
co-authored by Claude Opus 5.5
parent 6a1bc437c9
commit 8dad79f17a
11 changed files with 393 additions and 42 deletions
+75
View File
@@ -0,0 +1,75 @@
"""A run is held to what its source lists, and the variables that would run
commands on the Steward server are admin-only."""
from types import SimpleNamespace
import pytest
from steward.ansible import guards, runner
from steward.models.users import UserRole
@pytest.fixture
def source(tmp_path):
(tmp_path / "site.yml").write_text("- hosts: all\n tasks: []\n")
(tmp_path / "roles").mkdir()
(tmp_path / "roles" / "deep.yml").write_text("- hosts: all\n")
(tmp_path / "inventory.yml").write_text("all: {}\n")
return {"name": "local", "path": str(tmp_path)}
def test_playbook_must_be_listed_by_its_source(source, tmp_path):
assert guards.check_playbook(source, "site.yml") is None
assert guards.check_playbook(source, "roles/deep.yml") is None
(tmp_path.parent / "outside.yml").write_text("- hosts: localhost\n")
for path in ("../outside.yml", "/etc/passwd", str(tmp_path / "site.yml"), "missing.yml"):
assert "has no playbook" in guards.check_playbook(source, path)
def test_inventory_scope(source):
assert guards.check_inventory_scope(source, "steward:all") is None
assert guards.check_inventory_scope(source, "repo:local:inventory.yml") is None
assert "no inventory file" in guards.check_inventory_scope(source, "repo:local:../../etc/hosts")
assert guards.check_inventory_scope(source, "/tmp/inv") == "Invalid inventory_scope"
@pytest.mark.parametrize("variables", [
{"ansible_host": "10.0.0.5", "ansible_user": "steward", "ansible_become": True},
{"release": "1.2", "ansible_port": 2222},
{},
])
def test_operator_may_set_target_vars(variables):
assert guards.check_vars_for_role(variables, UserRole.operator) is None
@pytest.mark.parametrize("variables,word", [
({"ansible_connection": "local"}, "ansible_connection"),
({"ansible_ssh_common_args": "-o ProxyCommand=sh -c id"}, "ansible_ssh_common_args"),
({"ansible_python_interpreter": "/tmp/x"}, "ansible_python_interpreter"),
({"ansible_user": "{{ lookup('pipe', 'id') }}"}, "ansible_user"),
({"note": {"nested": ["{% raw %}"]}}, "note"),
])
def test_operator_may_not_set_controller_vars(variables, word):
err = guards.check_vars_for_role(variables, UserRole.operator)
assert err and word in err and "Only an admin" in err
assert guards.check_vars_for_role(variables, None) == err
assert guards.check_vars_for_role(variables, UserRole.admin) is None
def test_only_changes_are_held_to_the_role():
stored = {"ansible_ssh_common_args": "-J bastion", "ansible_user": "a"}
edited = {"ansible_ssh_common_args": "-J bastion", "ansible_user": "b"}
assert guards.changed_vars(edited, stored) == {"ansible_user": "b"}
assert guards.check_vars_for_role(guards.changed_vars(edited, stored), UserRole.operator) is None
edited["ansible_ssh_common_args"] = "-o ProxyCommand=x"
assert guards.check_vars_for_role(guards.changed_vars(edited, stored), UserRole.operator)
@pytest.mark.asyncio
async def test_trigger_run_refuses_a_path_its_source_does_not_list(source, monkeypatch):
monkeypatch.setattr(runner.src_module, "get_sources", lambda cfg: [source])
app = SimpleNamespace(config={})
run, src, err = await runner.trigger_run(app, source_name="local", playbook_path="../x.yml")
assert run is None and "has no playbook" in err
run, src, err = await runner.trigger_run(app, source_name="local", playbook_path="site.yml",
inventory_scope="repo:local:/etc/hosts")
assert run is None and "no inventory file" in err
+24
View File
@@ -132,3 +132,27 @@ def test_builtin_playbooks_get_steward_url_from_steward():
finally:
_context._app_ctx.reset(a)
_context._base_url_ctx.reset(u)
async def test_run_playbook_holds_variables_to_the_callers_role(monkeypatch):
monkeypatch.setattr(automation, "_source", lambda name: {"name": name, "path": "/x"})
monkeypatch.setattr(automation, "_playbook", lambda s, p: "- hosts: all\n tasks: []\n")
def _no_run(*a, **k):
raise AssertionError("a run was started")
monkeypatch.setattr(automation, "trigger_run", _no_run)
operator = Caller(user_id="u", username="op", role=UserRole.operator, token_id=1)
monkeypatch.setattr(automation, "current_caller_or_none", lambda: operator)
with pytest.raises(ValueError, match="Only an admin can set ansible_connection"):
await automation.run_playbook("s", "site.yml", extra_vars={"ansible_connection": "local"})
with pytest.raises(ValueError, match="Ansible evaluates it"):
await automation.run_playbook("s", "site.yml", extra_vars={"x": "{{ lookup('pipe','id') }}"})
def test_schedule_update_holds_only_changed_variables(monkeypatch):
operator = Caller(user_id="u", username="op", role=UserRole.operator, token_id=1)
monkeypatch.setattr(automation, "current_caller_or_none", lambda: operator)
stored = {"ansible_ssh_common_args": "-J bastion"}
automation.check_caller_vars({**stored, "release": "2"}, stored)
with pytest.raises(ValueError, match="Only an admin"):
automation.check_caller_vars({"ansible_ssh_common_args": "-o ProxyCommand=x"}, stored)
+18 -8
View File
@@ -14,17 +14,27 @@ _FORM_TAG = re.compile(r"<form\b[^>]*>", re.S | re.I)
_POST = re.compile(r"""\bmethod\s*=\s*["']?post\b""", re.I)
def forms_missing_token(text: str) -> list[int]:
"""Line numbers of POST forms whose first child is not {{ csrf_field() }}."""
return [text.count("\n", 0, m.start()) + 1 for m in _FORM_TAG.finditer(text)
if _POST.search(m.group(0))
and not text[m.end():].lstrip().startswith("{{ csrf_field() }}")]
def test_the_form_guard_can_fail():
broken = '<form\n method="post" action="/x">\n <input name="a">\n</form>'
fixed = '<form method="POST" action="/x">{{ csrf_field() }}<input name="a"></form>'
assert forms_missing_token(broken) == [1]
assert forms_missing_token(fixed) == []
assert forms_missing_token('<form method="get">') == []
def test_every_post_form_carries_the_token():
files = sorted((_REPO / "steward" / "templates").rglob("*.html")) + \
sorted((_REPO / "plugins").rglob("templates/**/*.html"))
missing = []
for f in files:
text = f.read_text()
for m in _FORM_TAG.finditer(text):
if _POST.search(m.group(0)) and \
not text[m.end():].lstrip().startswith("{{ csrf_field() }}"):
line = text.count("\n", 0, m.start()) + 1
missing.append(f"{f.relative_to(_REPO)}:{line}")
assert files
missing = [f"{f.relative_to(_REPO)}:{line}" for f in files
for line in forms_missing_token(f.read_text())]
assert not missing, "POST forms without {{ csrf_field() }}: " + ", ".join(missing)
+32 -15
View File
@@ -13,28 +13,45 @@ _REPO = pathlib.Path(steward.__file__).parent.parent
_ROUTE_METHODS = ("get", "post", "put", "patch", "delete", "route", "websocket")
def _route_decorated_views():
files = [p for root in ("steward", "plugins") for p in (_REPO / root).rglob("*.py")
if "migrations" not in p.parts]
for path in files:
tree = ast.parse(path.read_text())
for node in ast.walk(tree):
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
continue
decorators = [ast.unparse(d) for d in node.decorator_list]
if any(f".{m}('/" in d or f'.{m}("/' in d for d in decorators for m in _ROUTE_METHODS):
yield path, node, decorators
def route_views(source: str):
"""(function node, decorator texts) for each route-decorated function."""
for node in ast.walk(ast.parse(source)):
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
continue
decorators = [ast.unparse(d) for d in node.decorator_list]
if any(f".{m}('/" in d for d in decorators for m in _ROUTE_METHODS):
yield node, decorators
def unmarked_routes(source: str) -> list[str]:
return [n.name for n, decs in route_views(source)
if not any(d.startswith(("require_role(", "public_route(")) for d in decs)]
def _sources():
for root in ("steward", "plugins"):
for path in (_REPO / root).rglob("*.py"):
if "migrations" not in path.parts:
yield path, path.read_text()
def test_the_route_guard_can_fail():
source = (
"@bp.get('/open')\nasync def open_view(): ...\n"
"@bp.post('/closed')\n@require_role(UserRole.viewer)\nasync def closed(): ...\n"
"@bp.get('/login')\n@public_route('login')\nasync def login(): ...\n"
"def helper(): ...\n")
assert unmarked_routes(source) == ["open_view"]
def test_every_route_says_who_may_reach_it():
unmarked = [f"{p.relative_to(_REPO)}:{n.lineno} {n.name}"
for p, n, decs in _route_decorated_views()
if not any(d.startswith(("require_role(", "public_route(")) for d in decs)]
unmarked = [f"{p.relative_to(_REPO)} {name}" for p, text in _sources()
for name in unmarked_routes(text)]
assert not unmarked, "routes with neither require_role nor public_route: " + ", ".join(unmarked)
def test_the_scan_sees_routes():
names = {n.name for _, n, _ in _route_decorated_views()}
names = {n.name for _, text in _sources() for n, _ in route_views(text)}
assert {"login", "health", "ingest", "widget_table", "public_share"} <= names