252 lines
12 KiB
Python
252 lines
12 KiB
Python
#!/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() == "")
|
|
|
|
# 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))
|
|
# fields copied without the outer braces, and a value encoded twice, are forgiven
|
|
inner = json.dumps(rsa_jwk)[1:-1]
|
|
for label, raw in [("fields without braces (text)", inner),
|
|
("fields without braces (base64)", base64.b64encode(inner.encode()).decode()),
|
|
("encoded twice", base64.b64encode(b64.encode()).decode())]:
|
|
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))
|
|
except OktaSyncError as e:
|
|
chk(f"forgiven: {label}", False, str(e))
|
|
pem = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkq\n-----END PRIVATE KEY-----"
|
|
for label, raw in [("PEM text", pem), ("PEM in base64", base64.b64encode(pem.encode()).decode())]:
|
|
os.environ["OKTA_SYNC_PRIVATE_KEY"] = raw
|
|
err = fetch_err(FakeOkta()) or ""
|
|
chk(f"PEM is named: {label}", "PEM" in err and "MIIEvQ" not in err, err)
|
|
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 (11 characters, starts with a letter or digit)"),
|
|
("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"
|
|
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)
|