diff --git a/docs/waves/wave-13.md b/docs/waves/wave-13.md index ea528dc..c819a1e 100644 --- a/docs/waves/wave-13.md +++ b/docs/waves/wave-13.md @@ -388,3 +388,10 @@ and the third is logged: 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. + +T13.9 follow-up (2026-10-16): the first live deploy failed with "OKTA_SYNC_PRIVATE_KEY is not a +JWK as JSON or as base64 of JSON". The first loader used strict base64, which rejects any +space or line break, and it gave one message for every failure. The loader now forgives quote +marks, spaces, line breaks, missing padding, the URL-safe alphabet, a byte-order mark and a +one-key JWK Set, and each failure names its step (counts only, no key text). The new checks +in `tests/okta_sync_oauth_check.py` fail against the first loader and pass now. diff --git a/server/okta_sync.py b/server/okta_sync.py index 2cd7e67..9807ce6 100644 --- a/server/okta_sync.py +++ b/server/okta_sync.py @@ -169,18 +169,48 @@ def auth_method() -> str: 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.""" + in a Portainer environment field: it has no quote marks to be mangled. + + The reader forgives the usual copy and paste damage: quote marks around the whole + value, spaces and line breaks inside it, missing "=" padding, the URL-safe base64 + alphabet, a byte-order mark at the start of the file, and a JWK Set + ({"keys": [one key]}) in place of a single key. Raises OktaSyncError that says + which step failed. A message never holds any text of the key, only counts.""" raw = _key_raw() if not raw: raise _fail("OKTA_SYNC_PRIVATE_KEY is not set") + if len(raw) >= 2 and raw[0] == raw[-1] and raw[0] in "\"'": + raw = raw[1:-1].strip() + if raw.startswith("{"): + text = raw + else: + compact = re.sub(r"\s+", "", raw) + compact += "=" * (-len(compact) % 4) + decoded = None + for decode in (base64.b64decode, base64.urlsafe_b64decode): + try: + decoded = decode(compact) + break + except Exception: # noqa: BLE001 + continue + if decoded is None: + raise _fail(f"OKTA_SYNC_PRIVATE_KEY is not valid base64 ({len(compact)} characters after " + "removing spaces; it should be one long line of letters, digits, + / =)") + try: + text = decoded.decode("utf-8-sig") + except UnicodeDecodeError: + raise _fail("OKTA_SYNC_PRIVATE_KEY decodes from base64 but the result is not text") from None 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 + jwk = json.loads(text.lstrip("\ufeff")) + except ValueError: + raise _fail("OKTA_SYNC_PRIVATE_KEY is not JSON" + + (" after decoding base64" if not raw.startswith("{") else "")) from None + if isinstance(jwk, dict) and isinstance(jwk.get("keys"), list): + if len(jwk["keys"]) != 1: + raise _fail("OKTA_SYNC_PRIVATE_KEY is a key set with more than one key; paste one key") + jwk = jwk["keys"][0] 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") + raise _fail("OKTA_SYNC_PRIVATE_KEY is JSON but 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 diff --git a/tests/okta_sync_oauth_check.py b/tests/okta_sync_oauth_check.py index 4ad7cb7..f3292b0 100644 --- a/tests/okta_sync_oauth_check.py +++ b/tests/okta_sync_oauth_check.py @@ -178,6 +178,41 @@ os.environ["OKTA_SYNC_CLIENT_ID"] = "0oaCLIENT" os.environ.pop("OKTA_SYNC_PRIVATE_KEY") chk("no key: not configured", okta_sync.auth_method() == "") +# 4b. Copy and paste damage is forgiven, and the messages say which step failed +good = json.dumps(rsa_jwk) +b64 = base64.b64encode(good.encode()).decode() +variants = { + "double quotes around base64": '"' + b64 + '"', + "single quotes around base64": "'" + b64 + "'", + "line breaks every 76 characters": "\n".join(b64[i:i + 76] for i in range(0, len(b64), 76)), + "spaces and a trailing newline": " " + b64[:50] + " " + b64[50:] + " \r\n", + "padding removed": b64.rstrip("="), + "URL-safe alphabet": base64.urlsafe_b64encode(good.encode()).decode(), + "byte-order mark in the file": base64.b64encode(b"\xef\xbb\xbf" + good.encode()).decode(), + "JWK set with one key (JSON)": json.dumps({"keys": [rsa_jwk]}), + "JWK set with one key (base64)": base64.b64encode(json.dumps({"keys": [rsa_jwk]}).encode()).decode(), +} +for label, raw in variants.items(): + os.environ["OKTA_SYNC_PRIVATE_KEY"] = raw + try: + f = FakeOkta(rsa_pub) + okta_sync.fetch_users(http=f.client()) + chk(f"forgiven: {label}", isinstance(f.verified, dict) and f.user_calls == 1) + except OktaSyncError as e: + chk(f"forgiven: {label}", False, str(e)) +os.environ["OKTA_SYNC_PRIVATE_KEY"] = json.dumps({"keys": [rsa_jwk, rsa_jwk]}) +chk("a key set with two keys is refused", "more than one key" in (fetch_err(FakeOkta()) or "")) +for label, raw, want in [ + ("garbage characters", "!!!not*base64!!!", "not valid base64"), + ("base64 of non-JSON", base64.b64encode(b"hello world").decode(), "not JSON after decoding base64"), + ("base64 of bytes that are not text", base64.b64encode(b"\xff\xfe\xfd\xfc").decode(), "not text"), + ("broken JSON", "{ not json", "not JSON"), +]: + os.environ["OKTA_SYNC_PRIVATE_KEY"] = raw + err = fetch_err(FakeOkta()) or "" + chk(f"clear message: {label}", want in err, err) + chk(f"no key text in message: {label}", raw[:8] not in err.replace("OKTA_SYNC_PRIVATE_KEY", ""), err) + # 5. An SSWS token still works and wins setenv(rsa_jwk) os.environ["OKTA_API_TOKEN"] = "ssws-token-value"