""" 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, validate_authorization_request, verify_access_token, ) from starpunk.micropub import MicropubError, extract_bearer_token from starpunk.utils import absolute_url_for 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", "resource", ) 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": absolute_url_for("indieauth.authorize"), "token_endpoint": absolute_url_for("indieauth.token"), "revocation_endpoint": absolute_url_for("indieauth.revoke"), "revocation_endpoint_auth_methods_supported": ["none"], "scopes_supported": SUPPORTED_SCOPES, "response_types_supported": ["code"], # Public clients only (PKCE); clients identify with a client_id # URL whose JSON metadata lists redirect_uris, which is what MCP # calls a Client ID Metadata Document (v2.15.0, ADR-075) "token_endpoint_auth_methods_supported": ["none"], "client_id_metadata_document_supported": True, "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"], resource=auth_request["resource"], ) 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") # RFC 8707: a resource named here must be the one the code was issued for requested = (request.form.get("resource") or "").strip().rstrip("/") if requested and requested != (result["resource"] or ""): return _oauth_error("invalid_target", "resource does not match the authorization request") return _json(create_access_token(result["client_id"], result["scope"], resource=result["resource"])) @bp.route("/auth/token", methods=["GET"]) def token_verify(): """Legacy token verification for clients that still call it""" try: token = extract_bearer_token(request) except MicropubError as e: return _oauth_error("invalid_request", e.error_description) info = verify_access_token(token) if not info: return _oauth_error("unauthorized", "Invalid or expired access token", 401) return _json({k: info[k] for k in ("me", "client_id", "scope")}) @bp.route("/auth/revoke", methods=["POST"]) def revoke(): """RFC 7009 token revocation (always 200)""" revoke_access_token(request.form.get("token", "")) return _json({})