Files
Project-SDE-WP-Suite/server/okta_sync.py
Matt Mabrey 103e4d40ee T13.3: Okta deprovisioning sync job, fail closed (D18)
run_sync() compares the Okta user list (T13.2) to active local accounts and
disables the ones Okta no longer vouches for. One AuditLog row per change,
actor system:okta_sync, action user_deprovisioned_by_sync.

Fail closed: any exception from the fetch, an empty or untrusted answer, or a
failed save changes nothing and writes nothing. The fetch runs before the
database is read, so a failed fetch has no path to a change. It only ever
disables; an already-disabled account is untouched and gets no new row.

Decided with Matt 2026-10-16: disable on missing, SUSPENDED or DEPROVISIONED.
PASSWORD_EXPIRED, LOCKED_OUT and RECOVERY do not disable (the job never
re-enables, so a literal "not ACTIVE" would lock people out for good).
Added a guard: no match between any active local account and any Okta user is
refused as a wrong identity attribute, not read as a mass offboarding.

tests/okta_sync_job_check.py: 71 checks; removing the fail-closed branch and the
guard fails 28 of them. BL-069 logs the missing per-run cap.
2026-10-16 11:31:39 -07:00

339 lines
15 KiB
Python

"""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
T13.3 (the sync job, `run_sync` below) uses that list to disable local accounts.
Its rules are in its own docstring. In short: it only ever disables, it never
re-enables, it writes one audit row per change, and any failure means NO change.
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
import uuid
from dataclasses import dataclass, field
from typing import Callable, Optional
from urllib.parse import urlparse
import httpx
from sqlalchemy import select
from sqlalchemy.orm import Session
from . import models, 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
# ── T13.3: the sync job ───────────────────────────────────────────────────────
# Which Okta statuses mean "this person is gone or was blocked on purpose".
# Decided by Matt, 2026-10-16: a literal "anything that is not ACTIVE" would also
# catch PASSWORD_EXPIRED, LOCKED_OUT and RECOVERY, which people leave on their
# own, and because this job never re-enables, one AD password expiry would lock a
# person out of this app until an admin stepped in. A user who is MISSING from the
# list disables too (Okta's default list leaves out DEPROVISIONED users).
DISABLING_STATUSES = frozenset({"SUSPENDED", "DEPROVISIONED"})
SYNC_ACTOR = "system:okta_sync"
SYNC_ACTION = "user_deprovisioned_by_sync"
@dataclass
class SyncResult:
ok: bool # False = the run took NO action at all
error: str = "" # why, when ok is False
okta_users: int = 0 # size of the Okta list
checked: int = 0 # active local accounts looked at
disabled: "list[str]" = field(default_factory=list) # usernames disabled this run
def _gen_id(prefix: str) -> str:
# Same shape as server/app.py gen_id. Not imported: app.py will import this
# module (T13.4), and the reverse import would be circular.
return f"{prefix}_{uuid.uuid4().hex[:12]}"
def run_sync(db: Session, fetch: Optional[Callable[[], "list[OktaUser]"]] = None) -> SyncResult:
"""Compare the Okta user list to local accounts and disable the ones Okta no
longer vouches for.
The rules, none of which may be relaxed (D18):
1. FAIL CLOSED. If fetching raises ANY exception, or the answer cannot be
trusted, this function changes nothing and writes nothing. A failure is
never read as "nobody is active". The fetch happens before the database
is read, so there is no code path from a failed fetch to a change.
2. ONLY DISABLE. It sets is_active to False. No input makes it set True.
An account that is already disabled is not touched and gets no new
audit row, so a run that finds nothing new writes nothing.
3. One AuditLog row per disabled account, actor "system:okta_sync", so it
is never confused with an admin's action. Rows and changes are saved in
one transaction. If saving fails, none of it is kept.
4. Only changes are logged. A person who is still active in Okta and still
active here produces no row.
One guard beyond the rules above, inside decision 4's "anything the sync can't
confidently parse": if there are active local accounts and NONE of them
matches any Okta user, the identity attribute is almost certainly wrong (see
OKTA_SYNC_PROFILE_ATTRIBUTE). That is a setup mistake, not an offboarding of
the whole company, so the run is refused and nothing changes.
A local account matches an Okta user by username or by email, ignoring case,
the same two fields auth.find_user() uses. If the Okta list holds the same
identity twice with different statuses, the account is disabled only when
every one of them is a disabling status.
`fetch` is for tests. In production it is None and fetch_users() is used.
"""
fetch = fetch or fetch_users
# 1. The fetch. Nothing below runs unless it returned a list.
try:
okta_users = fetch()
except Exception as exc: # an error of ANY kind, not only OktaSyncError
msg = str(exc) if isinstance(exc, OktaSyncError) else f"unexpected {type(exc).__name__}"
log.error("Okta sync SKIPPED, no account was changed: %s", msg)
return SyncResult(ok=False, error=msg)
if not okta_users:
# fetch_users() already raises on an empty list. This covers a stand-in
# fetch (and any future change) that returns one: same rule.
msg = "the fetch returned no users"
log.error("Okta sync SKIPPED, no account was changed: %s", msg)
return SyncResult(ok=False, error=msg)
try:
by_identity: "dict[str, list[str]]" = {}
for u in okta_users:
by_identity.setdefault(u.identity.strip().lower(), []).append(u.status.strip().upper())
locals_ = list(db.scalars(select(models.User).where(models.User.is_active.is_(True))))
plan: "list[tuple[models.User, str]]" = []
matched = 0
for local in locals_:
statuses: "list[str]" = []
for key in {(local.username or "").strip().lower(), (local.email or "").strip().lower()}:
if key:
statuses.extend(by_identity.get(key, []))
if statuses:
matched += 1
if all(st in DISABLING_STATUSES for st in statuses):
plan.append((local, sorted(set(statuses))[0]))
else:
plan.append((local, "MISSING"))
if locals_ and matched == 0:
msg = (f"none of {len(locals_)} active local account(s) matches any of "
f"{len(okta_users)} Okta user(s); the identity attribute is probably wrong")
log.error("Okta sync SKIPPED, no account was changed: %s", msg)
return SyncResult(ok=False, error=msg, okta_users=len(okta_users), checked=len(locals_))
planned = [(local.username, status) for local, status in plan]
checked = len(locals_)
for local, status in plan:
local.is_active = False
db.add(models.AuditLog(
id=_gen_id("ev"), actor=SYNC_ACTOR, action=SYNC_ACTION,
entity_type="user", entity_id=local.id, project_id=None,
summary=local.username[:400],
detail={"okta_status": status, "via": "okta_sync"},
))
db.commit()
except Exception as exc:
db.rollback()
log.error("Okta sync FAILED, nothing was kept: unexpected %s", type(exc).__name__)
return SyncResult(ok=False, error=f"unexpected {type(exc).__name__}")
for name, status in planned:
log.warning("Okta sync disabled %r (Okta status: %s)", name, status)
log.info("Okta sync done: %d Okta user(s), %d active local account(s) checked, %d disabled",
len(okta_users), checked, len(planned))
return SyncResult(ok=True, okta_users=len(okta_users), checked=checked,
disabled=[name for name, _ in planned])