Claude 리뷰 기반 운영 안정성 보강
This commit is contained in:
1 parent
8b0a7e45ac
commit
725e44e999
15 files changed
+1427
-67
No files matched your search
+51
-6
@@ -19,12 +19,60 @@ from app.jobs.store import JobStore
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
|
||||
|
||||
class AuthConfigurationError(RuntimeError):
|
||||
"""운영 인증 설정이 모순될 때 기동을 막는다."""
|
||||
|
||||
|
||||
def validate_auth_settings(settings) -> None:
|
||||
"""REQUIRE_API_KEY=true 인데 키가 없으면 기동 실패 (fail-closed).
|
||||
|
||||
'키를 깜빡해서 무인증으로 떠 있었다'가 가능한 구성을 없애는 것이 목적이다.
|
||||
미출간 원고를 다루는 서버라 조용한 무인증이 가장 위험하다.
|
||||
"""
|
||||
if settings.require_api_key and not settings.api_key.strip():
|
||||
raise AuthConfigurationError(
|
||||
"REQUIRE_API_KEY=true 인데 API_KEY 가 비어 있습니다. "
|
||||
"키를 설정하거나 REQUIRE_API_KEY=false 로 두십시오."
|
||||
)
|
||||
|
||||
|
||||
def public_paths(settings) -> set[str]:
|
||||
"""인증 없이 접근 가능한 경로. 설정으로 좁힐 수 있다."""
|
||||
paths = {"/"}
|
||||
if settings.public_health:
|
||||
paths.add("/v1/health")
|
||||
if settings.public_docs:
|
||||
paths.update({"/docs", "/openapi.json", "/redoc"})
|
||||
return paths
|
||||
|
||||
|
||||
def is_authorized(settings, path: str, supplied: str) -> bool:
|
||||
"""요청 허용 여부. 순수 함수라 앱 기동 없이 테스트할 수 있다.
|
||||
|
||||
api_key 가 비어 있으면(개발 기본값) 인증을 걸지 않는다. 이 경우 기동 시
|
||||
critical 경고가 남는다.
|
||||
"""
|
||||
configured = settings.api_key.strip()
|
||||
if not configured:
|
||||
return True
|
||||
if path in public_paths(settings):
|
||||
return True
|
||||
protected_docs = {"/docs", "/openapi.json", "/redoc"}
|
||||
if not path.startswith("/v1") and path not in protected_docs:
|
||||
return True
|
||||
# compare_digest 는 비ASCII str 에서 TypeError 를 던진다. 한글/이모지 키를
|
||||
# 넣으면 전 요청이 500 이 되므로 반드시 bytes 로 비교한다.
|
||||
return hmac.compare_digest(configured.encode("utf-8"), (supplied or "").encode("utf-8"))
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
settings = get_settings()
|
||||
validate_auth_settings(settings)
|
||||
if not settings.api_key.strip():
|
||||
logging.critical(
|
||||
"API_KEY is empty: all /v1 endpoints are unauthenticated. "
|
||||
"Set REQUIRE_API_KEY=true with a key before exposing this server. "
|
||||
"Do not expose unpublished manuscripts publicly until client key rollout is complete."
|
||||
)
|
||||
app.state.settings = settings
|
||||
@@ -67,12 +115,9 @@ app.include_router(api_router)
|
||||
@app.middleware("http")
|
||||
async def optional_api_key_auth(request: Request, call_next):
|
||||
"""API_KEY가 설정된 운영 환경에서만 API 인증을 강제한다."""
|
||||
configured = _settings.api_key.strip()
|
||||
public_paths = {"/", "/v1/health", "/docs", "/openapi.json", "/redoc"}
|
||||
if configured and request.url.path not in public_paths and request.url.path.startswith("/v1"):
|
||||
supplied = request.headers.get("x-api-key", "")
|
||||
if not hmac.compare_digest(configured, supplied):
|
||||
return JSONResponse(status_code=401, content={"detail": "Invalid or missing API key"})
|
||||
settings = getattr(request.app.state, "settings", None) or _settings
|
||||
if not is_authorized(settings, request.url.path, request.headers.get("x-api-key", "")):
|
||||
return JSONResponse(status_code=401, content={"detail": "Invalid or missing API key"})
|
||||
return await call_next(request)
|
||||
|
||||
_STATIC_DIR = Path(__file__).resolve().parent / "static"
|
||||
|
||||
Reference in new issue
Block a user