- All dependencies to current releases (97 known vulnerabilities -> 0), Python 3.14, uv pinned, requirements-test.txt, lxml/dateutil pinned - CSRF tokens on admin forms, logout and IndieAuth consent - IndieAuth client and crosspost link-card fetches via safe_get - FLASK_DEBUG/FLASK_ENV default off/production; image sets them - Foreign keys enforced on pooled connections; migration 018 removes orphans - Rate limits shared across processes (rate_limits, migration 019) - datetime.utcnow() and sqlite3 default adapters replaced - compose.yaml fixed; duplicate dev_auth.py and test.ini removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
357 lines
14 KiB
Python
357 lines
14 KiB
Python
"""
|
|
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:
|
|
"""Client metadata is fetched through the SSRF-safe fetcher (v2.11.0)"""
|
|
|
|
@staticmethod
|
|
def _serve(monkeypatch, handler, private=()):
|
|
import httpx
|
|
|
|
def resolve(host, *args, **kwargs):
|
|
return [(2, 1, 6, "", ("10.0.0.5" if host in private else "93.184.216.34", 0))]
|
|
|
|
monkeypatch.setattr("starpunk.webmention_ssrf.TRANSPORT", httpx.MockTransport(handler))
|
|
monkeypatch.setattr("starpunk.webmention_ssrf.socket.getaddrinfo", resolve)
|
|
|
|
def test_json_metadata(self, app, monkeypatch):
|
|
import httpx
|
|
body = '{"client_id": "https://quill.example/", "redirect_uris": ["app://cb"]}'
|
|
self._serve(monkeypatch, lambda r: httpx.Response(
|
|
200, headers={"Content-Type": "application/json"}, text=body))
|
|
with app.test_request_context():
|
|
assert fetch_client_redirect_uris(CLIENT_ID) == ["app://cb"]
|
|
|
|
def test_html_link(self, app, monkeypatch):
|
|
import httpx
|
|
body = '<html><head><link rel="redirect_uri" href="/cb"></head></html>'
|
|
self._serve(monkeypatch, lambda r: httpx.Response(
|
|
200, headers={"Content-Type": "text/html"}, text=body))
|
|
with app.test_request_context():
|
|
assert fetch_client_redirect_uris(CLIENT_ID) == ["https://quill.example/cb"]
|
|
|
|
def test_link_header(self, app, monkeypatch):
|
|
import httpx
|
|
self._serve(monkeypatch, lambda r: httpx.Response(
|
|
200, headers={"Content-Type": "text/html", "Link": '</cb2>; rel="redirect_uri"'}, text="<p>hi</p>"))
|
|
with app.test_request_context():
|
|
assert fetch_client_redirect_uris(CLIENT_ID) == ["https://quill.example/cb2"]
|
|
|
|
def test_redirect_to_private_address_refused(self, app, monkeypatch):
|
|
import httpx
|
|
fetched = []
|
|
|
|
def handler(request):
|
|
fetched.append(request.headers["host"])
|
|
return httpx.Response(302, headers={"Location": "http://internal.example/"})
|
|
|
|
self._serve(monkeypatch, handler, private={"internal.example"})
|
|
with app.test_request_context():
|
|
assert fetch_client_redirect_uris(CLIENT_ID) == []
|
|
assert "internal.example" not in fetched
|
|
|
|
|
|
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
|