Files

346 lines
16 KiB
Python

"""What the MCP endpoint remembers (``/data/mcp.json``): the apps that
registered (OAuth dynamic client registration), the authorization requests
waiting for the owner's approval, the one-time codes, and the **connections**
(grants) — one per app the owner or a guest let in — with the access /
refresh tokens they hold, and the settings (which tool groups are on).
Every secret is stored hashed (sha256), like ``auth.json``. Revoking a
connection drops its tokens at once. A request leaves the store the moment it
is decided, its code handed to the caller that decided it; a rolled refresh
token is remembered, so its reuse (somebody else holds a copy) ends the
connection. Expired codes, requests and tokens, and
apps that registered but were never approved (a day on), are pruned on write.
"""
from __future__ import annotations
import base64
import hashlib
import secrets
import time
from users.store import _JsonFile, _hash
ACCESS_TTL_S = 3600 # an access token: an hour
REFRESH_TTL_S = 90 * 86400 # a refresh token: 90 days, rolled on every use
CODE_TTL_S = 300 # an authorization code: 5 minutes
PENDING_TTL_S = 15 * 60 # an approval waits a quarter of an hour
STALE_CLIENT_S = 86400 # a registered app nobody approved: a day
MAX_CLIENTS = 200 # registration is open — cap it
# A refresh token stays good this long after it was rolled: two requests
# racing on the same refresh must not lock the app out.
REFRESH_GRACE_S = 60
LAST_USED_EVERY_S = 60 # `lastUsed` is written at most this often
# Token records kept per connection — live ones and the rolled refresh tokens
# remembered for reuse detection. An app that rolls in a loop can't grow the
# file: the oldest generations go first.
MAX_TOKENS_PER_GRANT = 12
SCOPES = ("read", "full")
# The tool groups on (cli/mcp_tools.py GROUPS) and the cap on a tool's wait.
DEFAULT_SETTINGS = {"groups": ["read", "run", "agents"], "maxWaitS": 50}
def _id(prefix: str) -> str:
return prefix + secrets.token_hex(8)
def pkce_ok(verifier: str, challenge: str) -> bool:
"""RFC 7636 S256: BASE64URL(SHA256(verifier)) == challenge."""
if not verifier or not challenge or not 43 <= len(verifier) <= 128:
return False
digest = hashlib.sha256(verifier.encode()).digest()
want = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
return secrets.compare_digest(want, challenge)
class McpStore(_JsonFile):
def __init__(self, path: str):
super().__init__(path, {"clients": {}, "pending": {}, "codes": {},
"grants": {}, "tokens": {}, "settings": {}})
# ── housekeeping ─────────────────────────────────────────────────────────
def _prune(self, now: float) -> None:
d = self._data
for kind in ("pending", "codes", "tokens"):
for k in [k for k, r in d[kind].items() if r.get("exp", 0) < now]:
del d[kind][k]
used = {g.get("client") for g in d["grants"].values()}
for cid in [c for c, r in d["clients"].items()
if c not in used and r.get("created", 0) < now - STALE_CLIENT_S]:
del d["clients"][cid]
# ── clients (RFC 7591) ───────────────────────────────────────────────────
def register(self, *, name: str, redirect_uris: list[str], auth_method: str,
uri: str = "") -> tuple[str, str | None]:
"""A new app: (client_id, client_secret or None for a public one)."""
now = time.time()
secret = secrets.token_urlsafe(32) if auth_method != "none" else None
cid = _id("mcpc_")
with self._lock:
self._prune(now)
if len(self._data["clients"]) >= MAX_CLIENTS:
raise OverflowError("too many registered apps")
self._data["clients"][cid] = {
"name": name[:80], "redirectUris": redirect_uris, "authMethod": auth_method,
"secret": _hash(secret) if secret else None, "uri": uri[:200], "created": now}
self._save()
return cid, secret
def client(self, cid: str) -> dict | None:
with self._lock:
c = self._data["clients"].get(cid or "")
return dict(c) if c else None
def client_ok(self, cid: str, secret: str | None) -> bool:
"""The token endpoint's client check: a public client presents no
secret, a confidential one its own."""
c = self.client(cid)
if not c:
return False
if not c.get("secret"):
return True
return bool(secret) and secrets.compare_digest(c["secret"], _hash(secret))
# ── authorization requests waiting for an approval ───────────────────────
def add_pending(self, req: dict) -> str:
rid = secrets.token_urlsafe(24)
now = time.time()
with self._lock:
self._prune(now)
self._data["pending"][rid] = {**req, "status": "pending", "created": now,
"exp": now + PENDING_TTL_S}
self._save()
return rid
def pending(self, rid: str) -> dict | None:
with self._lock:
r = self._data["pending"].get(rid or "")
if not r or r.get("exp", 0) < time.time():
return None
return dict(r)
def pending_list(self) -> list[dict]:
now = time.time()
with self._lock:
return [{"id": k, **v} for k, v in self._data["pending"].items()
if v.get("exp", 0) >= now and v.get("status") == "pending"]
def update_pending(self, rid: str, patch: dict) -> dict | None:
with self._lock:
r = self._data["pending"].get(rid or "")
if not r:
return None
r.update(patch)
self._save()
return dict(r)
def decide(self, rid: str, *, approve: bool, user: str, scope: str | None = None,
via: str = "") -> dict | None:
"""Approve (mint the code) or deny a pending request, once — and take
it out of the store in the same step. Returns the request as decided,
with ``code`` when approved; None when it is gone or was already
decided.
The code is handed to this caller and nobody else: it is never parked
on the request, so someone polling the request's id can't collect a
code another browser's approval minted."""
now = time.time()
with self._lock:
r = self._data["pending"].get(rid or "")
if not r or r.get("exp", 0) < now or r.get("status") != "pending":
return None
del self._data["pending"][rid]
if not approve:
self._save()
return {**r, "status": "denied", "decidedAt": now, "via": via}
scope = scope if scope in SCOPES else r.get("scope") or "full"
code = secrets.token_urlsafe(32)
self._data["codes"][_hash(code)] = {
"client": r["client"], "user": user, "scope": scope,
"redirectUri": r["redirectUri"], "challenge": r["challenge"],
"resource": r.get("resource") or "", "exp": now + CODE_TTL_S}
self._save()
return {**r, "status": "approved", "decidedAt": now, "user": user,
"scope": scope, "via": via, "code": code}
# ── codes → tokens ───────────────────────────────────────────────────────
def redeem(self, code: str, *, client: str, redirect_uri: str, verifier: str) -> dict | None:
"""One code, once: the grant it mints with its first token pair."""
now = time.time()
with self._lock:
rec = self._data["codes"].pop(_hash(code or ""), None)
if rec:
self._save()
if (not rec or rec["exp"] < now or rec["client"] != client
or rec["redirectUri"] != redirect_uri or not pkce_ok(verifier, rec["challenge"])):
return None
c = self.client(client) or {}
gid = _id("mcpg_")
with self._lock:
self._data["grants"][gid] = {
"kind": "oauth", "client": client, "name": c.get("name") or "an app",
"user": rec["user"], "scope": rec["scope"], "created": now, "lastUsed": None}
out = self._mint(gid, now)
self._save()
return out
def _mint(self, gid: str, now: float) -> dict:
"""A new token pair for a grant — the next *generation* (``gen``),
which is what refresh reuse detection compares."""
g = self._data["grants"][gid]
gen = g["gen"] = int(g.get("gen") or 0) + 1
access, refresh = "aia_mcp_" + secrets.token_urlsafe(32), "aia_mcpr_" + secrets.token_urlsafe(32)
self._data["tokens"][_hash(access)] = {"grant": gid, "kind": "access", "gen": gen,
"exp": now + ACCESS_TTL_S}
self._data["tokens"][_hash(refresh)] = {"grant": gid, "kind": "refresh", "gen": gen,
"exp": now + REFRESH_TTL_S}
mine = sorted(((r.get("gen") or 0, r.get("exp") or 0, k)
for k, r in self._data["tokens"].items() if r.get("grant") == gid))
for _, _, k in mine[:max(0, len(mine) - MAX_TOKENS_PER_GRANT)]:
del self._data["tokens"][k]
return {"access_token": access, "refresh_token": refresh, "token_type": "Bearer",
"expires_in": ACCESS_TTL_S, "scope": g["scope"]}
def _used(self, g: dict, rec: dict) -> bool:
"""Note that a token of this generation was presented; True when that
is news (the caller saves)."""
gen = rec.get("gen") or 0
if gen > int(g.get("usedGen") or 0):
g["usedGen"] = gen
return True
return False
def _drop_grant(self, gid: str) -> bool:
if not self._data["grants"].pop(gid or "", None):
return False
for k in [k for k, r in self._data["tokens"].items() if r.get("grant") == gid]:
del self._data["tokens"][k]
return True
def refresh(self, token: str, *, client: str) -> dict | None:
"""Roll a refresh token. The rolled one is remembered (not usable):
* within ``REFRESH_GRACE_S`` it still works — two requests racing on
the same token must not lock the app out;
* later, if a token minted *after* it was ever used, somebody else
holds a copy: the whole connection is revoked (RFC 9700 §4.14.2);
* later, and nothing newer was ever used, the app never got our
answer: it is served again, and the unused newer tokens die."""
now = time.time()
with self._lock:
self._prune(now)
rec = self._data["tokens"].get(_hash(token or ""))
if not rec or rec.get("kind") != "refresh" or rec["exp"] < now:
return None
gid = rec["grant"]
g = self._data["grants"].get(gid)
if not g or g.get("client") != client:
return None
gen = rec.get("gen") or 0
rolled = rec.get("rolledAt")
if rolled and now - rolled > REFRESH_GRACE_S:
if int(g.get("usedGen") or 0) > gen:
self._drop_grant(gid)
self._save()
return None
for k in [k for k, r in self._data["tokens"].items()
if r.get("grant") == gid and (r.get("gen") or 0) > gen]:
del self._data["tokens"][k]
self._used(g, rec)
rec.setdefault("rolledAt", now)
out = self._mint(gid, now)
self._save()
return out
def revoke_token(self, token: str) -> bool:
"""RFC 7009. A refresh token takes its whole connection with it (the
app is disconnecting); an access token only itself. True when a
connection ended."""
with self._lock:
rec = self._data["tokens"].pop(_hash(token or ""), None)
if not rec:
return False
gone = rec.get("kind") == "refresh" and self._drop_grant(rec.get("grant") or "")
self._save()
return bool(gone)
# ── settings ─────────────────────────────────────────────────────────────
def settings(self) -> dict:
with self._lock:
return {**DEFAULT_SETTINGS, **(self._data.get("settings") or {})}
def set_settings(self, patch: dict) -> dict:
with self._lock:
self._data["settings"] = {**self.settings(), **patch}
self._save()
return dict(self._data["settings"])
# ── who a bearer token is ────────────────────────────────────────────────
def authenticate(self, token: str) -> dict | None:
"""The grant an access token belongs to, with its id."""
if not token:
return None
now = time.time()
with self._lock:
rec = self._data["tokens"].get(_hash(token))
if not rec or rec.get("kind") == "refresh" or rec["exp"] < now:
return None
g = self._data["grants"].get(rec["grant"])
if not g:
return None
news = self._used(g, rec)
if news or not g.get("lastUsed") or now - g["lastUsed"] > LAST_USED_EVERY_S:
g["lastUsed"] = now
self._save()
return {"id": rec["grant"], **g}
# ── connections (the Settings page) ──────────────────────────────────────
def grants(self, user: str | None = None) -> list[dict]:
with self._lock:
rows = [{"id": k, **v} for k, v in self._data["grants"].items()
if user is None or v.get("user") == user]
clients = self._data["clients"]
for r in rows:
c = clients.get(r.get("client") or "") or {}
r["redirectHost"] = _host((c.get("redirectUris") or [""])[0])
return sorted(rows, key=lambda r: r.get("created") or 0, reverse=True)
def grant(self, gid: str) -> dict | None:
with self._lock:
g = self._data["grants"].get(gid or "")
return {"id": gid, **g} if g else None
def update_grant(self, gid: str, patch: dict) -> dict | None:
with self._lock:
g = self._data["grants"].get(gid or "")
if not g:
return None
g.update(patch)
self._save()
return {"id": gid, **g}
def revoke(self, gid: str) -> bool:
with self._lock:
if not self._drop_grant(gid):
return False
self._save()
return True
def revoke_user(self, uid: str) -> int:
"""Every connection of one user, gone — a deleted guest's apps must
not outlive them. How many were dropped."""
if not uid:
return 0
with self._lock:
gids = [k for k, g in self._data["grants"].items() if g.get("user") == uid]
for gid in gids:
self._drop_grant(gid)
if gids:
self._save()
return len(gids)
def _host(uri: str) -> str:
rest = uri.split("://", 1)[-1]
return rest.split("/", 1)[0] if "://" in uri else uri.split(":", 1)[0]