Skip to content

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.

fix(security): attach HTTP auth middleware to served app under --sse-response (GHSA-8353-5qhw-8hfw) (#151)

Yves Junqueiraef2592d2d1b0
diff --git a/SECURITY.md b/SECURITY.md
index 3cb9af5..9bbc8b0 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -113,3 +113,38 @@ supplementary token only and cannot, on its own, admit a request.
`META_ACCESS_TOKEN` set, rotate the Meta access token
(`https://developers.facebook.com/tools/debug/accesstoken/`) and review Graph
API access logs for unexpected calls.
+
+### GHSA-8353-5qhw-8hfw — Unauthenticated HTTP MCP tool execution under `--sse-response` (auth middleware installed on the unserved app)
+
+- **Severity:** Critical (CVSS 3.1 9.1 — `AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N`)
+- **Affected versions:** `<= 1.0.118` when run with
+ `--transport streamable-http --sse-response` and a `META_ACCESS_TOKEN`
+ environment variable, on a network-reachable interface.
+- **Fixed in:** `1.0.119`
+- **Affected configurations:** Self-hosted deployments that pass
+ `--sse-response` and expose the streamable-HTTP port on a reachable network
+ interface with `META_ACCESS_TOKEN` set. The **default JSON response mode is
+ not affected**. The hosted MCP at `*.mcp.pipeboard.co` was not affected — it
+ runs in the default JSON mode, does not set `META_ACCESS_TOKEN`, and binds the
+ Python process to localhost behind an authenticating proxy.
+
+**What went wrong.** This is a third instance of the class fixed in
+GHSA-9gw6-46qc-99vr and GHSA-2v2f-mvfg-ph56. Those fixes hardened the HTTP auth
+middleware's request handling, but under `--sse-response` the middleware was not
+attached to the Starlette app that the streamable-http transport actually
+serves. As a result the served endpoint carried no auth gate in that
+configuration, so requests could reach tool handlers and fall back to the
+operator's `META_ACCESS_TOKEN`. The default JSON response mode was unaffected.
+
+**Fix.** The HTTP auth middleware is now attached to the served app
+unconditionally (independent of the response-format setting), with the SSE app
+covered as well for defense-in-depth. Regression tests assert the served app
+rejects unauthenticated requests in both JSON and `--sse-response` modes.
+
+**Action for operators.**
+- Upgrade to `1.0.119` or later.
+- If you exposed an earlier version with `--transport streamable-http
+ --sse-response` and `META_ACCESS_TOKEN` set on a reachable network, rotate the
+ Meta access token (`https://developers.facebook.com/tools/debug/accesstoken/`)
+ and review Graph API access logs for unexpected calls.
+- Credited to zx (Jace) — GitHub [@manus-use](https://github.com/manus-use).
diff --git a/STREAMABLE_HTTP_SETUP.md b/STREAMABLE_HTTP_SETUP.md
index a352128..157d71b 100644
--- a/STREAMABLE_HTTP_SETUP.md
+++ b/STREAMABLE_HTTP_SETUP.md
@@ -53,6 +53,7 @@ curl -X POST http://localhost:8080/mcp \
| `--transport` | Transport mode | `stdio` |
| `--host` | Server host address | `localhost` |
| `--port` | Server port | `8080` |
+| `--sse-response` | Return responses as SSE streams instead of JSON | `false` (JSON) |
### Examples
@@ -67,6 +68,42 @@ python -m meta_ads_mcp --transport streamable-http --host 0.0.0.0 --port 8080
python -m meta_ads_mcp --transport streamable-http --port 9000
```
+## Security Model (read before exposing the port)
+
+The HTTP transport uses a **per-request** authentication model that is
+deliberately different from stdio. Understanding it is the difference between a
+safe deployment and leaking your Meta account to the internet.
+
+- **stdio (local):** the server acts as whatever credential is configured in its
+ environment — `META_ACCESS_TOKEN`, `PIPEBOARD_API_TOKEN`, or a stored login.
+ Only the local process that launched it can talk to it, so this is expected
+ and safe. *If all you want is to use the MCP locally, prefer stdio.*
+
+- **streamable-http (network):** every request must carry **its own** token
+ header — `Authorization: Bearer <token>`, `X-META-ACCESS-TOKEN`, or the legacy
+ `X-PIPEBOARD-API-TOKEN`. Requests without one are rejected with
+ `401 Unauthorized`. The server-side `META_ACCESS_TOKEN` environment variable is
+ **intentionally not** used as an implicit fallback for HTTP requests — if it
+ were, any caller who can reach the port would act as you. This gating is
+ enforced by `AuthInjectionMiddleware`.
+
+**Operational rules:**
+
+1. **Do not expose the raw port to an untrusted network.** `--host 0.0.0.0`
+ binds to every interface. Put the server behind an authenticating reverse
+ proxy (or a private network / firewall), exactly as the hosted MCP at
+ `*.mcp.pipeboard.co` does (localhost-bound Python process behind a proxy).
+2. **Avoid setting `META_ACCESS_TOKEN` on a network-exposed HTTP server.** It is
+ an operator-wide, long-lived credential. Have callers pass their own tokens
+ in headers instead. If you must set it (e.g. single-tenant behind a trusted
+ proxy), ensure the port is unreachable by untrusted callers.
+3. **The auth gate applies in both response modes** — default JSON and
+ `--sse-response`. (Historically `--sse-response` had a bug where the gate was
+ not attached to the served app; see `SECURITY.md`, GHSA-8353-5qhw-8hfw. Fixed
+ in `1.0.119` — upgrade if you use `--sse-response`.)
+4. **If you ever exposed an unauthenticated server, rotate the Meta access
+ token** and review Graph API access logs.
+
## Authentication
### Primary Method: Bearer Token (Recommended)
@@ -295,10 +332,18 @@ client.callTool('get_ad_accounts', { limit: 5 })
### Security Considerations
+See **[Security Model](#security-model-read-before-exposing-the-port)** above for
+the per-request auth model and why it matters. In short:
+
1. **Use HTTPS**: In production, run behind a reverse proxy with SSL/TLS
-2. **Authentication**: Always use valid Bearer tokens.
-3. **Network Security**: Configure firewalls and access controls appropriately
-4. **Rate Limiting**: Consider implementing rate limiting for public APIs
+2. **Authentication**: Every request must carry its own token header; the server
+ returns `401` otherwise. Do not rely on a server-side `META_ACCESS_TOKEN` as
+ an implicit credential for HTTP callers — it is not used as a fallback.
+3. **Network Security**: Never expose the raw port to an untrusted network. Bind
+ to localhost behind an authenticating proxy, or restrict with firewalls.
+4. **Avoid `META_ACCESS_TOKEN` on network-exposed servers**: it is an
+ operator-wide credential; prefer per-request header tokens.
+5. **Rate Limiting**: Consider implementing rate limiting for public APIs
### Docker Deployment
@@ -325,7 +370,11 @@ export PIPEBOARD_API_TOKEN=your_pipeboard_token
export META_APP_ID=your_app_id
export META_APP_SECRET=your_app_secret
-# Optional (for direct Meta token)
+# Optional (for direct Meta token).
+# WARNING: on the HTTP transport this is NOT used as a fallback credential for
+# incoming requests — callers must pass their own token header (see "Security
+# Model"). Setting it on a network-exposed server is an operator-wide credential
+# risk; prefer stdio, or keep the port unreachable by untrusted callers.
export META_ACCESS_TOKEN=your_access_token
```
diff --git a/meta_ads_mcp/__init__.py b/meta_ads_mcp/__init__.py
index 77e625e..ec27f1e 100644
--- a/meta_ads_mcp/__init__.py
+++ b/meta_ads_mcp/__init__.py
@@ -6,7 +6,7 @@ This package provides a Meta Ads MCP integration
from meta_ads_mcp.core.server import main
-__version__ = "1.0.118"
+__version__ = "1.0.119"
__all__ = [
'get_ad_accounts',
diff --git a/meta_ads_mcp/core/http_auth_integration.py b/meta_ads_mcp/core/http_auth_integration.py
index d5684f7..e6c36e2 100644
--- a/meta_ads_mcp/core/http_auth_integration.py
+++ b/meta_ads_mcp/core/http_auth_integration.py
@@ -196,36 +196,48 @@ def setup_fastmcp_http_auth(mcp_server):
# 2. Patch the methods that provide the Starlette app instance
# This ensures our middleware is added to the app Uvicorn will actually serve.
+ # The streamable-http transport ALWAYS serves the app returned by
+ # streamable_http_app(): the SDK's run_streamable_http_async() calls
+ # self.streamable_http_app() regardless of the json_response setting.
+ # json_response is only forwarded to StreamableHTTPSessionManager as an
+ # SSE-vs-JSON wire-format switch — it does NOT change which Starlette app is
+ # served. Selecting the app to patch by json_response therefore attaches the
+ # auth middleware to the wrong (unserved) app under --sse-response, leaving
+ # the served app without an auth gate. See GHSA-8353-5qhw-8hfw.
+ #
+ # Patch streamable_http_app unconditionally (it is the served app), and
+ # also sse_app when present as defense-in-depth against future SDK routing
+ # changes. Both response formats are served by streamable_http_app today.
app_provider_methods = []
- if mcp_server.settings.json_response:
- if hasattr(mcp_server, "streamable_http_app") and callable(mcp_server.streamable_http_app):
- app_provider_methods.append("streamable_http_app")
- else:
- logger.warning("mcp_server.streamable_http_app not found or not callable, cannot patch for JSON responses.")
- else: # SSE
- if hasattr(mcp_server, "sse_app") and callable(mcp_server.sse_app):
- app_provider_methods.append("sse_app")
- else:
- logger.warning("mcp_server.sse_app not found or not callable, cannot patch for SSE responses.")
+ if hasattr(mcp_server, "streamable_http_app") and callable(mcp_server.streamable_http_app):
+ app_provider_methods.append("streamable_http_app")
+ else:
+ logger.error("mcp_server.streamable_http_app not found or not callable — the served streamable-http app cannot be protected with AuthInjectionMiddleware.")
+ if hasattr(mcp_server, "sse_app") and callable(mcp_server.sse_app):
+ app_provider_methods.append("sse_app")
if not app_provider_methods:
logger.error("No suitable app provider method (streamable_http_app or sse_app) found on mcp_server. Cannot add HTTP Auth middleware.")
# Fallback or error handling might be needed here if this is critical
-
+
for method_name in app_provider_methods:
original_app_provider_method = getattr(mcp_server, method_name)
-
- def new_patched_app_provider_method(*args, **kwargs):
+
+ # Bind method_name / original via default args so each patched closure
+ # captures its own iteration's values. Late-binding by reference would
+ # make every patched method call the LAST iteration's original — a real
+ # bug now that more than one method is patched.
+ def new_patched_app_provider_method(*args, _method_name=method_name, _original=original_app_provider_method, **kwargs):
# Call the original method to get/create the Starlette app
- app = original_app_provider_method(*args, **kwargs)
+ app = _original(*args, **kwargs)
if app:
- logger.debug(f"Original {method_name} returned app: {type(app)}. Adding AuthInjectionMiddleware.")
+ logger.debug(f"Original {_method_name} returned app: {type(app)}. Adding AuthInjectionMiddleware.")
# Now, add our middleware to this specific app instance
- setup_starlette_middleware(app)
+ setup_starlette_middleware(app)
else:
- logger.error(f"Original {method_name} returned None or a non-app object.")
+ logger.error(f"Original {_method_name} returned None or a non-app object.")
return app
-
+
setattr(mcp_server, method_name, new_patched_app_provider_method)
logger.debug(f"Patched mcp_server.{method_name} to inject AuthInjectionMiddleware.")
diff --git a/pyproject.toml b/pyproject.toml
index 2dbda47..a034611 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "meta-ads-mcp"
-version = "1.0.118"
+version = "1.0.119"
description = "Model Context Protocol (MCP) server for Meta Ads - Use Remote MCP at pipeboard.co for easiest setup"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/server.json b/server.json
index 4eea2d8..f345959 100644
--- a/server.json
+++ b/server.json
@@ -2,7 +2,7 @@
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
"name": "co.pipeboard/meta-ads-mcp",
"description": "Facebook / Meta Ads automation with AI: analyze performance, test creatives, optimize spend.",
- "version": "1.0.118",
+ "version": "1.0.119",
"remotes": [
{
"type": "streamable-http",
diff --git a/tests/test_http_auth_security.py b/tests/test_http_auth_security.py
index afd1fb0..cbbc93a 100644
--- a/tests/test_http_auth_security.py
+++ b/tests/test_http_auth_security.py
@@ -20,7 +20,10 @@ from starlette.responses import JSONResponse
from starlette.testclient import TestClient
from meta_ads_mcp.core.api import _redact_url, make_api_request
-from meta_ads_mcp.core.http_auth_integration import AuthInjectionMiddleware
+from meta_ads_mcp.core.http_auth_integration import (
+ AuthInjectionMiddleware,
+ setup_fastmcp_http_auth,
+)
def _build_app():
@@ -102,6 +105,83 @@ def test_middleware_accepts_supplementary_token_with_primary_credential():
assert resp.json() == {"reached_handler": True}
+# ---------------------------------------------------------------------------
+# GHSA-8353-5qhw-8hfw: AuthInjectionMiddleware must be attached to the app that
+# the streamable-http transport actually serves (streamable_http_app), in BOTH
+# JSON mode and --sse-response mode. The two tests above exercise the
+# middleware's dispatch() logic in isolation; these exercise the wiring in
+# setup_fastmcp_http_auth() that decides which served app the middleware lands
+# on. That wiring is where the vulnerability lived.
+# ---------------------------------------------------------------------------
+
+def _has_auth_middleware(app):
+ return any(m.cls == AuthInjectionMiddleware for m in app.user_middleware)
+
+
+def _fresh_fastmcp():
+ # Imported lazily so the rest of the suite runs even if the SDK is absent.
+ from mcp.server.fastmcp import FastMCP
+
+ return FastMCP("meta-ads-test")
+
+
[email protected]("sse_response", [False, True], ids=["json_mode", "sse_response_mode"])
+def test_served_app_has_auth_middleware(sse_response):
+ """The served streamable_http_app must carry AuthInjectionMiddleware in
+ both wire-format modes. Under --sse-response the previous code attached the
+ middleware to sse_app only (never served), leaving /mcp unauthenticated."""
+ server = _fresh_fastmcp()
+ # server.py:339 -> json_response = not args.sse_response
+ server.settings.json_response = not sse_response
+
+ setup_fastmcp_http_auth(server)
+
+ # This is the exact app run_streamable_http_async() serves.
+ served_app = server.streamable_http_app()
+ assert _has_auth_middleware(served_app), (
+ "streamable_http_app (the served app) is missing AuthInjectionMiddleware "
+ f"with sse_response={sse_response}; unauthenticated callers could reach tools"
+ )
+
+
+def test_served_app_rejects_unauthenticated_request_in_sse_mode():
+ """End-to-end: with --sse-response wiring, an unauthenticated POST /mcp to
+ the served app is rejected with 401 rather than reaching a tool handler."""
+ server = _fresh_fastmcp()
+ server.settings.json_response = False # simulate --sse-response
+
+ setup_fastmcp_http_auth(server)
+ served_app = server.streamable_http_app()
+
+ client = TestClient(served_app)
+ resp = client.post(
+ "/mcp",
+ json={"jsonrpc": "2.0", "method": "tools/call", "id": 1,
+ "params": {"name": "get_ad_accounts", "arguments": {}}},
+ headers={"Accept": "application/json, text/event-stream"},
+ )
+ assert resp.status_code == 401
+ assert resp.headers.get("WWW-Authenticate") == "Bearer"
+
+
+def test_patched_app_providers_do_not_cross_wire():
+ """Regression for the late-binding closure: patching both streamable_http_app
+ and sse_app must not make one provider call the other's original (which would
+ swap which app gets served / recurse). Each served app must be its own type
+ and carry the middleware."""
+ server = _fresh_fastmcp()
+ server.settings.json_response = True
+
+ setup_fastmcp_http_auth(server)
+
+ streamable = server.streamable_http_app()
+ sse = server.sse_app()
+ # Both are Starlette apps but distinct instances with the middleware present.
+ assert streamable is not sse
+ assert _has_auth_middleware(streamable)
+ assert _has_auth_middleware(sse)
+
+
def test_redact_url_strips_access_token():
url = (
"https://graph.facebook.com/v24.0/me/adaccounts"