Files
smeta-web/mcp_identity.py
T

363 lines
20 KiB
Python

"""OAuth state for the external MCP endpoint. Only hashes of grants/tokens reach SQLite."""
from __future__ import annotations
import asyncio
import base64
from contextlib import closing
import hashlib
import json
import os
import secrets
import time
from urllib.parse import urlencode, urlparse
from cryptography.fernet import Fernet
from mcp.server.auth.provider import (
AccessToken, AuthorizationCode, AuthorizationParams, AuthorizeError,
RefreshToken, RegistrationError, TokenError, construct_redirect_uri,
)
from mcp.shared.auth import OAuthClientInformationFull, OAuthToken
import db
SCOPES = frozenset({
"norms:read", "estimates:read", "estimates:write", "files:read", "files:write",
"chat:run", "reviews:run", "stove:estimate", "account:read",
})
ACCESS_TTL = 3600
REFRESH_TTL = 30 * 86400
GRANT_TTL = 300
def _digest(value: str) -> str:
return hashlib.sha256(value.encode()).hexdigest()
def _cipher() -> Fernet:
secret = os.environ.get("SESSION_SECRET", "")
if not secret:
raise RuntimeError("SESSION_SECRET is required for MCP client credential storage")
key = base64.urlsafe_b64encode(hashlib.sha256(("mcp-client:" + secret).encode()).digest())
return Fernet(key)
def init_db() -> None:
with closing(db._conn()) as conn, conn:
conn.executescript("""
CREATE TABLE IF NOT EXISTS mcp_oauth_clients (
client_id TEXT PRIMARY KEY, metadata TEXT NOT NULL, secret_cipher BLOB,
created_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS mcp_oauth_pending (
ticket_hash TEXT PRIMARY KEY, client_id TEXT NOT NULL, params TEXT NOT NULL,
expires_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS mcp_oauth_codes (
code_hash TEXT PRIMARY KEY, client_id TEXT NOT NULL, grant TEXT NOT NULL,
expires_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS mcp_oauth_tokens (
token_hash TEXT PRIMARY KEY, kind TEXT NOT NULL, family TEXT NOT NULL,
client_id TEXT NOT NULL, username TEXT NOT NULL, scopes TEXT NOT NULL,
resource TEXT NOT NULL, expires_at REAL NOT NULL, revoked_at REAL
);
CREATE INDEX IF NOT EXISTS idx_mcp_oauth_tokens_user
ON mcp_oauth_tokens(username, client_id, revoked_at);
CREATE TABLE IF NOT EXISTS mcp_oauth_consents (
username TEXT NOT NULL, client_id TEXT NOT NULL, scopes TEXT NOT NULL,
approved_at REAL NOT NULL, revoked_at REAL,
PRIMARY KEY(username, client_id)
);
CREATE TABLE IF NOT EXISTS mcp_pending_actions (
ticket_hash TEXT PRIMARY KEY, username TEXT NOT NULL, client_id TEXT NOT NULL,
tab_id TEXT NOT NULL, kind TEXT NOT NULL, expires_at REAL NOT NULL,
approved_at REAL
);
""")
def _active_user(username: str) -> bool:
user = db.get_user_by_email(username)
return bool(user and user.get("verified") and not user.get("blocked")
and not user.get("deleted_at"))
class InfosmetaOAuthProvider:
"""Persistent OAuth provider used by the SDK's AS and bearer middleware."""
def __init__(self, issuer: str, resource: str):
self.issuer = issuer.rstrip("/")
self.resource = resource.rstrip("/")
if not self.resource.startswith(self.issuer + "/"):
raise ValueError("MCP resource must be within issuer origin")
init_db()
async def get_client(self, client_id: str) -> OAuthClientInformationFull | None:
def read():
with closing(db._conn()) as conn:
return conn.execute("SELECT metadata, secret_cipher FROM mcp_oauth_clients WHERE client_id=?",
(client_id,)).fetchone()
row = await asyncio.to_thread(read)
if row is None:
return None
data = json.loads(row["metadata"])
if row["secret_cipher"]:
data["client_secret"] = _cipher().decrypt(row["secret_cipher"]).decode()
return OAuthClientInformationFull.model_validate(data)
async def register_client(self, client_info: OAuthClientInformationFull) -> None:
if not client_info.redirect_uris or len(client_info.redirect_uris) > 8:
raise RegistrationError("invalid_redirect_uri", "One to eight redirect URIs are required")
for uri in client_info.redirect_uris:
parsed = urlparse(str(uri))
loopback = parsed.hostname in {"localhost", "127.0.0.1", "::1"}
if parsed.scheme != "https" and not (parsed.scheme == "http" and loopback):
raise RegistrationError("invalid_redirect_uri", "Use HTTPS or localhost loopback")
if parsed.fragment or parsed.username or parsed.password:
raise RegistrationError("invalid_redirect_uri", "Redirect URI must not contain credentials or fragment")
requested = set((client_info.scope or "").split())
if not requested.issubset(SCOPES):
raise RegistrationError("invalid_client_metadata", "Unknown scope")
metadata = client_info.model_dump(mode="json")
secret = metadata.pop("client_secret", None)
ciphertext = _cipher().encrypt(secret.encode()) if secret else None
def write():
with closing(db._conn()) as conn, conn:
conn.execute("INSERT INTO mcp_oauth_clients VALUES (?, ?, ?, ?)",
(client_info.client_id, json.dumps(metadata), ciphertext, time.time()))
await asyncio.to_thread(write)
async def authorize(self, client: OAuthClientInformationFull,
params: AuthorizationParams) -> str:
if params.resource != self.resource:
raise AuthorizeError("invalid_target", "Token is only issued for this MCP resource")
scopes = params.scopes or []
if not scopes or not set(scopes).issubset(SCOPES):
raise AuthorizeError("invalid_scope", "No supported scopes requested")
ticket = secrets.token_urlsafe(32)
def write():
with closing(db._conn()) as conn, conn:
conn.execute("INSERT INTO mcp_oauth_pending VALUES (?, ?, ?, ?)",
(_digest(ticket), client.client_id,
params.model_dump_json(), time.time() + GRANT_TTL))
await asyncio.to_thread(write)
return f"{self.issuer}/oauth/consent?{urlencode({'ticket': ticket})}"
async def pending(self, ticket: str) -> dict | None:
def read():
with closing(db._conn()) as conn:
return conn.execute("SELECT p.client_id, p.params, p.expires_at, c.metadata "
"FROM mcp_oauth_pending p JOIN mcp_oauth_clients c "
"ON c.client_id=p.client_id WHERE p.ticket_hash=?",
(_digest(ticket),)).fetchone()
row = await asyncio.to_thread(read)
if row is None or row["expires_at"] < time.time():
return None
params = AuthorizationParams.model_validate_json(row["params"])
meta = json.loads(row["metadata"])
return {"client_id": row["client_id"], "client_name": meta.get("client_name") or row["client_id"],
"scopes": params.scopes or [], "redirect_uri": str(params.redirect_uri)}
async def confirm(self, ticket: str, username: str, *, approved: bool) -> str:
if approved and not await asyncio.to_thread(_active_user, username):
raise ValueError("Account is unavailable")
def write():
with closing(db._conn()) as conn, conn:
conn.execute("BEGIN IMMEDIATE")
row = conn.execute("SELECT client_id, params, expires_at FROM mcp_oauth_pending "
"WHERE ticket_hash=?", (_digest(ticket),)).fetchone()
if row is None or row["expires_at"] < time.time():
raise ValueError("Consent request expired")
conn.execute("DELETE FROM mcp_oauth_pending WHERE ticket_hash=?", (_digest(ticket),))
params = AuthorizationParams.model_validate_json(row["params"])
if not approved:
return construct_redirect_uri(str(params.redirect_uri),
error="access_denied", state=params.state, iss=self.issuer)
code = secrets.token_urlsafe(32)
grant = AuthorizationCode(code=code, scopes=params.scopes or [],
expires_at=time.time() + GRANT_TTL, client_id=row["client_id"],
code_challenge=params.code_challenge, redirect_uri=params.redirect_uri,
redirect_uri_provided_explicitly=params.redirect_uri_provided_explicitly,
resource=self.resource, subject=username)
data = grant.model_dump(mode="json", exclude={"code"})
conn.execute("INSERT INTO mcp_oauth_codes VALUES (?, ?, ?, ?)",
(_digest(code), row["client_id"], json.dumps(data), grant.expires_at))
conn.execute("INSERT INTO mcp_oauth_consents VALUES (?, ?, ?, ?, NULL) "
"ON CONFLICT(username,client_id) DO UPDATE SET "
"scopes=excluded.scopes, approved_at=excluded.approved_at, revoked_at=NULL",
(username, row["client_id"], json.dumps(grant.scopes), time.time()))
return construct_redirect_uri(str(params.redirect_uri), code=code,
state=params.state, iss=self.issuer)
return await asyncio.to_thread(write)
async def load_authorization_code(self, client: OAuthClientInformationFull,
authorization_code: str) -> AuthorizationCode | None:
def read():
with closing(db._conn()) as conn:
return conn.execute("SELECT grant, expires_at FROM mcp_oauth_codes "
"WHERE code_hash=? AND client_id=?",
(_digest(authorization_code), client.client_id)).fetchone()
row = await asyncio.to_thread(read)
if row is None or row["expires_at"] < time.time():
return None
return AuthorizationCode.model_validate({**json.loads(row["grant"]), "code": authorization_code})
def _issue(self, conn, *, client_id: str, username: str, scopes: list[str],
resource: str, family: str | None = None) -> OAuthToken:
family = family or secrets.token_urlsafe(24)
access, refresh = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
now = time.time()
for raw, kind, expires in ((access, "access", now + ACCESS_TTL),
(refresh, "refresh", now + REFRESH_TTL)):
conn.execute("INSERT INTO mcp_oauth_tokens VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL)",
(_digest(raw), kind, family, client_id, username,
json.dumps(scopes), resource, expires))
return OAuthToken(access_token=access, refresh_token=refresh, expires_in=ACCESS_TTL,
scope=" ".join(scopes))
async def exchange_authorization_code(self, client: OAuthClientInformationFull,
authorization_code: AuthorizationCode) -> OAuthToken:
if not authorization_code.subject or not await asyncio.to_thread(_active_user, authorization_code.subject):
raise TokenError("invalid_grant", "Account is unavailable")
def write():
with closing(db._conn()) as conn, conn:
row = conn.execute("DELETE FROM mcp_oauth_codes WHERE code_hash=? AND client_id=? "
"RETURNING grant", (_digest(authorization_code.code), client.client_id)).fetchone()
if row is None:
raise TokenError("invalid_grant", "Authorization code was already used")
saved = AuthorizationCode.model_validate({**json.loads(row["grant"]),
"code": authorization_code.code})
if saved.expires_at < time.time() or saved.subject != authorization_code.subject \
or saved.resource != self.resource:
raise TokenError("invalid_grant", "Authorization code is invalid")
return self._issue(conn, client_id=client.client_id, username=saved.subject,
scopes=saved.scopes, resource=self.resource)
return await asyncio.to_thread(write)
async def load_refresh_token(self, client: OAuthClientInformationFull,
refresh_token: str) -> RefreshToken | None:
row = await asyncio.to_thread(self._token_row, refresh_token, "refresh", client.client_id)
if row is None:
return None
return RefreshToken(token=refresh_token, client_id=client.client_id,
scopes=json.loads(row["scopes"]), expires_at=int(row["expires_at"]),
resource=row["resource"], subject=row["username"])
async def exchange_refresh_token(self, client: OAuthClientInformationFull,
refresh_token: RefreshToken, scopes: list[str]) -> OAuthToken:
if not set(scopes).issubset(refresh_token.scopes):
raise TokenError("invalid_scope", "Scope expansion requires consent")
if not refresh_token.subject or not await asyncio.to_thread(_active_user, refresh_token.subject):
raise TokenError("invalid_grant", "Account is unavailable")
def write():
with closing(db._conn()) as conn, conn:
conn.execute("BEGIN IMMEDIATE")
row = conn.execute("SELECT family, expires_at FROM mcp_oauth_tokens "
"WHERE token_hash=? AND kind='refresh' AND client_id=? "
"AND revoked_at IS NULL", (_digest(refresh_token.token), client.client_id)).fetchone()
if row is None or row["expires_at"] < time.time():
raise TokenError("invalid_grant", "Refresh token was already used")
conn.execute("UPDATE mcp_oauth_tokens SET revoked_at=? WHERE family=? AND revoked_at IS NULL",
(time.time(), row["family"]))
return self._issue(conn, client_id=client.client_id, username=refresh_token.subject,
scopes=scopes or refresh_token.scopes, resource=self.resource,
family=row["family"])
return await asyncio.to_thread(write)
def _token_row(self, raw: str, kind: str, client_id: str | None = None):
with closing(db._conn()) as conn:
query = "SELECT * FROM mcp_oauth_tokens WHERE token_hash=? AND kind=? AND revoked_at IS NULL"
args: tuple = (_digest(raw), kind)
if client_id is not None:
query += " AND client_id=?"
args += (client_id,)
row = conn.execute(query, args).fetchone()
if row is None or row["expires_at"] < time.time() or row["resource"] != self.resource:
return None
return row if _active_user(row["username"]) else None
async def load_access_token(self, token: str) -> AccessToken | None:
row = await asyncio.to_thread(self._token_row, token, "access")
if row is None:
return None
return AccessToken(token=token, client_id=row["client_id"],
scopes=json.loads(row["scopes"]), expires_at=int(row["expires_at"]),
resource=row["resource"], subject=row["username"],
claims={"iss": self.issuer})
async def revoke_token(self, token: AccessToken | RefreshToken) -> None:
def write():
with closing(db._conn()) as conn, conn:
row = conn.execute("SELECT family FROM mcp_oauth_tokens WHERE token_hash=?",
(_digest(token.token),)).fetchone()
if row:
conn.execute("UPDATE mcp_oauth_tokens SET revoked_at=? WHERE family=? AND revoked_at IS NULL",
(time.time(), row["family"]))
await asyncio.to_thread(write)
async def revoke_client_for_user(self, username: str, client_id: str) -> None:
def write():
with closing(db._conn()) as conn, conn:
conn.execute("UPDATE mcp_oauth_consents SET revoked_at=? "
"WHERE username=? AND client_id=?", (time.time(), username, client_id))
conn.execute("UPDATE mcp_oauth_tokens SET revoked_at=? "
"WHERE username=? AND client_id=? AND revoked_at IS NULL",
(time.time(), username, client_id))
await asyncio.to_thread(write)
async def list_clients_for_user(self, username: str) -> list[dict]:
def read():
with closing(db._conn()) as conn:
rows = conn.execute("SELECT c.client_id, c.metadata, g.scopes, g.approved_at "
"FROM mcp_oauth_consents g JOIN mcp_oauth_clients c "
"ON c.client_id=g.client_id WHERE g.username=? AND g.revoked_at IS NULL",
(username,)).fetchall()
return [{"client_id": r["client_id"],
"client_name": json.loads(r["metadata"]).get("client_name") or r["client_id"],
"scopes": json.loads(r["scopes"]), "approved_at": r["approved_at"]}
for r in rows]
return await asyncio.to_thread(read)
async def prepare_action(self, username: str, client_id: str, tab_id: str, kind: str) -> str:
if kind != "clear_files":
raise ValueError("Unknown action")
ticket = secrets.token_urlsafe(32)
def write():
with closing(db._conn()) as conn, conn:
conn.execute("INSERT INTO mcp_pending_actions VALUES (?,?,?,?,?,?,NULL)",
(_digest(ticket), username, client_id, tab_id, kind, time.time() + 600))
await asyncio.to_thread(write)
return f"{self.issuer}/mcp/confirm-action?{urlencode({'ticket': ticket})}"
async def action_info(self, ticket: str) -> dict | None:
def read():
with closing(db._conn()) as conn:
return conn.execute("SELECT username, client_id, tab_id, kind, expires_at, approved_at "
"FROM mcp_pending_actions WHERE ticket_hash=?", (_digest(ticket),)).fetchone()
row = await asyncio.to_thread(read)
if not row or row["expires_at"] < time.time():
return None
return {key: row[key] for key in ("username", "client_id", "tab_id", "kind", "approved_at")}
async def approve_action(self, ticket: str, username: str) -> None:
def write():
with closing(db._conn()) as conn, conn:
changed = conn.execute("UPDATE mcp_pending_actions SET approved_at=? "
"WHERE ticket_hash=? AND username=? AND expires_at>? AND approved_at IS NULL",
(time.time(), _digest(ticket), username, time.time()))
if changed.rowcount != 1:
raise ValueError("Confirmation expired")
await asyncio.to_thread(write)
async def consume_action(self, ticket: str, username: str, client_id: str,
tab_id: str, kind: str) -> None:
def write():
with closing(db._conn()) as conn, conn:
row = conn.execute("DELETE FROM mcp_pending_actions WHERE ticket_hash=? "
"AND username=? AND client_id=? AND tab_id=? AND kind=? AND approved_at IS NOT NULL "
"AND expires_at>? RETURNING ticket_hash",
(_digest(ticket), username, client_id, tab_id, kind, time.time())).fetchone()
if row is None:
raise PermissionError("Action needs browser confirmation")
await asyncio.to_thread(write)