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:
lucioandClaude Mythos 5.2 committed 2026-11-21 15:35:05 -08:00
1 parent 3909c35565
commit 57bc05ea7c
6 files changed
+488 -8

No files matched your search

+34 -1
View File
@@ -79,7 +79,8 @@ src/wodify/
service.py cache-through data access -- all fetches go through here
render.py compact text output (token-efficient, not a DOM dump)
listcmd.py the `list date` / `list workout` / `list mine` commands
mcpserver.py `wodify mcp` -- the same commands as a stdio MCP server (stdlib)
mcpserver.py `wodify mcp` -- the same commands as an MCP server, stdio or HTTP (stdlib)
accessjwt.py verifies Cloudflare Access assertions for the HTTP server (stdlib)
cli.py python -m wodify <cmd>
```
@@ -151,6 +152,38 @@ session and other members' names. Rules that must stay:
- Bodies over 1 MB are refused on the declared length, before reading. Logs carry the
request line and status only -- never headers, so never the token.
#### OAuth: Cloudflare Access does it, the origin verifies it
The server implements no OAuth. `wodify.luci.ooo` is a Cloudflare Access self-hosted
application ("Wodify MCP") with **Managed OAuth** on: Access answers an unauthenticated
MCP client with a 401 pointing at its discovery metadata, runs registration, login
(passkey) and token exchange itself, and forwards allowed requests to the origin with a
signed `Cf-Access-Jwt-Assertion` header. The client's own `Authorization` header is an
opaque `oauth:…` token that means nothing to the origin.
`accessjwt.py` verifies that assertion, and it must: the origin is reachable without
Cloudflare (home IP + the right SNI), so anything that trusts the edge alone, or a plain
header like `Cf-Access-Authenticated-User-Email`, is an open door. Checked on every
request: RS256 signature against the team's published keys, issuer, the application's
AUD tag, expiry, and (with `--access-email`) the identity.
- RS256 is verified in stdlib: one `pow()` with the public key, then the expected
PKCS#1 v1.5 block is **constructed and compared whole**, never parsed. Cross-checked
against an OpenSSL signature when written. The algorithm is pinned, not read from
the token.
- Keys are cached; an unknown `kid` triggers at most one refetch a minute. A failed
fetch refuses the request.
- The bearer token still works beside it -- but only on the LAN address, since Access
now intercepts everything arriving through Cloudflare.
- Who may log in is decided by the Access policy on the application (the account's
reusable "Allow emails" policy). `--access-email` is not set on the deployed unit, so
loosening that policy loosens this endpoint.
- The service's AUD tag and team domain are flags on `wodify-mcp.service`. If the Access
application is ever deleted and recreated, its AUD changes and the unit must follow.
- Dynamic client registration only accepts redirect URIs on `chatgpt.com`, `claude.ai`,
`claude.com` and localhost. Another client needs its callback added to the Access
application's Managed OAuth settings.
Path on the wire: Cloudflare (proxied A record `wodify.luci.ooo`, kept current by
`home-ddns` on luhpe, which follows every A record holding the home IP -- no per-record
config) -> home router :443 -> Caddy on the NAS (`wodify.luci.ooo` block, `/mcp` only)
+11
View File
@@ -109,6 +109,17 @@ A bearer token is mandatory — it will not start without one of at least 32 cha
every request without it gets `401`. `prime` is not offered over HTTP. Put TLS in front
of it (a reverse proxy); the server itself speaks plain HTTP.
For OAuth clients (ChatGPT, Claude connectors), put the hostname behind a Cloudflare
Access application with Managed OAuth and tell the server to verify what Access forwards:
```bash
wodify mcp --http 127.0.0.1:8765 \
--access-team yourteam.cloudflareaccess.com --access-aud <application AUD tag>
```
Access runs the OAuth flow; the server checks the signed assertion on every request.
`--access-email` (repeatable) additionally pins which identities are accepted.
Tools run the CLI in-process, so the read-only allowlist and write guard apply unchanged
and the cache below is shared with the command line.
+158
View File
@@ -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
View File
@@ -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
View File
@@ -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()
+238
View File
@@ -0,0 +1,238 @@
"""Cloudflare Access assertion checks, and the HTTP server accepting them."""
from __future__ import annotations
import base64
import hashlib
import json
import threading
import urllib.error
import urllib.request
import pytest
from wodify import accessjwt, mcpserver
from wodify.accessjwt import AccessVerifier, InvalidToken
# A throwaway RSA-2048 key made for these tests. It signs nothing real.
N = int(
"b67b0a3eb5d7ffe6e55bd6a64c19be2559109b0ce94fa557cf5ad6b0207f75b6"
"729addeaaf898c8dda0e10d1a40991cb5b89be76de4e6c0ecd72dd6bed2a78a4"
"a042fa30f78c3fc3827c2f6ff44fa2ae55865c62f7844dd8e4b468eb88692eb6"
"514ef870b3397a1b3478b4654628fb4871ef6eeeeddbcc7fbe08826452a2f368"
"a06993b0d48eed91ba723a771b527e9349c19399fb58113fbb0ed0574c510d42"
"8ed7e2de0e7faa4fe33f84cd75e46b842e50f37ee6ac45228b5ee32329cdcdd7"
"028e0f93569328fbefa7d820b77fda421f85253e93e7f4ccec6c4da900fc631c"
"64c8d45a494e0d0f063cba17532b16a2f2710b9d96f9d5d57c469424f6ce0901",
16)
D = int(
"353c19d60798b707f61b5fb86df5089abeabf07fc8c4ba78ae7e52a95921b606"
"7ed29d30ecfad4ad4152df273992ad1cc55c9edaf0a9b22e735332335d2209c6"
"0516e5044a03794aa1137787529fb4d6e50e687f5ab4173dd222ab8522eb847c"
"1da64b261db303e351e070c826baa7ec0f890934dce1457c72c4eabd37ba6005"
"c4baa20b280cd791022905ada110f81e2677f7ff090e7f86f651fa9d24ef4cce"
"f8fd6eade5fb5524b36134f7dd14983d1f56b44c239f7d5a9e1348de73fd4ebd"
"8d8d30edcd7832f6b5fb12b23ea8b00d7be3c1274780277e738defbe772cfc1c"
"62e9e2231bb6e161953c0db141b7a4c612381970c510e6e6bc8d3535e97d8c6d",
16)
E = 65537
TEAM = "example.cloudflareaccess.com"
AUD = "ab" * 32
NOW = 1_800_000_000
def b64(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
def sign(signed: bytes, n: int = N, d: int = D) -> bytes:
k = (n.bit_length() + 7) // 8
tail = accessjwt._SHA256_DIGEST_INFO + hashlib.sha256(signed).digest()
em = b"\x00\x01" + b"\xff" * (k - len(tail) - 3) + b"\x00" + tail
return pow(int.from_bytes(em, "big"), d, n).to_bytes(k, "big")
def token(claims=None, *, header=None, **overrides) -> str:
body = {"iss": f"https://{TEAM}", "aud": [AUD], "exp": NOW + 300,
"iat": NOW - 5, "nbf": NOW - 5, "email": "[email protected]"}
body.update(claims or {})
body.update(overrides)
head = {"alg": "RS256", "kid": "k1", "typ": "JWT"}
head.update(header or {})
signed = f"{b64(json.dumps(head).encode())}.{b64(json.dumps(body).encode())}"
return f"{signed}.{b64(sign(signed.encode()))}"
JWKS = {"keys": [{"kty": "RSA", "kid": "k1", "alg": "RS256",
"n": b64(N.to_bytes(256, "big")), "e": b64(E.to_bytes(3, "big"))}]}
def verifier(emails=(), jwks=JWKS, clock=None):
fetched = []
def fetch(url):
fetched.append(url)
return jwks
v = AccessVerifier(TEAM, AUD, emails, fetch=fetch,
now=clock or (lambda: NOW))
v.fetched = fetched
return v
def test_a_good_assertion_is_accepted():
v = verifier()
assert v.verify(token())["email"] == "[email protected]"
assert v.fetched == [f"https://{TEAM}/cdn-cgi/access/certs"]
v.verify(token())
assert len(v.fetched) == 1, "keys are cached"
@pytest.mark.parametrize("bad", [
None, "", "abc", "a.b", "a.b.c", "x" * 9000,
lambda: token(iss="https://evil.cloudflareaccess.com"),
lambda: token(aud=["cd" * 32]),
lambda: token(aud="cd" * 32),
lambda: token(exp=NOW - 120),
lambda: token(exp="never"),
lambda: token({"exp": None}),
lambda: token(nbf=NOW + 600),
lambda: token(header={"alg": "none"}),
lambda: token(header={"alg": "HS256"}),
lambda: token(header={"kid": "other"}),
lambda: token(header={"kid": 7}),
lambda: token().rsplit(".", 1)[0] + ".", # signature stripped
lambda: token().rsplit(".", 1)[0] + "." + b64(b"\x00" * 256),
lambda: token()[:-4] + "AAAA", # signature altered
])
def test_bad_assertions_are_refused(bad):
with pytest.raises(InvalidToken):
verifier().verify(bad() if callable(bad) else bad)
def test_a_payload_swapped_under_a_valid_signature_is_refused():
good = token()
head, _, sig = good.split(".")
forged_body = b64(json.dumps({
"iss": f"https://{TEAM}", "aud": [AUD], "exp": NOW + 300,
"email": "[email protected]"}).encode())
with pytest.raises(InvalidToken, match="bad signature"):
verifier().verify(f"{head}.{forged_body}.{sig}")
def test_email_allowlist():
assert verifier(["[email protected]"]).verify(token())
with pytest.raises(InvalidToken, match="identity not allowed"):
verifier(["[email protected]"]).verify(token())
with pytest.raises(InvalidToken, match="identity not allowed"):
verifier(["[email protected]"]).verify(token({"email": None}))
def test_unknown_kid_refetches_keys_but_not_more_than_once_a_minute():
clock = [NOW]
v = verifier(clock=lambda: clock[0])
v.verify(token())
for _ in range(5):
with pytest.raises(InvalidToken, match="unknown signing key"):
v.verify(token(header={"kid": "rotated"}))
assert len(v.fetched) == 1, "no refetch inside the window"
clock[0] += 61
with pytest.raises(InvalidToken):
v.verify(token(header={"kid": "rotated"}, exp=clock[0] + 300))
assert len(v.fetched) == 2
def test_key_fetch_failure_refuses_rather_than_allows():
def boom(url):
raise OSError("network down")
v = AccessVerifier(TEAM, AUD, fetch=boom, now=lambda: NOW)
with pytest.raises(InvalidToken, match="cannot fetch Access keys"):
v.verify(token())
def test_weak_keys_are_never_trusted():
assert not accessjwt.rs256_verify(3233, 17, b"m", b"\x01\x02") # toy key
assert not accessjwt.rs256_verify(N, 1, b"m", b"\x00" * 256) # e = 1
assert not accessjwt.rs256_verify(N, E, b"m", b"\xff" * 256) # s >= n
assert not accessjwt.rs256_verify(N, E, b"m", sign(b"m")[1:]) # short
@pytest.mark.parametrize("team,aud", [
("example.com", AUD), ("evil.com/x.cloudflareaccess.com", AUD),
("a.cloudflareaccess.com.evil.com", AUD), (TEAM, "short"), (TEAM, "zz" * 32),
])
def test_settings_are_validated(team, aud):
with pytest.raises(ValueError):
AccessVerifier(team, aud)
# ---------------------------------------------------------- through the server
BEARER = "t" * 40
@pytest.fixture()
def http(monkeypatch):
monkeypatch.setattr(mcpserver, "run_cli", lambda argv: (0, "ran " + " ".join(argv)))
server = mcpserver.make_http_server(
"127.0.0.1", 0, BEARER,
access=verifier(["[email protected]"], clock=lambda: NOW))
threading.Thread(target=server.serve_forever, daemon=True).start()
url = f"http://127.0.0.1:{server.server_address[1]}/mcp"
def post(**headers):
req = urllib.request.Request(url, method="POST", data=json.dumps(
{"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {"name": "my_classes"}}).encode())
for name, value in headers.items():
req.add_header(name.replace("_", "-"), value)
try:
with urllib.request.urlopen(req, timeout=5) as res:
return res.status
except urllib.error.HTTPError as exc:
return exc.code
yield post
server.shutdown()
server.server_close()
def test_server_accepts_an_access_assertion_without_the_bearer_token(http):
assert http(Cf_Access_Jwt_Assertion=token()) == 200
def test_server_accepts_it_alongside_an_opaque_oauth_bearer(http):
"""What an OAuth client actually sends: Access's opaque token in
Authorization, which the origin cannot check, plus the assertion."""
assert http(Authorization="Bearer oauth:opaque",
Cf_Access_Jwt_Assertion=token()) == 200
def test_server_still_accepts_the_bearer_token(http):
assert http(Authorization=f"Bearer {BEARER}") == 200
@pytest.mark.parametrize("headers", [
{},
{"Cf_Access_Jwt_Assertion": "garbage"},
{"Cf_Access_Jwt_Assertion": lambda: token(aud=["cd" * 32])},
{"Cf_Access_Jwt_Assertion": lambda: token(email="[email protected]")},
{"Cf_Access_Jwt_Assertion": lambda: token(exp=NOW - 600)},
{"Cf_Access_Authenticated_User_Email": "[email protected]"}, # a header is not proof
{"Authorization": "Bearer oauth:opaque"},
])
def test_server_refuses_everything_else(http, headers):
resolved = {k: v() if callable(v) else v for k, v in headers.items()}
assert http(**resolved) == 401
def test_without_access_configured_an_assertion_means_nothing(monkeypatch):
server = mcpserver.make_http_server("127.0.0.1", 0, BEARER)
threading.Thread(target=server.serve_forever, daemon=True).start()
req = urllib.request.Request(
f"http://127.0.0.1:{server.server_address[1]}/mcp", method="POST", data=b"{}")
req.add_header("Cf-Access-Jwt-Assertion", token())
with pytest.raises(urllib.error.HTTPError) as err:
urllib.request.urlopen(req, timeout=5)
assert err.value.code == 401
server.shutdown()
server.server_close()