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
Wire up GET /login/oauth/authorize (#6712)
Artur Patae8f522094443
diff --git a/lib/plausible/auth/auth.ex b/lib/plausible/auth/auth.exindex 7ae4fe86dc..147232e16d 100644--- a/lib/plausible/auth/auth.ex+++ b/lib/plausible/auth/auth.ex@@ -24,6 +24,8 @@ defmodule Plausible.Auth do@activation_request_limit 100_000@totp_setup_limit 100_000@totp_setup_ip_limit 100_000+ @oauth_authorize_limit 100_000+ @oauth_authorize_ip_limit 100_000env when env in [:test, :ce_test] ->@ip_rate_limit 5@@ -33,6 +35,8 @@ defmodule Plausible.Auth do@activation_ip_limit 100_000@totp_setup_ip_limit 100_000@activation_request_limit 100_000+ @oauth_authorize_limit 10+ @oauth_authorize_ip_limit 100_000_ ->@ip_rate_limit 5@@ -42,6 +46,8 @@ defmodule Plausible.Auth do@activation_ip_limit 2@totp_setup_ip_limit 2@activation_request_limit 5+ @oauth_authorize_limit 10+ @oauth_authorize_ip_limit 30end@rate_limits %{@@ -94,6 +100,16 @@ defmodule Plausible.Auth doprefix: "totp-setup:user",limit: @totp_setup_limit,interval: :timer.minutes(5)+ },+ oauth_authorize_ip: %{+ prefix: "oauth-authorize:ip",+ limit: @oauth_authorize_ip_limit,+ interval: :timer.minutes(1)+ },+ oauth_authorize_user: %{+ prefix: "oauth-authorize:user",+ limit: @oauth_authorize_limit,+ interval: :timer.minutes(1)}}diff --git a/lib/plausible/auth/scopes.ex b/lib/plausible/auth/scopes.exindex e066bf3a35..d27706e2ba 100644--- a/lib/plausible/auth/scopes.ex+++ b/lib/plausible/auth/scopes.ex@@ -9,4 +9,15 @@ defmodule Plausible.Auth.Scopes do@sites_read_all "sites:read:*"def sites_read(), do: @sites_read_all++ @descriptions %{+ @stats_read_all => "Read your sites' analytics (Stats API)",+ @sites_read_all => "Read the list and details of your sites"+ }++ @doc """+ Renders a scope as the line shown on an OAuth consent screen, falling back to+ the raw scope if it has no description.+ """+ def description(scope), do: Map.get(@descriptions, scope, scope)enddiff --git a/lib/plausible_web/controllers/oauth/authorize_controller.ex b/lib/plausible_web/controllers/oauth/authorize_controller.exindex e39a5664b0..569d07f9c9 100644--- a/lib/plausible_web/controllers/oauth/authorize_controller.ex+++ b/lib/plausible_web/controllers/oauth/authorize_controller.ex@@ -1,30 +1,167 @@defmodule PlausibleWeb.OAuth.AuthorizeController do@moduledoc """- OAuth 2.1 authorization module.+ OAuth 2.1 authorization controller.++ ### Responsibilities++ #### Render the consent screen++ It's a form for the user to approve or deny the app requesting for authorization.++ #### Handle form submitting++ There's a special Phoenix.Token.sign/verify flow in place to validate that the submitted data+ hasn't been tampered with in between rendering the screen and submitting the approve / deny decision."""use PlausibleWeb, :controller+ alias Plausible.Auth+ alias Plausible.OAuth+ alias PlausibleWeb.OAuth.AuthorizationRequest+ alias PlausibleWeb.OAuth.AuthorizationResponse++ plug :require_feature_flag+ plug :put_view, PlausibleWeb.AuthView++ @no_team_message "You need to belong to a team before authorizing an application. Please create or join a team and try again."++ @ungrantable_team_message "You cannot grant access to the selected team. Return to the application and start again."++ @rate_limited_message "Too many authorization requests. Wait a minute before trying again."++ @unverified_request_message "This authorization request has expired or could not be verified. Return to the application and start again."+@doc """- Validates an incoming [authorization request](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1#name-authorization-request)- and renders the consent screen for the logged-in user.+ Renders the consent form if it's valid authorization request. If not, it redirects with an error or renders a local error page."""- def authorize_form(conn, _params) do- not_implemented(conn)+ def authorize_form(conn, params) do+ with :ok <- rate_limit(conn),+ {:ok, request} <- AuthorizationRequest.build(params) do+ render_consent_form(conn, request)+ else+ {:error, {:rate_limit, _}} -> render_error_page(conn, @rate_limited_message, 429)+ {:redirect_error, request, error} -> redirect_error(conn, request, error)+ {:render_error, message} -> render_error_page(conn, message)+ endend@doc """- Turns the user's approve/deny decision into an- [authorization response](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1#name-authorization-response),- redirecting back to the client with a code or an error.+ Handles the user's approve/deny application form submit, turning it into an+ [authorization response](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1#name-authorization-response).+ It redirects with a code if the approve succeeds. In other cases, it redirects with an error or renders a local error page."""- def authorize(conn, _params) do- not_implemented(conn)+ def authorize(conn, params) do+ user = conn.assigns.current_user++ with :ok <- rate_limit(conn),+ {:ok, request} <- AuthorizationRequest.verify(conn, user, params["signed_request"]) do+ do_authorize(conn, user, request, params)+ else+ {:error, {:rate_limit, _}} -> render_error_page(conn, @rate_limited_message, 429)+ {:error, :invalid_signed_request} -> render_error_page(conn, @unverified_request_message)+ end+ end++ defp do_authorize(conn, user, request, %{"action" => "approve"} = params) do+ case granted_team(conn.assigns, params["team"]) do+ %Plausible.Teams.Team{} = team -> approve(conn, user, team, request)+ nil -> render_error_page(conn, @ungrantable_team_message)+ end+ end++ defp do_authorize(conn, _user, request, _params) do+ redirect_back(conn, request, error: "access_denied")+ end++ defp approve(conn, user, team, request) do+ attrs = %{+ client_id: request.client_id,+ client_name: request.client_name,+ redirect_uri: request.redirect_uri,+ code_challenge: request.code_challenge,+ code_challenge_method: request.code_challenge_method,+ scopes: request.scopes,+ resource: request.resource+ }++ case OAuth.create_authorization_code(user, team, attrs) do+ {:ok, code} -> redirect_back(conn, request, code: code)+ {:error, _} -> redirect_back(conn, request, error: "server_error")+ endend- defp not_implemented(conn) do+ # remove on rollout+ defp require_feature_flag(conn, _opts) do+ if FunWithFlags.enabled?(:mcp, for: conn.assigns.current_user) do+ conn+ else+ conn+ |> put_status(501)+ |> json(%{error: "not_implemented"})+ |> halt()+ end+ end++ defp rate_limit(conn) do+ with :ok <- Auth.rate_limit(:oauth_authorize_ip, conn) do+ Auth.rate_limit(:oauth_authorize_user, conn.assigns.current_user)+ end+ end++ # This currently needs no filtering for role.+ # `Plausible.Auth.UserSessions` preloads memberships with `on: tm.role != :guest`,+ # and `:guest` is the one role `Plausible.OAuth` will not issue a grant for.+ defp grantable_teams(assigns) do+ case assigns[:my_team] do+ nil -> assigns[:teams] || []+ my_team -> [my_team | assigns[:teams] || []]+ end+ end++ defp preselected_team(assigns) do+ teams = grantable_teams(assigns)+ identifier = assigns[:current_team] && assigns[:current_team].identifier++ Enum.find(teams, List.first(teams), &(&1.identifier == identifier))+ end++ defp granted_team(assigns, identifier) do+ Enum.find(grantable_teams(assigns), &(&1.identifier == identifier))+ end++ defp render_consent_form(conn, request) do+ case preselected_team(conn.assigns) do+ nil ->+ render_error_page(conn, @no_team_message)++ selected_team ->+ render(conn, "oauth_authorize.html",+ legacy_layout?: false,+ request: request,+ grantable_teams: grantable_teams(conn.assigns),+ selected_team: selected_team,+ signed_request: AuthorizationRequest.sign(conn, conn.assigns.current_user, request)+ )+ end+ end++ defp render_error_page(conn, message, status \\ 400) doconn- |> put_status(501)- |> json(%{error: "not_implemented"})+ |> put_status(status)+ |> render("oauth_error.html", legacy_layout?: false, message: message)+ end++ defp redirect_error(conn, %{redirect_uri: redirect_uri, state: state}, error) do+ redirect(conn,+ external: AuthorizationResponse.redirect_url(redirect_uri, error: error, state: state)+ )+ end++ defp redirect_back(conn, request, params) do+ redirect(conn,+ external:+ AuthorizationResponse.redirect_url(request.redirect_uri, params ++ [state: request.state])+ )endenddiff --git a/lib/plausible_web/oauth/authorization_request.ex b/lib/plausible_web/oauth/authorization_request.exnew file mode 100644index 0000000000..b8d9d93290--- /dev/null+++ b/lib/plausible_web/oauth/authorization_request.ex@@ -0,0 +1,143 @@+defmodule PlausibleWeb.OAuth.AuthorizationRequest do+ @moduledoc """+ ### Responsibilities++ - parse query params submitted by the application that is requesting for authorization+ - fetch the app's metadata document+ - validate that the document and params make up a valid [authorization request](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1#name-authorization-request)+ - provide utils to ensure that the valid request can be passed through the user's browser, without being tampered with++ """++ alias Plausible.OAuth.CIMD+ alias Plausible.OAuth.ProtectedResources++ @salt "oauth_authorization_request"+ @max_age_seconds 600++ @typedoc "A validated request, sealed for the round trip by `sign/3`."+ @type signed_request() :: String.t()++ @type t() :: %{+ client_id: String.t(),+ client_name: String.t() | nil,+ redirect_uri: String.t(),+ response_type: String.t(),+ code_challenge: String.t(),+ code_challenge_method: String.t(),+ scopes: [String.t()],+ resource: String.t(),+ state: String.t() | nil+ }++ @doc """+ Builds the authorization request from the parameters the client sent.+ It has three possible outcomes:+ - Valid request, application may be trustworthy, show to user to either approve or deny+ - Invalid request, application may be trustworthy, redirect to application with issue+ - Invalid request, application can't be trusted, no redirect, show error to user+ """+ @spec build(map()) ::+ {:ok, t()} | {:redirect_error, map(), String.t()} | {:render_error, String.t()}+ def build(params) do+ unvalidated = unvalidated_request(params)++ with {:ok, metadata} <- fetch_client_metadata(unvalidated.client_id),+ :ok <- validate_redirect_uri(unvalidated.redirect_uri, metadata) do+ validate_request(unvalidated, metadata)+ end+ end++ @doc """+ Encodes and signs the validated authorization request.+ Needed because the data is passed through the user's browser.+ """+ @spec sign(Plug.Conn.t(), Plausible.Auth.User.t(), t()) :: signed_request()+ def sign(conn, user, request) do+ Phoenix.Token.sign(conn, @salt, %{user_id: user.id, request: request})+ end++ @doc """+ Decodes the validated authorization request.++ Fails for one that is missing, tampered with, older than `#{@max_age_seconds}`+ seconds, or signed for a different user.+ """+ @spec verify(Plug.Conn.t(), Plausible.Auth.User.t(), term()) ::+ {:ok, t()} | {:error, :invalid_signed_request}+ def verify(conn, user, signed_request) when is_binary(signed_request) do+ case Phoenix.Token.verify(conn, @salt, signed_request, max_age: @max_age_seconds) do+ {:ok, %{user_id: user_id, request: request}} when user_id == user.id -> {:ok, request}+ _ -> {:error, :invalid_signed_request}+ end+ end++ def verify(_conn, _user, _signed_request), do: {:error, :invalid_signed_request}++ defp unvalidated_request(params) do+ %{+ client_id: params["client_id"],+ redirect_uri: params["redirect_uri"],+ response_type: params["response_type"],+ code_challenge: params["code_challenge"],+ code_challenge_method: params["code_challenge_method"],+ scope: params["scope"],+ resource: params["resource"],+ state: params["state"]+ }+ end++ defp validate_request(unvalidated, metadata) do+ cond do+ unvalidated.response_type != "code" ->+ {:redirect_error, unvalidated, "unsupported_response_type"}++ blank?(unvalidated.code_challenge) ->+ {:redirect_error, unvalidated, "invalid_request"}++ unvalidated.code_challenge_method != "S256" ->+ {:redirect_error, unvalidated, "invalid_request"}++ true ->+ with {:ok, resource} <- ProtectedResources.get_by_url(unvalidated.resource),+ {:ok, scopes} <-+ ProtectedResources.normalize_requested_scopes(unvalidated.scope, resource) do+ {:ok,+ %{+ client_id: unvalidated.client_id,+ redirect_uri: unvalidated.redirect_uri,+ response_type: unvalidated.response_type,+ code_challenge: unvalidated.code_challenge,+ code_challenge_method: unvalidated.code_challenge_method,+ scopes: scopes,+ resource: ProtectedResources.get_resource_url(resource),+ state: unvalidated.state,+ client_name: metadata["client_name"]+ }}+ else+ {:error, :not_found} -> {:redirect_error, unvalidated, "invalid_target"}+ {:error, :invalid_scope} -> {:redirect_error, unvalidated, "invalid_scope"}+ end+ end+ end++ defp fetch_client_metadata(client_id) when is_binary(client_id) and client_id != "" do+ case CIMD.fetch(client_id) do+ {:ok, metadata} -> {:ok, metadata}+ {:error, _} -> {:render_error, "Invalid or unreachable client_id metadata document."}+ end+ end++ defp fetch_client_metadata(_), do: {:render_error, "Missing or invalid client_id."}++ defp validate_redirect_uri(redirect_uri, metadata) do+ if CIMD.redirect_uri_registered?(redirect_uri, metadata["redirect_uris"] || []) do+ :ok+ else+ {:render_error,+ "The redirect_uri does not match any registered redirect URI for this client."}+ end+ end++ defp blank?(value), do: is_nil(value) or value == ""+enddiff --git a/lib/plausible_web/oauth/authorization_response.ex b/lib/plausible_web/oauth/authorization_response.exnew file mode 100644index 0000000000..ca12686729--- /dev/null+++ b/lib/plausible_web/oauth/authorization_response.ex@@ -0,0 +1,30 @@+defmodule PlausibleWeb.OAuth.AuthorizationResponse do+ @moduledoc """+ Builds the [authorization response](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1#name-authorization-response)+ URL the user agent is redirected to, carrying either a code or an error.++ The `redirect_uri` is appended to rather than rebuilt: it has already been+ matched against the client's registered URIs, so its own query - which the+ client is entitled to see back byte for byte - is preserved verbatim.+ """++ @doc """+ Appends response parameters to a validated `redirect_uri`.++ Parameters with a `nil` value are dropped, so an absent `state` does not+ become `state=`.+ """+ @spec redirect_url(String.t(), keyword()) :: String.t()+ def redirect_url(redirect_uri, params) do+ query = params |> Enum.reject(fn {_k, v} -> is_nil(v) end) |> URI.encode_query()+ uri = URI.parse(redirect_uri)++ merged =+ case uri.query do+ empty when empty in [nil, ""] -> query+ existing -> existing <> "&" <> query+ end++ URI.to_string(%{uri | query: merged})+ end+enddiff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.exindex a47f5609d6..9250703ec2 100644--- a/lib/plausible_web/router.ex+++ b/lib/plausible_web/router.ex@@ -476,9 +476,6 @@ defmodule PlausibleWeb.Router doget "/invitation-expired", AuthController, :invitation_expired- get "/login/oauth/authorize", OAuth.AuthorizeController, :authorize_form- post "/login/oauth/authorize", OAuth.AuthorizeController, :authorize-get "/password/request-reset", AuthController, :password_reset_request_formpost "/password/request-reset", AuthController, :password_reset_requestget "/2fa/setup/force-initiate", AuthController, :force_initiate_2fa_setup@@ -497,6 +494,17 @@ defmodule PlausibleWeb.Router dopost "/error_report", ErrorReportController, :submit_error_reportend+ scope "/login/oauth", PlausibleWeb do+ pipe_through [+ :browser,+ :csrf,+ PlausibleWeb.RequireAccountPlug+ ]++ get "/authorize", OAuth.AuthorizeController, :authorize_form+ post "/authorize", OAuth.AuthorizeController, :authorize+ end+scope "/login/oauth", PlausibleWeb dopipe_through :external_apipost "/token", OAuth.TokenController, :tokendiff --git a/lib/plausible_web/templates/auth/oauth_authorize.html.heex b/lib/plausible_web/templates/auth/oauth_authorize.html.heexnew file mode 100644index 0000000000..1c7461f8fa--- /dev/null+++ b/lib/plausible_web/templates/auth/oauth_authorize.html.heex@@ -0,0 +1,88 @@+<Layouts.auth heading="Authorize access" flash={@flash}>+ <.auth_container>+ <div class="flex flex-col gap-y-6">+ <p+ class="text-sm text-gray-600 dark:text-gray-400 text-center"+ data-test-id="client-identity"+ >+ <span class="font-semibold break-all">{@request.client_name || @request.client_id}</span>+ wants to connect to your Plausible account+ <span+ :if={@request.client_name}+ class="block text-xs text-gray-500 dark:text-gray-500 mt-1 break-all"+ >+ Client ID: {@request.client_id}+ </span>+ </p>++ <div class="rounded-md bg-gray-50 dark:bg-gray-900 p-4">+ <p class="text-sm font-semibold text-gray-800 dark:text-gray-200 mb-2">+ This will allow the application to:+ </p>+ <ul class="list-disc list-inside text-sm text-gray-600 dark:text-gray-400 space-y-1">+ <li :for={scope <- @request.scopes}>{Plausible.Auth.Scopes.description(scope)}</li>+ </ul>+ </div>++ <.form+ for={@conn}+ action={~p"/login/oauth/authorize"}+ method="post"+ class="flex flex-col gap-y-4"+ >+ <input type="hidden" name="signed_request" value={@signed_request} />++ <div class="flex flex-col gap-y-2" data-test-id="grant-team">+ <%= if length(@grantable_teams) > 1 do %>+ <label for="team" class="text-sm font-semibold text-gray-800 dark:text-gray-200">+ Grant access to team+ </label>+ <select+ id="team"+ name="team"+ class="block w-full rounded-md border-gray-300 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-100 text-sm"+ >+ <option+ :for={team <- @grantable_teams}+ value={team.identifier}+ selected={team.identifier == @selected_team.identifier}+ >+ {team.name}+ </option>+ </select>+ <% else %>+ <p class="text-sm font-semibold text-gray-800 dark:text-gray-200">+ Grant access to team+ </p>+ <p class="text-sm text-gray-600 dark:text-gray-400 break-all">+ {@selected_team.name}+ </p>+ <input type="hidden" name="team" value={@selected_team.identifier} />+ <% end %>+ <p class="text-xs text-gray-500 dark:text-gray-500">+ The connection will only be able to access the data of the selected team.+ </p>+ </div>++ <div class="flex gap-x-3 mt-2">+ <button+ type="submit"+ name="action"+ value="deny"+ class="btn-base btn-md btn-theme-secondary flex-1"+ >+ Deny+ </button>+ <button+ type="submit"+ name="action"+ value="approve"+ class="btn-base btn-md btn-theme-primary flex-1"+ >+ Approve+ </button>+ </div>+ </.form>+ </div>+ </.auth_container>+</Layouts.auth>diff --git a/lib/plausible_web/templates/auth/oauth_error.html.heex b/lib/plausible_web/templates/auth/oauth_error.html.heexnew file mode 100644index 0000000000..d1e2f0f5dc--- /dev/null+++ b/lib/plausible_web/templates/auth/oauth_error.html.heex@@ -0,0 +1,7 @@+<Layouts.auth heading="Authorization error" subtitle={@message} flash={@flash}>+ <.auth_container class="flex justify-center">+ <.button_link href="/sites" theme="secondary" mt?={false}>+ Back to your sites+ </.button_link>+ </.auth_container>+</Layouts.auth>diff --git a/test/plausible_web/controllers/oauth/authorize_controller_test.exs b/test/plausible_web/controllers/oauth/authorize_controller_test.exsnew file mode 100644index 0000000000..4944c935ca--- /dev/null+++ b/test/plausible_web/controllers/oauth/authorize_controller_test.exs@@ -0,0 +1,741 @@+defmodule PlausibleWeb.OAuth.AuthorizeControllerTest do+ @moduledoc """+ Tests /login/oauth/authorize screen+ """++ use PlausibleWeb.ConnCase+ use Plausible.Test.Support.DNS++ alias Plausible.OAuth.ProtectedResources+ alias Plausible.OAuth.Token++ @client_id "https://client.example.com/oauth-metadata"+ @redirect_uri "https://client.example.com/callback"++ setup %{conn: conn} do+ user = new_user()+ FunWithFlags.enable(:mcp, for_actor: user)+ {:ok, team} = Plausible.Teams.get_or_create(user)+ {:ok, conn: conn} = log_in(%{user: user, conn: conn})++ verifier = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)+ challenge = :crypto.hash(:sha256, verifier) |> Base.url_encode64(padding: false)++ valid_params = %{+ "client_id" => @client_id,+ "redirect_uri" => @redirect_uri,+ "response_type" => "code",+ "code_challenge" => challenge,+ "code_challenge_method" => "S256",+ "scope" => "sites:read:*",+ "state" => "xyz-state",+ "resource" => ProtectedResources.get_resource_url(ProtectedResources.mcp())+ }++ valid_doc = %{+ "client_id" => @client_id,+ "redirect_uris" => [@redirect_uri],+ "client_name" => "Test Client"+ }++ {:ok, conn: conn, user: user, team: team, valid_params: valid_params, valid_doc: valid_doc}+ end++ test "returns 'not_implemented' when the :mcp flag is not enabled for the user", %{+ conn: conn,+ user: user,+ valid_params: valid_params+ } do+ # setup enables it for this user, so it needs disabling here+ FunWithFlags.disable(:mcp, for_actor: user)+ conn = get_authorize(conn, valid_params)+ assert %{"error" => "not_implemented"} == json_response(conn, 501)+ end++ test "redirects to login when unauthenticated, return_to is the expected shape", %{+ valid_params: valid_params+ } do+ conn = build_conn() |> get_authorize(valid_params)++ [base, qs] = String.split(redirected_to(conn), "?")++ assert base == "/login"+ assert_matches ^strict_map(%{"return_to" => return_to}) = URI.decode_query(qs)++ [authorize_path, authorize_qs] = String.split(return_to, "?")++ assert authorize_path == "/login/oauth/authorize"+ assert URI.decode_query(authorize_qs) == valid_params+ end++ test "renders an error page for an unreachable client_id", %{+ conn: conn,+ valid_params: valid_params+ } do+ stub_dns(%{"client.example.com" => {[], []}})++ assert conn |> get_authorize(valid_params) |> html_response(400) =~+ "Authorization error"+ end++ test "refuses an over-long client_name before rendering the consent screen",+ %{conn: conn, valid_params: valid_params, valid_doc: valid_doc} do+ stub_dns()++ stub_metadata(%{valid_doc | "client_name" => String.duplicate("N", 256)})++ assert conn |> get_authorize(valid_params) |> html_response(400) =~+ "Authorization error"+ end++ test "renders an error page for an unregistered redirect_uri", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ params =+ %{valid_params | "redirect_uri" => "https://evil.example.com/callback"}++ assert conn |> get_authorize(params) |> html_response(400) =~ "Authorization error"+ end++ test "redirects back with an error for an unsupported response_type", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ params = %{valid_params | "response_type" => "token"}++ conn = get_authorize(conn, params)++ location = redirected_to(conn, 302)+ [base, qs] = String.split(location, "?")++ assert base == valid_params["redirect_uri"]++ assert_matches ^strict_map(%{+ "error" => "unsupported_response_type",+ "state" => "xyz-state"+ }) = URI.decode_query(qs)+ end++ test "redirects back with an error when PKCE is missing", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ params = %{valid_params | "code_challenge" => ""}++ conn = get_authorize(conn, params)++ location = redirected_to(conn, 302)+ [base, qs] = String.split(location, "?")++ assert base == valid_params["redirect_uri"]++ assert_matches ^strict_map(%{"error" => "invalid_request", "state" => "xyz-state"}) =+ URI.decode_query(qs)+ end++ test "rejects the plain PKCE method", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ params = %{valid_params | "code_challenge_method" => "plain"}++ conn = get_authorize(conn, params)++ location = redirected_to(conn, 302)+ [base, qs] = String.split(location, "?")++ assert base == valid_params["redirect_uri"]++ assert_matches ^strict_map(%{"error" => "invalid_request", "state" => "xyz-state"}) =+ URI.decode_query(qs)+ end++ test "redirects back with an error when resource is omitted", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ params = Map.delete(valid_params, "resource")++ conn = get_authorize(conn, params)++ location = redirected_to(conn, 302)+ [base, qs] = String.split(location, "?")++ assert base == valid_params["redirect_uri"]++ assert_matches ^strict_map(%{"error" => "invalid_target", "state" => "xyz-state"}) =+ URI.decode_query(qs)+ end++ test "redirects back with an error when resource is blank", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ params = %{valid_params | "resource" => ""}++ conn = get_authorize(conn, params)++ location = redirected_to(conn, 302)+ [base, qs] = String.split(location, "?")++ assert base == valid_params["redirect_uri"]++ assert_matches ^strict_map(%{"error" => "invalid_target", "state" => "xyz-state"}) =+ URI.decode_query(qs)+ end++ test "redirects back with invalid_target for an unknown resource", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ params = %{valid_params | "resource" => "https://elsewhere.example.com/mcp"}++ conn = get_authorize(conn, params)++ location = redirected_to(conn, 302)+ [base, qs] = String.split(location, "?")++ assert base == valid_params["redirect_uri"]++ assert_matches ^strict_map(%{"error" => "invalid_target", "state" => "xyz-state"}) =+ URI.decode_query(qs)+ end++ test "redirects back with an error for an unsupported scope", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ params = %{valid_params | "scope" => "stats:read:* admin:write"}++ conn = get_authorize(conn, params)++ location = redirected_to(conn, 302)+ [base, qs] = String.split(location, "?")++ assert base == valid_params["redirect_uri"]++ assert_matches ^strict_map(%{"error" => "invalid_scope", "state" => "xyz-state"}) =+ URI.decode_query(qs)+ end++ test "rate-limits the user, doesn't do a client metadata fetch when over limit", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()++ fetches = stub_metadata(valid_doc)++ statuses = Enum.map(1..30, fn _ -> get_authorize(conn, valid_params).status end)++ # 30 requests fall into at most two one-minute windows of 10+ limits = Enum.count(statuses, &(&1 == 429))+ passes = Enum.count(statuses, &(&1 == 200))++ assert limits >= 10+ assert passes >= 10+ assert :atomics.get(fetches, 1) == passes+ end++ test "renders the consent screen with client and scope details", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ html = conn |> get_authorize(valid_params) |> html_response(200)++ assert html =~ "Authorize access"+ assert html =~ "Test Client"+ assert html =~ "Read the list and details of your sites"+ end++ test "shows the verified client_id alongside the document's chosen client_name",+ %{conn: conn, valid_params: valid_params, valid_doc: valid_doc} do+ stub_dns()+ stub_metadata(valid_doc)++ html = conn |> get_authorize(valid_params) |> html_response(200)+ identity = text_of_element(html, "[data-test-id=client-identity]")++ assert identity =~ "Test Client"+ assert identity =~ valid_params["client_id"]+ end++ test "shows the client_id when the document declares no client_name", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc |> Map.delete("client_name"))++ html = conn |> get_authorize(valid_params) |> html_response(200)++ assert text_of_element(html, "[data-test-id=client-identity]") =~ valid_params["client_id"]+ end++ test "escapes the client_name it renders", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(%{valid_doc | "client_name" => "<script>alert('xss')</script>"})++ html = conn |> get_authorize(valid_params) |> html_response(200)++ refute html =~ "<script>alert"+ assert html =~ "<script>"+ end++ test "shows team name if user has one team", %{+ conn: conn,+ team: team,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ html = conn |> get_authorize(valid_params) |> html_response(200)++ assert html =~ team.name+ refute element_exists?(html, "select#team")++ assert text_of_attr(html, "form input[type=hidden][name=team]", "value") ==+ team.identifier+ end++ test "offers every team the user can grant, personal team included, excludes teams where they are a guest",+ %{+ conn: conn,+ team: team,+ user: user,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ assert team.name =~ "My personal sites"++ {first, second} = grantable_teams(user)++ guest_team = insert(:team, name: "Guest Team", identifier: Ecto.UUID.generate())+ add_member(guest_team, user: user, role: :guest)++ html = conn |> get_authorize(valid_params) |> html_response(200)+ options = text_of_element(html, "select#team")++ assert options =~ "My personal sites"+ assert options =~ first.name+ assert options =~ second.name+ refute options =~ guest_team.name+ end++ test "`__team` param in URL is ignored if it's not one of the user's teams", %{+ conn: conn,+ team: team,+ user: user,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ grantable_teams(user)+ other_team = insert(:team, identifier: Ecto.UUID.generate())+ params = Map.put(valid_params, "__team", other_team.identifier)++ html = conn |> get_authorize(params) |> html_response(200)++ # one of user's own teams is selected+ assert selected_team(html) == team.identifier+ end++ test "preselects the team the user was last working in", %{+ conn: conn,+ user: user,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ {_first, second} = grantable_teams(user)++ conn = get(conn, "/sites?__team=#{second.identifier}")+ assert conn.assigns.current_team.id == second.id++ html = conn |> get_authorize(valid_params) |> html_response(200)++ assert text_of_element(html, "select#team option[selected]") == second.name+ end++ test "approving the application redirects back with a code and the original state query param",+ %{+ conn: conn,+ user: user,+ team: team,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ fetches = stub_metadata(valid_doc)++ html = conn |> get_authorize(valid_params) |> html_response(200)++ conn =+ post_authorize(conn, %{+ "signed_request" => signed_request(html),+ "team" => selected_team(html),+ "action" => "approve"+ })++ # client metadata is fetched exactly once+ assert fetches |> :atomics.get(1) == 1++ [base, qs] = String.split(redirected_to(conn, 302), "?")+ decoded_qs = URI.decode_query(qs)++ assert base == valid_params["redirect_uri"]++ assert_matches ^strict_map(%{+ "code" => ^any(:string, &(&1 != "")),+ "state" => "xyz-state"+ }) = decoded_qs++ assert_matches %{+ code_hash: ^Token.hash(decoded_qs["code"]),+ client_id: ^valid_params["client_id"],+ client_name: ^valid_doc["client_name"],+ redirect_uri: ^valid_params["redirect_uri"],+ resource: ^valid_params["resource"],+ code_challenge: ^valid_params["code_challenge"],+ code_challenge_method: ^valid_params["code_challenge_method"],+ scopes: [^valid_params["scope"]],+ user_id: ^user.id,+ team_id: ^team.id,+ expires_at: ^(&(NaiveDateTime.compare(&1, NaiveDateTime.utc_now()) == :gt))+ } = Plausible.Repo.one!(Plausible.OAuth.AuthorizationCode)+ end++ test "denying redirects back with access_denied and issues no code", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ html = conn |> get_authorize(valid_params) |> html_response(200)++ conn =+ post_authorize(conn, %{+ "signed_request" => signed_request(html),+ "team" => selected_team(html),+ "action" => "deny"+ })++ [base, qs] = String.split(redirected_to(conn, 302), "?")++ assert base == valid_params["redirect_uri"]++ assert_matches ^strict_map(%{"error" => "access_denied", "state" => "xyz-state"}) =+ URI.decode_query(qs)++ assert Plausible.Repo.aggregate(Plausible.OAuth.AuthorizationCode, :count) == 0+ end++ test "redirects with access_denied if no action in submitted", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ html = conn |> get_authorize(valid_params) |> html_response(200)++ conn =+ post_authorize(conn, %{+ "signed_request" => signed_request(html),+ "team" => selected_team(html)+ })++ assert redirected_to(conn, 302) =~ "error=access_denied"+ assert Plausible.Repo.aggregate(Plausible.OAuth.AuthorizationCode, :count) == 0+ end++ test "renders an error page for a signed request that does not verify, issuing no code", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ html = conn |> get_authorize(valid_params) |> html_response(200)++ for signed_request <- [+ nil,+ "",+ "invalid",+ signed_request(html) <> "invalid"+ ] do+ assert conn+ |> post_authorize(%{+ "action" => "approve",+ "team" => selected_team(html),+ "signed_request" => signed_request+ })+ |> html_response(400) =~+ "Authorization error"+ end++ assert Plausible.Repo.aggregate(Plausible.OAuth.AuthorizationCode, :count) == 0+ end++ test "refuses a signed request issued to a different user", %{+ conn: conn,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ other_user = new_user()+ FunWithFlags.enable(:mcp, for_actor: other_user)+ {:ok, _} = Plausible.Teams.get_or_create(other_user)+ {:ok, conn: other_conn} = log_in(%{user: other_user, conn: build_conn() |> prepare_conn()})++ other_html = other_conn |> get_authorize(valid_params) |> html_response(200)++ conn =+ post_authorize(conn, %{+ "signed_request" => signed_request(other_html),+ "team" => selected_team(other_html),+ "action" => "approve"+ })++ assert html_response(conn, 400) =~ "Authorization error"++ assert Plausible.Repo.aggregate(Plausible.OAuth.AuthorizationCode, :count) == 0++ # it works for the other user+ other_conn =+ post_authorize(other_conn, %{+ "signed_request" => signed_request(other_html),+ "team" => selected_team(other_html),+ "action" => "approve"+ })++ assert redirected_to(other_conn, 302)+ end++ test "a user with an unverified email cannot reach the screen, let alone approve",+ %{conn: conn, user: user, valid_params: valid_params} do+ user |> Ecto.Changeset.change(email_verified: false) |> Plausible.Repo.update!()++ conn = get_authorize(conn, valid_params)++ assert redirected_to(conn) == "/activate"+ assert Plausible.Repo.aggregate(Plausible.OAuth.AuthorizationCode, :count) == 0+ end++ test "rate limits a decision before verifying it", %{+ conn: conn,+ user: user,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ html = conn |> get_authorize(valid_params) |> html_response(200)++ Enum.each(1..30, fn _ -> Plausible.Auth.rate_limit(:oauth_authorize_user, user) end)++ # The signature would not verify, so answering 429 rather than 400 is what+ # shows the limiter ran first.+ conn =+ post_authorize(conn, %{+ "signed_request" => signed_request(html) <> "invalid",+ "team" => selected_team(html),+ "action" => "approve"+ })++ assert html_response(conn, 429) =~ "Too many authorization requests"+ end++ test "refuses an approval once the user is over the rate limit", %{+ conn: conn,+ user: user,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ html = conn |> get_authorize(valid_params) |> html_response(200)++ Enum.each(1..30, fn _ -> Plausible.Auth.rate_limit(:oauth_authorize_user, user) end)++ conn =+ post_authorize(conn, %{+ "signed_request" => signed_request(html),+ "team" => selected_team(html),+ "action" => "approve"+ })++ assert html_response(conn, 429) =~ "Too many authorization requests"++ assert Plausible.Repo.aggregate(Plausible.OAuth.AuthorizationCode, :count) == 0+ end++ test "refuses to issue code if there's no team in the payload", %{+ conn: conn,+ user: user,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ grantable_teams(user)++ html = conn |> get_authorize(valid_params) |> html_response(200)++ conn =+ post_authorize(conn, %{+ "signed_request" => signed_request(html),+ "action" => "approve"+ })++ assert html_response(conn, 400) =~ "You cannot grant access to the selected team"+ assert Plausible.Repo.aggregate(Plausible.OAuth.AuthorizationCode, :count) == 0+ end++ test "refuses to issue code to a team that's not one of the user's teams", %{+ conn: conn,+ user: user,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ grantable_teams(user)+ other_team = insert(:team, identifier: Ecto.UUID.generate())++ html = conn |> get_authorize(valid_params) |> html_response(200)++ conn =+ post_authorize(conn, %{+ "signed_request" => signed_request(html),+ "team" => other_team.identifier,+ "action" => "approve"+ })++ assert html_response(conn, 400) =~ "You cannot grant access to the selected team"+ assert Plausible.Repo.aggregate(Plausible.OAuth.AuthorizationCode, :count) == 0+ end++ test "refuses to issue code to a team the user is only a guest on", %{+ conn: conn,+ user: user,+ valid_params: valid_params,+ valid_doc: valid_doc+ } do+ stub_dns()+ stub_metadata(valid_doc)++ guest_team = insert(:team, name: "Guest Team", identifier: Ecto.UUID.generate())+ add_member(guest_team, user: user, role: :guest)++ html = conn |> get_authorize(valid_params) |> html_response(200)++ conn =+ post_authorize(conn, %{+ "signed_request" => signed_request(html),+ "team" => guest_team.identifier,+ "action" => "approve"+ })++ assert html_response(conn, 400) =~ "You cannot grant access to the selected team"+ assert Plausible.Repo.aggregate(Plausible.OAuth.AuthorizationCode, :count) == 0+ end++ defp grantable_teams(user) do+ first = insert(:team, name: "First Team", identifier: Ecto.UUID.generate())+ second = insert(:team, name: "Second Team", identifier: Ecto.UUID.generate())++ add_member(first, user: user, role: :owner)+ add_member(second, user: user, role: :owner)++ {first, second}+ end++ # Returns a counter of how many times the document was fetched.+ defp stub_metadata(doc) do+ counter = :atomics.new(1, [])++ Req.Test.stub(Plausible.OAuth.CIMD, fn conn ->+ :atomics.add_get(counter, 1, 1)+ Plug.Conn.send_resp(conn, 200, Jason.encode!(doc))+ end)++ counter+ end++ defp get_authorize(conn, params),+ do: get(conn, "/login/oauth/authorize?" <> URI.encode_query(params))++ defp post_authorize(conn, params),+ do: post(conn, "/login/oauth/authorize", params)++ defp signed_request(html),+ do: text_of_attr(html, "input[name=signed_request]", "value")++ defp selected_team(html),+ do:+ text_of_attr(html, "select#team option[selected]", "value") ||+ text_of_attr(html, "input[name=team]", "value")+end