Files
Project-SDE-WP-Suite/tests/okta_sync_dpop_check.py

278 lines
13 KiB
Python

#!/usr/bin/env python3
"""Does the Okta sync use DPoP correctly? - D24 / T13.10.
A strict fake Okta (httpx.MockTransport) checks every DPoP proof the way RFC 9449 says a
server must: the header (typ dpop+jwt, ES256, a PUBLIC jwk only), the signature against
that jwk, htm, htu (no query), iat, a one-time jti, the nonce when the server asked for
one, and on an API call the ath hash of the access token and the same key as at the token
request. Also: auto mode finds out that DPoP is required, the nonce dance at the token
endpoint and at the API, paging, off mode, bounded retries, and no secret in any message.
Self-contained: no network, no server, no browser. Exit 0 all passed, 1 a failure.
"""
import base64
import hashlib
import json
import os
import sys
import time
from urllib.parse import parse_qs
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
os.environ["DATABASE_URL"] = "sqlite://"
for v in ("OKTA_API_TOKEN", "OKTA_SYNC_PROFILE_ATTRIBUTE", "OKTA_SYNC_DPOP"):
os.environ.pop(v, None)
os.environ["OKTA_ORG_URL"] = "https://example.okta.com"
import httpx # noqa: E402
import jwt # noqa: E402
from cryptography.hazmat.primitives.asymmetric import rsa # noqa: E402
from server import okta_sync # noqa: E402
from server.okta_sync import OktaSyncError # noqa: E402
fails = 0
def chk(label, ok, extra=""):
global fails
print(("PASS " if ok else "FAIL ") + label + (f" [{extra}]" if (extra and not ok) else ""))
if not ok:
fails += 1
pk = rsa.generate_private_key(public_exponent=65537, key_size=2048)
CLIENT_JWK = json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(pk))
CLIENT_JWK.update({"kid": "k1", "alg": "RS256", "use": "sig"})
CLIENT_PUB = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps({k: CLIENT_JWK[k] for k in ("kty", "n", "e")}))
os.environ["OKTA_SYNC_CLIENT_ID"] = "0oaCLIENT"
os.environ["OKTA_SYNC_PRIVATE_KEY"] = json.dumps(CLIENT_JWK)
TOKEN_URL = "https://example.okta.com/oauth2/v1/token"
USERS_URL = "https://example.okta.com/api/v1/users"
ACCESS = "ACCESS-TOKEN-VALUE-123"
def thumb(jwk):
return json.dumps({k: jwk[k] for k in ("crv", "kty", "x", "y")}, sort_keys=True, separators=(",", ":"))
class StrictOkta:
def __init__(self, require_dpop=False, token_nonce=False, api_nonce=False, always_bad_proof=False,
token_type_if_plain="Bearer", pages=1, endless_nonce=False):
self.endless_nonce = endless_nonce
self.require_dpop, self.token_nonce, self.api_nonce = require_dpop, token_nonce, api_nonce
self.always_bad_proof, self.token_type_if_plain, self.pages = always_bad_proof, token_type_if_plain, pages
self.token_calls = 0
self.api_calls = 0
self.problems = [] # anything the strict checks found wrong
self.jtis = set()
self.assertion_jtis = set()
self.token_key = None # thumbprint of the key used at the token request
self.api_keys = set()
self.dpop_on_token = 0
self.dpop_on_api = 0
self.issued_nonce = "nonce-" + os.urandom(3).hex()
self.api_seen = []
def _check_proof(self, req, url, method, ath=None, need_nonce=False):
proof = req.headers.get("dpop")
if not proof:
return None, "no proof"
try:
hdr = jwt.get_unverified_header(proof)
except Exception as e: # noqa: BLE001
return None, f"unreadable header {type(e).__name__}"
if hdr.get("typ") != "dpop+jwt" or hdr.get("alg") != "ES256":
self.problems.append(f"bad header typ/alg {hdr.get('typ')} {hdr.get('alg')}")
jwk = hdr.get("jwk")
if not isinstance(jwk, dict) or "d" in jwk or jwk.get("kty") != "EC":
self.problems.append("proof jwk missing or holds private part")
return None, "bad jwk"
try:
claims = jwt.decode(proof, jwt.algorithms.ECAlgorithm.from_jwk(json.dumps(jwk)),
algorithms=["ES256"], options={"verify_iat": False})
except Exception as e: # noqa: BLE001
self.problems.append(f"signature did not verify: {type(e).__name__}")
return None, "bad signature"
if claims.get("htm") != method:
self.problems.append(f"htm {claims.get('htm')} != {method}")
if claims.get("htu") != url:
self.problems.append(f"htu {claims.get('htu')} != {url}")
if abs(time.time() - int(claims.get("iat", 0))) > 60:
self.problems.append("iat not current")
if claims.get("jti") in self.jtis or not claims.get("jti"):
self.problems.append("jti missing or reused")
self.jtis.add(claims.get("jti"))
if ath is not None and claims.get("ath") != ath:
self.problems.append("ath wrong")
if ath is None and "ath" in claims:
self.problems.append("ath present on a token request")
if need_nonce and claims.get("nonce") != self.issued_nonce:
return jwk, "nonce"
return jwk, None
def handler(self, req: httpx.Request):
if req.url.path == "/oauth2/v1/token":
self.token_calls += 1
form = {k: v[0] for k, v in parse_qs(req.content.decode()).items()}
try:
a = jwt.decode(form["client_assertion"], CLIENT_PUB, algorithms=["RS256"], audience=TOKEN_URL)
if a["jti"] in self.assertion_jtis:
self.problems.append("client assertion jti reused")
self.assertion_jtis.add(a["jti"])
except Exception as e: # noqa: BLE001
self.problems.append(f"client assertion bad: {type(e).__name__}")
has = "dpop" in req.headers
if has:
self.dpop_on_token += 1
if self.always_bad_proof:
return httpx.Response(400, json={"error": "invalid_dpop_proof"})
if self.require_dpop and not has:
return httpx.Response(400, json={"error": "invalid_dpop_proof"})
if not has:
return httpx.Response(200, json={"token_type": self.token_type_if_plain, "access_token": ACCESS})
jwk, bad = self._check_proof(req, TOKEN_URL, "POST", need_nonce=self.token_nonce)
if bad == "nonce" or (self.endless_nonce and not bad):
return httpx.Response(400, json={"error": "use_dpop_nonce"}, headers={"DPoP-Nonce": self.issued_nonce})
if bad:
return httpx.Response(400, json={"error": "invalid_dpop_proof"})
self.token_key = thumb(jwk)
return httpx.Response(200, json={"token_type": "DPoP", "access_token": ACCESS})
if req.url.path == "/api/v1/users":
self.api_calls += 1
auth = req.headers.get("authorization", "")
self.api_seen.append(auth.split(" ")[0])
if auth.startswith("DPoP "):
self.dpop_on_api += 1
if auth != f"DPoP {ACCESS}":
self.problems.append("wrong DPoP access token")
ath = base64.urlsafe_b64encode(hashlib.sha256(ACCESS.encode()).digest()).rstrip(b"=").decode()
jwk, bad = self._check_proof(req, USERS_URL, "GET", ath=ath, need_nonce=self.api_nonce)
if bad == "nonce":
return httpx.Response(401, json={"errorCode": "invalid_token"},
headers={"DPoP-Nonce": self.issued_nonce,
"WWW-Authenticate": 'DPoP error="use_dpop_nonce"'})
if bad:
return httpx.Response(401, json={})
self.api_keys.add(thumb(jwk))
if thumb(jwk) != self.token_key:
self.problems.append("API proof key differs from the token request key")
elif auth == f"Bearer {ACCESS}":
if "dpop" in req.headers:
self.problems.append("DPoP header sent with a plain Bearer token")
else:
return httpx.Response(401, json={})
page = int(req.url.params.get("after", "0") or 0)
body = [{"status": "ACTIVE", "profile": {"login": f"user{page}"}}]
headers = {}
if page + 1 < self.pages:
headers["Link"] = f'<{USERS_URL}?after={page + 1}&limit=200>; rel="next"'
return httpx.Response(200, json=body, headers=headers)
return httpx.Response(404)
def client(self):
return httpx.Client(transport=httpx.MockTransport(self.handler))
def run(fake, mode=None):
if mode is None:
os.environ.pop("OKTA_SYNC_DPOP", None)
else:
os.environ["OKTA_SYNC_DPOP"] = mode
try:
return okta_sync.fetch_users(http=fake.client()), None
except OktaSyncError as e:
return None, str(e)
# 1. auto: a plain app needs no DPoP
f = StrictOkta()
users, err = run(f)
chk("auto, app without DPoP: works with one token call, Bearer", users and f.token_calls == 1 and f.dpop_on_token == 0 and f.api_seen == ["Bearer"], str(err))
chk("no problems found by the strict checks", not f.problems, str(f.problems))
# 2. auto: the app requires DPoP (what your tenant answered)
f = StrictOkta(require_dpop=True)
users, err = run(f)
chk("auto, app requires DPoP: plain try, then DPoP try, then users", users and f.token_calls == 2 and f.dpop_on_token == 1, f"{err} calls={f.token_calls}")
chk("API calls carry DPoP and the access token", f.api_calls == 1 and f.dpop_on_api == 1 and f.api_seen == ["DPoP"])
chk("API proof used the same key as the token request", len(f.api_keys) == 1 and f.api_keys == {f.token_key})
chk("every proof and assertion id is unique, no problems", not f.problems, str(f.problems))
# 3. nonce at the token endpoint
f = StrictOkta(require_dpop=True, token_nonce=True)
users, err = run(f)
chk("token nonce: plain, DPoP without nonce, DPoP with nonce", users and f.token_calls == 3, f"{err} calls={f.token_calls}")
chk("token nonce: no problems", not f.problems, str(f.problems))
# 4. nonce at the API
f = StrictOkta(require_dpop=True, api_nonce=True)
users, err = run(f)
chk("API nonce: the call is repeated once with the nonce", users and f.api_calls == 2 and f.dpop_on_api == 2, f"{err} calls={f.api_calls}")
chk("API nonce: no problems", not f.problems, str(f.problems))
# 5. paging: a new proof for every page, htu without the query
f = StrictOkta(require_dpop=True, pages=3)
users, err = run(f)
chk("3 pages with DPoP: 3 users, 3 API calls", users and len(users) == 3 and f.api_calls == 3, f"{err} {f.api_calls}")
chk("3 pages: htu had no query, jti unique, same key", not f.problems, str(f.problems))
# 6. mode on goes straight to DPoP
f = StrictOkta(require_dpop=True)
users, err = run(f, "on")
chk("mode on: DPoP from the first token call", users and f.token_calls == 1 and f.dpop_on_token == 1, f"{err} {f.token_calls}")
f = StrictOkta()
users, err = run(f, "true")
chk("mode on with an app that does not need it: still works", users is not None and not f.problems, f"{err} {f.problems}")
# 7. mode off
f = StrictOkta(require_dpop=True)
users, err = run(f, "off")
chk("mode off, app requires DPoP: stops after one call, names the error", users is None and f.token_calls == 1 and "invalid_dpop_proof" in err, str(err))
f = StrictOkta(token_type_if_plain="DPoP")
users, err = run(f, "off")
chk("mode off, DPoP-bound token: clear refusal, users never called", users is None and "DPoP-bound" in err and f.api_calls == 0, str(err))
f = StrictOkta(token_type_if_plain="mac")
users, err = run(f)
chk("unknown token type refused", users is None and "neither" in err, str(err))
# 8. bounded retries and a hopeless server
f = StrictOkta(always_bad_proof=True)
users, err = run(f)
chk("a server that always rejects the proof: bounded calls, clear error", users is None and f.token_calls <= 4 and "invalid_dpop_proof" in err and "DPoP was used" in err, f"{err} {f.token_calls}")
chk("no users call when the token failed", f.api_calls == 0)
f = StrictOkta(require_dpop=True, token_nonce=True, endless_nonce=True)
users, err = run(f)
chk("a server that asks for a nonce forever: bounded calls, clear error", users is None and f.token_calls <= 4 and "use_dpop_nonce" in err, f"{err} {f.token_calls}")
# 9. a new key on each run
f1, f2 = StrictOkta(require_dpop=True), StrictOkta(require_dpop=True)
run(f1); run(f2)
chk("each run makes its own DPoP key", f1.token_key and f2.token_key and f1.token_key != f2.token_key)
# 10. secrets and startup line
f = StrictOkta(always_bad_proof=True)
_, err = run(f)
chk("error holds no token, key or assertion", ACCESS not in err and CLIENT_JWK["d"][:12] not in err)
line = okta_sync.describe()
chk("startup line names the DPoP mode", "DPoP auto" in line, line)
os.environ["OKTA_SYNC_DPOP"] = "on"
chk("startup line follows the setting", "DPoP on" in okta_sync.describe())
os.environ.pop("OKTA_SYNC_DPOP")
# 11. the SSWS token path is untouched
os.environ["OKTA_API_TOKEN"] = "ssws-value"
f = StrictOkta()
def ssws_handler(req):
f.api_seen.append(req.headers.get("authorization", ""))
return httpx.Response(200, json=[{"status": "ACTIVE", "profile": {"login": "a"}}])
users = okta_sync.fetch_users(http=httpx.Client(transport=httpx.MockTransport(ssws_handler)))
chk("SSWS path unchanged: SSWS header, no DPoP", f.api_seen == ["SSWS ssws-value"] and users, str(f.api_seen))
os.environ.pop("OKTA_API_TOKEN")
print("\nDONE" if fails == 0 else f"\n{fails} FAILED")
sys.exit(1 if fails else 0)