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
+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