T13.2: Okta Management API client (D18)
New server/okta_sync.py: lists every Okta user and status with its own read-only credential (OKTA_API_TOKEN, SSWS), separate from the OIDC client. Follows pagination. Every failure raises OktaSyncError; an error is never an empty list, because T13.3 reads an empty list as "nobody is active". Also refuses: a next-page link to another host (token never leaves the org), a redirect, a chain over 50 pages (a cut-off list looks like missing users), a bad item among good ones (never skipped), and an empty list. tests/okta_sync_check.py: 52 checks, self-contained (httpx MockTransport). Not wired into app.py yet. T13.3 uses it; T13.4 starts it on a schedule.
This commit is contained in:
205
server/okta_sync.py
Normal file
205
server/okta_sync.py
Normal file
@@ -0,0 +1,205 @@
|
||||
"""Okta Management API client - T13.2, wave 13 (D18).
|
||||
|
||||
This module asks Okta one question: who is in the org, and what is each person's
|
||||
status? It is the first half of the deprovisioning sync. It does not touch the
|
||||
database and it does not disable anyone. T13.3 does that, using the list this
|
||||
module returns.
|
||||
|
||||
Trust boundary. Sign-in uses the OIDC client (OKTA_CLIENT_ID and OKTA_CLIENT_SECRET,
|
||||
see okta_auth.py). This module uses a different credential, OKTA_API_TOKEN, a
|
||||
read-only Okta API token. The two never mix. A rotation or a leak of one does not
|
||||
touch the other.
|
||||
|
||||
Failure rule (D18, decision 4). This is the most important rule in this file:
|
||||
**an error is never an empty list.** If anything goes wrong, this module raises
|
||||
OktaSyncError. It never returns [] to mean "the call failed". T13.3 reads an empty
|
||||
list as "nobody is active", so a function that returned [] on a network error
|
||||
would disable every account on an Okta outage. The cases that raise are:
|
||||
|
||||
- the token or the org URL is not set
|
||||
- a network error or a timeout
|
||||
- any HTTP status that is not 200 (401, 403 and 429 included)
|
||||
- a body that is not a JSON list, or an item that is not shaped as expected
|
||||
- a user with no usable identity value
|
||||
- a list with no users at all (a real org is never empty; an empty list means
|
||||
the token cannot see the users)
|
||||
- a page limit reached (a cut-off list would make real users look missing)
|
||||
- a "next page" link that points to a different host
|
||||
|
||||
The token is read from the environment each time it is used. It is never logged,
|
||||
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 logging
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import httpx
|
||||
|
||||
from . import okta_auth
|
||||
|
||||
log = logging.getLogger("wpsuite.okta_sync")
|
||||
|
||||
# Okta's own page maximum for this endpoint. Asking for the maximum keeps a
|
||||
# 20-odd account org to a single call.
|
||||
PAGE_LIMIT = 200
|
||||
# A cut-off list is more dangerous than an error, so the loop is bounded and
|
||||
# raises when the bound is reached. 50 pages of 200 is 10,000 people.
|
||||
MAX_PAGES = 50
|
||||
TIMEOUT_SECONDS = 15.0
|
||||
|
||||
# Which Okta *profile attribute* matches each OIDC claim that OKTA_IDENTITY_CLAIM
|
||||
# may name. The sign-in flow reads a claim from the ID token. This API returns
|
||||
# the profile instead. For the default claim, preferred_username, Okta's own
|
||||
# default maps it to profile.login. A claim that is not in this table is read
|
||||
# from profile[<claim>] (for example a custom attribute).
|
||||
# OKTA_SYNC_PROFILE_ATTRIBUTE overrides the whole table. Use it if the tenant
|
||||
# builds the claim from a different attribute.
|
||||
_CLAIM_TO_PROFILE = {
|
||||
"preferred_username": "login",
|
||||
"email": "email",
|
||||
}
|
||||
|
||||
|
||||
class OktaSyncError(Exception):
|
||||
"""The Okta user list could not be fetched with confidence. T13.3 must take no
|
||||
action on any account when it sees this."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OktaUser:
|
||||
identity: str # the value that matches users.username (lower case is NOT applied here)
|
||||
status: str # Okta's status, upper case: ACTIVE, SUSPENDED, DEPROVISIONED, ...
|
||||
|
||||
|
||||
# ── configuration ─────────────────────────────────────────────────────────────
|
||||
def _token() -> str:
|
||||
return os.getenv("OKTA_API_TOKEN", "").strip()
|
||||
|
||||
|
||||
def org_url() -> str:
|
||||
"""The Okta org base URL, for example https://yourorg.okta.com. The Management
|
||||
API lives here, not at the authorization server issuer. OKTA_ORG_URL wins if
|
||||
set. Otherwise it is the scheme and host of OKTA_ISSUER."""
|
||||
explicit = os.getenv("OKTA_ORG_URL", "").strip().rstrip("/")
|
||||
if explicit:
|
||||
return explicit
|
||||
issuer = (okta_auth.ISSUER or "").strip()
|
||||
parsed = urlparse(issuer)
|
||||
if parsed.scheme and parsed.netloc:
|
||||
return f"{parsed.scheme}://{parsed.netloc}"
|
||||
return ""
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
return bool(_token() 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."
|
||||
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."
|
||||
return f"Okta sync configured - org {base}, identity claim {okta_auth.IDENTITY_CLAIM!r}"
|
||||
|
||||
|
||||
def _profile_attribute() -> str:
|
||||
override = os.getenv("OKTA_SYNC_PROFILE_ATTRIBUTE", "").strip()
|
||||
if override:
|
||||
return override
|
||||
claim = okta_auth.IDENTITY_CLAIM
|
||||
return _CLAIM_TO_PROFILE.get(claim, claim)
|
||||
|
||||
|
||||
# ── the client ────────────────────────────────────────────────────────────────
|
||||
def _fail(reason: str) -> "OktaSyncError":
|
||||
# One place to build the error, so no call site can add a URL or a header by
|
||||
# accident.
|
||||
return OktaSyncError(f"Okta user list could not be fetched: {reason}")
|
||||
|
||||
|
||||
def _same_origin(url: str, base: str) -> bool:
|
||||
a, b = urlparse(url), urlparse(base)
|
||||
return (a.scheme, a.netloc) == (b.scheme, b.netloc)
|
||||
|
||||
|
||||
def _parse_user(item, attribute: str) -> OktaUser:
|
||||
if not isinstance(item, dict):
|
||||
raise _fail("a list item is not an object")
|
||||
status = item.get("status")
|
||||
profile = item.get("profile")
|
||||
if not isinstance(status, str) or not status.strip():
|
||||
raise _fail("a user has no status")
|
||||
if not isinstance(profile, dict):
|
||||
raise _fail("a user has no profile")
|
||||
value = profile.get(attribute)
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise _fail(f"a user has no value for profile attribute {attribute!r}")
|
||||
return OktaUser(identity=value.strip(), status=status.strip().upper())
|
||||
|
||||
|
||||
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
|
||||
on httpx.MockTransport). In production it is None and a short-lived client is
|
||||
made here."""
|
||||
token = _token()
|
||||
base = org_url()
|
||||
if not token:
|
||||
raise _fail("OKTA_API_TOKEN is not set")
|
||||
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]" = []
|
||||
try:
|
||||
for _ in range(MAX_PAGES):
|
||||
if not url:
|
||||
break
|
||||
try:
|
||||
resp = client.get(url, params=params, headers=headers,
|
||||
follow_redirects=False)
|
||||
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
|
||||
if resp.status_code != 200:
|
||||
raise _fail(f"Okta answered HTTP {resp.status_code}")
|
||||
try:
|
||||
body = resp.json()
|
||||
except ValueError:
|
||||
raise _fail("the response is not JSON") from None
|
||||
if not isinstance(body, list):
|
||||
raise _fail("the response is not a list of users")
|
||||
users.extend(_parse_user(item, attribute) for item in body)
|
||||
|
||||
nxt = resp.links.get("next", {}).get("url")
|
||||
if not nxt:
|
||||
url = None
|
||||
break
|
||||
if not _same_origin(nxt, base):
|
||||
# Never send the token to a host that the Link header names.
|
||||
raise _fail("a next-page link points to a different host")
|
||||
url, params = nxt, None # the next link already carries its query
|
||||
else:
|
||||
# The loop used every page and the last one still named a next page.
|
||||
raise _fail(f"more than {MAX_PAGES} pages; the list may be cut off")
|
||||
finally:
|
||||
if own_client:
|
||||
client.close()
|
||||
|
||||
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))
|
||||
return users
|
||||
Reference in New Issue
Block a user