Meta Ads (Facebook/Instagram) MCP server for Claude, ChatGPT, Perplexity & Cursor — the Meta node of Pipeboard’s 5-platform family (+ Google, TikTok, Snap, Reddit). Hosted remote MCP, badged Meta Business Partner, free plan — no self-hosting required.
Python advertisingai-agentschatgptclaudefacebook-adsinstagram-adsmcpmeta-adsmodel-context-protocolpipeboard
fix(security): HTML-escape OAuth callback error param (GHSA-6v2r-2m4r-768m) (#160)
Yves Junqueira271ea4cd5e0e
diff --git a/meta_ads_mcp/core/callback_server.py b/meta_ads_mcp/core/callback_server.pyindex bf5294d..5784557 100644--- a/meta_ads_mcp/core/callback_server.py+++ b/meta_ads_mcp/core/callback_server.py@@ -2,13 +2,14 @@import threadingimport socket-import asyncio-import json+import timeimport logging+import secretsimport webbrowserimport os+from html import escape as html_escapefrom http.server import HTTPServer, BaseHTTPRequestHandler-from urllib.parse import urlparse, parse_qs, quote+from urllib.parse import urlparse, parse_qsfrom typing import Dict, Any, Optionalfrom .utils import logger@@ -27,6 +28,9 @@ server_shutdown_timer = None# Timeout in seconds before shutting down the callback serverCALLBACK_SERVER_TIMEOUT = 180 # 3 minutes timeout+# Maximum number of characters of an OAuth error echoed back to the browser+MAX_ERROR_DISPLAY_LENGTH = 200+class CallbackHandler(BaseHTTPRequestHandler):def do_GET(self):@@ -36,8 +40,6 @@ class CallbackHandler(BaseHTTPRequestHandler):if self.path.startswith("/callback"):self._handle_oauth_callback()- elif self.path.startswith("/token"):- self._handle_token()else:# If no matching path, return a 404 errorself.send_response(404)@@ -47,6 +49,20 @@ class CallbackHandler(BaseHTTPRequestHandler):self.send_response(500)self.end_headers()+ def _send_html(self, html: str, csp: str = "default-src 'none'") -> None:+ """Send an HTML response with hardening headers."""+ body = html.encode("utf-8")+ self.send_response(200)+ self.send_header("Content-type", "text/html; charset=utf-8")+ self.send_header("Content-Length", str(len(body)))+ self.send_header("Content-Security-Policy", csp)+ self.send_header("X-Content-Type-Options", "nosniff")+ self.send_header("X-Frame-Options", "DENY")+ self.send_header("Referrer-Policy", "no-referrer")+ self.send_header("Cache-Control", "no-store")+ self.end_headers()+ self.wfile.write(body)+def _handle_oauth_callback(self):"""Handle OAuth callback after user authorization"""# Check if we're being redirected from Facebook with an authorization code@@ -58,19 +74,19 @@ class CallbackHandler(BaseHTTPRequestHandler):state = params.get('state', [None])[0]error = params.get('error', [None])[0]- # Send 200 OK response with a simple HTML page- self.send_response(200)- self.send_header("Content-type", "text/html")- self.end_headers()+ # Anything reaching this endpoint is attacker-controllable, so the error+ # is HTML-escaped (and truncated) before it is echoed back to the browser.+ csp = "default-src 'none'"if error:# User denied access or other error occurred+ safe_error = html_escape(error[:MAX_ERROR_DISPLAY_LENGTH])html = f"""<html><head><title>Authorization Failed</title></head><body><h1>Authorization Failed</h1>- <p>Error: {error}</p>+ <p>Error: {safe_error}</p><p>The authorization was cancelled or failed. You can close this window.</p></body></html>@@ -85,21 +101,25 @@ class CallbackHandler(BaseHTTPRequestHandler):token_container.update({"auth_code": code,"state": state,- "timestamp": asyncio.get_event_loop().time()+ "timestamp": time.monotonic()})- html = """+ # The success page needs its own inline script, so allow just that+ # one script via a per-response nonce rather than loosening the CSP.+ nonce = secrets.token_urlsafe(16)+ csp = f"default-src 'none'; script-src 'nonce-{nonce}'"+ html = f"""<html><head><title>Authorization Successful</title></head><body><h1>✅ Authorization Successful!</h1><p>You have successfully authorized the Meta Ads MCP application.</p><p>You can now close this window and return to your application.</p>- <script>+ <script nonce="{nonce}">// Try to close the window automatically after 2 seconds- setTimeout(function() {+ setTimeout(function() {{window.close();- }, 2000);+ }}, 2000);</script></body></html>@@ -118,27 +138,7 @@ class CallbackHandler(BaseHTTPRequestHandler):"""logger.warning("OAuth callback received without code or error")- self.wfile.write(html.encode())-- def _handle_token(self):- """Handle token endpoint for retrieving stored token data"""- # This endpoint allows other parts of the application to retrieve- # token information from the callback server-- self.send_response(200)- self.send_header("Content-type", "application/json")- self.end_headers()-- # Return current token container contents- response_data = {- "status": "success",- "data": token_container- }-- self.wfile.write(json.dumps(response_data).encode())-- # The actual token processing is now handled by the auth module- # that imports this module and accesses token_container+ self._send_html(html, csp)# Silence server logsdef log_message(self, format, *args):@@ -222,7 +222,6 @@ def start_callback_server() -> int:callback_server_thread.start()# Wait a moment for the server to start- import timetime.sleep(0.5)if not callback_server_running:diff --git a/tests/test_callback_server_xss.py b/tests/test_callback_server_xss.pynew file mode 100644index 0000000..b4c5848--- /dev/null+++ b/tests/test_callback_server_xss.py@@ -0,0 +1,92 @@+"""Regression tests for GHSA-6v2r-2m4r-768m.++The OAuth callback server reflected the `error` query parameter into an HTML+error page with no output encoding, so any page in the browser could navigate+to http://localhost:8080-8089/callback?error=<script>... during the 180s+authorization window and run script on the localhost origin.+"""++import threading+from http.server import HTTPServer+from urllib.parse import quote++import httpx+import pytest++from meta_ads_mcp.core.callback_server import (+ CallbackHandler,+ MAX_ERROR_DISPLAY_LENGTH,+)++XSS_PAYLOAD = "<script>alert(document.domain)</script>"+++def callback_url():+ """Run a real CallbackHandler on an ephemeral localhost port."""+ server = HTTPServer(("localhost", 0), CallbackHandler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ yield f"http://localhost:{server.server_port}"+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=5)+++def test_error_parameter_is_html_escaped(callback_url):+ response = httpx.get(f"{callback_url}/callback?error={quote(XSS_PAYLOAD)}")++ assert response.status_code == 200+ assert XSS_PAYLOAD not in response.text+ assert "<script>" not in response.text+ # The error is still shown to the user, just entity-encoded.+ assert "<script>" in response.text+ assert "Authorization Failed" in response.text+++def test_error_parameter_cannot_break_out_of_attributes(callback_url):+ payload = '" onload="alert(1)'+ response = httpx.get(f"{callback_url}/callback?error={quote(payload)}")++ assert 'onload="alert(1)' not in response.text+ assert """ in response.text+++def test_error_parameter_is_truncated(callback_url):+ payload = "A" * (MAX_ERROR_DISPLAY_LENGTH + 500)+ response = httpx.get(f"{callback_url}/callback?error={payload}")++ assert "A" * MAX_ERROR_DISPLAY_LENGTH in response.text+ assert "A" * (MAX_ERROR_DISPLAY_LENGTH + 1) not in response.text+++def test_error_page_sets_locked_down_security_headers(callback_url):+ response = httpx.get(f"{callback_url}/callback?error=access_denied")++ assert response.headers["content-security-policy"] == "default-src 'none'"+ assert response.headers["x-content-type-options"] == "nosniff"+ assert response.headers["referrer-policy"] == "no-referrer"+++def test_success_page_allows_only_its_own_nonced_script(callback_url):+ response = httpx.get(f"{callback_url}/callback?code=test-auth-code&state=xyz")++ csp = response.headers["content-security-policy"]+ assert csp.startswith("default-src 'none'; script-src 'nonce-")+ nonce = csp.split("'nonce-")[1].rstrip("'")+ # The inline script carries the nonce, so an injected script would not run.+ assert f'<script nonce="{nonce}">' in response.text+ assert response.headers["x-content-type-options"] == "nosniff"+++def test_token_endpoint_no_longer_exposes_the_auth_code(callback_url):+ """/token was unreferenced and handed the stored auth code to any+ same-origin page reachable via the XSS above."""+ httpx.get(f"{callback_url}/callback?code=test-auth-code&state=xyz")++ response = httpx.get(f"{callback_url}/token")++ assert response.status_code == 404+ assert "test-auth-code" not in response.text