test_http_client.py 7.39 KB
"""签名 HTTP 客户端的行为。

重点覆盖一个真实缺陷:上游返回 HTTP 200 但 body 里带 error_code 时,
只看状态码会把错误响应当成正常数据透传给大模型。
"""

from __future__ import annotations

import httpx
import pytest
import respx

from mcp_hive.core.errors import (
    BackendApiError,
    BackendTimeoutError,
    BackendTransportError,
    ConfigError,
)
from mcp_hive.core.http import client as client_module
from mcp_hive.core.http.client import SignedApiClient

BASE = "http://upstream.test/facade"
PATH = "/mcp/shelf/list"


@pytest.fixture
async def client(fake_credentials):
    c = SignedApiClient("used_car")
    await c.start()
    yield c
    await c.aclose()


@pytest.fixture(autouse=True)
def _no_retry_backoff(monkeypatch):
    """单测里不要真的退避等待。"""
    monkeypatch.setattr(client_module, "RETRY_BACKOFF", 0.0)


async def test_successful_call_returns_payload(client):
    with respx.mock(base_url=BASE) as mock:
        mock.post(PATH).mock(
            return_value=httpx.Response(200, json={"data": [{"a": 1}], "schema": []})
        )
        result = await client.call(PATH, {"storeName": "A"})
    assert result == {"data": [{"a": 1}], "schema": []}


async def test_both_layers_of_auth_headers_are_attached(client):
    """上游要两层签名,少任何一层请求都会被挡在验签之前。"""
    with respx.mock(base_url=BASE) as mock:
        route = mock.post(PATH).mock(return_value=httpx.Response(200, json={"data": []}))
        await client.call(PATH, {"storeName": "A"})

    headers = route.calls[0].request.headers
    assert headers["appKey"] == "test-app-key"
    assert len(headers["sign"]) == 40
    assert headers["timestamp"].isdigit()
    assert headers["x-app-id"] == "test-gw-app"
    assert len(headers["x-sign"]) == 64
    assert headers["x-nonce"].isdigit()
    assert headers["x-timestamp"] == headers["timestamp"]
    assert "application/json" in headers["content-type"]


async def test_http_200_with_error_code_is_still_an_error(client):
    """关键回归:旧实现只在非 200 时抛错,这种响应会被当成数据交给大模型。"""
    with respx.mock(base_url=BASE) as mock:
        mock.post(PATH).mock(
            return_value=httpx.Response(
                200, json={"error_code": "STORE_NOT_FOUND", "message": "门店未上架"}
            )
        )
        with pytest.raises(BackendApiError) as exc:
            await client.call(PATH, {"storeName": "不存在"})

    assert exc.value.error_code == "STORE_NOT_FOUND"
    assert exc.value.message == "门店未上架"
    assert exc.value.audit_status == "backend_error"


async def test_non_200_raises_backend_api_error(client):
    with respx.mock(base_url=BASE) as mock:
        mock.post(PATH).mock(
            return_value=httpx.Response(400, json={"error_code": "INVALID_PARAM", "message": "参数错误"})
        )
        with pytest.raises(BackendApiError) as exc:
            await client.call(PATH, {})

    assert exc.value.error_code == "INVALID_PARAM"
    assert exc.value.http_status == 400  # 4xx 是调用方问题,不该报成 502


async def test_upstream_5xx_maps_to_bad_gateway(client):
    with respx.mock(base_url=BASE) as mock:
        mock.post(PATH).mock(
            return_value=httpx.Response(500, json={"error_code": "INTERNAL_ERROR", "message": "boom"})
        )
        with pytest.raises(BackendApiError) as exc:
            await client.call(PATH, {})
    assert exc.value.http_status == 502


async def test_non_json_response_includes_body_snippet(client):
    """联调阻塞时上游返回的就是 text/plain「缺少必要参数」,
    错误信息必须把这段原文带出来,否则根本没法定位。"""
    with respx.mock(base_url=BASE) as mock:
        mock.post(PATH).mock(return_value=httpx.Response(400, text="缺少必要参数"))
        with pytest.raises(BackendTransportError) as exc:
            await client.call(PATH, {})
    assert "缺少必要参数" in str(exc.value)
    assert "400" in str(exc.value)


async def test_timeout_maps_to_timeout_error(client):
    with respx.mock(base_url=BASE) as mock:
        mock.post(PATH).mock(side_effect=httpx.ConnectTimeout("too slow"))
        with pytest.raises(BackendTimeoutError) as exc:
            await client.call(PATH, {})
    assert exc.value.audit_status == "timeout"
    assert exc.value.http_status == 504


async def test_connection_error_maps_to_transport_error(client):
    with respx.mock(base_url=BASE) as mock:
        mock.post(PATH).mock(side_effect=httpx.ConnectError("refused"))
        with pytest.raises(BackendTransportError):
            await client.call(PATH, {})


async def test_transport_error_never_leaks_the_secret(client):
    """错误信息会进日志和审计,两层的密钥都绝不能带上。"""
    with respx.mock(base_url=BASE) as mock:
        mock.post(PATH).mock(side_effect=httpx.ConnectError("refused"))
        with pytest.raises(BackendTransportError) as exc:
            await client.call(PATH, {"storeName": "A"})
    assert "test-secret" not in str(exc.value)
    assert "test-gw-secret" not in str(exc.value)


async def test_calling_before_start_raises_config_error(fake_credentials):
    """没 start 就调用,抛的是统一异常体系里的 ConfigError,不是裸 RuntimeError。"""
    c = SignedApiClient("used_car")
    with pytest.raises(ConfigError):
        await c.call(PATH, {})


async def test_retries_on_502_then_succeeds(client):
    with respx.mock(base_url=BASE) as mock:
        route = mock.post(PATH)
        route.side_effect = [
            httpx.Response(502, json={}),
            httpx.Response(200, json={"data": []}),
        ]
        result = await client.call(PATH, {})
    assert result == {"data": []}
    assert route.call_count == 2


async def test_does_not_retry_on_4xx(client):
    """4xx 是调用方的问题,重试只会白白放大上游压力。"""
    with respx.mock(base_url=BASE) as mock:
        route = mock.post(PATH).mock(
            return_value=httpx.Response(400, json={"error_code": "INVALID_PARAM", "message": "x"})
        )
        with pytest.raises(BackendApiError):
            await client.call(PATH, {})
    assert route.call_count == 1


async def test_exhausted_retries_still_report_the_real_upstream_status(client):
    """连续 502 时,最后一次的真实状态码必须能进到异常里(审计要记 upstream_status)。"""
    with respx.mock(base_url=BASE) as mock:
        mock.post(PATH).mock(return_value=httpx.Response(503, json={"message": "上游挂了"}))
        with pytest.raises(BackendApiError) as exc:
            await client.call(PATH, {})
    assert exc.value.status_code == 503


async def test_base_url_comes_from_credentials_at_call_time(client, monkeypatch):
    """凭证改了之后不用重启:下一次调用就打到新地址。"""
    from mcp_hive.core.config.settings import BackendCredentials

    moved = BackendCredentials(
        base_url="http://moved.test/facade",
        app_key="k2",
        secret="s2",
        gw_app_id="gw2",
        gw_secret="gs2",
    )

    async def _fake(_key):
        return moved

    monkeypatch.setattr(client_module, "get_credentials", _fake)

    with respx.mock(base_url="http://moved.test/facade") as mock:
        route = mock.post(PATH).mock(return_value=httpx.Response(200, json={"data": []}))
        await client.call(PATH, {})
    assert route.call_count == 1
    assert route.calls[0].request.headers["appKey"] == "k2"