Skip to content

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

fix(video): validate subtitle font paths

harry0703ad5496f1b729
diff --git a/app/controllers/v1/video.py b/app/controllers/v1/video.py
index 8c90c58e..862fdf51 100644
--- a/app/controllers/v1/video.py
+++ b/app/controllers/v1/video.py
@@ -207,6 +207,16 @@ def create_task(
task_id = utils.get_uuid()
request_id = base.get_task_id(request)
try:
+ if (
+ stop_at == "video"
+ and isinstance(body, TaskVideoRequest)
+ and body.subtitle_enabled
+ ):
+ # 字体名可由 API 客户端直接提交,不能等到后台渲染时才发现路径越界。
+ # 这里与渲染层共用目录边界校验,让非法请求在创建付费任务前返回 400。
+ file_security.resolve_path_within_directory(
+ utils.font_dir(), body.font_name or "STHeitiMedium.ttc"
+ )
task = {
"task_id": task_id,
"request_id": request_id,
diff --git a/app/services/video.py b/app/services/video.py
index 7b9dea41..fdb34d4e 100644
--- a/app/services/video.py
+++ b/app/services/video.py
@@ -1239,7 +1239,12 @@ def generate_video(
if params.subtitle_enabled:
if not params.font_name:
params.font_name = "STHeitiMedium.ttc"
- font_path = os.path.join(utils.font_dir(), params.font_name)
+ # API 入口虽已预检,WebUI、CLI 和内部调用仍可直接进入渲染层;
+ # 始终以真实路径校验字体必须留在 resource/fonts,阻断绝对路径、
+ # ../ 穿越及指向目录外的符号链接,再交给 PIL/MoviePy 打开。
+ font_path = file_security.resolve_path_within_directory(
+ utils.font_dir(), params.font_name
+ )
if os.name == "nt":
font_path = font_path.replace("\\", "/")
diff --git a/test/services/test_controller_video.py b/test/services/test_controller_video.py
index 8ad09914..4fa97792 100644
--- a/test/services/test_controller_video.py
+++ b/test/services/test_controller_video.py
@@ -16,7 +16,12 @@ from app.controllers.manager.base_manager import TaskQueueFullError
from app.controllers.v1 import video as video_controller
from app.models import const
from app.models.exception import HttpException
-from app.models.schema import TaskDeletionResponse, TaskListResponse, TaskQueryResponse
+from app.models.schema import (
+ TaskDeletionResponse,
+ TaskListResponse,
+ TaskQueryResponse,
+ TaskVideoRequest,
+)
from app.services import material_upload
from app.services import state as sm
from app.utils import utils
@@ -119,6 +124,81 @@ class TestVideoControllerTasks(unittest.TestCase):
def _request():
return SimpleNamespace(headers={"x-task-id": "request-123"})
+ def test_video_task_rejects_font_outside_font_directory_before_queueing(self):
+ """非法字体路径必须在任务入队前返回 400,不产生付费后台任务。"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ font_dir = Path(temp_dir, "fonts")
+ font_dir.mkdir()
+ outside = Path(temp_dir, "outside.ttf")
+ outside.write_bytes(b"not a font")
+
+ for font_name in (str(outside), "../outside.ttf"):
+ with (
+ self.subTest(font_name=font_name),
+ patch.object(video_controller.utils, "font_dir", return_value=str(font_dir)),
+ patch.object(video_controller.sm.state, "update_task") as update_task,
+ patch.object(video_controller.task_manager, "add_task") as add_task,
+ ):
+ body = TaskVideoRequest(video_subject="Coffee", font_name=font_name)
+ with self.assertRaises(HttpException) as raised:
+ video_controller.create_task(self._request(), body, stop_at="video")
+
+ self.assertEqual(raised.exception.status_code, 400)
+ update_task.assert_not_called()
+ add_task.assert_not_called()
+
+ def test_video_task_rejects_font_symlink_outside_font_directory(self):
+ """即使路径字符串位于字体目录内,也不能借符号链接读取目录外文件。"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ font_dir = Path(temp_dir, "fonts")
+ font_dir.mkdir()
+ outside = Path(temp_dir, "outside.ttf")
+ outside.write_bytes(b"not a font")
+ try:
+ (font_dir / "linked.ttf").symlink_to(outside)
+ except (NotImplementedError, OSError) as exc:
+ self.skipTest(f"symlinks are unavailable: {exc}")
+
+ with (
+ patch.object(video_controller.utils, "font_dir", return_value=str(font_dir)),
+ patch.object(video_controller.sm.state, "update_task") as update_task,
+ patch.object(video_controller.task_manager, "add_task") as add_task,
+ ):
+ body = TaskVideoRequest(video_subject="Coffee", font_name="linked.ttf")
+ with self.assertRaises(HttpException) as raised:
+ video_controller.create_task(self._request(), body, stop_at="video")
+
+ self.assertEqual(raised.exception.status_code, 400)
+ update_task.assert_not_called()
+ add_task.assert_not_called()
+
+ def test_video_task_accepts_font_inside_directory_and_ignores_disabled_subtitles(self):
+ """正常字体仍能入队,关闭字幕时保留原有的未使用字体兼容行为。"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ font_dir = Path(temp_dir, "fonts")
+ font_dir.mkdir()
+ (font_dir / "custom.ttf").write_bytes(b"font file")
+ cases = (
+ TaskVideoRequest(video_subject="Coffee", font_name="custom.ttf"),
+ TaskVideoRequest(
+ video_subject="Coffee", subtitle_enabled=False, font_name="../unused.ttf"
+ ),
+ )
+ for body in cases:
+ with (
+ self.subTest(font_name=body.font_name, enabled=body.subtitle_enabled),
+ patch.object(video_controller.utils, "font_dir", return_value=str(font_dir)),
+ patch.object(video_controller.sm.state, "update_task") as update_task,
+ patch.object(video_controller.task_manager, "add_task") as add_task,
+ ):
+ response = video_controller.create_task(
+ self._request(), body, stop_at="video"
+ )
+
+ self.assertEqual(response["status"], 200)
+ update_task.assert_called_once()
+ add_task.assert_called_once()
+
def test_create_task_queues_requested_pipeline_stage(self):
"""创建任务应持久化初始状态,并把原请求模型与停止阶段交给队列。"""
body = MagicMock()
@@ -371,6 +451,29 @@ class TestVideoControllerTasks(unittest.TestCase):
self.assertEqual(raised.exception.status_code, 404)
+class TestVideoControllerCreateHTTP(unittest.TestCase):
+ """验证越界字体在真实 HTTP 入口返回 400,而不是创建后台任务。"""
+
+ 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 test_video_request_rejects_font_path_traversal(self):
+ with patch.object(video_controller.task_manager, "add_task") as add_task:
+ response = self.client.post(
+ "/api/v1/videos",
+ json={"video_subject": "Coffee", "font_name": "../../README.md"},
+ )
+
+ self.assertEqual(response.status_code, 400)
+ add_task.assert_not_called()
+
+
class TestVideoControllerDeleteHTTP(unittest.TestCase):
"""DELETE /api/v1/tasks/{task_id} 的真实 HTTP 级回归测试。"""
diff --git a/test/services/test_video.py b/test/services/test_video.py
index b16e0706..53a18cef 100644
--- a/test/services/test_video.py
+++ b/test/services/test_video.py
@@ -64,6 +64,47 @@ class TestVideoService(unittest.TestCase):
vd._runtime_disabled_video_codecs.clear()
vd._ffmpeg_encoder_exists.cache_clear()
+ def test_generate_video_rejects_font_outside_directory_before_opening_media(self):
+ """WebUI、CLI 或内部调用绕过 API 时,渲染层也必须阻断越界字体。"""
+ with tempfile.TemporaryDirectory() as temp_dir:
+ font_dir = Path(temp_dir, "fonts")
+ font_dir.mkdir()
+ outside = Path(temp_dir, "outside.ttf")
+ outside.write_bytes(b"not a font")
+
+ for font_name in (str(outside), "../outside.ttf"):
+ with (
+ self.subTest(font_name=font_name),
+ patch.object(vd.utils, "font_dir", return_value=str(font_dir)),
+ patch.object(vd, "_open_video_clip_quietly") as open_video,
+ ):
+ params = vd.VideoParams(video_subject="Coffee", font_name=font_name)
+ with self.assertRaisesRegex(ValueError, "outside the allowed directory"):
+ vd.generate_video(
+ video_path="unused.mp4",
+ audio_path="unused.mp3",
+ subtitle_path="unused.srt",
+ output_file="unused-output.mp4",
+ params=params,
+ )
+ open_video.assert_not_called()
+
+ def test_generate_video_accepts_bundled_font_before_opening_media(self):
+ """内置字体必须继续通过校验,不能阻断默认字幕生成链路。"""
+ params = vd.VideoParams(video_subject="Coffee", font_name="STHeitiMedium.ttc")
+ with patch.object(
+ vd, "_open_video_clip_quietly", side_effect=RuntimeError("media reached")
+ ) as open_video:
+ with self.assertRaisesRegex(RuntimeError, "media reached"):
+ vd.generate_video(
+ video_path="unused.mp4",
+ audio_path="unused.mp3",
+ subtitle_path="unused.srt",
+ output_file="unused-output.mp4",
+ params=params,
+ )
+ open_video.assert_called_once_with("unused.mp4")
+
def test_subtitle_spring_animation_keeps_color_and_mask_aligned(self):
"""
弹跳动画必须同步缩放颜色帧和透明蒙版。