NINA / auth.py
Malina
Claude Fable 5.1
v0.90: scoped single-use tokens, hardened link fetch, 45-minute cap, whole-video digest, one classification call, no OCR
1d697a7
Raw History Blame
4.15 kB
# Per-use signed-token verification. NINA and LUNA share this file byte for byte:
# change one, copy to the other.
#
# Token = base64url(JSON{u,e,j,s,k,iat}) "." base64url(HMAC-SHA256(secret, msg)).
# u user id s SCOPE: the api_name this token may start (run, chat,
# e expiry (epoch s) route, fetch, build, clarify)
# j single-use id k "consume" when a use was charged for it, else "free"
# iat issued-at
#
# Fail closed: no secret means every request is refused, and that is announced at
# import. A token without a scope is accepted only until TOKEN_REQUIRE_SCOPE=1 is set
# on the Space (rollout: Spaces first, then the Worker emits scopes, then the switch).
# Used jtis are kept in memory AND in a small file, so a restart inside a token's
# lifetime does not reopen it for replay.
import base64
import hashlib
import hmac
import json
import os
import tempfile
import threading
import time
from config import SIGNING_SECRET, SPACE_TAG
REQUIRE_SCOPE = os.getenv("TOKEN_REQUIRE_SCOPE", "0") == "1"
_MAX_FUTURE_SKEW = 60 # an iat this far ahead of our clock is not ours
_MAX_LIFETIME = 900 # the Worker issues 600 s; anything longer is suspicious
_JTI_FILE = os.path.join(tempfile.gettempdir(), f"{SPACE_TAG}_used_jti.json")
if not SIGNING_SECRET:
print(f"[{SPACE_TAG.upper()}] WARNING: signing secret is not set - every request will be "
"refused. Set it in Settings > Variables and secrets.", flush=True)
_jti_lock = threading.Lock()
def _load_jti() -> dict:
try:
with open(_JTI_FILE, encoding="utf-8") as f:
d = json.load(f)
now = int(time.time())
return {k: int(v) for k, v in d.items() if int(v) >= now}
except Exception:
return {}
_used_jti: dict = _load_jti()
def _save_jti() -> None:
try:
tmp = _JTI_FILE + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(_used_jti, f)
os.replace(tmp, _JTI_FILE)
except Exception:
pass
def _b64url_decode(s: str) -> bytes:
return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
def check_usage_token(token: str, scope: str | None = None) -> str:
"""Return "ok", or a short reason: unconfigured, missing, bad-signature, expired,
future, missing-scope, wrong-scope, replayed. The reason lets the caller tell a
token that waited out its life in the queue from a forged one."""
if not SIGNING_SECRET:
return "unconfigured"
if not token or "." not in token or len(token) > 2048:
return "missing"
try:
msg, sig = token.rsplit(".", 1)
expected = hmac.new(SIGNING_SECRET.encode(), msg.encode(), hashlib.sha256).digest()
try:
got = _b64url_decode(sig)
except Exception:
return "bad-signature"
if not hmac.compare_digest(expected, got):
return "bad-signature"
payload = json.loads(_b64url_decode(msg))
now = int(time.time())
exp = int(payload.get("e", 0))
if exp < now:
return "expired"
iat = payload.get("iat")
if iat is not None:
iat = int(iat)
if iat > now + _MAX_FUTURE_SKEW:
return "future"
if exp - iat > _MAX_LIFETIME:
return "expired"
s = payload.get("s")
if scope:
if s is None:
if REQUIRE_SCOPE:
return "missing-scope"
elif not hmac.compare_digest(str(s), scope):
return "wrong-scope"
jti = payload.get("j", "")
if not jti or not isinstance(jti, str) or len(jti) > 64:
return "missing"
with _jti_lock:
for k in [k for k, e in _used_jti.items() if e < now]:
_used_jti.pop(k, None)
if jti in _used_jti:
return "replayed"
_used_jti[jti] = exp
_save_jti()
return "ok"
except Exception:
return "bad-signature"
def verify_usage_token(token: str, scope: str | None = None) -> bool:
return check_usage_token(token, scope) == "ok"