T13.9 follow-up 3: read pretty-printed and hand-copied JWKs, report the line and column of a syntax error (D23)

This commit is contained in:
2026-10-16 16:56:11 -07:00
parent c75450a000
commit 83e77ec622
3 changed files with 86 additions and 15 deletions

View File

@@ -166,6 +166,36 @@ def auth_method() -> str:
return ""
def _parse_json_forgiving(text: str):
"""Parse the key text as JSON, forgiving what copying does to it. Returns
(object, None) or (None, "problem at line L column C: what"). The problem names a
position and a rule, never any text of the key. Forgiven: line breaks and other control
characters inside a string (a long value wrapped over several lines), curly quote
marks, and a comma before a closing brace. Spaces inside the key's own number fields
are removed, because those fields are base64 text."""
attempts = [text]
cleaned = (text.replace("\u201c", '"').replace("\u201d", '"').replace("\u2018", "'").replace("\u2019", "'"))
cleaned = re.sub(r",\s*([}\]])", r"\1", cleaned)
if cleaned != text:
attempts.append(cleaned)
last = ""
for t in attempts:
try:
obj = json.loads(t, strict=False)
except json.JSONDecodeError as exc:
last = f"{exc.msg} at line {exc.lineno} column {exc.colno}"
continue
except ValueError:
last = "unreadable"
continue
if isinstance(obj, dict):
for k in ("n", "e", "d", "p", "q", "dp", "dq", "qi", "x", "y"):
if isinstance(obj.get(k), str):
obj[k] = re.sub(r"\s+", "", obj[k])
return obj, None
return None, last
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
@@ -207,21 +237,19 @@ def _load_jwk() -> dict:
"JSON with the fields kty, kid, n, e and d")
if text.startswith('"'):
text = "{" + text.rstrip(",") + "}" # the fields were copied without the outer braces
try:
jwk = json.loads(text)
except ValueError:
jwk, problem = _parse_json_forgiving(text)
if problem is not None and not text.startswith("{"):
# One more layer? A value that was encoded twice decodes to base64 text.
again = None
if not text.startswith("{"):
try:
again = base64.b64decode(re.sub(r"\s+", "", text) + "=" * (-len(re.sub(r"\s+", "", text)) % 4))
jwk = json.loads(again.decode("utf-8-sig").strip())
except Exception: # noqa: BLE001
again = None
if again is None:
shape = ("starts with a brace" if text.startswith("{") else
"starts with a letter or digit" if text[:1].isalnum() else "starts with a symbol")
raise _fail(f"OKTA_SYNC_PRIVATE_KEY is not JSON{via} ({len(text)} characters, {shape})") from None
try:
squeezed = re.sub(r"\s+", "", text)
again = base64.b64decode(squeezed + "=" * (-len(squeezed) % 4)).decode("utf-8-sig").strip()
jwk, problem = _parse_json_forgiving(again)
except Exception: # noqa: BLE001
pass
if problem is not None:
shape = ("starts with a brace" if text.startswith("{") else
"starts with a letter or digit" if text[:1].isalnum() else "starts with a symbol")
raise _fail(f"OKTA_SYNC_PRIVATE_KEY is not JSON{via} ({len(text)} characters, {shape}; {problem})")
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")