Fix deployment: Use OAuth session tokens properly
Browse filesKey changes:
- Update MockAuth to accept username parameter
- get_auth_from_header now looks up OAuth sessions to extract access_token
- Session tokens are properly resolved to HF OAuth access tokens
- Added detailed logging throughout deployment process
- Better error handling with user-friendly messages for 401/403 errors
- Added HfApi.whoami() call to verify token and get username
- Improved error messages for authentication and permission issues
This ensures the deploy endpoint uses the proper OAuth token from the
authenticated session rather than trying to use a session UUID directly.
103 unmodified lines1041051061071081091101111121131141151161171181191201211221231241251261271281 unmodified line130131132133134135136336 unmodified lines47347447547647747847948048148248348448548648748848949049149249349449549668 unmodified lines565566567568569570571572103 unmodified lines# Mock authentication for development# In production, integrate with HuggingFace OAuthclass MockAuth:def __init__(self, token: Optional[str] = None):self.token = token# Extract username from dev token or use generic nameif token and token.startswith("dev_token_"):# Extract username from dev token format: dev_token_<username>_<timestamp>parts = token.split("_")self.username = parts[2] if len(parts) > 2 else "user"else:self.username = "user" if token else Nonedef is_authenticated(self):# Accept any token (for dev mode)return bool(self.token)def get_auth_from_header(authorization: Optional[str] = None):"""Extract authentication from header"""if not authorization:return MockAuth(None)# Handle "Bearer " prefixif authorization.startswith("Bearer "):1 unmodified lineelse:token = authorizationreturn MockAuth(token)@app.get("/")336 unmodified lines"dev_mode": True}# Production mode with real tokentry:from huggingface_hub import HfApiimport tempfileimport uuid# Get user token from header or use server tokenuser_token = auth.token if auth.token else os.getenv("HF_TOKEN")if not user_token:raise HTTPException(status_code=401, detail="No HuggingFace token available")# Create API clientapi = HfApi(token=user_token)# Generate space name if not providedspace_name = request.space_name or f"anycoder-{uuid.uuid4().hex[:8]}"repo_id = f"{auth.username}/{space_name}"# Map language to SDKlanguage_to_sdk = {68 unmodified linesfinally:os.unlink(temp_path)except Exception as e:raise HTTPException(status_code=500, detail=f"Deployment failed: {str(e)}")@app.websocket("/ws/generate")103 unmodified lines1041051061071081091101111121131141151161171181191201211 unmodified line123124125126127128129130131132133134135136137138139140141142143336 unmodified lines48048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152268 unmodified lines591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622103 unmodified lines# Mock authentication for development# In production, integrate with HuggingFace OAuthclass MockAuth:def __init__(self, token: Optional[str] = None, username: Optional[str] = None):self.token = tokenself.username = usernamedef is_authenticated(self):return bool(self.token)def get_auth_from_header(authorization: Optional[str] = None):"""Extract authentication from header or session token"""if not authorization:return MockAuth(None, None)# Handle "Bearer " prefixif authorization.startswith("Bearer "):1 unmodified lineelse:token = authorization# Check if this is a session token (UUID format)if token and "-" in token and len(token) > 20:# Look up the session to get user infoif token in user_sessions:session = user_sessions[token]return MockAuth(session["access_token"], session["username"])# Dev token format: dev_token_<username>_<timestamp>if token and token.startswith("dev_token_"):parts = token.split("_")username = parts[2] if len(parts) > 2 else "user"return MockAuth(token, username)# Regular token (OAuth access token passed directly)return MockAuth(token, None)@app.get("/")336 unmodified lines"dev_mode": True}# Production mode with real OAuth tokentry:from huggingface_hub import HfApiimport tempfileimport uuid# Get user token - should be the access_token from OAuth sessionuser_token = auth.token if auth.token else os.getenv("HF_TOKEN")if not user_token:raise HTTPException(status_code=401, detail="No HuggingFace token available. Please sign in first.")print(f"[Deploy] Attempting deployment with token (first 10 chars): {user_token[:10]}...")# Create API clientapi = HfApi(token=user_token)# Get the actual username from HuggingFace APItry:user_info = api.whoami()print(f"[Deploy] User info from HF API: {user_info}")username = user_info.get("name") or user_info.get("preferred_username") or auth.username or "user"except Exception as e:print(f"[Deploy] Failed to get user info from HF API: {e}")# Fallback to auth username if availableusername = auth.usernameif not username:raise HTTPException(status_code=401,detail="Failed to verify HuggingFace account. Please sign in again.")# Generate space name if not providedspace_name = request.space_name or f"anycoder-{uuid.uuid4().hex[:8]}"repo_id = f"{username}/{space_name}"print(f"[Deploy] Creating/updating space: {repo_id}")# Map language to SDKlanguage_to_sdk = {68 unmodified linesfinally:os.unlink(temp_path)except HTTPException:# Re-raise HTTP exceptions as-israiseexcept Exception as e:# Log the full error for debuggingimport tracebackerror_details = traceback.format_exc()print(f"[Deploy] Deployment error: {error_details}")# Provide user-friendly error messageerror_msg = str(e)if "401" in error_msg or "Unauthorized" in error_msg:raise HTTPException(status_code=401,detail="Authentication failed. Please sign in again with HuggingFace.")elif "403" in error_msg or "Forbidden" in error_msg:raise HTTPException(status_code=403,detail="Permission denied. Your HuggingFace token may not have the required permissions (manage-repos scope).")else:raise HTTPException(status_code=500,detail=f"Deployment failed: {error_msg}")@app.websocket("/ws/generate")
backend_api.py+67-17