151 lines
7.0 KiB
Python
151 lines
7.0 KiB
Python
import asyncio
|
|
import importlib.util
|
|
import json
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
from relay.hainuo1065 import Hainuo1065Agent, NativeAPIError, read_native_config
|
|
from .conftest import provision
|
|
from .test_integration import dispatch
|
|
|
|
|
|
POLICY = {"mode": "text-only", "tools": "disabled", "contract": "hainuo-1065-v1"}
|
|
|
|
|
|
def config(tmp_path, url="http://127.0.0.1:8643"):
|
|
path = tmp_path / "native.json"
|
|
path.write_text(json.dumps({"url": url, "api_key": "fake-local-key-" * 4, "mode": "text-only"}))
|
|
return path
|
|
|
|
|
|
def native_handler(seen, *, policy=POLICY, completion=None):
|
|
def handler(request):
|
|
seen.append(request)
|
|
assert request.headers["Authorization"].startswith("Bearer fake-local-key-")
|
|
if request.url.path == "/health":
|
|
return httpx.Response(200, json={"status": "ok", "platform": "hermes-agent", "version": "package-fixture"})
|
|
if request.url.path == "/v1/capabilities":
|
|
return httpx.Response(200, json={"hainuo_relay_policy": policy})
|
|
if request.url.path == "/v1/models":
|
|
return httpx.Response(200, json={"data": [{"id": "hainuo-relay-text"}]})
|
|
assert request.url.path == "/v1/chat/completions"
|
|
return httpx.Response(200, json=completion or {"choices": [{"message": {"role": "assistant", "content": "真实API格式结果"}, "finish_reason": "stop"}]})
|
|
return handler
|
|
|
|
|
|
async def test_native_api_request_fields_idempotency_and_result(tmp_path):
|
|
seen = []
|
|
adapter = Hainuo1065Agent(config(tmp_path), transport=httpx.MockTransport(native_handler(seen)))
|
|
assert await adapter.execute("只回复联调通过", "ou_a", "turn_1") == "真实API格式结果"
|
|
post = seen[-1]
|
|
assert json.loads(post.content) == {"model": "hainuo-relay-text", "stream": False,
|
|
"messages": [{"role": "user", "content": "只回复联调通过"}]}
|
|
assert post.headers["Idempotency-Key"].startswith("hn-")
|
|
idem = post.headers["Idempotency-Key"]
|
|
await adapter.execute("只回复联调通过", "ou_a", "turn_1")
|
|
assert seen[-1].headers["Idempotency-Key"] == idem
|
|
await adapter.execute("只回复联调通过", "ou_b", "turn_1")
|
|
assert seen[-1].headers["Idempotency-Key"] != idem
|
|
await adapter.close()
|
|
|
|
|
|
async def test_refuses_stock_unrestricted_api(tmp_path):
|
|
seen = []
|
|
adapter = Hainuo1065Agent(config(tmp_path), transport=httpx.MockTransport(native_handler(seen, policy={})))
|
|
result = await adapter.execute("anything", "owner", "turn")
|
|
assert "policy missing" in result
|
|
assert all(request.method != "POST" for request in seen)
|
|
await adapter.close()
|
|
|
|
|
|
@pytest.mark.parametrize("completion", [
|
|
{"choices": []},
|
|
{"choices": [{"message": {"content": "partial"}, "finish_reason": "length"}]},
|
|
{"choices": [{"message": {"content": "tool", "tool_calls": [{"id": "x"}]}, "finish_reason": "stop"}]},
|
|
])
|
|
async def test_incomplete_native_results_fail_closed(tmp_path, completion):
|
|
adapter = Hainuo1065Agent(config(tmp_path), transport=httpx.MockTransport(native_handler([], completion=completion)))
|
|
assert "未完成请求" in await adapter.execute("anything", "owner", "turn")
|
|
await adapter.close()
|
|
|
|
|
|
async def test_native_redirect_no_retry_and_no_error_body_leak(tmp_path):
|
|
seen = []
|
|
def handler(request):
|
|
seen.append(request)
|
|
return httpx.Response(302, headers={"Location": "https://outside.invalid/"}, text="fake-confidential-body")
|
|
adapter = Hainuo1065Agent(config(tmp_path), transport=httpx.MockTransport(handler))
|
|
result = await adapter.execute("anything", "owner", "turn")
|
|
assert "fake-confidential" not in result and "HTTP 302" in result
|
|
assert len(seen) == 1
|
|
await adapter.close()
|
|
|
|
|
|
@pytest.mark.parametrize("url", ["http://example.invalid:8643", "http://localhost:8643", "https://127.0.0.1:8643", "http://127.0.0.1:8643/p/other", "http://user:pass@127.0.0.1:8643"])
|
|
def test_native_target_cannot_be_remote_or_profile_switched(tmp_path, url):
|
|
with pytest.raises(ValueError):
|
|
read_native_config(config(tmp_path, url))
|
|
|
|
|
|
def test_native_launcher_enforces_no_tools_and_endpoint_whitelist():
|
|
script = Path(__file__).resolve().parents[1] / "scripts/hainuo_native_api.py"
|
|
spec = importlib.util.spec_from_file_location("native_launcher_test", script)
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
class Native:
|
|
def _create_agent(self):
|
|
return SimpleNamespace(tools=[{"name": "terminal"}], valid_tool_names={"terminal"})
|
|
def _http_route_table(self):
|
|
return [("GET", "/health", None), ("POST", "/v1/chat/completions", None),
|
|
("DELETE", "/api/sessions/x", None), ("POST", "/api/jobs", None)]
|
|
tools = SimpleNamespace(_get_platform_tools=lambda config, platform, **kwargs: {"terminal"})
|
|
Restricted = module.restricted_adapter_class(Native, tools)
|
|
assert tools._get_platform_tools({}, "api_server") == set()
|
|
assert tools._get_platform_tools({}, "feishu") == {"terminal"}
|
|
assert len(Restricted()._http_route_table()) == 2
|
|
assert Restricted()._wire_plugin_handlers(object()) is None
|
|
with pytest.raises(RuntimeError, match="refuses an Agent with tools"):
|
|
Restricted()._create_agent()
|
|
|
|
|
|
async def test_encrypted_ecs_device_native_http_and_return(env):
|
|
"""Real socket chain; native API is a contract fixture, not installed Hermes."""
|
|
from fastapi import FastAPI, Request
|
|
from .conftest import serve
|
|
from relay.device import run_device
|
|
app = FastAPI()
|
|
seen = []
|
|
@app.get("/health")
|
|
async def health():
|
|
return {"status": "ok", "platform": "hermes-agent", "version": "contract-fixture"}
|
|
@app.get("/v1/capabilities")
|
|
async def capabilities():
|
|
return {"hainuo_relay_policy": POLICY}
|
|
@app.get("/v1/models")
|
|
async def models():
|
|
return {"data": [{"id": "hainuo-relay-text"}]}
|
|
@app.post("/v1/chat/completions")
|
|
async def chat(request: Request):
|
|
seen.append(await request.json())
|
|
assert request.headers.get("Idempotency-Key")
|
|
return {"choices": [{"message": {"content": "本机API对接成功"}, "finish_reason": "stop"}]}
|
|
server, server_task, port = await serve(app)
|
|
directory, _ = await provision(env)
|
|
cfg = config(env["root"], f"http://127.0.0.1:{port}")
|
|
connected = asyncio.Event()
|
|
device = asyncio.create_task(run_device(directory, env["router_url"], connected_event=connected, hainuo_config=cfg))
|
|
env["tasks"].append(device)
|
|
try:
|
|
await asyncio.wait_for(connected.wait(), 5)
|
|
response = await dispatch(env, "ou_test", "/助手 只回复本机API对接成功", "native-turn")
|
|
assert response.json()["result"] == "本机API对接成功"
|
|
assert seen[0]["messages"][0]["content"] == "只回复本机API对接成功"
|
|
assert (await dispatch(env, "ou_test", "/助手 repeat", "native-turn")).json()["status"] == "duplicate"
|
|
assert len(seen) == 1
|
|
finally:
|
|
server.should_exit = True
|
|
await asyncio.wait_for(server_task, 5)
|