Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.
TypeScript analyticsanalytics-dashboardclickhouseelixirgoogle-analyticsmarketingopen-source-analyticsphoenixplausible-analyticspostgresqlprivacyprivacy-friendlyself-hostedsimple-analyticsstatisticstailwindcssweb-analyticswebsite-analyticswebsite-statswebsite-tracking
Implement MCP list_sites tool (#6753)
Artur Pata2328f880ef8a
diff --git a/lib/plausible/oauth.ex b/lib/plausible/oauth.exindex 24b724df0d..6fb99a054c 100644--- a/lib/plausible/oauth.ex+++ b/lib/plausible/oauth.ex@@ -178,37 +178,38 @@ defmodule Plausible.OAuth doend@doc """- Looks up the grant a raw access token belongs to, preloading the bound user- and team.+ Looks up the grant a raw access token belongs to, preloading the bound user, team,+ and their current role in the team. Returns the grant and role.- `resource` is the protected resource the token is presented to. A token issued+ The argument `resource` is the protected resource the token is supposed to be for. A token issuedfor a different resource is not found.- Expired, revoked and wrong-resource tokens all return `{:error, :invalid_token}`+ Expired, revoked, wrong resource, invalid role tokens all return+ `{:error, :invalid_token}`([see error codes](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1#name-error-codes))."""@spec find_access_token(String.t(), ProtectedResources.t()) ::- {:ok, Grant.t()} | {:error, :invalid_token}+ {:ok, Grant.t(), Membership.role()} | {:error, :invalid_token}def find_access_token(raw_access, resource) when is_binary(raw_access) doresource_url = ProtectedResources.get_resource_url(resource)query =from(g in Grant,+ inner_join: u in assoc(g, :user),+ inner_join: t in assoc(g, :team),+ inner_join: tm in Membership,+ on: tm.team_id == g.team_id and tm.user_id == g.user_id,where:g.access_token_hash == ^Token.hash(raw_access) andg.resource == ^resource_url andg.access_token_expires_at > ^now() andis_nil(g.revoked_at),- preload: [:user, :team]+ preload: [user: u, team: t],+ select: {g, tm.role})- with %Grant{team_id: team_id, user_id: user_id} = grant <- Repo.one(query),- :ok <-- [team_id: team_id, user_id: user_id]- |> Memberships.team_role()- |> validate_role() do- {:ok, grant}- else+ case Repo.one(query) do+ {%Grant{} = grant, role} when role in @roles_with_oauth -> {:ok, grant, role}_ -> {:error, :invalid_token}endenddiff --git a/lib/plausible/oauth/protected_resources.ex b/lib/plausible/oauth/protected_resources.exindex 9752f84da8..bc554de41c 100644--- a/lib/plausible/oauth/protected_resources.ex+++ b/lib/plausible/oauth/protected_resources.ex@@ -68,4 +68,18 @@ defmodule Plausible.OAuth.ProtectedResources doenddef normalize_granted_scopes(_scopes, _resource), do: {:error, :invalid_scope}++ @doc """+ Returns `scope` if `resource` supports it, raising otherwise.+ Useful for ensuring a tool's required scope and a resource's supported scopes+ are in sync at compile time.+ """+ @spec scope!(t(), String.t()) :: String.t()+ def scope!(resource, scope) do+ if scope in resource.scopes_supported do+ scope+ else+ raise ArgumentError, "unknown scope: #{inspect(scope)}"+ end+ endenddiff --git a/lib/plausible/oauth/token.ex b/lib/plausible/oauth/token.exindex 685336485d..ea15237450 100644--- a/lib/plausible/oauth/token.ex+++ b/lib/plausible/oauth/token.ex@@ -22,9 +22,16 @@ defmodule Plausible.OAuth.Token dodef generate(kind) doraw = "#{plaintext_prefix(kind)}-#{random_value()}"- %{raw: raw, hash: hash(raw), hint: String.slice(raw, -@hint_length, @hint_length)}+ %{raw: raw, hash: hash(raw), hint: hint(raw)}end+ @doc """+ The trailing characters of a raw token, kept alongside the hash so a grant can+ be told apart from another in a list without storing the token itself.+ """+ @spec hint(String.t()) :: String.t()+ def hint(raw), do: String.slice(raw, -@hint_length, @hint_length)+@doc """Hashes a raw token or code."""diff --git a/lib/plausible_web/controllers/mcp/mcp_controller.ex b/lib/plausible_web/controllers/mcp/mcp_controller.exindex 642549c8c6..23b2485bf0 100644--- a/lib/plausible_web/controllers/mcp/mcp_controller.ex+++ b/lib/plausible_web/controllers/mcp/mcp_controller.ex@@ -5,18 +5,73 @@ defmodule PlausibleWeb.MCP.MCPController do"""use PlausibleWeb, :controller+ use Plausible.Repo++ import Ecto.Query, only: [select: 3]++ alias Plausible.Auth.Scopes+ alias Plausible.OAuth.ProtectedResources+ alias Plausible.Teams.Membership+ alias PlausibleWeb.Plugs.AuthorizeOAuthAPI++ require Logger++ @resource ProtectedResources.mcp()++ @supported_versions ["2026-07-28"]++ @public_methods ["server/discover"]++ plug :authorize when action == :handle++ defp authorize(conn, _opts) do+ case message(conn.body_params) do+ {:ok, _message, method, _id} when method not in @public_methods ->+ AuthorizeOAuthAPI.call(conn, resource: @resource)++ _public_or_unroutable ->+ conn+ end+ end++ @cache_ttl_ms :timer.minutes(5)+ @cache_scope "public"++ @version_key "io.modelcontextprotocol/protocolVersion"+ @capabilities_key "io.modelcontextprotocol/clientCapabilities"+ @server_info_key "io.modelcontextprotocol/serverInfo"++ # Every tool declares what scope is needed on the OAuth grant+ # and what role in the team is needed.+ @tool_specs [+ %{+ name: "list_sites",+ scope: ProtectedResources.scope!(@resource, Scopes.sites_read()),+ roles: Membership.roles!([:owner, :admin, :editor, :billing, :viewer]),+ description:+ "List the sites (websites) the authorized team has access to. Returns each site's domain and timezone.",+ inputSchema: %{type: "object", properties: %{}, additionalProperties: false}+ }+ ]++ @tools Enum.map(@tool_specs, &Map.drop(&1, [:scope, :roles]))+ @tools_by_name Map.new(@tool_specs, &{&1.name, &1})@doc """Answers a single JSON-RPC request (https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http#sending-messages)."""def handle(conn, _params) do- conn- |> put_status(501)- |> json(%{error: "not_implemented"})+ case message(conn.body_params) do+ {:ok, message, method, id} ->+ handle_request(conn, message, method, id)++ :error ->+ send_json(conn, 400, error_response(nil, -32_600, "Invalid Request"))+ endend@doc """- Handles `GET` and `DELETE` verbs that earlier MCP versions used for session management by rejecting them.+ Rejects `GET` and `DELETE`, which earlier MCP versions used for session management.This implementation is not backwards-compatible (https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/streamable-http#earlier-streamable-http-revisions)."""def not_supported(conn, _params) do@@ -24,4 +79,245 @@ defmodule PlausibleWeb.MCP.MCPController do|> put_status(405)|> json(%{error: "method_not_allowed", error_description: "Use POST for MCP."})end++ defp handle_request(conn, message, method, id) do+ meta = meta(message)++ with :ok <- validate_headers_present(conn, method),+ :ok <- validate_meta_fields(meta),+ :ok <- validate_header_body_match(conn, message, method, meta),+ :ok <- validate_version(meta) do+ case dispatch(conn, id, method, message) do+ {status, body} -> send_json(conn, status, body)+ {status, body, headers} -> conn |> merge_resp_headers(headers) |> send_json(status, body)+ end+ else+ {:error, status, code, error_message, data} ->+ send_json(conn, status, error_response(id, code, error_message, data))+ end+ end++ defp message(%{"jsonrpc" => "2.0", "method" => method, "id" => id} = message)+ when is_binary(method),+ do: {:ok, message, method, id}++ defp message(_body_params), do: :error++ @always_expected_headers ["mcp-protocol-version", "mcp-method"]+ defp validate_headers_present(conn, method) do+ expected_headers =+ if(expect_name_header?(method),+ do: ["mcp-name"],+ else: []+ )++ expected_headers = expected_headers ++ @always_expected_headers++ case Enum.filter(expected_headers, fn header -> conn |> get_header(header) |> is_nil() end) do+ [] ->+ :ok++ [first_missing_header | _] ->+ header_mismatch("Missing required header: #{first_missing_header}")+ end+ end++ defp validate_meta_fields(meta) do+ cond do+ not is_binary(meta[@version_key]) ->+ invalid_params("Missing or invalid _meta field: #{@version_key}")++ not is_map(meta[@capabilities_key]) ->+ invalid_params("Missing or invalid _meta field: #{@capabilities_key}")++ true ->+ :ok+ end+ end++ # The body is the source of truth. Headers must match the body.+ defp validate_header_body_match(conn, message, method, meta) do+ cond do+ get_header(conn, "mcp-protocol-version") != meta[@version_key] ->+ header_mismatch("Header mcp-protocol-version does not match _meta protocolVersion")++ get_header(conn, "mcp-method") != method ->+ header_mismatch("Header mcp-method does not match request method")++ expect_name_header?(method) and+ decode_header_value(get_header(conn, "mcp-name")) != params(message)["name"] ->+ header_mismatch("Header mcp-name does not match params.name")++ true ->+ :ok+ end+ end++ defp validate_version(meta) do+ version = meta[@version_key]++ if version in @supported_versions do+ :ok+ else+ {:error, 400, -32_022, "Unsupported protocol version",+ %{supported: @supported_versions, requested: version}}+ end+ end++ defp dispatch(_conn, id, "server/discover", _message) do+ {200, success_response(id, cacheable(discover_result()))}+ end++ defp dispatch(_conn, id, "tools/list", _message) do+ {200, success_response(id, cacheable(%{tools: @tools}))}+ end++ defp dispatch(conn, id, "tools/call", message) do+ params = params(message)+ name = params["name"]++ case Map.fetch(@tools_by_name, name) do+ {:ok, spec} ->+ case call_tool(conn, spec, params) do+ {:ok, value} ->+ {200, success_response(id, %{content: [text_content(value)], isError: false})}++ {:error, :insufficient_scope, scope} ->+ {403, %{error: "insufficient_scope"},+ [+ {"www-authenticate", AuthorizeOAuthAPI.challenge(@resource, scope)}+ ]}++ # A role is not something re-authorizing can change, so this stays a+ # tool error: the user has to ask an admin, and the model should say so.+ {:error, message} ->+ {200, success_response(id, %{content: [text_content(message)], isError: true})}+ end++ :error ->+ {400, error_response(id, -32_602, "Unknown tool")}+ end+ end++ defp dispatch(_conn, id, _method, _message) do+ {404, error_response(id, -32_601, "Method not found")}+ end++ defp cacheable(result) do+ Map.merge(result, %{ttlMs: @cache_ttl_ms, cacheScope: @cache_scope})+ end++ defp discover_result do+ %{+ supportedVersions: @supported_versions,+ capabilities: %{tools: %{}},+ instructions:+ "#{Plausible.product_name()} MCP server. Use list_sites to discover the sites the authorized team can access."+ }+ end++ defp call_tool(conn, spec, tool_args) do+ with :ok <- require_scope(conn, spec.scope),+ :ok <- require_role(conn, spec.roles) do+ run_tool(conn, spec.name, tool_args)+ end+ end++ defp run_tool(conn, "list_sites", _tool_args) do+ sites =+ conn.assigns.current_user+ |> Plausible.Sites.for_user_query(conn.assigns.current_team)+ |> select([site: s], %{domain: s.domain, timezone: s.timezone})+ |> Repo.all()++ {:ok, %{sites: sites}}+ end++ defp require_scope(conn, scope) do+ if scope in (conn.assigns[:oauth_scopes] || []) do+ :ok+ else+ {:error, :insufficient_scope, scope}+ end+ end++ defp require_role(conn, roles) do+ role = conn.assigns[:current_team_role]++ if role in roles do+ :ok+ else+ {:error,+ "Your role in this team (#{role}) does not permit this action. It requires one of: " <>+ Enum.map_join(roles, ", ", &to_string/1)}+ end+ end++ defp success_response(id, result) do+ result = Map.merge(result, %{resultType: "complete", _meta: server_meta()})++ %{jsonrpc: "2.0", id: id, result: result}+ end++ defp server_meta do+ %{@server_info_key => %{name: Plausible.product_name(), version: app_version()}}+ end++ defp error_response(id, code, message, data \\ nil) do+ error = %{code: code, message: message}+ error = if data, do: Map.put(error, :data, data), else: error+ %{jsonrpc: "2.0", id: id, error: error}+ end++ defp header_mismatch(message), do: {:error, 400, -32_020, message, nil}+ defp invalid_params(message), do: {:error, 400, -32_602, message, nil}++ defp text_content(value) when is_binary(value), do: %{type: "text", text: value}+ defp text_content(value), do: %{type: "text", text: JSON.encode!(value)}++ # `params` and `_meta` are client-supplied and need not be objects. `get_in/2`+ # raises on a scalar or a list, so neither is ever indexed into directly.+ defp params(%{"params" => params}) when is_map(params), do: params+ defp params(_message), do: %{}++ defp meta(message) do+ case params(message) do+ %{"_meta" => meta} when is_map(meta) -> meta+ _ -> %{}+ end+ end++ defp get_header(conn, name), do: conn |> get_req_header(name) |> List.first()++ defp expect_name_header?("tools/call" = _method), do: true+ defp expect_name_header?(_method), do: false++ # `Mcp-Name` arrives as `=?base64?<encoded>?=` when the value isn't header-safe,+ # so decode it before comparing against the body.+ defp decode_header_value("=?base64?" <> rest = value) do+ with [encoded, ""] <- String.split(rest, "?=", parts: 2),+ {:ok, decoded} <- Base.decode64(encoded) do+ decoded+ else+ _ -> value+ end+ end++ defp decode_header_value(value), do: value++ defp send_json(conn, status, body) do+ conn+ |> put_status(status)+ |> json(body)+ end++ defp app_version do+ runtime_version() || to_string(Application.spec(:plausible, :vsn) || "0.0.0")+ end++ defp runtime_version do+ :plausible+ |> Application.get_env(:runtime_metadata, [])+ |> Keyword.get(:version)+ endenddiff --git a/lib/plausible_web/plugs/authorize_oauth_api.ex b/lib/plausible_web/plugs/authorize_oauth_api.exnew file mode 100644index 0000000000..f68b5568eb--- /dev/null+++ b/lib/plausible_web/plugs/authorize_oauth_api.ex@@ -0,0 +1,89 @@+defmodule PlausibleWeb.Plugs.AuthorizeOAuthAPI do+ @moduledoc """+ Plug for authorizing requests that carry an OAuth 2.1 Bearer access token.++ Modeled on `PlausibleWeb.Plugs.AuthorizePublicAPI`.++ Assigns+ - `:current_user`,+ - `:current_team`+ - `:current_team_role`+ - `:oauth_scopes`++ A failure answers `401` with a+ [`WWW-Authenticate` header](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1#name-the-www-authenticate-respon)+ pointing at the Protected Resource Metadata document, which is how a client+ discovers which authorization server to use.+ """++ import Plug.Conn++ alias Plausible.OAuth+ alias Plausible.OAuth.ProtectedResources+ alias PlausibleWeb.Api.Helpers, as: H+ alias PlausibleWeb.Api.RateLimit+ use PlausibleWeb.VerifiedRoutes++ def init(opts), do: opts++ def call(conn, opts) do+ resource = Keyword.fetch!(opts, :resource)++ with {:ok, raw_token} <- get_bearer_token(conn),+ {:ok, grant, role} <- OAuth.find_access_token(raw_token, resource),+ :ok <- check_rate_limit(grant.team) do+ conn+ |> assign(:current_user, grant.user)+ |> assign(:current_team, grant.team)+ |> assign(:current_team_role, role)+ |> assign(:oauth_scopes, grant.scopes)+ else+ {:error, :missing_token} ->+ conn+ |> put_resp_header("www-authenticate", challenge(resource))+ |> H.unauthorized("unauthorized")++ {:error, :invalid_token} ->+ conn+ |> put_resp_header(+ "www-authenticate",+ challenge(resource) <> ~s(, error="invalid_token")+ )+ |> H.unauthorized("invalid_token")++ {:error, :rate_limit, _message} ->+ H.too_many_requests(conn, "too_many_requests")+ end+ end++ defp get_bearer_token(conn) do+ case List.first(get_req_header(conn, "authorization")) do+ "Bearer " <> token -> {:ok, String.trim(token)}+ _ -> {:error, :missing_token}+ end+ end++ defp check_rate_limit(team) do+ RateLimit.check_rate_limit(RateLimit.limit_key(team), team.hourly_api_request_limit)+ end++ @doc """+ Builds the `WWW-Authenticate` challenge for a request refused because its token+ does not carry `scope`. See [runtime insufficient scope errors](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization#runtime-insufficient-scope-errors).++ ## Examples+ iex> challenge(Plausible.OAuth.ProtectedResources.mcp(), "sites:read:*")+ ~s(Bearer resource_metadata="http://localhost:8000/.well-known/oauth-protected-resource/mcp", scope="sites:read:*", error="insufficient_scope")+ """+ @spec challenge(ProtectedResources.t(), String.t()) :: String.t()+ def challenge(resource, scope),+ do: challenge(resource) <> ~s(, scope="#{scope}", error="insufficient_scope")++ defp challenge(resource),+ do: ~s(Bearer resource_metadata="#{resource_metadata_url(resource)}")++ defp resource_metadata_url(resource) do+ "#{PlausibleWeb.Endpoint.url()}/.well-known/oauth-protected-resource" <>+ resource.resource_path+ end+enddiff --git a/test/plausible/oauth_test.exs b/test/plausible/oauth_test.exsindex fbdf687247..02035873db 100644--- a/test/plausible/oauth_test.exs+++ b/test/plausible/oauth_test.exs@@ -18,11 +18,7 @@ defmodule Plausible.OAuthTest do@client_id "https://client.example.com/oauth-metadata"@redirect_uri "https://client.example.com/callback"- setup do- user = new_user()- {:ok, team} = Plausible.Teams.get_or_create(user)- {:ok, user: user, team: team}- end+ setup [:create_user, :create_team]describe "Step 1: create_authorization_code/3" dotest "refuses a resource this server does not know", %{user: user, team: team} do@@ -257,7 +253,7 @@ defmodule Plausible.OAuthTest do})# Verify that the token works for the correct resource.- assert {:ok, _grant} = OAuth.find_access_token(access_token, mcp())+ assert {:ok, _grant, _role} = OAuth.find_access_token(access_token, mcp())endtest "rejects an expired token", %{user: user, team: team} do@@ -307,7 +303,7 @@ defmodule Plausible.OAuthTest doscope: "sites:read:*"}) = response- assert {:ok, token} = OAuth.find_access_token(response.access_token, mcp())+ assert {:ok, token, _role} = OAuth.find_access_token(response.access_token, mcp())resource = resource()@@ -350,7 +346,7 @@ defmodule Plausible.OAuthTest domember = add_member(team, role: :editor){_grant, access_token} = issue_grant(member, team)- assert {:ok, _} = OAuth.find_access_token(access_token, mcp())+ assert {:ok, _, _role} = OAuth.find_access_token(access_token, mcp())Plausible.Teams.Membership|> Repo.get_by!(team_id: team.id, user_id: member.id)@@ -358,6 +354,22 @@ defmodule Plausible.OAuthTest doassert {:error, :invalid_token} = OAuth.find_access_token(access_token, mcp())end++ test "an access token stops resolving once the user is demoted to guest" do+ owner = new_user()+ {:ok, team} = Plausible.Teams.get_or_create(owner)+ member = add_member(team, role: :editor)++ {_grant, access_token} = issue_grant(member, team)+ assert {:ok, _, :editor} = OAuth.find_access_token(access_token, mcp())++ Plausible.Teams.Membership+ |> Repo.get_by!(team_id: team.id, user_id: member.id)+ |> Ecto.Changeset.change(role: :guest)+ |> Repo.update!()++ assert {:error, :invalid_token} = OAuth.find_access_token(access_token, mcp())+ endenddescribe "Step 4: revoke_grant/1 and after_user_removed_from_team/2" do@@ -409,7 +421,7 @@ defmodule Plausible.OAuthTest doassert {:error, :invalid_token} = OAuth.find_access_token(access_token, mcp())assert_matches %Grant{revoked_at: nil} = Plausible.Repo.get!(Grant, kept.id)- assert {:ok, _} = OAuth.find_access_token(kept_token, mcp())+ assert {:ok, _, _role} = OAuth.find_access_token(kept_token, mcp())endtest "a member leaving revokes the grants they held against the team" do@@ -432,7 +444,7 @@ defmodule Plausible.OAuthTest doassert revoked_atassert_matches %Grant{revoked_at: nil} = Plausible.Repo.get!(Grant, kept.id)- assert {:ok, _} = OAuth.find_access_token(kept_token, mcp())+ assert {:ok, _, _role} = OAuth.find_access_token(kept_token, mcp())endend@@ -480,7 +492,7 @@ defmodule Plausible.OAuthTest do}){:ok, response} = OAuth.issue_token(consumed_code)- {:ok, grant} = OAuth.find_access_token(response.access_token, mcp())+ {:ok, grant, _role} = OAuth.find_access_token(response.access_token, mcp()){grant, response.access_token}enddiff --git a/test/plausible_web/controllers/mcp/mcp_controller_test.exs b/test/plausible_web/controllers/mcp/mcp_controller_test.exsnew file mode 100644index 0000000000..5f5d19a19c--- /dev/null+++ b/test/plausible_web/controllers/mcp/mcp_controller_test.exs@@ -0,0 +1,1084 @@+defmodule PlausibleWeb.MCP.MCPControllerTest do+ # Not `async: true`: the end-to-end flow stubs the CIMD fetch and its DNS lookup.+ use PlausibleWeb.ConnCase+ use Plausible.Test.Support.DNS++ alias Plausible.Auth.Scopes+ alias Plausible.OAuth+ alias Plausible.OAuth.{ProtectedResources, Token}++ @version "2026-07-28"++ setup [:create_user, :create_team]++ describe "authentication" do+ test "401s without a token, pointing at metadata that actually resolves", %{conn: conn} do+ conn =+ conn+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/list")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/list",+ "params" => %{+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })++ assert json_response(conn, 401) == %{"error" => "unauthorized"}++ assert [challenge] = get_resp_header(conn, "www-authenticate")+ assert [_, metadata_url] = Regex.run(~r/resource_metadata="([^"]+)"/, challenge)++ metadata = build_conn() |> get(URI.parse(metadata_url).path) |> json_response(200)++ assert metadata == %{+ "resource" => ProtectedResources.get_resource_url(ProtectedResources.mcp()),+ "authorization_servers" => [PlausibleWeb.Endpoint.url()],+ "scopes_supported" => ProtectedResources.mcp().scopes_supported,+ "bearer_methods_supported" => ["header"]+ }+ end++ test "tools/call requires a token too", %{conn: conn} do+ conn =+ conn+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/call")+ |> put_req_header("mcp-name", "list_sites")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/call",+ "params" => %{+ "name" => "list_sites",+ "arguments" => %{},+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })++ assert json_response(conn, 401) == %{"error" => "unauthorized"}+ end++ test "401s an unknown token", %{conn: conn} do+ conn =+ conn+ |> put_req_header("authorization", "Bearer not-a-token")+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/list")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/list",+ "params" => %{+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })++ assert json_response(conn, 401) == %{"error" => "invalid_token"}+ end++ # A token that is ours, unexpired and unrevoked must still be refused if it+ # was issued for a different resource. This is what pins the controller to+ # `ProtectedResources.mcp()`.+ test "401s a token issued for another resource", %{conn: conn, user: user, team: team} do+ token = Token.generate(:access).raw++ insert(:oauth_grant,+ user: user,+ team: team,+ access_token: token,+ resource: "https://elsewhere.example/mcp"+ )++ conn =+ conn+ |> put_req_header("authorization", "Bearer " <> token)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/list")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/list",+ "params" => %{+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })++ assert json_response(conn, 401) == %{"error" => "invalid_token"}+ end++ test "a malformed request on a method needing no token is 400, not a crash", %{conn: conn} do+ conn =+ conn+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "server/discover")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "server/discover",+ "params" => "not-an-object"+ })++ assert json_response(conn, 400) == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "error" => %{+ "code" => -32_602,+ "message" =>+ "Missing or invalid _meta field: io.modelcontextprotocol/protocolVersion"+ }+ }+ end+ end++ describe "envelope validation" do+ setup :insert_token++ test "rejects a protocol version header disagreeing with the body", %{conn: conn, token: t} do+ conn =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", "2025-11-25")+ |> put_req_header("mcp-method", "tools/list")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/list",+ "params" => %{+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })++ assert json_response(conn, 400) == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "error" => %{+ "code" => -32_020,+ "message" => "Header mcp-protocol-version does not match _meta protocolVersion"+ }+ }+ end++ test "rejects a method header disagreeing with the body", %{conn: conn, token: t} do+ conn =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "server/discover")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/list",+ "params" => %{+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })++ assert json_response(conn, 400) == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "error" => %{+ "code" => -32_020,+ "message" => "Header mcp-method does not match request method"+ }+ }+ end++ test "rejects an mcp-name header disagreeing with params.name", %{conn: conn, token: t} do+ conn =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/call")+ |> put_req_header("mcp-name", "something_else")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/call",+ "params" => %{+ "name" => "list_sites",+ "arguments" => %{},+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })++ assert json_response(conn, 400) == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "error" => %{+ "code" => -32_020,+ "message" => "Header mcp-name does not match params.name"+ }+ }+ end++ test "accepts a base64-encoded mcp-name header", %{conn: conn, token: t} do+ resp =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/call")+ |> put_req_header("mcp-name", "=?base64?" <> Base.encode64("list_sites") <> "?=")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/call",+ "params" => %{+ "name" => "list_sites",+ "arguments" => %{},+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })+ |> json_response(200)++ assert resp == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "result" => %{+ "content" => [+ %{+ "type" => "text",+ "text" => JSON.encode!(%{sites: []})+ }+ ],+ "isError" => false,+ "resultType" => "complete",+ "_meta" => %{+ "io.modelcontextprotocol/serverInfo" => %{+ "name" => Plausible.product_name(),+ "version" => app_version()+ }+ }+ }+ }+ end++ test "rejects a missing header", %{conn: conn, token: t} do+ conn =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/list",+ "params" => %{+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })++ assert json_response(conn, 400) == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "error" => %{+ "code" => -32_020,+ "message" => "Missing required header: mcp-method"+ }+ }+ end++ test "rejects a missing _meta protocol version", %{conn: conn, token: t} do+ conn =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/list")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/list",+ "params" => %{+ "_meta" => %{"io.modelcontextprotocol/clientCapabilities" => %{}}+ }+ })++ assert json_response(conn, 400) == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "error" => %{+ "code" => -32_602,+ "message" =>+ "Missing or invalid _meta field: io.modelcontextprotocol/protocolVersion"+ }+ }+ end++ test "rejects an unsupported version, naming what is supported", %{conn: conn, token: t} do+ conn =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", "1999-01-01")+ |> put_req_header("mcp-method", "tools/list")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/list",+ "params" => %{+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => "1999-01-01",+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })++ assert json_response(conn, 400) == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "error" => %{+ "code" => -32_022,+ "message" => "Unsupported protocol version",+ "data" => %{+ "supported" => [@version],+ "requested" => "1999-01-01"+ }+ }+ }+ end++ test "rejects a non-object params", %{conn: conn, token: t} do+ conn =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/list")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/list",+ "params" => "not-an-object"+ })++ assert json_response(conn, 400) == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "error" => %{+ "code" => -32_602,+ "message" =>+ "Missing or invalid _meta field: io.modelcontextprotocol/protocolVersion"+ }+ }+ end++ test "rejects a non-object _meta", %{conn: conn, token: t} do+ conn =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/list")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/list",+ "params" => %{"_meta" => "not-an-object"}+ })++ assert json_response(conn, 400) == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "error" => %{+ "code" => -32_602,+ "message" =>+ "Missing or invalid _meta field: io.modelcontextprotocol/protocolVersion"+ }+ }+ end++ test "rejects a batch array with a token", %{conn: conn, token: t} do+ conn =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/list")+ |> put_req_header("content-type", "application/json")+ |> post(+ "/mcp",+ JSON.encode!([+ %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/list",+ "params" => %{+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ }+ ])+ )++ assert json_response(conn, 400) == %{+ "jsonrpc" => "2.0",+ "id" => nil,+ "error" => %{"code" => -32_600, "message" => "Invalid Request"}+ }+ end++ test "rejects a batch array without a token", %{conn: conn} do+ conn =+ conn+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/list")+ |> put_req_header("content-type", "application/json")+ |> post(+ "/mcp",+ JSON.encode!([+ %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/list",+ "params" => %{+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ }+ ])+ )++ assert json_response(conn, 400) == %{+ "jsonrpc" => "2.0",+ "id" => nil,+ "error" => %{"code" => -32_600, "message" => "Invalid Request"}+ }+ end++ test "a notification is an invalid request - this revision defines none", %{+ conn: conn,+ token: t+ } do+ conn =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "notifications/progress")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "method" => "notifications/progress",+ "params" => %{+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })++ assert json_response(conn, 400) == %{+ "jsonrpc" => "2.0",+ "id" => nil,+ "error" => %{"code" => -32_600, "message" => "Invalid Request"}+ }+ end+ end++ describe "server/discover" do+ # A client picks a protocol version before it holds a token, and a bare 401+ # tells it nothing about which versions the server speaks.+ test "advertises versions, the tools capability and the server, without a token", %{+ conn: conn+ } do+ resp =+ conn+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "server/discover")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "server/discover",+ "params" => %{+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })+ |> json_response(200)++ assert resp == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "result" => %{+ "supportedVersions" => [@version],+ "capabilities" => %{"tools" => %{}},+ "instructions" =>+ "#{Plausible.product_name()} MCP server. Use list_sites to discover the sites the authorized team can access.",+ "resultType" => "complete",+ "_meta" => %{+ "io.modelcontextprotocol/serverInfo" => %{+ "name" => Plausible.product_name(),+ "version" => app_version()+ }+ },+ "ttlMs" => :timer.minutes(5),+ "cacheScope" => "public"+ }+ }+ end+ end++ describe "tools/list" do+ setup :insert_token++ test "returns list_sites, with caching hints and the server identity", %{conn: conn, token: t} do+ resp =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/list")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/list",+ "params" => %{+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })+ |> json_response(200)++ assert resp == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "result" => %{+ "tools" => [+ %{+ "name" => "list_sites",+ "description" =>+ "List the sites (websites) the authorized team has access to. Returns each site's domain and timezone.",+ "inputSchema" => %{+ "type" => "object",+ "properties" => %{},+ "additionalProperties" => false+ }+ }+ ],+ "resultType" => "complete",+ "_meta" => %{+ "io.modelcontextprotocol/serverInfo" => %{+ "name" => Plausible.product_name(),+ "version" => app_version()+ }+ },+ "ttlMs" => :timer.minutes(5),+ "cacheScope" => "public"+ }+ }+ end+ end++ describe "tools/call" do+ setup :insert_token++ test "an unknown tool is a protocol error, not a tool error", %{conn: conn, token: t} do+ conn =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/call")+ |> put_req_header("mcp-name", "made_up_tool")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/call",+ "params" => %{+ "name" => "made_up_tool",+ "arguments" => %{},+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })++ assert json_response(conn, 400) == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "error" => %{"code" => -32_602, "message" => "Unknown tool"}+ }+ end+ end++ describe "tools/call list_sites" do+ setup :insert_token++ test "returns the team's sites", %{conn: conn, user: user, token: t} do+ site = new_site(owner: user)++ resp =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/call")+ |> put_req_header("mcp-name", "list_sites")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/call",+ "params" => %{+ "name" => "list_sites",+ "arguments" => %{},+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })+ |> json_response(200)++ assert resp == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "result" => %{+ "content" => [+ %{+ "type" => "text",+ "text" =>+ JSON.encode!(%{+ sites: [%{domain: site.domain, timezone: site.timezone}]+ })+ }+ ],+ "isError" => false,+ "resultType" => "complete",+ "_meta" => %{+ "io.modelcontextprotocol/serverInfo" => %{+ "name" => Plausible.product_name(),+ "version" => app_version()+ }+ }+ }+ }+ end++ test "returns an empty list when the team has no sites", %{conn: conn, token: t} do+ resp =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/call")+ |> put_req_header("mcp-name", "list_sites")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/call",+ "params" => %{+ "name" => "list_sites",+ "arguments" => %{},+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })+ |> json_response(200)++ assert resp == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "result" => %{+ "content" => [+ %{+ "type" => "text",+ "text" => JSON.encode!(%{sites: []})+ }+ ],+ "isError" => false,+ "resultType" => "complete",+ "_meta" => %{+ "io.modelcontextprotocol/serverInfo" => %{+ "name" => Plausible.product_name(),+ "version" => app_version()+ }+ }+ }+ }+ end++ test "does not leak another team's sites", %{conn: conn, user: user, token: t} do+ mine = new_site(owner: user)+ _theirs = new_site(owner: new_user())++ resp =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/call")+ |> put_req_header("mcp-name", "list_sites")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/call",+ "params" => %{+ "name" => "list_sites",+ "arguments" => %{},+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })+ |> json_response(200)++ assert resp == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "result" => %{+ "content" => [+ %{+ "type" => "text",+ "text" =>+ JSON.encode!(%{+ sites: [%{domain: mine.domain, timezone: mine.timezone}]+ })+ }+ ],+ "isError" => false,+ "resultType" => "complete",+ "_meta" => %{+ "io.modelcontextprotocol/serverInfo" => %{+ "name" => Plausible.product_name(),+ "version" => app_version()+ }+ }+ }+ }+ end++ test "a grant lacking sites:read is 403, challenging for the scope it needs", %{+ conn: conn,+ user: user,+ team: team+ } do+ new_site(owner: user)++ token = Token.generate(:access).raw++ insert(:oauth_grant,+ user: user,+ team: team,+ access_token: token,+ scopes: [Scopes.stats_read()]+ )++ conn =+ conn+ |> put_req_header("authorization", "Bearer " <> token)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/call")+ |> put_req_header("mcp-name", "list_sites")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/call",+ "params" => %{+ "name" => "list_sites",+ "arguments" => %{},+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })++ assert json_response(conn, 403) == %{"error" => "insufficient_scope"}++ assert [challenge] = get_resp_header(conn, "www-authenticate")++ assert challenge ==+ ~s(Bearer resource_metadata="#{PlausibleWeb.Endpoint.url()}/.well-known/oauth-protected-resource/mcp", scope="#{Scopes.sites_read()}", error="insufficient_scope")+ end++ # The roles the tool declares have to match what listing sites actually+ # allows, so each one is exercised rather than assumed.+ test "serves every role the tool declares", %{conn: conn, user: owner, team: team} do+ site = new_site(owner: owner)++ for role <- [:viewer, :billing, :editor, :admin] do+ member = add_member(team, role: role)+ member_token = Token.generate(:access).raw+ insert(:oauth_grant, user: member, team: team, access_token: member_token)++ resp =+ conn+ |> recycle()+ |> put_req_header("authorization", "Bearer " <> member_token)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/call")+ |> put_req_header("mcp-name", "list_sites")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/call",+ "params" => %{+ "name" => "list_sites",+ "arguments" => %{},+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })+ |> json_response(200)++ assert resp == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "result" => %{+ "content" => [+ %{+ "type" => "text",+ "text" =>+ JSON.encode!(%{+ sites: [%{domain: site.domain, timezone: site.timezone}]+ })+ }+ ],+ "isError" => false,+ "resultType" => "complete",+ "_meta" => %{+ "io.modelcontextprotocol/serverInfo" => %{+ "name" => Plausible.product_name(),+ "version" => app_version()+ }+ }+ }+ }+ end+ end+ end++ describe "unknown method" do+ setup :insert_token++ test "is 404 with -32601", %{conn: conn, token: t} do+ conn =+ conn+ |> put_req_header("authorization", "Bearer " <> t)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "resources/list")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "resources/list",+ "params" => %{+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })++ assert json_response(conn, 404) == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "error" => %{"code" => -32_601, "message" => "Method not found"}+ }+ end+ end++ # These only ever answer 405, so they stay unauthenticated - a 401 would hide+ # the signal an older client uses to detect the protocol revision.+ describe "GET /mcp and DELETE /mcp" do+ test "GET is 405 without a token", %{conn: conn} do+ assert conn |> get("/mcp") |> json_response(405) == %{+ "error" => "method_not_allowed",+ "error_description" => "Use POST for MCP."+ }+ end++ test "DELETE is 405 without a token", %{conn: conn} do+ assert conn |> delete("/mcp") |> json_response(405) == %{+ "error" => "method_not_allowed",+ "error_description" => "Use POST for MCP."+ }+ end+ end++ describe "end to end flow" do+ setup [:create_site, :log_in]++ test "app can be authorized, the acquired token works for listing sites, stops working when revoked",+ %{+ conn: conn,+ user: user,+ site: site+ } do+ client_id = "https://client.example.com/oauth-metadata"+ redirect_uri = "https://client.example.com/callback"++ FunWithFlags.enable(:mcp, for_actor: user)++ stub_dns()++ Req.Test.stub(Plausible.OAuth.CIMD, fn conn ->+ Plug.Conn.send_resp(+ conn,+ 200,+ JSON.encode!(%{+ "client_id" => client_id,+ "redirect_uris" => [redirect_uri],+ "client_name" => "Test Client"+ })+ )+ end)++ verifier = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)+ challenge = :crypto.hash(:sha256, verifier) |> Base.url_encode64(padding: false)+ resource = ProtectedResources.get_resource_url(ProtectedResources.mcp())++ html =+ conn+ |> get(+ "/login/oauth/authorize?" <>+ URI.encode_query(%{+ "client_id" => client_id,+ "redirect_uri" => redirect_uri,+ "response_type" => "code",+ "code_challenge" => challenge,+ "code_challenge_method" => "S256",+ "scope" => "sites:read:*",+ "resource" => resource+ })+ )+ |> html_response(200)++ redirect =+ conn+ |> post("/login/oauth/authorize", %{+ "signed_request" => text_of_attr(html, "input[name=signed_request]", "value"),+ "team" => text_of_attr(html, "input[name=team]", "value"),+ "action" => "approve"+ })+ |> redirected_to(302)++ assert [base, query] = String.split(redirect, "?")+ assert base == redirect_uri++ params = URI.decode_query(query)+ code = params["code"]++ %{"access_token" => access_token, "token_type" => "Bearer"} =+ build_conn()+ |> post("/login/oauth/token", %{+ "grant_type" => "authorization_code",+ "client_id" => client_id,+ "code" => code,+ "code_verifier" => verifier,+ "redirect_uri" => redirect_uri,+ "resource" => resource+ })+ |> json_response(200)++ resp =+ build_conn()+ |> put_req_header("authorization", "Bearer " <> access_token)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/call")+ |> put_req_header("mcp-name", "list_sites")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/call",+ "params" => %{+ "name" => "list_sites",+ "arguments" => %{},+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })+ |> json_response(200)++ assert resp == %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "result" => %{+ "content" => [+ %{+ "type" => "text",+ "text" =>+ JSON.encode!(%{+ sites: [%{domain: site.domain, timezone: site.timezone}]+ })+ }+ ],+ "isError" => false,+ "resultType" => "complete",+ "_meta" => %{+ "io.modelcontextprotocol/serverInfo" => %{+ "name" => Plausible.product_name(),+ "version" => app_version()+ }+ }+ }+ }++ {:ok, grant, _role} = OAuth.find_access_token(access_token, ProtectedResources.mcp())+ OAuth.revoke_grant(grant)++ revoked =+ build_conn()+ |> put_req_header("authorization", "Bearer " <> access_token)+ |> put_req_header("mcp-protocol-version", @version)+ |> put_req_header("mcp-method", "tools/call")+ |> put_req_header("mcp-name", "list_sites")+ |> post("/mcp", %{+ "jsonrpc" => "2.0",+ "id" => 1,+ "method" => "tools/call",+ "params" => %{+ "name" => "list_sites",+ "arguments" => %{},+ "_meta" => %{+ "io.modelcontextprotocol/protocolVersion" => @version,+ "io.modelcontextprotocol/clientCapabilities" => %{}+ }+ }+ })++ assert json_response(revoked, 401) == %{"error" => "invalid_token"}+ end+ end++ defp insert_token(%{user: user, team: team}) do+ token = Token.generate(:access).raw+ insert(:oauth_grant, user: user, team: team, access_token: token)++ {:ok, token: token}+ end++ defp app_version, do: to_string(Application.spec(:plausible, :vsn))+enddiff --git a/test/plausible_web/controllers/oauth/token_controller_test.exs b/test/plausible_web/controllers/oauth/token_controller_test.exsindex 78068f4868..5d393d8a7b 100644--- a/test/plausible_web/controllers/oauth/token_controller_test.exs+++ b/test/plausible_web/controllers/oauth/token_controller_test.exs@@ -139,7 +139,7 @@ defmodule PlausibleWeb.OAuth.TokenControllerTest dorefute resp["refresh_token"] == resp["access_token"]- assert {:ok, grant} = OAuth.find_access_token(resp["access_token"], resource)+ assert {:ok, grant, _role} = OAuth.find_access_token(resp["access_token"], resource)assert_matches %{user: %{id: ^auth_code.user_id},diff --git a/test/plausible_web/plugs/authorize_oauth_api_test.exs b/test/plausible_web/plugs/authorize_oauth_api_test.exsnew file mode 100644index 0000000000..5a45f9603f--- /dev/null+++ b/test/plausible_web/plugs/authorize_oauth_api_test.exs@@ -0,0 +1,193 @@+defmodule PlausibleWeb.Plugs.AuthorizeOAuthAPITest do+ use PlausibleWeb.ConnCase, async: true++ alias Plausible.OAuth+ alias Plausible.OAuth.{Grant, ProtectedResources, Token}+ alias PlausibleWeb.Plugs.AuthorizeOAuthAPI++ doctest PlausibleWeb.Plugs.AuthorizeOAuthAPI, import: true++ setup [:create_user, :create_team]++ test "assigns the user, team, role and granted scopes", %{user: user, team: team} do+ access_token = Token.generate(:access).raw+ insert(:oauth_grant, user: user, team: team, access_token: access_token)++ conn = authorize(bypassed_conn(), access_token)++ refute conn.halted+ assert conn.assigns.current_user.id == user.id+ assert conn.assigns.current_team.id == team.id+ assert conn.assigns.current_team_role == :owner+ assert conn.assigns.oauth_scopes == ProtectedResources.mcp().scopes_supported+ end++ test "assigns the role the user currently holds, not the one they had", %{+ user: user,+ team: team+ } do+ access_token = Token.generate(:access).raw+ insert(:oauth_grant, user: user, team: team, access_token: access_token)++ Plausible.Repo.get_by!(Plausible.Teams.Membership, user_id: user.id, team_id: team.id)+ |> Ecto.Changeset.change(role: :viewer)+ |> Plausible.Repo.update!()++ assert authorize(bypassed_conn(), access_token).assigns.current_team_role == :viewer+ end++ test "halts once the user is demoted to a role that cannot hold a grant", %{+ user: user,+ team: team+ } do+ access_token = Token.generate(:access).raw+ insert(:oauth_grant, user: user, team: team, access_token: access_token)++ Plausible.Repo.get_by!(Plausible.Teams.Membership, user_id: user.id, team_id: team.id)+ |> Ecto.Changeset.change(role: :guest)+ |> Plausible.Repo.update!()++ conn = authorize(bypassed_conn(), access_token)++ assert conn.halted+ assert_matches ^strict_map(%{"error" => "invalid_token"}) = json_response(conn, 401)+ end++ test "halts once the user is no longer a member of the team, but does not by itself revoke the token",+ %{user: user, team: team} do+ access_token = Token.generate(:access).raw+ insert(:oauth_grant, user: user, team: team, access_token: access_token)++ remove_from_team(user, team)++ conn = authorize(bypassed_conn(), access_token)++ assert conn.halted+ assert_matches ^strict_map(%{"error" => "invalid_token"}) = json_response(conn, 401)++ assert ["Bearer resource_metadata=" <> _ = challenge] =+ get_resp_header(conn, "www-authenticate")++ assert challenge =~ ~s(error="invalid_token")++ assert %Grant{revoked_at: nil} =+ Plausible.Repo.get_by!(Grant, access_token_hash: Token.hash(access_token))+ end++ test "halts on a missing token" do+ conn =+ bypassed_conn() |> get("/") |> AuthorizeOAuthAPI.call(resource: ProtectedResources.mcp())++ assert conn.halted+ assert_matches ^strict_map(%{"error" => "unauthorized"}) = json_response(conn, 401)+ end++ test "points a caller with no token at the metadata document" do+ conn =+ bypassed_conn() |> get("/") |> AuthorizeOAuthAPI.call(resource: ProtectedResources.mcp())++ assert [challenge] = get_resp_header(conn, "www-authenticate")++ assert challenge ==+ ~s(Bearer resource_metadata="#{PlausibleWeb.Endpoint.url()}/.well-known/oauth-protected-resource/mcp")+ end++ test "halts on an unknown token" do+ conn = authorize(bypassed_conn(), "made-up")++ assert conn.halted+ assert_matches ^strict_map(%{"error" => "invalid_token"}) = json_response(conn, 401)+ end++ test "halts on an expired token", %{user: user, team: team} do+ access_token = Token.generate(:access).raw++ insert(:oauth_grant,+ user: user,+ team: team,+ access_token: access_token,+ access_token_expires_at: NaiveDateTime.utc_now(:second)+ )++ conn = authorize(bypassed_conn(), access_token)++ assert conn.halted+ assert_matches ^strict_map(%{"error" => "invalid_token"}) = json_response(conn, 401)+ end++ test "halts on a revoked token", %{user: user, team: team} do+ access_token = Token.generate(:access).raw++ :oauth_grant+ |> insert(user: user, team: team, access_token: access_token)+ |> OAuth.revoke_grant()++ conn = authorize(bypassed_conn(), access_token)++ assert conn.halted+ assert_matches ^strict_map(%{"error" => "invalid_token"}) = json_response(conn, 401)+ end++ test "halts on a token issued for another resource", %{user: user, team: team} do+ access_token = Token.generate(:access).raw+ insert(:oauth_grant, user: user, team: team, access_token: access_token)++ conn =+ bypassed_conn()+ |> put_req_header("authorization", "Bearer #{access_token}")+ |> get("/")+ |> AuthorizeOAuthAPI.call(resource: %{resource_path: "/elsewhere", scopes_supported: []})++ assert conn.halted+ assert_matches ^strict_map(%{"error" => "invalid_token"}) = json_response(conn, 401)+ end++ test "halts once the team's hourly request limit is spent, spends the same limit as Stats / Sites API keys",+ %{user: user, team: team} do+ team = team |> Ecto.Changeset.change(hourly_api_request_limit: 1) |> Plausible.Repo.update!()++ stats_api_key = insert(:api_key, user: user, team: team, scopes: ["stats:read:*"])+ access_token = Token.generate(:access).raw+ insert(:oauth_grant, user: user, team: team, access_token: access_token)++ conn_within_limit = authorize(bypassed_conn(), access_token)+ refute conn_within_limit.halted++ conn_oauth_over_limit = authorize(bypassed_conn(), access_token)++ assert conn_oauth_over_limit.halted++ assert_matches ^strict_map(%{"error" => "too_many_requests"}) =+ json_response(conn_oauth_over_limit, 429)++ conn_api_over_limit =+ build_conn()+ |> put_req_header("authorization", "Bearer #{stats_api_key.key}")+ |> get(~p"/api/v1/stats/aggregate", %{"site_id" => "no-such-site.example"})++ assert conn_api_over_limit.halted++ assert_matches ^strict_map(%{+ "error" =>+ "Too many API requests. The limit is 1 per hour. Please contact us to request more capacity."+ }) = json_response(conn_api_over_limit, 429)+ end++ defp bypassed_conn() do+ build_conn()+ |> put_private(PlausibleWeb.FirstLaunchPlug, :skip)+ |> bypass_through(PlausibleWeb.Router)+ end++ defp authorize(conn, access_token) do+ conn+ |> put_req_header("authorization", "Bearer #{access_token}")+ |> get("/")+ |> AuthorizeOAuthAPI.call(resource: ProtectedResources.mcp())+ end++ defp remove_from_team(user, team) do+ Plausible.Repo.get_by!(Plausible.Teams.Membership, user_id: user.id, team_id: team.id)+ |> Plausible.Repo.delete!()+ end+enddiff --git a/test/support/factory.ex b/test/support/factory.exindex df1d0af1b5..9b7a440077 100644--- a/test/support/factory.ex+++ b/test/support/factory.ex@@ -301,6 +301,39 @@ defmodule Plausible.Factory domerge_attributes(auth_code, attrs)end+ @doc """+ Takes the plaintext `:access_token` and `:refresh_token` a test will present,+ and stores what the server keeps for them - the hash and the hint. Both+ default to fresh random values.++ Defaults describe a live grant for the MCP resource, carrying every scope that+ resource supports.+ """+ def oauth_grant_factory(attrs) do+ {access_token, attrs} =+ Map.pop_lazy(attrs, :access_token, fn -> Plausible.OAuth.Token.generate(:access).raw end)++ {refresh_token, attrs} =+ Map.pop_lazy(attrs, :refresh_token, fn -> Plausible.OAuth.Token.generate(:refresh).raw end)++ resource = Plausible.OAuth.ProtectedResources.mcp()+ expires_at = NaiveDateTime.add(NaiveDateTime.utc_now(:second), 3600, :second)++ grant = %Plausible.OAuth.Grant{+ client_id: "https://client.example.com/oauth-metadata",+ scopes: resource.scopes_supported,+ resource: Plausible.OAuth.ProtectedResources.get_resource_url(resource),+ access_token_hash: Plausible.OAuth.Token.hash(access_token),+ access_token_hint: Plausible.OAuth.Token.hint(access_token),+ access_token_expires_at: expires_at,+ refresh_token_hash: Plausible.OAuth.Token.hash(refresh_token),+ refresh_token_hint: Plausible.OAuth.Token.hint(refresh_token),+ refresh_token_expires_at: expires_at+ }++ merge_attributes(grant, attrs)+ end+def imported_visitors_factory do%{table: "imported_visitors",