chore: fix pre commit format and pipeline issue (#1144)

This commit is contained in:
Wendong-Fan 2026-02-04 00:06:29 +00:00 committed by GitHub
parent 2256497dff
commit 893f51fc82
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
970 changed files with 11235 additions and 9533 deletions

View file

@ -12,12 +12,17 @@
# limitations under the License.
# ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
from fastapi import APIRouter, Request, HTTPException
from fastapi.responses import RedirectResponse, JSONResponse, HTMLResponse
from app.component.environment import env
from app.component.oauth_adapter import OauthCallbackPayload, get_oauth_adapter
from typing import Optional
import logging
import re
from urllib.parse import quote, urlencode
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
from app.component.oauth_adapter import OauthCallbackPayload, get_oauth_adapter
# Allowed OAuth provider names (alphanumeric and hyphens only)
ALLOWED_PROVIDER_PATTERN = re.compile(r"^[a-zA-Z0-9_-]+$")
logger = logging.getLogger("server_oauth_controller")
@ -25,20 +30,20 @@ router = APIRouter(prefix="/oauth", tags=["Oauth Servers"])
@router.get("/{app}/login", name="OAuth Login Redirect")
def oauth_login(app: str, request: Request, state: Optional[str] = None):
def oauth_login(app: str, request: Request, state: str | None = None):
"""Redirect user to OAuth provider's authorization endpoint."""
try:
callback_url = str(request.url_for("OAuth Callback", app=app))
if callback_url.startswith("http://"):
callback_url = "https://" + callback_url[len("http://") :]
adapter = get_oauth_adapter(app, callback_url)
url = adapter.get_authorize_url(state)
if not url:
logger.error("Failed to generate authorization URL", extra={"provider": app, "callback_url": callback_url})
raise HTTPException(status_code=400, detail="Failed to generate authorization URL")
logger.info("OAuth login initiated", extra={"provider": app})
return RedirectResponse(str(url))
except HTTPException:
@ -49,29 +54,53 @@ def oauth_login(app: str, request: Request, state: Optional[str] = None):
@router.get("/{app}/callback", name="OAuth Callback")
def oauth_callback(app: str, request: Request, code: Optional[str] = None, state: Optional[str] = None):
def oauth_callback(
app: str,
request: Request,
code: str | None = None,
state: str | None = None,
):
"""Handle OAuth provider callback and redirect to client app."""
# Security: Validate provider name to prevent injection
if not ALLOWED_PROVIDER_PATTERN.match(app):
logger.warning(
"OAuth callback invalid provider name",
extra={"provider": app[:50]}, # Truncate for logging
)
raise HTTPException(status_code=400, detail="Invalid provider")
if not code:
logger.warning("OAuth callback missing code", extra={"provider": app})
raise HTTPException(status_code=400, detail="Missing code parameter")
logger.info("OAuth callback received", extra={"provider": app, "has_state": state is not None})
redirect_url = f"eigent://callback/oauth?provider={app}&code={code}&state={state}"
html_content = f"""
<html>
<head>
<title>OAuth Callback</title>
</head>
<body>
<script type='text/javascript'>
window.location.href = '{redirect_url}';
</script>
<p>Redirecting, please wait...</p>
<button onclick='window.close()'>Close this window</button>
</body>
</html>
"""
logger.info(
"OAuth callback received",
extra={"provider": app, "has_state": state is not None},
)
# Security: URL-encode all parameters to prevent XSS
params = {"provider": app, "code": code}
if state is not None:
params["state"] = state
redirect_url = f"eigent://callback/oauth?{urlencode(params)}"
# Security: Use a safe redirect approach without embedding in JavaScript
# The redirect URL uses a custom protocol, so we encode it safely
safe_redirect_url = quote(redirect_url, safe=":/&?=")
html_content = f"""<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>OAuth Callback</title>
<meta http-equiv="refresh" content="0;url={safe_redirect_url}">
</head>
<body>
<p>Redirecting, please wait...</p>
<p>If you are not redirected, <a href="{safe_redirect_url}">click here</a>.</p>
<button onclick="window.close()">Close this window</button>
</body>
</html>"""
return HTMLResponse(content=html_content)
@ -89,4 +118,4 @@ def fetch_token(app: str, request: Request, data: OauthCallbackPayload):
return JSONResponse(token_data)
except Exception as e:
logger.error("OAuth token fetch failed", extra={"provider": app, "error": str(e)}, exc_info=True)
raise HTTPException(status_code=500, detail="Internal server error")
raise HTTPException(status_code=500, detail="Internal server error")