跨域默认不放行,陌生来源交浏览器拦

跨域默认放开所有来源等于放行任意网站带凭证读响应,比改之前固定回通
配符更糟:那个组合浏览器本来会拦,改成回显来源就真能读了。默认改回空
名单,不在名单里就不下发跨域头,交给浏览器拦。填星号不放行任何来
源,只在启动时提醒一次。
This commit is contained in:
hrz 2026-10-22 01:42:38 +00:00
parent 6e5e528245
commit 7e70484540
3 changed files with 102 additions and 10 deletions

View file

@ -33,10 +33,13 @@ OTHER_MAC = "11:22:33:44:55:66"
CLIENT_ID = "7b94d69a-9808-4c59-9c9b-704333b38aff"
def build_config(enabled=True, allowed=None, **extra):
def build_config(enabled=True, allowed=None, cors=None, **extra):
auth = {"enabled": enabled, "allowed_devices": allowed or []}
auth.update(extra)
return {"server": {"auth": auth, "auth_key": SECRET}}
server = {"auth": auth, "auth_key": SECRET}
if cors is not None:
server["cors"] = cors
return {"server": server}
def build_ws_server(config):
@ -297,6 +300,81 @@ def test_handler_state_initialized():
print("OK: OTAHandler 状态初始化完整")
def _cors_headers_for(config, origin):
"""给一个响应加跨域头后返回头字典"""
from aiohttp import web
ota = build_ota(config)
resp = web.Response(text="x")
ota._add_cors_headers(resp, fake_request({"Origin": origin}))
return resp.headers
def test_cors_blocks_unknown_origin():
"""默认配置下任意来源都拿不到跨域头,带凭证不可跨域读"""
headers = _cors_headers_for(build_config(enabled=True), "https://evil.example")
assert "Access-Control-Allow-Origin" not in headers, (
f"默认配置不应回显陌生来源,实际 {dict(headers)}"
)
assert "Access-Control-Allow-Credentials" not in headers, (
"未放行来源时不应下发允许带凭证的头"
)
print("OK: 默认配置下陌生来源无跨域头")
def test_cors_wildcard_not_allowed():
"""allowed_origins 配 * 也不回显,避免带凭证的跨域读取"""
headers = _cors_headers_for(
build_config(enabled=True, cors={"allowed_origins": ["*"]}),
"https://evil.example",
)
assert "Access-Control-Allow-Origin" not in headers, (
f"配 * 也不应回显来源,实际 {dict(headers)}"
)
assert "Access-Control-Allow-Credentials" not in headers, (
"配 * 时不得下发允许带凭证的头"
)
print("OK: allowed_origins 配 * 不放行任意来源")
def test_cors_allows_listed_origin():
"""名单内的来源正常放行"""
allowed = "https://console.example"
headers = _cors_headers_for(
build_config(enabled=True, cors={"allowed_origins": [allowed]}),
allowed,
)
assert headers.get("Access-Control-Allow-Origin") == allowed, (
f"名单内来源应被回显,实际 {dict(headers)}"
)
assert headers.get("Access-Control-Allow-Credentials") == "true"
other = _cors_headers_for(
build_config(enabled=True, cors={"allowed_origins": [allowed]}),
"https://evil.example",
)
assert "Access-Control-Allow-Origin" not in other, "名单外来源不应放行"
print("OK: 名单内来源放行、名单外拦截")
def test_all_cors_call_sites_pass_request():
"""所有跨域头调用点都要传 request,避免某条路径静默不发头"""
import re
pattern = re.compile(r"_add_cors_headers\(\s*\w+\s*\)")
offenders = []
for rel in (
"core/api/base_handler.py",
"core/api/ota_handler.py",
"core/api/vision_handler.py",
):
path = os.path.join(SERVER, rel)
for line in open(path, encoding="utf-8"):
if pattern.search(line):
offenders.append(f"{rel}: {line.strip()}")
assert not offenders, f"这些调用点没传 request:{offenders}"
print("OK: 所有跨域头调用点都传了 request")
def main() -> int:
test_allowed_mac_without_token_rejected()
test_allowed_mac_forged_client_id_rejected()
@ -311,6 +389,10 @@ def main() -> int:
test_mqtt_topic_injection_blocked()
test_download_requires_credential()
test_handler_state_initialized()
test_cors_blocks_unknown_origin()
test_cors_wildcard_not_allowed()
test_cors_allows_listed_origin()
test_all_cors_call_sites_pass_request()
print("\nALL PASS: 3448 认证旁路已关闭")
return 0

View file

@ -47,10 +47,12 @@ server:
# token 签发时刻下界(Unix 秒)。改成当前时间即可一次性作废所有存量 token,
# 设备下次开机请求 OTA 时会自动换发新 token,无需维护黑名单
issued_after: 0
# CORS 允许的来源列表。默认 ["*"] 表示回显任意来源的 Origin;
# 收紧时填具体来源,例如 ["https://your-console.example.com"]
# CORS 允许的来源列表,默认空表示不做跨域放行
# 需要跨域时填具体来源,例如 ["https://your-console.example.com"]
# 注意:填 "*" 不会放行任意来源。来源不在名单里就不下发跨域头,
# 浏览器会直接拦下,带凭证的请求仍受同源保护
cors:
allowed_origins: ["*"]
allowed_origins: []
# MQTT网关配置,用于通过OTA下发到设备,根据mqtt_gateway的.env文件配置,格式为host:port
mqtt_gateway: null
# MQTT签名密钥,用于生成MQTT连接密码,根据mqtt_gateway的.env文件配置

View file

@ -6,15 +6,24 @@ class BaseHandler:
def __init__(self, config: dict):
self.config = config
self.logger = setup_logging()
self._cors_wildcard_warned = False
def _resolve_cors_origin(self, origin: str | None) -> str | None:
"""回显允许的 Origin,取不到或不在名单里时不放 CORS 头"""
"""回显名单内的 Origin;其余情况不下发 CORS 头,由浏览器拦截
这里刻意不支持通配:回显任意来源并带上 Allow-Credentials 会让任意网站
都能带凭证读响应,而固定写 "*" 配 Allow-Credentials 属于浏览器明确
拒绝的组合,反而挡得更严。宁可什么都不放,也不放宽。
"""
if not origin:
return None
cors = self.config.get("server", {}).get("cors", {}) or {}
allowed = cors.get("allowed_origins", ["*"]) or ["*"]
if "*" in allowed:
return origin
allowed = cors.get("allowed_origins", []) or []
if "*" in allowed and not self._cors_wildcard_warned:
self._cors_wildcard_warned = True
self.logger.bind(tag="BaseHandler").warning(
"cors.allowed_origins 里的 * 不会放行任意来源,请填写具体来源"
)
return origin if origin in allowed else None
def _add_cors_headers(self, response, request=None):
@ -26,7 +35,6 @@ class BaseHandler:
request.headers.get("Origin") if request is not None else None
)
if origin:
# 回显具体 Origin,配合 Allow-Credentials 才是浏览器规范允许的写法
response.headers["Access-Control-Allow-Origin"] = origin
response.headers["Access-Control-Allow-Credentials"] = "true"
response.headers["Vary"] = "Origin"