Admin login now uses OpenID Connect (PKCE, nonce, ID token verified against the provider JWKS) and only OIDC_ADMIN_SUB may log in. Micropub tokens are issued and verified by StarPunk itself, with a consent screen behind the OIDC session and a Connected Apps page to revoke them, so an external IndieAuth server (Gondulf) is no longer needed. Existing notes, media, tags, webmentions, author profile and sessions are unchanged. Migration 011 adds new tables only. BREAKING CHANGE: production requires OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET and OIDC_ADMIN_SUB. The ADMIN_ME page must point Micropub apps at StarPunk's IndieAuth endpoints. See ADR-064. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
244 lines
9.4 KiB
Python
244 lines
9.4 KiB
Python
"""
|
|
Tests for OIDC admin login (starpunk/auth.py, v2.0.0)
|
|
"""
|
|
|
|
import time
|
|
from unittest.mock import MagicMock, patch
|
|
from urllib.parse import parse_qs, urlparse
|
|
|
|
import jwt
|
|
import pytest
|
|
from cryptography.hazmat.primitives.asymmetric import rsa
|
|
|
|
from starpunk import auth
|
|
from starpunk.auth import (
|
|
InvalidStateError,
|
|
OIDCError,
|
|
UnauthorizedError,
|
|
_pkce_challenge,
|
|
handle_callback,
|
|
initiate_login,
|
|
verify_session,
|
|
)
|
|
|
|
ISSUER = "https://id.example.com"
|
|
CLIENT_ID = "starpunk-client"
|
|
ADMIN_SUB = "admin-sub-123"
|
|
|
|
METADATA = {
|
|
"issuer": ISSUER,
|
|
"authorization_endpoint": f"{ISSUER}/authorize",
|
|
"token_endpoint": f"{ISSUER}/api/oidc/token",
|
|
"jwks_uri": f"{ISSUER}/.well-known/jwks.json",
|
|
"id_token_signing_alg_values_supported": ["RS256"],
|
|
}
|
|
|
|
PRIVATE_KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
OTHER_KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
|
|
|
|
@pytest.fixture
|
|
def app(tmp_path):
|
|
from starpunk import create_app
|
|
|
|
data = tmp_path / "data"
|
|
return create_app(
|
|
{
|
|
"TESTING": True,
|
|
"SITE_URL": "https://blog.example.com",
|
|
"ADMIN_ME": "https://example.com",
|
|
"SESSION_SECRET": "test-secret",
|
|
"DATA_PATH": data,
|
|
"NOTES_PATH": data / "notes",
|
|
"DATABASE_PATH": data / "starpunk.db",
|
|
"OIDC_ISSUER": ISSUER,
|
|
"OIDC_CLIENT_ID": CLIENT_ID,
|
|
"OIDC_CLIENT_SECRET": "secret",
|
|
"OIDC_ADMIN_SUB": ADMIN_SUB,
|
|
}
|
|
)
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def provider():
|
|
"""Fake identity provider: discovery, JWKS key and token endpoint"""
|
|
auth._METADATA_CACHE.clear()
|
|
metadata_response = MagicMock(status_code=200)
|
|
metadata_response.json.return_value = METADATA
|
|
metadata_response.raise_for_status.return_value = None
|
|
with patch("starpunk.auth.httpx.get", return_value=metadata_response) as get, patch(
|
|
"starpunk.auth._get_signing_key", return_value=PRIVATE_KEY.public_key()
|
|
), patch("starpunk.auth.httpx.post") as post, patch(
|
|
"starpunk.author_discovery.get_author_profile"
|
|
):
|
|
yield {"get": get, "post": post}
|
|
|
|
|
|
def make_id_token(nonce, sub=ADMIN_SUB, aud=CLIENT_ID, iss=ISSUER, key=PRIVATE_KEY, exp_in=300):
|
|
now = int(time.time())
|
|
claims = {"iss": iss, "aud": aud, "sub": sub, "iat": now, "exp": now + exp_in, "nonce": nonce}
|
|
return jwt.encode(claims, key, algorithm="RS256")
|
|
|
|
|
|
def start_login(app, next_url=None):
|
|
"""Run initiate_login and return (state, nonce) from the stored row"""
|
|
with app.test_request_context():
|
|
url = initiate_login(next_url)
|
|
query = parse_qs(urlparse(url).query)
|
|
return query["state"][0], query["nonce"][0], query
|
|
|
|
|
|
def token_response(provider, id_token, status=200):
|
|
response = MagicMock(status_code=status, text="")
|
|
response.json.return_value = {"id_token": id_token, "access_token": "x"}
|
|
provider["post"].return_value = response
|
|
|
|
|
|
class TestInitiateLogin:
|
|
def test_redirects_to_provider_with_pkce(self, app):
|
|
with app.test_request_context():
|
|
url = initiate_login()
|
|
parsed = urlparse(url)
|
|
query = parse_qs(parsed.query)
|
|
assert f"{parsed.scheme}://{parsed.netloc}{parsed.path}" == METADATA["authorization_endpoint"]
|
|
assert query["client_id"] == [CLIENT_ID]
|
|
assert query["redirect_uri"] == ["https://blog.example.com/auth/callback"]
|
|
assert query["response_type"] == ["code"]
|
|
assert query["scope"] == ["openid"]
|
|
assert query["code_challenge_method"] == ["S256"]
|
|
assert query["state"][0] and query["nonce"][0]
|
|
|
|
def test_stores_verifier_matching_challenge(self, app):
|
|
state, _, query = start_login(app)
|
|
from starpunk.database import get_db
|
|
|
|
with app.app_context():
|
|
row = get_db(app).execute(
|
|
"SELECT code_verifier FROM oidc_login_state WHERE state = ?", (state,)
|
|
).fetchone()
|
|
assert _pkce_challenge(row["code_verifier"]) == query["code_challenge"][0]
|
|
|
|
def test_rejects_offsite_next_url(self, app):
|
|
state, _, _ = start_login(app, "https://evil.example/steal")
|
|
from starpunk.database import get_db
|
|
|
|
with app.app_context():
|
|
row = get_db(app).execute(
|
|
"SELECT next_url FROM oidc_login_state WHERE state = ?", (state,)
|
|
).fetchone()
|
|
assert row["next_url"] is None
|
|
|
|
def test_issuer_mismatch_fails(self, app, provider):
|
|
provider["get"].return_value.json.return_value = {**METADATA, "issuer": "https://other"}
|
|
with app.test_request_context(), pytest.raises(OIDCError):
|
|
initiate_login()
|
|
|
|
|
|
class TestHandleCallback:
|
|
def test_success_creates_admin_session(self, app, provider):
|
|
state, nonce, _ = start_login(app, "/admin/new")
|
|
token_response(provider, make_id_token(nonce))
|
|
|
|
with app.test_request_context():
|
|
session_token, next_url = handle_callback("code", state, ISSUER)
|
|
assert verify_session(session_token)["me"] == "https://example.com"
|
|
assert next_url == "/admin/new"
|
|
|
|
sent = provider["post"].call_args
|
|
assert sent.kwargs["data"]["grant_type"] == "authorization_code"
|
|
assert sent.kwargs["data"]["code_verifier"]
|
|
assert sent.kwargs["auth"] == (CLIENT_ID, "secret")
|
|
|
|
def test_state_is_single_use(self, app, provider):
|
|
state, nonce, _ = start_login(app)
|
|
token_response(provider, make_id_token(nonce))
|
|
with app.test_request_context():
|
|
handle_callback("code", state)
|
|
with pytest.raises(InvalidStateError):
|
|
handle_callback("code", state)
|
|
|
|
def test_unknown_state(self, app):
|
|
with app.test_request_context(), pytest.raises(InvalidStateError):
|
|
handle_callback("code", "nope")
|
|
|
|
def test_wrong_subject_is_unauthorized(self, app, provider):
|
|
state, nonce, _ = start_login(app)
|
|
token_response(provider, make_id_token(nonce, sub="someone-else"))
|
|
with app.test_request_context(), pytest.raises(UnauthorizedError):
|
|
handle_callback("code", state)
|
|
|
|
@pytest.mark.parametrize(
|
|
"kwargs",
|
|
[
|
|
{"aud": "another-client"},
|
|
{"iss": "https://evil.example"},
|
|
{"key": OTHER_KEY},
|
|
{"exp_in": -3600},
|
|
],
|
|
)
|
|
def test_invalid_id_token_rejected(self, app, provider, kwargs):
|
|
state, nonce, _ = start_login(app)
|
|
token_response(provider, make_id_token(nonce, **kwargs))
|
|
with app.test_request_context(), pytest.raises(OIDCError):
|
|
handle_callback("code", state)
|
|
|
|
def test_nonce_mismatch_rejected(self, app, provider):
|
|
state, _, _ = start_login(app)
|
|
token_response(provider, make_id_token("wrong-nonce"))
|
|
with app.test_request_context(), pytest.raises(OIDCError):
|
|
handle_callback("code", state)
|
|
|
|
def test_callback_issuer_mismatch_rejected(self, app, provider):
|
|
state, nonce, _ = start_login(app)
|
|
token_response(provider, make_id_token(nonce))
|
|
with app.test_request_context(), pytest.raises(OIDCError):
|
|
handle_callback("code", state, "https://evil.example")
|
|
|
|
def test_token_endpoint_error(self, app, provider):
|
|
state, _, _ = start_login(app)
|
|
token_response(provider, None, status=400)
|
|
with app.test_request_context(), pytest.raises(OIDCError):
|
|
handle_callback("code", state)
|
|
|
|
|
|
class TestRoutes:
|
|
def test_login_page_shows_sso_button(self, app):
|
|
response = app.test_client().get("/auth/login")
|
|
assert response.status_code == 200
|
|
assert b"Sign in with" in response.data
|
|
assert b'name="me"' not in response.data
|
|
|
|
def test_login_post_redirects_to_provider(self, app):
|
|
response = app.test_client().post("/auth/login")
|
|
assert response.status_code == 302
|
|
assert response.headers["Location"].startswith(METADATA["authorization_endpoint"])
|
|
|
|
def test_callback_sets_cookie_and_returns_to_next(self, app, provider):
|
|
client = app.test_client()
|
|
with client.session_transaction() as s:
|
|
s["next"] = "https://blog.example.com/admin/tokens"
|
|
login = client.post("/auth/login")
|
|
query = parse_qs(urlparse(login.headers["Location"]).query)
|
|
token_response(provider, make_id_token(query["nonce"][0]))
|
|
|
|
response = client.get(f"/auth/callback?code=abc&state={query['state'][0]}&iss={ISSUER}")
|
|
assert response.status_code == 302
|
|
assert response.headers["Location"] == "https://blog.example.com/admin/tokens"
|
|
cookie = response.headers["Set-Cookie"]
|
|
assert "starpunk_session=" in cookie and "HttpOnly" in cookie and "Secure" in cookie
|
|
|
|
def test_callback_wrong_user_gets_no_cookie(self, app, provider):
|
|
client = app.test_client()
|
|
login = client.post("/auth/login")
|
|
query = parse_qs(urlparse(login.headers["Location"]).query)
|
|
token_response(provider, make_id_token(query["nonce"][0], sub="intruder"))
|
|
|
|
response = client.get(f"/auth/callback?code=abc&state={query['state'][0]}")
|
|
assert response.headers["Location"].endswith("/auth/login")
|
|
assert "starpunk_session" not in response.headers.get("Set-Cookie", "")
|
|
|
|
def test_callback_provider_error(self, app):
|
|
response = app.test_client().get("/auth/callback?error=access_denied")
|
|
assert response.status_code == 302
|
|
assert response.headers["Location"].endswith("/auth/login")
|