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 `SSO.Domains.remove/1,2` and `SSO.Domains.check_can_remove/1` (#5461)
Adrian Gruntkowski0968ed7f2c99
diff --git a/extra/lib/plausible/auth/sso.ex b/extra/lib/plausible/auth/sso.exindex 3d74021d68..b109f380cc 100644--- a/extra/lib/plausible/auth/sso.ex+++ b/extra/lib/plausible/auth/sso.ex@@ -59,14 +59,14 @@ defmodule Plausible.Auth.SSO do| {:error, :multiple_memberships, Teams.Team.t(), Auth.User.t()}def provision_user(identity) docase find_user(identity) do- {:ok, :standard, user, integration} ->- provision_standard_user(user, identity, integration)+ {:ok, :standard, user, integration, domain} ->+ provision_standard_user(user, identity, integration, domain)- {:ok, :sso, user, integration} ->- provision_sso_user(user, identity, integration)+ {:ok, :sso, user, integration, domain} ->+ provision_sso_user(user, identity, integration, domain)- {:ok, :integration, integration} ->- provision_identity(identity, integration)+ {:ok, :integration, _, integration, domain} ->+ provision_identity(identity, integration, domain){:error, :not_found} ->{:error, :integration_not_found}@@ -77,7 +77,7 @@ defmodule Plausible.Auth.SSO dodef deprovision_user!(%{type: :standard} = user), do: userdef deprovision_user!(user) do- user = Repo.preload(user, :sso_integration)+ user = Repo.preload(user, [:sso_integration, :sso_domain]):ok = Auth.UserSessions.revoke_all(user)@@ -86,6 +86,7 @@ defmodule Plausible.Auth.SSO do|> Ecto.Changeset.put_change(:type, :standard)|> Ecto.Changeset.put_change(:sso_identity_id, nil)|> Ecto.Changeset.put_assoc(:sso_integration, nil)+ |> Ecto.Changeset.put_assoc(:sso_domain, nil)|> Repo.update!()end@@ -268,25 +269,28 @@ defmodule Plausible.Auth.SSO dodefp find_user(identity) docase find_user_with_fallback(identity) do- {:ok, type, user, integration} ->- {:ok, type, Repo.preload(user, :sso_integration), integration}+ {:ok, type, user, integration, domain} ->+ {:ok, type, Repo.preload(user, [:sso_integration, :sso_domain]), integration, domain}- error ->+ {:error, _} = error ->errorendenddefp find_user_with_fallback(identity) do- with {:error, :not_found} <- find_by_identity(identity.id) do+ with {:error, :not_found} <- find_by_identity(identity) dofind_by_email(identity.email)endend- defp find_by_identity(id) do- if user = Repo.get_by(Auth.User, sso_identity_id: id) do- user = Repo.preload(user, sso_integration: :team)+ defp find_by_identity(identity) do+ if user = Repo.get_by(Auth.User, sso_identity_id: identity.id, type: :sso) do+ with {:ok, sso_domain} <- SSO.Domains.lookup(identity.email),+ :ok <- check_domain_integration_match(sso_domain, user) do+ user = Repo.preload(user, sso_integration: :team)- {:ok, user.type, user, user.sso_integration}+ {:ok, user.type, user, user.sso_integration, sso_domain}+ endelse{:error, :not_found}end@@ -296,10 +300,10 @@ defmodule Plausible.Auth.SSO dowith {:ok, sso_domain} <- SSO.Domains.lookup(email) docase find_by_email(sso_domain.sso_integration.team, email) do{:ok, user} ->- {:ok, user.type, user, sso_domain.sso_integration}+ {:ok, user.type, user, sso_domain.sso_integration, sso_domain}{:error, :not_found} ->- {:ok, :integration, sso_domain.sso_integration}+ {:ok, :integration, nil, sso_domain.sso_integration, sso_domain}endendend@@ -323,7 +327,15 @@ defmodule Plausible.Auth.SSO doendend- defp provision_sso_user(user, identity, integration) do+ defp check_domain_integration_match(sso_domain, user) do+ if sso_domain.sso_integration_id == user.sso_integration_id do+ :ok+ else+ {:error, :not_found}+ end+ end++ defp provision_sso_user(user, identity, integration, domain) dochangeset =user|> change()@@ -331,13 +343,14 @@ defmodule Plausible.Auth.SSO do|> put_change(:name, identity.name)|> put_change(:sso_identity_id, identity.id)|> put_change(:last_sso_login, NaiveDateTime.utc_now(:second))+ |> put_assoc(:sso_domain, domain)with {:ok, user} <- Repo.update(changeset) do{:ok, :sso, integration.team, user}endend- defp provision_standard_user(user, identity, integration) do+ defp provision_standard_user(user, identity, integration, domain) dochangeset =user|> change()@@ -346,6 +359,7 @@ defmodule Plausible.Auth.SSO do|> put_change(:sso_identity_id, identity.id)|> put_change(:last_sso_login, NaiveDateTime.utc_now(:second))|> put_assoc(:sso_integration, integration)+ |> put_assoc(:sso_domain, domain)with :ok <- ensure_team_member(integration.team, user),:ok <- ensure_one_membership(user, integration.team),@@ -355,7 +369,7 @@ defmodule Plausible.Auth.SSO doendend- defp provision_identity(identity, integration) do+ defp provision_identity(identity, integration, domain) dorandom_password =64|> :crypto.strong_rand_bytes()@@ -375,6 +389,7 @@ defmodule Plausible.Auth.SSO do|> put_change(:sso_identity_id, identity.id)|> put_change(:last_sso_login, NaiveDateTime.utc_now(:second))|> put_assoc(:sso_integration, integration)+ |> put_assoc(:sso_domain, domain)team = integration.teamrole = integration.team.policy.sso_default_rolediff --git a/extra/lib/plausible/auth/sso/domains.ex b/extra/lib/plausible/auth/sso/domains.exindex 5f33752bc4..b459603b3b 100644--- a/extra/lib/plausible/auth/sso/domains.ex+++ b/extra/lib/plausible/auth/sso/domains.ex@@ -5,6 +5,7 @@ defmodule Plausible.Auth.SSO.Domains doimport Ecto.Query+ alias Plausible.Authalias Plausible.Auth.SSOalias Plausible.Repo@@ -59,6 +60,81 @@ defmodule Plausible.Auth.SSO.Domains doendend+ @spec remove(SSO.Domain.t(), Keyword.t()) ::+ :ok | {:error, :force_sso_enabled | :sso_users_present}+ def remove(sso_domain, opts \\ []) do+ force_deprovision? = Keyword.get(opts, :force_deprovision?, false)++ check = check_can_remove(sso_domain)++ case {check, force_deprovision?} do+ {:ok, _} ->+ Repo.delete!(sso_domain)+ :ok++ {{:error, :sso_users_present}, true} ->+ domain_users = users_by_domain(sso_domain)++ {:ok, :ok} =+ Repo.transaction(fn ->+ Enum.each(domain_users, &SSO.deprovision_user!/1)+ Repo.delete!(sso_domain)+ :ok+ end)++ :ok++ {{:error, error}, _} ->+ {:error, error}+ end+ end++ @spec check_can_remove(SSO.Domain.t()) ::+ :ok | {:error, :force_sso_enabled | :sso_users_present}+ def check_can_remove(sso_domain) do+ sso_domain = Repo.preload(sso_domain, sso_integration: [:team, :sso_domains])+ team = sso_domain.sso_integration.team+ domain_users_count = sso_domain |> users_by_domain_query() |> Repo.aggregate(:count)++ integration_users_count =+ sso_domain.sso_integration |> users_by_integration_query() |> Repo.aggregate(:count)++ only_domain_with_users? =+ domain_users_count > 0 and integration_users_count == domain_users_count++ cond do+ team.policy.force_sso != :none and only_domain_with_users? ->+ {:error, :force_sso_enabled}++ domain_users_count > 0 ->+ {:error, :sso_users_present}++ true ->+ :ok+ end+ end++ defp users_by_domain(sso_domain) do+ sso_domain+ |> users_by_domain_query()+ |> Repo.all()+ end++ defp users_by_domain_query(sso_domain) do+ from(+ u in Auth.User,+ where: u.sso_domain_id == ^sso_domain.id+ )+ end++ defp users_by_integration_query(sso_integration) do+ from(+ u in Auth.User,+ where: u.sso_integration_id == ^sso_integration.id,+ where: u.type == :sso+ )+ end+defp normalize_lookup(domain_or_email) dodomain_or_email|> String.split("@", parts: 2)diff --git a/extra/lib/plausible_web/controllers/sso_controller.ex b/extra/lib/plausible_web/controllers/sso_controller.exindex 74c00b316c..00772ee6c0 100644--- a/extra/lib/plausible_web/controllers/sso_controller.ex+++ b/extra/lib/plausible_web/controllers/sso_controller.ex@@ -70,7 +70,7 @@ defmodule PlausibleWeb.SSOController doelse%SSO.Identity{id: Ecto.UUID.generate(),- name: "Some SSO Person",+ name: name_from_email(email),email: email,expires_at: expires_at}@@ -90,4 +90,13 @@ defmodule PlausibleWeb.SSOController doLogger.error(body)conn |> send_resp(200, "OK")end++ defp name_from_email(email) do+ |> String.split("@", parts: 2)+ |> List.first()+ |> String.split(".")+ |> Enum.take(2)+ |> Enum.map_join(" ", &String.capitalize/1)+ endenddiff --git a/lib/plausible/auth/user.ex b/lib/plausible/auth/user.exindex 3d511d1ed5..2bdc0e7ac0 100644--- a/lib/plausible/auth/user.ex+++ b/lib/plausible/auth/user.ex@@ -47,6 +47,7 @@ defmodule Plausible.Auth.User dofield :last_sso_login, :naive_datetimebelongs_to :sso_integration, Plausible.Auth.SSO.Integration, on_replace: :nilify+ belongs_to :sso_domain, Plausible.Auth.SSO.Domain, on_replace: :nilifyendhas_many :sessions, Plausible.Auth.UserSessiondiff --git a/test/plausible/auth/sso/domains_test.exs b/test/plausible/auth/sso/domains_test.exsindex 2f6300d3df..046b64324f 100644--- a/test/plausible/auth/sso/domains_test.exs+++ b/test/plausible/auth/sso/domains_test.exs@@ -11,11 +11,12 @@ defmodule Plausible.Auth.SSO.DomainsTest doalias Plausible.Teamssetup do- team = new_site().team+ owner = new_user(totp_enabled: true, totp_secret: "secret")+ team = new_site(owner: owner).teamintegration = SSO.initiate_saml_integration(team)- {:ok, team: team, integration: integration}+ {:ok, team: team, owner: owner, integration: integration}enddescribe "add/2" do@@ -177,8 +178,134 @@ defmodule Plausible.Auth.SSO.DomainsTest doendend+ describe "check_can_remove/1" do+ setup %{integration: integration} do+ domain = generate_domain()+ {:ok, sso_domain} = SSO.Domains.add(integration, domain)++ {:ok, domain: domain, sso_domain: sso_domain}+ end++ test "returns ok when all conditions met", %{sso_domain: sso_domain} do+ assert :ok = SSO.Domains.remove(sso_domain)++ refute Repo.reload(sso_domain)+ end++ test "returns ok when force SSO enabled and SSO users on other domains present", %{+ team: team,+ integration: integration,+ sso_domain: sso_domain+ } do+ other_domain = generate_domain()+ {:ok, other_sso_domain} = SSO.Domains.add(integration, other_domain)+ _other_sso_domain = SSO.Domains.verify(other_sso_domain, skip_checks?: true)+ other_identity = new_identity("Mary Goodwill", "mary@" <> other_domain)+ {:ok, _, _, _other_sso_user} = SSO.provision_user(other_identity)+ {:ok, _team} = SSO.set_force_sso(team, :all_but_owners)++ sso_domain = Repo.reload!(sso_domain)+ assert :ok = SSO.Domains.check_can_remove(sso_domain)+ end++ test "returns error when force SSO enabled and SSO users only present on current domain", %{+ team: team,+ domain: domain,+ sso_domain: sso_domain+ } do+ sso_domain = SSO.Domains.verify(sso_domain, skip_checks?: true)+ identity = new_identity("Claude Leferge", "claude@" <> domain)+ {:ok, _, _, _sso_user} = SSO.provision_user(identity)+ {:ok, _team} = SSO.set_force_sso(team, :all_but_owners)++ sso_domain = Repo.reload!(sso_domain)+ assert {:error, :force_sso_enabled} = SSO.Domains.check_can_remove(sso_domain)+ end++ test "returns error when SSO users present on current domain", %{+ domain: domain,+ sso_domain: sso_domain+ } do+ sso_domain = SSO.Domains.verify(sso_domain, skip_checks?: true)+ identity = new_identity("Claude Leferge", "claude@" <> domain)+ {:ok, _, _, _sso_user} = SSO.provision_user(identity)++ sso_domain = Repo.reload!(sso_domain)+ assert {:error, :sso_users_present} = SSO.Domains.check_can_remove(sso_domain)+ end+ end++ describe "remove/1,2" do+ setup %{integration: integration} do+ domain = generate_domain()+ {:ok, sso_domain} = SSO.Domains.add(integration, domain)++ {:ok, domain: domain, sso_domain: sso_domain}+ end++ test "removes the domain if conditions met", %{sso_domain: sso_domain} do+ assert :ok = SSO.Domains.remove(sso_domain)+ refute Repo.reload(sso_domain)+ end++ test "fails to remove the domain whenSSO users present on it", %{+ domain: domain,+ sso_domain: sso_domain+ } do+ sso_domain = SSO.Domains.verify(sso_domain, skip_checks?: true)+ identity = new_identity("Claude Leferge", "claude@" <> domain)+ {:ok, _, _, _sso_user} = SSO.provision_user(identity)++ assert {:error, :sso_users_present} = SSO.Domains.remove(sso_domain)+ assert Repo.reload(sso_domain)+ end++ test "removes the domain and deprovisions SSO users when force flag set", %{+ domain: domain,+ sso_domain: sso_domain+ } do+ sso_domain = SSO.Domains.verify(sso_domain, skip_checks?: true)+ identity = new_identity("Claude Leferge", "claude@" <> domain)+ {:ok, _, _, sso_user} = SSO.provision_user(identity)++ assert :ok = SSO.Domains.remove(sso_domain, force_deprovision?: true)+ refute Repo.reload(sso_domain)++ # SSO user is deprovisioned+ sso_user = Repo.reload(sso_user)++ assert sso_user.type == :standard+ refute sso_user.sso_identity_id+ refute sso_user.sso_integration_id+ refute sso_user.sso_domain_id+ end++ test "fails to remove when force SSO enabled with SSO users only on that domain", %{+ team: team,+ domain: domain,+ sso_domain: sso_domain+ } do+ sso_domain = SSO.Domains.verify(sso_domain, skip_checks?: true)+ identity = new_identity("Claude Leferge", "claude@" <> domain)+ {:ok, _, _, _sso_user} = SSO.provision_user(identity)+ {:ok, _} = SSO.set_force_sso(team, :all_but_owners)++ sso_domain = Repo.reload!(sso_domain)+ assert {:error, :force_sso_enabled} = SSO.Domains.check_can_remove(sso_domain)+ end+ end+defp generate_domain() do"example-#{Enum.random(1..10_000)}.com"end++ defp new_identity(name, email, id \\ Ecto.UUID.generate()) do+ %SSO.Identity{+ id: id,+ name: name,+ email: email,+ expires_at: NaiveDateTime.add(NaiveDateTime.utc_now(:second), 6, :hour)+ }+ endendenddiff --git a/test/plausible/auth/sso_test.exs b/test/plausible/auth/sso_test.exsindex 3268e212a9..ddce2e295c 100644--- a/test/plausible/auth/sso_test.exs+++ b/test/plausible/auth/sso_test.exs@@ -179,6 +179,7 @@ defmodule Plausible.Auth.SSOTest dotest "provisions a new SSO user form identity", %{integration: integration,domain: domain,+ sso_domain: sso_domain,team: team} doidentity = new_identity("Jane Sculley", "jane@" <> domain)@@ -192,6 +193,7 @@ defmodule Plausible.Auth.SSOTest doassert user.name == identity.nameassert user.sso_identity_id == identity.idassert user.sso_integration_id == integration.id+ assert user.sso_domain_id == sso_domain.idassert user.email_verifiedassert user.last_sso_loginassert_team_membership(user, team, :viewer)@@ -200,7 +202,8 @@ defmodule Plausible.Auth.SSOTest dotest "provisions SSO user from existing user", %{integration: integration,team: team,- domain: domain+ domain: domain,+ sso_domain: sso_domain} douser = new_user(email: "jane@" <> domain, name: "Jane Sculley")add_member(team, user: user, role: :editor)@@ -220,11 +223,17 @@ defmodule Plausible.Auth.SSOTest doassert sso_user.name == identity.nameassert sso_user.sso_identity_id == identity.idassert sso_user.sso_integration_id == integration.id+ assert sso_user.sso_domain_id == sso_domain.idassert sso_user.email_verifiedassert sso_user.last_sso_loginend- test "provisions existing SSO user", %{integration: integration, team: team, domain: domain} do+ test "provisions existing SSO user", %{+ integration: integration,+ team: team,+ domain: domain,+ sso_domain: sso_domain+ } douser = new_user(email: "jane@" <> domain, name: "Jane Sculley")add_member(team, user: user, role: :editor)identity = new_identity(user.name, user.email)@@ -239,6 +248,7 @@ defmodule Plausible.Auth.SSOTest doassert sso_user.name == identity.nameassert sso_user.sso_identity_id == identity.idassert sso_user.sso_integration_id == integration.id+ assert sso_user.sso_domain_id == sso_domain.idassert sso_user.last_sso_loginend@@ -303,6 +313,23 @@ defmodule Plausible.Auth.SSOTest doassert {:error, :over_limit} = SSO.provision_user(identity)end++ test "does not provision existing SSO user when email domain is not allowlisted", %{+ domain: domain+ } do+ identity = new_identity("Jane Sculley", "jane@" <> domain)++ assert {:ok, _, _, sso_user} = SSO.provision_user(identity)++ identity =+ new_identity(+ "Jane Sculley on New Email",+ "[email protected]",+ sso_user.sso_identity_id+ )++ assert {:error, :integration_not_found} = SSO.provision_user(identity)+ endenddescribe "deprovision_user!/1" do@@ -327,6 +354,7 @@ defmodule Plausible.Auth.SSOTest doassert updated_user.type == :standardrefute updated_user.sso_identity_idrefute updated_user.sso_integration_id+ refute updated_user.sso_domain_idendtest "handles standard user gracefully without revoking existing sessions" do@@ -340,6 +368,7 @@ defmodule Plausible.Auth.SSOTest doassert updated_user.type == :standardrefute updated_user.sso_identity_idrefute updated_user.sso_integration_id+ refute updated_user.sso_domain_idendenddiff --git a/test/plausible_web/controllers/sso_controller_test.exs b/test/plausible_web/controllers/sso_controller_test.exsindex eb04000a4d..3e244ca944 100644--- a/test/plausible_web/controllers/sso_controller_test.exs+++ b/test/plausible_web/controllers/sso_controller_test.exs@@ -122,7 +122,7 @@ defmodule PlausibleWeb.SSOControllerTest dodomain: domain,integration: integration} do- email = "dana@" <> domain+ email = "dana.lake@" <> domainconn =post(conn, Routes.sso_path(conn, :saml_consume, integration.identifier), %{@@ -137,7 +137,7 @@ defmodule PlausibleWeb.SSOControllerTest doassert user.type == :ssoassert user.email == email- assert user.name == "Some SSO Person"+ assert user.name == "Dana Lake"assert get_session(conn, :user_token) == sso_session.tokenend