180 lines
5.9 KiB
Python
180 lines
5.9 KiB
Python
"""
|
|||
|
|
M5 安全与审计测试
|
||
|
|
=================
|
||
|
|
|
||
|
|
【功能说明】
|
||
|
|
覆盖回滚服务(快照还原闭环)、审计 API、HITL 中断状态机修正。
|
||
|
|
重点验证「改坏了能改回来」这条硬约束 5 的核心兜底。
|
||
|
|
|
||
|
|
【技术选型理由】
|
||
|
|
1. 回滚测试做完整闭环:改 → 备份 → 索引 → 回滚 → 验证内容一致;
|
||
|
|
2. 状态机测试验证 waiting_approval 能正确进入;
|
||
|
|
3. 审计 API 测试验证过滤与统计。
|
||
|
|
"""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import json
|
||
|
|
import shutil
|
||
|
|
from pathlib import Path
|
||
|
|
from typing import Generator
|
||
|
|
from uuid import uuid4
|
||
|
|
|
||
|
|
import pytest
|
||
|
|
|
||
|
|
from app.tasks.rollback_service import RollbackService, list_backups, record_backup
|
||
|
|
from app.tools.file_tools import edit_file, read_file, write_file
|
||
|
|
|
||
|
|
|
||
|
|
# ---------- Fixtures ----------
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.fixture()
|
||
|
|
def d_tmp_path() -> Generator[Path, None, None]:
|
||
|
|
base = Path(r"D:\Agent\pytest_tmp")
|
||
|
|
base.mkdir(parents=True, exist_ok=True)
|
||
|
|
work = base / uuid4().hex[:12]
|
||
|
|
work.mkdir(parents=True, exist_ok=True)
|
||
|
|
yield work
|
||
|
|
shutil.rmtree(work, ignore_errors=True)
|
||
|
|
|
||
|
|
|
||
|
|
# ---------- 回滚服务:快照还原闭环 ----------
|
||
|
|
|
||
|
|
|
||
|
|
def test_rollback_by_snapshots(d_tmp_path: Path) -> None:
|
||
|
|
"""完整回滚闭环:改码 → 快照 → 回滚 → 内容回到改码前。"""
|
||
|
|
task_id = f"t_{uuid4().hex[:8]}"
|
||
|
|
target = d_tmp_path / "Sample.java"
|
||
|
|
write_file(target, "原始代码内容", task_id=task_id)
|
||
|
|
# 覆盖写入(会自动快照 + 记录索引)
|
||
|
|
write_file(target, "被 Agent 改坏的内容", task_id=task_id)
|
||
|
|
|
||
|
|
# 确认快照索引已记录
|
||
|
|
backups = list_backups(task_id)
|
||
|
|
assert len(backups) >= 1, "快照索引应有记录"
|
||
|
|
|
||
|
|
# 执行回滚
|
||
|
|
service = RollbackService()
|
||
|
|
result = service.rollback_task(task_id, strategy="snapshot")
|
||
|
|
assert result["success"] is True
|
||
|
|
assert result["strategy_used"] == "snapshot"
|
||
|
|
assert len(result["restored_files"]) >= 1
|
||
|
|
|
||
|
|
# 验证内容已还原
|
||
|
|
content = read_file(target)["content"]
|
||
|
|
assert content == "原始代码内容"
|
||
|
|
|
||
|
|
|
||
|
|
def test_rollback_edit_file_also_records(d_tmp_path: Path) -> None:
|
||
|
|
"""edit_file 的备份也被索引,可用于回滚。"""
|
||
|
|
task_id = f"t_{uuid4().hex[:8]}"
|
||
|
|
target = d_tmp_path / "Code.java"
|
||
|
|
write_file(target, "public class A { int x = 1; }", task_id=task_id)
|
||
|
|
edit_file(target, "int x = 1;", "int x = 2;", task_id=task_id)
|
||
|
|
|
||
|
|
backups = list_backups(task_id)
|
||
|
|
assert len(backups) >= 1
|
||
|
|
|
||
|
|
service = RollbackService()
|
||
|
|
result = service.rollback_task(task_id, strategy="snapshot")
|
||
|
|
assert result["success"] is True
|
||
|
|
content = read_file(target)["content"]
|
||
|
|
assert "int x = 1;" in content, "应还原到编辑前版本"
|
||
|
|
|
||
|
|
|
||
|
|
def test_rollback_no_backups_returns_failure(d_tmp_path: Path) -> None:
|
||
|
|
"""无快照记录时返回失败,不抛异常。"""
|
||
|
|
service = RollbackService()
|
||
|
|
result = service.rollback_task("task_不存在的", strategy="snapshot")
|
||
|
|
assert result["success"] is False
|
||
|
|
assert "未找到" in result["message"]
|
||
|
|
|
||
|
|
|
||
|
|
def test_get_task_backups(d_tmp_path: Path) -> None:
|
||
|
|
"""查询任务快照列表(首次写入新文件不产生快照,覆盖才有)。"""
|
||
|
|
task_id = f"t_{uuid4().hex[:8]}"
|
||
|
|
target = d_tmp_path / "X.txt"
|
||
|
|
write_file(target, "v1", task_id=task_id) # 新建,无快照
|
||
|
|
write_file(target, "v2", task_id=task_id) # 覆盖 → 1 条快照
|
||
|
|
write_file(target, "v3", task_id=task_id) # 覆盖 → 2 条快照
|
||
|
|
|
||
|
|
service = RollbackService()
|
||
|
|
backups = service.get_task_backups(task_id)
|
||
|
|
assert len(backups) >= 2
|
||
|
|
assert all(b["task_id"] == task_id for b in backups)
|
||
|
|
|
||
|
|
|
||
|
|
# ---------- 任务状态机 ----------
|
||
|
|
|
||
|
|
|
||
|
|
def test_task_waiting_approval_transition(d_tmp_path: Path) -> None:
|
||
|
|
"""running → waiting_approval 合法迁移(HITL 中断场景)。"""
|
||
|
|
from app.schemas.task import TaskCreate
|
||
|
|
from app.tasks.task_store import SqliteTaskStore
|
||
|
|
|
||
|
|
store = SqliteTaskStore(d_tmp_path / "t.db")
|
||
|
|
task = store.create(
|
||
|
|
TaskCreate(project_id="p", requirement_text="需求"), thread_id="th1"
|
||
|
|
)
|
||
|
|
updated = store.update_status(
|
||
|
|
task.id,
|
||
|
|
status="waiting_approval",
|
||
|
|
pending_approval='{"message":"高风险待审批","plan":{"steps":[]}}',
|
||
|
|
)
|
||
|
|
assert updated is not None
|
||
|
|
assert updated.status == "waiting_approval"
|
||
|
|
assert "高风险" in updated.pending_approval
|
||
|
|
|
||
|
|
|
||
|
|
def test_task_waiting_approval_then_running(d_tmp_path: Path) -> None:
|
||
|
|
"""waiting_approval → running 合法(审批通过后恢复执行)。"""
|
||
|
|
from app.schemas.task import TaskCreate
|
||
|
|
from app.tasks.task_store import SqliteTaskStore
|
||
|
|
|
||
|
|
store = SqliteTaskStore(d_tmp_path / "t.db")
|
||
|
|
task = store.create(
|
||
|
|
TaskCreate(project_id="p", requirement_text="需求"), thread_id="th1"
|
||
|
|
)
|
||
|
|
store.update_status(task.id, status="waiting_approval")
|
||
|
|
updated = store.update_status(task.id, status="running")
|
||
|
|
assert updated is not None and updated.status == "running"
|
||
|
|
|
||
|
|
|
||
|
|
# ---------- 审计 API ----------
|
||
|
|
|
||
|
|
|
||
|
|
def test_audit_api_list_and_summary() -> None:
|
||
|
|
"""审计 API 能读取日志并统计。"""
|
||
|
|
from fastapi.testclient import TestClient
|
||
|
|
|
||
|
|
from app.main import create_app
|
||
|
|
|
||
|
|
app = create_app()
|
||
|
|
with TestClient(app) as client:
|
||
|
|
resp = client.get("/api/audit?limit=5")
|
||
|
|
body = resp.json()
|
||
|
|
assert body["code"] == 0
|
||
|
|
assert isinstance(body["data"], list)
|
||
|
|
|
||
|
|
resp2 = client.get("/api/audit/summary")
|
||
|
|
body2 = resp2.json()
|
||
|
|
assert body2["code"] == 0
|
||
|
|
assert "total" in body2["data"]
|
||
|
|
assert "by_action" in body2["data"]
|
||
|
|
|
||
|
|
|
||
|
|
# ---------- 路由完整性 ----------
|
||
|
|
|
||
|
|
|
||
|
|
def test_all_m5_routes_registered() -> None:
|
||
|
|
"""M5 新增路由全部注册成功。"""
|
||
|
|
from app.main import create_app
|
||
|
|
|
||
|
|
app = create_app()
|
||
|
|
paths = {r.path for r in app.routes if hasattr(r, "path")}
|
||
|
|
assert "/api/audit" in paths
|
||
|
|
assert "/api/audit/summary" in paths
|
||
|
|
assert "/api/tasks/{task_id}/rollback" in paths
|
||
|
|
assert "/api/tasks/{task_id}/backups" in paths
|