认证配置刷新与凭证下发补齐

全模块部署下本地配的白名单、激活码、吊销线、有效期原来一个都用不上,整段被跳过了。改成逐键并进去。取配置的函数不再收参数,自己读本地文件——调用方只有上次的结果,会盖回旧值。

吊销线填成未来时间戳原来直接起不来,现在降级成警告。列表型配置配成字符串会被拆开,现在报错。

走 MQTT 的设备原先拿不到凭证,现在一并下发。浏览器凭证走子协议头,跨域被拦时补了提示,回归脚本逐条加了用例
This commit is contained in:
hrz 2026-10-23 03:49:45 +00:00
parent 98e8fe240d
commit bdaa1d0c24
10 changed files with 602 additions and 48 deletions

View file

@ -22,6 +22,7 @@ Usage:
from __future__ import annotations
import asyncio
import json
import os
import sys
import time
@ -79,10 +80,10 @@ def recording_logger():
"""收集日志调用,构造期发出的告警也要能拿到"""
records = []
def bind(**kw):
def record(level):
return lambda *a, **k: records.append((level, " ".join(str(x) for x in a)))
def record(level):
return lambda *a, **k: records.append((level, " ".join(str(x) for x in a)))
def bind(**kw):
return SimpleNamespace(
info=record("info"),
warning=record("warning"),
@ -90,7 +91,15 @@ def recording_logger():
debug=record("debug"),
)
logger = SimpleNamespace(bind=bind)
# 顶层也挂上各级方法:core.auth 是模块级 logger.warning(...),
# 不走 bind,不挂的话 patch 上去的对象调不到就报 AttributeError
logger = SimpleNamespace(
bind=bind,
info=record("info"),
warning=record("warning"),
error=record("error"),
debug=record("debug"),
)
logger.records = records
return logger
@ -428,8 +437,11 @@ def test_expire_seconds_bad_type_falls_back():
def test_issued_after_invalid_fails_fast():
"""4c. 吊销线配成未来时间或字符串 → 启动即报错,不静默 401"""
for bad in (int(time.time()) + 3600, "not-a-number", -5):
"""4c. 吊销线配成字符串或负数 → 启动即报错,不静默 401
未来时间戳不在这一类里:它降级成警告并截到当前,见 test_issued_after_future_timestamp_degrades。
"""
for bad in ("not-a-number", -5):
try:
AuthManager(secret_key=SECRET, issued_after=bad)
except ValueError:
@ -845,10 +857,12 @@ def test_config_loader_keeps_api_and_local_keys():
async def fake_get_server_config():
return {k: (v.copy() if isinstance(v, dict) else v) for k, v in api_payload.items()}
with patch.object(loader, "init_service"), patch.object(
with patch.object(loader, "read_config", return_value=custom), patch.object(
loader, "get_project_dir", return_value="/tmp/"
), patch.object(loader, "init_service"), patch.object(
loader, "get_server_config", fake_get_server_config
):
merged = asyncio.run(loader.get_config_from_api_async(custom))
merged = asyncio.run(loader.get_config_from_api_async())
server = merged["server"]
assert server["auth"]["enabled"] is True, "认证开关应来自智控台"
@ -864,6 +878,392 @@ def test_config_loader_keeps_api_and_local_keys():
print("OK: 智控台部署下 server 字段逐键合并不丢失")
# ------------------------------------------------- 10. round 2:8 条 P1 的接缝
def test_subprotocol_reaches_session_layer():
"""10a. 子协议合并结果必须落到 ConnectionHandler 读的那份 request.headers 上
之前 _connection_headers 只把合并结果交给 _handle_auth,
ConnectionHandler 又从头读了一遍 dict(ws.request.headers),
结果浏览器连接认证过了但会话里没有 device-id,页面一直提示要绑定。
"""
import inspect
from core.connection import ConnectionHandler
ws_server = build_ws_server(build_config(enabled=True, allowed=[ALLOWED_MAC]))
token = ws_server.auth.generate_token(CLIENT_ID, ALLOWED_MAC)
ws = fake_ws(subprotocol_header(ALLOWED_MAC, CLIENT_ID, token))
ws_server._connection_headers(ws)
# ConnectionHandler.handle_connection 就是这么读的(connection.py)
session_headers = dict(ws.request.headers)
assert session_headers.get("device-id"), (
"子协议里的 device-id 没落到 request.headers,会话拿不到设备标识"
)
assert session_headers.get("client-id") == CLIENT_ID, session_headers
assert session_headers.get("authorization", "").startswith("Bearer "), (
f"子协议里的 token 没落到 request.headers:{session_headers}"
)
# 兜住"ConnectionHandler 改成从别处取"——只测合并函数会漏掉这一半
source = inspect.getsource(ConnectionHandler.handle_connection)
assert "ws.request.headers" in source, (
"ConnectionHandler 不再从 ws.request.headers 取,合并结果可能落不到会话层,"
"请同步改 websocket_server._connection_headers 并更新本用例"
)
print("OK: 子协议凭证一路传到会话层")
def test_mqtt_branch_returns_token():
"""10b. MQTT 分支的响应体里必须带 token,且额度消耗与响应一致"""
config = build_config(
enabled=True,
allowed=[ALLOWED_MAC],
_server={"mqtt_gateway": "1.2.3.4:1883", "mqtt_signature_key": "sig-key"},
)
ota = build_ota(config)
request = FakeRequest({"device-id": ALLOWED_MAC, "client-id": CLIENT_ID})
resp = asyncio.run(ota.handle_post(request))
assert resp.status == 200, f"白名单自举应 200,实际 {resp.status}"
body = json.loads(resp.text)
assert body.get("mqtt"), f"应下发 MQTT 配置:{body}"
token = body["mqtt"].get("token")
assert token, (
f"MQTT 分支没带 token,激活码与自举名额却已经消耗掉了:{body['mqtt']}"
)
# 额度与响应一致:同一台设备不带凭证再来一次,必须被拒
again = asyncio.run(
ota.handle_post(FakeRequest({"device-id": ALLOWED_MAC, "client-id": CLIENT_ID}))
)
assert again.status == 401, (
f"第一次给了 token 却消耗了额度,第二次应 401,实际 {again.status}"
)
# 拿这个 token 能换到下一次,不至于只能连一次
renewed = asyncio.run(
ota.handle_post(
FakeRequest(
{"device-id": ALLOWED_MAC, "client-id": CLIENT_ID, **bearer(token)}
)
)
)
assert renewed.status == 200, f"MQTT 分支下发的 token 应可续签,实际 {renewed.status}"
print("OK: MQTT 分支下发 token,额度消耗与响应一致")
def test_activation_code_returns_token_on_mqtt_branch():
"""10c. 激活码绑定的 MQTT 设备也要拿到 token,否则码白烧"""
config = build_config(
enabled=True,
activation_codes=[f"mqtt-code: {ALLOWED_MAC}"],
_server={"mqtt_gateway": "1.2.3.4:1883", "mqtt_signature_key": "sig-key"},
)
ota = build_ota(config)
resp = asyncio.run(
ota.handle_post(
FakeRequest(
{
"device-id": ALLOWED_MAC,
"client-id": CLIENT_ID,
**bearer("mqtt-code"),
}
)
)
)
assert resp.status == 200, f"激活码应 200,实际 {resp.status}"
body = json.loads(resp.text)
assert body["mqtt"].get("token"), f"激活码用掉却没下发 token:{body['mqtt']}"
print("OK: 激活码在 MQTT 分支也能换到 token")
def test_whitelist_normalized_and_bootstrap_for_any_spelling():
"""10d. 白名单按归一值比较:分隔符和大小写不同都该认同一台设备
websocket 侧认不认白名单只体现在 token 有效期上,
所以用"短有效期签发 + 白名单放长"来区分:认出来就过,认不出就过期。
"""
from core.auth import normalize_device_id
for form in (
"aa:bb:cc:dd:ee:ff",
"AA:BB:CC:DD:EE:FF",
"aa-bb-cc-dd-ee-ff",
"aabbccddeeff",
"AA_BB_CC_DD_EE_FF",
):
config = build_config(
enabled=True,
allowed=["AA-BB-CC-DD-EE-FF"],
allowed_devices_expire_seconds=7200,
)
ws_server = build_ws_server(config)
assert ws_server.allowed_devices == {"aabbccddeeff"}, (
f"加载时没归一:{ws_server.allowed_devices}"
)
# 造一个 10 秒前就签发的 token:白名单不认它就只有默认有效期,会过期
stale_ts = int(time.time()) - 10
content = f"{CLIENT_ID}|{form}|{stale_ts}"
signature = ws_server.auth._sign(content)
token = f"{signature}.{stale_ts}"
ok = run_ws_auth(
ws_server,
{"device-id": form, "client-id": CLIENT_ID, **bearer(token)},
)
assert ok, (
f"白名单写法 {form} 没认出来(归一值 {normalize_device_id(form)}),"
"会让这台设备的 token 拿到默认有效期"
)
# OTA 侧的白名单同样按归一值比较
ota = build_ota(build_config(enabled=True, allowed=["AA-BB-CC-DD-EE-FF"]))
assert ota.allowed_devices == {"aabbccddeeff"}, ota.allowed_devices
print("OK: 白名单认得各种分隔符与大小写写法")
def test_list_config_rejects_scalar_string():
"""10e. allowed_devices / activation_codes 配成字符串必须报错,不能逐字符拆"""
# allowed_devices 两边都读,activation_codes 只有 OTA 读,按各自加载的那一侧触发
for key, bad, load in (
("allowed_devices", "aa:bb:cc:dd:ee:ff", build_ws_server),
("activation_codes", "SecretCode1", build_ota),
):
config = build_config(enabled=True)
config["server"]["auth"][key] = bad
try:
load(config)
raise AssertionError(f"server.auth.{key} 配成字符串应报错")
except ValueError:
pass
print("OK: 列表型配置配成字符串时报错")
def test_issued_after_future_timestamp_degrades():
"""10f. 填未来的吊销时刻只警告并截到当前,不该让整个进程起不来"""
from core.auth import normalize_issued_after
future = int(time.time()) + 60
logger = recording_logger()
with patch("core.auth.logger", logger):
clamped = normalize_issued_after(future)
assert clamped <= int(time.time()), f"未来时刻应截到当前,实际 {clamped}"
warned = " ".join(messages(logger, "warning"))
assert "issued_after" in warned, f"截断了却没提示:{warned}"
# 能构造出来,WebSocket / OTA / 视觉接口才不会一起没
with patch("core.auth.logger", logger):
manager = AuthManager(secret_key=SECRET, issued_after=future)
assert manager.issued_after <= int(time.time())
# 非整数与负数仍然是配错,该报错
for bad in ("abc", -1):
try:
normalize_issued_after(bad)
raise AssertionError(f"issued_after={bad!r} 应报错")
except ValueError:
pass
print("OK: 未来吊销时刻降级为警告,填错仍报错")
def test_reload_order_keeps_config_intact_on_bad_auth():
"""10g. 换配置时先校验认证段:配错不能留下"配置换了一半、模块不再重建"的状态"""
ws_server = build_ws_server(build_config(enabled=True, allowed=[ALLOWED_MAC]))
before = ws_server.config
broken = build_config(enabled=True)
broken["server"]["auth"]["allowed_devices"] = "aa:bb:cc:dd:ee:ff"
try:
ws_server._load_auth_config(broken)
raise AssertionError("配错的 auth 段应抛错")
except ValueError:
pass
assert ws_server.config is before, "校验没过就不该动 self.config"
print("OK: 认证段校验失败时配置保持原样")
def test_config_loader_merges_local_auth_keys():
"""10h. 全模块部署下本地配的四个认证项必须逐键并进去"""
import config.config_loader as loader
api_payload = {"server": {"ip": "10.0.0.5", "auth": {"enabled": True}}}
local = {
"manager-api": {"url": "http://console", "secret": "msecret"},
"server": {
"auth": {
"allowed_devices": ["aa:bb:cc:dd:ee:ff"],
"activation_codes": ["local-code"],
"issued_after": 1700000000,
"expire_seconds": 3600,
}
},
}
async def fake_get_server_config():
return {k: (v.copy() if isinstance(v, dict) else v) for k, v in api_payload.items()}
with patch.object(loader, "read_config", return_value=local), patch.object(
loader, "get_project_dir", return_value="/tmp/"
), patch.object(loader, "init_service"), patch.object(
loader, "get_server_config", fake_get_server_config
):
merged = asyncio.run(loader.get_config_from_api_async())
auth = merged["server"]["auth"]
assert auth["enabled"] is True, "认证开关应来自智控台"
for key, want in (
("allowed_devices", ["aa:bb:cc:dd:ee:ff"]),
("activation_codes", ["local-code"]),
("issued_after", 1700000000),
("expire_seconds", 3600),
):
assert auth.get(key) == want, f"本地配的 {key} 没生效:{auth}"
assert merged["server"]["ip"] == "10.0.0.5", "接口返回的字段不该被吞"
print("OK: 全模块部署下本地四个认证项都并进去了")
def test_update_config_keeps_local_auth_keys():
"""10i. 走完 update_config(),本地四个认证项在 self.config 里仍然是本地配的值
这条断言覆盖整条链:本地配置 → get_config_from_api_async → 合并 → 赋回 self.config。
只测 get_config_from_api_async() 挡不住"入参传错"——传 self.config 或只传 server 段
都不报错,但四个键会悄悄变回空。
"""
import config.config_loader as loader
import core.websocket_server as ws_mod
ws_server = build_ws_server(build_config(enabled=True, allowed=[ALLOWED_MAC]))
ws_server.config_lock = asyncio.Lock()
local = {
"manager-api": {"url": "http://console", "secret": "msecret"},
"server": {
"auth": {
"allowed_devices": ["aa:bb:cc:dd:ee:ff"],
"activation_codes": ["local-code"],
"issued_after": 1700000000,
"expire_seconds": 3600,
}
},
}
api_payload = {
"selected_module": [],
"server": {"ip": "10.0.0.9", "auth": {"enabled": True}},
}
# 刷新前就签好的 token:auth_key 只在启动时算一次,刷新配置不能把它换掉,
# 换了等于给所有在线设备换了一把密钥,token 集体作废
old_token = ws_server.auth.generate_token(CLIENT_ID, ALLOWED_MAC)
async def fake_get_server_config():
return {k: (v.copy() if isinstance(v, dict) else v) for k, v in api_payload.items()}
with patch.object(loader, "read_config", return_value=local), patch.object(
loader, "get_project_dir", return_value="/tmp/"
), patch.object(loader, "init_service"), patch.object(
loader, "get_server_config", fake_get_server_config
), patch.object(
ws_mod, "initialize_modules", return_value={}
), patch.object(
ws_mod, "check_vad_update", return_value=False
), patch.object(
ws_mod, "check_asr_update", return_value=False
):
ok = asyncio.run(ws_server.update_config())
assert ok, f"update_config 应成功:{messages(ws_server.logger, 'error')}"
auth = ws_server.config["server"]["auth"]
for key, want in (
("allowed_devices", ["aa:bb:cc:dd:ee:ff"]),
("activation_codes", ["local-code"]),
("issued_after", 1700000000),
("expire_seconds", 3600),
):
assert auth.get(key) == want, (
f"刷新配置后本地的 {key} 没了,说明入参传的是上次合并结果:{auth}"
)
assert ws_server.config["server"]["ip"] == "10.0.0.9", "接口返回的字段应生效"
assert ws_server.config["server"]["auth_key"] == SECRET, "auth_key 被刷新掉了"
assert ws_server.auth.verify_token(
old_token, client_id=CLIENT_ID, username=ALLOWED_MAC
), "刷新配置让刷新前签的 token 失效了,等于给在线设备全换了一把密钥"
print("OK: update_config 刷新后本地认证项与接口字段都在")
def test_cors_empty_warn_reports_blocked_origin():
"""10j. 名单为空时跨域被拦,服务端要留信号,否则只有浏览器那头知道"""
with captured_warnings() as logger:
handler = VisionHandler(build_config(enabled=True, cors={"allowed_origins": []}))
response = _cors_headers_for(handler.config, "http://127.0.0.1:8006")
assert "Access-Control-Allow-Origin" not in response, "空名单不该放行"
warned = " ".join(messages(logger, "warning"))
assert "allowed_origins" in warned, f"被拦下却没留服务端信号:{warned}"
assert "127.0.0.1:8006" in warned, f"告警里应点名是哪个来源被拦:{warned}"
print("OK: 名单为空时服务端会点名被拦的来源")
def test_tester_page_covers_both_localhost_spellings():
"""10k. 测试页的两种打开方式都要在文档里写清,两个 origin 不是一回事"""
import re
readme = open(
os.path.join(REPO, "main", "digital-human", "README.md"), encoding="utf-8"
).read()
for origin in ("http://127.0.0.1:8006", "http://localhost:8006"):
assert origin in readme, f"README 没写 {origin},按这种地址打开会连不上"
assert "file://" in readme, "README 应说明用 file:// 打开没意义"
config_yaml = open(
os.path.join(SERVER, "config.yaml"), encoding="utf-8"
).read()
# 说明写在 cors: 上方的注释里,正则得连注释一起框进来
block = re.search(
r"(?:^[ \t]*#.*\n)+^[ \t]*cors:\s*\n\s*allowed_origins:[^\n]*",
config_yaml,
re.M,
)
assert block, "config.yaml 里找不到 cors 配置"
comment = block.group(0)
assert "127.0.0.1:8006" in comment and "localhost:8006" in comment, (
"config.yaml 注释要同时写两个来源,只写一个按另一种方式打开照样不通"
)
assert '"null"' not in comment, (
'不该再引导填 "null":页面检测到 file:// 会自己弹窗挡住,origin 不会是 null'
)
print("OK: 文档写清了测试页的两种来源")
def test_tester_page_reuses_token():
"""10l. 测试页拿到 token 要存下来复用,激活码用一次就作废"""
connector = open(
os.path.join(REPO, "main", "digital-human", "js", "core", "network", "ota-connector.js"),
encoding="utf-8",
).read()
manager = open(
os.path.join(REPO, "main", "digital-human", "js", "config", "manager.js"),
encoding="utf-8",
).read()
assert "xz_tester_token" in connector, "OTA 拿到的 token 没存下来"
assert "config.token || config.activationCode" in connector, (
"发 OTA 时应优先用 token,没有才用激活码"
)
assert "xz_tester_activationCode" in manager and "loadConfig" in manager
load_config_body = manager.split("export function loadConfig")[1].split("export function")[0]
assert "xz_tester_activationCode" in load_config_body, (
"激活码只写不读,刷新页面就断了"
)
get_config_body = manager.split("export function getConfig")[1].split("// 保存连接URL")[0]
assert "xz_tester_token" in get_config_body, "存下来的 token 没传下去"
print("OK: 测试页会复用 token,激活码也读得回来")
def main() -> int:
test_allowed_mac_without_token_rejected()
test_allowed_mac_forged_client_id_rejected()
@ -903,6 +1303,18 @@ def main() -> int:
test_cors_vary_always_written()
test_all_cors_call_sites_pass_request()
test_config_loader_keeps_api_and_local_keys()
test_subprotocol_reaches_session_layer()
test_mqtt_branch_returns_token()
test_activation_code_returns_token_on_mqtt_branch()
test_whitelist_normalized_and_bootstrap_for_any_spelling()
test_list_config_rejects_scalar_string()
test_issued_after_future_timestamp_degrades()
test_reload_order_keeps_config_intact_on_bad_auth()
test_config_loader_merges_local_auth_keys()
test_update_config_keeps_local_auth_keys()
test_cors_empty_warn_reports_blocked_origin()
test_tester_page_covers_both_localhost_spellings()
test_tester_page_reuses_token()
print("\nALL PASS: 3448 认证旁路已关闭")
return 0

View file

@ -37,8 +37,26 @@ python start.py
1. **激活码**:向服务端运维要一个码,填进页面的「激活码」输入框。页面请求 OTA 时带上它,服务端换发一次 websocket token,用掉即失效。
2. **设备MAC**:填无分隔符或带冒号的 12 位 MAC 都行,页面会统一去掉分隔符转小写后再发给服务端。OTA 请求头和 websocket 子协议用的是同一个值,签名才对得上。
激活码只能用一次,页面拿到 token 后会自己存着,之后每次 OTA 都用 token 续签,不用再填码。
websocket 的凭证走子协议头而不是 URL:`Sec-WebSocket-Protocol: xiaozhi, t-<token>, d-<deviceId>, c-<clientId>`。浏览器不能自定义 websocket 请求头,服务端握手时只回显 `xiaozhi`。放进 URL 查询串的凭证不再被采信,理由是查询串会原样落进反代访问日志。
## 跨域
服务端默认不下发跨域响应头,页面从别的来源打开时会被浏览器拦掉。跨域失败在浏览器里读不到状态码,只会在控制台报一句不透明的错,所以要让服务端把页面的来源加进白名单:
`http://127.0.0.1:8006` 和 `http://localhost:8006` 是两个不同来源,按上面哪个地址打开就得填哪个,两个都填最省事:
```yaml
server:
cors:
allowed_origins:
- http://127.0.0.1:8006
- http://localhost:8006
```
`main/digital-human` 里的页面是用 `python start.py` 起 HTTP 服务打开的,不是双击文件;用 `file://` 打开时页面会自己弹窗挡住整页,来源是 `null` 也不必往名单里填。
不开启认证时以上都不用填,行为与之前一致。
# 目录说明

View file

@ -72,6 +72,18 @@ export function loadConfig() {
if (savedEmojiEnabled !== null && emojiEnabledInput) {
emojiEnabledInput.value = savedEmojiEnabled;
}
// 激活码和 token 要读回来,否则刷新页面就断了:
// 服务端激活码用掉即作废,读不回来就只能重新填一个
const activationCodeInput = document.getElementById('activationCode');
if (activationCodeInput) {
activationCodeInput.value = localStorage.getItem('xz_tester_activationCode') || '';
}
// token 是 OTA 下发回来的续签凭证,比激活码长效,放着下次直接用
const token = localStorage.getItem('xz_tester_token');
if (token) {
sessionStorage.setItem('xz_tester_token', token);
}
}
// 保存配置
@ -112,6 +124,7 @@ export function getConfig() {
const deviceName = document.getElementById('deviceName')?.value.trim() || '';
const clientId = document.getElementById('clientId')?.value.trim() || '';
const activationCode = document.getElementById('activationCode')?.value.trim() || '';
const token = sessionStorage.getItem('xz_tester_token') || '';
const emojiEnabled = document.getElementById('emojiEnabled')?.value !== 'false';
return {
@ -120,6 +133,9 @@ export function getConfig() {
deviceMac,
clientId,
activationCode,
// 有 token 就用它续签,激活码是一次性的,用掉即失效,
// 第二次再拿激活码去 OTA 会被拒
token,
emojiEnabled
};
}

View file

@ -27,6 +27,14 @@ export async function webSocketConnect(otaUrl, config) {
return;
}
// token 存下来下次续签用:激活码用掉即作废,
// 不存的话第二次点连接必然被服务端拒
const issuedToken = (websocket.token || otaResult.mqtt?.token || '').replace(/^Bearer\s+/i, '');
if (issuedToken) {
sessionStorage.setItem('xz_tester_token', issuedToken);
localStorage.setItem('xz_tester_token', issuedToken);
}
// 使用OTA返回的websocket URL
const connUrl = new URL(websocket.url);
@ -72,16 +80,15 @@ function validateConfig(config) {
// OTA发送请求,验证状态,并返回响应数据
async function sendOTA(otaUrl, config) {
try {
// 有 token 用 token 续签,没有才用激活码换首次 token
const credential = config.token || config.activationCode;
const res = await fetch(otaUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Device-Id': normalizeDeviceId(config.deviceId),
'Client-Id': config.clientId,
// 开了认证时,OTA 要拿激活码换首次 token;用掉即失效
...(config.activationCode
? { 'Authorization': `Bearer ${config.activationCode}` }
: {})
...(credential ? { 'Authorization': `Bearer ${credential}` } : {})
},
body: JSON.stringify({
version: 0,
@ -116,6 +123,14 @@ async function sendOTA(otaUrl, config) {
const result = await res.json();
return result; // 返回完整的响应数据
} catch (err) {
// 跨域失败在浏览器里是不透明的:fetch 直接抛 TypeError,
// 拿不到状态码,也看不出是服务端没回跨域头还是服务没起来。
// 页面知道自己的来源,直接点名让人去加白名单
if (err instanceof TypeError) {
log(`请求 ${otaUrl} 被浏览器拦下(跨域)。把 ${window.location.origin} 加到服务端的 server.cors.allowed_origins 里`, 'error');
} else {
log(`OTA请求失败: ${err.message}`, 'error');
}
return null; // 失败返回null
}
}

View file

@ -60,8 +60,10 @@ server:
# 需要跨域时填具体来源,例如 ["https://your-console.example.com"]
# 注意:填 "*" 不会放行任意来源。来源不在名单里就不下发跨域头,
# 浏览器会直接拦下,带凭证的请求仍受同源保护
# 另:用本地文件直接打开的测试页面(如 digital-human/index.html)
# 浏览器上报的来源是 null,需要跨域时把 "null" 一并填进来
# 仓库自带的测试页(main/digital-human)用 HTTP 服务打开时来源是
# http://127.0.0.1:8006 或 http://localhost:8006——这是两个不同来源,
# 按哪种方式打开就得把哪个填进来,只填一个照样连不上。
# 用 file:// 直接双击打开的,页面会自己弹窗挡住,配置这一项没意义
cors:
allowed_origins: []
# MQTT网关配置,用于通过OTA下发到设备,根据mqtt_gateway的.env文件配置,格式为host:port

View file

@ -40,7 +40,7 @@ async def load_config():
custom_config = read_config(custom_config_path)
if custom_config.get("manager-api", {}).get("url"):
config = await get_config_from_api_async(custom_config)
config = await get_config_from_api_async()
else:
# 合并配置
config = merge_configs(default_config, custom_config)
@ -52,10 +52,16 @@ async def load_config():
return config
async def get_config_from_api_async(config):
"""从Java API获取配置(异步版本)"""
async def get_config_from_api_async():
"""从Java API获取配置(异步版本),本地配置逐键覆盖上去
本地配置在这里自己读,不接受调用方传进来:调用方手里只有上一次合并
完的结果,拿它当"本地"会把旧值盖回这次新拉到的响应,改配置不生效。
"""
local_config = read_config(get_project_dir() + "data/.config.yaml") or {}
# 初始化API客户端
init_service(config)
init_service(local_config)
# 获取服务器配置
config_data = await get_server_config()
@ -64,25 +70,36 @@ async def get_config_from_api_async(config):
config_data["read_config_from_api"] = True
config_data["manager-api"] = {
"url": config["manager-api"].get("url", ""),
"secret": config["manager-api"].get("secret", ""),
"url": local_config.get("manager-api", {}).get("url", ""),
"secret": local_config.get("manager-api", {}).get("secret", ""),
}
server_config = config_data.setdefault("server", {})
# 认证开关以智控台的参数管理为准,这里只补默认值。
# 不能重建整个 auth,否则接口返回的 allowed_devices、activation_codes
# 这些字段会被抹掉,智控台部署下等于配置写了不生效
server_config.setdefault("auth", {}).setdefault("enabled", False)
server_auth = server_config.setdefault("auth", {})
server_auth.setdefault("enabled", False)
# 智控台只下发 enabled 这一个键,本地配的白名单、激活码、吊销线、有效期
# 得逐键并进去。整段跳过的话它们在官方全模块部署里一个都用不了,
# 而本地这边没有任何提示,配了等于没配。
# 智控台哪天开始下发这些键,以智控台为准
for key, value in ((local_config.get("server") or {}).get("auth") or {}).items():
if key != "enabled":
server_auth.setdefault(key, value)
# server 的其余配置以本地为准,但只覆盖本地显式写过的字段。
# 整块替换会把接口返回的 cors、websocket 等一并吞掉。
# auth 例外,它归智控台管
for key, value in (config.get("server") or {}).items():
# auth 例外,它归智控台管,在上面单独合并
# 注意 auth_key 在 server 下、不在 server.auth 里,它归这一段管;
# 而 config.yaml 里根本没有 auth_key 这一行,默认部署下压根不参与合并,
# 靠 app.py 回落到 manager-api.secret。要改它得显式写进 data/.config.yaml
for key, value in (local_config.get("server") or {}).items():
if key != "auth":
server_config[key] = value
# 如果服务器没有prompt_template,则从本地配置读取
if not config_data.get("prompt_template"):
config_data["prompt_template"] = config.get("prompt_template")
config_data["prompt_template"] = local_config.get("prompt_template")
return config_data

View file

@ -2,11 +2,17 @@ from aiohttp import web
from config.logger import setup_logging
def allowed_origins(config: dict) -> list:
cors = config.get("server", {}).get("cors", {}) or {}
return cors.get("allowed_origins", []) or []
class BaseHandler:
def __init__(self, config: dict):
self.config = config
self.logger = setup_logging()
self._cors_wildcard_warned = False
self._cors_empty_warned = False
def _resolve_cors_origin(self, origin: str | None) -> str | None:
"""回显名单内的 Origin;其余情况不下发 CORS 头,由浏览器拦截
@ -42,6 +48,16 @@ class BaseHandler:
if origin:
response.headers["Access-Control-Allow-Origin"] = origin
response.headers["Access-Control-Allow-Credentials"] = "true"
elif requested_origin and not allowed_origins(self.config):
# 名单空着的时候浏览器只会报一个不透明的跨域错误,
# 服务端这边一点信号都没有,读日志的人会一头雾水
if not self._cors_empty_warned:
self._cors_empty_warned = True
self.logger.bind(tag="BaseHandler").warning(
f"cors.allowed_origins 是空的,本次来自 {requested_origin} 的"
"跨域请求不会放行。浏览器侧只会报读不到状态码的错,"
"排查这类问题时先把这个来源加进名单"
)
async def handle_options(self, request):
"""处理OPTIONS请求,添加CORS头信息"""

View file

@ -9,7 +9,7 @@ import glob
from typing import Dict, List, Tuple
from aiohttp import web
from core.auth import AuthManager
from core.auth import AuthManager, auth_config_list, normalize_device_id
from core.utils.util import get_local_ip, get_vision_url
from core.api.base_handler import BaseHandler
@ -27,11 +27,6 @@ DEVICE_ID_PATTERN = re.compile(
DEVICE_MODEL_PATTERN = re.compile(r"[A-Za-z0-9_\-]+")
def _normalize_device_id(device_id: str) -> str:
"""去掉分隔符转小写,让 aa:bb:cc:dd:ee:ff 与 aabbccddeeff 视为同一台设备"""
return re.sub(r"[:\-_]", "", device_id).lower()
def _error_response(status: int, message: str) -> web.Response:
"""OTA 拒绝响应,状态码与智控台 /ota/ 保持一致,固件按状态码判断才不会走偏"""
return web.Response(
@ -102,7 +97,12 @@ class OTAHandler(BaseHandler):
auth_config = config["server"].get("auth", {})
self.auth_enable = auth_config.get("enabled", False)
# 设备白名单:命中白名单只影响 token 有效期,不再跳过 token 校验
self.allowed_devices = set(auth_config.get("allowed_devices", []))
# 加载时就归一成去掉分隔符的小写,和激活码绑定、OTA 请求头用同一套写法,
# 否则同一台设备换个分隔符或大小写就既不认白名单也不认激活码,直接锁死
self.allowed_devices = {
normalize_device_id(item)
for item in auth_config_list(auth_config, "allowed_devices")
}
# 白名单设备的 token 有效期,默认与普通设备一致
self.allowed_expire_seconds = auth_config.get(
"allowed_devices_expire_seconds", None
@ -112,7 +112,7 @@ class OTAHandler(BaseHandler):
self.allowed_bootstrapped = set()
# 一次性激活码,供无 token 的设备首次绑定;写 "码: Device-Id" 可绑到具体设备
self.activation_codes = _parse_activation_codes(
auth_config.get("activation_codes", []) or []
auth_config_list(auth_config, "activation_codes")
)
secret_key = config["server"]["auth_key"]
expire_seconds = auth_config.get("expire_seconds")
@ -141,7 +141,7 @@ class OTAHandler(BaseHandler):
def _expire_for(self, device_id: str):
"""白名单设备的 token 有效期,其余设备沿用默认"""
if self.allowed_devices and device_id in self.allowed_devices:
if self.allowed_devices and normalize_device_id(device_id) in self.allowed_devices:
return self.allowed_expire_seconds
return None
@ -179,11 +179,11 @@ class OTAHandler(BaseHandler):
if not (
self.allowed_bootstrap
and self.allowed_devices
and device_id in self.allowed_devices
and device_id not in self.allowed_bootstrapped
and normalize_device_id(device_id) in self.allowed_devices
and normalize_device_id(device_id) not in self.allowed_bootstrapped
):
return ""
self.allowed_bootstrapped.add(device_id)
self.allowed_bootstrapped.add(normalize_device_id(device_id))
self.logger.bind(tag=TAG).warning(
f"白名单设备免凭证自举签发 token: {device_id},此后该设备必须携带凭证"
)
@ -196,7 +196,7 @@ class OTAHandler(BaseHandler):
bound_device = self.activation_codes[presented]
if not bound_device:
return True
return _normalize_device_id(bound_device) == _normalize_device_id(device_id)
return normalize_device_id(bound_device) == normalize_device_id(device_id)
def _consume_activation_code(self, presented: str) -> None:
"""作废一次性激活码,只在响应组装成功后调用"""
@ -442,6 +442,8 @@ class OTAHandler(BaseHandler):
self.logger.bind(tag=TAG).warning("缺少MQTT签名密钥,密码留空")
# 构建MQTT配置(直接使用 mqtt_gateway 字符串)
# token 一并下发:开认证时固件下载要带凭证,MQTT 设备自己不会再
# 走一遍 OTA,不在这里给就永远换不到凭证
return_json["mqtt"] = {
"endpoint": mqtt_gateway_endpoint,
"client_id": mqtt_client_id,
@ -449,6 +451,7 @@ class OTAHandler(BaseHandler):
"password": password,
"publish_topic": "device-server",
"subscribe_topic": f"devices/p2p/{mac_address_safe}",
"token": ws_token,
}
self.logger.bind(tag=TAG).info(f"为设备 {device_id} 下发MQTT网关配置")

View file

@ -1,8 +1,11 @@
import hmac
import base64
import hashlib
import re
import time
from loguru import logger
DEFAULT_EXPIRE_SECONDS = 60 * 60 * 24 * 30
# 有效期上限,防止把过期时间配成准永久凭证
MAX_EXPIRE_SECONDS = 60 * 60 * 24 * 90
@ -24,18 +27,25 @@ def normalize_expire_seconds(expire_seconds) -> int:
def normalize_issued_after(issued_after) -> int:
"""吊销时刻归一化,配置不合法时直接报错,不留到验签时静默失败"""
"""吊销时刻归一化
非整数和负数直接报错——这两类是配错了,不会有人这么填。
超前的时间戳只降级成警告并截到当前时间:这一格最容易踩的是跨主机时钟偏差,
而吊销线超前本来就等于没设,不值得为它把整个进程拖到起不来。
"""
try:
value = int(issued_after or 0)
except (TypeError, ValueError):
raise ValueError(f"server.auth.issued_after 必须是整数,当前值:{issued_after!r}")
if value < 0:
raise ValueError(f"server.auth.issued_after 不能为负数,当前值:{value}")
if value > int(time.time()):
raise ValueError(
"server.auth.issued_after 是吊销线,只能是过去或当前的时间戳,"
f"当前值:{value}"
now = int(time.time())
if value > now:
logger.warning(
f"server.auth.issued_after 填的是未来的时间戳(当前值 {value},本机 {now}),"
"已截到当前时间。吊销线超前等于没设,请检查两台机器的时钟是否对得上"
)
return now
return value
@ -45,6 +55,29 @@ class AuthenticationError(Exception):
pass
def normalize_device_id(device_id: str) -> str:
"""把 Device-Id 归一成去掉分隔符的小写
白名单、激活码绑定、OTA 请求头三处都要用同一个值比较,
同一台设备换个分隔符或大小写就会被一边认一边不认。
"""
return re.sub(r"[:\-_]", "", device_id).lower()
def auth_config_list(auth_config: dict, key: str) -> list:
"""取 auth 段里的列表型配置,配成标量字符串时直接报错
不校验的话 set("aa:bb:cc:dd:ee:ff") 会逐字符拆成 7 个元素,
激活码字符串会被拆成十个单字符码,配了等于没配还看不出问题。
"""
value = auth_config.get(key)
if value is None:
return []
if not isinstance(value, list):
raise ValueError(f"server.auth.{key} 必须是列表,当前值:{value!r}")
return value
class AuthManager:
"""
统一授权认证管理器

View file

@ -32,7 +32,12 @@ _setup_websockets_logger()
from core.connection import ConnectionHandler
from config.config_loader import get_config_from_api_async
from core.auth import AuthManager, AuthenticationError
from core.auth import (
AuthManager,
AuthenticationError,
auth_config_list,
normalize_device_id,
)
from core.utils.modules_initialize import initialize_modules
from core.utils.util import check_vad_update, check_asr_update
@ -90,7 +95,12 @@ class WebSocketServer:
auth_config = config["server"].get("auth", {})
self.auth_enable = auth_config.get("enabled", False)
# 设备白名单:命中白名单只影响 token 的校验时长,不再跳过校验本身
self.allowed_devices = set(auth_config.get("allowed_devices", []))
# 和 OTA 侧同一套写法:加载时归一成去分隔符的小写,
# 否则设备换个分隔符或大小写上报,同一台设备一边认白名单一边不认
self.allowed_devices = {
normalize_device_id(device_id)
for device_id in auth_config_list(auth_config, "allowed_devices")
}
# 白名单设备的 token 有效期,默认与普通设备一致,不因白名单放宽
self.allowed_expire_seconds = auth_config.get(
"allowed_devices_expire_seconds", None
@ -128,11 +138,14 @@ class WebSocketServer:
请求头优先,两者都不从 URL 查询串取:查询串会原样落进反代访问日志,
设备标识和 token 都不该出现在那里。
合并结果写回 request.headers:ConnectionHandler 会再读一次那里,
不写回去浏览器连接就是认证过了但会话里没有 device-id。
"""
headers = dict(websocket.request.headers)
for key, value in _parse_subprotocol_headers(headers).items():
if not headers.get(key):
headers[key] = value
websocket.request.headers[key] = value
return headers
async def _handle_connection(self, websocket: websockets.ServerConnection):
@ -198,7 +211,7 @@ class WebSocketServer:
try:
async with self.config_lock:
# 重新获取配置(使用异步版本)
new_config = await get_config_from_api_async(self.config)
new_config = await get_config_from_api_async()
if new_config is None:
self.logger.bind(tag=TAG).error("获取新配置失败")
return False
@ -209,10 +222,17 @@ class WebSocketServer:
self.logger.bind(tag=TAG).info(
f"检查VAD和ASR类型是否需要更新: {update_vad} {update_asr}"
)
# auth_key 是 app.py 启动时算出来写进 config 的,
# config.yaml 里没有这一行,重新拉一次接口就没了。
# 换掉了等于换了一把签名密钥,刷新前签发的 token 全部作废
new_config["server"].setdefault(
"auth_key", self.config["server"]["auth_key"]
)
# 认证属性先跟着配置刷新:_load_auth_config 配错会抛,
# 抛了却已经把 self.config 换掉的话,模块不重建、配置还换了一半
self._load_auth_config(new_config)
# 更新配置
self.config = new_config
# 认证属性跟随配置刷新,避免改配置后不生效
self._load_auth_config(new_config)
# 重新初始化组件
modules = initialize_modules(
self.logger,
@ -255,7 +275,9 @@ class WebSocketServer:
raise AuthenticationError("Missing or invalid Authorization header")
# 白名单设备只延长 token 有效期,仍然校验 token
expire_seconds = None
if self.allowed_devices and device_id in self.allowed_devices:
if self.allowed_devices and normalize_device_id(
device_id or ""
) in self.allowed_devices:
expire_seconds = self.allowed_expire_seconds
# 进行认证
auth_success = self.auth.verify_token(