T13.9: sign in to the Okta Management API as an OAuth service app, private_key_jwt (D23)

This commit is contained in:
2026-10-16 15:29:32 -07:00
parent ad1b8273c0
commit d137d690f9
7 changed files with 422 additions and 11 deletions

View File

@@ -68,6 +68,19 @@ OKTA_REDIRECT_URI=CHANGE_ME
# stays off (the startup log says so).
# OKTA_API_TOKEN=CHANGE_ME
#
# Second way to sign in to the Management API (D23): an Okta "API Services" app that
# uses client authentication private_key_jwt. Set these two INSTEAD of OKTA_API_TOKEN.
# If OKTA_API_TOKEN is also set, the token is used.
# OKTA_SYNC_CLIENT_ID the client ID of that app (starts with 0oa)
# 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
# into chat or a ticket.
# OKTA_SYNC_CLIENT_ID=0oaXXXXXXXXXXXXXXXXX
# OKTA_SYNC_PRIVATE_KEY=
# The Okta org URL that serves the Management API, e.g. https://yourorg.okta.com
# Optional. If unset, it is the scheme and host of OKTA_ISSUER. Must be https.
# OKTA_ORG_URL=https://your-org.okta.com

View File

@@ -35,8 +35,11 @@ never put in an error message, and never returned to a browser. Errors carry the
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 json
import logging
import os
import re
import threading
import time
import uuid
@@ -46,6 +49,7 @@ from typing import Callable, Optional
from urllib.parse import urlparse
import httpx
import jwt
from sqlalchemy import select, update
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
@@ -135,21 +139,132 @@ def org_url() -> str:
return ""
# D23: a second way to prove who we are to Okta. Okta apps of type "API Services"
# use OAuth 2.0 with client authentication private_key_jwt: this app holds a private
# key (a JWK), signs a short JWT with it, trades the JWT for a one-hour access token
# that carries only the scope okta.users.read, and sends that as a Bearer token. The
# private key never leaves this process. An SSWS API token (OKTA_API_TOKEN) still
# works and wins if both are set, so a deploy that has only a token behaves as before.
OAUTH_SCOPE = "okta.users.read"
ASSERTION_LIFETIME_SECONDS = 300
def _client_id() -> str:
return os.getenv("OKTA_SYNC_CLIENT_ID", "").strip()
def _key_raw() -> str:
return os.getenv("OKTA_SYNC_PRIVATE_KEY", "").strip()
def auth_method() -> str:
""""token" (SSWS API token), "oauth" (service app with a private key), or "" (none)."""
if _token():
return "token"
if _client_id() and _key_raw():
return "oauth"
return ""
def _load_jwk() -> dict:
"""OKTA_SYNC_PRIVATE_KEY is the private key as a JWK. Two forms are accepted:
the JSON itself (it starts with "{"), or that JSON encoded as base64. Use base64
in a Portainer environment field: it has no quote marks to be mangled. Raises
OktaSyncError without ever putting the key, or any part of it, in the message."""
raw = _key_raw()
if not raw:
raise _fail("OKTA_SYNC_PRIVATE_KEY is not set")
try:
text = raw if raw.startswith("{") else base64.b64decode(raw, validate=True).decode("utf-8")
jwk = json.loads(text)
except Exception: # noqa: BLE001 - any failure here is "cannot read the key"; say nothing more
raise _fail("OKTA_SYNC_PRIVATE_KEY is not a JWK as JSON or as base64 of JSON") from None
if not isinstance(jwk, dict) or jwk.get("kty") not in {"RSA", "EC"}:
raise _fail("OKTA_SYNC_PRIVATE_KEY is not an RSA or EC key")
if "d" not in jwk:
raise _fail("OKTA_SYNC_PRIVATE_KEY holds a PUBLIC key; the private key is needed to sign")
return jwk
def _client_assertion(jwk: dict, client_id: str, audience: str) -> str:
"""The signed JWT that proves we hold the key. Okta's rules: iss and sub are the
client ID, aud is the token endpoint, and the lifetime is at most 60 minutes."""
alg = jwk.get("alg") or ("RS256" if jwk["kty"] == "RSA" else "ES256")
algorithms = jwt.algorithms.get_default_algorithms()
if alg not in algorithms:
raise _fail(f"the key names an algorithm that is not supported ({alg})")
try:
key = algorithms[alg].from_jwk(json.dumps(jwk))
now = int(time.time())
return jwt.encode(
{"iss": client_id, "sub": client_id, "aud": audience, "iat": now,
"exp": now + ASSERTION_LIFETIME_SECONDS, "jti": uuid.uuid4().hex},
key, algorithm=alg, headers={"kid": jwk["kid"]} if jwk.get("kid") else None)
except OktaSyncError:
raise
except Exception as exc: # noqa: BLE001
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."""
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 = ""
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}")
try:
body = resp.json()
except ValueError:
raise _fail("the token response is not JSON") from None
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
def is_configured() -> bool:
return bool(_token() and org_url().startswith("https://"))
return bool(auth_method() and org_url().startswith("https://"))
def describe() -> str:
"""One line for the startup log. Never contains the token."""
if not _token():
return "Okta sync DISABLED - OKTA_API_TOKEN is not set. Deprovisioning is not detected."
method = auth_method()
if not method:
return ("Okta sync DISABLED - set OKTA_API_TOKEN, or OKTA_SYNC_CLIENT_ID and "
"OKTA_SYNC_PRIVATE_KEY. Deprovisioning is not detected.")
base = org_url()
if not base:
return "Okta sync DISABLED - no OKTA_ORG_URL and OKTA_ISSUER has no host. Deprovisioning is not detected."
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"
return f"Okta sync configured ({mode}) - org {base}, identity claim {okta_auth.IDENTITY_CLAIM!r}"
how = "API token" if method == "token" else "OAuth service app (private_key_jwt)"
return (f"Okta sync configured ({mode}) - org {base}, credential: {how}, "
f"identity claim {okta_auth.IDENTITY_CLAIM!r}")
def dry_run() -> bool:
@@ -200,22 +315,26 @@ def fetch_users(http: Optional[httpx.Client] = None) -> "list[OktaUser]":
any problem; never returns an empty list. `http` is for tests (a client built
on httpx.MockTransport). In production it is None and a short-lived client is
made here."""
token = _token()
method = auth_method()
base = org_url()
if not token:
raise _fail("OKTA_API_TOKEN is not set")
if not method:
raise _fail("no Okta credential is set (OKTA_API_TOKEN, or OKTA_SYNC_CLIENT_ID and OKTA_SYNC_PRIVATE_KEY)")
if not base.startswith("https://"):
raise _fail("the org URL is missing or is not https")
attribute = _profile_attribute()
own_client = http is None
client = http if http is not None else httpx.Client(timeout=TIMEOUT_SECONDS)
headers = {"Accept": "application/json", "Authorization": f"SSWS {token}"}
url: Optional[str] = f"{base}/api/v1/users"
params: Optional[dict] = {"limit": PAGE_LIMIT}
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)}"}
url: Optional[str] = f"{base}/api/v1/users"
params: Optional[dict] = {"limit": PAGE_LIMIT}
for _ in range(MAX_PAGES):
if not url:
break