Files
StarPunk/tests/test_indieauth.py
PhilandClaude Opus 5.5 84411a16d9 feat: MCP server for AI clients (v2.15.0, ADR-075)
Add an MCP server at SITE_URL/mcp so AI assistants (claude.ai connectors,
Claude Code) can search, read and write notes.

- starpunk/mcp_server: official MCP SDK 2.3, stateless Streamable HTTP with
  JSON responses, served by uvicorn as a sidecar from the same image.
  Ten tools; writes go through the Micropub handlers.
- IndieAuth: RFC 8707 resource indicators bound to codes and tokens
  (migration 022), client ID metadata document + public client metadata,
  draft in scopes_supported, default MCP scopes, consent screen note.
- BACKGROUND_WORKERS_ENABLED flag so the sidecar runs no workers.
- Docs: ADR-075, architecture/mcp.md and updates; CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 16:36:58 -07:00

435 lines
18 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, "resource": None,
}
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
MCP_RESOURCE = "https://blog.example.com/mcp"
class TestResourceIndicators:
"""RFC 8707 resource binding for MCP clients (v2.15.0, ADR-075)"""
def test_metadata_advertises_cimd_and_draft(self, client):
data = client.get("/.well-known/oauth-authorization-server").get_json()
assert data["client_id_metadata_document_supported"] is True
assert data["token_endpoint_auth_methods_supported"] == ["none"]
assert "draft" in data["scopes_supported"]
def test_mcp_resource_accepted(self, app):
with app.test_request_context():
result = validate_authorization_request(auth_params(resource=MCP_RESOURCE + "/"))
assert result["resource"] == MCP_RESOURCE
def test_no_resource_is_micropub(self, app):
with app.test_request_context():
assert validate_authorization_request(auth_params())["resource"] is None
def test_unknown_resource_rejected(self, app):
with app.test_request_context():
with pytest.raises(AuthorizationRequestError) as e:
validate_authorization_request(auth_params(resource="https://other.example/mcp"))
assert e.value.error == "invalid_target"
assert e.value.redirectable
def test_mcp_client_without_scope_is_offered_defaults(self, app):
with app.test_request_context():
result = validate_authorization_request(auth_params(scope="", resource=MCP_RESOURCE))
assert result["scopes"] == ["create", "update", "delete", "media", "draft"]
def test_consent_page_names_mcp(self, admin_client):
response = admin_client.get("/auth/authorize?" + urlencode(auth_params(resource=MCP_RESOURCE)))
assert response.status_code == 200
assert b"MCP" in response.data
assert b'name="resource" value="https://blog.example.com/mcp"' in response.data
def _token_form(self, query, **extra):
return {
"grant_type": "authorization_code",
"code": query["code"][0],
"client_id": CLIENT_ID,
"redirect_uri": REDIRECT_URI,
"code_verifier": "v" * 50,
**extra,
}
def test_resource_carried_to_token(self, app, admin_client, client):
query = approve(admin_client, granted=["create"], resource=MCP_RESOURCE)
body = client.post("/auth/token", data=self._token_form(query, resource=MCP_RESOURCE)).get_json()
with app.test_request_context():
info = verify_access_token(body["access_token"])
assert info["resource"] == MCP_RESOURCE
assert info["scope"] == "create"
def test_token_request_resource_must_match(self, admin_client, client):
query = approve(admin_client, granted=["create"], resource=MCP_RESOURCE)
response = client.post("/auth/token", data=self._token_form(query, resource="https://other.example/"))
assert response.status_code == 400
assert response.get_json()["error"] == "invalid_target"
def test_micropub_token_has_no_resource(self, app, admin_client, client):
query = approve(admin_client, granted=["create"])
body = client.post("/auth/token", data=self._token_form(query)).get_json()
with app.test_request_context():
assert verify_access_token(body["access_token"])["resource"] is None
def test_legacy_verification_shape_unchanged(self, app, client):
with app.test_request_context():
token = create_access_token(CLIENT_ID, "create", resource=MCP_RESOURCE)["access_token"]
data = client.get("/auth/token", headers={"Authorization": f"Bearer {token}"}).get_json()
assert data == {"me": "https://example.com", "client_id": CLIENT_ID, "scope": "create"}