Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
1329644
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 3, 2026
5d6fd80
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 3, 2026
0aa5520
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 3, 2026
d61b77f
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 3, 2026
a90f0a5
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 4, 2026
5b6a459
Merge main into issue-20567-cleanup-proposals (#20567)
mrveiss Nov 6, 2026
05a7c84
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 6, 2026
dd95607
fix(cleanup): admin gate tested through the real auth stack, pending …
mrveiss Nov 6, 2026
c4ef9b9
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 6, 2026
24f851f
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 6, 2026
fbab48a
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 6, 2026
fde77d9
fix(cleanup): admin gate tested through the real auth stack, intent a…
mrveiss Nov 6, 2026
6177410
Merge origin/main into issue-20567-cleanup-proposals (main wins for #…
mrveiss Nov 6, 2026
5e2b0ce
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 7, 2026
3c0ad13
test(cleanup): use FakeAsyncSession as the DB session in the cleanup-…
mrveiss Nov 7, 2026
6c4f63a
refactor(cleanup): reuse audit_logger.AuditResult instead of an inlin…
mrveiss Nov 7, 2026
c7d7a9b
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 7, 2026
a179305
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 7, 2026
8f13ca4
Merge origin/issue-20567-cleanup-proposals (main sync)
mrveiss Nov 7, 2026
07c8302
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 7, 2026
7bc3ed7
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 7, 2026
6def252
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 7, 2026
4142faf
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 7, 2026
9958c00
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
cd10121
fix(admin): real-service pending test, index definition, vanished-fil…
mrveiss Nov 8, 2026
2e8127f
Merge remote-tracking branch 'origin/main' into issue-20567-cleanup-p…
mrveiss Nov 8, 2026
cef54df
refactor(admin): split execute_env_copies_cleanup under 30 lines (#20…
mrveiss Nov 8, 2026
2776725
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
94300b0
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
4670639
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
11c7b59
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
d425e26
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
78a461d
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
c325bf7
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 8, 2026
86ffcf2
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 9, 2026
4440175
Merge main into issue-20567-cleanup-proposals (auto-sync) [skip ci]
github-actions[bot] Nov 9, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 4 additions & 9 deletions autobot-backend/api/admin_cleanup_proposals.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,10 @@ async def _propose(
raise HTTPException(status.HTTP_409_CONFLICT, f"Not proposable: {plan.refused}")
if not plan.targets:
raise HTTPException(status.HTTP_409_CONFLICT, "There is nothing to remove")
service = ApprovalGateService(session)
node = node_identity()
pending = await service.list_approvals(
status=ApprovalStatus.PENDING.value,
approval_type=ApprovalType.DESTRUCTIVE_ACTION.value,
extra_where=(Approval.context["action"].astext == action, Approval.context["node"].astext == node),
limit=1,
)
if pending:
service, node = ApprovalGateService(session), node_identity()
extra = (Approval.context["action"].astext == action, Approval.context["node"].astext == node)
status_, kind = ApprovalStatus.PENDING.value, ApprovalType.DESTRUCTIVE_ACTION.value
if await service.list_approvals(status=status_, approval_type=kind, extra_where=extra, limit=1):
raise HTTPException(status.HTTP_409_CONFLICT, _ALREADY_PENDING)
try:
approval = await service.create_approval(
Expand Down
40 changes: 31 additions & 9 deletions autobot-backend/api/admin_cleanup_proposals_20567_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@
from services import install_cleanup_actions as acts


def _json_arrow_for_old_sqlite(engine) -> None:
"""Some SQLite builds predate ``->>``: run the same statement through ``json_extract`` (same result)."""
import re

from sqlalchemy import event

@event.listens_for(engine.sync_engine, "before_cursor_execute", retval=True)
def _rewrite(_conn, _cursor, statement, parameters, _context, _many): # noqa: ANN001
return re.sub(r"\(?(\w+\.context) ->> \?\)?", r"json_extract(\1, ?)", statement), parameters


def _seed(root: Path) -> None:
backend = root / "autobot-backend"
backend.mkdir(parents=True)
Expand All @@ -27,18 +38,29 @@ def _seed(root: Path) -> None:


async def test_status_counts_and_proposal_does_not_remove(tmp_path: Path) -> None:
"""The REAL approval service over real SQLite: a PENDING row is stored, and nothing is removed."""
from sqlalchemy import select

from models.approval import Approval, ApprovalComment, TaskApprovalLink
from tests.helpers._sqlite_test_engine import real_savepoint_session_factory

await asyncio.to_thread(_seed, tmp_path)
create = AsyncMock(return_value=SimpleNamespace(id="a1", status="pending"))
service = SimpleNamespace(create_approval=create, list_approvals=AsyncMock(return_value=[]))
with (
patch.object(acts, "install_root", return_value=tmp_path),
patch.object(routes, "ApprovalGateService", return_value=service),
async for factory in real_savepoint_session_factory(
[Approval.__table__, ApprovalComment.__table__, TaskApprovalLink.__table__]
):
status = await routes.env_copies_status()
reply = await routes.propose_env_copies_cleanup({"id": "u1"}, MagicMock())
_json_arrow_for_old_sqlite(factory.kw["bind"])
async with factory() as session:
with patch.object(acts, "install_root", return_value=tmp_path):
status = await routes.env_copies_status()
reply = await routes.propose_env_copies_cleanup({"id": "u1"}, session)
with pytest.raises(HTTPException) as repeat: # the real pending lookup finds the first one
await routes.propose_env_copies_cleanup({"id": "u1"}, session)
async with factory() as session:
rows = (await session.execute(select(Approval))).scalars().all()
assert status.count == 1 and reply.action == acts.ENV_COPIES_ACTION
assert reply.status == "pending"
assert create.await_args.kwargs["context"] == {"action": acts.ENV_COPIES_ACTION, "node": acts.node_identity()}
assert reply.status == "pending" and repeat.value.status_code == 409
assert len(rows) == 1 and str(rows[0].id) == reply.approval_id and rows[0].status == "pending"
assert rows[0].context == {"action": acts.ENV_COPIES_ACTION, "node": acts.node_identity()}
assert len(await asyncio.to_thread(lambda: list((tmp_path / "autobot-backend").glob(".env.*~")))) == 2


Expand Down
98 changes: 98 additions & 0 deletions autobot-backend/api/admin_cleanup_proposals_auth_20567_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Copyright 2025-2026 mrveiss
# SPDX-License-Identifier: Apache-2.0
"""#20567: the cleanup routes sit behind the REAL ``check_admin_permission`` gate and the real ``get_current_user``.

The handler tests call the functions directly, so the router dependency never runs there. Here the REAL auth
stack answers through a ``TestClient``: only the identity it reads and the database (a ``FakeAsyncSession``: auth, not transactions, is under test) are stood in.
"""

from __future__ import annotations

import importlib
import sys
import uuid
from types import SimpleNamespace
from unittest.mock import AsyncMock

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient

from services import install_cleanup_actions as acts
from services.approval_gate_service import ApprovalGateService
from testkit.fake_async_session import FakeAsyncSession
from tests.conftest import load_real_auth_middleware

_INTERNAL_KEY = {"X-Internal-API-Key": "internal-service-key-for-tests"}
_APPROVAL_ID = uuid.UUID("00000000-0000-4000-8000-000000000567")
_PATHS = {
"status": ("GET", "/api/admin/env-copies-cleanup"),
"propose": ("POST", "/api/admin/env-copies-cleanup/requests"),
}


def _person(role: str) -> dict:
return {"username": role, "role": role, "user_id": "u-567", "id": "u-567", "auth_method": "jwt"}


@pytest.fixture
def client(monkeypatch):
"""A client whose gate is the production code; ``identity.user`` is the human it resolves."""
real = load_real_auth_middleware()
monkeypatch.setitem(sys.modules, "auth_middleware", real)
monkeypatch.delitem(sys.modules, "api.admin_cleanup_proposals", raising=False)
routes = importlib.import_module("api.admin_cleanup_proposals")
identity = SimpleNamespace(user=None)
monkeypatch.setattr(real, "resolve_human_user", AsyncMock(side_effect=lambda _request: identity.user))
monkeypatch.setattr(
real, "verify_internal_api_key", lambda provided: provided == _INTERNAL_KEY["X-Internal-API-Key"]
)
plan = acts.CleanupPlan(targets=(acts.Path("a"),), kept=acts.Path("b"))
monkeypatch.setattr(routes, "plan_env_copies", lambda: plan)
created = SimpleNamespace(id=_APPROVAL_ID, status="pending")
monkeypatch.setattr(ApprovalGateService, "list_approvals", AsyncMock(return_value=[]))
monkeypatch.setattr(ApprovalGateService, "create_approval", AsyncMock(return_value=created))
app = FastAPI()
app.include_router(routes.router, prefix="/api")
app.dependency_overrides[routes.get_db_session] = lambda: FakeAsyncSession()
yield TestClient(app, raise_server_exceptions=False), identity
sys.modules.pop("api.admin_cleanup_proposals", None)


@pytest.mark.parametrize(("method", "path"), _PATHS.values(), ids=list(_PATHS))
def test_an_anonymous_caller_is_401(client, method: str, path: str) -> None:
test_client, _ = client

assert test_client.request(method, path).status_code == 401


@pytest.mark.parametrize(("method", "path"), _PATHS.values(), ids=list(_PATHS))
def test_a_non_admin_is_403(client, method: str, path: str) -> None:
test_client, identity = client
identity.user = _person("user")

assert test_client.request(method, path).status_code == 403


@pytest.mark.parametrize(("method", "path"), _PATHS.values(), ids=list(_PATHS))
def test_the_internal_key_alone_is_refused(client, method: str, path: str) -> None:
test_client, _ = client

assert test_client.request(method, path, headers=_INTERNAL_KEY).status_code in (401, 403)


def test_an_admin_passes_the_gate(client) -> None:
test_client, identity = client
identity.user = _person("admin")

assert test_client.get(_PATHS["status"][1]).status_code == 200


def test_an_admin_proposal_is_201_and_names_the_approval(client) -> None:
test_client, identity = client
identity.user = _person("admin")

reply = test_client.post(_PATHS["propose"][1])

assert reply.status_code == 201
assert reply.json()["approval_id"] == str(_APPROVAL_ID) and reply.json()["action"] == acts.ENV_COPIES_ACTION
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,24 @@ def test_duplicate_cleanups_on_one_node_fail_and_other_nodes_do_not_collide(monk
assert _run(monkeypatch, ok).call_count == 2
with pytest.raises(RuntimeError, match=r"a \(2 pending\)"):
_run(monkeypatch, ok[:1] * 2)


def test_the_env_copies_index_definition_matches_the_migration_and_the_model(monkeypatch) -> None:
"""Columns/expressions, uniqueness and the partial WHERE of the created index, against the model's index."""
from sqlalchemy.dialects import postgresql

from models.approval import PENDING_ENV_COPIES_INDEX, PENDING_ENV_COPIES_WHERE, Approval

create = _run(monkeypatch, [])
call = next(c for c in create.call_args_list if c.args[0] == PENDING_ENV_COPIES_INDEX)
assert call.args[1] == "approvals" and call.kwargs["unique"] is True
assert [str(e) for e in call.args[2]] == ["(context ->> 'action')", "(context ->> 'node')"]
assert str(call.kwargs["postgresql_where"]) == PENDING_ENV_COPIES_WHERE
model_index = {i.name: i for i in Approval.__table__.indexes}[PENDING_ENV_COPIES_INDEX]
assert model_index.unique is True
assert str(model_index.dialect_options["postgresql"]["where"]) == PENDING_ENV_COPIES_WHERE
literal = {"dialect": postgresql.dialect(), "compile_kwargs": {"literal_binds": True}}
model_expressions = [
str(e.compile(**literal)).replace("approvals.", "").strip("()") for e in model_index.expressions
]
assert model_expressions == [str(e).strip("()") for e in call.args[2]]
Loading