""" backend/app/services/integration_tool_auth.py 用途:Dify / 集成方 HTTP Tool API 共用鉴权(Bearer 或 X-Integration-Key)。 依赖:Flask current_app、core.errors。 逻辑:file-check / accounting-voucher-check 等 Tool Blueprint before_request 调用; 密钥优先 FILE_CHECK_TOOL_API_KEY,回退 INTEGRATION_API_KEY。 """ from __future__ import annotations from flask import current_app, request from app.core.errors import ServiceUnavailableError, UnauthorizedError def require_integration_tool_auth() -> None: """ 校验 Tool API 访问权限。 核心逻辑:Authorization Bearer 与 X-Integration-Key 二选一,值须与配置密钥完全一致。 Raises: ServiceUnavailableError: 服务端未配置密钥。 UnauthorizedError: 缺少或错误的凭证。 """ configured = str( current_app.config.get("FILE_CHECK_TOOL_API_KEY") or current_app.config.get("INTEGRATION_API_KEY") or "" ).strip() if not configured: raise ServiceUnavailableError( "FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured", code="missing_auth", ) bearer = str(request.headers.get("Authorization") or "").strip() api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else "" integration_key = str(request.headers.get("X-Integration-Key") or "").strip() if configured in {api_token, integration_key}: return if not api_token and not integration_key: raise UnauthorizedError("missing_auth") raise UnauthorizedError("invalid_auth")