Spaces:
Paused
Paused
File size: 7,339 Bytes
6049960 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | """Owner/guest isolation and Hugging Face OAuth for the public Space.
* Owner (HF user ABSOLUTION_OWNER, default 2Btainment) works in the data root
(existing bucket content, untouched).
* Everyone else works in <data_root>/guests/<namespace>/ where namespace is
"hf-<username>" for signed-in non-owners or "anon-<random>" per browser.
* The namespace is decided server-side from an HMAC-signed cookie only.
"""
from __future__ import annotations
import base64, contextvars, hashlib, hmac, json, os, re, secrets, shutil, threading, time
import urllib.parse, urllib.request
from pathlib import Path
OWNER = os.environ.get("ABSOLUTION_OWNER", "2Btainment")
COOKIE = "omega_session"
GUEST_TTL_SECONDS = float(os.environ.get("ABSOLUTION_GUEST_TTL_HOURS", "24")) * 3600
SESSION_MAX_AGE = 30 * 24 * 3600
current_root: contextvars.ContextVar[Path | None] = contextvars.ContextVar("omega_root", default=None)
current_identity: contextvars.ContextVar[dict | None] = contextvars.ContextVar("omega_identity", default=None)
def _b64(b: bytes) -> str:
return base64.urlsafe_b64encode(b).decode().rstrip("=")
def _unb64(s: str) -> bytes:
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
class Sessions:
def __init__(self, data_root: Path):
self.data_root = data_root
self.guest_root = data_root / "guests"
self.guest_root.mkdir(parents=True, exist_ok=True)
self.key = self._load_key()
def _load_key(self) -> bytes:
env = os.environ.get("OAUTH_CLIENT_SECRET") or os.environ.get("ABSOLUTION_SESSION_KEY")
if env:
return hashlib.sha256(b"omega-session-v1|" + env.encode()).digest()
path = self.guest_root / ".session_key"
try:
if path.is_file():
return path.read_bytes()
key = secrets.token_bytes(32)
path.write_bytes(key)
return key
except OSError:
return secrets.token_bytes(32)
def sign(self, payload: dict) -> str:
body = _b64(json.dumps(payload, separators=(",", ":")).encode())
mac = _b64(hmac.new(self.key, body.encode(), hashlib.sha256).digest())
return f"{body}.{mac}"
def verify(self, token: str | None) -> dict | None:
if not token or "." not in token:
return None
body, mac = token.rsplit(".", 1)
good = _b64(hmac.new(self.key, body.encode(), hashlib.sha256).digest())
if not hmac.compare_digest(mac, good):
return None
try:
data = json.loads(_unb64(body))
except ValueError:
return None
if not isinstance(data, dict) or data.get("exp", 0) < time.time():
return None
return data
def new_anonymous(self) -> dict:
return {"kind": "anon", "sid": secrets.token_hex(16), "exp": int(time.time()) + SESSION_MAX_AGE}
def for_user(self, username: str, previous: dict | None) -> dict:
sid = (previous or {}).get("sid") or secrets.token_hex(16)
return {"kind": "hf", "user": username, "sid": sid, "exp": int(time.time()) + SESSION_MAX_AGE}
@staticmethod
def is_owner(session: dict | None) -> bool:
return bool(session and session.get("kind") == "hf" and session.get("user") == OWNER)
def namespace(self, session: dict) -> tuple[str, Path]:
if self.is_owner(session):
return "owner", self.data_root
if session.get("kind") == "hf" and session.get("user"):
ns = "hf-" + re.sub(r"[^A-Za-z0-9_.-]", "_", session["user"])[:96]
else:
ns = "anon-" + re.sub(r"[^a-f0-9]", "", session.get("sid", ""))[:32]
if ns in ("anon-", "hf-"):
raise ValueError("invalid session")
root = self.guest_root / ns
root.mkdir(parents=True, exist_ok=True)
return ns, root
# ---- guest cleanup: only ever touches <data_root>/guests/<ns>/<project> ----
def cleanup(self) -> int:
removed = 0
now = time.time()
guest = self.guest_root.resolve()
for ns_dir in list(self.guest_root.iterdir()):
if not ns_dir.is_dir() or ns_dir.is_symlink():
continue
for proj in list(ns_dir.iterdir()):
if not proj.is_dir() or proj.is_symlink():
continue
if proj.resolve().parent.parent != guest:
continue
manifest = proj / "manifest.json"
ref = manifest if manifest.exists() else proj
if now - ref.stat().st_mtime > GUEST_TTL_SECONDS:
shutil.rmtree(proj, ignore_errors=True); removed += 1
try:
if not any(ns_dir.iterdir()):
ns_dir.rmdir()
except OSError:
pass
return removed
def start_cleanup_thread(self, interval: float = 3600):
def loop():
while True:
try:
self.cleanup()
except Exception:
pass
time.sleep(interval)
threading.Thread(target=loop, daemon=True, name="guest-cleanup").start()
# ---- Hugging Face OAuth (env vars injected by HF when README has hf_oauth: true) ----
def oauth_config() -> dict | None:
cid = os.environ.get("OAUTH_CLIENT_ID"); sec = os.environ.get("OAUTH_CLIENT_SECRET")
if not cid or not sec:
return None
return {"client_id": cid, "client_secret": sec,
"provider": os.environ.get("OPENID_PROVIDER_URL", "https://huggingface.co").rstrip("/"),
"scopes": os.environ.get("OAUTH_SCOPES", "openid profile"),
"host": os.environ.get("SPACE_HOST", "")}
def redirect_uri(cfg: dict, request_base: str) -> str:
base = f"https://{cfg['host']}" if cfg.get("host") else request_base.rstrip("/")
return base + "/login/callback"
def authorize_url(cfg: dict, redirect: str, state: str) -> str:
q = urllib.parse.urlencode({"client_id": cfg["client_id"], "redirect_uri": redirect,
"scope": cfg["scopes"], "response_type": "code", "state": state})
return f"{cfg['provider']}/oauth/authorize?{q}"
def exchange_code(cfg: dict, code: str, redirect: str) -> str:
data = urllib.parse.urlencode({"grant_type": "authorization_code", "code": code,
"redirect_uri": redirect, "client_id": cfg["client_id"]}).encode()
basic = base64.b64encode(f"{cfg['client_id']}:{cfg['client_secret']}".encode()).decode()
req = urllib.request.Request(f"{cfg['provider']}/oauth/token", data=data,
headers={"Authorization": f"Basic {basic}",
"Content-Type": "application/x-www-form-urlencoded"})
with urllib.request.urlopen(req, timeout=15) as r:
return json.loads(r.read())["access_token"]
def fetch_username(cfg: dict, token: str) -> str:
req = urllib.request.Request(f"{cfg['provider']}/oauth/userinfo",
headers={"Authorization": f"Bearer {token}"})
with urllib.request.urlopen(req, timeout=15) as r:
info = json.loads(r.read())
name = info.get("preferred_username") or info.get("name")
if not name:
raise ValueError("userinfo without username")
return str(name)
|