absolution-omega / app /access.py
2Btainment's picture
Owner-only project library via HF OAuth; isolated 24h guest workspaces (server-side enforced)
6049960 verified
Raw History Blame Contribute Delete
7.34 kB
"""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)