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

@@ -408,13 +408,41 @@ posture the abandoned LDAPS design took, carried forward deliberately (D16).
**Who this is for:** app admins, and project super users who manage accounts.
When `OKTA_API_TOKEN` is set, the `api` container asks Okta every 15 minutes
When Okta credentials are set (`OKTA_API_TOKEN`, or the service-app pair below), the `api` container asks Okta every 15 minutes
(`OKTA_SYNC_INTERVAL_SECONDS`) who is still active. It **disables** a local
account when the person is missing from Okta's list, or when Okta shows the
status SUSPENDED or DEPROVISIONED. A password expiry, a lockout, or a recovery
in progress does not disable anyone. With no token set, the sync is off and the
startup log says `Okta sync DISABLED`.
**Two ways to sign in to Okta.** Set one of them.
- *API token (SSWS):* set `OKTA_API_TOKEN` to the token string. It has about 40
letters, digits, hyphens and underscores, and no quote marks.
- *Service app with a private key (`private_key_jwt`):* set `OKTA_SYNC_CLIENT_ID`
(the app's client ID, it starts with `0oa`) and `OKTA_SYNC_PRIVATE_KEY` (the
private key as a JWK). The key starts with `{` and has fields such as `kty`,
`kid` and `d`. In Portainer, encode it as base64 first, because Portainer can
change the quote marks in JSON. In Windows PowerShell, save the key to a file
`key.json` and run:
[Convert]::ToBase64String([IO.File]::ReadAllBytes("key.json"))
Paste the one-line result as the value. Delete `key.json` afterward. The key is
a secret: never put it in Git, a ticket, or a chat.
The Okta admin must set up the app as follows: the app type is API Services; the
scope `okta.users.read` is granted on the Okta API Scopes tab; an admin role
that can read users (for example Read-only Administrator) is assigned to the app;
and "Require Demonstrating Proof of Possession (DPoP)" is off. If both
`OKTA_API_TOKEN` and the service-app pair are set, the token is used.
The startup line in the log says which credential is in use. A failed sign-in
shows the HTTP status and the Okta error code, for example
`Okta answered HTTP 400 to the token request, error invalid_scope`. Common codes:
`invalid_client` (wrong client ID or key, or the key is not registered on the app),
`invalid_scope` (the scope is not granted), `access_denied` (no admin role assigned).
**First deploy: use the dry run.** Set `OKTA_SYNC_DRY_RUN=true` in `.env` (or the
Portainer stack environment) with the token, then run `docker compose up -d --build api`.
The sync runs as normal but changes no account and writes no audit row. Read the

View File

@@ -59,6 +59,8 @@ services:
# needed; the host firewall must allow https to the Okta org.
OKTA_API_TOKEN: ${OKTA_API_TOKEN:-}
OKTA_ORG_URL: ${OKTA_ORG_URL:-}
OKTA_SYNC_CLIENT_ID: ${OKTA_SYNC_CLIENT_ID:-}
OKTA_SYNC_PRIVATE_KEY: ${OKTA_SYNC_PRIVATE_KEY:-}
OKTA_SYNC_PROFILE_ATTRIBUTE: ${OKTA_SYNC_PROFILE_ATTRIBUTE:-}
OKTA_SYNC_INTERVAL_SECONDS: ${OKTA_SYNC_INTERVAL_SECONDS:-}
OKTA_SYNC_DRY_RUN: ${OKTA_SYNC_DRY_RUN:-}

View File

@@ -29,3 +29,35 @@ first live run. It does not stop a bad live run.
**Rules from D18 that stay:** fail closed, only disable, one audit row for each
change, actor `system:okta_sync`.
## D23: sign in to the Okta Management API as an OAuth service app
**Asked by:** Matt Mabrey, 2026-10-16. **Extends:** D18, T13.2. **Task:** T13.9.
**Why:** The first deploy of the sync ended with `Okta answered HTTP 401`. The
credential that Okta security gave Matt is an API Services app that uses client
authentication `private_key_jwt`. It is a private key (a JWK with the fields `kty`,
`use` and `kid`), not an SSWS API token. The sync sent that value as an SSWS token,
and Okta refused it.
**Decision:** The sync accepts a second credential.
- `OKTA_SYNC_CLIENT_ID` and `OKTA_SYNC_PRIVATE_KEY` (a JWK as JSON, or as base64 of
that JSON). The sync signs a JWT (RS256 or ES256, from the key's `alg`; `kid` goes
in the header; `iss` and `sub` are the client ID; `aud` is `<org>/oauth2/v1/token`;
life 5 minutes; a new `jti` each time) and posts it to `<org>/oauth2/v1/token`
with `grant_type=client_credentials` and `scope=okta.users.read`.
- The access token is used as `Authorization: Bearer` on `/api/v1/users`. It is
requested again at the start of each run. It is not stored.
- `OKTA_API_TOKEN` still works. If both are set, the token wins. A deploy that sets
only a token is unchanged.
- A DPoP token (`token_type` not Bearer) is refused with a clear message.
**Rules from D18 that stay:** fail closed. Any problem with the key, the token
request or the user list raises an error, and the sync changes no account. The key,
the signed JWT and the access token are never logged and never put in an error
message. An error carries the HTTP status and the Okta error code only when that
code is a short lower-case word.
**Not decided here:** how often the key is replaced. A key is registered on the Okta
app and has no expiry that this code checks.

View File

@@ -370,3 +370,21 @@ and the third is logged:
1. The web server publishes no port (the host's reverse proxy reaches it). The override publishes 8080 on loopback.
2. An existing `proxy` network on a PC can have no gateway, and Docker then does not publish ports. The override uses its own bridge. The stock nginx `default.conf` also answers "localhost" first and the app server answers only wp.controls.dev, so the override removes the stock file and makes the app server the default.
3. The backup container cannot start on Windows: `scripts/entrypoint.sh` has CRLF line endings (BL-070). The override turns the backup service off.
## T13.9: D23 sign in as an OAuth service app (private_key_jwt)
**Item:** D23 (`docs/waves/decisions-2026-10-16.md`). Extends T13.2.
**Done when:**
- [x] with `OKTA_SYNC_CLIENT_ID` and `OKTA_SYNC_PRIVATE_KEY`, the sync gets an access token and lists users with `Bearer` (`tests/okta_sync_oauth_check.py`)
- [x] the assertion verifies against the public key: `iss`, `sub`, `aud`, `kid`, life, `jti`
- [x] RSA and EC keys; JSON and base64 forms
- [x] a failed token request, a missing token, a DPoP token, a public key, or an unreadable key raises, and the users endpoint is never called
- [x] `OKTA_API_TOKEN` still works and wins when both are set
- [x] the startup line names the credential and holds no secret; no error message holds key text
- [x] mutation checks: Bearer to SSWS, wrong `aud`, DPoP accepted, public-key check removed: each makes the test fail
- [x] `.env.example`, `docker-compose.yml`, `DEPLOYMENT.md` describe the variables and the Okta app setup
Result 2026-10-16: sandbox, fake Okta. Not yet run against the real tenant.
No new dependency: PyJWT signs with `cryptography`, which Authlib already installs.

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

View File

@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""Does the Okta sync sign in as an OAuth service app (private_key_jwt)? - D23 / T13.9.
Checks, with a fake Okta (httpx.MockTransport) and freshly made keys:
- the token request carries the right form fields and a JWT that VERIFIES against the
public key, with iss and sub = client ID, aud = the token endpoint, kid in the header,
a short lifetime, and a one-time jti
- the users request then uses the Bearer token, not SSWS
- every failure raises OktaSyncError and the users endpoint is never called
- the key is accepted as JSON and as base64, RSA and EC; a public key is refused
- an SSWS API token still works and wins when both are set
- the key, the assertion and the token never appear in an error message or the startup line
Self-contained: no network, no server, no browser. Exit 0 all passed, 1 a failure.
"""
import base64
import json
import os
import sys
from urllib.parse import parse_qs
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
os.environ["DATABASE_URL"] = "sqlite://"
for v in ("OKTA_API_TOKEN", "OKTA_SYNC_CLIENT_ID", "OKTA_SYNC_PRIVATE_KEY", "OKTA_SYNC_PROFILE_ATTRIBUTE"):
os.environ.pop(v, None)
os.environ["OKTA_ORG_URL"] = "https://example.okta.com"
import httpx # noqa: E402
import jwt # noqa: E402
from cryptography.hazmat.primitives.asymmetric import ec, rsa # noqa: E402
from server import okta_sync # noqa: E402
from server.okta_sync import OktaSyncError # noqa: E402
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
def make_rsa():
pk = rsa.generate_private_key(public_exponent=65537, key_size=2048)
jwk = json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(pk))
jwk.update({"kid": "rsa-kid-1", "use": "sig", "alg": "RS256"})
pub = {k: jwk[k] for k in ("kty", "n", "e")}
return jwk, jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(pub)), "RS256"
def make_ec():
pk = ec.generate_private_key(ec.SECP256R1())
jwk = json.loads(jwt.algorithms.ECAlgorithm.to_jwk(pk))
jwk.update({"kid": "ec-kid-1", "use": "sig", "alg": "ES256"})
pub = {k: jwk[k] for k in ("kty", "crv", "x", "y")}
return jwk, jwt.algorithms.ECAlgorithm.from_jwk(json.dumps(pub)), "ES256"
class FakeOkta:
def __init__(self, pub=None, alg="RS256", token_status=200, token_body=None, user_status=200):
self.pub, self.alg = pub, alg
self.token_status, self.token_body, self.user_status = token_status, token_body, user_status
self.token_calls, self.user_calls, self.seen_auth, self.form, self.verified = 0, 0, [], {}, None
def handler(self, req: httpx.Request):
if req.url.path == "/oauth2/v1/token":
self.token_calls += 1
self.form = {k: v[0] for k, v in parse_qs(req.content.decode()).items()}
if self.pub is not None and "client_assertion" in self.form:
try:
self.verified = jwt.decode(self.form["client_assertion"], self.pub, algorithms=[self.alg],
audience="https://example.okta.com/oauth2/v1/token")
except Exception as e: # noqa: BLE001
self.verified = e
body = self.token_body if self.token_body is not None else {
"token_type": "Bearer", "access_token": "ACCESS-TOKEN-VALUE", "expires_in": 3600}
return httpx.Response(self.token_status, json=body)
if req.url.path == "/api/v1/users":
self.user_calls += 1
self.seen_auth.append(req.headers.get("authorization", ""))
return httpx.Response(self.user_status, json=[
{"status": "ACTIVE", "profile": {"login": "alice"}}])
return httpx.Response(404)
def client(self):
return httpx.Client(transport=httpx.MockTransport(self.handler))
def setenv(jwk=None, as_b64=False, client_id="0oaCLIENT"):
os.environ["OKTA_SYNC_CLIENT_ID"] = client_id
if jwk is None:
os.environ.pop("OKTA_SYNC_PRIVATE_KEY", None)
else:
raw = json.dumps(jwk)
os.environ["OKTA_SYNC_PRIVATE_KEY"] = base64.b64encode(raw.encode()).decode() if as_b64 else raw
def fetch_err(fake):
try:
okta_sync.fetch_users(http=fake.client())
return None
except OktaSyncError as e:
return str(e)
# 1. Happy path, RSA, JSON form
rsa_jwk, rsa_pub, _ = make_rsa()
setenv(rsa_jwk)
chk("method is oauth", okta_sync.auth_method() == "oauth")
chk("is_configured with client id and key", okta_sync.is_configured())
f = FakeOkta(rsa_pub, "RS256")
users = okta_sync.fetch_users(http=f.client())
chk("returns the user", [u.identity for u in users] == ["alice"])
chk("token request fields", f.form.get("grant_type") == "client_credentials"
and f.form.get("scope") == "okta.users.read"
and f.form.get("client_assertion_type") == "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
v = f.verified
chk("assertion verifies against the public key", isinstance(v, dict), repr(v))
if isinstance(v, dict):
chk("iss and sub are the client id", v.get("iss") == "0oaCLIENT" and v.get("sub") == "0oaCLIENT")
chk("aud is the token endpoint", v.get("aud") == "https://example.okta.com/oauth2/v1/token")
chk("lifetime is at most 5 minutes", 0 < v["exp"] - v["iat"] <= 300)
chk("jti present", bool(v.get("jti")))
hdr = jwt.get_unverified_header(f.form["client_assertion"])
chk("kid and alg in the header", hdr.get("kid") == "rsa-kid-1" and hdr.get("alg") == "RS256")
chk("users call uses Bearer, not SSWS", f.seen_auth == ["Bearer ACCESS-TOKEN-VALUE"], str(f.seen_auth))
f2 = FakeOkta(rsa_pub)
okta_sync.fetch_users(http=f2.client())
chk("each assertion has a new jti", f.verified["jti"] != f2.verified["jti"])
# 2. base64 form and EC key
setenv(rsa_jwk, as_b64=True)
f = FakeOkta(rsa_pub)
chk("base64 form works", [u.identity for u in okta_sync.fetch_users(http=f.client())] == ["alice"])
ec_jwk, ec_pub, _ = make_ec()
setenv(ec_jwk)
f = FakeOkta(ec_pub, "ES256")
okta_sync.fetch_users(http=f.client())
chk("EC key works and verifies", isinstance(f.verified, dict), repr(f.verified))
# 3. Failures raise and never reach the users endpoint
setenv(rsa_jwk)
for label, fake in [
("token endpoint 401", FakeOkta(token_status=401, token_body={"error": "invalid_client"})),
("token endpoint 400 invalid_scope", FakeOkta(token_status=400, token_body={"error": "invalid_scope"})),
("token endpoint 500", FakeOkta(token_status=500, token_body={})),
("no access_token in body", FakeOkta(token_body={"token_type": "Bearer"})),
("DPoP token type", FakeOkta(token_body={"token_type": "DPoP", "access_token": "x"})),
("body is not an object", FakeOkta(token_body=[1, 2])),
]:
err = fetch_err(fake)
chk(f"{label}: raises, users never called", err is not None and fake.user_calls == 0, str(err))
e = fetch_err(FakeOkta(token_status=401, token_body={"error": "invalid_client"}))
chk("error carries the Okta error code and the status", "401" in e and "invalid_client" in e, e)
e = fetch_err(FakeOkta(token_status=400, token_body={"error": "<script>bad value with spaces</script>"}))
chk("an unsafe error value is dropped", "script" not in e and "400" in e, e)
# 4. Bad key material
pub_only = {k: rsa_jwk[k] for k in ("kty", "n", "e", "kid")}
for label, raw in [("public key only", json.dumps(pub_only)),
("not JSON, not base64", "{{{ not json"),
("base64 of something else", base64.b64encode(b"hello").decode()),
("wrong kty", json.dumps({"kty": "oct", "k": "AAAA"}))]:
os.environ["OKTA_SYNC_PRIVATE_KEY"] = raw
fake = FakeOkta()
err = fetch_err(fake)
chk(f"{label}: refused before any call", err is not None and fake.token_calls == 0 and fake.user_calls == 0, str(err))
if label == "public key only":
chk("public key: the message says it is a PUBLIC key", err is not None and "PUBLIC" in err, str(err))
chk(f"{label}: message holds no key text", err is not None and rsa_jwk["d"][:12] not in err and "hello" not in err)
setenv(rsa_jwk, client_id="")
os.environ["OKTA_SYNC_CLIENT_ID"] = ""
chk("no client id: not configured", okta_sync.auth_method() == "" and not okta_sync.is_configured())
os.environ["OKTA_SYNC_CLIENT_ID"] = "0oaCLIENT"
os.environ.pop("OKTA_SYNC_PRIVATE_KEY")
chk("no key: not configured", okta_sync.auth_method() == "")
# 5. An SSWS token still works and wins
setenv(rsa_jwk)
os.environ["OKTA_API_TOKEN"] = "ssws-token-value"
chk("method is token when both are set", okta_sync.auth_method() == "token")
f = FakeOkta()
okta_sync.fetch_users(http=f.client())
chk("SSWS used, no token request made", f.seen_auth == ["SSWS ssws-token-value"] and f.token_calls == 0, str(f.seen_auth))
os.environ.pop("OKTA_API_TOKEN")
# 6. Secrets stay out of the startup line
setenv(rsa_jwk)
line = okta_sync.describe()
chk("startup line names the method", "OAuth service app" in line, line)
chk("startup line holds no key part", rsa_jwk["d"][:12] not in line and rsa_jwk["n"][:12] not in line)
os.environ.pop("OKTA_SYNC_CLIENT_ID"); os.environ.pop("OKTA_SYNC_PRIVATE_KEY")
chk("startup line says DISABLED with no credential", "DISABLED" in okta_sync.describe())
print("\nDONE" if fails == 0 else f"\n{fails} FAILED")
sys.exit(1 if fails else 0)