T13.10: DPoP for the Okta Management API calls, auto-detected (D24)

This commit is contained in:
2026-10-16 17:10:19 -07:00
parent 83e77ec622
commit 1a3468effd
7 changed files with 490 additions and 40 deletions

View File

@@ -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=

View File

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