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]>
239 lines
8.9 KiB
Python
239 lines
8.9 KiB
Python
"""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()
|