Files
alzeo/tests/test_vllm_engine_auth.py
Hasan BasbunarandClaude Opus 5.5 67cdd08fb2 vllm-lane.sh, install-nemotron-super.sh: one base for the vLLM lanes, and Super VL as one of them
The three vLLM lanes' installers (Kolibri, Nemotron, Nemotron Super) share vllm-lane.sh: the
engine's cache and port, the preflight and the room, the fetch, the service, the uninstall with
its opencode and pi cleanup, the proof. Each carried a copy of its own, a fix in one missing from
the next. lanes.sh's lane_prune_images removes a build of a lane's image once no installed unit
names it: the two Nemotron lanes run one image, and Bolt's update took away the build Super VL's
unit named; and unit_hf_cache and existing, one reading each where a dozen copies were.

The seventh lane: Super VL in NVFP4 with its LiLiCorr drafter, four requests at a time over
the 1,048,576-token window, 16 images and 2 videos per conversation, served in the Nemotron
lane's vLLM image (the card's own build does not hold the window at the card's share once
the media limits are set). Its unit, its installer in two halves (--units-only, --prepare,
the second building the shared image through install-nemotron.sh), its uninstall, which
keeps the image while the Bolt lane runs it, as the Bolt lane's keeps it while this one
does; every other unit names it in its Conflicts= and After=, the proxy holds requests for
it while it boots; its opencode provider (nemotron-super, 990,000 + 32,000 of its window),
pi's levels and check-pins.sh's two checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 14:25:42 +02:00

151 lines
6.9 KiB
Python

#!/usr/bin/env python3
"""vllm_engine_auth.RequireKey: the key on every route of the Kolibri lane's engine.
vLLM 0.29 checks --api-key only under /v1, /v2, /inference and /cohere: /invocations
(SageMaker's router, registered on every server, which runs chat and completions),
/tokenize and /detokenize answered anyone who reached the port. The middleware refuses
everything but /health and /metrics without the key, as the SGLang lanes do; the unit
loads it and the installer puts it where the unit mounts it.
"""
import asyncio
import importlib.util
import pathlib
import re
import tempfile
import unittest
import unittest.mock
REPO = pathlib.Path(__file__).resolve().parents[1]
_spec = importlib.util.spec_from_file_location("vllm_engine_auth", REPO / "vllm_engine_auth.py")
auth = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(auth)
KEY = "sk-test-0123456789abcdef"
class Fake:
"""An ASGI app that records being reached, and a send() that records the reply."""
def __init__(self):
self.reached, self.sent = [], []
async def app(self, scope, receive, send):
self.reached.append(scope["path"])
async def send(self, msg):
self.sent.append(msg)
class TheEngineAsksTheKeyEverywhere(unittest.TestCase):
def setUp(self):
d = pathlib.Path(tempfile.mkdtemp(prefix="vllm-auth-"))
self.keyfile = d / "api-key"
self.keyfile.write_text(KEY + "\n")
self.env = unittest.mock.patch.dict("os.environ", {"QWEN38_KEY_FILE": str(self.keyfile)})
self.env.start()
self.addCleanup(self.env.stop)
def call(self, path, auth_header=None, kind="http", method="POST", root=""):
fake = Fake()
mw = auth.RequireKey(fake.app)
headers = [(b"content-type", b"application/json")]
if auth_header is not None:
headers.append((b"authorization", auth_header.encode()))
scope = {"type": kind, "path": path, "root_path": root, "method": method, "headers": headers}
asyncio.run(mw(scope, None, fake.send))
status = next((m["status"] for m in fake.sent if m["type"] == "http.response.start"), None)
return fake, status
def test_invocations_without_the_key_is_refused(self):
fake, status = self.call("/invocations")
self.assertEqual(status, 401)
self.assertEqual(fake.reached, [], "the engine never saw it")
def test_every_unguarded_vllm_route_is_refused_without_the_key(self):
for path in ("/invocations", "/tokenize", "/detokenize", "/scale_elastic_ep", "/ping",
"/version", "/load", "/v1/chat/completions", "/v1/models", "/start_profile"):
with self.subTest(path=path):
fake, status = self.call(path)
self.assertEqual((status, fake.reached), (401, []))
def test_the_key_opens_them(self):
for path in ("/invocations", "/tokenize", "/v1/chat/completions", "/version"):
with self.subTest(path=path):
fake, status = self.call(path, f"Bearer {KEY}")
self.assertEqual((status, fake.reached), (None, [path]))
def test_a_wrong_key_or_another_scheme_is_refused(self):
for header in (f"Bearer {KEY}x", "Bearer ", f"Basic {KEY}", KEY, f"bearer{KEY}"):
with self.subTest(header=header):
fake, status = self.call("/invocations", header)
self.assertEqual((status, fake.reached), (401, []))
def test_the_scheme_is_case_blind_as_in_vllm(self):
fake, status = self.call("/invocations", f"bearer {KEY}")
self.assertEqual(fake.reached, ["/invocations"])
def test_health_and_metrics_stay_open(self):
# the cockpit reads both without the key, on every lane
for path in ("/health", "/metrics", "/metrics/"):
with self.subTest(path=path):
fake, status = self.call(path, method="GET")
self.assertEqual((status, fake.reached), (None, [path]))
def test_only_those_two_are_open_not_what_starts_like_them(self):
# pinned: a test of the open routes passed with "path.startswith(OPEN)" too, which
# opens any route vLLM may add under /health or /metrics without the slash (review,
# 2026-10-14; none in 0.29)
for path in ("/healthz", "/health/x", "/healthy", "/metricsx", "/metrics_raw"):
with self.subTest(path=path):
fake, status = self.call(path, method="GET")
self.assertEqual((status, fake.reached), (401, []))
def test_a_root_path_is_taken_off_first(self):
fake, status = self.call("/engine/health", root="/engine", method="GET")
self.assertEqual(fake.reached, ["/engine/health"])
fake, status = self.call("/engine/invocations", root="/engine")
self.assertEqual(status, 401)
def test_preflight_and_lifespan_pass(self):
fake, status = self.call("/invocations", method="OPTIONS")
self.assertEqual(fake.reached, ["/invocations"])
fake = Fake()
asyncio.run(auth.RequireKey(fake.app)({"type": "lifespan", "path": ""}, None, fake.send))
self.assertEqual(fake.reached, [""])
def test_a_websocket_without_the_key_is_closed(self):
fake, _ = self.call("/v1/realtime", kind="websocket")
self.assertEqual(fake.reached, [])
self.assertEqual(fake.sent, [{"type": "websocket.close", "code": 1008}])
def test_an_empty_key_file_keeps_the_engine_down(self):
self.keyfile.write_text("\n")
with self.assertRaises(RuntimeError):
auth.RequireKey(Fake().app)
class TheLaneLoadsIt(unittest.TestCase):
def test_the_unit_loads_the_middleware_from_its_own_mount(self):
unit = (REPO / "qwen38-kolibri.service.template").read_text()
self.assertIn("--middleware vllm_engine_auth.RequireKey", unit)
mount = re.search(r"-v (\S+):(/opt/qwen38-auth):ro", unit)
self.assertIsNotNone(mount, "the module's directory, read-only, and nothing else of the config")
self.assertIn("-e PYTHONPATH=/opt/qwen38-auth", unit)
self.assertIn("-e QWEN38_KEY_FILE=/out/api-key", unit)
self.assertIn("-v __HOME__/.config/qwen38:/out", unit, "where the key file is")
def test_the_installer_puts_it_there(self):
# in the service step the three vLLM lanes' installers share (vllm-lane.sh)
shared = (REPO / "vllm-lane.sh").read_text()
step = shared[shared.index("vlane_service_files(){"):]
step = step[:step.index("\n}\n")]
self.assertIn('"$HERE/vllm_engine_auth.py"', step)
self.assertIn("$CONFIG_DIR/vllm-auth/vllm_engine_auth.py", step)
for script in ("install-kolibri.sh", "install-nemotron.sh", "install-nemotron-super.sh"):
with self.subTest(script=script):
inst = (REPO / script).read_text()
service = inst[inst.index("install_service(){"):]
self.assertIn("vlane_service_files ", service[:service.index("\n}\n")])
if __name__ == "__main__":
unittest.main()