From a4991628beff66f38a47b07e7dc5d418a151c8a5 Mon Sep 17 00:00:00 2001 From: CI Test Date: Fri, 3 Jul 2026 08:32:49 +0800 Subject: [PATCH] =?UTF-8?q?fix(security):=20/metrics=20=E7=AB=AF=E7=82=B9?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20Bearer=20Token=20=E8=AE=A4=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 通过 METRICS_AUTH_TOKEN 环境变量配置认证 Token - 未配置 Token 时不启用认证(向后兼容) - 认证失败返回 401 Unauthorized --- apps/api/app/middleware/prometheus_metrics.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/apps/api/app/middleware/prometheus_metrics.py b/apps/api/app/middleware/prometheus_metrics.py index 2c61cec47..18601209a 100644 --- a/apps/api/app/middleware/prometheus_metrics.py +++ b/apps/api/app/middleware/prometheus_metrics.py @@ -121,9 +121,19 @@ class PrometheusMetricsMiddleware(BaseHTTPMiddleware): async def metrics_endpoint(request: Request) -> PlainTextResponse: - """FastAPI endpoint that returns Prometheus metrics in text format.""" + """FastAPI endpoint that returns Prometheus metrics in text format. + + 需要 Bearer Token 认证,Token 通过 METRICS_AUTH_TOKEN 环境变量配置。 + """ import os + # Bearer Token 认证 + auth_token = os.getenv("METRICS_AUTH_TOKEN", "") + if auth_token: + auth_header = request.headers.get("Authorization", "") + if not auth_header.startswith("Bearer ") or auth_header[7:] != auth_token: + return PlainTextResponse(content="Unauthorized", status_code=401) + version = os.getenv("APP_VERSION", "unknown") environment = os.getenv("APP_ENV", "unknown") APP_INFO.labels(version=version, environment=environment).set(1)