利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.
Python ai-video-generatorcontent-creationffmpeginstagram-reelsllmpythonshort-videosubtitlestext-to-speechtiktokvideo-automationvideo-workflowworkflow-automationyoutube-shorts
fix(api): enforce configured API key
harry070328a55ddc1d3f
diff --git a/app/asgi.py b/app/asgi.pyindex a7486515..1d8401a4 100644--- a/app/asgi.py+++ b/app/asgi.py@@ -11,6 +11,7 @@ from fastapi.staticfiles import StaticFilesfrom loguru import loggerfrom app.config import config+from app.controllers import basefrom app.models.exception import HttpExceptionfrom app.router import root_api_routerfrom app.utils import utils@@ -21,6 +22,19 @@ async def application_lifespan(_: FastAPI):"""集中处理 API 进程启动恢复和关闭日志。"""logger.info("startup event")+ configured_api_key = config.app.get("api_key", "")+ if configured_api_key in (None, ""):+ logger.warning(+ "API key authentication is disabled; keep the API on a trusted network"+ )+ elif isinstance(configured_api_key, str):+ # 只记录保护范围,不得输出 Key、长度或摘要,避免凭据进入日志系统。+ logger.info("API key authentication is enabled for /api/v1 and /tasks")+ else:+ logger.error(+ "API key authentication is misconfigured: app.api_key must be a string"+ )+# 跨平台发布由当前进程线程池执行,不会在服务重启后恢复。启动时把 Redis# 中确认已失去执行进程的活动状态收敛为失败,避免任务永久无法删除。from app.services import task as task_service@@ -70,6 +84,27 @@ def get_application() -> FastAPI:app = get_application()+[email protected]("http")+async def protect_generated_task_files(request: Request, call_next):+ """保护任务产物静态路由,防止绕过 API 鉴权直接下载。++ ``/tasks`` 由 StaticFiles 独立挂载,无法复用 APIRouter 的依赖,+ 因此在中间件中调用同一个 verify_token。鉴权函数会在未配置+ api_key 时放行;OPTIONS 预检请求也保留给 CORS 中间件处理。+ """++ request_path = request.url.path+ is_task_file = request_path == "/tasks" or request_path.startswith("/tasks/")+ if is_task_file and request.method != "OPTIONS":+ try:+ base.verify_token(request)+ except HttpException as exception:+ return exception_handler(request, exception)++ return await call_next(request)++# Configures the CORS middleware for the FastAPI appcors_allowed_origins_str = os.getenv("CORS_ALLOWED_ORIGINS", "")origins = cors_allowed_origins_str.split(",") if cors_allowed_origins_str else ["*"]diff --git a/app/controllers/base.py b/app/controllers/base.pyindex 9c80460a..c858836c 100644--- a/app/controllers/base.py+++ b/app/controllers/base.py@@ -1,6 +1,8 @@+import secrets+from typing import Annotatedfrom uuid import uuid4-from fastapi import Request+from fastapi import Header, Requestfrom app.config import configfrom app.models.exception import HttpException@@ -29,14 +31,68 @@ def get_api_key(request: Request):return api_key-def verify_token(request: Request):- token = get_api_key(request)- if token != config.app.get("api_key", ""):- request_id = get_task_id(request)- request_url = request.url- user_agent = request.headers.get("user-agent")+def get_api_key_values(request: Request) -> list[str]:+ """返回请求中全部 API Key Header,保留重复值用于安全校验。"""++ # Starlette Headers 提供 getlist(),可以区分代理或客户端发送的重复 Header。+ # 单元测试中的轻量 Request 替身只使用普通 dict,因此保留兼容回退。+ get_list = getattr(request.headers, "getlist", None)+ if callable(get_list):+ return [value for value in get_list("x-api-key") if isinstance(value, str)]++ api_key = get_api_key(request)+ return [api_key] if isinstance(api_key, str) else []+++def verify_token(+ request: Request,+ x_api_key: Annotated[str | None, Header(alias="x-api-key")] = None,+):+ """按配置决定是否校验 API Key。++ 空 Key 保留现有的本地免认证模式;管理员显式配置非空 Key 后,API+ 路由和任务产物下载都会要求客户端通过 ``x-api-key`` 请求头提供同一+ 个值。参数声明同时让 Swagger 展示该请求头,便于受保护环境调试。+ """++ configured_key = config.app.get("api_key", "")+ if configured_key in (None, ""):+ return None++ # 配置项必须是字符串。这里拒绝列表、数字等错误类型,避免字符串隐式+ # 转换产生难以发现的认证行为;错误信息也不包含实际 Key。+ if not isinstance(configured_key, str):raise HttpException(- task_id=request_id,+ task_id=get_task_id(request),+ status_code=500,+ message="API authentication is misconfigured",+ )++ # FastAPI 参数用于在 OpenAPI 中声明 x-api-key;实际校验始终读取 Request,+ # 才能识别同名 Header 被重复发送的情况。普通客户端和反向代理对重复 Header+ # 的取值顺序可能不同,因此必须拒绝,而不能隐式采用第一个或最后一个值。+ token_values = get_api_key_values(request)+ if not token_values and isinstance(x_api_key, str):+ token_values = [x_api_key]++ if len(token_values) != 1:+ raise HttpException(+ task_id=get_task_id(request),+ status_code=401,+ message="invalid API key",+ )++ # compare_digest 对 str 只支持 ASCII。请求 Header 属于不可信输入,攻击者+ # 可以发送 Latin-1 字符触发 TypeError。统一编码为 UTF-8 bytes 后既保留+ # 恒定时间比较,也支持 TOML 中合法的 Unicode Key。+ token = token_values[0]+ if not secrets.compare_digest(+ token.encode("utf-8"), configured_key.encode("utf-8")+ ):+ raise HttpException(+ task_id=get_task_id(request),status_code=401,- message=f"invalid token: {request_url}, {user_agent}",+ message="invalid API key",)++ return Nonediff --git a/app/controllers/v1/llm.py b/app/controllers/v1/llm.pyindex 68d7bb77..3d58eda5 100644--- a/app/controllers/v1/llm.py+++ b/app/controllers/v1/llm.py@@ -1,5 +1,6 @@-from fastapi import Request+from fastapi import Depends, Request+from app.controllers import basefrom app.controllers.v1.base import new_routerfrom app.models.schema import (VideoScriptRequest,@@ -12,9 +13,9 @@ from app.models.schema import (from app.services import llmfrom app.utils import utils-# authentication dependency-# router = new_router(dependencies=[Depends(base.verify_token)])-router = new_router()+# LLM 接口与视频接口共用同一鉴权规则,避免新增端点时遗漏保护。+# api_key 为空时 verify_token 直接放行,不改变默认本地使用体验。+router = new_router(dependencies=[Depends(base.verify_token)])@router.post(diff --git a/app/controllers/v1/video.py b/app/controllers/v1/video.pyindex 8fed8cff..00ef176b 100644--- a/app/controllers/v1/video.py+++ b/app/controllers/v1/video.py@@ -36,9 +36,9 @@ from app.services import state as smfrom app.services import task as tmfrom app.utils import file_security, utils-# 认证依赖项-# router = new_router(dependencies=[Depends(base.verify_token)])-router = new_router()+# 统一在 V1 视频路由入口执行鉴权。verify_token 会在 api_key 为空时+# 保留现有免认证行为,只有管理员显式配置后才会影响客户端。+router = new_router(dependencies=[Depends(base.verify_token)])_enable_redis = config.app.get("enable_redis", False)_redis_host = config.app.get("redis_host", "localhost")diff --git a/app/models/exception.py b/app/models/exception.pyindex d938cb5a..78ee1c95 100644--- a/app/models/exception.py+++ b/app/models/exception.py@@ -18,7 +18,10 @@ class HttpException(Exception):else:msg = f"HttpException: {status_code}, {task_id}, {message}\n{tb_str}"- if status_code == 400:+ # 400/401 都是可预期的客户端输入问题。尤其鉴权开启后,公网扫描可能+ # 产生大量无效 Key;使用 WARNING 既保留定位信息,也避免污染 ERROR+ # 告警。服务端配置错误和其它异常仍保持 ERROR。+ if status_code in (400, 401):logger.warning(msg)else:logger.error(msg)diff --git a/config.example.toml b/config.example.tomlindex 2b29c3ec..4a86c9a7 100644--- a/config.example.toml+++ b/config.example.toml@@ -13,6 +13,18 @@ listen_port = 8080[app]+# Optional protection for API routes and generated files under /tasks.+# Leave empty for local backward-compatible access. When configured, clients+# must send the same value in the x-api-key request header. Keep real keys only+# in config.toml and never commit them.+# API 路由和 /tasks 生成文件的可选保护。留空时保持本地免认证行为;+# 配置后客户端必须通过 x-api-key 请求头传入同一个值。+# Task artifact requests also require this header; a browser address bar cannot+# attach custom headers, so authenticated clients should download them via HTTP.+# 任务产物下载同样需要该请求头;浏览器地址栏无法附加自定义请求头,启用鉴权后+# 应由 API 客户端携带请求头下载。+api_key = ""+# -----------------------------------------------------------------------------# General / 通用设置# -----------------------------------------------------------------------------diff --git a/test/services/test_api_authentication.py b/test/services/test_api_authentication.pynew file mode 100644index 00000000..827f748b--- /dev/null+++ b/test/services/test_api_authentication.py@@ -0,0 +1,109 @@+import unittest+from unittest.mock import patch++from fastapi.testclient import TestClient++from app import asgi+from app.config import config+++class TestAPIAuthenticationHTTP(unittest.TestCase):+ """从真实 ASGI 入口验证 V1 API 的可选鉴权,覆盖两个业务路由组。"""++ def setUp(self):+ self.original_app_config = dict(config.app)+ self.client = TestClient(asgi.app)++ def tearDown(self):+ config.app.clear()+ config.app.update(self.original_app_config)++ def test_empty_key_preserves_existing_open_access(self):+ """默认空 Key 不要求请求头,保证旧客户端和本地 WebUI 继续工作。"""++ config.app["api_key"] = ""++ response = self.client.get("/api/v1/tasks")++ self.assertEqual(response.status_code, 200)++ def test_video_routes_require_matching_key_when_configured(self):+ """视频路由在启用保护后必须统一拒绝缺失和错误的 Key。"""++ config.app["api_key"] = "video-secret"++ missing = self.client.get("/api/v1/tasks")+ wrong = self.client.get(+ "/api/v1/tasks",+ headers={"x-api-key": "wrong"},+ )+ accepted = self.client.get(+ "/api/v1/tasks",+ headers={"x-api-key": "video-secret"},+ )++ self.assertEqual(missing.status_code, 401)+ self.assertEqual(wrong.status_code, 401)+ self.assertEqual(accepted.status_code, 200)++ def test_llm_routes_authenticate_before_request_validation(self):+ """LLM 路由必须先鉴权,未认证请求不得进入会产生费用的业务逻辑。"""++ config.app["api_key"] = "llm-secret"++ # 请求模型提供了默认值,空请求也可能真实调用大模型。这里隔离外部+ # 服务并核对调用次数,既验证鉴权顺序,也避免测试消耗用户的 API。+ with patch(+ "app.controllers.v1.llm.llm.generate_script",+ return_value="mocked script",+ ) as generate_script:+ missing = self.client.post("/api/v1/scripts", json={})+ accepted = self.client.post(+ "/api/v1/scripts",+ json={},+ headers={"x-api-key": "llm-secret"},+ )++ self.assertEqual(missing.status_code, 401)+ self.assertEqual(accepted.status_code, 200)+ generate_script.assert_called_once()++ def test_openapi_documents_api_key_header_for_v1_routes(self):+ """Swagger 必须显示 x-api-key,避免启用保护后只能靠猜测请求格式。"""++ schema = self.client.get("/openapi.json").json()+ parameters = schema["paths"]["/api/v1/tasks"]["get"]["parameters"]++ self.assertTrue(+ any(+ parameter["in"] == "header" and parameter["name"] == "x-api-key"+ for parameter in parameters+ )+ )++ def test_duplicate_api_key_headers_are_rejected(self):+ """重复凭据的解释可能因代理不同而变化,因此无论顺序都必须拒绝。"""++ config.app["api_key"] = "video-secret"++ correct_first = self.client.get(+ "/api/v1/tasks",+ headers=[+ ("x-api-key", "video-secret"),+ ("x-api-key", "wrong"),+ ],+ )+ wrong_first = self.client.get(+ "/api/v1/tasks",+ headers=[+ ("x-api-key", "wrong"),+ ("x-api-key", "video-secret"),+ ],+ )++ self.assertEqual(correct_first.status_code, 401)+ self.assertEqual(wrong_first.status_code, 401)+++if __name__ == "__main__":+ unittest.main()diff --git a/test/services/test_asgi_static_files.py b/test/services/test_asgi_static_files.pyindex a9a2c45d..ab85ae9c 100644--- a/test/services/test_asgi_static_files.py+++ b/test/services/test_asgi_static_files.py@@ -5,13 +5,21 @@ from pathlib import Pathfrom fastapi.testclient import TestClientfrom app import asgi+from app.config import configfrom app.utils import utilsclass TestTaskStaticFiles(unittest.TestCase):def setUp(self):+ self.original_app_config = dict(config.app)+ # 普通静态文件测试验证默认开放模式,不能依赖开发者本机是否启用了 Key。+ config.app["api_key"] = ""self.client = TestClient(asgi.app)+ def tearDown(self):+ config.app.clear()+ config.app.update(self.original_app_config)+def test_serves_regular_task_file(self):with tempfile.TemporaryDirectory(prefix="static-task-", dir=utils.task_dir()@@ -25,6 +33,57 @@ class TestTaskStaticFiles(unittest.TestCase):self.assertEqual(response.status_code, 200)self.assertEqual(response.text, "task artifact")+ def test_configured_key_protects_task_file(self):+ """配置 Key 后,任务文件必须拒绝缺失或错误凭据,只接受正确请求头。"""++ config.app["api_key"] = "task-file-secret"+ with tempfile.TemporaryDirectory(+ prefix="static-task-auth-", dir=utils.task_dir()+ ) as task_directory:+ task_path = Path(task_directory)+ artifact = task_path / "artifact.txt"+ artifact.write_text("protected task artifact", encoding="utf-8")+ artifact_url = f"/tasks/{task_path.name}/{artifact.name}"++ missing = self.client.get(artifact_url)+ wrong = self.client.get(+ artifact_url,+ headers={"x-api-key": "wrong"},+ )+ accepted = self.client.get(+ artifact_url,+ headers={"x-api-key": "task-file-secret"},+ )++ self.assertEqual(missing.status_code, 401)+ self.assertEqual(wrong.status_code, 401)+ self.assertEqual(accepted.status_code, 200)+ self.assertEqual(accepted.text, "protected task artifact")++ def test_configured_key_does_not_protect_health_or_docs(self):+ """健康检查和 Swagger 文档保持公开,方便部署探针与人工配置。"""++ config.app["api_key"] = "task-file-secret"++ 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 校验提前拒绝。"""++ config.app["api_key"] = "task-file-secret"++ response = self.client.options(+ "/tasks/example/artifact.txt",+ headers={+ "Origin": "https://example.com",+ "Access-Control-Request-Method": "GET",+ "Access-Control-Request-Headers": "x-api-key",+ },+ )++ self.assertEqual(response.status_code, 200)+def test_does_not_serve_symlink_to_file_outside_tasks(self):with (tempfile.TemporaryDirectory(@@ -44,9 +103,7 @@ class TestTaskStaticFiles(unittest.TestCase):except (NotImplementedError, OSError) as error:self.skipTest(f"symbolic links are unavailable: {error}")- response = self.client.get(- f"/tasks/{task_path.name}/{exposed_link.name}"- )+ response = self.client.get(f"/tasks/{task_path.name}/{exposed_link.name}")self.assertEqual(response.status_code, 404)self.assertNotIn(b"must not be served", response.content)diff --git a/test/services/test_controller_base.py b/test/services/test_controller_base.pyindex 6b16c5c6..cf743f85 100644--- a/test/services/test_controller_base.py+++ b/test/services/test_controller_base.py@@ -81,7 +81,7 @@ class TestControllerAuthentication(unittest.TestCase):with (patch.object(base, "uuid4", return_value=self.generated_task_id),- patch("app.models.exception.logger.error") as log_error,+ patch("app.models.exception.logger.warning") as log_warning,):with self.assertRaises(HttpException):base.verify_token(@@ -93,10 +93,10 @@ class TestControllerAuthentication(unittest.TestCase):))- logged_error = log_error.call_args.args[0]- self.assertIn(str(self.generated_task_id), logged_error)- self.assertNotIn(malicious_task_id, logged_error)- self.assertNotIn("forged-log-entry", logged_error)+ logged_warning = log_warning.call_args.args[0]+ self.assertIn(str(self.generated_task_id), logged_warning)+ self.assertNotIn(malicious_task_id, logged_warning)+ self.assertNotIn("forged-log-entry", logged_warning)def test_verify_token_accepts_matching_key(self):"""配置了 API Key 时,相同请求头必须正常通过鉴权。"""@@ -106,6 +106,17 @@ class TestControllerAuthentication(unittest.TestCase):self.assertIsNone(result)+ def test_verify_token_allows_requests_when_key_is_not_configured(self):+ """未配置 Key 时必须保留历史免认证行为,避免本地升级后中断。"""++ config.app.pop("api_key", None)+ self.assertIsNone(base.verify_token(self._request()))++ for configured_key in (None, ""):+ with self.subTest(configured_key=configured_key):+ config.app["api_key"] = configured_key+ self.assertIsNone(base.verify_token(self._request()))+def test_verify_token_rejects_missing_or_wrong_key(self):"""缺失和错误的 API Key 都必须返回 401,并保留客户端 request ID,@@ -123,7 +134,32 @@ class TestControllerAuthentication(unittest.TestCase):base.verify_token(self._request(headers))self.assertEqual(raised.exception.status_code, 401)- self.assertIn("invalid token", raised.exception.message)+ self.assertEqual(raised.exception.message, "invalid API key")++ def test_verify_token_rejects_non_string_configuration(self):+ """非字符串配置应明确报错,且错误中不得暴露配置内容。"""++ config.app["api_key"] = ["unexpected", "value"]++ with self.assertRaises(HttpException) as raised:+ base.verify_token(self._request())++ self.assertEqual(raised.exception.status_code, 500)+ self.assertEqual(+ raised.exception.message,+ "API authentication is misconfigured",+ )++ def test_verify_token_handles_unicode_without_server_error(self):+ """非 ASCII Header 不得触发 compare_digest TypeError 或返回 500。"""++ config.app["api_key"] = "密钥-é"+ self.assertIsNone(base.verify_token(self._request({"x-api-key": "密钥-é"})))++ with self.assertRaises(HttpException) as raised:+ base.verify_token(self._request({"x-api-key": "错误-é"}))++ self.assertEqual(raised.exception.status_code, 401)def test_new_router_preserves_common_prefix_and_dependencies(self):"""所有 V1 路由都应复用统一前缀,并仅在传入时设置鉴权依赖。"""diff --git a/test/services/test_controller_video.py b/test/services/test_controller_video.pyindex f3b2998a..5024a106 100644--- a/test/services/test_controller_video.py+++ b/test/services/test_controller_video.py@@ -375,8 +375,15 @@ class TestVideoControllerDeleteHTTP(unittest.TestCase):"""DELETE /api/v1/tasks/{task_id} 的真实 HTTP 级回归测试。"""def setUp(self):+ self.original_app_config = dict(config.app)+ # 这些用例只验证任务删除协议;鉴权行为由独立测试覆盖。+ config.app["api_key"] = ""self.client = TestClient(asgi.app)+ def tearDown(self):+ config.app.clear()+ config.app.update(self.original_app_config)+def _seed_completed_task(self, task_id: str) -> str:"""创建一个已完成的任务,返回其存储目录路径。"""