feat: accept Cloudflare Access assertions on the HTTP MCP server
Cloudflare Access (Managed OAuth) runs the OAuth flow for clients such as ChatGPT; the origin verifies the signed Cf-Access-Jwt-Assertion itself -- RS256 in stdlib by construct-and-compare, issuer, AUD, expiry. Co-Authored-By: Claude Mythos 5.2 <[email protected]>
This commit is contained in:
1 parent
3909c35565
commit
57bc05ea7c
6 files changed
+488
-8
No files matched your search
@@ -0,0 +1,158 @@
|
||||
"""Verify the JWT Cloudflare Access attaches to requests it has authenticated.
|
||||
|
||||
When the MCP endpoint sits behind a Cloudflare Access application, Access does
|
||||
the OAuth dance with the client and forwards each allowed request with a signed
|
||||
``Cf-Access-Jwt-Assertion`` header. The edge check alone is not enough: the
|
||||
origin is reachable without Cloudflare (home IP, right SNI), so the origin must
|
||||
verify that signature itself. This module is that check.
|
||||
|
||||
stdlib only. Python ships no RSA primitive, but *verifying* RS256 needs none:
|
||||
it is one modular exponentiation with the public key, then a comparison. The
|
||||
comparison is done the safe way round -- build the one encoding that is valid
|
||||
for this digest (RFC 8017 s.9.2) and compare all of it -- rather than parsing
|
||||
the decrypted block, which is where signature-forgery bugs have historically
|
||||
lived. No secret is involved, so there is nothing for timing to leak.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
from typing import Any, Callable, Iterable
|
||||
|
||||
_TEAM = re.compile(r"[a-z0-9-]+\.cloudflareaccess\.com\Z")
|
||||
#: DER prefix of DigestInfo for SHA-256 (RFC 8017, section 9.2, note 1).
|
||||
_SHA256_DIGEST_INFO = bytes.fromhex("3031300d060960864801650304020105000420")
|
||||
MAX_TOKEN_CHARS = 8192
|
||||
MIN_KEY_BITS = 2048
|
||||
LEEWAY = 60 # seconds of clock skew tolerated
|
||||
REFETCH_AFTER = 60 # at most one key refetch per minute for unknown kids
|
||||
|
||||
|
||||
class InvalidToken(Exception):
|
||||
"""The assertion is missing, malformed, mis-signed, expired or not for us."""
|
||||
|
||||
|
||||
def _b64url(text: str) -> bytes:
|
||||
try:
|
||||
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
||||
except (binascii.Error, ValueError) as exc:
|
||||
raise InvalidToken("bad base64") from exc
|
||||
|
||||
|
||||
def rs256_verify(n: int, e: int, signed: bytes, signature: bytes) -> bool:
|
||||
"""RSASSA-PKCS1-v1_5 with SHA-256, by construct-and-compare."""
|
||||
k = (n.bit_length() + 7) // 8
|
||||
if n.bit_length() < MIN_KEY_BITS or e < 3 or e % 2 == 0 or len(signature) != k:
|
||||
return False
|
||||
s = int.from_bytes(signature, "big")
|
||||
if s >= n:
|
||||
return False
|
||||
tail = _SHA256_DIGEST_INFO + hashlib.sha256(signed).digest()
|
||||
expected = b"\x00\x01" + b"\xff" * (k - len(tail) - 3) + b"\x00" + tail
|
||||
return hmac.compare_digest(pow(s, e, n).to_bytes(k, "big"), expected)
|
||||
|
||||
|
||||
def _fetch_json(url: str) -> Any:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "wodify-mcp"})
|
||||
with urllib.request.urlopen(req, timeout=10) as res:
|
||||
return json.loads(res.read(1 << 20))
|
||||
|
||||
|
||||
class AccessVerifier:
|
||||
"""Checks assertions from one Access application of one team."""
|
||||
|
||||
def __init__(self, team_domain: str, audience: str,
|
||||
emails: Iterable[str] = (), *,
|
||||
fetch: Callable[[str], Any] = _fetch_json,
|
||||
now: Callable[[], float] = time.time) -> None:
|
||||
team_domain = team_domain.strip().lower()
|
||||
if not _TEAM.match(team_domain):
|
||||
raise ValueError(f"not an Access team domain: {team_domain!r} "
|
||||
"(expected <team>.cloudflareaccess.com)")
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", audience.strip()):
|
||||
raise ValueError("the Access AUD tag is 64 hex characters")
|
||||
self.issuer = f"https://{team_domain}"
|
||||
self.audience = audience.strip()
|
||||
self.emails = frozenset(e.strip().lower() for e in emails if e.strip())
|
||||
self._fetch, self._now = fetch, now
|
||||
self._keys: dict[str, tuple[int, int]] = {}
|
||||
self._fetched_at = 0.0
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# ---- keys ------------------------------------------------------------
|
||||
|
||||
def _load_keys(self) -> None:
|
||||
data = self._fetch(f"{self.issuer}/cdn-cgi/access/certs")
|
||||
keys: dict[str, tuple[int, int]] = {}
|
||||
for jwk in (data.get("keys") or []) if isinstance(data, dict) else []:
|
||||
if (isinstance(jwk, dict) and jwk.get("kty") == "RSA"
|
||||
and isinstance(jwk.get("kid"), str)):
|
||||
try:
|
||||
keys[jwk["kid"]] = (int.from_bytes(_b64url(jwk["n"]), "big"),
|
||||
int.from_bytes(_b64url(jwk["e"]), "big"))
|
||||
except (KeyError, TypeError, InvalidToken):
|
||||
continue
|
||||
if keys:
|
||||
self._keys = keys
|
||||
|
||||
def _key(self, kid: str) -> tuple[int, int]:
|
||||
with self._lock:
|
||||
# Access rotates keys, so an unknown kid means "look again" -- but
|
||||
# rate-limited, or junk tokens would become a request amplifier.
|
||||
if kid not in self._keys and self._now() - self._fetched_at >= REFETCH_AFTER:
|
||||
self._fetched_at = self._now()
|
||||
try:
|
||||
self._load_keys()
|
||||
except Exception as exc: # noqa: BLE001 - network, JSON, anything
|
||||
raise InvalidToken(f"cannot fetch Access keys: {exc}") from exc
|
||||
try:
|
||||
return self._keys[kid]
|
||||
except KeyError:
|
||||
raise InvalidToken("unknown signing key") from None
|
||||
|
||||
# ---- verification ----------------------------------------------------
|
||||
|
||||
def verify(self, token: str | None) -> dict[str, Any]:
|
||||
"""Return the claims, or raise :class:`InvalidToken`."""
|
||||
if not token or len(token) > MAX_TOKEN_CHARS or token.count(".") != 2:
|
||||
raise InvalidToken("no usable assertion")
|
||||
head_b64, body_b64, sig_b64 = token.split(".")
|
||||
try:
|
||||
header = json.loads(_b64url(head_b64))
|
||||
claims = json.loads(_b64url(body_b64))
|
||||
except (ValueError, UnicodeDecodeError) as exc:
|
||||
raise InvalidToken("unparseable assertion") from exc
|
||||
if not isinstance(header, dict) or not isinstance(claims, dict):
|
||||
raise InvalidToken("unparseable assertion")
|
||||
# The algorithm is pinned, never taken from the token: no "none", no
|
||||
# HS256-with-the-public-key.
|
||||
if header.get("alg") != "RS256" or not isinstance(header.get("kid"), str):
|
||||
raise InvalidToken("unexpected algorithm")
|
||||
|
||||
n, e = self._key(header["kid"])
|
||||
if not rs256_verify(n, e, f"{head_b64}.{body_b64}".encode(), _b64url(sig_b64)):
|
||||
raise InvalidToken("bad signature")
|
||||
|
||||
now = self._now()
|
||||
if claims.get("iss") != self.issuer:
|
||||
raise InvalidToken("wrong issuer")
|
||||
aud = claims.get("aud")
|
||||
if self.audience not in (aud if isinstance(aud, list) else [aud]):
|
||||
raise InvalidToken("wrong audience")
|
||||
exp = claims.get("exp")
|
||||
if not isinstance(exp, (int, float)) or exp + LEEWAY < now:
|
||||
raise InvalidToken("expired")
|
||||
for claim in ("nbf", "iat"):
|
||||
value = claims.get(claim)
|
||||
if isinstance(value, (int, float)) and value - LEEWAY > now:
|
||||
raise InvalidToken("not valid yet")
|
||||
if self.emails and str(claims.get("email") or "").lower() not in self.emails:
|
||||
raise InvalidToken("identity not allowed")
|
||||
return claims
|
||||
+21
-1
@@ -149,6 +149,14 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
mc.add_argument("--token-file", default=None, metavar="PATH",
|
||||
help="file holding the bearer token (default: "
|
||||
"$WODIFY_MCP_TOKEN, else ~/.config/wodify/mcp-token)")
|
||||
mc.add_argument("--access-team", default=None, metavar="TEAM.cloudflareaccess.com",
|
||||
help="with --http: also accept requests authenticated by this "
|
||||
"Cloudflare Access team (needs --access-aud)")
|
||||
mc.add_argument("--access-aud", default=None, metavar="AUD",
|
||||
help="the Access application's AUD tag (64 hex chars)")
|
||||
mc.add_argument("--access-email", action="append", default=[], metavar="EMAIL",
|
||||
help="only accept Access identities with this email "
|
||||
"(repeatable; default: whatever the Access policy allows)")
|
||||
mc.add_argument("--allow-prime", action="store_true",
|
||||
help="also offer the prime tool over HTTP (off by default)")
|
||||
pr = sub.add_parser("prime",
|
||||
@@ -192,8 +200,20 @@ def main(argv: list[str] | None = None) -> int:
|
||||
if args.command == "mcp":
|
||||
from . import mcpserver
|
||||
if args.http:
|
||||
access = None
|
||||
if args.access_team or args.access_aud:
|
||||
if not (args.access_team and args.access_aud):
|
||||
print("--access-team and --access-aud go together", file=sys.stderr)
|
||||
return 2
|
||||
from . import accessjwt
|
||||
try:
|
||||
access = accessjwt.AccessVerifier(
|
||||
args.access_team, args.access_aud, args.access_email)
|
||||
except ValueError as exc:
|
||||
print(f"bad Access settings: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
return mcpserver.serve_http(args.http, args.token_file,
|
||||
allow_prime=args.allow_prime)
|
||||
allow_prime=args.allow_prime, access=access)
|
||||
return mcpserver.serve()
|
||||
if args.command == "doctor":
|
||||
return cmd_doctor(args)
|
||||
|
||||
+26
-6
@@ -26,6 +26,7 @@ import threading
|
||||
from typing import Any, Callable
|
||||
|
||||
from . import __version__, actions
|
||||
from .accessjwt import InvalidToken
|
||||
from .listcmd import MINE_MAX_DAYS
|
||||
|
||||
PROTOCOL_VERSIONS = ("2025-06-18", "2025-03-26", "2024-11-05")
|
||||
@@ -424,7 +425,12 @@ def load_token(path: str | None = None) -> str:
|
||||
|
||||
|
||||
def make_http_server(host: str, port: int, token: str, *,
|
||||
allow_prime: bool = False) -> http.server.ThreadingHTTPServer:
|
||||
allow_prime: bool = False,
|
||||
access=None) -> http.server.ThreadingHTTPServer:
|
||||
"""``access`` is an optional ``accessjwt.AccessVerifier``. With it, a
|
||||
request is also accepted when it carries a valid Cloudflare Access
|
||||
assertion -- that is how OAuth clients arrive. The bearer token keeps
|
||||
working either way."""
|
||||
if len(token) < MIN_TOKEN_CHARS:
|
||||
raise ValueError(f"token must be at least {MIN_TOKEN_CHARS} chars")
|
||||
tools = build_tools()
|
||||
@@ -459,7 +465,18 @@ def make_http_server(host: str, port: int, token: str, *,
|
||||
"""Auth first, for every path and method: an unauthenticated caller
|
||||
learns nothing, not even which paths exist."""
|
||||
given = (self.headers.get("Authorization") or "").encode()
|
||||
if not hmac.compare_digest(given, expected):
|
||||
self.who = "token"
|
||||
allowed = hmac.compare_digest(given, expected)
|
||||
if not allowed and access is not None:
|
||||
try:
|
||||
claims = access.verify(self.headers.get("Cf-Access-Jwt-Assertion"))
|
||||
except InvalidToken as exc:
|
||||
self.who = f"access refused: {exc}"
|
||||
else:
|
||||
allowed = True
|
||||
self.who = "access:" + str(
|
||||
claims.get("email") or claims.get("common_name") or "?")
|
||||
if not allowed:
|
||||
self.close_connection = True
|
||||
self._reply(401, {"error": "unauthorized"},
|
||||
WWW_Authenticate='Bearer realm="wodify"')
|
||||
@@ -502,7 +519,8 @@ def make_http_server(host: str, port: int, token: str, *,
|
||||
|
||||
def log_message(self, fmt: str, *args: Any) -> None:
|
||||
# Request line and status only -- never headers, so never the token.
|
||||
sys.stderr.write("%s %s\n" % (self.address_string(), fmt % args))
|
||||
sys.stderr.write("%s [%s] %s\n" % (
|
||||
self.address_string(), getattr(self, "who", "-"), fmt % args))
|
||||
|
||||
server = http.server.ThreadingHTTPServer((host, port), Handler)
|
||||
server.daemon_threads = True
|
||||
@@ -510,14 +528,16 @@ def make_http_server(host: str, port: int, token: str, *,
|
||||
|
||||
|
||||
def serve_http(listen: str, token_file: str | None = None, *,
|
||||
allow_prime: bool = False) -> int:
|
||||
allow_prime: bool = False, access=None) -> int:
|
||||
host, _, port = listen.rpartition(":")
|
||||
if not host or not port.isdigit():
|
||||
raise SystemExit(f"--http wants HOST:PORT, got {listen!r}")
|
||||
server = make_http_server(host, int(port), load_token(token_file),
|
||||
allow_prime=allow_prime)
|
||||
allow_prime=allow_prime, access=access)
|
||||
sys.stdout = sys.stderr # nothing here prints to a client
|
||||
print(f"wodify mcp: serving http://{listen}{MCP_PATH} (bearer token required)",
|
||||
how = "bearer token" + (
|
||||
f" or Cloudflare Access ({access.issuer})" if access else "")
|
||||
print(f"wodify mcp: serving http://{listen}{MCP_PATH} ({how} required)",
|
||||
file=sys.stderr, flush=True)
|
||||
try:
|
||||
server.serve_forever()
|
||||
|
||||
Reference in new issue
Block a user