Files

142 lines
7.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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"}