fix(security): /metrics 端点添加 Bearer Token 认证
Deploy / Deploy Staging (push) Has been cancelled
Deploy / Build Production Runtime Images (push) Has been cancelled
Deploy / Deploy Production (push) Has been cancelled
Deploy / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Failing after 148h21m16s
CI/CD Pipeline / Validate Code Quality And Tests (push) Failing after 148h21m22s
Deploy / Deploy Staging (push) Has been cancelled
Deploy / Build Production Runtime Images (push) Has been cancelled
Deploy / Deploy Production (push) Has been cancelled
Deploy / Production Browser E2E (push) Has been cancelled
CI/CD Pipeline / Frontend Lint (push) Failing after 148h21m16s
CI/CD Pipeline / Validate Code Quality And Tests (push) Failing after 148h21m22s
- 通过 METRICS_AUTH_TOKEN 环境变量配置认证 Token - 未配置 Token 时不启用认证(向后兼容) - 认证失败返回 401 Unauthorized
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user