Implement server-side OAuth for Docker Space
Browse files- Add OAuth endpoints to FastAPI backend (/api/auth/login, /api/auth/callback, /api/auth/session)
- Replace client-side OAuth with server-side flow using OAUTH_CLIENT_ID and OAUTH_CLIENT_SECRET
- Handle HuggingFace OAuth callback and token exchange
- Create session management for authenticated users
- Update frontend to use backend OAuth endpoints instead of @huggingface/hub
- Remove @huggingface/hub dependency (not needed for Docker Spaces)
- Fix 'Failed to start login process' error by implementing proper Docker Space OAuth
Files changed (3)
12344566789101112131415161718192021222319 unmodified lines4344454647484950515253545556575859606187 unmodified lines149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254"""FastAPI backend for AnyCoder - provides REST API endpoints"""from fastapi import FastAPI, HTTPException, Header, WebSocket, WebSocketDisconnectfrom fastapi import FastAPI, HTTPException, Header, WebSocket, WebSocketDisconnect, Request, Responsefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import StreamingResponsefrom fastapi.responses import StreamingResponse, RedirectResponse, JSONResponsefrom pydantic import BaseModelfrom typing import Optional, List, Dict, AsyncGeneratorimport jsonimport asynciofrom datetime import datetimeimport secretsimport base64import urllib.parse
# Import only what we need, avoiding Gradio UI importsimport sysimport osfrom huggingface_hub import InferenceClientimport httpx
# Define models and languages here to avoid importing Gradio UIAVAILABLE_MODELS = [19 unmodified lines allow_headers=["*"],)
# OAuth configurationOAUTH_CLIENT_ID = os.getenv("OAUTH_CLIENT_ID", "")OAUTH_CLIENT_SECRET = os.getenv("OAUTH_CLIENT_SECRET", "")OAUTH_SCOPES = os.getenv("OAUTH_SCOPES", "openid profile manage-repos")OPENID_PROVIDER_URL = os.getenv("OPENID_PROVIDER_URL", "https://huggingface.co")SPACE_HOST = os.getenv("SPACE_HOST", "localhost:7860")
# In-memory store for OAuth states (in production, use Redis or similar)oauth_states = {}
# In-memory store for user sessionsuser_sessions = {}
# Pydantic models for request/responseclass CodeGenerationRequest(BaseModel):87 unmodified lines return {"languages": LANGUAGE_CHOICES}
@app.get("/api/auth/login")async def oauth_login(request: Request): """Initiate OAuth login flow""" # Generate a random state to prevent CSRF state = secrets.token_urlsafe(32) oauth_states[state] = {"timestamp": datetime.now()} # Build redirect URI protocol = "https" if SPACE_HOST and not SPACE_HOST.startswith("localhost") else "http" redirect_uri = f"{protocol}://{SPACE_HOST}/api/auth/callback" # Build authorization URL auth_url = ( f"{OPENID_PROVIDER_URL}/oauth/authorize" f"?client_id={OAUTH_CLIENT_ID}" f"&redirect_uri={urllib.parse.quote(redirect_uri)}" f"&scope={urllib.parse.quote(OAUTH_SCOPES)}" f"&state={state}" f"&response_type=code" ) return JSONResponse({"login_url": auth_url, "state": state})
@app.get("/api/auth/callback")async def oauth_callback(code: str, state: str, request: Request): """Handle OAuth callback""" # Verify state to prevent CSRF if state not in oauth_states: raise HTTPException(status_code=400, detail="Invalid state parameter") # Clean up old states oauth_states.pop(state, None) # Exchange code for tokens protocol = "https" if SPACE_HOST and not SPACE_HOST.startswith("localhost") else "http" redirect_uri = f"{protocol}://{SPACE_HOST}/api/auth/callback" # Prepare authorization header auth_string = f"{OAUTH_CLIENT_ID}:{OAUTH_CLIENT_SECRET}" auth_bytes = auth_string.encode('utf-8') auth_b64 = base64.b64encode(auth_bytes).decode('utf-8') async with httpx.AsyncClient() as client: try: token_response = await client.post( f"{OPENID_PROVIDER_URL}/oauth/token", data={ "client_id": OAUTH_CLIENT_ID, "code": code, "grant_type": "authorization_code", "redirect_uri": redirect_uri, }, headers={ "Authorization": f"Basic {auth_b64}", "Content-Type": "application/x-www-form-urlencoded", }, ) token_response.raise_for_status() token_data = token_response.json() # Get user info access_token = token_data.get("access_token") userinfo_response = await client.get( f"{OPENID_PROVIDER_URL}/oauth/userinfo", headers={"Authorization": f"Bearer {access_token}"}, ) userinfo_response.raise_for_status() user_info = userinfo_response.json() # Create session session_token = secrets.token_urlsafe(32) user_sessions[session_token] = { "access_token": access_token, "user_info": user_info, "timestamp": datetime.now(), } # Redirect to frontend with session token frontend_url = f"{protocol}://{SPACE_HOST}/?session={session_token}" return RedirectResponse(url=frontend_url) except httpx.HTTPError as e: print(f"OAuth error: {e}") raise HTTPException(status_code=500, detail=f"OAuth failed: {str(e)}")
@app.get("/api/auth/session")async def get_session(session: str): """Get user info from session token""" if session not in user_sessions: raise HTTPException(status_code=401, detail="Invalid session") session_data = user_sessions[session] return { "access_token": session_data["access_token"], "user_info": session_data["user_info"], }
@app.get("/api/auth/status")async def auth_status(authorization: Optional[str] = Header(None)): """Check authentication status"""13 unmodified lines1415161717181913 unmodified lines "react-dom": "^18.3.1", "axios": "^1.7.2", "@monaco-editor/react": "^4.6.0", "@huggingface/hub": "^0.15.1", "prismjs": "^1.29.0", "react-markdown": "^9.0.1", "remark-gfm": "^4.0.0"121234567891011121313141516171819202124 unmodified lines4647484647495051524950515253545556575859606162636465666768697071727374757677787980818283848586873 unmodified lines91929362949596976 unmodified lines1041051067510710810911079808182838411111211311411511611711886119120121122// HuggingFace OAuth authentication utilitiesimport { oauthLoginUrl, oauthHandleRedirectIfPresent } from "@huggingface/hub";// HuggingFace OAuth authentication utilities (Server-side flow for Docker Spaces)
const STORAGE_KEY = 'hf_oauth_token';const USER_INFO_KEY = 'hf_user_info';const DEV_MODE_KEY = 'hf_dev_mode';const API_BASE = '/api';
// Check if we're in development mode (localhost)const isDevelopment = typeof window !== 'undefined' && (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1');
export interface OAuthUserInfo { id: string; id?: string; sub?: string; name: string; preferred_username?: string; preferredUsername?: string; picture?: string; avatarUrl?: string;}
24 unmodified lines return null; } // Check if we're handling an OAuth redirect const oauthResult = await oauthHandleRedirectIfPresent(); // Check if we're handling an OAuth callback (session parameter in URL) const urlParams = new URLSearchParams(window.location.search); const sessionToken = urlParams.get('session'); if (oauthResult) { // Store the OAuth result storeOAuthData(oauthResult); return oauthResult; if (sessionToken) { // Fetch session data from backend try { const response = await fetch(`${API_BASE}/auth/session?session=${sessionToken}`); if (response.ok) { const data = await response.json(); // Normalize user info const userInfo: OAuthUserInfo = { id: data.user_info.sub || data.user_info.id, name: data.user_info.name, preferredUsername: data.user_info.preferred_username || data.user_info.preferredUsername, avatarUrl: data.user_info.picture || data.user_info.avatarUrl, }; const oauthResult: OAuthResult = { accessToken: data.access_token, accessTokenExpiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), userInfo, }; // Store the OAuth result storeOAuthData(oauthResult); // Clean up URL window.history.replaceState({}, document.title, window.location.pathname); return oauthResult; } } catch (error) { console.error('Failed to fetch session:', error); } } // Check if we have stored credentials3 unmodified lines if (storedToken && storedUserInfo) { return { accessToken: storedToken, accessTokenExpiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // Assume 24h accessTokenExpiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), userInfo: storedUserInfo, }; }6 unmodified lines}
/** * Redirect to HuggingFace OAuth login page * Redirect to HuggingFace OAuth login page (via backend) */export async function loginWithHuggingFace(): Promise<void> { try { const loginUrl = await oauthLoginUrl({ // Redirect back to the current page redirectUrl: window.location.href, // Request scopes - adjust as needed scopes: "openid profile inference-api", }); // Call backend to get OAuth URL const response = await fetch(`${API_BASE}/auth/login`); if (!response.ok) { throw new Error('Failed to get login URL'); } const data = await response.json(); // Redirect to the OAuth authorization URL window.location.href = loginUrl; window.location.href = data.login_url; } catch (error) { console.error('Failed to initiate OAuth login:', error); throw new Error('Failed to start login process');backend_api.py+119-2
frontend/package.json-1
frontend/src/lib/auth.ts+51-18