Files
web-page-backend/stock/app/auth.py
gahusb 227e294bd3 feat(stock-webai): add X-WebAI-Key auth dependency + tests
verify_webai_key FastAPI dependency: 401 on missing/wrong key,
503 when WEBAI_API_KEY env unset. 4 unit tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 08:33:07 +09:00

29 lines
1009 B
Python

import os
import logging
from fastapi import Header, HTTPException
from starlette.requests import Request
logger = logging.getLogger("stock")
def verify_webai_key(
request: Request,
x_webai_key: str | None = Header(default=None, alias="X-WebAI-Key"),
) -> None:
"""
/api/webai/* 보호용 FastAPI dependency.
- WEBAI_API_KEY env 미설정 → 503 (다른 endpoint 무영향)
- 헤더 누락 또는 키 불일치 → 401 + logger.warning(ip)
"""
configured = os.getenv("WEBAI_API_KEY", "").strip()
if not configured:
logger.error("WEBAI_API_KEY not configured — refusing /api/webai/* request")
raise HTTPException(status_code=503, detail="webai auth not configured")
if not x_webai_key or x_webai_key != configured:
remote = request.client.host if request.client else "?"
logger.warning("auth_fail path=%s remote=%s", request.url.path, remote)
raise HTTPException(status_code=401, detail="invalid or missing X-WebAI-Key")