Download auth.py from fffiloni/hf-picks: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/spaces/fffiloni/hf-picks/resolve/main/auth.py
- Command line
-
hf download hf://spaces/fffiloni/hf-picks/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/fffiloni/hf-picks/resolve/main/auth.py
10.8 kB
| """HF OAuth identity only. Hub tokens never leave the callback or enter a cache. | |
| The initiating tab holds a random verifier; the server stores its SHA-256 challenge. | |
| This binds the handoff to that tab without relying on third-party iframe cookies. | |
| The top-level sign-in tab separately binds the OAuth callback with an HttpOnly cookie. | |
| OAuth itself uses an independent state and S256 PKCE verifier. Short-lived app | |
| sessions live in memory, are revocable, and confer no access to private Hub data. | |
| """ | |
| from __future__ import annotations | |
| import base64 | |
| import hashlib | |
| import hmac | |
| import os | |
| import re | |
| import secrets | |
| import time | |
| from urllib.parse import urlencode, urlsplit | |
| import httpx | |
| from fastapi import APIRouter, HTTPException, Query, Request | |
| from fastapi.responses import FileResponse, RedirectResponse, JSONResponse | |
| from pydantic import BaseModel, Field | |
| from pathlib import Path | |
| HUB = "https://huggingface.co" | |
| ROOT = Path(__file__).resolve().parent | |
| USERNAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]{0,95}$") | |
| PROOF = r"^[A-Za-z0-9_-]{43,128}$" | |
| def challenge(verifier): | |
| return base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode() | |
| class Identity: | |
| FLOW_TTL = 600 | |
| SESSION_TTL = 8 * 3600 | |
| CAPACITY = 1024 | |
| def __init__(self, *, client_id=None, client_secret=None, origin=None, transport=None): | |
| self.client_id = client_id if client_id is not None else os.getenv("OAUTH_CLIENT_ID", "") | |
| self.client_secret = client_secret if client_secret is not None else os.getenv("OAUTH_CLIENT_SECRET", "") | |
| host = os.getenv("SPACE_HOST", "") | |
| self.origin = (origin or os.getenv("HF_PICKS_ORIGIN") or ("https://" + host if host else "")).rstrip("/") | |
| parsed = urlsplit(self.origin) | |
| valid_origin = parsed.scheme == "https" and parsed.hostname and not (parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path) | |
| self.enabled = bool(self.client_id and self.client_secret and valid_origin) | |
| self.flows, self.sessions = {}, {} | |
| self.http = httpx.AsyncClient(timeout=20, follow_redirects=False, transport=transport) | |
| def prune(self): | |
| now = time.time() | |
| for table in (self.flows, self.sessions): | |
| for key in [k for k, v in table.items() if v["expires"] <= now]: | |
| del table[key] | |
| def start(self, proof, identifier=None): | |
| if not self.enabled: | |
| raise HTTPException(503, "HF sign-in is not configured. You can use a public profile or try the demo.") | |
| self.prune() | |
| if len(self.flows) >= self.CAPACITY: | |
| raise HTTPException(429, "Many people are signing in. Please try again shortly.") | |
| state, verifier = identifier or secrets.token_urlsafe(32), secrets.token_urlsafe(48) | |
| if state in self.flows: | |
| raise HTTPException(409, "This sign-in attempt has already started.") | |
| self.flows[state] = {"expires": time.time() + self.FLOW_TTL, "proof": proof, "verifier": verifier, "browser": secrets.token_urlsafe(32), "status": "pending"} | |
| params = {"client_id": self.client_id, "redirect_uri": self.origin + "/auth/callback", "response_type": "code", | |
| "scope": "openid profile", "state": state, "code_challenge": challenge(verifier), "code_challenge_method": "S256"} | |
| return {"flow": state, "authorizeUrl": HUB + "/oauth/authorize?" + urlencode(params), "expiresIn": self.FLOW_TTL} | |
| def flow(self, identifier, verifier): | |
| self.prune() | |
| flow = self.flows.get(identifier) | |
| if not flow or not hmac.compare_digest(flow["proof"], challenge(verifier)): | |
| raise HTTPException(401, "This sign-in attempt expired. Please start again.") | |
| return flow | |
| async def callback(self, state, code, error, browser=""): | |
| self.prune() | |
| flow = self.flows.get(state) | |
| if not flow or flow["status"] != "pending" or not re.fullmatch(r"[A-Za-z0-9_-]{43}", browser) or not hmac.compare_digest(flow["browser"], browser): | |
| return "expired" | |
| # Mark before awaiting: the callback code/state cannot be replayed concurrently. | |
| flow["status"] = "exchanging" | |
| if error or not code: | |
| flow.update(status="error", error="Sign-in was cancelled. Your draft is unchanged.", expires=time.time() + 120) | |
| return "cancelled" | |
| try: | |
| token_response = await self.http.post(HUB + "/oauth/token", auth=(self.client_id, self.client_secret), | |
| data={"grant_type": "authorization_code", "code": code, "redirect_uri": self.origin + "/auth/callback", "code_verifier": flow.pop("verifier")}) | |
| token_response.raise_for_status() | |
| token = token_response.json() | |
| if not isinstance(token, dict): | |
| raise ValueError("Invalid token response") | |
| access_token = token.get("access_token") | |
| if not isinstance(access_token, str) or token.get("token_type", "").lower() != "bearer": | |
| raise ValueError("Invalid token response") | |
| response = await self.http.get(HUB + "/oauth/userinfo", headers={"Authorization": "Bearer " + access_token}) | |
| response.raise_for_status() | |
| profile = response.json() | |
| if not isinstance(profile, dict): | |
| raise ValueError("Invalid identity response") | |
| username = profile.get("preferred_username", "") | |
| if not profile.get("sub") or not isinstance(username, str) or not USERNAME.fullmatch(username): | |
| raise ValueError("Invalid identity response") | |
| ttl = min(self.SESSION_TTL, max(0, int(token.get("expires_in", self.SESSION_TTL)))) | |
| if ttl < 1: | |
| raise ValueError("Expired identity") | |
| # Only a public identity survives this callback. Discard all HF tokens. | |
| flow.update(status="ready", user={"username": username, "name": str(profile.get("name") or username)[:120]}, | |
| sessionExpires=time.time() + ttl, expires=time.time() + 120) | |
| return "success" | |
| except (httpx.HTTPError, ValueError, TypeError, KeyError): | |
| flow.update(status="error", error="HF sign-in could not be completed. Please try again.", expires=time.time() + 120) | |
| return "error" | |
| def poll(self, identifier, verifier): | |
| flow = self.flow(identifier, verifier) | |
| if flow["status"] == "error": | |
| return {"status": "error", "message": flow["error"]} | |
| if flow["status"] != "ready": | |
| return {"status": "pending"} | |
| if flow["sessionExpires"] <= time.time(): | |
| return {"status": "error", "message": "Sign-in expired. Please start again."} | |
| if "session" not in flow: | |
| if len(self.sessions) >= self.CAPACITY: | |
| raise HTTPException(429, "Sign-in is busy. Please try again shortly.") | |
| flow["session"] = secrets.token_urlsafe(32) | |
| self.sessions[flow["session"]] = {"user": flow["user"], "expires": flow["sessionExpires"]} | |
| return {"status": "ready", "session": flow["session"], "user": flow["user"], "expiresAt": flow["sessionExpires"]} | |
| def user(self, request): | |
| self.prune() | |
| token = request.headers.get("authorization", "").removeprefix("Bearer ") | |
| return self.sessions.get(token, {}).get("user") | |
| router = APIRouter() | |
| class StartBody(BaseModel): | |
| challenge: str = Field(pattern=r"^[A-Za-z0-9_-]{43}$") | |
| class PollBody(BaseModel): | |
| flow: str = Field(pattern=r"^[A-Za-z0-9_-]{43}$") | |
| verifier: str = Field(pattern=PROOF) | |
| async def me(request: Request): | |
| auth = request.app.state.identity | |
| return {"enabled": auth.enabled, "user": auth.user(request)} | |
| async def start(body: StartBody, request: Request): | |
| auth = request.app.state.identity | |
| if request.headers.get("origin") != auth.origin: | |
| raise HTTPException(403, "Start sign-in from HF Picks.") | |
| data = auth.start(body.challenge) | |
| response = JSONResponse(data) | |
| response.set_cookie("__Host-hf-picks-oauth", auth.flows[data["flow"]]["browser"], max_age=auth.FLOW_TTL, | |
| secure=True, httponly=True, samesite="lax", path="/") | |
| return response | |
| async def poll(body: PollBody, request: Request): | |
| return request.app.state.identity.poll(body.flow, body.verifier) | |
| async def navigate_start(request: Request, flow: str = Query(pattern=r"^[A-Za-z0-9_-]{43}$"), challenge: str = Query(pattern=r"^[A-Za-z0-9_-]{43}$")): | |
| auth = request.app.state.identity | |
| site = request.headers.get("sec-fetch-site", "") | |
| referrer = urlsplit(request.headers.get("referer", "")) | |
| origin = f"{referrer.scheme}://{referrer.netloc}" | |
| # A known flow/proof must never let a third-party site initiate a victim's login. | |
| if site not in ("", "same-origin") or (site != "same-origin" and origin != auth.origin): | |
| raise HTTPException(403, "Start sign-in from HF Picks.") | |
| data = auth.start(challenge, flow) | |
| response = RedirectResponse(data["authorizeUrl"], status_code=303) | |
| response.set_cookie("__Host-hf-picks-oauth", auth.flows[flow]["browser"], max_age=auth.FLOW_TTL, | |
| secure=True, httponly=True, samesite="lax", path="/") | |
| return response | |
| async def cancel(body: PollBody, request: Request): | |
| auth = request.app.state.identity | |
| auth.flow(body.flow, body.verifier) | |
| auth.flows.pop(body.flow, None) | |
| return {"ok": True} | |
| async def logout(request: Request): | |
| auth = request.app.state.identity | |
| token = request.headers.get("authorization", "").removeprefix("Bearer ") | |
| auth.sessions.pop(token, None) | |
| # A completed handoff cannot recreate a revoked session. | |
| for key in [k for k, v in auth.flows.items() if v.get("session") == token]: | |
| del auth.flows[key] | |
| return {"ok": True} | |
| async def callback(request: Request, state: str = Query("", max_length=128), code: str = Query("", max_length=2048), error: str = Query("", max_length=120)): | |
| status = await request.app.state.identity.callback(state, code, error, request.cookies.get("__Host-hf-picks-oauth", "")) | |
| response = RedirectResponse("/auth/complete?status=" + status, status_code=303) | |
| if status != "expired": | |
| response.delete_cookie("__Host-hf-picks-oauth", secure=True, httponly=True, samesite="lax", path="/") | |
| return response | |
| async def complete(): | |
| return FileResponse(ROOT / "static" / "auth.html", headers={"Cache-Control": "no-store"}) | |