Skip to content

Commit 95bbf3e

Browse files
kxz2002juncaipeng
authored andcommitted
[Feature] Enable FastDeploy to support adding the “--api-key” authentication parameter. (PaddlePaddle#4806)
* add api key initial commit * add unit test * modify unit test * move middleware to a single file and add unit tests
1 parent 86ed252 commit 95bbf3e

File tree

7 files changed

+454
-2
lines changed

7 files changed

+454
-2
lines changed

fastdeploy/entrypoints/openai/api_server.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
"""
2-
# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.
1+
"""# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved.
32
#
43
# Licensed under the Apache License, Version 2.0 (the "License"
54
# you may not use this file except in compliance with the License.
@@ -38,6 +37,7 @@
3837
from fastdeploy.engine.expert_service import ExpertService
3938
from fastdeploy.entrypoints.chat_utils import load_chat_template
4039
from fastdeploy.entrypoints.engine_client import EngineClient
40+
from fastdeploy.entrypoints.openai.middleware import AuthenticationMiddleware
4141
from fastdeploy.entrypoints.openai.protocol import (
4242
ChatCompletionRequest,
4343
ChatCompletionResponse,
@@ -266,6 +266,12 @@ async def lifespan(app: FastAPI):
266266
instrument(app)
267267

268268

269+
env_api_key_func = environment_variables.get("FD_API_KEY")
270+
env_tokens = env_api_key_func() if env_api_key_func else []
271+
if tokens := [key for key in (args.api_key or env_tokens) if key]:
272+
app.add_middleware(AuthenticationMiddleware, tokens)
273+
274+
269275
@asynccontextmanager
270276
async def connection_manager():
271277
"""
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import hashlib
2+
import secrets
3+
from collections.abc import Awaitable
4+
5+
from fastapi.responses import JSONResponse
6+
from starlette.datastructures import URL, Headers
7+
from starlette.types import ASGIApp, Receive, Scope, Send
8+
9+
10+
class AuthenticationMiddleware:
11+
"""
12+
Pure ASGI middleware that authenticates each request by checking
13+
if the Authorization Bearer token exists and equals anyof "{api_key}".
14+
15+
Notes
16+
-----
17+
There are two cases in which authentication is skipped:
18+
1. The HTTP method is OPTIONS.
19+
2. The request path doesn't start with /v1 (e.g. /health).
20+
"""
21+
22+
def __init__(self, app: ASGIApp, tokens: list[str]) -> None:
23+
self.app = app
24+
self.api_tokens = [hashlib.sha256(t.encode("utf-8")).digest() for t in tokens]
25+
26+
def verify_token(self, headers: Headers) -> bool:
27+
authorization_header_value = headers.get("Authorization")
28+
if not authorization_header_value:
29+
return False
30+
31+
scheme, _, param = authorization_header_value.partition(" ")
32+
if scheme.lower() != "bearer":
33+
return False
34+
35+
param_hash = hashlib.sha256(param.encode("utf-8")).digest()
36+
37+
token_match = False
38+
for token_hash in self.api_tokens:
39+
token_match |= secrets.compare_digest(param_hash, token_hash)
40+
41+
return token_match
42+
43+
def __call__(self, scope: Scope, receive: Receive, send: Send) -> Awaitable[None]:
44+
if scope["type"] not in ("http", "websocket") or scope["method"] == "OPTIONS":
45+
# scope["type"] can be "lifespan" or "startup" for example,
46+
# in which case we don't need to do anything
47+
return self.app(scope, receive, send)
48+
root_path = scope.get("root_path", "")
49+
url_path = URL(scope=scope).path.removeprefix(root_path)
50+
headers = Headers(scope=scope)
51+
# Type narrow to satisfy mypy.
52+
if url_path.startswith("/v1") and not self.verify_token(headers):
53+
response = JSONResponse(content={"error": "Unauthorized"}, status_code=401)
54+
return response(scope, receive, send)
55+
return self.app(scope, receive, send)

fastdeploy/entrypoints/openai/utils.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,5 +239,7 @@ def make_arg_parser(parser: FlexibleArgumentParser) -> FlexibleArgumentParser:
239239
help="Workers silent for more than this many seconds are killed and restarted.Value is a positive number or 0. Setting it to 0 has the effect of infinite timeouts by disabling timeouts for all workers entirely.",
240240
)
241241

242+
parser.add_argument("--api-key", type=str, action="append", help="API_KEY required for service authentication")
243+
242244
parser = EngineArgs.add_cli_args(parser)
243245
return parser

fastdeploy/envs.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,8 @@
130130
"FD_CACHE_PROC_EXIT_TIMEOUT": lambda: int(os.getenv("FD_CACHE_PROC_EXIT_TIMEOUT", "600")),
131131
# Count for cache_transfer_manager process error
132132
"FD_CACHE_PROC_ERROR_COUNT": lambda: int(os.getenv("FD_CACHE_PROC_ERROR_COUNT", "10")),
133+
# API_KEY required for service authentication
134+
"FD_API_KEY": lambda: [] if "FD_API_KEY" not in os.environ else os.environ["FD_API_KEY"].split(","),
133135
# EPLB related
134136
"FD_ENABLE_REDUNDANT_EXPERTS": lambda: int(os.getenv("FD_ENABLE_REDUNDANT_EXPERTS", "0")) == 1,
135137
"FD_REDUNDANT_EXPERTS_NUM": lambda: int(os.getenv("FD_REDUNDANT_EXPERTS_NUM", "0")),

tests/e2e/test_api_key.py

Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
1+
import os
2+
import signal
3+
import socket
4+
import subprocess
5+
import sys
6+
import time
7+
from typing import Optional
8+
9+
import pytest
10+
import requests
11+
12+
FD_API_PORT = int(os.getenv("FD_API_PORT", 8188))
13+
FD_ENGINE_QUEUE_PORT = int(os.getenv("FD_ENGINE_QUEUE_PORT", 8133))
14+
FD_METRICS_PORT = int(os.getenv("FD_METRICS_PORT", 8233))
15+
FD_CACHE_QUEUE_PORT = int(os.getenv("FD_CACHE_QUEUE_PORT", 8333))
16+
PORTS_TO_CLEAN = [FD_API_PORT, FD_ENGINE_QUEUE_PORT, FD_METRICS_PORT, FD_CACHE_QUEUE_PORT]
17+
18+
current_server_process: Optional[subprocess.Popen] = None
19+
20+
21+
def is_port_open(host: str, port: int, timeout=1.0):
22+
"""
23+
Check if a TCP port is open on the given host.
24+
Returns True if connection succeeds, False otherwise.
25+
"""
26+
try:
27+
with socket.create_connection((host, port), timeout):
28+
return True
29+
except Exception:
30+
return False
31+
32+
33+
def kill_process_on_port(port: int):
34+
"""
35+
Kill processes that are listening on the given port.
36+
Uses `lsof` to find process ids and sends SIGKILL.
37+
"""
38+
try:
39+
output = subprocess.check_output(f"lsof -i:{port} -t", shell=True).decode().strip()
40+
current_pid = os.getpid()
41+
parent_pid = os.getppid()
42+
for pid in output.splitlines():
43+
pid = int(pid)
44+
if pid in (current_pid, parent_pid):
45+
print(f"Skip killing current process (pid={pid}) on port {port}")
46+
continue
47+
os.kill(pid, signal.SIGKILL)
48+
print(f"Killed process on port {port}, pid={pid}")
49+
except subprocess.CalledProcessError:
50+
pass
51+
52+
53+
def clean_ports():
54+
"""
55+
Kill all processes occupying the ports listed in PORTS_TO_CLEAN.
56+
"""
57+
for port in PORTS_TO_CLEAN:
58+
kill_process_on_port(port)
59+
time.sleep(2)
60+
61+
62+
def start_api_server(api_key_cli: Optional[list[str]] = None, api_key_env: Optional[str] = None):
63+
global current_server_process
64+
clean_ports()
65+
66+
env = os.environ.copy()
67+
if api_key_env is not None:
68+
env["FD_API_KEY"] = api_key_env
69+
else:
70+
env.pop("FD_API_KEY", None)
71+
base_path = os.getenv("MODEL_PATH")
72+
if base_path:
73+
model_path = os.path.join(base_path, "ERNIE-4.5-0.3B-Paddle")
74+
else:
75+
model_path = "./ERNIE-4.5-0.3B-Paddle"
76+
log_path = "server.log"
77+
78+
cmd = [
79+
sys.executable,
80+
"-m",
81+
"fastdeploy.entrypoints.openai.api_server",
82+
"--model",
83+
model_path,
84+
"--port",
85+
str(FD_API_PORT),
86+
"--tensor-parallel-size",
87+
"1",
88+
"--engine-worker-queue-port",
89+
str(FD_ENGINE_QUEUE_PORT),
90+
"--metrics-port",
91+
str(FD_METRICS_PORT),
92+
"--cache-queue-port",
93+
str(FD_CACHE_QUEUE_PORT),
94+
"--max-model-len",
95+
"32768",
96+
"--max-num-seqs",
97+
"128",
98+
"--quantization",
99+
"wint4",
100+
"--graph-optimization-config",
101+
'{"cudagraph_capture_sizes": [1], "use_cudagraph":true}',
102+
]
103+
104+
if api_key_cli is not None:
105+
for key in api_key_cli:
106+
cmd.extend(["--api-key", key])
107+
108+
with open(log_path, "w") as logfile:
109+
process = subprocess.Popen(cmd, stdout=logfile, stderr=subprocess.STDOUT, start_new_session=True, env=env)
110+
111+
for _ in range(300):
112+
if is_port_open("127.0.0.1", FD_API_PORT):
113+
print(f"API server started (port: {FD_API_PORT}, cli_key: {api_key_cli}, env_key: {api_key_env})")
114+
current_server_process = process
115+
return process
116+
time.sleep(1)
117+
else:
118+
if process.poll() is None:
119+
os.killpg(process.pid, signal.SIGTERM)
120+
raise RuntimeError(f"API server failed to start in 5 minutes (port: {FD_API_PORT})")
121+
122+
123+
def stop_api_server():
124+
global current_server_process
125+
if current_server_process and current_server_process.poll() is None:
126+
try:
127+
os.killpg(current_server_process.pid, signal.SIGTERM)
128+
current_server_process.wait(timeout=10)
129+
print(f"API server stopped (pid: {current_server_process.pid})")
130+
except Exception as e:
131+
print(f"Failed to stop server: {e}")
132+
current_server_process = None
133+
clean_ports()
134+
135+
136+
@pytest.fixture(scope="function", autouse=True)
137+
def teardown_server():
138+
yield
139+
stop_api_server()
140+
os.environ.pop("FD_API_KEY", None)
141+
142+
143+
@pytest.fixture(scope="function")
144+
def api_url():
145+
return f"http://0.0.0.0:{FD_API_PORT}/v1/chat/completions"
146+
147+
148+
@pytest.fixture
149+
def common_headers():
150+
return {"Content-Type": "application/json"}
151+
152+
153+
@pytest.fixture
154+
def valid_auth_headers():
155+
return {"Content-Type": "application/json", "Authorization": "Bearer {api_key}"}
156+
157+
158+
@pytest.fixture
159+
def test_payload():
160+
return {"messages": [{"role": "user", "content": "hello"}], "temperature": 0.9, "max_tokens": 100}
161+
162+
163+
def test_api_key_cli_only(api_url, common_headers, valid_auth_headers, test_payload):
164+
test_api_key = ["cli_test_key_123", "cli_test_key_456"]
165+
start_api_server(api_key_cli=test_api_key)
166+
167+
response = requests.post(api_url, json=test_payload, headers=common_headers)
168+
assert response.status_code == 401
169+
assert "error" in response.json()
170+
assert "unauthorized" in response.json()["error"].lower()
171+
172+
invalid_headers = valid_auth_headers.copy()
173+
invalid_headers["Authorization"] = invalid_headers["Authorization"].format(api_key="wrong_key")
174+
response = requests.post(api_url, json=test_payload, headers=invalid_headers)
175+
assert response.status_code == 401
176+
177+
valid_headers = valid_auth_headers.copy()
178+
valid_headers["Authorization"] = valid_headers["Authorization"].format(api_key=test_api_key[0])
179+
response = requests.post(api_url, json=test_payload, headers=valid_headers)
180+
assert response.status_code == 200
181+
182+
valid_headers = valid_auth_headers.copy()
183+
valid_headers["Authorization"] = valid_headers["Authorization"].format(api_key=test_api_key[1])
184+
response = requests.post(api_url, json=test_payload, headers=valid_headers)
185+
assert response.status_code == 200
186+
187+
188+
def test_api_key_env_only(api_url, common_headers, valid_auth_headers, test_payload):
189+
test_api_key = "env_test_key_456,env_test_key_789"
190+
start_api_server(api_key_env=test_api_key)
191+
192+
response = requests.post(api_url, json=test_payload, headers=common_headers)
193+
assert response.status_code == 401
194+
195+
valid_headers = valid_auth_headers.copy()
196+
valid_headers["Authorization"] = valid_headers["Authorization"].format(api_key="env_test_key_456")
197+
response = requests.post(api_url, json=test_payload, headers=valid_headers)
198+
assert response.status_code == 200
199+
200+
valid_headers = valid_auth_headers.copy()
201+
valid_headers["Authorization"] = valid_headers["Authorization"].format(api_key="env_test_key_789")
202+
response = requests.post(api_url, json=test_payload, headers=valid_headers)
203+
assert response.status_code == 200
204+
205+
206+
def test_api_key_cli_priority_over_env(api_url, valid_auth_headers, test_payload):
207+
cli_key = ["cli_priority_key_789"]
208+
env_key = "env_low_priority_key_000"
209+
start_api_server(api_key_cli=cli_key, api_key_env=env_key)
210+
211+
env_headers = valid_auth_headers.copy()
212+
env_headers["Authorization"] = env_headers["Authorization"].format(api_key=env_key)
213+
response = requests.post(api_url, json=test_payload, headers=env_headers)
214+
assert response.status_code == 401
215+
216+
cli_headers = valid_auth_headers.copy()
217+
cli_headers["Authorization"] = cli_headers["Authorization"].format(api_key=cli_key[0])
218+
response = requests.post(api_url, json=test_payload, headers=cli_headers)
219+
assert response.status_code == 200
220+
221+
222+
def test_api_key_not_set(api_url, common_headers, valid_auth_headers, test_payload):
223+
start_api_server(api_key_cli=None, api_key_env=None)
224+
225+
response = requests.post(api_url, json=test_payload, headers=common_headers)
226+
assert response.status_code == 200
227+
228+
cli_headers = valid_auth_headers.copy()
229+
cli_headers["Authorization"] = cli_headers["Authorization"].format(api_key="some_api_key")
230+
response = requests.post(api_url, json=test_payload, headers=cli_headers)
231+
assert response.status_code == 200

0 commit comments

Comments
 (0)