Skip to content

Commit 9362fd9

Browse files
abidlabsgradio-pr-botclaude
authored
Use local HF token in Workflow, gated behind a write-token auth model (#13520)
* Use local HF token in Workflow * add changeset * Gate Workflow editing and local HF token behind a write token Locally, launch() prints a private edit link carrying a per-process write_token (Jupyter-style); the frontend persists it as a cookie. Sessions without it - share links, tunnels, LAN visitors - get a read-only canvas, cannot save, and never receive the host's huggingface_hub token. On Spaces, write access requires OAuth as the Space owner or an org member with write access. Co-Authored-By: Claude Fable 5 <[email protected]> * Address review: simplify token helpers, use whoami cache, trim tests - Move huggingface_hub imports to top of file; drop defensive try/except in _get_locally_saved_hf_token - Drop the GRADIO_WORKFLOW_WRITE_TOKEN env override - Replace the hand-rolled TTL cache with whoami(cache=True) on a shared HfApi instance - Consolidate write-access tests and remove trivial/duplicated ones Co-Authored-By: Claude Fable 5 <[email protected]> * changes * changes * Remove changesets so CI regenerates one Co-Authored-By: Claude Fable 5 <[email protected]> * add changeset * Address Copilot review: respect quiet, Secure cookie, defer autosave - Gate the edit-link print behind quiet=True so the write token can't leak into logs when silence was requested - Mark the write-token cookie Secure when served over HTTPS - Defer autosave until the write-access check answers, so guests in the optimistic window don't fire saves the backend rejects Co-Authored-By: Claude Fable 5 <[email protected]> * Fix typecheck: use a real gr.Request in workflow tests ty rejects SimpleNamespace where Request | None is expected; Request supports kwargs-based construction for exactly this testing use. Co-Authored-By: Claude Fable 5 <[email protected]> * changes * changes * changes * changes * changes --------- Co-authored-by: gradio-pr-bot <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
1 parent af4945f commit 9362fd9

13 files changed

Lines changed: 1196 additions & 221 deletions

‎.changeset/wise-buttons-relate.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@gradio/workflowcanvas": minor
3+
"gradio": minor
4+
---
5+
6+
feat:Use local HF token in Workflow, gated behind a write-token auth model

‎gradio/helpers.py‎

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import os
1212
import shutil
1313
import warnings
14-
from collections.abc import Callable, Iterable, Sequence
14+
from collections.abc import Callable, Iterable, MutableMapping, Sequence
1515
from functools import partial
1616
from pathlib import Path
1717
from types import SimpleNamespace
@@ -915,6 +915,26 @@ def create_tracker(fn, track_tqdm):
915915
)
916916

917917

918+
def _session_from_request(request: Any) -> MutableMapping[str, Any]:
919+
"""Return the request's session, or an empty mapping if there is no session
920+
to read (the normal case for apps without OAuth / SessionMiddleware).
921+
922+
For a real Starlette/fastapi request the session lives in `scope["session"]`;
923+
touching `.session` directly would raise Starlette's "SessionMiddleware must
924+
be installed" assertion when it's absent, so we gate on `scope` membership
925+
instead. A `gr.Request` exposes the fastapi request as `.request`; objects
926+
without a Starlette `scope` (a queued `gr.Request` rebuilt from kwargs) may
927+
still carry a plain `.session`.
928+
"""
929+
if request is None:
930+
return {}
931+
underlying = getattr(request, "request", None) or request
932+
scope = getattr(underlying, "scope", None)
933+
if isinstance(scope, dict):
934+
return scope.get("session", {})
935+
return getattr(underlying, "session", None) or {}
936+
937+
918938
def special_args(
919939
fn: Callable,
920940
inputs: list[Any] | None = None,
@@ -969,32 +989,14 @@ def special_args(
969989
oauth.OAuthToken,
970990
):
971991
if inputs is not None:
972-
# Retrieve session from gr.Request, if it exists (i.e. if user is logged in)
973-
try:
974-
session = (
975-
# request.session (if fastapi.Request obj i.e. direct call)
976-
getattr(request, "session", {})
977-
or
978-
# or request.request.session (if gr.Request obj i.e. websocket call)
979-
getattr(getattr(request, "request", None), "session", {})
980-
)
981-
except AssertionError as e:
982-
if (
983-
"SessionMiddleware must be installed to access request.session"
984-
in str(e)
985-
):
986-
warnings.warn(
987-
"Empty session being created. Install gradio[oauth] and add a gr.LoginButton to your app to enable OAuth login.",
988-
UserWarning,
989-
)
990-
session = {}
991-
else:
992-
raise e
993-
994-
# `session` is usually a copy of the underlying session (gr.Request
995-
# converts it to an `Obj`), so expiry means "treat as logged out"
996-
# here; the session entry itself is only removed on the next
997-
# LoginButton page-load check, which operates on the raw session.
992+
# Read the session if a SessionMiddleware is installed (i.e. the
993+
# user may be logged in); otherwise treat as logged out. Required
994+
# OAuth params still raise an explicit error below.
995+
session = _session_from_request(request)
996+
997+
# Expiry means "treat as logged out" here; the session entry
998+
# itself is only removed on the next LoginButton page-load check,
999+
# which operates on the raw session.
9981000
oauth_info = oauth._get_valid_oauth_info_from_session(session)
9991001

10001002
# Inject user profile

0 commit comments

Comments
 (0)