Import ECS deployed relay source and historical patches (2026-10-27)
This commit is contained in:
@@ -0,0 +1,116 @@
|
||||
import asyncio
|
||||
import contextlib
|
||||
import json
|
||||
import socket
|
||||
|
||||
import fakeredis.aioredis
|
||||
import httpx
|
||||
import pytest_asyncio
|
||||
import uvicorn
|
||||
|
||||
from relay.cli import device_request, init_project, issue
|
||||
from relay.config import Settings
|
||||
from relay.connector import create_app as connector_app
|
||||
from relay.router import create_app as router_app
|
||||
|
||||
|
||||
class PlatformStub:
|
||||
def __init__(self):
|
||||
self.replies = []
|
||||
self.exchanges = 0
|
||||
self.refreshes = 0
|
||||
|
||||
async def exchange(self, code):
|
||||
self.exchanges += 1
|
||||
await asyncio.sleep(0.01)
|
||||
return {"user_access_token": "fake-user-token", "refresh_token": "fake-refresh-token",
|
||||
"expires_in": 6900, "refresh_expires_in": 2592000, "open_id": "ou_test"}
|
||||
|
||||
async def refresh(self, token):
|
||||
self.refreshes += 1
|
||||
await asyncio.sleep(0.01)
|
||||
return {"user_access_token": "new-fake-token", "refresh_token": "rotated-fake-token",
|
||||
"expires_in": 7200, "open_id": "ou_test"}
|
||||
|
||||
async def user_info(self, token):
|
||||
return {"open_id": "ou_test"}
|
||||
|
||||
async def reply(self, message, text):
|
||||
self.replies.append((message, text))
|
||||
|
||||
async def close(self):
|
||||
pass
|
||||
|
||||
|
||||
async def serve(app):
|
||||
sock = socket.socket()
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
sock.listen(128)
|
||||
port = sock.getsockname()[1]
|
||||
server = uvicorn.Server(uvicorn.Config(app, log_level="critical", access_log=False, lifespan="on"))
|
||||
task = asyncio.create_task(server.serve(sockets=[sock]))
|
||||
for _ in range(200):
|
||||
if server.started:
|
||||
return server, task, port
|
||||
if task.done():
|
||||
task.result()
|
||||
raise RuntimeError("server failed")
|
||||
await asyncio.sleep(0.01)
|
||||
raise RuntimeError("server startup timeout")
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def env(tmp_path):
|
||||
init_project(tmp_path, "localhost")
|
||||
settings = Settings(environment="test", admin_secret="a" * 40, internal_secret="b" * 40,
|
||||
data_dir=tmp_path / "runtime/connector", ca_cert=tmp_path / "runtime/trust/ca.pem",
|
||||
connector_key=tmp_path / "runtime/connector/connector.key",
|
||||
connector_public_key=tmp_path / "runtime/trust/connector.pub",
|
||||
feishu_enabled=True, feishu_app_id="cli_test", feishu_app_secret="fake-app-secret",
|
||||
feishu_encrypt_key="fake-encrypt-key", feishu_verification_token="fake-verification",
|
||||
public_url="http://localhost", router_url="ws://localhost/device/ws", request_timeout=2)
|
||||
redis = fakeredis.aioredis.FakeRedis(decode_responses=True)
|
||||
platform = PlatformStub()
|
||||
connector = connector_app(settings, redis=redis, platform=platform)
|
||||
router = router_app(settings, redis=redis)
|
||||
cs, ct, cp = await serve(connector)
|
||||
rs, rt, rp = await serve(router)
|
||||
client = httpx.AsyncClient(base_url=f"http://127.0.0.1:{cp}", timeout=10)
|
||||
state = {"settings": settings, "redis": redis, "platform": platform, "connector": connector,
|
||||
"router": router, "client": client, "root": tmp_path,
|
||||
"connector_url": f"http://127.0.0.1:{cp}", "router_url": f"ws://127.0.0.1:{rp}/device/ws",
|
||||
"admin": {"X-Admin-Secret": settings.admin_secret}, "tasks": []}
|
||||
yield state
|
||||
for task in state["tasks"]:
|
||||
task.cancel()
|
||||
await asyncio.gather(*state["tasks"], return_exceptions=True)
|
||||
await client.aclose()
|
||||
cs.should_exit = rs.should_exit = True
|
||||
await asyncio.wait_for(asyncio.gather(ct, rt), timeout=10)
|
||||
await redis.aclose()
|
||||
|
||||
|
||||
async def provision(env, owner="ou_test"):
|
||||
directory = env["root"] / owner
|
||||
device_request(directory)
|
||||
output = env["root"] / (owner + "-issued")
|
||||
issue(env["root"], directory / "request.json", output)
|
||||
for name in ["device.pem", "ca.pem", "connector.pub", "device.json"]:
|
||||
(directory / name).write_bytes((output / name).read_bytes())
|
||||
registration = json.loads((output / "registration.json").read_text())
|
||||
response = await env["client"].post("/admin/devices", json=registration, headers=env["admin"])
|
||||
assert response.status_code == 201, response.text
|
||||
response = await env["client"].post("/admin/test/binding-code", json={"open_id": owner, "text": "ignored"}, headers=env["admin"])
|
||||
code = response.json()["message"].split(":")[-1]
|
||||
from relay.device import bind_device
|
||||
await bind_device(directory, env["connector_url"], code)
|
||||
return directory, registration["host_id"]
|
||||
|
||||
|
||||
async def connect_device(env, directory, root=None):
|
||||
from relay.device import run_device
|
||||
connected = asyncio.Event()
|
||||
task = asyncio.create_task(run_device(directory, env["router_url"], root=root, connected_event=connected))
|
||||
env["tasks"].append(task)
|
||||
await asyncio.wait_for(connected.wait(), 5)
|
||||
return task
|
||||
@@ -0,0 +1,24 @@
|
||||
import json
|
||||
import httpx
|
||||
import pytest
|
||||
from relay.device import LocalAgent
|
||||
|
||||
|
||||
async def test_local_agent_contract_and_no_redirect():
|
||||
requests = []
|
||||
def handler(request):
|
||||
requests.append(json.loads(request.content))
|
||||
return httpx.Response(200, json={"result": "本机助手结果"})
|
||||
agent = LocalAgent("http://127.0.0.1:8765/relay/read-only", transport=httpx.MockTransport(handler))
|
||||
assert await agent.execute("整理测试文件", "ou_test", "turn") == "本机助手结果"
|
||||
assert requests[0] == {"text": "整理测试文件", "open_id": "ou_test", "turn_id": "turn", "channel": "im", "read_only": True}
|
||||
await agent.close()
|
||||
agent = LocalAgent("http://127.0.0.1:8765/relay/read-only", transport=httpx.MockTransport(
|
||||
lambda request: httpx.Response(302, headers={"Location": "https://evil.invalid"})))
|
||||
assert "未返回成功" in await agent.execute("text", "owner", "turn")
|
||||
await agent.close()
|
||||
|
||||
|
||||
def test_agent_rejects_nonlocal_endpoint():
|
||||
with pytest.raises(ValueError):
|
||||
LocalAgent("https://external.example.invalid/run")
|
||||
@@ -0,0 +1,141 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives import padding
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
from websockets.asyncio.client import connect
|
||||
|
||||
from relay.crypto import load_private, sign
|
||||
from relay.device import DeviceJournal
|
||||
from relay.config import Settings
|
||||
from .conftest import provision, connect_device
|
||||
from .test_integration import dispatch, event
|
||||
|
||||
|
||||
async def test_expired_and_capacity_oauth(env):
|
||||
client = env["client"]
|
||||
data = (await client.post("/oauth/start", json={})).json()
|
||||
env["connector"].state.oauth.pending[data["state"]].expires = time.monotonic() - 1
|
||||
assert (await client.get("/oauth/cb", params={"state": data["state"], "code": "x"})).status_code == 400
|
||||
env["settings"].max_pending = 1
|
||||
assert (await client.post("/oauth/start", json={})).status_code == 201
|
||||
assert (await client.post("/oauth/start", json={})).status_code == 503
|
||||
|
||||
|
||||
async def test_binding_wrong_signature_does_not_consume(env):
|
||||
# Provision one device but remove initial binding to exercise a second code.
|
||||
directory, host = await provision(env)
|
||||
env["connector"].state.store.unbind("ou_test")
|
||||
response = await env["client"].post("/admin/test/binding-code", headers=env["admin"],
|
||||
json={"open_id": "ou_test", "text": "ignored"})
|
||||
code = response.json()["message"].split(":")[-1]
|
||||
proof = sign({"host_id": host, "code": code, "ts": int(time.time())}, load_private(directory / "device.key"))
|
||||
damaged = {**proof, "signature": "AAAA"}
|
||||
assert (await env["client"].post("/device/bind", json={"host_id": host, "proof": damaged})).status_code == 403
|
||||
assert (await env["client"].post("/device/bind", json={"host_id": host, "proof": proof})).status_code == 200
|
||||
assert (await env["client"].post("/device/bind", json={"host_id": host, "proof": proof})).status_code == 404
|
||||
|
||||
|
||||
async def test_timeout_is_unknown_and_cannot_reexecute(env):
|
||||
directory, host = await provision(env)
|
||||
# A live session is required: pause reply processing to reproduce an ambiguous result.
|
||||
await connect_device(env, directory)
|
||||
env["connector"].state.reply_task.cancel()
|
||||
await asyncio.sleep(0)
|
||||
result = await dispatch(env, "ou_test", "/回显 delayed", "timeout-turn")
|
||||
assert result.json()["status"] == "unknown"
|
||||
assert (await dispatch(env, "ou_test", "/回显 retried", "timeout-turn")).json()["status"] == "duplicate"
|
||||
assert (await env["client"].get("/ready")).status_code == 503
|
||||
|
||||
|
||||
async def test_duplicate_device_connection_rejected(env):
|
||||
from relay.crypto import raw_public
|
||||
from cryptography.hazmat.primitives.asymmetric import x25519
|
||||
directory, host = await provision(env)
|
||||
await connect_device(env, directory)
|
||||
async with connect(env["router_url"], proxy=None) as ws:
|
||||
challenge = json.loads(await ws.recv())["challenge"]
|
||||
proof = sign({"host_id": host, "session_id": secrets.token_hex(16), "challenge": challenge,
|
||||
"kx": raw_public(x25519.X25519PrivateKey.generate().public_key()), "ts": int(time.time())},
|
||||
load_private(directory / "device.key"))
|
||||
await ws.send(json.dumps({"host_id": host, "cert": (directory / "device.pem").read_text(), "proof": proof}))
|
||||
from websockets.exceptions import ConnectionClosed
|
||||
with pytest.raises(ConnectionClosed):
|
||||
await ws.recv()
|
||||
assert (await dispatch(env, "ou_test", "/回显 original")).json()["result"] == "original"
|
||||
|
||||
|
||||
async def test_encrypted_webhook_and_stale_signature(env):
|
||||
directory, _ = await provision(env)
|
||||
await connect_device(env, directory)
|
||||
s = env["settings"]
|
||||
raw_event = json.dumps(event(env, "om_encrypted"), ensure_ascii=False).encode()
|
||||
pad = padding.PKCS7(128).padder()
|
||||
padded = pad.update(raw_event) + pad.finalize()
|
||||
iv = secrets.token_bytes(16)
|
||||
enc = Cipher(algorithms.AES(hashlib.sha256(s.feishu_encrypt_key.encode()).digest()), modes.CBC(iv)).encryptor()
|
||||
import base64
|
||||
raw = json.dumps({"encrypt": base64.b64encode(iv + enc.update(padded) + enc.finalize()).decode()}).encode()
|
||||
timestamp, nonce = str(int(time.time())), "encrypted-nonce"
|
||||
headers = {"X-Lark-Request-Timestamp": timestamp, "X-Lark-Request-Nonce": nonce,
|
||||
"X-Lark-Signature": hashlib.sha256((timestamp + nonce + s.feishu_encrypt_key).encode() + raw).hexdigest()}
|
||||
assert (await env["client"].post("/feishu/event", content=raw, headers=headers)).status_code == 200
|
||||
for _ in range(100):
|
||||
if env["platform"].replies:
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
assert env["platform"].replies == [("om_encrypted", "平台事件")]
|
||||
headers["X-Lark-Request-Timestamp"] = str(int(time.time()) - 600)
|
||||
assert (await env["client"].post("/feishu/event", content=raw, headers=headers)).status_code == 403
|
||||
|
||||
|
||||
async def test_h5_and_whoami_only_returns_owned_static_domain(env):
|
||||
await provision(env)
|
||||
env["settings"].device_domain = "pc.example.invalid"
|
||||
response = await env["client"].get("/h5")
|
||||
assert response.status_code == 200
|
||||
assert "script-src 'self'" in response.headers["content-security-policy"]
|
||||
assert (await env["client"].get("/assets/app.js")).status_code == 200
|
||||
assert (await env["client"].get("/api/whoami")).status_code == 401
|
||||
response = await env["client"].get("/api/whoami?target=https://evil.invalid", headers={"Authorization": "Bearer fake-user"})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["url"].endswith(".pc.example.invalid/")
|
||||
assert response.json()["device_login_required"] is True
|
||||
|
||||
|
||||
async def test_proxy_blocks_auth_endpoints_absolute_urls_and_traversal(env):
|
||||
env["settings"].proxy_enabled = True
|
||||
for target in ["https://evil.invalid/", "//evil.invalid/", "/open-apis/auth/v3/tenant_access_token/internal",
|
||||
"/open-apis/authen/v1/user_info", "/open-apis/drive/v1/files/%2e%2e/auth", "/open-apis/drive/v1/files%0d%0aX:evil"]:
|
||||
result = await env["client"].get("/proxy", headers={"Authorization": "Bearer fake-user", "X-Relay-Target": target})
|
||||
assert result.status_code == 403, target
|
||||
|
||||
|
||||
def test_device_journal_survives_restart(tmp_path):
|
||||
path = tmp_path / "journal.sqlite"
|
||||
journal = DeviceJournal(path)
|
||||
assert journal.consume("turn")
|
||||
journal.close()
|
||||
journal = DeviceJournal(path)
|
||||
assert not journal.consume("turn")
|
||||
journal.close()
|
||||
|
||||
|
||||
def test_production_fails_closed():
|
||||
with pytest.raises(ValueError):
|
||||
Settings(environment="production", admin_secret="short", internal_secret="short")
|
||||
with pytest.raises(ValueError):
|
||||
Settings(environment="production", admin_secret="a" * 40, internal_secret="b" * 40,
|
||||
public_url="http://localhost")
|
||||
|
||||
|
||||
async def test_validation_errors_do_not_echo_tokens(env):
|
||||
token = "fake-confidential-token-" * 300
|
||||
response = await env["client"].post("/oauth/refresh", json={"refresh_token": token})
|
||||
assert response.status_code == 422
|
||||
assert "fake-confidential" not in response.text
|
||||
assert response.json() == {"detail": "invalid request parameters"}
|
||||
@@ -0,0 +1,38 @@
|
||||
import copy
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from cryptography.exceptions import InvalidSignature, InvalidTag
|
||||
from cryptography.hazmat.primitives.asymmetric import ed25519, x25519
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from relay.crypto import (issue_ca, issue_device, raw_public, seal, open_envelope, verify_device)
|
||||
|
||||
|
||||
def test_encrypted_and_authenticated():
|
||||
signer = ed25519.Ed25519PrivateKey.generate()
|
||||
recipient = x25519.X25519PrivateKey.generate()
|
||||
envelope = seal({"text": "秘密合同"}, raw_public(recipient.public_key()), signer, host_id="host", session_id="session")
|
||||
assert "秘密" not in str(envelope)
|
||||
assert open_envelope(envelope, recipient, signer.public_key(), host_id="host", session_id="session")["text"] == "秘密合同"
|
||||
damaged = copy.deepcopy(envelope)
|
||||
damaged["ciphertext"] = damaged["ciphertext"][:-4] + "AAAA"
|
||||
with pytest.raises(InvalidSignature):
|
||||
open_envelope(damaged, recipient, signer.public_key(), host_id="host", session_id="session")
|
||||
with pytest.raises(ValueError):
|
||||
open_envelope(envelope, recipient, signer.public_key(), host_id="other", session_id="session")
|
||||
# Long-term signing key alone cannot recover a recorded session's data.
|
||||
with pytest.raises(InvalidTag):
|
||||
open_envelope(envelope, x25519.X25519PrivateKey.generate(), signer.public_key(), host_id="host", session_id="session")
|
||||
|
||||
|
||||
def test_certificate_identity_and_trust():
|
||||
ca_key, ca = issue_ca()
|
||||
device = ed25519.Ed25519PrivateKey.generate()
|
||||
pem = issue_device(ca_key, ca, "a" * 32, device.public_key()).public_bytes(serialization.Encoding.PEM).decode()
|
||||
ca_pem = ca.public_bytes(serialization.Encoding.PEM)
|
||||
verify_device(pem, ca_pem, "a" * 32)
|
||||
with pytest.raises(ValueError):
|
||||
verify_device(pem, ca_pem, "b" * 32)
|
||||
_, other_ca = issue_ca()
|
||||
with pytest.raises((ValueError, InvalidSignature)):
|
||||
verify_device(pem, other_ca.public_bytes(serialization.Encoding.PEM), "a" * 32)
|
||||
@@ -0,0 +1,85 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from relay.config import Settings
|
||||
from .conftest import provision
|
||||
|
||||
|
||||
def setup_module_source():
|
||||
path = Path(__file__).resolve().parents[1] / "scripts/configure_feishu_longconn.py"
|
||||
spec = importlib.util.spec_from_file_location("feishu_setup_test", path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_longconn_does_not_require_webhook_secrets():
|
||||
settings = Settings(environment="test", admin_secret="a" * 40, internal_secret="b" * 40,
|
||||
feishu_enabled=True, feishu_app_id="cli_test", feishu_app_secret="fake-secret")
|
||||
assert settings.feishu_event_source == "longconn"
|
||||
with pytest.raises(ValueError):
|
||||
Settings(environment="test", admin_secret="a" * 40, internal_secret="b" * 40,
|
||||
feishu_enabled=True, feishu_app_id="cli_test", feishu_app_secret="fake-secret", feishu_event_source="webhook")
|
||||
|
||||
|
||||
def test_setup_checks_private_origin_and_never_returns_tokens():
|
||||
module = setup_module_source()
|
||||
seen = []
|
||||
def handler(request):
|
||||
seen.append(request)
|
||||
assert request.url.host == "open.w.cnooc.com.cn"
|
||||
if request.url.path.endswith("app_access_token/internal"):
|
||||
return httpx.Response(200, json={"code": 0, "app_access_token": "fake-sensitive-app-token"})
|
||||
if request.url.path.endswith("tenant_access_token/internal"):
|
||||
return httpx.Response(200, json={"code": 0, "tenant_access_token": "fake-sensitive-tenant-token"})
|
||||
return httpx.Response(200, json={"code": 0, "data": {"URL": "wss://ws.private.invalid/path?ticket=fake-sensitive-ticket"}})
|
||||
with httpx.Client(transport=httpx.MockTransport(handler), follow_redirects=False) as client:
|
||||
result = module.check_platform("https://open.w.cnooc.com.cn", "cli_test", "fake-secret", client)
|
||||
assert len(seen) == 3
|
||||
assert "fake-sensitive" not in str(result)
|
||||
assert "ws.private.invalid" in str(result)
|
||||
|
||||
|
||||
def test_setup_refuses_redirect_and_suppresses_response_body():
|
||||
module = setup_module_source()
|
||||
with httpx.Client(transport=httpx.MockTransport(lambda request: httpx.Response(302, headers={"Location": "https://evil.invalid"}, text="fake-secret")), follow_redirects=False) as client:
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
module.check_platform("https://open.w.cnooc.com.cn", "cli_test", "fake-secret", client)
|
||||
assert "302" in str(error.value) and "fake-secret" not in str(error.value)
|
||||
|
||||
|
||||
def test_env_update_preserves_other_settings_and_backs_up(tmp_path):
|
||||
module = setup_module_source()
|
||||
path = tmp_path / ".env"
|
||||
path.write_text("# existing\nHN_ADMIN_SECRET=fake-admin\nHN_FEISHU_ENABLED=false\nHN_FEISHU_ENABLED=false\nHN_PUBLIC_URL=https://10.77.76.13\n")
|
||||
module.update_env(path, {"HN_FEISHU_ENABLED": "true", "HN_FEISHU_APP_SECRET": "fake-platform-secret", "HN_OAUTH_ENABLED": "false"})
|
||||
value = path.read_text()
|
||||
assert "HN_ADMIN_SECRET=fake-admin" in value and "HN_PUBLIC_URL=https://10.77.76.13" in value
|
||||
assert value.count("HN_FEISHU_ENABLED=") == 1
|
||||
assert "HN_FEISHU_APP_SECRET=fake-platform-secret" in value
|
||||
assert len(list(tmp_path.glob(".env.before-feishu-*"))) == 1
|
||||
|
||||
|
||||
async def test_admin_can_unbind_test_identity_without_revoking_device(env):
|
||||
directory, host = await provision(env)
|
||||
result = await env["client"].post(f"/admin/devices/{host}/unbind", headers=env["admin"])
|
||||
assert result.status_code == 200
|
||||
device = env["connector"].state.store.device(host)
|
||||
assert device["owner"] is None and device["revoked"] == 0
|
||||
assert await env["redis"].get("hn:web-generation:" + host) == "2"
|
||||
from relay.device import bind_device
|
||||
code_result = await env["client"].post("/admin/test/binding-code", headers=env["admin"], json={"open_id": "ou_real", "text": "ignored"})
|
||||
code = code_result.json()["message"].split(":")[-1]
|
||||
await bind_device(directory, env["connector_url"], code)
|
||||
assert env["connector"].state.store.device(host)["owner"] == "ou_real"
|
||||
|
||||
|
||||
async def test_unconfigured_webhook_and_unverified_oauth_are_closed(env):
|
||||
env["settings"].feishu_encrypt_key = ""
|
||||
env["settings"].feishu_verification_token = ""
|
||||
env["settings"].oauth_enabled = False
|
||||
assert (await env["client"].post("/feishu/event", json={})).status_code == 503
|
||||
assert (await env["client"].post("/oauth/start", json={})).status_code == 503
|
||||
@@ -0,0 +1,150 @@
|
||||
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)
|
||||
@@ -0,0 +1,38 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import tarfile
|
||||
|
||||
from scripts.fetch_official_images import export_image, digest_file
|
||||
|
||||
|
||||
def test_offline_docker_archive_preserves_config_and_rootfs(tmp_path):
|
||||
cache, output = tmp_path / "cache", tmp_path / "out"
|
||||
cache.mkdir()
|
||||
output.mkdir()
|
||||
layer = io.BytesIO()
|
||||
with tarfile.open(fileobj=layer, mode="w") as tar:
|
||||
content = b"hello ARM64\n"
|
||||
info = tarfile.TarInfo("test.txt")
|
||||
info.size, info.mode = len(content), 0o644
|
||||
tar.addfile(info, io.BytesIO(content))
|
||||
raw = layer.getvalue()
|
||||
raw_digest = hashlib.sha256(raw).hexdigest()
|
||||
import gzip
|
||||
compressed = gzip.compress(raw)
|
||||
blob_digest = hashlib.sha256(compressed).hexdigest()
|
||||
(cache / (blob_digest + ".blob")).write_bytes(compressed)
|
||||
config = json.dumps({"architecture": "arm64", "os": "linux", "config": {"Env": []},
|
||||
"rootfs": {"type": "layers", "diff_ids": ["sha256:" + raw_digest]}}).encode()
|
||||
config_digest = hashlib.sha256(config).hexdigest()
|
||||
(cache / (config_digest + ".blob")).write_bytes(config)
|
||||
record = {"name": "test", "tag": "arm64", "config": {"digest": "sha256:" + config_digest},
|
||||
"layers": [{"digest": "sha256:" + blob_digest}]}
|
||||
export_image(record, cache, output)
|
||||
path = output / record["archive"]
|
||||
assert record["archive_sha256"] == digest_file(path)
|
||||
with tarfile.open(path) as tar:
|
||||
manifest = json.load(tar.extractfile("manifest.json"))[0]
|
||||
assert manifest["RepoTags"] == ["test:arm64"]
|
||||
assert tar.extractfile(manifest["Config"]).read() == config
|
||||
assert tar.extractfile(manifest["Layers"][0]).read() == raw
|
||||
@@ -0,0 +1,143 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from relay.crypto import load_private, sign
|
||||
from .conftest import provision, connect_device
|
||||
|
||||
|
||||
async def dispatch(env, owner, text, turn=None):
|
||||
return await env["client"].post("/admin/test/dispatch", headers=env["admin"],
|
||||
json={"open_id": owner, "text": text, "turn_id": turn or uuid.uuid4().hex})
|
||||
|
||||
|
||||
async def test_two_devices_encrypted_isolation_and_dedup(env):
|
||||
a, ah = await provision(env, "ou_a")
|
||||
b, bh = await provision(env, "ou_b")
|
||||
await connect_device(env, a)
|
||||
await connect_device(env, b)
|
||||
responses = await asyncio.gather(dispatch(env, "ou_a", "/回显 A的唯一结果"), dispatch(env, "ou_b", "/回显 B的唯一结果"))
|
||||
assert [x.json()["result"] for x in responses] == ["A的唯一结果", "B的唯一结果"]
|
||||
first = await dispatch(env, "ou_a", "/回显 once", "same-turn")
|
||||
again = await dispatch(env, "ou_a", "/回显 twice", "same-turn")
|
||||
assert first.json()["status"] == "completed"
|
||||
assert again.json()["status"] == "duplicate"
|
||||
# Directory compromise cannot silently substitute B's certificate for A.
|
||||
presence_b = await env["redis"].get("hn:online:" + bh)
|
||||
await env["redis"].set("hn:online:" + ah, presence_b)
|
||||
assert (await dispatch(env, "ou_a", "/回显 leaked")).status_code == 409
|
||||
|
||||
|
||||
async def test_offline_revoke_and_persistence(env):
|
||||
directory, host = await provision(env)
|
||||
assert (await dispatch(env, "ou_test", "/主机名")).json()["status"] == "offline"
|
||||
await connect_device(env, directory)
|
||||
assert (await dispatch(env, "ou_test", "/主机名")).json()["status"] == "completed"
|
||||
result = await env["client"].post(f"/admin/devices/{host}/revoke", headers=env["admin"])
|
||||
assert result.status_code == 200
|
||||
assert (await dispatch(env, "ou_test", "/主机名")).json()["status"] == "unavailable"
|
||||
await asyncio.sleep(0.05)
|
||||
assert not await env["redis"].exists("hn:online:" + host)
|
||||
from relay.store import Store
|
||||
db = Store(env["settings"].data_dir / "metadata.sqlite")
|
||||
assert db.device(host)["revoked"] == 1
|
||||
db.close()
|
||||
|
||||
|
||||
async def test_device_read_boundary(env):
|
||||
directory, host = await provision(env)
|
||||
root = env["root"] / "test-files"
|
||||
root.mkdir()
|
||||
(root / "allowed.txt").write_text("授权内容", encoding="utf-8")
|
||||
(env["root"] / "outside.txt").write_text("不该读到", encoding="utf-8")
|
||||
await connect_device(env, directory, root)
|
||||
assert (await dispatch(env, "ou_test", "/读取 allowed.txt")).json()["result"] == "授权内容"
|
||||
assert "拒绝" in (await dispatch(env, "ou_test", "/读取 ../outside.txt")).json()["result"]
|
||||
assert "只读诊断" in (await dispatch(env, "ou_test", "rm -rf /")).json()["result"]
|
||||
|
||||
|
||||
async def test_binding_requires_device_proof_and_one_time_code(env):
|
||||
directory, host = await provision(env)
|
||||
response = await env["client"].post("/device/bind", json={"host_id": host, "proof": {}})
|
||||
assert response.status_code == 403
|
||||
response = await env["client"].post("/admin/devices", json={"host_id": host, "cert": "invalid"})
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
async def test_oauth_wrong_secret_does_not_destroy_and_claim_once(env):
|
||||
client = env["client"]
|
||||
start = await client.post("/oauth/start?state=attacker", json={})
|
||||
assert start.status_code == 201
|
||||
data = start.json()
|
||||
assert data["state"] != "attacker"
|
||||
assert data["claim_secret"] not in data["authorization_url"]
|
||||
cb = await client.get("/oauth/cb", params={"state": data["state"], "code": "fake-code"})
|
||||
assert cb.status_code == 200
|
||||
bad = await client.get("/oauth/claim", params={"state": data["state"]}, headers={"X-OAuth-Claim-Secret": "bad"})
|
||||
assert bad.status_code == 404
|
||||
good = await client.get("/oauth/claim", params={"state": data["state"]}, headers={"X-OAuth-Claim-Secret": data["claim_secret"]})
|
||||
assert good.status_code == 200
|
||||
assert good.json()["expires_in"] == 6900
|
||||
assert "code" not in good.json()
|
||||
assert good.headers["cache-control"] == "no-store"
|
||||
assert (await client.get("/oauth/claim", params={"state": data["state"]}, headers={"X-OAuth-Claim-Secret": data["claim_secret"]})).status_code == 404
|
||||
assert (await client.get("/oauth/cb?state=unknown&code=x")).status_code == 400
|
||||
|
||||
|
||||
async def test_oauth_concurrent_callbacks_claims_and_refresh(env):
|
||||
client = env["client"]
|
||||
data = (await client.post("/oauth/start", json={})).json()
|
||||
responses = await asyncio.gather(*[client.get("/oauth/cb", params={"state": data["state"], "code": "same"}) for _ in range(2)])
|
||||
assert sorted(x.status_code for x in responses) == [200, 400]
|
||||
assert env["platform"].exchanges == 1
|
||||
responses = await asyncio.gather(*[client.get("/oauth/claim", params={"state": data["state"]}, headers={"X-OAuth-Claim-Secret": data["claim_secret"]}) for _ in range(2)])
|
||||
assert sorted(x.status_code for x in responses) == [200, 404]
|
||||
responses = await asyncio.gather(*[client.post("/oauth/refresh", json={"refresh_token": "same-fake-refresh"}) for _ in range(2)])
|
||||
assert sorted(x.status_code for x in responses) == [200, 409]
|
||||
assert env["platform"].refreshes == 1
|
||||
|
||||
|
||||
async def test_body_limit_proxy_disabled_and_rate_limit(env):
|
||||
client = env["client"]
|
||||
assert (await client.post("/oauth/start", content=b"x" * 300000)).status_code == 413
|
||||
assert (await client.get("/proxy", headers={"X-Relay-Target": "https://evil.invalid"})).status_code == 404
|
||||
statuses = [(await client.post("/oauth/start", json={})).status_code for _ in range(21)]
|
||||
assert statuses[-1] == 429
|
||||
|
||||
|
||||
def event(env, message_id="om_test", text="/回显 平台事件", chat_type="p2p"):
|
||||
return {"header": {"event_type": "im.message.receive_v1", "app_id": env["settings"].feishu_app_id,
|
||||
"token": env["settings"].feishu_verification_token},
|
||||
"event": {"sender": {"sender_type": "user", "sender_id": {"open_id": "ou_test"}},
|
||||
"message": {"message_id": message_id, "chat_type": chat_type, "message_type": "text",
|
||||
"content": json.dumps({"text": text}, ensure_ascii=False)}}}
|
||||
|
||||
|
||||
async def test_webhook_signature_event_routing_and_replay(env):
|
||||
directory, _ = await provision(env)
|
||||
await connect_device(env, directory)
|
||||
raw = json.dumps(event(env), ensure_ascii=False).encode()
|
||||
timestamp, nonce = str(int(time.time())), "nonce"
|
||||
signature = hashlib.sha256((timestamp + nonce + env["settings"].feishu_encrypt_key).encode() + raw).hexdigest()
|
||||
headers = {"X-Lark-Request-Timestamp": timestamp, "X-Lark-Request-Nonce": nonce, "X-Lark-Signature": signature}
|
||||
assert (await env["client"].post("/feishu/event", content=raw)).status_code == 403
|
||||
for _ in range(2):
|
||||
assert (await env["client"].post("/feishu/event", content=raw, headers=headers)).status_code == 200
|
||||
for _ in range(100):
|
||||
if env["platform"].replies:
|
||||
break
|
||||
await asyncio.sleep(0.02)
|
||||
assert env["platform"].replies == [("om_test", "平台事件")]
|
||||
# No transcript or credentials persisted in either connector metadata or device journal.
|
||||
for db in [env["settings"].data_dir / "metadata.sqlite", directory / "journal.sqlite"]:
|
||||
assert "平台事件".encode() not in db.read_bytes()
|
||||
|
||||
|
||||
async def test_group_events_ignored(env):
|
||||
result = await env["client"].post("/internal/events", json=event(env, chat_type="group"),
|
||||
headers={"X-Internal-Secret": env["settings"].internal_secret})
|
||||
assert result.status_code == 200
|
||||
await asyncio.sleep(0.05)
|
||||
assert env["platform"].replies == []
|
||||
@@ -0,0 +1,36 @@
|
||||
import httpx
|
||||
import pytest
|
||||
from relay.platform import Feishu, PlatformError
|
||||
|
||||
|
||||
async def test_private_platform_domain_and_reply_target(env):
|
||||
seen = []
|
||||
def handler(request):
|
||||
seen.append(request)
|
||||
if request.url.path.endswith("app_access_token/internal"):
|
||||
return httpx.Response(200, json={"code": 0, "app_access_token": "fake-app-token", "expire": 7200})
|
||||
if request.url.path.endswith("tenant_access_token/internal"):
|
||||
return httpx.Response(200, json={"code": 0, "tenant_access_token": "fake-tenant-token", "expire": 7200})
|
||||
if request.url.path.endswith("oidc/access_token"):
|
||||
return httpx.Response(200, json={"code": 0, "data": {"access_token": "fake-user-token",
|
||||
"refresh_token": "fake-refresh", "expires_in": 6900, "open_id": "ou_test"}})
|
||||
return httpx.Response(200, json={"code": 0, "data": {}})
|
||||
env["settings"].feishu_api_base = "https://private.example.invalid"
|
||||
f = Feishu(env["settings"], transport=httpx.MockTransport(handler))
|
||||
result = await f.exchange("fake-code")
|
||||
assert result["expires_in"] == 6900
|
||||
await f.reply("om_original", "你好")
|
||||
assert all(x.url.host == "private.example.invalid" for x in seen)
|
||||
assert seen[-1].url.path == "/open-apis/im/v1/messages/om_original/reply"
|
||||
assert seen[-1].headers["Authorization"] == "Bearer fake-tenant-token"
|
||||
assert len([x for x in seen if x.url.path.endswith("app_access_token/internal")]) == 1
|
||||
await f.close()
|
||||
|
||||
|
||||
async def test_platform_errors_never_echo_credentials(env):
|
||||
f = Feishu(env["settings"], transport=httpx.MockTransport(
|
||||
lambda request: httpx.Response(400, text="fake-secret-that-must-not-appear")))
|
||||
with pytest.raises(PlatformError) as error:
|
||||
await f.app_token()
|
||||
assert "fake-secret" not in str(error.value)
|
||||
await f.close()
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Opt-in real PostgreSQL verification in an isolated, newly created schema."""
|
||||
import os
|
||||
import uuid
|
||||
import psycopg
|
||||
import pytest
|
||||
from psycopg import sql
|
||||
from relay.store import Store
|
||||
|
||||
|
||||
@pytest.mark.skipif(not os.environ.get("HN_TEST_DATABASE_URL"), reason="real PostgreSQL URL not supplied")
|
||||
def test_postgres_metadata_and_duplicate_claim(tmp_path):
|
||||
url = os.environ["HN_TEST_DATABASE_URL"]
|
||||
schema = "hn_test_" + uuid.uuid4().hex
|
||||
conn = psycopg.connect(url, autocommit=True)
|
||||
conn.execute(sql.SQL("CREATE SCHEMA {}").format(sql.Identifier(schema)))
|
||||
from psycopg.conninfo import make_conninfo
|
||||
isolated = make_conninfo(url, options=f"-c search_path={schema}")
|
||||
store = None
|
||||
try:
|
||||
store = Store(tmp_path / "unused.sqlite", isolated)
|
||||
store.add_device("host", "cert", "fingerprint")
|
||||
store.bind("host", "owner")
|
||||
assert store.by_owner("owner")["host_id"] == "host"
|
||||
assert store.begin_turn("turn", "owner", "host")
|
||||
assert not store.begin_turn("turn", "owner", "host")
|
||||
store.audit("owner", "instruction", "host", "completed")
|
||||
store.revoke("host")
|
||||
assert not store.by_owner("owner")
|
||||
finally:
|
||||
if store:
|
||||
store.close()
|
||||
conn.execute(sql.SQL("DROP SCHEMA {} CASCADE").format(sql.Identifier(schema)))
|
||||
conn.close()
|
||||
@@ -0,0 +1,44 @@
|
||||
import asyncio
|
||||
import json
|
||||
import secrets
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
from relay.device import run_device
|
||||
from .conftest import provision, serve
|
||||
from .test_hainuo1065 import POLICY, config
|
||||
from .test_web_session import browser
|
||||
|
||||
|
||||
async def test_h5_cookie_to_encrypted_device_to_native_http_result(env):
|
||||
"""Real loopback HTTP + WS, with a native model contract fixture."""
|
||||
app = FastAPI()
|
||||
@app.get("/health")
|
||||
async def health():
|
||||
return {"status": "ok", "platform": "hermes-agent"}
|
||||
@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():
|
||||
return {"choices": [{"message": {"content": "42"}, "finish_reason": "stop"}]}
|
||||
server, task, port = await serve(app)
|
||||
directory, host = 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)
|
||||
headers = await browser(env, directory, host)
|
||||
response = await env["client"].post("/web/chat", headers=headers,
|
||||
json={"text": "17加25", "request_id": secrets.token_hex(16)})
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "completed"
|
||||
assert response.json()["result"] == "42"
|
||||
finally:
|
||||
server.should_exit = True
|
||||
await asyncio.wait_for(task, 5)
|
||||
@@ -0,0 +1,141 @@
|
||||
import asyncio
|
||||
import json
|
||||
import secrets
|
||||
import time
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from relay.crypto import load_private, sign
|
||||
from relay.web_session import COOKIE, digest
|
||||
from .conftest import provision, connect_device
|
||||
|
||||
|
||||
async def issue(env, directory, host):
|
||||
config = json.loads((directory / "device.json").read_text())
|
||||
proof = sign({"host_id": host, "owner": config["owner"], "purpose": "h5-pair-v1",
|
||||
"nonce": secrets.token_hex(16), "ts": int(time.time())}, load_private(directory / "device.key"))
|
||||
response = await env["client"].post("/device/web-pair", json={"host_id": host, "proof": proof})
|
||||
assert response.status_code == 200, response.text
|
||||
return response.json(), proof
|
||||
|
||||
|
||||
async def claim(env, code):
|
||||
return await env["client"].post("/web/claim", json={"code": code}, headers={"Origin": env["settings"].public_url})
|
||||
|
||||
|
||||
def cookie(response):
|
||||
return {"Cookie": COOKIE + "=" + response.cookies.get(COOKIE)}
|
||||
|
||||
|
||||
async def browser(env, directory, host):
|
||||
issued, _ = await issue(env, directory, host)
|
||||
response = await claim(env, issued["code"])
|
||||
assert response.status_code == 200, response.text
|
||||
return {**cookie(response), "Origin": env["settings"].public_url}
|
||||
|
||||
|
||||
async def test_browser_pairing_one_time_signed_and_secure_cookie(env):
|
||||
directory, host = await provision(env)
|
||||
issued, proof = await issue(env, directory, host)
|
||||
assert "signature" in issued
|
||||
# The anonymous browser can neither name an owner nor invent a device signature.
|
||||
assert (await env["client"].post("/device/web-pair", json={"host_id": host, "proof": {}})).status_code == 403
|
||||
assert (await env["client"].post("/device/web-pair", json={"host_id": host, "proof": proof})).status_code == 409
|
||||
response = await claim(env, issued["code"])
|
||||
assert response.status_code == 200
|
||||
header = response.headers["set-cookie"].lower()
|
||||
assert "secure" in header and "httponly" in header and "samesite=strict" in header
|
||||
assert "code" not in response.json() and "owner" not in response.json()
|
||||
assert (await claim(env, issued["code"])).status_code == 404
|
||||
assert (await env["client"].get("/web/session")).status_code == 401 # Secure cookies never sent over test HTTP.
|
||||
session = await env["client"].get("/web/session", headers=cookie(response))
|
||||
assert session.status_code == 200 and session.json()["host_id"] == host
|
||||
assert session.headers["cache-control"] == "no-store"
|
||||
|
||||
|
||||
async def test_cross_origin_cannot_consume_pair_code_or_send_chat(env):
|
||||
directory, host = await provision(env)
|
||||
issued, _ = await issue(env, directory, host)
|
||||
for origin in [None, "https://evil.invalid", "null", "http://localhost.evil.invalid"]:
|
||||
headers = {} if origin is None else {"Origin": origin}
|
||||
result = await env["client"].post("/web/claim", json={"code": issued["code"]}, headers=headers)
|
||||
assert result.status_code == 403
|
||||
response = await claim(env, issued["code"])
|
||||
assert response.status_code == 200
|
||||
result = await env["client"].post("/web/chat", headers={**cookie(response), "Origin": "https://evil.invalid"},
|
||||
json={"text": "hello", "request_id": secrets.token_hex(16)})
|
||||
assert result.status_code == 403
|
||||
|
||||
|
||||
async def test_web_devices_are_isolated_and_chat_deduplicates(env):
|
||||
a, ah = await provision(env, "ou_a")
|
||||
b, bh = await provision(env, "ou_b")
|
||||
await connect_device(env, a)
|
||||
await connect_device(env, b)
|
||||
a_headers = await browser(env, a, ah)
|
||||
b_headers = await browser(env, b, bh)
|
||||
rid = secrets.token_hex(16)
|
||||
a_result, b_result = await asyncio.gather(
|
||||
env["client"].post("/web/chat", headers=a_headers, json={"text": "/回显 A独立回复", "request_id": rid}),
|
||||
env["client"].post("/web/chat", headers=b_headers, json={"text": "/回显 B独立回复", "request_id": rid}))
|
||||
assert a_result.json()["result"] == "A独立回复"
|
||||
assert b_result.json()["result"] == "B独立回复"
|
||||
again = await env["client"].post("/web/chat", headers=a_headers, json={"text": "/回显 repeat", "request_id": rid})
|
||||
assert again.json()["status"] == "duplicate"
|
||||
# Redis contains only pairing/session metadata, never the plaintext chat transcript.
|
||||
for key in await env["redis"].keys("hn:web*"):
|
||||
value = await env["redis"].get(key)
|
||||
assert "独立回复" not in str(value)
|
||||
|
||||
|
||||
async def test_logout_expiry_and_revoke_invalidate_browser(env):
|
||||
directory, host = await provision(env)
|
||||
headers = await browser(env, directory, host)
|
||||
assert (await env["client"].post("/web/logout", headers=headers)).status_code == 200
|
||||
assert (await env["client"].get("/web/session", headers=headers)).status_code == 401
|
||||
headers = await browser(env, directory, host)
|
||||
await env["redis"].delete("hn:web-session:" + digest(headers["Cookie"].split("=", 1)[1]))
|
||||
assert (await env["client"].get("/web/session", headers=headers)).status_code == 401
|
||||
headers = await browser(env, directory, host)
|
||||
await env["client"].post(f"/admin/devices/{host}/revoke", headers=env["admin"])
|
||||
assert (await env["client"].get("/web/session", headers=headers)).status_code == 401
|
||||
|
||||
|
||||
async def test_binding_generation_invalidates_old_codes_and_sessions(env):
|
||||
directory, host = await provision(env)
|
||||
issued, _ = await issue(env, directory, host)
|
||||
headers = await browser(env, directory, host)
|
||||
await env["redis"].incr("hn:web-generation:" + host)
|
||||
assert (await claim(env, issued["code"])).status_code == 401
|
||||
assert (await env["client"].get("/web/session", headers=headers)).status_code == 401
|
||||
|
||||
|
||||
async def test_pair_code_expiry_and_anonymous_chat_denied(env):
|
||||
directory, host = await provision(env)
|
||||
issued, _ = await issue(env, directory, host)
|
||||
await env["redis"].delete("hn:web-code:" + digest(issued["code"]))
|
||||
assert (await claim(env, issued["code"])).status_code == 404
|
||||
assert (await env["client"].post("/web/chat", headers={"Origin": env["settings"].public_url},
|
||||
json={"text": "hello", "request_id": secrets.token_hex(16)})).status_code == 401
|
||||
|
||||
|
||||
async def test_unprefixed_question_uses_native_agent_prefix(env):
|
||||
directory, host = await provision(env)
|
||||
headers = await browser(env, directory, host)
|
||||
seen = []
|
||||
async def capture(owner, text, turn):
|
||||
seen.append((owner, text))
|
||||
return {"status": "completed", "result": "42", "turn_id": turn}
|
||||
env["connector"].state.broker.dispatch = capture
|
||||
response = await env["client"].post("/web/chat", headers=headers,
|
||||
json={"text": "17加25", "request_id": secrets.token_hex(16), "open_id": "attacker"})
|
||||
assert response.json()["result"] == "42"
|
||||
assert seen == [("ou_test", "/助手 17加25")]
|
||||
|
||||
|
||||
async def test_concurrent_claim_exactly_one_browser(env):
|
||||
directory, host = await provision(env)
|
||||
issued, _ = await issue(env, directory, host)
|
||||
results = await asyncio.gather(claim(env, issued["code"]), claim(env, issued["code"]))
|
||||
assert sorted(x.status_code for x in results) == [200, 404]
|
||||
Reference in New Issue
Block a user