Skip to content

利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.

fix(asgi): normalize CORS origins (#1392)

XiaoChene0c9cb77ffd0
diff --git a/app/asgi.py b/app/asgi.py
index 278e2dfd..bfb2b201 100644
--- a/app/asgi.py
+++ b/app/asgi.py
@@ -63,12 +63,66 @@ def validation_exception_handler(request: Request, e: RequestValidationError):
)
+_DEFAULT_PORTS = {"http": 80, "https": 443}
+
+
+def _normalize_allowed_origin(raw_origin: str) -> str | None:
+ """把配置项折叠成浏览器实际发送的 Origin 形式。
+
+ Origin 请求头由 RFC 6454 固定为 ``scheme://host[:port]``:没有路径、没有尾
+ 斜杠,scheme 与 host 已经规范化为小写,并且省略协议的默认端口。用户在浏览器
+ 地址栏复制得到的 ``https://frontend.example/``,以及显式写出默认端口的
+ ``https://frontend.example:443``,都与浏览器实际发送的
+ ``https://frontend.example`` 逐字符不相等,白名单因此静默失效:前端只看到
+ CORS 报错,服务端只留下一行 blocked 日志,两边都指不到配置本身。
+
+ 返回 ``None`` 表示该写法不可能匹配任何 Origin(缺少 scheme、scheme 不是
+ http/https、主机名为空或含空白、IPv6 字面量畸形、端口非法或越界),调用方应
+ 丢弃并告警。解析失败必须收敛成 ``None``:本函数在模块导入期就会执行,让
+ ``urlsplit()`` 的 ``ValueError`` 冒出去等于整条 API 无法启动。
+ """
+
+ if raw_origin == "*":
+ return raw_origin
+
+ try:
+ parsed = urlsplit(raw_origin)
+ scheme = parsed.scheme.lower()
+ # 读取 hostname / port 时才校验 netloc:畸形 IPv6 字面量由 urlsplit()
+ # 抛出,非数字端口与超出 0-65535 的端口在读取 port 时抛出。
+ host = parsed.hostname
+ port = parsed.port
+ except ValueError:
+ return None
+
+ # 只有 http/https 具备浏览器 Origin 语义,且两者都有可省略的默认端口。
+ if scheme not in _DEFAULT_PORTS or not host:
+ return None
+ if any(character.isspace() for character in host):
+ return None
+
+ # 显式小写,不依赖 urlsplit 在不同 Python 版本上的大小写处理。
+ host = host.lower()
+ # 浏览器序列化 Origin 时给 IPv6 字面量保留方括号;``:443``、``:0443``、
+ # ``:80`` 这类默认端口写法必须折叠成不带端口的形态才能与真实前端匹配。
+ if ":" in host:
+ host = f"[{host}]"
+ if port is None or port == _DEFAULT_PORTS[scheme]:
+ return f"{scheme}://{host}"
+ return f"{scheme}://{host}:{port}"
+
+
def parse_cors_allowed_origins(raw_origins: str | None) -> list[str]:
"""解析浏览器跨域来源白名单。
CORS 只约束浏览器中的跨域 JavaScript,不影响 curl、Postman、n8n
或服务端 SDK。未配置时返回空列表,表示默认不开放跨域访问;用户确实
部署了独立网页前端时,再通过 ``CORS_ALLOWED_ORIGINS`` 显式开启。
+
+ 每个来源都先折叠成 Origin 请求头的规范形式,因此 ``https://a.example/``、
+ ``HTTPS://A.Example`` 与显式默认端口的 ``https://a.example:443`` 得到同一个
+ 结果,无法匹配任何 Origin 的写法会被丢弃并留下告警。畸形条目只丢弃自身,
+ 不会中断这里的解析——本函数在模块导入期调用,解析异常会让 API 无法启动。
"""
if not raw_origins:
@@ -76,7 +130,21 @@ def parse_cors_allowed_origins(raw_origins: str | None) -> list[str]:
# 去除逗号分隔项两侧的空白,并忽略空项,避免常见的环境变量格式
# ``https://a.example, https://b.example,`` 产生永远无法匹配的来源。
- return [origin.strip() for origin in raw_origins.split(",") if origin.strip()]
+ origins: list[str] = []
+ for candidate in raw_origins.split(","):
+ item = candidate.strip()
+ if not item:
+ continue
+ origin = _normalize_allowed_origin(item)
+ if origin is None:
+ logger.warning(
+ f"ignoring configured CORS origin that cannot match a browser "
+ f"Origin header: {item!r}"
+ )
+ continue
+ if origin not in origins:
+ origins.append(origin)
+ return origins
def configure_cors(instance: FastAPI, allowed_origins: list[str]) -> None:
diff --git a/test/services/test_asgi_cors.py b/test/services/test_asgi_cors.py
index 9c14149f..bfb39dea 100644
--- a/test/services/test_asgi_cors.py
+++ b/test/services/test_asgi_cors.py
@@ -1,5 +1,5 @@
import unittest
-from unittest.mock import Mock
+from unittest.mock import Mock, patch
from fastapi import FastAPI, File, UploadFile
from fastapi.testclient import TestClient
@@ -37,6 +37,121 @@ class TestASGICORS(unittest.TestCase):
self.assertEqual(asgi.parse_cors_allowed_origins(""), [])
self.assertEqual(asgi.parse_cors_allowed_origins(None), [])
+ def test_origin_parser_normalizes_every_item_to_origin_header_shape(self):
+ """配置项必须折叠成 Origin 请求头的规范形式,否则白名单静默失效。"""
+
+ origins = asgi.parse_cors_allowed_origins(
+ "https://frontend.example/,"
+ "HTTPS://Admin.Example,"
+ "https://frontend.example/,"
+ "localhost:3000,"
+ "ftp://files.example,"
+ "*"
+ )
+
+ # 尾斜杠、大小写差异和重复项都归一到同一个来源;缺少 scheme 的主机名、
+ # 非 http/https 的 scheme 都不可能出现在 Origin 头里,因此被丢弃。
+ self.assertEqual(
+ origins,
+ ["https://frontend.example", "https://admin.example", "*"],
+ )
+
+ def test_malformed_entry_is_dropped_without_losing_valid_origins(self):
+ """畸形条目只能丢弃自身并留下告警,不得中断整份配置的解析。"""
+
+ with patch.object(asgi, "logger") as mocked_logger:
+ origins = asgi.parse_cors_allowed_origins(
+ "https://valid.example,"
+ "https://[::1,"
+ "https://frontend.example:bad,"
+ "https://frontend.example:99999,"
+ "https://second.example"
+ )
+
+ # 畸形 IPv6 字面量和非法端口都不可能出现在 Origin 头里。它们的解析异常
+ # 必须在这里收敛:本函数由模块导入期调用,异常冒出去等于整条 API 起不来。
+ self.assertEqual(
+ origins,
+ ["https://valid.example", "https://second.example"],
+ )
+ self.assertEqual(mocked_logger.warning.call_count, 3)
+
+ def test_explicit_default_port_is_folded_into_the_origin(self):
+ """显式写出默认端口的写法必须折叠成浏览器实际发送的 Origin。"""
+
+ origins = asgi.parse_cors_allowed_origins(
+ "https://secure.example:443,"
+ "http://plain.example:80,"
+ "https://padded.example:0443,"
+ "https://custom.example:8443,"
+ "https://[::1]:3000"
+ )
+
+ # :443 / :0443 / :80 都等于协议的默认端口,浏览器序列化 Origin 时会省略;
+ # 非默认端口必须保留,IPv6 字面量则要连方括号一起保留。
+ self.assertEqual(
+ origins,
+ [
+ "https://secure.example",
+ "http://plain.example",
+ "https://padded.example",
+ "https://custom.example:8443",
+ "https://[::1]:3000",
+ ],
+ )
+
+ def test_address_bar_style_origin_admits_the_trusted_frontend(self):
+ """从地址栏复制的带尾斜杠写法必须与规范写法得到同一个前端访问结果。"""
+
+ trusted_origin = "https://frontend.example"
+ client = self._create_client(
+ asgi.parse_cors_allowed_origins("https://frontend.example/")
+ )
+
+ response = client.get("/probe", headers={"Origin": trusted_origin})
+ preflight = client.options(
+ "/probe",
+ headers={
+ "Origin": trusted_origin,
+ "Access-Control-Request-Method": "GET",
+ },
+ )
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(
+ response.headers["access-control-allow-origin"], trusted_origin
+ )
+ self.assertEqual(preflight.status_code, 200)
+ self.assertEqual(
+ preflight.headers["access-control-allow-origin"], trusted_origin
+ )
+
+ def test_default_port_configuration_admits_the_trusted_frontend(self):
+ """配置里写了默认端口时,浏览器不带端口的 Origin 仍必须被放行。"""
+
+ trusted_origin = "https://frontend.example"
+ client = self._create_client(
+ asgi.parse_cors_allowed_origins("https://frontend.example:443")
+ )
+
+ response = client.get("/probe", headers={"Origin": trusted_origin})
+ preflight = client.options(
+ "/probe",
+ headers={
+ "Origin": trusted_origin,
+ "Access-Control-Request-Method": "GET",
+ },
+ )
+
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(
+ response.headers["access-control-allow-origin"], trusted_origin
+ )
+ self.assertEqual(preflight.status_code, 200)
+ self.assertEqual(
+ preflight.headers["access-control-allow-origin"], trusted_origin
+ )
+
def test_empty_configuration_keeps_browser_same_origin_policy(self):
"""未配置白名单时,第三方网页不能读取响应或通过预检。"""