Files
planet/backend/tests/test_actions_approval.py
T
linkong 1c0066edc6
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.85.0
2026-12-06 22:47:23 +08:00

248 lines
9.4 KiB
Python

"""Tests for §4.5 action request matrix, SSRF/allowlist guards, webhook formats, and AuditLog."""
from __future__ import annotations
from contextlib import asynccontextmanager
from types import SimpleNamespace
from httpx import ASGITransport, AsyncClient
import pytest
from sqlalchemy import create_engine, select
from sqlalchemy.orm import Session
from app.core.access_gate import get_current_user, require_admin_user
from app.core.enums import UserRole
from app.db.migrations import discover_migrations
from app.db.session import Base, get_db
from app.main import app
from app.models.action_request import ActionRequest
from app.models.system_log import AuditLog
from app.models.system_setting import SystemSetting
from app.services.actions import (
ActionValidationError,
decide_action_request,
format_webhook_payload,
validate_allowlisted_webhook_url,
)
class _AsyncSQLiteSession:
def __init__(self, session: Session):
self._session = session
def get_bind(self):
return self._session.get_bind()
def add(self, instance) -> None:
self._session.add(instance)
async def get(self, entity, ident):
return self._session.get(entity, ident)
async def execute(self, statement, params=None):
return (
self._session.execute(statement, params)
if params is not None
else self._session.execute(statement)
)
async def flush(self) -> None:
self._session.flush()
async def commit(self) -> None:
self._session.commit()
class _AsyncConnShim:
def __init__(self, conn):
self._conn = conn
self.dialect = conn.dialect
async def execute(self, stmt, params=None):
return (
self._conn.execute(stmt, params)
if params is not None
else self._conn.execute(stmt)
)
async def _make_sqlite_session():
engine = create_engine("sqlite:///:memory:")
with engine.begin() as raw_conn:
shim = _AsyncConnShim(raw_conn)
for step in discover_migrations():
if step.version in {"0012", "0013"}:
await step.upgrade(shim)
Base.metadata.create_all(raw_conn, checkfirst=True)
for step in discover_migrations():
if step.version == "0013":
await step.upgrade(shim)
@asynccontextmanager
async def _factory():
with Session(engine) as session:
yield _AsyncSQLiteSession(session)
return engine, _factory
def test_webhook_allowlist_ssrf_and_bot_formats(monkeypatch) -> None:
allowlist = ["https://hooks.example.com/planet"]
# SSRF private/loopback IP must always be blocked even if allowlisted!
with pytest.raises(ActionValidationError):
validate_allowlisted_webhook_url("http://127.0.0.1:8080/hook", ["http://127.0.0.1:8080"])
with pytest.raises(ActionValidationError):
validate_allowlisted_webhook_url("http://169.254.169.254/latest", ["http://169.254.169.254"])
# Non-allowlisted external host must be blocked
with pytest.raises(ActionValidationError):
validate_allowlisted_webhook_url("https://evil.example.org/leak", allowlist)
# Mock DNS resolution for public allowlisted domain
monkeypatch.setattr(
"app.services.ai.tool_registry.socket.getaddrinfo",
lambda *_a, **_kw: [(2, 1, 6, "", ("93.184.216.34", 443))],
)
ok_url = validate_allowlisted_webhook_url("https://hooks.example.com/planet/bot1", allowlist)
assert ok_url == "https://hooks.example.com/planet/bot1"
req = ActionRequest(id=9, action_type="notify_webhook", target_object_ids=["cable:apg-1"], requested_by="admin1")
assert format_webhook_payload(channel="wecom", title="T", summary="S", request_obj=req)["msgtype"] == "markdown"
assert format_webhook_payload(channel="dingtalk", title="T", summary="S", request_obj=req)["markdown"]["title"] == "T"
assert format_webhook_payload(channel="feishu", title="T", summary="S", request_obj=req)["msg_type"] == "text"
assert format_webhook_payload(channel="generic", title="T", summary="S", request_obj=req)["event"] == "planet.action_request"
@pytest.mark.asyncio
async def test_action_approval_matrix_ai_pending_and_audit_log(monkeypatch) -> None:
_engine, session_factory = await _make_sqlite_session()
actor = {"id": 1, "username": "viewer1", "role": UserRole.VIEWER.value}
async with session_factory() as db:
db.add(
SystemSetting(
category="actions",
payload={"webhook_allowlist": ["https://hooks.example.com/planet"]},
)
)
await db.commit()
async def _override_db():
async with session_factory() as session:
yield session
async def _override_read():
return SimpleNamespace(**actor)
async def _override_admin():
return SimpleNamespace(**actor)
app.dependency_overrides[get_db] = _override_db
app.dependency_overrides[get_current_user] = _override_read
app.dependency_overrides[require_admin_user] = _override_admin
try:
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
# 1. Viewer cannot submit
r_v = await client.post(
"/api/v1/actions",
json={"action_type": "add_to_watchlist", "target_object_ids": ["cable:apg-1"]},
)
assert r_v.status_code == 403
# 2. Admin can directly execute low-risk action
actor.update({"id": 2, "username": "admin1", "role": UserRole.ADMIN.value})
r_low = await client.post(
"/api/v1/actions",
json={"action_type": "add_to_watchlist", "target_object_ids": ["cable:apg-1"]},
)
assert r_low.status_code == 200
assert r_low.json()["status"] == "executed"
# 3. AI-suggested low-risk stays strictly pending
r_ai = await client.post(
"/api/v1/actions",
json={
"action_type": "add_to_watchlist",
"target_object_ids": ["cable:apg-1"],
"ai_suggested": True,
},
)
assert r_ai.status_code == 200
assert r_ai.json()["status"] == "pending"
# 4. Super_admin submits high-risk webhook -> stays pending
actor.update({"id": 3, "username": "super1", "role": UserRole.SUPER_ADMIN.value})
r_high = await client.post(
"/api/v1/actions",
json={
"action_type": "notify_webhook",
"target_object_ids": ["cable:apg-1"],
"params": {
"webhook_url": "https://hooks.example.com/planet/alert",
"channel": "wecom",
"title": "Cable Alert",
"summary": "Review requested",
},
},
)
assert r_high.status_code == 200
high_id = r_high.json()["id"]
assert r_high.json()["status"] == "pending"
# 5. Admin cannot approve high risk (403)
actor.update({"id": 2, "username": "admin1", "role": UserRole.ADMIN.value})
assert (
await client.post(
f"/api/v1/actions/{high_id}/approve",
json={"decision_reason": "Try approve"},
)
).status_code == 403
# 6. Same super1 cannot approve own high-risk request (403)
actor.update({"id": 3, "username": "super1", "role": UserRole.SUPER_ADMIN.value})
assert (
await client.post(
f"/api/v1/actions/{high_id}/approve",
json={"decision_reason": "Self approval forbidden"},
)
).status_code == 403
# 7. Empty reason rejected (422)
actor.update({"id": 4, "username": "super2", "role": UserRole.SUPER_ADMIN.value})
assert (
await client.post(
f"/api/v1/actions/{high_id}/approve",
json={"decision_reason": " "},
)
).status_code == 422
# 8. Distinct super2 approves high risk with reason -> executes allowlisted webhook + writes AuditLog
monkeypatch.setattr(
"app.services.ai.tool_registry.socket.getaddrinfo",
lambda *_a, **_kw: [(2, 1, 6, "", ("93.184.216.34", 443))],
)
sent_payloads = []
async def _mock_post(url, body_bytes, headers):
sent_payloads.append((url, body_bytes, headers))
return {"status_code": 200}
async with session_factory() as db:
req_obj = await db.get(ActionRequest, high_id)
done = await decide_action_request(
db,
req=req_obj,
decision="approve",
decision_reason="Verified independent evidence",
actor_id=4,
actor_name="super2",
actor_role=UserRole.SUPER_ADMIN.value,
http_post_fn=_mock_post,
)
assert done.status == "executed"
assert len(sent_payloads) == 1
audits = list((await db.execute(select(AuditLog))).scalars().all())
assert any(a.target_id == str(high_id) and a.result == "executed" for a in audits)
finally:
app.dependency_overrides.clear()