#!/usr/bin/env python3 """Does the Okta Management API client keep its promises? - D18 / T13.2. The one promise that matters: a failure is never an empty list. T13.3 reads an empty list as "nobody is active", so a client that returned [] when Okta was down would disable the whole org. Every failure below must raise OktaSyncError. Also checked: the client uses its own credential (never the OIDC client secret), follows pagination, never sends the token to another host, never follows a redirect, and never lets the token reach a log line, an error message, or describe(). Self-contained: no server, no database, no network, no browser. httpx's MockTransport stands in for Okta. Exit 0 all passed, 1 a failure. """ import logging import os import sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, ROOT) import httpx # noqa: E402 from server import okta_auth, okta_sync # noqa: E402 TOKEN = "00tok-SECRET-api-token-xyz" CLIENT_SECRET = "oidc-client-SECRET-abc" ORG = "https://example.okta.com" 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 class Capture(logging.Handler): def __init__(self): super().__init__() self.lines = [] def emit(self, record): self.lines.append(record.getMessage()) cap = Capture() logging.getLogger("wpsuite").addHandler(cap) logging.getLogger("wpsuite").setLevel(logging.DEBUG) def reset_env(): os.environ["OKTA_API_TOKEN"] = TOKEN os.environ["OKTA_CLIENT_SECRET"] = CLIENT_SECRET os.environ.pop("OKTA_ORG_URL", None) os.environ.pop("OKTA_SYNC_PROFILE_ATTRIBUTE", None) okta_auth.ISSUER = f"{ORG}/oauth2/default" okta_auth.IDENTITY_CLAIM = "preferred_username" def user(login, status="ACTIVE", **profile): p = {"login": login, "email": login} p.update(profile) return {"id": "00u" + login, "status": status, "profile": p} def client(handler): return httpx.Client(transport=httpx.MockTransport(handler)) def raises(handler, label, **kw): """Run fetch_users against `handler`; it must raise OktaSyncError, and the message must not hold the token.""" reset_env() try: out = okta_sync.fetch_users(http=client(handler)) except okta_sync.OktaSyncError as exc: msg = str(exc) clean = TOKEN not in msg and CLIENT_SECRET not in msg and "example.okta.com" not in msg chk(f"{label}: raises, message has no token or host", clean, msg) return msg except Exception as exc: # the wrong exception type chk(f"{label}: raises OktaSyncError", False, f"{type(exc).__name__}: {exc}") return "" chk(f"{label}: raises (did NOT raise, returned {out!r})", False) return "" def ok(body): return lambda req: httpx.Response(200, json=body) # ── 1. a good fetch ─────────────────────────────────────────────────────────── print("\n1. a good fetch") reset_env() seen = [] def good(req): seen.append(req) return httpx.Response(200, json=[user("alice", "ACTIVE"), user("bob", "suspended")]) users = okta_sync.fetch_users(http=client(good)) chk("returns every user", [u.identity for u in users] == ["alice", "bob"]) chk("status is upper case", [u.status for u in users] == ["ACTIVE", "SUSPENDED"]) chk("asks the users endpoint of the org", str(seen[0].url).startswith(f"{ORG}/api/v1/users")) chk("asks for the page maximum", seen[0].url.params.get("limit") == "200") chk("authenticates with the API token (SSWS)", seen[0].headers.get("authorization") == f"SSWS {TOKEN}") chk("never sends the OIDC client secret", CLIENT_SECRET not in str(seen[0].headers)) # ── 2. pagination ───────────────────────────────────────────────────────────── print("\n2. pagination") reset_env() calls = [] def paged(req): calls.append(req) if "after=p2" not in str(req.url): return httpx.Response(200, json=[user("alice")], headers={"Link": f'<{ORG}/api/v1/users?limit=200&after=p2>; rel="next"'}) return httpx.Response(200, json=[user("bob")]) users = okta_sync.fetch_users(http=client(paged)) chk("follows the next link and returns both pages", [u.identity for u in users] == ["alice", "bob"]) chk("two requests, no more", len(calls) == 2) chk("page 2 also carries the token", calls[1].headers.get("authorization") == f"SSWS {TOKEN}") # ── 3. the failure rule: an error is never an empty list ────────────────────── print("\n3. every failure raises (never returns an empty list)") for code in (401, 403, 404, 429, 500, 502, 503): raises(lambda req, c=code: httpx.Response(c, json={"errorCode": "x"}), f"HTTP {code}") raises(lambda req: httpx.Response(302, headers={"Location": "https://evil.example/"}), "a redirect (never followed)") raises(lambda req: (_ for _ in ()).throw(httpx.ConnectError("boom to https://example.okta.com/api/v1/users")), "connection error") raises(lambda req: (_ for _ in ()).throw(httpx.ReadTimeout("slow")), "timeout") raises(lambda req: httpx.Response(200, text="not json"), "body is not JSON") raises(ok({"errorCode": "E0000011"}), "body is an object, not a list") raises(ok("a string"), "body is a string") raises(ok([]), "an empty list (not credible for a real org)") raises(ok(["alice"]), "an item that is not an object") raises(ok([{"profile": {"login": "a"}}]), "an item with no status") raises(ok([{"status": "ACTIVE"}]), "an item with no profile") raises(ok([{"status": "ACTIVE", "profile": {}}]), "an item with no login") raises(ok([{"status": "ACTIVE", "profile": {"login": " "}}]), "an item with a blank login") raises(ok([user("alice"), {"status": "ACTIVE", "profile": {}}]), "one bad item among good ones (never skipped)") # ── 4. misconfiguration raises ──────────────────────────────────────────────── print("\n4. misconfiguration") reset_env() os.environ["OKTA_API_TOKEN"] = "" try: okta_sync.fetch_users(http=client(good)) chk("no token raises", False) except okta_sync.OktaSyncError: chk("no token raises", True) reset_env() okta_auth.ISSUER = "" try: okta_sync.fetch_users(http=client(good)) chk("no org URL raises", False) except okta_sync.OktaSyncError: chk("no org URL raises", True) reset_env() os.environ["OKTA_ORG_URL"] = "http://example.okta.com" sent = [] try: okta_sync.fetch_users(http=client(lambda r: sent.append(r) or httpx.Response(200, json=[user("a")]))) chk("an http org URL raises", False) except okta_sync.OktaSyncError: chk("an http org URL raises", True) chk("...and no request was made (token never sent over http)", sent == []) # ── 5. never leaks the token to another host, never loops forever ───────────── print("\n5. next-link safety") reset_env() hosts = [] def evil_link(req): hosts.append(req.url.host) return httpx.Response(200, json=[user("alice")], headers={"Link": '; rel="next"'}) raises(evil_link, "a next link to another host") chk("...the other host was never contacted", hosts == ["example.okta.com"]) count = [] def endless(req): count.append(1) return httpx.Response(200, json=[user("alice")], headers={"Link": f'<{ORG}/api/v1/users?after={len(count)}>; rel="next"'}) raises(endless, "an endless next chain (page cap)") chk(f"...stops at the cap ({okta_sync.MAX_PAGES} requests)", len(count) == okta_sync.MAX_PAGES, str(len(count))) # ── 6. org URL and identity attribute ───────────────────────────────────────── print("\n6. org URL and identity attribute") reset_env() chk("org URL is the issuer's scheme and host", okta_sync.org_url() == ORG) os.environ["OKTA_ORG_URL"] = "https://corp.okta.com/" chk("OKTA_ORG_URL wins, trailing slash removed", okta_sync.org_url() == "https://corp.okta.com") reset_env() okta_auth.IDENTITY_CLAIM = "email" body = [{"status": "ACTIVE", "profile": {"login": "alice", "email": "alice@x.com"}}] chk("claim 'email' reads profile.email", okta_sync.fetch_users(http=client(ok(body)))[0].identity == "alice@x.com") okta_auth.IDENTITY_CLAIM = "sAMAccountName" body = [{"status": "ACTIVE", "profile": {"login": "alice@x.com", "sAMAccountName": "alice"}}] chk("a custom claim reads profile[]", okta_sync.fetch_users(http=client(ok(body)))[0].identity == "alice") os.environ["OKTA_SYNC_PROFILE_ATTRIBUTE"] = "login" chk("OKTA_SYNC_PROFILE_ATTRIBUTE overrides", okta_sync.fetch_users(http=client(ok(body)))[0].identity == "alice@x.com") # ── 7. the token never leaks ────────────────────────────────────────────────── print("\n7. the token never leaks") reset_env() chk("describe() has no token", TOKEN not in okta_sync.describe() and "configured" in okta_sync.describe()) os.environ["OKTA_API_TOKEN"] = "" chk("describe() says DISABLED without a token", "DISABLED" in okta_sync.describe()) reset_env() every_log = " ".join(cap.lines) chk("no log line holds the API token", TOKEN not in every_log) chk("no log line holds the client secret", CLIENT_SECRET not in every_log) print() print("ALL PASSED" if not fails else f"{fails} FAILED") sys.exit(0 if not fails else 1)