""" Tests for the built-in IndieAuth server (starpunk/indieauth.py, v2.0.0) """ import base64 import hashlib import secrets from unittest.mock import MagicMock, patch from urllib.parse import parse_qs, urlencode, urlparse import pytest from starpunk.auth import create_session from starpunk.indieauth import ( AuthorizationRequestError, InvalidGrantError, check_scope, create_access_token, create_authorization_code, fetch_client_redirect_uris, redeem_authorization_code, validate_authorization_request, verify_access_token, ) CLIENT_ID = "https://quill.example/" REDIRECT_URI = "https://quill.example/auth/callback" def challenge_for(verifier): digest = hashlib.sha256(verifier.encode()).digest() return base64.urlsafe_b64encode(digest).rstrip(b"=").decode() @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", } ) @pytest.fixture def client(app): return app.test_client() @pytest.fixture def admin_client(app): """Test client with a valid admin session cookie""" client = app.test_client() with app.test_request_context(): token = create_session("https://example.com") client.set_cookie("starpunk_session", token) return client def auth_params(verifier="v" * 50, **overrides): params = { "response_type": "code", "client_id": CLIENT_ID, "redirect_uri": REDIRECT_URI, "state": "client-state", "code_challenge": challenge_for(verifier), "code_challenge_method": "S256", "scope": "create media", } params.update(overrides) return params def approve(admin_client, granted=("create", "media"), **overrides): form = auth_params(**overrides) form["decision"] = "approve" form["scope_granted"] = list(granted) response = admin_client.post("/auth/authorize/approve", data=form) assert response.status_code == 302 return parse_qs(urlparse(response.headers["Location"]).query) class TestValidation: def test_valid_request(self, app): with app.test_request_context(): result = validate_authorization_request(auth_params()) assert result["scopes"] == ["create", "media"] @pytest.mark.parametrize( "overrides", [{"client_id": "not-a-url"}, {"redirect_uri": ""}, {"client_id": "ftp://x.example/"}], ) def test_untrusted_client_errors_are_not_redirected(self, app, overrides): with app.test_request_context(), pytest.raises(AuthorizationRequestError) as e: validate_authorization_request(auth_params(**overrides)) assert e.value.redirectable is False def test_missing_pkce_is_redirectable_error(self, app): with app.test_request_context(), pytest.raises(AuthorizationRequestError) as e: validate_authorization_request(auth_params(code_challenge="")) assert e.value.redirectable is True def test_plain_pkce_rejected(self, app): with app.test_request_context(), pytest.raises(AuthorizationRequestError): validate_authorization_request(auth_params(code_challenge_method="plain")) def test_cross_origin_redirect_needs_client_registration(self, app): params = auth_params(redirect_uri="https://evil.example/cb") with app.test_request_context(), patch( "starpunk.indieauth.fetch_client_redirect_uris", return_value=[] ), pytest.raises(AuthorizationRequestError) as e: validate_authorization_request(params) assert e.value.redirectable is False def test_cross_origin_redirect_allowed_when_published(self, app): params = auth_params(redirect_uri="app://callback") with app.test_request_context(), patch( "starpunk.indieauth.fetch_client_redirect_uris", return_value=["app://callback"] ): assert validate_authorization_request(params)["redirect_uri"] == "app://callback" class TestClientMetadata: def _response(self, content_type, body, links=None): response = MagicMock(status_code=200, text=body, url="https://quill.example/") response.headers = {"Content-Type": content_type} response.links = links or {} response.json.return_value = __import__("json").loads(body) if "json" in content_type else None return response def test_json_metadata(self, app): body = '{"client_id": "https://quill.example/", "redirect_uris": ["app://cb"]}' with app.test_request_context(), patch( "starpunk.webmention_ssrf.validate_url_for_fetch" ), patch("starpunk.indieauth.httpx.get", return_value=self._response("application/json", body)): assert fetch_client_redirect_uris(CLIENT_ID) == ["app://cb"] def test_html_link(self, app): body = '
' with app.test_request_context(), patch( "starpunk.webmention_ssrf.validate_url_for_fetch" ), patch("starpunk.indieauth.httpx.get", return_value=self._response("text/html", body)): assert fetch_client_redirect_uris(CLIENT_ID) == ["https://quill.example/cb"] class TestCodesAndTokens: def test_full_exchange(self, app): verifier = secrets.token_urlsafe(50) with app.test_request_context(): code = create_authorization_code(CLIENT_ID, REDIRECT_URI, "create", challenge_for(verifier)) result = redeem_authorization_code(code, CLIENT_ID, REDIRECT_URI, verifier) assert result == {"me": "https://example.com", "scope": "create", "client_id": CLIENT_ID} token = create_access_token(CLIENT_ID, "create") info = verify_access_token(token["access_token"]) assert info["me"] == "https://example.com" assert info["scope"] == "create" def test_code_single_use(self, app): verifier = "v" * 50 with app.test_request_context(): code = create_authorization_code(CLIENT_ID, REDIRECT_URI, "create", challenge_for(verifier)) redeem_authorization_code(code, CLIENT_ID, REDIRECT_URI, verifier) with pytest.raises(InvalidGrantError): redeem_authorization_code(code, CLIENT_ID, REDIRECT_URI, verifier) @pytest.mark.parametrize( "client_id,redirect_uri,verifier", [ ("https://other.example/", REDIRECT_URI, "v" * 50), (CLIENT_ID, "https://quill.example/other", "v" * 50), (CLIENT_ID, REDIRECT_URI, "wrong-verifier"), ], ) def test_code_mismatch_rejected(self, app, client_id, redirect_uri, verifier): with app.test_request_context(): code = create_authorization_code(CLIENT_ID, REDIRECT_URI, "create", challenge_for("v" * 50)) with pytest.raises(InvalidGrantError): redeem_authorization_code(code, client_id, redirect_uri, verifier) def test_token_stored_hashed(self, app): from starpunk.database import get_db with app.test_request_context(): token = create_access_token(CLIENT_ID, "create")["access_token"] rows = get_db(app).execute("SELECT token_hash FROM indieauth_tokens").fetchall() assert token not in [r["token_hash"] for r in rows] def test_unknown_token(self, app): with app.test_request_context(): assert verify_access_token("nope") is None assert verify_access_token("") is None def test_check_scope(self): assert check_scope("create", "create media") assert not check_scope("create", "media") assert not check_scope("create", "") class TestEndpoints: def test_metadata(self, client): data = client.get("/.well-known/oauth-authorization-server").get_json() assert data["issuer"] == "https://blog.example.com/" assert data["authorization_endpoint"] == "https://blog.example.com/auth/authorize" assert data["token_endpoint"] == "https://blog.example.com/auth/token" assert data["code_challenge_methods_supported"] == ["S256"] def test_discovery_links_on_homepage(self, client): html = client.get("/").data.decode() assert 'rel="indieauth-metadata"' in html assert 'rel="micropub"' in html def test_authorize_requires_login(self, client): response = client.get("/auth/authorize?" + urlencode(auth_params())) assert response.status_code == 302 assert response.headers["Location"].endswith("/auth/login") with client.session_transaction() as s: assert "/auth/authorize?" in s["next"] def test_authorize_shows_consent(self, admin_client): response = admin_client.get("/auth/authorize?" + urlencode(auth_params())) assert response.status_code == 200 assert b"quill.example" in response.data assert b'value="create"' in response.data def test_authorize_bad_client_shows_error_page(self, admin_client): response = admin_client.get("/auth/authorize?" + urlencode(auth_params(client_id="nope"))) assert response.status_code == 400 def test_approve_requires_login(self, client): response = client.post("/auth/authorize/approve", data={**auth_params(), "decision": "approve"}) assert response.headers["Location"].endswith("/auth/login") def test_deny(self, admin_client): form = {**auth_params(), "decision": "deny"} query = parse_qs(urlparse(admin_client.post("/auth/authorize/approve", data=form).headers["Location"]).query) assert query["error"] == ["access_denied"] assert query["state"] == ["client-state"] def test_full_micropub_flow(self, admin_client, client): verifier = "v" * 50 query = approve(admin_client, granted=["create"]) assert query["state"] == ["client-state"] assert query["iss"] == ["https://blog.example.com/"] response = client.post( "/auth/token", data={ "grant_type": "authorization_code", "code": query["code"][0], "client_id": CLIENT_ID, "redirect_uri": REDIRECT_URI, "code_verifier": verifier, }, ) assert response.status_code == 200 assert response.headers["Cache-Control"] == "no-store" body = response.get_json() assert body["me"] == "https://example.com" assert body["scope"] == "create" # media was unchecked token = body["access_token"] micropub = client.post( "/micropub", data={"h": "entry", "content": "Posted through the built-in IndieAuth server"}, headers={"Authorization": f"Bearer {token}"}, ) assert micropub.status_code == 201 verify = client.get("/auth/token", headers={"Authorization": f"Bearer {token}"}) assert verify.get_json()["client_id"] == CLIENT_ID client.post("/auth/revoke", data={"token": token}) again = client.post( "/micropub", data={"h": "entry", "content": "should fail"}, headers={"Authorization": f"Bearer {token}"}, ) assert again.status_code == 401 def test_profile_only_code_cannot_get_token(self, admin_client, client): query = approve(admin_client, granted=[], scope="") form = { "grant_type": "authorization_code", "code": query["code"][0], "client_id": CLIENT_ID, "redirect_uri": REDIRECT_URI, "code_verifier": "v" * 50, } assert client.post("/auth/token", data=form).get_json()["error"] == "invalid_grant" def test_profile_only_redemption(self, admin_client, client): query = approve(admin_client, granted=[], scope="") response = client.post( "/auth/authorize", data={ "grant_type": "authorization_code", "code": query["code"][0], "client_id": CLIENT_ID, "redirect_uri": REDIRECT_URI, "code_verifier": "v" * 50, }, ) assert response.get_json() == {"me": "https://example.com"} def test_unsupported_grant(self, client): assert client.post("/auth/token", data={"grant_type": "password"}).status_code == 400 def test_admin_can_list_and_revoke(self, app, admin_client): with app.test_request_context(): token = create_access_token(CLIENT_ID, "create")["access_token"] page = admin_client.get("/admin/tokens") assert page.status_code == 200 and b"quill.example" in page.data from starpunk.database import get_db with app.app_context(): token_id = get_db(app).execute("SELECT id FROM indieauth_tokens").fetchone()["id"] admin_client.post(f"/admin/tokens/{token_id}/revoke") with app.test_request_context(): assert verify_access_token(token) is None