Skip to content

Suno-style web UI for a self-hosted MiniMax-Music3 inference server

Harden inference API access checks

Adam B.bb7e5d3f971b
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d6afcf8..2f5aaaa 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -13,9 +13,10 @@ jobs:
- uses: actions/setup-python@v6
with:
python-version: "3.12"
- - run: python -m pip install ruff==0.17.2
+ - run: python -m pip install ruff==0.17.2 fastapi==0.162.0 httpx==0.28.1
- run: ruff check --select E4,E7,E9,F inference/
- run: python -m compileall -q inference/
+ - run: python -m unittest discover -s inference -p 'test_*.py'
test:
runs-on: ubuntu-latest
diff --git a/inference/server.py b/inference/server.py
index f4e9be2..787ca73 100644
--- a/inference/server.py
+++ b/inference/server.py
@@ -30,6 +30,7 @@ Requests are rendered one at a time; generation is ~3x slower than realtime on a
"""
import argparse
import base64
+import hmac
import io
import json
import queue
@@ -41,7 +42,6 @@ import soundfile as sf
import torch
from diffusers import ComponentsManager, ModularPipeline
from fastapi import FastAPI, Header, HTTPException, Response
-from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
@@ -226,7 +226,6 @@ def _worker():
app = FastAPI(title="MiniMax Music 3", description="Text-to-music on one GPU, upstream's API.")
-app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
@app.get("/health")
@@ -246,7 +245,7 @@ def list_models():
def speech(req: SpeechRequest, authorization: str = Header(None), x_api_key: str = Header(None)):
if ARGS.api_key:
supplied = x_api_key or (authorization or "").removeprefix("Bearer ").strip()
- if supplied != ARGS.api_key:
+ if not hmac.compare_digest(supplied.encode("utf-8"), ARGS.api_key.encode("utf-8")):
raise HTTPException(401, "bad or missing API key")
if req.response_format != "wav":
raise HTTPException(422, "response_format %r is not supported; only 'wav'" % req.response_format)
diff --git a/inference/test_security.py b/inference/test_security.py
new file mode 100644
index 0000000..abf2748
--- /dev/null
+++ b/inference/test_security.py
@@ -0,0 +1,103 @@
+import asyncio
+import hmac
+import sys
+from pathlib import Path
+from types import ModuleType, SimpleNamespace
+from unittest import TestCase
+from unittest.mock import patch
+
+import httpx
+
+
+def _load_server():
+ inference_dir = str(Path(__file__).resolve().parent)
+ if inference_dir not in sys.path:
+ sys.path.insert(0, inference_dir)
+
+ soundfile = ModuleType("soundfile")
+ torch = ModuleType("torch")
+ diffusers = ModuleType("diffusers")
+ diffusers.ComponentsManager = type("ComponentsManager", (), {})
+ diffusers.ModularPipeline = type("ModularPipeline", (), {})
+
+ with patch.dict(sys.modules, {"soundfile": soundfile, "torch": torch, "diffusers": diffusers}):
+ import server
+
+ return server
+
+
+server = _load_server()
+
+
+class InferenceSecurityTests(TestCase):
+ def setUp(self):
+ self.original_args = server.ARGS
+ self.original_ready = server.STATE["ready"]
+ server.ARGS = SimpleNamespace(api_key="secret")
+ server.STATE["ready"] = False
+
+ def tearDown(self):
+ server.ARGS = self.original_args
+ server.STATE["ready"] = self.original_ready
+
+ def _speech(self, headers=None):
+ return self._request(
+ "POST",
+ "/v1/audio/speech",
+ headers=headers or {},
+ json={"input": "[Verse]", "instructions": "ambient", "seed": 7},
+ )
+
+ def _request(self, method, path, **kwargs):
+ async def send():
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=server.app), base_url="http://testserver"
+ ) as client:
+ return await client.request(method, path, **kwargs)
+
+ return asyncio.run(send())
+
+ def test_never_adds_access_control_allow_origin(self):
+ origin = {"Origin": "https://evil.example"}
+ responses = [
+ self._request("GET", "/health", headers=origin),
+ self._request("GET", "/v1/models", headers=origin),
+ self._request(
+ "OPTIONS",
+ "/v1/audio/speech",
+ headers={
+ **origin,
+ "Access-Control-Request-Method": "POST",
+ "Access-Control-Request-Headers": "authorization,content-type",
+ },
+ ),
+ self._speech(origin),
+ ]
+
+ for response in responses:
+ with self.subTest(status=response.status_code):
+ self.assertNotIn("access-control-allow-origin", response.headers)
+
+ def test_accepts_bearer_and_x_api_key_headers(self):
+ for headers in (
+ {"Authorization": "Bearer secret"},
+ {"X-API-Key": "secret"},
+ ):
+ with self.subTest(headers=headers):
+ self.assertEqual(self._speech(headers).status_code, 503)
+
+ def test_api_key_remains_optional(self):
+ server.ARGS.api_key = None
+
+ self.assertEqual(self._speech().status_code, 503)
+
+ def test_rejects_wrong_or_missing_api_key_with_401(self):
+ self.assertEqual(self._speech({"Authorization": "Bearer wrong"}).status_code, 401)
+ self.assertEqual(self._speech().status_code, 401)
+
+ def test_compares_api_key_with_constant_time_primitive(self):
+ with patch.object(hmac, "compare_digest", wraps=hmac.compare_digest) as compare_digest:
+ response = self._speech({"Authorization": "Bearer wrong"})
+
+ self.assertEqual(response.status_code, 401)
+ compare_digest.assert_called_once_with(b"wrong", b"secret")