Spaces:
Paused
Paused
File size: 4,153 Bytes
da9de03 e0ee73b da9de03 281f5b1 da9de03 281f5b1 da9de03 281f5b1 e0ee73b da9de03 e0ee73b 281f5b1 da9de03 281f5b1 da9de03 281f5b1 da9de03 281f5b1 da9de03 281f5b1 e0ee73b da9de03 acf555c 281f5b1 da9de03 acf555c 281f5b1 da9de03 acf555c da9de03 281f5b1 da9de03 acf555c 281f5b1 acf555c da9de03 acf555c 281f5b1 acf555c da9de03 | 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 | # 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"
|