fix(video-generation): follow same-origin MiniMax API redirects (#8458)

This commit is contained in:
Nan Gao 2026-11-21 16:43:42 +08:00 committed by GitHub
parent db55b1322f
commit 317ced8030
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 174 additions and 9 deletions

View File

@ -160,6 +160,10 @@ accepts `MINIMAX_VIDEO_RESOLUTION` and `MINIMAX_VIDEO_DURATION` (integer seconds
Unset overrides use the provider defaults. Invalid duration strings fail before
the script submits a request.
MiniMax submission, status polling, and file lookup each follow up to five
HTTP 307 or 308 redirects within the configured API origin (scheme, hostname,
and effective port). Each redirect preserves the request method and body.
Generated videos download over HTTPS on port 443. The skill checks the
provider's download-host allowlist before the first request and after each
redirect, up to five redirects. Gemini sends its API key only to its API host

View File

@ -19,6 +19,7 @@ MINIMAX_VIDEO_HOSTS = {
}
MINIMAX_OSS_ENDPOINTS = {"oss-cn-wulanchabu.aliyuncs.com", "oss-cn-shanghai.aliyuncs.com"}
MAX_DOWNLOAD_REDIRECTS = 5
MAX_MINIMAX_API_REDIRECTS = 5
def _resolve_provider(override_env: str, existing_provider: str, has_existing_creds: bool) -> str:
@ -56,6 +57,45 @@ def _require_success(response: requests.Response) -> None:
raise ValueError(f"Unexpected HTTP status {response.status_code} from video provider")
def _api_origin(url: str) -> tuple[str, str, int]:
parsed = urlsplit(url)
host = parsed.hostname
if parsed.scheme not in {"http", "https"} or not host:
raise ValueError("Invalid MiniMax API redirect origin")
port = parsed.port
# Check the entire authority, including brackets for an IPv6 literal.
# hostname/port alone would discard user information or stray delimiters.
host_field = parsed.netloc if port is None else parsed.netloc.rsplit(":", 1)[0]
expected = f"[{host}]" if ":" in host else host
if host_field.lower() != expected.lower():
raise ValueError("Invalid MiniMax API redirect authority")
default_port = 443 if parsed.scheme == "https" else 80
return parsed.scheme, host, default_port if port is None else port
def _minimax_api_request(send, url: str, *, timeout: int, **kwargs) -> requests.Response:
response = send(url, timeout=timeout, allow_redirects=False, **kwargs)
if response.status_code in (307, 308):
origin = _api_origin(response.request.url)
with requests.Session() as session:
for _ in range(MAX_MINIMAX_API_REDIRECTS):
# Requests prepares the redirect with the original method and body,
# and resolves Location against the full URL (including GET params).
target = response.next
if target is None:
raise ValueError("MiniMax API redirect has no destination")
if _api_origin(target.url) != origin:
raise ValueError("MiniMax API redirect changes origin")
settings = session.merge_environment_settings(target.url, {}, None, None, None)
response = session.send(target, timeout=timeout, allow_redirects=False, **settings)
if response.status_code not in (307, 308):
break
else:
raise ValueError("Too many MiniMax API redirects")
_require_success(response)
return response
def _guess_mime(image_path: str) -> str:
ext = os.path.splitext(image_path)[1].lower()
mime_types = {
@ -80,14 +120,13 @@ def _to_data_url(image_path: str) -> str:
def _poll_video_task(host: str, auth: str, task_id: str, max_attempts: int = 120, interval: int = 3) -> str:
for _ in range(max_attempts):
response = requests.get(
response = _minimax_api_request(
requests.get,
f"{host}/v1/query/video_generation",
headers={"Authorization": auth},
params={"task_id": task_id},
timeout=30,
allow_redirects=False,
)
_require_success(response)
payload = response.json()
status = payload.get("status")
if status == "Success":
@ -139,14 +178,13 @@ def _poll_gemini_operation(api_key: str, operation_name: str, max_attempts: int
def _retrieve_file_url(host: str, auth: str, file_id: str) -> str:
response = requests.get(
response = _minimax_api_request(
requests.get,
f"{host}/v1/files/retrieve",
headers={"Authorization": auth},
params={"file_id": file_id},
timeout=30,
allow_redirects=False,
)
_require_success(response)
payload = response.json()
_check_base_resp(payload)
return payload["file"]["download_url"]
@ -223,14 +261,13 @@ def _generate_video_minimax(prompt: str, reference_images: list[str], output_fil
raise ValueError(error) from exc
if reference_images:
body["first_frame_image"] = _to_data_url(reference_images[0])
response = requests.post(
response = _minimax_api_request(
requests.post,
f"{host}/v1/video_generation",
headers={"Authorization": auth, "Content-Type": "application/json"},
json=body,
timeout=60,
allow_redirects=False,
)
_require_success(response)
payload = response.json()
_check_base_resp(payload)
task_id = payload["task_id"]

View File

@ -1,3 +1,4 @@
import json
import sys
from pathlib import Path
@ -101,6 +102,129 @@ def test_minimax_full_flow(monkeypatch, tmp_path, video_settings):
assert "successfully" in msg.lower()
def mock_http_transport(monkeypatch, responses):
"""Record the prepared requests and return the scripted responses in order."""
sent = []
def send(adapter, request, **kwargs):
assert len(sent) < len(responses), f"Unexpected {request.method} {request.url}"
status, payload = responses[len(sent)]
sent.append(request)
response = requests.Response()
response.request = request
response.url = request.url
response.status_code = status
if isinstance(payload, str):
response.headers["Location"] = payload
payload = b""
elif isinstance(payload, dict):
payload = json.dumps(payload).encode()
response._content = payload
return response
monkeypatch.setattr(requests.adapters.HTTPAdapter, "send", send)
return sent
def test_minimax_api_follows_same_origin_redirects_through_generation(monkeypatch, tmp_path):
host = "https://minimax.example:8443"
monkeypatch.setenv("MINIMAX_API_HOST", host)
monkeypatch.setenv("MINIMAX_API_KEY", "test-key")
sent = mock_http_transport(monkeypatch, [
(307, "submit/next"),
(308, f"{host}/submit/final"),
(200, {"task_id": "T1"}),
(307, "?task_id=T1&step=2"),
(308, f"{host}/poll/final?cursor=next"),
(200, {"status": "Success", "file_id": "F1"}),
(308, "/retrieve?file_id=F1"),
(307, f"{host}/retrieve/final"),
(200, {"file": {"download_url": MINIMAX_VIDEO}}),
(200, b"video"),
])
prompt = tmp_path / "prompt.txt"
prompt.write_text("a cat runs", encoding="utf-8")
output = tmp_path / "video.mp4"
vid.generate_video(str(prompt), [], str(output))
assert [(request.method, request.url) for request in sent] == [
("POST", f"{host}/v1/video_generation"),
("POST", f"{host}/v1/submit/next"),
("POST", f"{host}/submit/final"),
("GET", f"{host}/v1/query/video_generation?task_id=T1"),
("GET", f"{host}/v1/query/video_generation?task_id=T1&step=2"),
("GET", f"{host}/poll/final?cursor=next"),
("GET", f"{host}/v1/files/retrieve?file_id=F1"),
("GET", f"{host}/retrieve?file_id=F1"),
("GET", f"{host}/retrieve/final"),
("GET", MINIMAX_VIDEO),
]
assert json.loads(sent[0].body) == {"model": "MiniMax-Hailuo-2.3", "prompt": "a cat runs"}
for request in sent[:3]:
assert request.body == sent[0].body
assert request.headers["Content-Type"] == "application/json"
assert all(request.body is None for request in sent[3:])
assert all(request.headers["Authorization"] == "Bearer test-key" for request in sent[:-1])
assert "Authorization" not in sent[-1].headers
assert output.read_bytes() == b"video"
@pytest.mark.parametrize("destination", [
"http://minimax.example/submit",
"https://minimax.example:8443/submit",
"https://filecdn.minimax.chat/submit",
"https://user@minimax.example/submit",
"https://minimax.example:/submit",
])
def test_minimax_api_rejects_untrusted_redirect_before_sending(monkeypatch, tmp_path, destination):
host = "https://minimax.example"
monkeypatch.setenv("MINIMAX_API_HOST", host)
monkeypatch.setenv("MINIMAX_API_KEY", "test-key")
sent = mock_http_transport(monkeypatch, [(307, "/submit/next"), (308, destination)])
output = tmp_path / "video.mp4"
output.write_bytes(b"existing video")
with pytest.raises(ValueError):
vid._generate_video_minimax("a cat runs", [], str(output))
assert [request.url for request in sent] == [f"{host}/v1/video_generation", f"{host}/submit/next"]
assert output.read_bytes() == b"existing video"
@pytest.mark.parametrize("count", [5, 6])
def test_minimax_api_limits_same_origin_redirects(monkeypatch, count):
host = "https://minimax.example:443"
responses = [(307, f"https://minimax.example/step/{i + 1}") for i in range(count)]
responses.append((200, {"file": {"download_url": MINIMAX_VIDEO}}))
sent = mock_http_transport(monkeypatch, responses)
if count == 5:
assert vid._retrieve_file_url(host, "Bearer test-key", "F1") == MINIMAX_VIDEO
else:
with pytest.raises(ValueError):
vid._retrieve_file_url(host, "Bearer test-key", "F1")
assert len(sent) == 6
@pytest.mark.parametrize("status", [300, 301, 302, 303, 304, 305, 306])
def test_minimax_api_rejects_other_3xx(monkeypatch, status):
host = "https://minimax.example"
sent = mock_http_transport(monkeypatch, [(status, "/next")])
with pytest.raises(ValueError, match=str(status)):
vid._poll_video_task(host, "Bearer test-key", "T1", max_attempts=1)
assert [request.url for request in sent] == [f"{host}/v1/query/video_generation?task_id=T1"]
@pytest.mark.parametrize("status", [307, 308])
def test_minimax_api_rejects_redirect_without_location(monkeypatch, status):
host = "https://minimax.example"
sent = mock_http_transport(monkeypatch, [(status, b"")])
with pytest.raises(ValueError, match="no destination"):
vid._retrieve_file_url(host, "Bearer test-key", "F1")
assert [request.url for request in sent] == [f"{host}/v1/files/retrieve?file_id=F1"]
@pytest.mark.parametrize("duration", ["abc", "2.5", "²"])
def test_minimax_rejects_invalid_duration(monkeypatch, tmp_path, duration):
monkeypatch.setenv("MINIMAX_API_KEY", "m")