ckb/.agents/modules/mcp/server/auth.py
Michał Kopeć bbfda5a65d Sync: local changes as of 2026-10-29T13:50:12Z
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-29 14:50:12 +01:00

254 lines
12 KiB
Python

"""Authentication for the ckb MCP server, switched by CKB_MCP_AUTH:
none no check. Only for stdio or a server reachable from localhost/VPN alone.
token shared secret(s). Accepted as `Authorization: Bearer <token>` or as a
secret path prefix `/<token>/mcp` - Claude's web connector cannot send a
custom header, so the path form is how it authenticates without OAuth.
A read-write CKB_MCP_TOKEN and/or a read-only CKB_MCP_READ_TOKEN, or
one per person/agent with its own write bit (CKB_MCP_TOKENS_FILE).
oauth the server is an OAuth 2.1 resource server: it advertises an external
authorization server (Authentik, Keycloak, Zitadel, Auth0, ...) and
verifies the JWT access tokens that server issues against its JWKS,
or via RFC 7662 introspection for opaque tokens.
Either way the caller ends up as a User with a write bit, read by caller().
Token mode sets it in an ASGI middleware; OAuth mode derives it from the MCP
SDK's verified access token. Read-only callers neither see nor can call the
write tools.
"""
import contextvars
import hmac
import json
import logging
import os
from pathlib import Path
log = logging.getLogger("ckb-mcp.auth")
_TOKEN_USER = contextvars.ContextVar("ckb_token_user", default=None)
def _min_len(token, what):
if len(token) < 24:
raise SystemExit(f"{what} is shorter than 24 characters "
"(generate one with: python3 -c 'import secrets; print(secrets.token_urlsafe(32))')")
# ----------------------------------------------------------------- token ---
def load_tokens(env):
"""[{token, name, email, write}] from CKB_MCP_TOKENS_FILE, else from CKB_MCP_TOKEN
(read-write) and/or CKB_MCP_READ_TOKEN (read-only). In the file, `write` must be
stated as true: an entry without it is read-only."""
path = env.get("CKB_MCP_TOKENS_FILE")
if path:
tokens = []
for e in json.loads(Path(path).read_text(encoding="utf-8")):
_min_len(e.get("token", ""), f"token for {e.get('name', '?')}")
tokens.append({"token": e["token"], "name": e.get("name", "ckb-mcp user"),
"email": e.get("email", "ckb-mcp@localhost"), "write": e.get("write") is True})
if not tokens:
raise SystemExit(f"{path} lists no tokens")
else:
name, email = env.get("CKB_MCP_AUTHOR_NAME", "ckb-mcp user"), env.get("CKB_MCP_AUTHOR_EMAIL", "ckb-mcp@localhost")
tokens = []
if env.get("CKB_MCP_TOKEN"):
_min_len(env["CKB_MCP_TOKEN"], "CKB_MCP_TOKEN")
tokens.append({"token": env["CKB_MCP_TOKEN"], "name": name, "email": email, "write": True})
if env.get("CKB_MCP_READ_TOKEN"):
_min_len(env["CKB_MCP_READ_TOKEN"], "CKB_MCP_READ_TOKEN")
tokens.append({"token": env["CKB_MCP_READ_TOKEN"], "name": f"{name} (read-only)", "email": email, "write": False})
if not tokens:
raise SystemExit("CKB_MCP_AUTH=token needs CKB_MCP_TOKEN, CKB_MCP_READ_TOKEN or CKB_MCP_TOKENS_FILE")
if len({t["token"] for t in tokens}) != len(tokens):
raise SystemExit("two token entries share the same secret")
return tokens
class TokenAuthMiddleware:
def __init__(self, app, tokens, mcp_path="/mcp", open_paths=("/health",)):
self.app = app
self.tokens = tokens
self.mcp_path = mcp_path
self.open_paths = open_paths
def _match(self, presented):
found = None
for t in self.tokens: # compare against every entry: no early exit, no timing hint
if hmac.compare_digest(presented.encode(), t["token"].encode()):
found = t
return found
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return await self.app(scope, receive, send)
headers = scope.get("headers", [])
path = scope.get("path", "")
if path in self.open_paths:
return await self.app(scope, receive, send)
user = None
auth = dict(headers).get(b"authorization", b"").decode("latin-1")
if auth.lower().startswith("bearer "):
user = self._match(auth[7:].strip())
if user is None:
# Secret path form: /<token>/mcp -> /mcp
seg, _, rest = path.lstrip("/").partition("/")
if seg and "/" + rest == self.mcp_path:
user = self._match(seg)
if user:
path = self.mcp_path
if user is None:
await send({"type": "http.response.start", "status": 401,
"headers": [(b"content-type", b"application/json")]})
await send({"type": "http.response.body", "body": b'{"error":"unauthorized"}'})
return
# The MCP handler runs in a task spawned from this request, so it sees this value.
reset = _TOKEN_USER.set(user)
try:
return await self.app(dict(scope, path=path, raw_path=path.encode()), receive, send)
finally:
_TOKEN_USER.reset(reset)
def caller(mode, env):
"""(name, email, may_write) for the current request, or None when unauthenticated."""
if mode == "token":
u = _TOKEN_USER.get()
return (u["name"], u["email"], u["write"]) if u else None
if mode == "oauth":
from mcp.server.auth.middleware.auth_context import get_access_token
tok = get_access_token()
if tok is None:
return None
claims = tok.claims or {}
sub = claims.get("sub") or tok.subject or "unknown"
name = claims.get("name") or claims.get("preferred_username") or sub
return name, claims.get("email") or f"{sub}@oauth.invalid", bool(claims.get("ckb_write"))
return env.get("CKB_MCP_AUTHOR_NAME", "ckb-mcp user"), env.get("CKB_MCP_AUTHOR_EMAIL", "ckb-mcp@localhost"), True
# ----------------------------------------------------------------- oauth ---
def oauth_settings(env, resource_url):
"""AuthSettings + TokenVerifier for resource-server mode. Imports stay local so
none/token mode run without PyJWT installed."""
from mcp.server.auth.settings import AuthSettings
issuer = env.get("CKB_MCP_OAUTH_ISSUER")
if not issuer:
raise SystemExit("CKB_MCP_AUTH=oauth needs CKB_MCP_OAUTH_ISSUER (the authorization server URL)")
scopes = [s for s in env.get("CKB_MCP_OAUTH_SCOPES", "").split() if s]
settings = AuthSettings(
issuer_url=issuer,
resource_server_url=resource_url,
required_scopes=scopes or None,
# The verifier checks `aud` itself, so the SDK's resource check is off.
validate_token_resource=False,
)
return settings, OAuthVerifier(env, resource_url)
def _split(v):
return [x.strip().lower() for x in (v or "").replace(",", " ").split() if x.strip()]
class OAuthVerifier:
def __init__(self, env, resource_url):
self.issuer = env["CKB_MCP_OAUTH_ISSUER"].rstrip("/")
self.audience = env.get("CKB_MCP_OAUTH_AUDIENCE") or resource_url
self.jwks_url = env.get("CKB_MCP_OAUTH_JWKS_URL")
self.introspection_url = env.get("CKB_MCP_OAUTH_INTROSPECTION_URL")
self.client_id = env.get("CKB_MCP_OAUTH_CLIENT_ID")
self.client_secret = env.get("CKB_MCP_OAUTH_CLIENT_SECRET")
# Introspection responses must name this server in `aud`, as JWTs must. Some IdPs
# omit `aud` from introspection; this opt-out accepts those, and only those.
self.allow_missing_aud = env.get("CKB_MCP_OAUTH_ALLOW_MISSING_AUD") == "1"
# Who may use the server at all, and who may write. An entry is an email,
# a subject, or "@domain". Empty allowed list = anyone the issuer authenticates.
self.allowed = _split(env.get("CKB_MCP_OAUTH_ALLOWED"))
self.writers = _split(env.get("CKB_MCP_OAUTH_WRITERS"))
# A token may write only if it also carries this scope, when set. This is how a
# machine client (client-credentials, no email) gets read-only or read-write.
self.write_scope = env.get("CKB_MCP_OAUTH_WRITE_SCOPE", "").strip()
if not (self.jwks_url or self.introspection_url):
raise SystemExit("CKB_MCP_AUTH=oauth needs CKB_MCP_OAUTH_JWKS_URL (JWT tokens) "
"or CKB_MCP_OAUTH_INTROSPECTION_URL (opaque tokens)")
self._jwks = None
@staticmethod
def _matches(rules, claims):
email = (claims.get("email") or "").lower()
sub = (claims.get("sub") or "").lower()
for r in rules:
if r.startswith("@") and email.endswith(r):
return True
if r in (email, sub):
return True
return False
def _claims_jwt(self, token):
import jwt
if self._jwks is None:
self._jwks = jwt.PyJWKClient(self.jwks_url, cache_keys=True)
key = self._jwks.get_signing_key_from_jwt(token)
return jwt.decode(token, key.key, algorithms=["RS256", "ES256", "PS256", "EdDSA"],
audience=self.audience, issuer=self.issuer,
options={"require": ["exp", "iss", "sub"]})
async def _claims_introspect(self, token):
import httpx2 as httpx # the MCP SDK's own HTTP client; no extra dependency
async with httpx.AsyncClient(timeout=10) as client:
r = await client.post(self.introspection_url, data={"token": token},
auth=(self.client_id, self.client_secret) if self.client_id else None)
r.raise_for_status()
claims = r.json()
if not claims.get("active"):
return None
aud = claims.get("aud")
if not aud:
if not self.allow_missing_aud:
log.warning("introspected token has no aud; refused (CKB_MCP_OAUTH_ALLOW_MISSING_AUD=1 accepts it)")
return None
elif self.audience not in (aud if isinstance(aud, list) else [aud]):
return None
return claims
async def verify_token(self, token):
from mcp.server.auth.provider import AccessToken
import anyio
import jwt
try:
if self.jwks_url:
# PyJWKClient fetches keys synchronously (first use, key rotation): keep it off the event loop.
claims = await anyio.to_thread.run_sync(self._claims_jwt, token)
else:
claims = await self._claims_introspect(token)
except jwt.InvalidTokenError as e:
# A bad, expired or foreign token: routine, and the client is told 401.
log.info("token rejected: %s", e)
return None
except Exception as e:
# JWKS unreachable, wrong URL, IdP down: an operator problem that would
# otherwise look like nothing but a stream of 401s.
log.warning("token verification failed: %s: %s", type(e).__name__, e)
return None
if not claims:
return None
if self.allowed and not self._matches(self.allowed, claims):
return None
scope = claims.get("scope") or claims.get("scp") or ""
scopes = scope.split() if isinstance(scope, str) else list(scope)
claims["ckb_write"] = (((not self.writers) or self._matches(self.writers, claims))
and ((not self.write_scope) or self.write_scope in scopes))
return AccessToken(
token=token,
client_id=str(claims.get("client_id") or claims.get("azp") or "unknown"),
scopes=scopes,
expires_at=claims.get("exp"),
resource=self.audience,
subject=claims.get("sub"),
claims=claims,
)