From 1a3468effdda287deebac697bcfd8844ed20cbe5 Mon Sep 17 00:00:00 2001 From: Matt Mabrey Date: Fri, 16 Oct 2026 17:10:19 -0700 Subject: [PATCH] T13.10: DPoP for the Okta Management API calls, auto-detected (D24) --- DEPLOYMENT.md | 10 +- docker-compose.yml | 1 + docs/waves/decisions-2026-10-16.md | 33 ++++ docs/waves/wave-13.md | 17 ++ server/.env.example | 8 +- server/okta_sync.py | 184 +++++++++++++++---- tests/okta_sync_dpop_check.py | 277 +++++++++++++++++++++++++++++ 7 files changed, 490 insertions(+), 40 deletions(-) create mode 100644 tests/okta_sync_dpop_check.py diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index d1eb3f4..5692ab7 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -433,15 +433,19 @@ startup log says `Okta sync DISABLED`. The Okta admin must set up the app as follows: the app type is API Services; the scope `okta.users.read` is granted on the Okta API Scopes tab; an admin role - that can read users (for example Read-only Administrator) is assigned to the app; - and "Require Demonstrating Proof of Possession (DPoP)" is off. If both + that can read users (for example Read-only Administrator) is assigned to the app. + DPoP can be on or off. By default (`OKTA_SYNC_DPOP=auto`) the sync asks for a plain + token first, and if Okta answers `invalid_dpop_proof` it uses DPoP. Set + `OKTA_SYNC_DPOP` to `on` or `off` only to force one way. If both `OKTA_API_TOKEN` and the service-app pair are set, the token is used. The startup line in the log says which credential is in use. A failed sign-in shows the HTTP status and the Okta error code, for example `Okta answered HTTP 400 to the token request, error invalid_scope`. Common codes: `invalid_client` (wrong client ID or key, or the key is not registered on the app), -`invalid_scope` (the scope is not granted), `access_denied` (no admin role assigned). +`invalid_scope` (the scope is not granted), `access_denied` (no admin role assigned), `invalid_dpop_proof` (DPoP was used and Okta +rejected the proof: send the log lines to the developer), `use_dpop_nonce` (Okta kept +asking for a new nonce). **First deploy: use the dry run.** Set `OKTA_SYNC_DRY_RUN=true` in `.env` (or the Portainer stack environment) with the token, then run `docker compose up -d --build api`. diff --git a/docker-compose.yml b/docker-compose.yml index 9723b43..c3e4e53 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -61,6 +61,7 @@ services: OKTA_ORG_URL: ${OKTA_ORG_URL:-} OKTA_SYNC_CLIENT_ID: ${OKTA_SYNC_CLIENT_ID:-} OKTA_SYNC_PRIVATE_KEY: ${OKTA_SYNC_PRIVATE_KEY:-} + OKTA_SYNC_DPOP: ${OKTA_SYNC_DPOP:-} OKTA_SYNC_PROFILE_ATTRIBUTE: ${OKTA_SYNC_PROFILE_ATTRIBUTE:-} OKTA_SYNC_INTERVAL_SECONDS: ${OKTA_SYNC_INTERVAL_SECONDS:-} OKTA_SYNC_DRY_RUN: ${OKTA_SYNC_DRY_RUN:-} diff --git a/docs/waves/decisions-2026-10-16.md b/docs/waves/decisions-2026-10-16.md index 900ea07..a72c302 100644 --- a/docs/waves/decisions-2026-10-16.md +++ b/docs/waves/decisions-2026-10-16.md @@ -61,3 +61,36 @@ code is a short lower-case word. **Not decided here:** how often the key is replaced. A key is registered on the Okta app and has no expiry that this code checks. + +## D24: DPoP for the Okta Management API calls + +**Asked by:** Matt Mabrey, 2026-10-16. **Extends:** D23. **Task:** T13.10. + +**Why:** The first live token request with the service-app key ended with +`error invalid_dpop_proof`. The Okta app requires DPoP (RFC 9449). With DPoP, every +request carries a signed proof from a key that only the caller holds, so a stolen +access token alone does not work. The choice was to ask the Okta admin to switch DPoP +off, or to build it. Matt chose to build it. + +**Decision:** + +- `OKTA_SYNC_DPOP` is `auto` (default), `on` or `off`. In auto mode the sync asks for a + plain Bearer token first. If Okta answers `invalid_dpop_proof`, the sync asks again with + DPoP. So one build works whether the Okta app requires DPoP or not. +- Each run makes its own throwaway EC P-256 key. It is held in memory only, never + stored, logged or configured. The public half goes in each proof header. +- Each request gets its own proof (ES256, `typ` dpop+jwt): `htm`, `htu` without the + query, a one-time `jti`, `iat`, the server's latest `nonce`, and on an API call `ath` + (a hash of the access token). The same key is used for the token request and the API + calls. A new client assertion is built for every token attempt. +- A nonce challenge is answered once per request, at the token endpoint and at the API. + The token request is tried at most 4 times. +- A DPoP-bound token is sent as `Authorization: DPoP `. If the setting is `off` + and Okta returns a DPoP-bound token, the sync stops with a clear message. + +**Rules from D18 and D23 that stay:** fail closed; the key, the assertions, the proofs and +the access token are never logged or put in an error message; an error carries the HTTP +status and Okta's short error code only. The SSWS token path is unchanged. + +**Not verified:** this has been tested only against a fake Okta that follows the RFC. The +first run against the real tenant is the real test. diff --git a/docs/waves/wave-13.md b/docs/waves/wave-13.md index 3d5e42e..c143d48 100644 --- a/docs/waves/wave-13.md +++ b/docs/waves/wave-13.md @@ -405,3 +405,20 @@ with a brace, but Python's strict JSON reader refused them (PowerShell accepted The loader now accepts control characters such as line breaks inside a string, curly quote marks and a trailing comma, removes spaces inside the key's number fields, and a real syntax error reports the line and column (position and rule only, never key text). + +## T13.10: D24 DPoP for the Okta Management API + +**Item:** D24 (`docs/waves/decisions-2026-10-16.md`). Extends T13.9. + +**Done when:** + +- [x] auto mode: a plain Bearer token is tried first; `invalid_dpop_proof` makes the sync retry with DPoP (`tests/okta_sync_dpop_check.py`) +- [x] each proof verifies: header (`dpop+jwt`, ES256, public jwk only), signature, `htm`, `htu` without query, current `iat`, one-time `jti`, `ath` on API calls, same key for token and API calls +- [x] nonce challenges at the token endpoint and at the API are answered once, and the retries are bounded +- [x] paging: a new proof for every page +- [x] mode `on` and mode `off`; a DPoP-bound token with mode off is refused; each run makes a new key +- [x] no secret in any message or the startup line; the SSWS path is unchanged +- [x] mutation checks: query kept in `htu`, `ath` omitted, `jti` reused, nonce not retried (token and API), private key in the proof header, and auto detection removed each make a test fail +- [x] `.env.example`, `docker-compose.yml`, `DEPLOYMENT.md` updated + +Result 2026-10-16: sandbox, strict fake Okta. Not yet run against the real tenant. diff --git a/server/.env.example b/server/.env.example index 6122269..48a804c 100644 --- a/server/.env.example +++ b/server/.env.example @@ -75,9 +75,13 @@ OKTA_REDIRECT_URI=CHANGE_ME # OKTA_SYNC_PRIVATE_KEY its PRIVATE key as a JWK, as JSON or as base64 of that JSON. # In Portainer use base64: it has no quote marks to be mangled. # The Okta app needs the scope okta.users.read granted (Okta API Scopes tab), an admin -# role such as Read-only Administrator assigned to it, and "Require Demonstrating Proof -# of Possession (DPoP)" switched OFF. The key is a secret: never commit it or paste it +# role such as Read-only Administrator assigned to it. If the app has "Require Demonstrating +# Proof of Possession (DPoP)" switched on, the sync detects that and uses DPoP by itself. The key is a secret: never commit it or paste it # into chat or a ticket. +# OKTA_SYNC_DPOP: auto (default), on, or off. auto asks for a plain Bearer token first, and +# uses DPoP only if Okta answers invalid_dpop_proof. Set "on" to always use DPoP. +# Set "off" to never use it. You normally set nothing. +# OKTA_SYNC_DPOP=auto # OKTA_SYNC_CLIENT_ID=0oaXXXXXXXXXXXXXXXXX # OKTA_SYNC_PRIVATE_KEY= diff --git a/server/okta_sync.py b/server/okta_sync.py index 9cd1378..b214195 100644 --- a/server/okta_sync.py +++ b/server/okta_sync.py @@ -36,6 +36,7 @@ exception class name and the HTTP status only. httpx exceptions can include the request URL, so the URL is not copied into the message either. """ import base64 +import hashlib import json import logging import os @@ -50,6 +51,7 @@ from urllib.parse import urlparse import httpx import jwt +from cryptography.hazmat.primitives.asymmetric import ec from sqlalchemy import select, update from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session @@ -281,34 +283,127 @@ def _client_assertion(jwk: dict, client_id: str, audience: str) -> str: raise _fail(f"the key could not sign ({type(exc).__name__})") from None -def _access_token(client: httpx.Client, base: str) -> str: - """Trade a signed assertion for an access token. Returns the token string. - Raises OktaSyncError for every failure. Neither the key, the assertion nor the - token is logged or put in a message.""" +def _dpop_mode() -> str: + """OKTA_SYNC_DPOP (D24): "auto" (the default), "on" or "off". + auto: ask for a plain Bearer token first. If Okta answers invalid_dpop_proof, the + Okta app requires DPoP, and the sync asks again with DPoP. Nothing to set. + on: always use DPoP. + off: never use DPoP. A DPoP-bound token is then refused with a clear message.""" + v = os.getenv("OKTA_SYNC_DPOP", "").strip().lower() + if v in {"1", "true", "yes", "on"}: + return "on" + if v in {"0", "false", "no", "off"}: + return "off" + return "auto" + + +def _url_no_query(url: str) -> str: + p = urlparse(url) + return f"{p.scheme}://{p.netloc}{p.path}" + + +class _Dpop: + """DPoP (RFC 9449): proof that the caller holds a key, sent with every request, so + a stolen access token alone is useless. One throwaway EC key (P-256) is made for each + run and is never stored or logged. Each request gets its own signed proof: the method + (htm), the URL without its query (htu), a one-time id (jti), the time (iat), the + server's latest nonce if it gave one, and for an API call a hash of the access token + (ath). The public half of the key travels in the proof header.""" + + def __init__(self): + self._key = ec.generate_private_key(ec.SECP256R1()) + pub = json.loads(jwt.algorithms.ECAlgorithm.to_jwk(self._key.public_key())) + self._pub = {k: pub[k] for k in ("kty", "crv", "x", "y")} + self.nonce: Optional[str] = None + + def proof(self, method: str, url: str, access_token: Optional[str] = None) -> str: + claims = {"jti": uuid.uuid4().hex, "htm": method.upper(), "htu": _url_no_query(url), + "iat": int(time.time())} + if self.nonce: + claims["nonce"] = self.nonce + if access_token: + claims["ath"] = base64.urlsafe_b64encode( + hashlib.sha256(access_token.encode()).digest()).rstrip(b"=").decode() + return jwt.encode(claims, self._key, algorithm="ES256", + headers={"typ": "dpop+jwt", "jwk": self._pub}) + + def take_nonce(self, resp: httpx.Response) -> Optional[str]: + n = resp.headers.get("DPoP-Nonce") + if n: + self.nonce = n + return n + + +class _Credential: + """What is sent with each Management API call: an SSWS token, a Bearer token, or a + DPoP-bound token with a fresh proof for every request.""" + + def __init__(self, scheme: str, token: str, dpop: Optional[_Dpop] = None): + self.scheme, self.token, self.dpop = scheme, token, dpop + + def headers(self, method: str, url: str) -> dict: + h = {"Accept": "application/json"} + if self.dpop is not None: + h["Authorization"] = f"DPoP {self.token}" + h["DPoP"] = self.dpop.proof(method, url, self.token) + else: + h["Authorization"] = f"{self.scheme} {self.token}" + return h + + +def _error_code(resp: httpx.Response) -> str: + """Okta's OAuth error code (invalid_client, invalid_scope, invalid_dpop_proof, ...). + It tells an admin what to fix and holds no secret. Kept only if it is a short code.""" + try: + c = resp.json().get("error", "") + if isinstance(c, str) and re.fullmatch(r"[a-z_]{1,40}", c): + return c + except Exception: # noqa: BLE001 + pass + return "" + + +def _access_token(client: httpx.Client, base: str) -> _Credential: + """Trade a signed assertion for an access token. Raises OktaSyncError for every + failure. Neither the key, the assertion nor the token is logged or put in a message. + Each attempt gets a new assertion, because Okta accepts an assertion id only once.""" client_id = _client_id() if not client_id: raise _fail("OKTA_SYNC_CLIENT_ID is not set") endpoint = f"{base}/oauth2/v1/token" - assertion = _client_assertion(_load_jwk(), client_id, endpoint) - try: - resp = client.post( - endpoint, headers={"Accept": "application/json"}, follow_redirects=False, - data={"grant_type": "client_credentials", "scope": OAUTH_SCOPE, - "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", - "client_assertion": assertion}) - except httpx.HTTPError as exc: - raise _fail(f"network error on the token request ({type(exc).__name__})") from None - if resp.status_code != 200: - # Okta's error code (invalid_client, invalid_scope, ...) tells an admin what - # to fix and holds no secret. Keep it only if it looks like a short code. - code = "" + jwk = _load_jwk() + mode = _dpop_mode() + dpop: Optional[_Dpop] = _Dpop() if mode == "on" else None + nonce_retries = 0 + resp = None + for _ in range(4): + headers = {"Accept": "application/json"} + if dpop is not None: + headers["DPoP"] = dpop.proof("POST", endpoint) try: - c = resp.json().get("error", "") - if isinstance(c, str) and re.fullmatch(r"[a-z_]{1,40}", c): - code = f", error {c}" - except Exception: # noqa: BLE001 - pass - raise _fail(f"Okta answered HTTP {resp.status_code} to the token request{code}") + resp = client.post( + endpoint, headers=headers, follow_redirects=False, + data={"grant_type": "client_credentials", "scope": OAUTH_SCOPE, + "client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", + "client_assertion": _client_assertion(jwk, client_id, endpoint)}) + except httpx.HTTPError as exc: + raise _fail(f"network error on the token request ({type(exc).__name__})") from None + if dpop is not None: + dpop.take_nonce(resp) + if resp.status_code == 200: + break + code = _error_code(resp) + if mode == "auto" and dpop is None and code == "invalid_dpop_proof": + dpop = _Dpop() # the Okta app requires DPoP: ask again with it + continue + if dpop is not None and code == "use_dpop_nonce" and dpop.nonce and nonce_retries < 2: + nonce_retries += 1 # Okta asks for its nonce in the proof: ask again with it + continue + raise _fail(f"Okta answered HTTP {resp.status_code} to the token request" + + (f", error {code}" if code else "") + + (" (DPoP was used)" if dpop is not None else "")) + else: + raise _fail("the token request did not succeed after retries") try: body = resp.json() except ValueError: @@ -316,9 +411,14 @@ def _access_token(client: httpx.Client, base: str) -> str: tok = body.get("access_token") if isinstance(body, dict) else None if not isinstance(tok, str) or not tok: raise _fail("the token response has no access token") - if str(body.get("token_type", "")).lower() != "bearer": - raise _fail("the token response is not a Bearer token (the Okta app may require DPoP)") - return tok + kind = str(body.get("token_type", "")).lower() + if kind == "dpop": + if dpop is None: + raise _fail("the token is DPoP-bound but OKTA_SYNC_DPOP is off") + return _Credential("DPoP", tok, dpop) + if kind == "bearer": + return _Credential("Bearer", tok) + raise _fail("the token response is neither a Bearer nor a DPoP token") def is_configured() -> bool: @@ -337,7 +437,8 @@ def describe() -> str: if not base.startswith("https://"): return f"Okta sync DISABLED - org URL {base!r} is not https. The token is never sent over http." mode = "DRY RUN, no account is changed" if dry_run() else "live" - how = "API token" if method == "token" else "OAuth service app (private_key_jwt)" + how = ("API token" if method == "token" + else f"OAuth service app (private_key_jwt), DPoP {_dpop_mode()}") return (f"Okta sync configured ({mode}) - org {base}, credential: {how}, " f"identity claim {okta_auth.IDENTITY_CLAIM!r}") @@ -385,6 +486,22 @@ def _parse_user(item, attribute: str) -> OktaUser: return OktaUser(identity=value.strip(), status=status.strip().upper()) +def _get_page(client: httpx.Client, cred: _Credential, url: str, params: Optional[dict]) -> httpx.Response: + """One GET, with the credential's headers. With DPoP, each call has its own proof, + and if the server answers use_dpop_nonce the call is repeated once with its nonce.""" + for attempt in (0, 1): + resp = client.get(url, params=params, headers=cred.headers("GET", url), follow_redirects=False) + if cred.dpop is None: + return resp + nonce = cred.dpop.take_nonce(resp) + asks = resp.status_code in (400, 401) and nonce and ( + "use_dpop_nonce" in resp.headers.get("WWW-Authenticate", "") or "use_dpop_nonce" in resp.text) + if attempt == 0 and asks: + continue + return resp + return resp + + def fetch_users(http: Optional[httpx.Client] = None) -> "list[OktaUser]": """Return every user Okta lists, as OktaUser values. Raises OktaSyncError on any problem; never returns an empty list. `http` is for tests (a client built @@ -403,11 +520,8 @@ def fetch_users(http: Optional[httpx.Client] = None) -> "list[OktaUser]": users: "list[OktaUser]" = [] started = time.monotonic() try: - if method == "token": - headers = {"Accept": "application/json", "Authorization": f"SSWS {_token()}"} - else: - headers = {"Accept": "application/json", - "Authorization": f"Bearer {_access_token(client, base)}"} + cred = (_Credential("SSWS", _token()) if method == "token" + else _access_token(client, base)) url: Optional[str] = f"{base}/api/v1/users" params: Optional[dict] = {"limit": PAGE_LIMIT} for _ in range(MAX_PAGES): @@ -416,8 +530,7 @@ def fetch_users(http: Optional[httpx.Client] = None) -> "list[OktaUser]": if time.monotonic() - started > TOTAL_DEADLINE_SECONDS: raise _fail(f"took longer than {int(TOTAL_DEADLINE_SECONDS)} seconds in total") try: - resp = client.get(url, params=params, headers=headers, - follow_redirects=False) + resp = _get_page(client, cred, url, params) except httpx.HTTPError as exc: # Class name only. The exception text can carry the URL. raise _fail(f"network error ({type(exc).__name__})") from None @@ -448,7 +561,8 @@ def fetch_users(http: Optional[httpx.Client] = None) -> "list[OktaUser]": if not users: raise _fail("Okta returned no users, which is not credible for a real org") - log.info("Okta user list fetched: %d user(s)", len(users)) + log.info("Okta user list fetched: %d user(s)%s", len(users), + " (with DPoP)" if cred.dpop is not None else "") return users diff --git a/tests/okta_sync_dpop_check.py b/tests/okta_sync_dpop_check.py new file mode 100644 index 0000000..687c28f --- /dev/null +++ b/tests/okta_sync_dpop_check.py @@ -0,0 +1,277 @@ +#!/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)