Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Add connected apps view: lists and allows revoking OAuth grants (#6830)

Artur Pata1b9498c7cd3a
diff --git a/lib/plausible/oauth.ex b/lib/plausible/oauth.ex
index fdcc840402..f3e4b9facf 100644
--- a/lib/plausible/oauth.ex
+++ b/lib/plausible/oauth.ex
@@ -359,6 +359,52 @@ defmodule Plausible.OAuth do
end
end
+ @doc """
+ Lists the grants a user can still use, across all of their teams, with the
+ team preloaded. Revoked grants and grants whose refresh token has expired
+ are left out, since neither can be used anymore.
+
+ Most recently connected grants come first.
+ """
+ @spec list_grants(Plausible.Auth.User.t()) :: [Grant.t()]
+ def list_grants(user) do
+ Repo.all(
+ from(g in Grant,
+ inner_join: t in assoc(g, :team),
+ where:
+ g.user_id == ^user.id and
+ is_nil(g.revoked_at) and
+ g.refresh_token_expires_at > ^now(),
+ order_by: [desc: g.inserted_at, desc: g.id],
+ preload: [team: t]
+ )
+ )
+ end
+
+ @doc """
+ Revokes one of the user's grants by its id.
+
+ Returns `{:error, :not_found}` for an id that doesn't belong to one of the
+ user's live grants, including one that is already revoked.
+ """
+ @spec revoke_user_grant(Plausible.Auth.User.t(), term()) :: :ok | {:error, :not_found}
+ def revoke_user_grant(user, grant_id) do
+ now = now()
+
+ with {id, ""} <- Integer.parse(to_string(grant_id)),
+ {1, _} <-
+ Repo.update_all(
+ from(g in Grant,
+ where: g.id == ^id and g.user_id == ^user.id and is_nil(g.revoked_at)
+ ),
+ set: [revoked_at: now, updated_at: now]
+ ) do
+ :ok
+ else
+ _ -> {:error, :not_found}
+ end
+ end
+
@doc """
Revokes a grant, invalidating its access and refresh tokens.
diff --git a/lib/plausible_web/controllers/settings_controller.ex b/lib/plausible_web/controllers/settings_controller.ex
index b5602bc806..6a69d156c9 100644
--- a/lib/plausible_web/controllers/settings_controller.ex
+++ b/lib/plausible_web/controllers/settings_controller.ex
@@ -24,6 +24,8 @@ defmodule PlausibleWeb.SettingsController do
plug Plausible.Plugs.RestrictUserType,
[deny: :sso] when action in [:update_name, :update_email, :update_password]
+ plug :require_mcp_feature_flag when action in [:connected_apps, :revoke_connected_app]
+
def index(conn, _params) do
redirect(conn, to: ~p"/settings/preferences")
end
@@ -201,6 +203,37 @@ defmodule PlausibleWeb.SettingsController do
end
end
+ def connected_apps(conn, _params) do
+ grants = Plausible.OAuth.list_grants(conn.assigns.current_user)
+
+ render(conn, :connected_apps, layout: {PlausibleWeb.LayoutView, :settings}, grants: grants)
+ end
+
+ def revoke_connected_app(conn, %{"id" => id}) do
+ case Plausible.OAuth.revoke_user_grant(conn.assigns.current_user, id) do
+ :ok ->
+ conn
+ |> put_flash(:success, "Access revoked successfully")
+ |> redirect(to: ~p"/settings/connected-apps#connected-apps")
+
+ {:error, :not_found} ->
+ conn
+ |> put_flash(:error, "Could not find connected app to revoke")
+ |> redirect(to: ~p"/settings/connected-apps#connected-apps")
+ end
+ end
+
+ # remove on rollout
+ defp require_mcp_feature_flag(conn, _opts) do
+ if FunWithFlags.enabled?(:mcp, for: conn.assigns.current_user) do
+ conn
+ else
+ conn
+ |> render_error(404)
+ |> halt()
+ end
+ end
+
def danger_zone(conn, _params) do
solely_owned_teams =
conn.assigns.current_user
diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.ex
index 7ce3519af9..9e121e499d 100644
--- a/lib/plausible_web/router.ex
+++ b/lib/plausible_web/router.ex
@@ -560,6 +560,9 @@ defmodule PlausibleWeb.Router do
post "/api-keys", SettingsController, :create_api_key
delete "/api-keys/:id", SettingsController, :delete_api_key
+ get "/connected-apps", SettingsController, :connected_apps
+ delete "/connected-apps/:id", SettingsController, :revoke_connected_app
+
get "/danger-zone", SettingsController, :danger_zone
get "/team/general", SettingsController, :team_general
diff --git a/lib/plausible_web/templates/settings/connected_apps.html.heex b/lib/plausible_web/templates/settings/connected_apps.html.heex
new file mode 100644
index 0000000000..febdcd1d24
--- /dev/null
+++ b/lib/plausible_web/templates/settings/connected_apps.html.heex
@@ -0,0 +1,54 @@
+<.settings_tiles>
+ <.tile>
+ <:title>
+ <a id="connected-apps">Connected apps</a>
+ </:title>
+ <:subtitle>
+ Applications you have authorized to access your Plausible data.
+ </:subtitle>
+
+ <%= if Enum.empty?(@grants) do %>
+ <div class="flex flex-col items-center justify-center pt-5 pb-6 max-w-md mx-auto">
+ <h3 class="text-center text-base font-medium text-gray-900 dark:text-gray-100 leading-7">
+ No connected apps
+ </h3>
+ <p class="text-center text-sm mt-1 text-gray-500 dark:text-gray-400 leading-5 text-pretty">
+ Applications you authorize to access your Plausible account will appear here.
+ </p>
+ </div>
+ <% else %>
+ <.table rows={@grants}>
+ <:thead>
+ <.th>Application</.th>
+ <.th hide_on_mobile>Team</.th>
+ <.th hide_on_mobile>Connected</.th>
+ <.th invisible>Actions</.th>
+ </:thead>
+
+ <:tbody :let={grant}>
+ <.td max_width="max-w-60" title={grant.client_id}>
+ <span class="block truncate font-medium">{grant.client_name || grant.client_id}</span>
+ <span
+ :if={grant.client_name}
+ class="block truncate text-xs text-gray-500 dark:text-gray-400"
+ >
+ Client ID: {grant.client_id}
+ </span>
+ </.td>
+ <.td hide_on_mobile truncate max_width="max-w-40">
+ {Plausible.Teams.name(grant.team)}
+ </.td>
+ <.td hide_on_mobile>{PlausibleWeb.TextHelpers.format_date(grant.inserted_at)}</.td>
+ <.td actions>
+ <.delete_button
+ method="delete"
+ href={~p"/settings/connected-apps/#{grant.id}"}
+ aria-label={"Revoke access for #{grant.client_name || grant.client_id}"}
+ data-confirm={"Are you sure you want to revoke access for #{grant.client_name || grant.client_id}? The application will need to be authorized again to reconnect."}
+ />
+ </.td>
+ </:tbody>
+ </.table>
+ <% end %>
+ </.tile>
+</.settings_tiles>
diff --git a/lib/plausible_web/views/layout_view.ex b/lib/plausible_web/views/layout_view.ex
index 9ca656a173..fbfd1e7db8 100644
--- a/lib/plausible_web/views/layout_view.ex
+++ b/lib/plausible_web/views/layout_view.ex
@@ -108,6 +108,9 @@ defmodule PlausibleWeb.LayoutView do
if(not Teams.setup?(current_team),
do: %{key: "API keys", value: "api-keys", icon: :api_keys}
),
+ if(FunWithFlags.enabled?(:mcp, for: assigns.current_user),
+ do: %{key: "Connected apps", value: "connected-apps", icon: :link}
+ ),
if(Plausible.Users.type(assigns.current_user) == :standard,
do: %{key: "Danger zone", value: "danger-zone", icon: :exclamation_triangle}
)
diff --git a/test/plausible/oauth_test.exs b/test/plausible/oauth_test.exs
index 5bd02e1aea..7068940fe9 100644
--- a/test/plausible/oauth_test.exs
+++ b/test/plausible/oauth_test.exs
@@ -8,6 +8,8 @@ defmodule Plausible.OAuthTest do
- `Step 3: issue_token/1 and find_access_token/2`: opens a grant from the redeemed code, returns token AND resolves an access token back to its grant
- `Step 4: revoke_grant/1 and after_user_removed_from_team/2` invalidates both tokens
- `Step 5: refresh_token/2` rotates both tokens
+
+ Also covers the connected apps view: `list_grants/1` and `revoke_user_grant/2`.
"""
use Plausible.DataCase
@@ -643,6 +645,87 @@ defmodule Plausible.OAuthTest do
end
end
+ describe "list_grants/1" do
+ test "lists the user's live grants across teams, most recently connected first", %{
+ user: user,
+ team: team
+ } do
+ now = NaiveDateTime.utc_now(:second)
+
+ {:ok, other_team} = Plausible.Teams.get_or_create(new_user())
+ add_member(other_team, user: user, role: :viewer)
+
+ oldest =
+ insert(:oauth_grant,
+ user: user,
+ team: team,
+ inserted_at: NaiveDateTime.add(now, -3, :day)
+ )
+
+ older =
+ insert(:oauth_grant,
+ user: user,
+ team: other_team,
+ inserted_at: NaiveDateTime.add(now, -1, :day)
+ )
+
+ newest = insert(:oauth_grant, user: user, team: team, inserted_at: now)
+
+ assert [first, second, third] = OAuth.list_grants(user)
+ assert first.id == newest.id
+ assert second.id == older.id
+ assert second.team.id == other_team.id
+ assert third.id == oldest.id
+ end
+
+ test "leaves out revoked and expired grants", %{user: user, team: team} do
+ insert(:oauth_grant, user: user, team: team, revoked_at: past())
+ insert(:oauth_grant, user: user, team: team, refresh_token_expires_at: past())
+
+ assert OAuth.list_grants(user) == []
+ end
+
+ test "leaves out other users' grants", %{user: user, team: team} do
+ other_user = add_member(team, role: :editor)
+ insert(:oauth_grant, user: other_user, team: team)
+
+ assert OAuth.list_grants(user) == []
+ end
+ end
+
+ describe "revoke_user_grant/2" do
+ test "revokes the user's grant", %{user: user, team: team} do
+ {grant, access_token} = issue_grant(user, team)
+
+ assert :ok = OAuth.revoke_user_grant(user, to_string(grant.id))
+
+ assert %Grant{revoked_at: %NaiveDateTime{}} = Repo.reload!(grant)
+ assert {:error, :invalid_token} = OAuth.find_access_token(access_token, mcp())
+ end
+
+ test "does not revoke another user's grant", %{team: team} do
+ other_user = add_member(team, role: :editor)
+ grant = insert(:oauth_grant, user: other_user, team: team)
+
+ assert {:error, :not_found} = OAuth.revoke_user_grant(new_user(), grant.id)
+
+ assert %Grant{revoked_at: nil} = Repo.reload!(grant)
+ end
+
+ test "does not find an already revoked grant", %{user: user, team: team} do
+ revoked_at = past()
+ grant = insert(:oauth_grant, user: user, team: team, revoked_at: revoked_at)
+
+ assert {:error, :not_found} = OAuth.revoke_user_grant(user, grant.id)
+
+ assert_matches %Grant{revoked_at: ^revoked_at} = Repo.reload!(grant)
+ end
+
+ test "does not find a malformed id", %{user: user} do
+ assert {:error, :not_found} = OAuth.revoke_user_grant(user, "not-an-id")
+ end
+ end
+
defp pkce do
verifier = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
challenge = :crypto.hash(:sha256, verifier) |> Base.url_encode64(padding: false)
diff --git a/test/plausible_web/controllers/settings_controller/connected_apps_test.exs b/test/plausible_web/controllers/settings_controller/connected_apps_test.exs
new file mode 100644
index 0000000000..abb4778186
--- /dev/null
+++ b/test/plausible_web/controllers/settings_controller/connected_apps_test.exs
@@ -0,0 +1,165 @@
+defmodule PlausibleWeb.SettingsController.ConnectedAppsTest do
+ use PlausibleWeb.ConnCase, async: true
+ use Plausible.Repo
+
+ alias PlausibleWeb.TextHelpers
+
+ describe "DELETE /settings/connected-apps/:id" do
+ setup [:create_user, :log_in, :create_team]
+
+ setup %{user: user} do
+ FunWithFlags.enable(:mcp, for_actor: user)
+ :ok
+ end
+
+ test "returns 404 without the feature flag", %{conn: conn, user: user, team: team} do
+ FunWithFlags.disable(:mcp, for_actor: user)
+ grant = insert(:oauth_grant, user: user, team: team)
+
+ conn = delete(conn, ~p"/settings/connected-apps/#{grant.id}")
+
+ assert html_response(conn, 404)
+ refute Repo.reload!(grant).revoked_at
+ end
+
+ test "revokes the grant", %{conn: conn, user: user, team: team} do
+ grant = insert(:oauth_grant, user: user, team: team)
+
+ conn = delete(conn, ~p"/settings/connected-apps/#{grant.id}")
+
+ assert redirected_to(conn, 302) == ~p"/settings/connected-apps#connected-apps"
+ assert Phoenix.Flash.get(conn.assigns.flash, :success) == "Access revoked successfully"
+ assert Repo.reload!(grant).revoked_at
+ end
+
+ test "user can't revoke a grant that doesn't belong to them", %{conn: conn, team: team} do
+ other_user = add_member(team, role: :editor)
+ grant = insert(:oauth_grant, user: other_user, team: team)
+
+ conn = delete(conn, ~p"/settings/connected-apps/#{grant.id}")
+
+ assert redirected_to(conn, 302) == ~p"/settings/connected-apps#connected-apps"
+
+ assert Phoenix.Flash.get(conn.assigns.flash, :error) ==
+ "Could not find connected app to revoke"
+
+ refute Repo.reload!(grant).revoked_at
+ end
+ end
+
+ describe "GET /settings/connected-apps" do
+ setup [:create_user, :log_in, :create_team]
+
+ setup %{user: user} do
+ FunWithFlags.enable(:mcp, for_actor: user)
+ :ok
+ end
+
+ test "returns 404 without the feature flag", %{conn: conn, user: user} do
+ FunWithFlags.disable(:mcp, for_actor: user)
+
+ conn = get(conn, ~p"/settings/connected-apps")
+
+ assert html_response(conn, 404)
+ end
+
+ test "shows an empty state", %{conn: conn} do
+ conn = get(conn, ~p"/settings/connected-apps")
+
+ assert html = html_response(conn, 200)
+ assert html =~ "No connected apps"
+ end
+
+ test "lists the user's grants, most recently connected first", %{
+ conn: conn,
+ user: user,
+ team: team
+ } do
+ now = NaiveDateTime.utc_now(:second)
+ yesterday = NaiveDateTime.add(now, -1, :day)
+
+ named_grant =
+ insert(:oauth_grant,
+ user: user,
+ team: team,
+ client_name: "Claude",
+ inserted_at: now
+ )
+
+ unnamed_grant =
+ insert(:oauth_grant,
+ user: user,
+ team: team,
+ client_name: nil,
+ inserted_at: yesterday
+ )
+
+ revoked_grant =
+ insert(:oauth_grant,
+ client_name: "revoked grant",
+ user: user,
+ team: team,
+ revoked_at: now
+ )
+
+ expired_grant =
+ insert(:oauth_grant,
+ client_name: "expired grant",
+ user: user,
+ team: team,
+ refresh_token_expires_at: yesterday
+ )
+
+ other_user = add_member(team, role: :editor)
+
+ other_user_grant =
+ insert(:oauth_grant, client_name: "other user grant", user: other_user, team: team)
+
+ conn = get(conn, ~p"/settings/connected-apps")
+
+ assert html = html_response(conn, 200)
+
+ refute html =~ revoked_grant.client_name
+ refute html =~ expired_grant.client_name
+ refute html =~ other_user_grant.client_name
+
+ assert table_rows(html) == [
+ {[
+ [named_grant.client_name, "Client ID: #{named_grant.client_id}"],
+ "My personal sites",
+ TextHelpers.format_date(now),
+ # delete cell has no text
+ ""
+ ], ~p"/settings/connected-apps/#{named_grant.id}"},
+ {[
+ named_grant.client_id,
+ "My personal sites",
+ TextHelpers.format_date(yesterday),
+ ""
+ ], ~p"/settings/connected-apps/#{unnamed_grant.id}"}
+ ]
+ end
+ end
+
+ # Each row's cells and the path its revoke button deletes. A cell with
+ # several lines (spans) is a list of their texts.
+ defp table_rows(html) do
+ html
+ |> find("tbody tr")
+ |> Enum.map(fn row ->
+ delete_link_url = text_of_attr(row, "a[data-method=delete]", "data-to")
+ cells = row |> find("td") |> Enum.map(&cell_contents/1)
+ {cells, delete_link_url}
+ end)
+ end
+
+ defp cell_contents(cell) do
+ spans = cell |> find("span") |> Enum.to_list()
+
+ if length(spans) > 1 do
+ Enum.map(spans, &text/1)
+ else
+ text(cell)
+ end
+ end
+end
diff --git a/test/plausible_web/controllers/settings_controller_test.exs b/test/plausible_web/controllers/settings_controller_test.exs
index 0452a66c24..1cf907edae 100644
--- a/test/plausible_web/controllers/settings_controller_test.exs
+++ b/test/plausible_web/controllers/settings_controller_test.exs
@@ -1452,6 +1452,7 @@ defmodule PlausibleWeb.SettingsControllerTest do
security: {"Security", "/settings/security"},
subscription: {"Subscription", "/settings/billing/subscription"},
api_keys: {"API keys", "/settings/api-keys"},
+ connected_apps: {"Connected apps", "/settings/connected-apps"},
danger_zone: {"Danger zone", "/settings/danger-zone"},
team_general: {"General", "/settings/team/general"},
sso: {"Single Sign-On", "/settings/sso/info"},
@@ -1509,6 +1510,35 @@ defmodule PlausibleWeb.SettingsControllerTest do
end
end
+ describe "Account settings - connected apps" do
+ setup [:create_user, :log_in]
+
+ test "are listed in the account menu with the feature flag", %{conn: conn, user: user} do
+ FunWithFlags.enable(:mcp, for_actor: user)
+
+ conn = get(conn, ~p"/settings/preferences")
+ html = html_response(conn, 200)
+
+ expected_account_menu =
+ if(ee?(),
+ do: [:preferences, :security, :subscription, :api_keys, :connected_apps, :danger_zone],
+ else: [:preferences, :security, :api_keys, :connected_apps, :danger_zone]
+ )
+
+ html
+ |> LazyHTML.from_document()
+ |> assert_sidebar_menu(expected_account_menu)
+ |> assert_mobile_menu(expected_account_menu)
+ end
+
+ test "are not listed without the feature flag", %{conn: conn} do
+ conn = get(conn, ~p"/settings/preferences")
+
+ html_response(conn, 200)
+ |> refute_unexpected_menu_items([:connected_apps])
+ end
+ end
+
describe "Team settings" do
setup [:create_user, :log_in]