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>
229 lines
7.4 KiB
Python
229 lines
7.4 KiB
Python
"""
|
|
IndieAuth server routes for StarPunk (v2.0.0, ADR-064)
|
|
|
|
Endpoints:
|
|
GET /.well-known/oauth-authorization-server Server metadata
|
|
GET /auth/authorize Consent screen (admin login required)
|
|
POST /auth/authorize Profile-only code redemption
|
|
POST /auth/authorize/approve Consent decision
|
|
POST /auth/token Code -> access token (and legacy revoke)
|
|
GET /auth/token Legacy token verification
|
|
POST /auth/revoke Token revocation (RFC 7009)
|
|
"""
|
|
|
|
from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl
|
|
|
|
from flask import (
|
|
Blueprint,
|
|
current_app,
|
|
jsonify,
|
|
redirect,
|
|
render_template,
|
|
request,
|
|
session,
|
|
url_for,
|
|
)
|
|
|
|
from starpunk.auth import verify_session
|
|
from starpunk.indieauth import (
|
|
SUPPORTED_SCOPES,
|
|
AuthorizationRequestError,
|
|
InvalidGrantError,
|
|
create_access_token,
|
|
create_authorization_code,
|
|
issuer,
|
|
redeem_authorization_code,
|
|
revoke_access_token,
|
|
site_url_for,
|
|
validate_authorization_request,
|
|
verify_access_token,
|
|
)
|
|
from starpunk.micropub import extract_bearer_token
|
|
|
|
bp = Blueprint("indieauth", __name__)
|
|
|
|
# Parameters carried from the consent screen back to the approve handler
|
|
_REQUEST_FIELDS = (
|
|
"response_type",
|
|
"client_id",
|
|
"redirect_uri",
|
|
"state",
|
|
"code_challenge",
|
|
"code_challenge_method",
|
|
"scope",
|
|
)
|
|
|
|
|
|
def _json(payload: dict, status: int = 200):
|
|
response = jsonify(payload)
|
|
response.status_code = status
|
|
response.headers["Cache-Control"] = "no-store"
|
|
return response
|
|
|
|
|
|
def _oauth_error(error: str, description: str, status: int = 400):
|
|
return _json({"error": error, "error_description": description}, status)
|
|
|
|
|
|
def _redirect_with(redirect_uri: str, params: dict):
|
|
"""Append params to redirect_uri, keeping any query it already has"""
|
|
parts = urlparse(redirect_uri)
|
|
query = parse_qsl(parts.query, keep_blank_values=True) + list(params.items())
|
|
return redirect(urlunparse(parts._replace(query=urlencode(query))))
|
|
|
|
|
|
def _admin_session():
|
|
return verify_session(request.cookies.get("starpunk_session"))
|
|
|
|
|
|
def _request_error_page(error: AuthorizationRequestError):
|
|
return (
|
|
render_template("admin/authorize.html", request_error=error.description),
|
|
400,
|
|
)
|
|
|
|
|
|
@bp.route("/.well-known/oauth-authorization-server")
|
|
def metadata():
|
|
"""IndieAuth server metadata"""
|
|
return _json(
|
|
{
|
|
"issuer": issuer(),
|
|
"authorization_endpoint": site_url_for("indieauth.authorize"),
|
|
"token_endpoint": site_url_for("indieauth.token"),
|
|
"revocation_endpoint": site_url_for("indieauth.revoke"),
|
|
"revocation_endpoint_auth_methods_supported": ["none"],
|
|
"scopes_supported": SUPPORTED_SCOPES,
|
|
"response_types_supported": ["code"],
|
|
"grant_types_supported": ["authorization_code"],
|
|
"code_challenge_methods_supported": ["S256"],
|
|
"authorization_response_iss_parameter_supported": True,
|
|
}
|
|
)
|
|
|
|
|
|
@bp.route("/auth/authorize", methods=["GET"])
|
|
def authorize():
|
|
"""Show the consent screen to the logged-in admin"""
|
|
try:
|
|
auth_request = validate_authorization_request(request.args.to_dict())
|
|
except AuthorizationRequestError as e:
|
|
if not e.redirectable:
|
|
return _request_error_page(e)
|
|
return _redirect_with(
|
|
request.args["redirect_uri"],
|
|
{
|
|
"error": e.error,
|
|
"error_description": e.description,
|
|
"state": request.args.get("state", ""),
|
|
"iss": issuer(),
|
|
},
|
|
)
|
|
|
|
if not _admin_session():
|
|
# Come back here after logging in with OIDC
|
|
session["next"] = request.url
|
|
return redirect(url_for("auth.login_form"))
|
|
|
|
return render_template(
|
|
"admin/authorize.html",
|
|
auth_request=auth_request,
|
|
fields={k: request.args.get(k, "") for k in _REQUEST_FIELDS},
|
|
me=current_app.config["ADMIN_ME"],
|
|
)
|
|
|
|
|
|
@bp.route("/auth/authorize/approve", methods=["POST"])
|
|
def approve():
|
|
"""Record the admin's consent decision and redirect to the client"""
|
|
if not _admin_session():
|
|
return redirect(url_for("auth.login_form"))
|
|
|
|
params = {k: request.form.get(k, "") for k in _REQUEST_FIELDS}
|
|
try:
|
|
auth_request = validate_authorization_request(params)
|
|
except AuthorizationRequestError as e:
|
|
return _request_error_page(e)
|
|
|
|
if request.form.get("decision") != "approve":
|
|
return _redirect_with(
|
|
auth_request["redirect_uri"],
|
|
{"error": "access_denied", "state": auth_request["state"], "iss": issuer()},
|
|
)
|
|
|
|
# Only scopes that were both requested and left checked
|
|
granted = [s for s in auth_request["scopes"] if s in request.form.getlist("scope_granted")]
|
|
code = create_authorization_code(
|
|
auth_request["client_id"],
|
|
auth_request["redirect_uri"],
|
|
" ".join(granted),
|
|
auth_request["code_challenge"],
|
|
)
|
|
current_app.logger.info(
|
|
f"IndieAuth: approved {auth_request['client_id']} (scope: {' '.join(granted) or 'none'})"
|
|
)
|
|
return _redirect_with(
|
|
auth_request["redirect_uri"],
|
|
{"code": code, "state": auth_request["state"], "iss": issuer()},
|
|
)
|
|
|
|
|
|
def _redeem_from_form():
|
|
return redeem_authorization_code(
|
|
request.form.get("code", ""),
|
|
request.form.get("client_id", ""),
|
|
request.form.get("redirect_uri", ""),
|
|
request.form.get("code_verifier", ""),
|
|
)
|
|
|
|
|
|
@bp.route("/auth/authorize", methods=["POST"])
|
|
def authorize_redeem():
|
|
"""Profile-only flow: redeem a code for the user's identity"""
|
|
if request.form.get("grant_type", "authorization_code") != "authorization_code":
|
|
return _oauth_error("unsupported_grant_type", "Only authorization_code is supported")
|
|
try:
|
|
result = _redeem_from_form()
|
|
except InvalidGrantError as e:
|
|
return _oauth_error("invalid_grant", str(e))
|
|
return _json({"me": result["me"]})
|
|
|
|
|
|
@bp.route("/auth/token", methods=["POST"])
|
|
def token():
|
|
"""Exchange an authorization code for an access token"""
|
|
if request.form.get("action") == "revoke":
|
|
# Legacy IndieAuth revocation
|
|
revoke_access_token(request.form.get("token", ""))
|
|
return _json({})
|
|
|
|
if request.form.get("grant_type") != "authorization_code":
|
|
return _oauth_error("unsupported_grant_type", "Only authorization_code is supported")
|
|
|
|
try:
|
|
result = _redeem_from_form()
|
|
except InvalidGrantError as e:
|
|
return _oauth_error("invalid_grant", str(e))
|
|
|
|
if not result["scope"]:
|
|
# Spec: a code issued without scope cannot be used for an access token
|
|
return _oauth_error("invalid_grant", "No scope was granted; use the authorization endpoint")
|
|
|
|
return _json(create_access_token(result["client_id"], result["scope"]))
|
|
|
|
|
|
@bp.route("/auth/token", methods=["GET"])
|
|
def token_verify():
|
|
"""Legacy token verification for clients that still call it"""
|
|
info = verify_access_token(extract_bearer_token(request))
|
|
if not info:
|
|
return _oauth_error("unauthorized", "Invalid or expired access token", 401)
|
|
return _json(info)
|
|
|
|
|
|
@bp.route("/auth/revoke", methods=["POST"])
|
|
def revoke():
|
|
"""RFC 7009 token revocation (always 200)"""
|
|
revoke_access_token(request.form.get("token", ""))
|
|
return _json({})
|