Skip to content

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

fix(security): restrict custom audio file paths

YANG10244a82f8ce6772
diff --git a/app/services/task.py b/app/services/task.py
index 7ac812eb..f7e52b9a 100644
--- a/app/services/task.py
+++ b/app/services/task.py
@@ -356,7 +356,12 @@ def save_script_data(task_id, video_script, video_terms, params):
task_artifacts.write_script_data(task_id, script_data)
-def resolve_custom_audio_file(task_id: str, custom_audio_file: str | None) -> str:
+def resolve_custom_audio_file(
+ task_id: str,
+ custom_audio_file: str | None,
+ *,
+ allow_server_file_input: bool = False,
+) -> str:
requested_file = (custom_audio_file or "").strip()
if not requested_file:
return ""
@@ -370,6 +375,20 @@ def resolve_custom_audio_file(task_id: str, custom_audio_file: str | None) -> st
except ValueError as exc:
task_dir_error = exc
+ # A missing path that otherwise stays inside the task directory is safe to
+ # report precisely. Paths outside that boundary use the same generic error
+ # regardless of whether they exist, so callers cannot probe the host filesystem.
+ if str(task_dir_error) == "file does not exist":
+ raise task_dir_error
+
+ # HTTP requests and other untrusted callers must never turn a submitted path
+ # into a server-side file read. WebUI uploads already live in the task directory;
+ # only the local CLI explicitly opts into resolving files elsewhere on the host.
+ if not allow_server_file_input:
+ raise ValueError(
+ "custom audio file must be stored within the current task directory"
+ ) from task_dir_error
+
server_audio_file = path.realpath(
requested_file
if path.isabs(requested_file)
@@ -455,7 +474,14 @@ def _resolve_reusable_voice_preview(
return preview_file, math.ceil(duration), sub_maker
-def generate_audio(task_id, params, video_script, voice_preview=None):
+def generate_audio(
+ task_id,
+ params,
+ video_script,
+ voice_preview=None,
+ *,
+ allow_server_file_input: bool = False,
+):
"""
Generate audio for the video script.
If a custom audio file is provided, it will be used directly.
@@ -472,7 +498,9 @@ def generate_audio(task_id, params, video_script, voice_preview=None):
requested_custom_audio_file = getattr(params, "custom_audio_file", None)
try:
custom_audio_file = resolve_custom_audio_file(
- task_id, requested_custom_audio_file
+ task_id,
+ requested_custom_audio_file,
+ allow_server_file_input=allow_server_file_input,
)
except ValueError as exc:
_mark_task_failed(
@@ -1188,6 +1216,7 @@ def _run_pipeline(
stop_at: str = "video",
voice_preview: dict | None = None,
loomloom_video_request: loomloom.LoomLoomConfirmedVideoRequest | None = None,
+ allow_server_file_input: bool = False,
):
logger.info(f"start task: {task_id}, stop_at: {stop_at}")
sm.state.update_task(task_id, state=const.TASK_STATE_PROCESSING, progress=5)
@@ -1288,6 +1317,7 @@ def _run_pipeline(
params,
video_script,
voice_preview=voice_preview,
+ allow_server_file_input=allow_server_file_input,
)
if not audio_file:
return _mark_task_failed(
@@ -1439,8 +1469,14 @@ def start(
stop_at: str = "video",
voice_preview: dict | None = None,
loomloom_video_request: loomloom.LoomLoomConfirmedVideoRequest | None = None,
+ allow_server_file_input: bool = False,
):
- """执行任务流水线,并确保未预期异常也会转换成可查询的失败状态。"""
+ """
+ 执行任务流水线,并确保未预期异常也会转换成可查询的失败状态。
+
+ ``allow_server_file_input`` 只供本机 CLI 使用。HTTP API 和 WebUI 必须保持
+ 默认值,让自定义音频始终受当前任务目录约束。
+ """
try:
return _run_pipeline(
task_id,
@@ -1448,6 +1484,7 @@ def start(
stop_at=stop_at,
voice_preview=voice_preview,
loomloom_video_request=loomloom_video_request,
+ allow_server_file_input=allow_server_file_input,
)
except Exception as exc:
logger.exception(
diff --git a/cli.py b/cli.py
index 022bcc9e..4f60baab 100644
--- a/cli.py
+++ b/cli.py
@@ -778,7 +778,15 @@ def run_cli(argv: Sequence[str] | None = None) -> int:
task_id = args.task_id or utils.get_uuid()
logger.info(f"start CLI task: task_id={task_id}, stop_at={args.stop_at}")
try:
- result = tm.start(task_id=task_id, params=params, stop_at=args.stop_at)
+ result = tm.start(
+ task_id=task_id,
+ params=params,
+ stop_at=args.stop_at,
+ # CLI inputs come from the local operator rather than an HTTP client.
+ # Preserve support for arbitrary local audio paths without weakening the
+ # task service's secure default for API and WebUI callers.
+ allow_server_file_input=True,
+ )
except Exception as exc:
logger.exception(
f"CLI task failed with an unexpected error: task_id={task_id}, error={exc}"
diff --git a/test/services/test_cli.py b/test/services/test_cli.py
index 9311ad70..71133e19 100644
--- a/test/services/test_cli.py
+++ b/test/services/test_cli.py
@@ -69,6 +69,7 @@ class TestCli(unittest.TestCase):
self.assertEqual(kwargs["task_id"], "task-123")
self.assertEqual(kwargs["stop_at"], "script")
self.assertEqual(kwargs["params"].video_subject, "命令行测试")
+ self.assertIs(kwargs["allow_server_file_input"], True)
print_mock.assert_called_once()
def test_run_cli_returns_error_when_task_fails(self):
diff --git a/test/services/test_task.py b/test/services/test_task.py
index eb0cb201..dffe4579 100644
--- a/test/services/test_task.py
+++ b/test/services/test_task.py
@@ -713,7 +713,61 @@ class TestTaskService(unittest.TestCase):
self.assertIsNone(sub_maker)
tts.assert_not_called()
- def test_generate_audio_accepts_server_side_custom_file(self):
+ def test_generate_audio_rejects_server_side_custom_file_by_default(self):
+ task_id = "test-custom-audio-untrusted-server-side"
+ task_dir = utils.task_dir(task_id)
+ state = MemoryState()
+
+ with tempfile.NamedTemporaryFile(suffix=".mp3") as server_audio:
+ server_audio.write(b"fake audio")
+ server_audio.flush()
+ params = VideoParams(
+ video_subject="custom audio",
+ video_script="",
+ custom_audio_file=server_audio.name,
+ voice_name="test-voice",
+ )
+
+ try:
+ with (
+ patch.object(tm.voice, "tts") as tts,
+ patch.object(tm.voice, "get_audio_duration") as get_duration,
+ patch.object(tm.sm, "state", state),
+ ):
+ audio_file, audio_duration, result_sub_maker = tm.generate_audio(
+ task_id, params, "script"
+ )
+ finally:
+ shutil.rmtree(task_dir, ignore_errors=True)
+
+ self.assertIsNone(audio_file)
+ self.assertIsNone(audio_duration)
+ self.assertIsNone(result_sub_maker)
+ tts.assert_not_called()
+ get_duration.assert_not_called()
+ failed_task = state.get_task(task_id)
+ self.assertEqual(failed_task["failed_stage"], "audio")
+ self.assertIn("current task directory", failed_task["error"])
+
+ def test_external_custom_audio_error_does_not_reveal_file_existence(self):
+ task_id = "test-custom-audio-existence-oracle"
+ task_dir = utils.task_dir(task_id)
+
+ with tempfile.NamedTemporaryFile(suffix=".mp3") as server_audio:
+ external_paths = [server_audio.name, f"{server_audio.name}.missing"]
+ errors = []
+ try:
+ for external_path in external_paths:
+ with self.assertRaises(ValueError) as raised:
+ tm.resolve_custom_audio_file(task_id, external_path)
+ errors.append(str(raised.exception))
+ finally:
+ shutil.rmtree(task_dir, ignore_errors=True)
+
+ self.assertEqual(errors[0], errors[1])
+ self.assertIn("current task directory", errors[0])
+
+ def test_generate_audio_accepts_server_side_custom_file_for_trusted_cli(self):
task_id = "test-custom-audio-server-side"
task_dir = utils.task_dir(task_id)
@@ -733,7 +787,10 @@ class TestTaskService(unittest.TestCase):
patch.object(tm.voice, "get_audio_duration", return_value=6),
):
audio_file, audio_duration, result_sub_maker = tm.generate_audio(
- task_id, params, "script"
+ task_id,
+ params,
+ "script",
+ allow_server_file_input=True,
)
finally:
shutil.rmtree(task_dir, ignore_errors=True)
@@ -960,6 +1017,37 @@ class TestTaskService(unittest.TestCase):
self.assertEqual(result, expected)
generate_final.assert_not_called()
+ def test_start_forwards_trusted_server_file_flag_to_audio_stage(self):
+ params = VideoParams(video_subject="CLI custom audio")
+
+ with (
+ patch.object(tm.utils, "check_ffmpeg_ready", return_value=True),
+ patch.object(tm, "generate_script", return_value="generated script"),
+ patch.object(tm, "generate_terms", return_value=["audio"]),
+ patch.object(tm, "save_script_data"),
+ patch.object(
+ tm,
+ "generate_audio",
+ return_value=("audio.mp3", 5, None),
+ ) as generate_audio,
+ patch.object(tm.sm.state, "update_task"),
+ ):
+ result = tm.start(
+ "trusted-cli-audio",
+ params,
+ stop_at="audio",
+ allow_server_file_input=True,
+ )
+
+ self.assertEqual(result, {"audio_file": "audio.mp3", "audio_duration": 5})
+ generate_audio.assert_called_once_with(
+ "trusted-cli-audio",
+ params,
+ "generated script",
+ voice_preview=None,
+ allow_server_file_input=True,
+ )
+
def test_start_completes_video_without_cross_posting(self):
"""
完整任务在自动发布未配置时仍应稳定完成,并把所有中间产物写入最终