Skip to content

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

fix(api): restrict cross-origin browser access

harry0703373ec466485b
diff --git a/README-en.md b/README-en.md
index 3519dcc7..23175407 100644
--- a/README-en.md
+++ b/README-en.md
@@ -280,6 +280,8 @@ Open your browser and visit http://127.0.0.1:8501
Open your browser and visit http://127.0.0.1:8080/docs or http://127.0.0.1:8080/redoc
+> The API allows same-origin browser access by default. Set the `CORS_ALLOWED_ORIGINS` environment variable only when a separate browser frontend must call the API directly from another origin, for example `http://localhost:3000,https://frontend.example.com`. CORS does not affect curl, Postman, n8n, or other server-side clients.
+
### Manual Deployment 📦
#### ① Create a Python Virtual Environment
diff --git a/README-ja.md b/README-ja.md
index 707561e5..558cf1f0 100644
--- a/README-ja.md
+++ b/README-ja.md
@@ -278,6 +278,8 @@ docker compose -f docker-compose.release.yml up
ブラウザーで http://127.0.0.1:8080/docs または http://127.0.0.1:8080/redoc を開きます
+> API はデフォルトで同一オリジンのブラウザーアクセスのみを許可します。別のブラウザーフロントエンドから API を直接呼び出す場合に限り、環境変数 `CORS_ALLOWED_ORIGINS` へ信頼するオリジンを設定してください(例: `http://localhost:3000,https://frontend.example.com`)。curl、Postman、n8n、その他のサーバー側クライアントは CORS の影響を受けません。
+
### 手動でデプロイ 📦
#### ① Python の仮想環境を作成する
diff --git a/README.md b/README.md
index 9db075d5..2ea2c965 100644
--- a/README.md
+++ b/README.md
@@ -287,6 +287,8 @@ docker compose -f docker-compose.release.yml up
打开浏览器,访问 http://127.0.0.1:8080/docs 或者 http://127.0.0.1:8080/redoc
+> API 默认仅允许同源网页访问。只有独立网页前端需要从其他来源直接调用 API 时,才应通过环境变量 `CORS_ALLOWED_ORIGINS` 配置可信来源,例如 `http://localhost:3000,https://frontend.example.com`。curl、Postman、n8n 和其他服务端调用不受 CORS 限制。
+
### 手动部署 📦
> 视频教程
diff --git a/app/asgi.py b/app/asgi.py
index 1d8401a4..278e2dfd 100644
--- a/app/asgi.py
+++ b/app/asgi.py
@@ -2,6 +2,7 @@
import os
from contextlib import asynccontextmanager
+from urllib.parse import urlsplit
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
@@ -62,6 +63,107 @@ def validation_exception_handler(request: Request, e: RequestValidationError):
)
+def parse_cors_allowed_origins(raw_origins: str | None) -> list[str]:
+ """解析浏览器跨域来源白名单。
+
+ CORS 只约束浏览器中的跨域 JavaScript,不影响 curl、Postman、n8n
+ 或服务端 SDK。未配置时返回空列表,表示默认不开放跨域访问;用户确实
+ 部署了独立网页前端时,再通过 ``CORS_ALLOWED_ORIGINS`` 显式开启。
+ """
+
+ if not raw_origins:
+ return []
+
+ # 去除逗号分隔项两侧的空白,并忽略空项,避免常见的环境变量格式
+ # ``https://a.example, https://b.example,`` 产生永远无法匹配的来源。
+ return [origin.strip() for origin in raw_origins.split(",") if origin.strip()]
+
+
+def configure_cors(instance: FastAPI, allowed_origins: list[str]) -> None:
+ """按显式白名单配置 CORS;空白名单保持默认同源策略。"""
+
+ if not allowed_origins:
+ logger.info(
+ "browser cross-origin API access is disabled; set "
+ "CORS_ALLOWED_ORIGINS to enable trusted origins"
+ )
+ return
+
+ allow_all_origins = "*" in allowed_origins
+ configured_api_key = config.app.get("api_key", "")
+ if allow_all_origins and configured_api_key in (None, ""):
+ # ``*`` 是用户显式选择的兼容模式,因此不强制拒绝启动;但在免认证
+ # 状态下它会允许任意网页读取和调用 API,必须留下可定位的安全告警。
+ logger.warning(
+ "CORS allows every browser origin while API key authentication is "
+ "disabled; configure app.api_key or restrict CORS_ALLOWED_ORIGINS"
+ )
+
+ instance.add_middleware(
+ CORSMiddleware,
+ allow_origins=allowed_origins,
+ # Starlette 在 ``*`` 与 credentials 同时启用时会反射任意 Origin。
+ # 通配符模式不需要 Cookie 认证,因此主动关闭 credentials;显式来源
+ # 仍保留旧行为,避免影响已有独立网页前端的 credentials 请求模式。
+ allow_credentials=not allow_all_origins,
+ allow_methods=["*"],
+ allow_headers=["*"],
+ # 远程 HTTPS 前端访问本机或局域网 API 时,现代浏览器会额外发送
+ # Private Network Access 预检。只有精确白名单来源可以获得许可;
+ # 通配符模式继续拒绝,避免任意网站探测用户的私有网络服务。
+ allow_private_network=not allow_all_origins,
+ )
+
+
+def is_browser_origin_allowed(
+ request: Request, allowed_origins: list[str]
+) -> bool:
+ """判断浏览器请求来源是否为同源或显式白名单来源。"""
+
+ origin = request.headers.get("origin")
+ if not origin:
+ # curl、Postman、n8n 和服务端 SDK 通常不发送 Origin。保留这类请求,
+ # 避免安全修复错误地改变现有 API 客户端的调用契约。
+ return True
+ if "*" in allowed_origins or origin in allowed_origins:
+ return True
+
+ # 浏览器对同源 POST 也可能发送 Origin。仅比较 scheme + authority,忽略
+ # 路径和查询参数;反向代理部署若未正确转发公网 scheme/host,可通过显式
+ # CORS_ALLOWED_ORIGINS 声明外部来源,避免依赖不可信的转发 Header。
+ request_url = urlsplit(str(request.url))
+ request_origin = f"{request_url.scheme}://{request_url.netloc}"
+ return origin == request_origin
+
+
+def configure_browser_access(instance: FastAPI, allowed_origins: list[str]) -> None:
+ """同时配置服务端 Origin 防护与浏览器 CORS 响应策略。"""
+
+ @instance.middleware("http")
+ async def reject_untrusted_browser_origin(request: Request, call_next):
+ """主动拒绝不可信浏览器来源,覆盖无需 CORS 预检的简单请求。"""
+
+ if not is_browser_origin_allowed(request, allowed_origins):
+ origin = request.headers.get("origin", "")
+ logger.warning(
+ f"blocked untrusted browser origin: method={request.method}, "
+ f"path={request.url.path}, origin={origin}"
+ )
+ return JSONResponse(
+ status_code=403,
+ content=utils.get_response(
+ status=403,
+ message="cross-origin browser request is not allowed",
+ ),
+ )
+
+ return await call_next(request)
+
+ # CORS 中间件最后注册后位于 Origin 防护外层:可信预检可直接成功,
+ # 非可信预检由 CORS 拒绝;无需预检的实际请求仍会进入上面的 403 防护。
+ configure_cors(instance, allowed_origins)
+
+
def get_application() -> FastAPI:
"""Initialize FastAPI application.
@@ -105,16 +207,11 @@ async def protect_generated_task_files(request: Request, call_next):
return await call_next(request)
-# Configures the CORS middleware for the FastAPI app
-cors_allowed_origins_str = os.getenv("CORS_ALLOWED_ORIGINS", "")
-origins = cors_allowed_origins_str.split(",") if cors_allowed_origins_str else ["*"]
-app.add_middleware(
- CORSMiddleware,
- allow_origins=origins,
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
+# 默认遵循浏览器同源策略;仅在用户显式配置可信网页来源时开放跨域。
+cors_allowed_origins = parse_cors_allowed_origins(
+ os.getenv("CORS_ALLOWED_ORIGINS", "")
)
+configure_browser_access(app, cors_allowed_origins)
task_dir = utils.task_dir()
app.mount("/tasks", StaticFiles(directory=task_dir, html=True), name="")
diff --git a/test/services/test_asgi_cors.py b/test/services/test_asgi_cors.py
new file mode 100644
index 00000000..9c14149f
--- /dev/null
+++ b/test/services/test_asgi_cors.py
@@ -0,0 +1,177 @@
+import unittest
+from unittest.mock import Mock
+
+from fastapi import FastAPI, File, UploadFile
+from fastapi.testclient import TestClient
+
+from app import asgi
+
+
+class TestASGICORS(unittest.TestCase):
+ """验证浏览器跨域默认值和显式兼容配置,避免重新引入开放 CORS。"""
+
+ @staticmethod
+ def _create_client(allowed_origins: list[str]) -> TestClient:
+ """构造只包含探针路由的应用,隔离业务任务和外部 API 调用。"""
+
+ application = FastAPI()
+
+ @application.get("/probe")
+ def probe():
+ return {"status": "ok"}
+
+ asgi.configure_browser_access(application, allowed_origins)
+ return TestClient(application)
+
+ def test_origin_parser_trims_values_and_ignores_empty_items(self):
+ """环境变量中的空格和尾随逗号不应破坏合法来源匹配。"""
+
+ origins = asgi.parse_cors_allowed_origins(
+ " https://a.example,https://b.example, ,"
+ )
+
+ self.assertEqual(
+ origins,
+ ["https://a.example", "https://b.example"],
+ )
+ self.assertEqual(asgi.parse_cors_allowed_origins(""), [])
+ self.assertEqual(asgi.parse_cors_allowed_origins(None), [])
+
+ def test_empty_configuration_keeps_browser_same_origin_policy(self):
+ """未配置白名单时,第三方网页不能读取响应或通过预检。"""
+
+ client = self._create_client([])
+ origin = "https://evil.attacker.example"
+
+ response = client.get("/probe", headers={"Origin": origin})
+ preflight = client.options(
+ "/probe",
+ headers={
+ "Origin": origin,
+ "Access-Control-Request-Method": "GET",
+ },
+ )
+
+ self.assertEqual(response.status_code, 403)
+ self.assertNotIn("access-control-allow-origin", response.headers)
+ self.assertNotIn("access-control-allow-credentials", response.headers)
+ self.assertEqual(preflight.status_code, 403)
+ self.assertNotIn("access-control-allow-origin", preflight.headers)
+
+ def test_same_origin_and_server_clients_remain_compatible(self):
+ """同源浏览器和不发送 Origin 的服务端客户端必须继续正常访问。"""
+
+ client = self._create_client([])
+
+ same_origin = client.get(
+ "/probe",
+ headers={"Origin": "http://testserver"},
+ )
+ server_client = client.get("/probe")
+
+ self.assertEqual(same_origin.status_code, 200)
+ self.assertEqual(server_client.status_code, 200)
+
+ def test_explicit_origin_allows_only_the_trusted_frontend(self):
+ """独立网页前端显式配置后可以访问,其他来源仍必须被拒绝。"""
+
+ trusted_origin = "https://frontend.example"
+ untrusted_origin = "https://evil.attacker.example"
+ client = self._create_client([trusted_origin])
+
+ trusted = client.get("/probe", headers={"Origin": trusted_origin})
+ untrusted = client.get("/probe", headers={"Origin": untrusted_origin})
+ trusted_preflight = client.options(
+ "/probe",
+ headers={
+ "Origin": trusted_origin,
+ "Access-Control-Request-Method": "GET",
+ },
+ )
+ untrusted_preflight = client.options(
+ "/probe",
+ headers={
+ "Origin": untrusted_origin,
+ "Access-Control-Request-Method": "GET",
+ },
+ )
+
+ self.assertEqual(trusted.headers["access-control-allow-origin"], trusted_origin)
+ self.assertEqual(trusted.headers["access-control-allow-credentials"], "true")
+ self.assertNotIn("access-control-allow-origin", untrusted.headers)
+ self.assertEqual(trusted_preflight.status_code, 200)
+ self.assertEqual(untrusted_preflight.status_code, 400)
+
+ def test_trusted_origin_can_request_private_network_access(self):
+ """精确白名单应支持远程网页访问本机或局域网 API 的额外预检。"""
+
+ trusted_origin = "https://frontend.example"
+ client = self._create_client([trusted_origin])
+
+ preflight = client.options(
+ "/probe",
+ headers={
+ "Origin": trusted_origin,
+ "Access-Control-Request-Method": "GET",
+ "Access-Control-Request-Private-Network": "true",
+ },
+ )
+
+ self.assertEqual(preflight.status_code, 200)
+ self.assertEqual(
+ preflight.headers["access-control-allow-private-network"],
+ "true",
+ )
+
+ def test_explicit_wildcard_does_not_enable_credentials(self):
+ """显式通配符保留兼容能力,但不得再次形成反射 Origin 的组合。"""
+
+ client = self._create_client(["*"])
+ origin = "https://frontend.example"
+
+ response = client.get("/probe", headers={"Origin": origin})
+ preflight = client.options(
+ "/probe",
+ headers={
+ "Origin": origin,
+ "Access-Control-Request-Method": "GET",
+ },
+ )
+
+ self.assertEqual(response.headers["access-control-allow-origin"], "*")
+ self.assertNotIn("access-control-allow-credentials", response.headers)
+ self.assertEqual(preflight.status_code, 200)
+ self.assertEqual(preflight.headers["access-control-allow-origin"], "*")
+ self.assertNotIn("access-control-allow-credentials", preflight.headers)
+
+ def test_untrusted_multipart_request_is_rejected_before_side_effect(self):
+ """无需预检的 multipart 请求也必须在进入上传处理函数前返回 403。"""
+
+ application = FastAPI()
+ save_upload = Mock(return_value="stored.mp3")
+
+ @application.post("/upload")
+ def upload(file: UploadFile = File(...)):
+ return {"file": save_upload(file.filename)}
+
+ asgi.configure_browser_access(application, [])
+ client = TestClient(application)
+
+ response = client.post(
+ "/upload",
+ headers={"Origin": "https://evil.attacker.example"},
+ files={
+ "file": (
+ "attack.mp3",
+ b"attacker-controlled",
+ "audio/mpeg",
+ )
+ },
+ )
+
+ self.assertEqual(response.status_code, 403)
+ save_upload.assert_not_called()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/test/services/test_asgi_static_files.py b/test/services/test_asgi_static_files.py
index ab85ae9c..ad80a2c9 100644
--- a/test/services/test_asgi_static_files.py
+++ b/test/services/test_asgi_static_files.py
@@ -68,8 +68,8 @@ class TestTaskStaticFiles(unittest.TestCase):
self.assertEqual(self.client.get("/ping").status_code, 200)
self.assertEqual(self.client.get("/docs").status_code, 200)
- def test_options_request_is_left_to_cors_middleware(self):
- """受保护文件的 CORS 预检不应被 API Key 校验提前拒绝。"""
+ def test_unconfigured_cors_rejects_task_file_preflight(self):
+ """默认同源模式必须拒绝第三方网页对任务文件发起预检。"""
config.app["api_key"] = "task-file-secret"
@@ -82,7 +82,8 @@ class TestTaskStaticFiles(unittest.TestCase):
},
)
- self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.status_code, 403)
+ self.assertNotIn("access-control-allow-origin", response.headers)
def test_does_not_serve_symlink_to_file_outside_tasks(self):
with (