test_audit.py 7.29 KB
"""审计:脱敏、记录构造、写入器的降级行为。

不依赖 MySQL —— 仓库用假实现替换掉。
"""

from __future__ import annotations

import asyncio
import json
from datetime import datetime

import pytest

from mcp_hive.core.audit import recorder as recorder_module
from mcp_hive.core.audit.entry import AuditEntry, AuditStatus, CallerChannel
from mcp_hive.core.audit.masking import mask_arguments
from mcp_hive.core.audit.recorder import AuditRecorder
from mcp_hive.core.config.settings import AppSettings, DatabaseSettings


def make_entry(**overrides) -> AuditEntry:
    base = {
        "request_id": "req-1",
        "ts": datetime(2026, 8, 1, 10, 0, 0),
        "service": "used_car",
        "tool_name": "query_monthly_data",
        "status": AuditStatus.SUCCESS,
        "duration_ms": 42,
    }
    base.update(overrides)
    return AuditEntry(**base)


# -------------------------------------------------------------------- 脱敏


@pytest.mark.parametrize(
    "key",
    ["secret", "password", "token", "api_key", "apiKey", "appKey", "sign", "Authorization"],
)
def test_sensitive_keys_are_masked(key):
    assert mask_arguments({key: "s3cr3t"})[key] == "***"


def test_normal_values_pass_through():
    args = {"store_name": "比亚迪深圳南山店", "month": "2026-08", "store_id": 42}
    assert mask_arguments(args) == args


def test_masking_is_recursive():
    result = mask_arguments({"outer": {"password": "x", "keep": 1}})
    assert result["outer"]["password"] == "***"
    assert result["outer"]["keep"] == 1


def test_long_strings_are_truncated():
    result = mask_arguments({"note": "x" * 900})
    assert len(result["note"]) < 900
    assert result["note"].endswith("…")


def test_masking_survives_deep_nesting():
    deep = current = {}
    for _ in range(20):
        current["next"] = {}
        current = current["next"]
    assert mask_arguments(deep)  # 不能爆栈


# --------------------------------------------------------------- 记录构造


def test_identity_is_never_marked_verified():
    """本系统不做鉴权,这一列必须恒为 0,避免被误当成可追责的凭据。"""
    assert make_entry().to_row()["identity_verified"] == 0


def test_each_entry_gets_its_own_call_id():
    """一次 HTTP 请求可以携带多次工具调用,审计行的唯一标识不能用 request_id。"""
    a, b = make_entry(), make_entry()
    assert a.call_id != b.call_id
    assert a.request_id == b.request_id


def test_arguments_are_serialized_as_json():
    row = make_entry(arguments={"month": "2026-08"}).to_row()
    assert json.loads(row["arguments_json"]) == {"month": "2026-08"}


def test_oversized_arguments_are_truncated_with_a_marker():
    row = make_entry(arguments={"blob": "x" * 10000}).to_row(max_argument_chars=200)
    payload = json.loads(row["arguments_json"])
    assert payload["_truncated"] is True
    assert len(row["arguments_json"]) < 400


def test_error_message_is_capped_to_column_width():
    row = make_entry(error_message="e" * 2000).to_row()
    assert len(row["error_message"]) <= 512


def test_empty_error_message_becomes_null():
    assert make_entry(error_message="").to_row()["error_message"] is None


def test_jsonl_round_trips():
    payload = json.loads(make_entry(arguments={"a": 1}).to_jsonl())
    assert payload["tool_name"] == "query_monthly_data"
    assert payload["ts"].startswith("2026-08-01")


# ----------------------------------------------------------------- 写入器


class FakeRepo:
    def __init__(self, fail: bool = False) -> None:
        self.rows: list[AuditEntry] = []
        self.fail = fail
        self.calls = 0

    async def insert_many(self, entries):
        self.calls += 1
        if self.fail:
            raise RuntimeError("数据库挂了")
        self.rows.extend(entries)
        return len(entries)


def make_settings() -> AppSettings:
    """数据库故意留空:这些用例全部注入假仓库,不碰真实的库。"""
    return AppSettings(
        log_level="INFO",
        mcp_host="127.0.0.1",
        mcp_port=53101,
        gateway_host="127.0.0.1",
        gateway_port=8100,
        console_password="123456",
        session_secret="s",
        database=DatabaseSettings(host="", port=3306, name="", user="", password=""),
    )


@pytest.fixture
def recorder_env(tmp_path, monkeypatch):
    """把 recorder 的模块常量换成单测友好的取值(落盘到 tmp、刷新间隔调短)。

    这些参数从环境变量改成了模块常量,所以单测靠 monkeypatch 改常量,
    而不是构造一份配置对象传进去。
    """
    fallback = tmp_path / "audit.jsonl"
    monkeypatch.setattr(recorder_module, "FALLBACK_PATH", str(fallback))
    monkeypatch.setattr(recorder_module, "FLUSH_INTERVAL", 0.05)
    monkeypatch.setattr(recorder_module, "BATCH_SIZE", 10)
    monkeypatch.setattr(recorder_module, "QUEUE_SIZE", 100)
    return fallback


async def test_recorder_writes_entries_to_repo(recorder_env):
    recorder = AuditRecorder(make_settings())
    repo = FakeRepo()
    recorder._repo = repo  # 注入假仓库,跳过真实数据库
    await recorder.start()

    recorder.submit(make_entry(tool_name="a"))
    recorder.submit(make_entry(tool_name="b"))
    await recorder.stop()

    assert {e.tool_name for e in repo.rows} == {"a", "b"}
    assert recorder.written == 2


async def test_recorder_falls_back_to_file_when_db_fails(recorder_env):
    """数据库挂了绝不能影响业务查询,审计降级写本地文件。"""
    recorder = AuditRecorder(make_settings())
    recorder._repo = FakeRepo(fail=True)
    await recorder.start()

    recorder.submit(make_entry(tool_name="degraded"))
    await recorder.stop()

    fallback = recorder_env
    assert fallback.exists()
    assert "degraded" in fallback.read_text(encoding="utf-8")
    assert recorder.fallback_written == 1


async def test_submit_never_raises_even_without_start(recorder_env):
    """审计的任何问题都不能把业务调用带崩。"""
    recorder = AuditRecorder(make_settings())
    recorder.submit(make_entry())  # 没 start,也不能抛


async def test_full_queue_drops_instead_of_blocking(recorder_env, monkeypatch):
    """宁可丢审计,也不能阻塞工具调用。"""
    monkeypatch.setattr(recorder_module, "QUEUE_SIZE", 2)
    recorder = AuditRecorder(make_settings())
    for _ in range(10):
        recorder.submit(make_entry())
    assert recorder.dropped == 8  # 队列只吃下 2 条


async def test_health_reports_counters(recorder_env):
    recorder = AuditRecorder(make_settings())
    health = recorder.health()
    assert set(health) >= {"db_ready", "queued", "written", "dropped"}


async def test_writer_survives_a_failing_batch_and_keeps_running(recorder_env):
    """后台任务不能因为一次异常就退出,否则后面所有审计都丢了。"""
    recorder = AuditRecorder(make_settings())
    repo = FakeRepo(fail=True)
    recorder._repo = repo
    await recorder.start()

    recorder.submit(make_entry(tool_name="first"))
    await asyncio.sleep(0.2)
    repo.fail = False
    recorder.submit(make_entry(tool_name="second"))
    await recorder.stop()

    assert [e.tool_name for e in repo.rows] == ["second"]
    assert recorder.fallback_written == 1


def test_caller_channel_values():
    assert CallerChannel.AGENT in CallerChannel.ALL
    assert CallerChannel.CONSOLE in CallerChannel.ALL