T13.9 follow-up 2: name PEM keys, forgive missing braces and double encoding, give a length hint (D23)
This commit is contained in:
@@ -181,7 +181,7 @@ def _load_jwk() -> dict:
|
||||
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("{"):
|
||||
if raw.startswith(("{", '"', "-----BEGIN")):
|
||||
text = raw
|
||||
else:
|
||||
compact = re.sub(r"\s+", "", raw)
|
||||
@@ -200,11 +200,28 @@ def _load_jwk() -> dict:
|
||||
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
|
||||
text = text.lstrip("\ufeff").strip()
|
||||
via = "" if raw.startswith(("{", '"', "-----BEGIN")) else " after decoding base64"
|
||||
if text.startswith("-----BEGIN"):
|
||||
raise _fail("OKTA_SYNC_PRIVATE_KEY holds a PEM key (-----BEGIN ...). A JWK is needed: "
|
||||
"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.lstrip("\ufeff"))
|
||||
jwk = json.loads(text)
|
||||
except ValueError:
|
||||
raise _fail("OKTA_SYNC_PRIVATE_KEY is not JSON"
|
||||
+ (" after decoding base64" if not raw.startswith("{") else "")) from None
|
||||
# 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
|
||||
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")
|
||||
|
||||
Reference in New Issue
Block a user