Skip to content

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

fix(api): parse byte ranges with HTTP grammar

Rudy Celekli3ab8a36464c7
diff --git a/app/controllers/v1/video.py b/app/controllers/v1/video.py
index 20539aba..6a7f7391 100644
--- a/app/controllers/v1/video.py
+++ b/app/controllers/v1/video.py
@@ -172,11 +172,16 @@ def _parse_byte_range(
try:
# 视频播放器这里只需要单段 bytes range。拒绝多段请求可以避免返回体
# 与 Content-Range 不一致,也避免异常字符串落入 int() 产生 500。
- if not range_header.startswith("bytes=") or "," in range_header:
+ unit, separator, positions = range_header.strip(" \t").partition("=")
+ if unit.lower() != "bytes" or not separator or "," in positions:
raise ValueError("unsupported range format")
- start_text, end_text = range_header[6:].split("-", 1)
+ start_text, end_text = positions.split("-", 1)
if not start_text and not end_text:
raise ValueError("empty range")
+ # HTTP positions use ASCII DIGIT, not Python's broader int syntax.
+ if any(value and not (value.isascii() and value.isdigit())
+ for value in (start_text, end_text)):
+ raise ValueError("invalid byte position")
if not start_text:
suffix_length = int(end_text)
diff --git a/test/services/test_http_byte_range_grammar.py b/test/services/test_http_byte_range_grammar.py
new file mode 100644
index 00000000..2c3a1578
--- /dev/null
+++ b/test/services/test_http_byte_range_grammar.py
@@ -0,0 +1,32 @@
+from unittest.mock import patch
+
+import pytest
+from fastapi.testclient import TestClient
+
+from app import asgi
+from app.config import config
+from app.controllers.v1 import video as controller
+from app.models.exception import HttpException
+
+
[email protected]('header', ['Bytes=1-3', 'BYTES=-3'])
+def test_stream_accepts_case_insensitive_byte_unit(tmp_path, header):
+ (tmp_path / 'clip.mp4').write_bytes(b'0123456789')
+ with patch.dict(config.app, {'api_key': ''}), patch.object(controller.utils, 'task_dir', return_value=str(tmp_path)):
+ response = TestClient(asgi.get_application()).get('/api/v1/stream/clip.mp4', headers={'Range': header})
+ assert response.status_code == 206
+ assert response.content == (b'123' if header == 'Bytes=1-3' else b'789')
+
+
[email protected]('header', ['bytes=+1-3', 'bytes=1_0-', 'bytes=1-+3', 'bytes=-+3', 'bytes= 1-3'])
+def test_stream_rejects_non_http_numeric_syntax(tmp_path, header):
+ (tmp_path / 'clip.mp4').write_bytes(b'01234567890123456789')
+ with patch.dict(config.app, {'api_key': ''}), patch.object(controller.utils, 'task_dir', return_value=str(tmp_path)):
+ response = TestClient(asgi.get_application()).get('/api/v1/stream/clip.mp4', headers={'Range': header})
+ assert response.status_code == 416
+
+
+def test_byte_positions_require_ascii_digits():
+ with pytest.raises(HttpException) as raised:
+ controller._parse_byte_range('bytes=١-٣', 10, 'fixture')
+ assert raised.value.status_code == 416