Skip to content

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

Implement SSO setup UI (#5473)

Adrian Gruntkowski153702c20f8e
diff --git a/config/runtime.exs b/config/runtime.exs
index c898d54398..323c8e3073 100644
--- a/config/runtime.exs
+++ b/config/runtime.exs
@@ -306,6 +306,12 @@ license_key = get_var_from_path_or_env(config_dir, "LICENSE_KEY", "")
sso_enabled = get_bool_from_path_or_env(config_dir, "SSO_ENABLED", false)
+sso_saml_adapter =
+ case get_var_from_path_or_env(config_dir, "SSO_SAML_ADAPTER", "fake") do
+ "fake" -> PlausibleWeb.SSO.FakeSAMLAdapter
+ "real" -> PlausibleWeb.SSO.RealSAMLAdapter
+ end
+
config :plausible,
environment: env,
mailer_email: mailer_email,
@@ -316,7 +322,8 @@ config :plausible,
license_key: license_key,
data_dir: data_dir,
session_transfer_dir: session_transfer_dir,
- sso_enabled: sso_enabled
+ sso_enabled: sso_enabled,
+ sso_saml_adapter: sso_saml_adapter
config :plausible, :selfhost,
enable_email_verification: enable_email_verification,
diff --git a/extra/lib/plausible/auth/sso.ex b/extra/lib/plausible/auth/sso.ex
index b109f380cc..4f2f216da1 100644
--- a/extra/lib/plausible/auth/sso.ex
+++ b/extra/lib/plausible/auth/sso.ex
@@ -15,14 +15,20 @@ defmodule Plausible.Auth.SSO do
{:sso_default_role, Teams.Policy.sso_member_role()}
| {:sso_session_timeout_minutes, non_neg_integer()}
+ @spec get_integration_for(Teams.Team.t()) :: {:ok, SSO.Integration.t()} | {:error, :not_found}
+ def get_integration_for(%Teams.Team{} = team) do
+ query = integration_query() |> where([i], i.team_id == ^team.id)
+
+ if integration = Repo.one(query) do
+ {:ok, integration}
+ else
+ {:error, :not_found}
+ end
+ end
+
@spec get_integration(String.t()) :: {:ok, SSO.Integration.t()} | {:error, :not_found}
def get_integration(identifier) when is_binary(identifier) do
- query =
- from(i in SSO.Integration,
- inner_join: t in assoc(i, :team),
- where: i.identifier == ^identifier,
- preload: [team: t]
- )
+ query = integration_query() |> where([i], i.identifier == ^identifier)
if integration = Repo.one(query) do
{:ok, integration}
@@ -31,6 +37,16 @@ defmodule Plausible.Auth.SSO do
end
end
+ defp integration_query() do
+ from(i in SSO.Integration,
+ inner_join: t in assoc(i, :team),
+ as: :team,
+ left_join: d in assoc(i, :sso_domains),
+ as: :sso_domains,
+ preload: [team: t, sso_domains: d]
+ )
+ end
+
@spec initiate_saml_integration(Teams.Team.t()) :: SSO.Integration.t()
def initiate_saml_integration(team) do
changeset = SSO.Integration.init_changeset(team)
@@ -96,10 +112,15 @@ defmodule Plausible.Auth.SSO do
params = Map.new(attrs)
policy_changeset = Teams.Policy.update_changeset(team.policy, params)
- team
- |> Ecto.Changeset.change()
- |> Ecto.Changeset.put_embed(:policy, policy_changeset)
- |> Repo.update()
+ changeset =
+ team
+ |> Ecto.Changeset.change()
+ |> Ecto.Changeset.put_embed(:policy, policy_changeset)
+
+ case Repo.update(changeset) do
+ {:ok, integration} -> {:ok, integration}
+ {:error, changeset} -> {:error, changeset.changes.policy}
+ end
end
@spec set_force_sso(Teams.Team.t(), Teams.Policy.force_sso_mode()) ::
diff --git a/extra/lib/plausible/auth/sso/integration.ex b/extra/lib/plausible/auth/sso/integration.ex
index 6fddbc39dc..a5c01d2747 100644
--- a/extra/lib/plausible/auth/sso/integration.ex
+++ b/extra/lib/plausible/auth/sso/integration.ex
@@ -16,6 +16,7 @@ defmodule Plausible.Auth.SSO.Integration do
import PolymorphicEmbed
alias Plausible.Auth.SSO
+ alias Plausible.Teams
@type t() :: %__MODULE__{}
@@ -36,6 +37,12 @@ defmodule Plausible.Auth.SSO.Integration do
timestamps()
end
+ @spec configured?(t()) :: boolean()
+ def configured?(%__MODULE__{config: %config_mod{} = config}) do
+ config_mod.configured?(config)
+ end
+
+ @spec init_changeset(Teams.Team.t()) :: Ecto.Changeset.t()
def init_changeset(team) do
params = %{config: %{__type__: :saml}}
@@ -46,6 +53,7 @@ defmodule Plausible.Auth.SSO.Integration do
|> put_assoc(:team, team)
end
+ @spec update_changeset(t(), map()) :: Ecto.Changeset.t()
def update_changeset(integration, config_params) do
params = tag_params(:saml, config_params)
diff --git a/extra/lib/plausible/auth/sso/saml_config.ex b/extra/lib/plausible/auth/sso/saml_config.ex
index 94774cd719..d5194efa72 100644
--- a/extra/lib/plausible/auth/sso/saml_config.ex
+++ b/extra/lib/plausible/auth/sso/saml_config.ex
@@ -12,6 +12,8 @@ defmodule Plausible.Auth.SSO.SAMLConfig do
use Ecto.Schema
+ alias Plausible.Auth.SSO
+
import Ecto.Changeset
@type t() :: %__MODULE__{}
@@ -26,17 +28,30 @@ defmodule Plausible.Auth.SSO.SAMLConfig do
field :idp_metadata, :string
end
+ @spec configured?(t()) :: boolean()
+ def configured?(config) do
+ !!(config.idp_signin_url && config.idp_entity_id && config.idp_cert_pem)
+ end
+
+ @spec entity_id(SSO.Integration.t()) :: String.t()
+ def entity_id(integration) do
+ PlausibleWeb.Endpoint.url() <> "/sso/" <> integration.identifier
+ end
+
+ @spec changeset(t(), map()) :: Ecto.Changeset.t()
def changeset(struct, params) do
struct
|> cast(params, @fields)
end
+ @spec update_changeset(t(), map()) :: Ecto.Changeset.t()
def update_changeset(struct, params) do
struct
|> cast(params, @fields)
|> validate_required(@required_fields)
|> validate_url(:idp_signin_url)
|> validate_pem(:idp_cert_pem)
+ |> update_change(:idp_entity_id, &String.trim/1)
end
defp validate_url(changeset, field) do
@@ -52,12 +67,23 @@ defmodule Plausible.Auth.SSO.SAMLConfig do
defp validate_pem(changeset, field) do
if pem = get_change(changeset, field) do
+ pem = clean_pem(pem)
+
case X509.Certificate.from_pem(pem) do
- {:ok, _cert} -> changeset
+ {:ok, _cert} -> put_change(changeset, field, pem)
{:error, _} -> add_error(changeset, field, "invalid certificate", validation: :cert_pem)
end
else
changeset
end
end
+
+ defp clean_pem(pem) do
+ pem
+ |> String.split("\n")
+ |> Enum.map(&String.trim/1)
+ |> Enum.reject(&(&1 == ""))
+ |> Enum.join("\n")
+ |> String.trim()
+ end
end
diff --git a/extra/lib/plausible_web/controllers/sso_controller.ex b/extra/lib/plausible_web/controllers/sso_controller.ex
index 00772ee6c0..f56bca8037 100644
--- a/extra/lib/plausible_web/controllers/sso_controller.ex
+++ b/extra/lib/plausible_web/controllers/sso_controller.ex
@@ -3,12 +3,13 @@ defmodule PlausibleWeb.SSOController do
require Logger
- alias Plausible.Auth
alias Plausible.Auth.SSO
- alias Plausible.Repo
alias PlausibleWeb.Router.Helpers, as: Routes
+ plug Plausible.Plugs.AuthorizeTeamAccess,
+ [:owner] when action in [:sso_settings]
+
def login_form(conn, params) do
render(conn, "login_form.html", error: params["error"])
end
@@ -32,57 +33,12 @@ defmodule PlausibleWeb.SSOController do
end
end
- def saml_signin(conn, %{
- "integration_id" => integration_id,
- "email" => email,
- "return_to" => return_to
- }) do
- conn
- |> put_layout(false)
- |> render("saml_signin.html",
- integration_id: integration_id,
- email: email,
- return_to: return_to,
- nonce: conn.private[:sso_nonce]
- )
+ def saml_signin(conn, params) do
+ saml_adapter().signin(conn, params)
end
- def saml_consume(conn, %{
- "integration_id" => integration_id,
- "email" => email,
- "return_to" => return_to
- }) do
- case SSO.get_integration(integration_id) do
- {:ok, integration} ->
- session_timeout_minutes = integration.team.policy.sso_session_timeout_minutes
-
- expires_at =
- NaiveDateTime.add(NaiveDateTime.utc_now(:second), session_timeout_minutes, :minute)
-
- identity =
- if user = Repo.get_by(Auth.User, email: email) do
- %SSO.Identity{
- id: user.sso_identity_id || Ecto.UUID.generate(),
- name: user.name,
- email: email,
- expires_at: expires_at
- }
- else
- %SSO.Identity{
- id: Ecto.UUID.generate(),
- name: name_from_email(email),
- email: email,
- expires_at: expires_at
- }
- end
-
- PlausibleWeb.UserAuth.log_in_user(conn, identity, return_to)
-
- {:error, :not_found} ->
- redirect(conn,
- to: Routes.sso_path(conn, :login_form, error: "Wrong email.", return_to: return_to)
- )
- end
+ def saml_consume(conn, params) do
+ saml_adapter().consume(conn, params)
end
def csp_report(conn, _params) do
@@ -91,12 +47,19 @@ defmodule PlausibleWeb.SSOController do
conn |> send_resp(200, "OK")
end
- defp name_from_email(email) do
- email
- |> String.split("@", parts: 2)
- |> List.first()
- |> String.split(".")
- |> Enum.take(2)
- |> Enum.map_join(" ", &String.capitalize/1)
+ def sso_settings(conn, _params) do
+ if Plausible.Teams.setup?(conn.assigns.current_team) and Plausible.sso_enabled?() do
+ render(conn, :sso_settings,
+ layout: {PlausibleWeb.LayoutView, :settings},
+ connect_live_socket: true
+ )
+ else
+ conn
+ |> redirect(to: Routes.site_path(conn, :index))
+ end
+ end
+
+ defp saml_adapter() do
+ Application.fetch_env!(:plausible, :sso_saml_adapter)
end
end
diff --git a/extra/lib/plausible_web/live/sso_management.ex b/extra/lib/plausible_web/live/sso_management.ex
new file mode 100644
index 0000000000..89b280d214
--- /dev/null
+++ b/extra/lib/plausible_web/live/sso_management.ex
@@ -0,0 +1,691 @@
+defmodule PlausibleWeb.Live.SSOManagement do
+ @moduledoc """
+ Live view for SSO setup and management.
+ """
+ use PlausibleWeb, :live_view
+
+ alias Plausible.Auth.SSO
+ alias Plausible.Teams
+
+ alias PlausibleWeb.Router.Helpers, as: Routes
+
+ @fake_verify_interval :timer.seconds(10)
+
+ def mount(_params, _session, socket) do
+ socket = load_integration(socket, socket.assigns.current_team)
+
+ Process.send_after(self(), :fake_domain_verify, @fake_verify_interval)
+
+ {:ok, route_mode(socket)}
+ end
+
+ def render(assigns) do
+ ~H"""
+ <.flash_messages flash={@flash} />
+
+ <.tile :if={@mode != :manage} docs="sso">
+ <:title>
+ <a id="sso-config">Single Sign-On</a>
+ </:title>
+ <:subtitle>
+ Configure and manage Single Sign-On for your team
+ </:subtitle>
+
+ <.init_view :if={@mode == :init} current_team={@current_team} />
+
+ <.init_setup_view
+ :if={@mode == :init_setup}
+ integration={@integration}
+ current_team={@current_team}
+ />
+
+ <.idp_form_view
+ :if={@mode == :idp_form}
+ integration={@integration}
+ config_changeset={@config_changeset}
+ />
+
+ <.domain_setup_view
+ :if={@mode == :domain_setup}
+ integration={@integration}
+ domain_changeset={@domain_changeset}
+ />
+
+ <.domain_verify_view :if={@mode == :domain_verify} domain={@domain} />
+ </.tile>
+
+ <.manage_view
+ :if={@mode == :manage}
+ integration={@integration}
+ current_team={@current_team}
+ can_toggle_force_sso?={@can_toggle_force_sso?}
+ force_sso_warning={@force_sso_warning}
+ policy_changeset={@policy_changeset}
+ role_options={@role_options}
+ domain_delete_checks={@domain_delete_checks}
+ />
+ """
+ end
+
+ def init_view(assigns) do
+ ~H"""
+ <form id="sso-init" for={} phx-submit="init-sso">
+ <p class="text-sm">Click below to start setting up Single Sign-On for your team.</p>
+
+ <.button type="submit">Start Configuring SSO</.button>
+ </form>
+ """
+ end
+
+ def init_setup_view(assigns) do
+ ~H"""
+ <div class="flex-col space-y-6">
+ <p class="text-sm">
+ Use the following parameters when configuring your Identity Provider of choice:
+ </p>
+
+ <.form id="sso-sp-config" for={} class="flex-col space-y-4">
+ <.input_with_clipboard
+ id="sp-entity-id"
+ name="sp-entity-id"
+ label="Entity ID"
+ value={SSO.SAMLConfig.entity_id(@integration)}
+ />
+
+ <.input_with_clipboard
+ id="sp-acs-url"
+ name="sp-acs-url"
+ label="ACS URL"
+ value={saml_acs_url(@integration)}
+ />
+ </.form>
+
+ <div class="flex-col space-y-3">
+ <p class="text-sm">Following attribute mappings must be setup at Identity Provider:</p>
+
+ <ul role="list" class="list-disc leading-6 text-sm ml-8">
+ <li :for={param <- ["email", "first_name", "last_name"]}>
+ <code>{param}</code>
+ </li>
+ </ul>
+ </div>
+
+ <form id="sso-idp-form" for={} phx-submit="show-idp-form">
+ <p class="text-sm">Click below to start setting up Single Sign-On for your team.</p>
+
+ <.button type="submit">Start Configuring</.button>
+ </form>
+ </div>
+ """
+ end
+
+ def idp_form_view(assigns) do
+ ~H"""
+ <div class="flex-col space-y-6">
+ <p class="text-sm">
+ Enter configuration details of Identity Provider after configuring it:
+ </p>
+
+ <.form
+ :let={f}
+ id="sso-idp-config"
+ for={@config_changeset}
+ class="flex-col space-y-4"
+ phx-submit="update-integration"
+ >
+ <.input field={f[:idp_signin_url]} label="Sign-in URL" placeholder="<URL>" />
+
+ <.input field={f[:idp_entity_id]} label="Entity ID" placeholder="<Entity ID>" />
+
+ <.input field={f[:idp_cert_pem]} type="textarea" label="Certificate in PEM format" />
+
+ <.button type="submit">Save</.button>
+ </.form>
+ </div>
+ """
+ end
+
+ def domain_setup_view(assigns) do
+ ~H"""
+ <div class="flex-col space-y-6">
+ <p class="text-sm">
+ In order for Single Sign-On to work, you have to allow at least one email address domain:
+ </p>
+
+ <.form
+ :let={f}
+ id="sso-add-domain"
+ for={@domain_changeset}
+ class="flex-col space-y-4"
+ phx-submit="add-domain"
+ >
+ <.input field={f[:domain]} label="Domain" placeholder="example.com" />
+
+ <.button type="submit">Add Domain</.button>
+ </.form>
+ </div>
+ """
+ end
+
+ def domain_verify_view(assigns) do
+ ~H"""
+ <div class="flex-col space-y-6">
+ <p class="text-sm">Verifying domain {@domain.domain}</p>
+
+ <p class="text-sm">You can verify the domain using one of 3 methods:</p>
+
+ <ul class="list-disc ml-4 space-y-6">
+ <li>
+ <.input_with_clipboard
+ name="verification-dns-txt"
+ label={"Add a TXT record to #{@domain.domain} domain with the following value"}
+ id="verification-dns-txt"
+ value={"plausible-sso-verification=#{@domain.identifier}"}
+ />
+ </li>
+ <li>
+ <.input_with_clipboard
+ name="verification-url"
+ label={"Publish a file or route at https://#{@domain.domain}/plausible-sso-verification rendering the following contents"}
+ id="verification-url"
+ value={@domain.identifier}
+ />
+ </li>
+ <li>
+ <.input_with_clipboard
+ name="verification-meta-tag"
+ label={"Add a following META tag to the web page at https://#{@domain.domain}"}
+ id="verification-meta-tag"
+ value={~s|<meta name="plausible-sso-verification" content="#{@domain.identifier}">|}
+ />
+ </li>
+ </ul>
+
+ <form id="show-manage" for={} phx-submit="show-manage">
+ <.button type="submit">Continue</.button>
+ </form>
+ </div>
+ """
+ end
+
+ def manage_view(assigns) do
+ ~H"""
+ <.tile docs="sso">
+ <:title>
+ <a id="sso-manage-config">Single Sign-On</a>
+ </:title>
+ <:subtitle>
+ Configure and manage Single Sign-On for your team
+ </:subtitle>
+
+ <div class="flex-col space-y-6">
+ <p class="text-sm">
+ Use the following parameters when configuring your Identity Provider of choice:
+ </p>
+
+ <form id="sso-sp-config" for={} class="flex-col space-y-4">
+ <.input_with_clipboard
+ id="sp-entity-id"
+ name="sp-entity-id"
+ label="Entity ID"
+ value={SSO.SAMLConfig.entity_id(@integration)}
+ />
+
+ <.input_with_clipboard
+ id="sp-acs-url"
+ name="sp-acs-url"
+ label="ACS URL"
+ value={saml_acs_url(@integration)}
+ />
+ </form>
+
+ <div class="flex-col space-y-3">
+ <p class="text-sm">Following attribute mappings must be setup at Identity Provider:</p>
+
+ <ul role="list" class="list-disc leading-6 text-sm ml-8">
+ <li :for={param <- ["email", "first_name", "last_name"]}>
+ <code>{param}</code>
+ </li>
+ </ul>
+ </div>
+
+ <div class="flex-col space-y-3">
+ <p class="text-sm">
+ Current Identity Provider configuration:
+ </p>
+
+ <.form :let={f} id="sso-idp-config" for={} class="flex-col space-y-4">
+ <.input
+ field={f[:idp_signin_url]}
+ value={@integration.config.idp_signin_url}
+ label="Sign-in URL"
+ readonly={true}
+ />
+
+ <.input
+ field={f[:idp_entity_id]}
+ value={@integration.config.idp_entity_id}
+ label="Entity ID"
+ readonly={true}
+ />
+
+ <.input
+ field={f[:idp_cert_pem]}
+ type="textarea"
+ label="Certificate in PEM format"
+ value={@integration.config.idp_cert_pem}
+ readonly={true}
+ />
+ </.form>
+
+ <form id="show-idp-form" for={} phx-submit="show-idp-form">
+ <.button type="submit">Edit</.button>
+ </form>
+ </div>
+ </div>
+ </.tile>
+
+ <.tile docs="sso">
+ <:title>
+ <a id="sso-domains-config">SSO Domains</a>
+ </:title>
+ <:subtitle>
+ Email domains accepted from Identity Provider
+ </:subtitle>
+ <div class="flex-col space-y-3">
+ <.table rows={@integration.sso_domains}>
+ <:thead>
+ <.th>Domain</.th>
+ <.th>Added at</.th>
+ <.th>Status</.th>
+ <.th invisible>Actions</.th>
+ </:thead>
+ <:tbody :let={domain}>
+ <.td>{domain.domain}</.td>
+ <.td>{Calendar.strftime(domain.inserted_at, "%b %-d, %Y at %H:%m UTC")}</.td>
+ <.td>{domain.status}</.td>
+ <.td actions>
+ <.styled_link
+ id={"verify-domain-#{domain.identifier}"}
+ phx-click="verify-domain"
+ phx-value-identifier={domain.identifier}
+ >
+ Verify
+ </.styled_link>
+
+ <.delete_button
+ :if={is_nil(@domain_delete_checks[domain.identifier])}
+ id={"remove-domain-#{domain.identifier}"}
+ phx-click="remove-domain"
+ phx-value-identifier={domain.identifier}
+ class="text-sm text-red-600"
+ data-confirm={"Are you sure you want to remove domain '#{domain.domain}'?"}
+ />
+
+ <.delete_button
+ :if={@domain_delete_checks[domain.identifier]}
+ id={"disabled-remove-domain-#{domain.identifier}"}
+ class="text-sm text-red-600"
+ data-confirm={"You cannot delete this domain. #{@domain_delete_checks[domain.identifier]}"}
+ />
+ </.td>
+ </:tbody>
+ </.table>
+
+ <form id="show-domain-setup" for={} phx-submit="show-domain-setup">
+ <.button type="submit">Add Domain</.button>
+ </form>
+ </div>
+ </.tile>
+
+ <.tile docs="sso">
+ <:title>
+ <a id="sso-policy-config">SSO Policy</a>
+ </:title>
+ <:subtitle>
+ Adjust your SSO policy configuration
+ </:subtitle>
+ <div
+ x-data={Jason.encode!(%{active: @current_team.policy.force_sso == :all_but_owners})}
+ class="flex-col space-y-3"
+ >
+ <p class="text-sm">Enforce Single Sign-On for the whole team, except Owners:</p>
+
+ <.tooltip enabled?={not @can_toggle_force_sso?}>
+ <:tooltip_content>
+ <div class="text-xs">
+ To get access to this feature, {@force_sso_warning}.
+ </div>
+ </:tooltip_content>
+ <div class="flex itemx-center mb-3">
+ <PlausibleWeb.Components.Generic.toggle_switch
+ id="enable-force-sso"
+ id_suffix="toggle"
+ js_active_var="active"
+ disabled={not @can_toggle_force_sso?}
+ phx-click="toggle-force-sso"
+ />
+ <span class={[
+ "ml-3 text-sm font-medium",
+ if(@can_toggle_force_sso?,
+ do: "text-gray-900 dark:text-gray-100",
+ else: "text-gray-500 dark:text-gray-400"
+ )
+ ]}>
+ Force Single Sign-On
+ </span>
+ </div>
+ </.tooltip>
+ </div>
+
+ <div class="flex-col space-y-3">
+ <.form
+ :let={f}
+ id="sso-policy"
+ for={@policy_changeset}
+ class="flex-col space-y-4"
+ phx-submit="update-policy"
+ >
+ <.input
+ field={f[:sso_default_role]}
+ label="Default role"
+ type="select"
+ options={@role_options}
+ />
+
+ <.input
+ field={f[:sso_session_timeout_minutes]}
+ label="Session timeout (minutes)"
+ type="number"
+ />
+
+ <.button type="submit">Update</.button>
+ </.form>
+ </div>
+ </.tile>
+ """
+ end
+
+ def handle_event("init-sso", _params, socket) do
+ team = socket.assigns.current_team
+ integration = SSO.initiate_saml_integration(team)
+
+ socket =
+ socket
+ |> assign(:integration, integration)
+ |> load_integration(team)
+ |> route_mode()
+
+ {:noreply, socket}
+ end
+
+ def handle_event("show-idp-form", _params, socket) do
+ {:noreply, route_mode(socket, :idp_form)}
+ end
+
+ def handle_event("update-integration", params, socket) do
+ socket =
+ case SSO.update_integration(socket.assigns.integration, params["saml_config"] || %{}) do
+ {:ok, integration} ->
+ socket
+ |> assign(:integration, integration)
+ |> load_integration(socket.assigns.current_team)
+ |> route_mode()
+
+ {:error, changeset} ->
+ assign(socket, :config_changeset, changeset)
+ end
+
+ {:noreply, socket}
+ end
+
+ def handle_event("add-domain", params, socket) do
+ integration = socket.assigns.integration
+
+ socket =
+ case SSO.Domains.add(integration, params["domain"]["domain"] || "") do
+ {:ok, sso_domain} ->
+ socket
+ |> load_integration(socket.assigns.current_team)
+ |> assign(:domain, sso_domain)
+ |> route_mode(:domain_verify)
+
+ {:error, changeset} ->
+ socket
+ |> assign(:domain_changeset, changeset)
+ end
+
+ {:noreply, socket}
+ end
+
+ def handle_event("show-manage", _params, socket) do
+ {:noreply, route_mode(socket, :manage)}
+ end
+
+ def handle_event("show-domain-setup", _params, socket) do
+ {:noreply, route_mode(socket, :domain_setup)}
+ end
+
+ def handle_event("verify-domain", params, socket) do
+ integration = socket.assigns.integration
+ domain = Enum.find(integration.sso_domains, &(&1.identifier == params["identifier"]))
+
+ if domain do
+ socket =
+ socket
+ |> load_integration(socket.assigns.current_team)
+ |> assign(:domain, domain)
+ |> route_mode(:domain_verify)
+
+ {:noreply, socket}
+ else
+ {:noreply, route_mode(socket, :manage)}
+ end
+ end
+
+ def handle_event("remove-domain", params, socket) do
+ integration = socket.assigns.integration
+ domain = Enum.find(integration.sso_domains, &(&1.identifier == params["identifier"]))
+
+ if domain do
+ socket =
+ case SSO.Domains.remove(domain) do
+ :ok ->
+ socket
+ |> load_integration(socket.assigns.current_team)
+ |> route_mode()
+
+ {:error, :force_sso_enabled} ->
+ socket
+
+ {:error, :sso_users_present} ->
+ socket
+ end
+
+ {:noreply, socket}
+ else
+ {:noreply, route_mode(socket, :manage)}
+ end
+ end
+
+ def handle_event("toggle-force-sso", _params, socket) do
+ team = socket.assigns.current_team
+ new_toggle = if team.policy.force_sso == :none, do: :all_but_owners, else: :none
+
+ case SSO.set_force_sso(socket.assigns.current_team, new_toggle) do
+ {:ok, team} ->
+ socket =
+ socket
+ |> assign(:current_team, team)
+
+ {:noreply, socket}
+
+ {:error, _} ->
+ {:noreply, route_mode(socket, :manage)}
+ end
+ end
+
+ def handle_event("update-policy", params, socket) do
+ team = socket.assigns.current_team
+ params = params["policy"]
+
+ attrs = [
+ sso_default_role: params["sso_default_role"],
+ sso_session_timeout_minutes: params["sso_session_timeout_minutes"]
+ ]
+
+ socket =
+ case SSO.update_policy(team, attrs) do
+ {:ok, team} ->
+ policy_changeset = Teams.Policy.update_changeset(team.policy, %{})
+
+ socket
+ |> assign(:current_team, team)
+ |> assign(:policy_changeset, policy_changeset)
+
+ {:error, changeset} ->
+ socket
+ |> assign(:policy_changeset, changeset)
+ end
+
+ {:noreply, socket}
+ end
+
+ def handle_info(:fake_domain_verify, %{assigns: %{integration: integration}} = socket)
+ when not is_nil(integration) do
+ sso_domains =
+ integration.sso_domains
+ |> Enum.map(fn domain ->
+ if domain.status == :pending do
+ SSO.Domains.verify(domain, skip_checks?: true)
+ else
+ domain
+ end
+ end)
+
+ Process.send_after(self(), :fake_domain_verify, @fake_verify_interval)
+
+ integration = %{integration | sso_domains: sso_domains}
+
+ {:noreply, assign(socket, :integration, integration)}
+ end
+
+ def handle_info(:fake_domain_verify, socket) do
+ Process.send_after(self(), :fake_domain_verify, @fake_verify_interval)
+
+ {:noreply, socket}
+ end
+
+ defp load_integration(socket, team) do
+ integration =
+ case SSO.get_integration_for(team) do
+ {:ok, integration} -> integration
+ {:error, :not_found} -> nil
+ end
+
+ assign(socket, :integration, integration)
+ end
+
+ defp route_mode(socket, force_mode \\ nil) do
+ integration = socket.assigns.integration
+
+ mode =
+ cond do
+ force_mode ->
+ force_mode
+
+ is_nil(integration) ->
+ :init
+
+ not SSO.Integration.configured?(integration) ->
+ :init_setup
+
+ integration.sso_domains == [] ->
+ :domain_setup
+
+ true ->
+ :manage
+ end
+
+ socket
+ |> assign(:mode, mode)
+ |> load(mode)
+ end
+
+ defp load(socket, :idp_form) do
+ assign(
+ socket,
+ :config_changeset,
+ SSO.SAMLConfig.changeset(socket.assigns.integration.config, %{})
+ )
+ end
+
+ defp load(socket, :domain_setup) do
+ assign(socket, :domain_changeset, SSO.Domain.create_changeset(socket.assigns.integration, ""))
+ end
+
+ defp load(socket, :manage) do
+ team = socket.assigns.current_team
+ toggle_mode = if team.policy.force_sso == :none, do: :all_but_owners, else: :none
+
+ {can_toggle_force_sso?, toggle_disabled_reason} =
+ case SSO.check_force_sso(team, toggle_mode) do
+ :ok ->
+ {true, nil}
+
+ {:error, :no_integration} ->
+ {false, "you must first setup Single Sign-on"}
+
+ {:error, :no_domain} ->
+ {false, "you must add a domain"}
+
+ {:error, :no_verified_domain} ->
+ {false, "you must verify a domain"}
+
+ {:error, :owner_mfa_disabled} ->
+ {false, "all Owners must have MFA enabled"}
+
+ {:error, :no_sso_user} ->
+ {false, "at least one SSO user must log in successfully"}
+ end
+
+ policy_changeset = Teams.Policy.update_changeset(team.policy, %{})
+
+ role_options =
+ Enum.map(Teams.Policy.sso_member_roles(), fn role ->
+ {String.capitalize(to_string(role)), role}
+ end)
+ |> Enum.sort()
+
+ domain_delete_checks =
+ Enum.into(socket.assigns.integration.sso_domains, %{}, fn domain ->
+ prevent_delete_reason =
+ case Plausible.Auth.SSO.Domains.check_can_remove(domain) do
+ :ok -> nil
+ {:error, :force_sso_enabled} -> "You must disable 'Force SSO' first."
+ {:error, :sso_users_present} -> "There are existing SSO accounts on this domain."
+ end
+
+ {domain.identifier, prevent_delete_reason}
+ end)
+
+ socket
+ |> assign(:domain_delete_checks, domain_delete_checks)
+ |> assign(:can_toggle_force_sso?, can_toggle_force_sso?)
+ |> assign(:force_sso_warning, toggle_disabled_reason)
+ |> assign(:policy_changeset, policy_changeset)
+ |> assign(:role_options, role_options)
+ end
+
+ defp load(socket, _) do
+ socket
+ end
+
+ defp saml_acs_url(integration) do
+ Routes.sso_url(
+ PlausibleWeb.Endpoint,
+ :saml_consume,
+ integration.identifier
+ )
+ end
+end
diff --git a/extra/lib/plausible_web/sso/fake_saml_adapter.ex b/extra/lib/plausible_web/sso/fake_saml_adapter.ex
new file mode 100644
index 0000000000..0e2033d6fb
--- /dev/null
+++ b/extra/lib/plausible_web/sso/fake_saml_adapter.ex
@@ -0,0 +1,69 @@
+defmodule PlausibleWeb.SSO.FakeSAMLAdapter do
+ @moduledoc """
+ Fake implementation of SAML authentication interface.
+ """
+
+ alias Plausible.Auth
+ alias Plausible.Auth.SSO
+ alias Plausible.Repo
+
+ alias PlausibleWeb.Router.Helpers, as: Routes
+
+ def signin(conn, params) do
+ conn
+ |> Phoenix.Controller.put_layout(false)
+ |> Phoenix.Controller.render("saml_signin.html",
+ integration_id: params["integration_id"],
+ email: params["email"],
+ return_to: params["return_to"],
+ nonce: conn.private[:sso_nonce]
+ )
+ end
+
+ def consume(conn, params) do
+ case SSO.get_integration(params["integration_id"]) do
+ {:ok, integration} ->
+ session_timeout_minutes = integration.team.policy.sso_session_timeout_minutes
+
+ expires_at =
+ NaiveDateTime.add(NaiveDateTime.utc_now(:second), session_timeout_minutes, :minute)
+
+ identity =
+ if user = Repo.get_by(Auth.User, email: params["email"]) do
+ %SSO.Identity{
+ id: user.sso_identity_id || Ecto.UUID.generate(),
+ name: user.name,
+ email: user.email,
+ expires_at: expires_at
+ }
+ else
+ %SSO.Identity{
+ id: Ecto.UUID.generate(),
+ name: name_from_email(params["email"]),
+ email: params["email"],
+ expires_at: expires_at
+ }
+ end
+
+ PlausibleWeb.UserAuth.log_in_user(conn, identity, params["return_to"])
+
+ {:error, :not_found} ->
+ Phoenix.Controller.redirect(conn,
+ to:
+ Routes.sso_path(conn, :login_form,
+ error: "Wrong email.",
+ return_to: params["return_to"]
+ )
+ )
+ end
+ end
+
+ defp name_from_email(email) do
+ email
+ |> String.split("@", parts: 2)
+ |> List.first()
+ |> String.split(".")
+ |> Enum.take(2)
+ |> Enum.map_join(" ", &String.capitalize/1)
+ end
+end
diff --git a/extra/lib/plausible_web/templates/sso/sso_settings.html.heex b/extra/lib/plausible_web/templates/sso/sso_settings.html.heex
new file mode 100644
index 0000000000..f650b95f74
--- /dev/null
+++ b/extra/lib/plausible_web/templates/sso/sso_settings.html.heex
@@ -0,0 +1,3 @@
+<.settings_tiles>
+ {live_render(@conn, PlausibleWeb.Live.SSOManagement, id: "sso-management")}
+</.settings_tiles>
diff --git a/lib/plausible/teams/policy.ex b/lib/plausible/teams/policy.ex
index 56e5db7447..e35d3912ce 100644
--- a/lib/plausible/teams/policy.ex
+++ b/lib/plausible/teams/policy.ex
@@ -41,6 +41,9 @@ defmodule Plausible.Teams.Policy do
field :sso_session_timeout_minutes, :integer, default: @default_timeout_minutes
end
+ @spec sso_member_roles() :: [sso_member_role()]
+ def sso_member_roles(), do: @sso_member_roles
+
@spec update_changeset(t(), map()) :: Ecto.Changeset.t()
def update_changeset(policy, params) do
policy
diff --git a/lib/plausible_web/components/generic.ex b/lib/plausible_web/components/generic.ex
index 57de8d3cf6..4503f7ba89 100644
--- a/lib/plausible_web/components/generic.ex
+++ b/lib/plausible_web/components/generic.ex
@@ -404,6 +404,8 @@ defmodule PlausibleWeb.Components.Generic do
attr :id_suffix, :string, default: ""
attr :disabled, :boolean, default: false
+ attr(:rest, :global)
+
def toggle_switch(assigns) do
~H"""
<button
@@ -415,6 +417,7 @@ defmodule PlausibleWeb.Components.Generic do
x-on:click={"#{@js_active_var} = !#{@js_active_var}"}
x-bind:aria-checked={@js_active_var}
disabled={@disabled}
+ {@rest}
>
<span
class="relative inline-flex h-6 w-11 flex-shrink-0 rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none focus:ring-2 focus:ring-indigo-600 focus:ring-offset-2"
diff --git a/lib/plausible_web/controllers/settings_controller.ex b/lib/plausible_web/controllers/settings_controller.ex
index 5d0c2b5852..1c0da88beb 100644
--- a/lib/plausible_web/controllers/settings_controller.ex
+++ b/lib/plausible_web/controllers/settings_controller.ex
@@ -1,5 +1,6 @@
defmodule PlausibleWeb.SettingsController do
use PlausibleWeb, :controller
+ use Plausible
use Plausible.Repo
alias Plausible.Auth
diff --git a/lib/plausible_web/live/components/form.ex b/lib/plausible_web/live/components/form.ex
index 064a6561df..e8a379b2a9 100644
--- a/lib/plausible_web/live/components/form.ex
+++ b/lib/plausible_web/live/components/form.ex
@@ -151,8 +151,8 @@ defmodule PlausibleWeb.Live.Components.Form do
def input(%{type: "textarea"} = assigns) do
~H"""
- <div class="mt-2">
- <.label for={@id}>{@label}</.label>
+ <div class={@mt? && "mt-2"}>
+ <.label class="mb-2" for={@id}>{@label}</.label>
<textarea
id={@id}
rows="6"
diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.ex
index 704ce9a3d3..3d4f04cd0a 100644
--- a/lib/plausible_web/router.ex
+++ b/lib/plausible_web/router.ex
@@ -152,6 +152,9 @@ defmodule PlausibleWeb.Router do
plug :fetch_session
plug :fetch_live_flash
+ end
+
+ pipeline :sso_saml_auth do
plug :protect_from_forgery, with: :clear_session
end
@@ -165,7 +168,12 @@ defmodule PlausibleWeb.Router do
scope "/sso/saml", PlausibleWeb do
pipe_through [PlausibleWeb.Plugs.GateSSO, :sso_saml]
- get "/signin/:integration_id", SSOController, :saml_signin
+ scope [] do
+ pipe_through :sso_saml_auth
+
+ get "/signin/:integration_id", SSOController, :saml_signin
+ end
+
post "/consume/:integration_id", SSOController, :saml_consume
post "/csp-report", SSOController, :csp_report
end
@@ -445,6 +453,11 @@ defmodule PlausibleWeb.Router do
get "/team/general", SettingsController, :team_general
post "/team/general/name", SettingsController, :update_team_name
+
+ on_ee do
+ get "/sso/general", SSOController, :sso_settings
+ end
+
post "/team/invitations/:invitation_id/accept", InvitationController, :accept_invitation
post "/team/invitations/:invitation_id/reject", InvitationController, :reject_invitation
delete "/team/invitations/:invitation_id", InvitationController, :remove_team_invitation
diff --git a/lib/plausible_web/views/layout_view.ex b/lib/plausible_web/views/layout_view.ex
index 6d1021cb48..ffe2d4d428 100644
--- a/lib/plausible_web/views/layout_view.ex
+++ b/lib/plausible_web/views/layout_view.ex
@@ -133,6 +133,9 @@ defmodule PlausibleWeb.LayoutView do
if(current_team_role in [:owner, :billing, :admin, :editor],
do: %{key: "API Keys", value: "api-keys", icon: :key}
),
+ if(Plausible.sso_enabled?() and current_team_role == :owner,
+ do: %{key: "Single Sign-On", value: "sso/general", icon: :cloud}
+ ),
if(current_team_role == :owner,
do: %{key: "Danger Zone", value: "team/delete", icon: :exclamation_triangle}
)
diff --git a/test/plausible/auth/sso_test.exs b/test/plausible/auth/sso_test.exs
index ddce2e295c..76d676ef7e 100644
--- a/test/plausible/auth/sso_test.exs
+++ b/test/plausible/auth/sso_test.exs
@@ -73,13 +73,40 @@ defmodule Plausible.Auth.SSOTest do
assert {:ok, integration} =
SSO.update_integration(integration, %{
idp_signin_url: "https://example.com",
- idp_entity_id: "some-entity",
+ idp_entity_id: " some-entity ",
idp_cert_pem: @cert_pem
})
assert integration.config.idp_signin_url == "https://example.com"
assert integration.config.idp_entity_id == "some-entity"
- assert integration.config.idp_cert_pem == @cert_pem
+
+ assert X509.Certificate.from_pem(integration.config.idp_cert_pem) ==
+ X509.Certificate.from_pem(@cert_pem)
+ end
+
+ test "updates integration with whitespace around PEM" do
+ malformed_pem =
+ @cert_pem
+ |> String.split("\n")
+ |> Enum.map_join("\n\n", &(" " <> &1 <> " "))
+
+ team = new_site().team
+ integration = SSO.initiate_saml_integration(team)
+
+ assert {:ok, integration} =
+ SSO.update_integration(integration, %{
+ idp_signin_url: "https://example.com",
+ idp_entity_id: "some-entity",
+ idp_cert_pem: malformed_pem
+ })
+
+ assert integration.config.idp_signin_url == "https://example.com"
+ assert integration.config.idp_entity_id == "some-entity"
+
+ assert integration.config.idp_cert_pem == String.trim(@cert_pem)
+
+ assert X509.Certificate.from_pem(integration.config.idp_cert_pem) ==
+ X509.Certificate.from_pem(@cert_pem)
end
test "optionally accepts metadata" do
@@ -401,6 +428,18 @@ defmodule Plausible.Auth.SSOTest do
assert team.policy.sso_default_role == :editor
assert team.policy.sso_session_timeout_minutes == 360
end
+
+ test "returns changeset on invalid input" do
+ team = new_site().team
+
+ assert {:error, changeset} =
+ SSO.update_policy(team, sso_session_timeout_minutes: "1024000005")
+
+ assert %{sso_session_timeout_minutes: [:number]} =
+ Ecto.Changeset.traverse_errors(changeset, fn {_msg, opts} ->
+ opts[:validation]
+ end)
+ end
end
describe "check_force_sso/2" do
diff --git a/test/plausible_web/controllers/sso_controller_sync_test.exs b/test/plausible_web/controllers/sso_controller_sync_test.exs
index eb37966129..9132f4a64e 100644
--- a/test/plausible_web/controllers/sso_controller_sync_test.exs
+++ b/test/plausible_web/controllers/sso_controller_sync_test.exs
@@ -1,61 +1,91 @@
defmodule PlausibleWeb.SSOControllerSyncTest do
use PlausibleWeb.ConnCase
+ use Plausible.Teams.Test
+
@moduletag :ee_only
on_ee do
- setup do
- patch_env(:sso_enabled, false)
- end
+ describe "sso_enabled = false" do
+ setup do
+ patch_env(:sso_enabled, false)
+ end
- test "standard login form does not show link to SSO login", %{conn: conn} do
- conn = get(conn, Routes.auth_path(conn, :login_form))
+ test "standard login form does not show link to SSO login", %{conn: conn} do
+ conn = get(conn, Routes.auth_path(conn, :login_form))
- assert html = html_response(conn, 200)
+ assert html = html_response(conn, 200)
- refute html =~ Routes.sso_path(conn, :login_form)
- refute html =~ "Single Sign-on"
- end
+ refute html =~ Routes.sso_path(conn, :login_form)
+ refute html =~ "Single Sign-on"
+ end
- test "login_form/2 is guarded by the env var", %{conn: conn} do
- conn = get(conn, Routes.sso_path(conn, :login_form))
+ test "sso_settings/2 are guarded by the env var", %{conn: conn} do
+ user = new_user()
+ team = new_site(owner: user).team |> Plausible.Teams.complete_setup()
+ {:ok, ctx} = log_in(%{conn: conn, user: user})
+ conn = ctx[:conn]
+ conn = set_current_team(conn, team)
- assert redirected_to(conn, 302) == "/"
- end
+ conn = get(conn, Routes.sso_path(conn, :sso_settings))
- test "login/2 is guarded by the env var", %{conn: conn} do
- conn = post(conn, Routes.sso_path(conn, :login), %{"email" => "[email protected]"})
+ assert redirected_to(conn, 302) == "/sites"
+ end
- assert redirected_to(conn, 302) == "/"
- end
+ test "sso team settings item is guarded by the env var", %{conn: conn} do
+ user = new_user()
+ team = new_site(owner: user).team |> Plausible.Teams.complete_setup()
+ {:ok, ctx} = log_in(%{conn: conn, user: user})
+ conn = ctx[:conn]
+ conn = set_current_team(conn, team)
+
+ conn = get(conn, Routes.settings_path(conn, :team_general))
+
+ assert html = html_response(conn, 200)
- test "saml_signin/2 is guarded by the env var", %{conn: conn} do
- conn =
- get(
- conn,
- Routes.sso_path(conn, :saml_signin, Ecto.UUID.generate(),
- email: "[email protected]",
- return_to: "/sites"
+ refute html =~ "Single Sign-On"
+ end
+
+ test "login_form/2 is guarded by the env var", %{conn: conn} do
+ conn = get(conn, Routes.sso_path(conn, :login_form))
+
+ assert redirected_to(conn, 302) == "/"
+ end
+
+ test "login/2 is guarded by the env var", %{conn: conn} do
+ conn = post(conn, Routes.sso_path(conn, :login), %{"email" => "[email protected]"})
+
+ assert redirected_to(conn, 302) == "/"
+ end
+
+ test "saml_signin/2 is guarded by the env var", %{conn: conn} do
+ conn =
+ get(
+ conn,
+ Routes.sso_path(conn, :saml_signin, Ecto.UUID.generate(),
+ email: "[email protected]",
+ return_to: "/sites"
+ )
)
- )
- assert redirected_to(conn, 302) == "/"
- end
+ assert redirected_to(conn, 302) == "/"
+ end
- test "saml_consume/2 is guarded by the env var", %{conn: conn} do
- conn =
- post(conn, Routes.sso_path(conn, :saml_consume, Ecto.UUID.generate()), %{
- "email" => "[email protected]",
- "return_to" => "/sites"
- })
+ test "saml_consume/2 is guarded by the env var", %{conn: conn} do
+ conn =
+ post(conn, Routes.sso_path(conn, :saml_consume, Ecto.UUID.generate()), %{
+ "email" => "[email protected]",
+ "return_to" => "/sites"
+ })
- assert redirected_to(conn, 302) == "/"
- end
+ assert redirected_to(conn, 302) == "/"
+ end
- test "csp_report/2 is guarded by the env var", %{conn: conn} do
- conn = post(conn, Routes.sso_path(conn, :csp_report), %{})
+ test "csp_report/2 is guarded by the env var", %{conn: conn} do
+ conn = post(conn, Routes.sso_path(conn, :csp_report), %{})
- assert redirected_to(conn, 302) == "/"
+ assert redirected_to(conn, 302) == "/"
+ end
end
end
end
diff --git a/test/plausible_web/controllers/sso_controller_test.exs b/test/plausible_web/controllers/sso_controller_test.exs
index 3e244ca944..bccbe1fafe 100644
--- a/test/plausible_web/controllers/sso_controller_test.exs
+++ b/test/plausible_web/controllers/sso_controller_test.exs
@@ -12,7 +12,7 @@ defmodule PlausibleWeb.SSOControllerTest do
alias Plausible.Repo
setup do
- team = new_site().team
+ team = new_site().team |> Plausible.Teams.complete_setup()
integration = SSO.initiate_saml_integration(team)
domain = "example-#{Enum.random(1..10_000)}.com"
@@ -181,5 +181,26 @@ defmodule PlausibleWeb.SSOControllerTest do
Routes.sso_path(conn, :login_form, error: "Wrong email.", return_to: "/sites")
end
end
+
+ describe "sso_settings/2" do
+ setup [:create_user, :log_in, :create_team]
+
+ test "redirects when team is not setup", %{conn: conn, team: team} do
+ conn = set_current_team(conn, team)
+ conn = get(conn, Routes.sso_path(conn, :sso_settings))
+
+ assert redirected_to(conn, 302) == "/sites"
+ end
+
+ test "renders when team is setup", %{conn: conn, team: team} do
+ team = Plausible.Teams.complete_setup(team)
+ conn = set_current_team(conn, team)
+ conn = get(conn, Routes.sso_path(conn, :sso_settings))
+
+ assert html = html_response(conn, 200)
+
+ assert html =~ "Configure and manage Single Sign-On for your team"
+ end
+ end
end
end
diff --git a/test/plausible_web/live/sso_management_test.exs b/test/plausible_web/live/sso_management_test.exs
new file mode 100644
index 0000000000..f2ea62906c
--- /dev/null
+++ b/test/plausible_web/live/sso_management_test.exs
@@ -0,0 +1,280 @@
+defmodule PlausibleWeb.Live.SSOMangementTest do
+ use PlausibleWeb.ConnCase, async: false
+
+ @moduletag :ee_only
+
+ on_ee do
+ use Bamboo.Test, shared: true
+ use Plausible.Teams.Test
+
+ import Phoenix.LiveViewTest
+ import Plausible.Test.Support.HTML
+
+ alias Plausible.Auth.SSO
+
+ @cert_pem """
+ -----BEGIN CERTIFICATE-----
+ MIIFdTCCA12gAwIBAgIUNcATm3CidmlEMMsZa9KBZpWYCVcwDQYJKoZIhvcNAQEL
+ BQAwYzELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
+ GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEcMBoGA1UEAwwTc29tZWlkcC5leGFt
+ cGxlLmNvbTAeFw0yNTA1MjExMjI5MzVaFw0yNjA1MjExMjI5MzVaMGMxCzAJBgNV
+ BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
+ aWRnaXRzIFB0eSBMdGQxHDAaBgNVBAMME3NvbWVpZHAuZXhhbXBsZS5jb20wggIi
+ MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC1N6Drbjed+lFXpOYvE6Efgndy
+ W7kYiO8LqQTr4UwVrp9ArxgYuK4TrcNRh2rhS08xAzNTo+NqnJOm95baG97ADYk1
+ TqVIKxzaFurv+L/Na0wVXyeNUtxIVKF59uElsg2YLm5eQhL9fmN8jVINCvwDPzxc
+ Ihm6mQOaL/i/0DGINOqwHG9MGMZ11AeOM0wKMuXJ2+aKjHOCedhMYVuOaHZgLkcX
+ Zzgiv7itm3+JpCjL474MMfibiqKHR0e3QRNcsEC13f/LD8BAGOwsKLznFC8Uctms
+ 48EDNbxxLG01jVbnJSxRrcDN3RUDjtCdHyaTCCFJAgmldHKKua3VQEynOwJIkFMC
+ fpL1LpLvATzIt0cT1ESb1RHIlgacmESVn/TW2QjO5tp4FAu7GJK+5xY7jPvI6saG
+ oUHsk0zo9obLK8WYneF19ln+Ea5ZCl9PcTi559AKGpYzpL/9uxoPT1zxxTn6c2lt
+ 4xkxkuHtYqi/ENHGdo4CLBL93GDZEilSVmZjD/9N9990yWbPXXQ0eNoFckYSZuls
+ HaWz8W5c046/ob8mASI6wzAUCkO9Zz4WbIj9A+mNZB32hMZbMA02gU//ffvNkFjL
+ DGlNbROCg2DX64rvGs/RuqhuDVCnVfid9B36Cgs76GWI8dCInEfyZMtiqUb7E8Oe
+ BPVwtTscz1StlF/0cQIDAQABoyEwHzAdBgNVHQ4EFgQU9lvXH4X04v99rrwKNzsw
+ pNQP/dUwDQYJKoZIhvcNAQELBQADggIBAJD0MD+OK58vlP2HEoKLQYAKYM/4NsBz
+ vSK1PtZsEj0fqiuu66ceH0wlKlGquRad4Z+LXMptu1DzMNmJsf0zSQfleGFks3xI
+ 86hgkQ7f0qjs+YJzjJUxF9H8zX4jJk5poOqOJwStHBCDLsUmIxnT7/il3jlT0Nj4
+ cVs4946pCg7rP1kR9jojFD5yvzKoRBJG3/qvFnzAi8cDv9CRjSgoDTZyzZmwdCgu
+ NioW7YeFCtvYxvY7HDXinwq/w8Gn3n8zdISoAqSpYrt5Y5ygJGiEYVDWdA50a6PC
+ gq5xt8RCizz1L7a5BUJFMCQ0pyAUuODTndPUGLT8i7jFgzhamFPD72zFMk2+IabE
+ Dutyt2GFeTQ75wL8QvfsKm29Vd5EjAsdfmup3hCpLGqF3g8Sh0aXDrj8KPqIecuS
+ gkL69M9iXfnwZhTo23zUuFjBNoAIPXkNKXiJS7p9IEpYRVnlPYLToSEnnzptoPPQ
+ zMBb8x/UMMtNYkyehSLhuIPrRLvv3eth7Hq3hA7tOCRyyf78tReVm+VoRx6AK68v
+ 5ufxMKBFRTNoLIN3sD+DmSUNY+CaHxRMDhSESy0Ac/95J2yKi+Y1Kml2GV53pSlT
+ 6FPm8B0R9YXM7lHhTLyL7DYqnvklkLh2bUqCLyBowynPyGqdYV4DbFSiST14fGXR
+ mNEYF78kg0IA
+ -----END CERTIFICATE-----
+ """
+
+ describe "/settings/sso/general" do
+ setup [:create_user, :log_in, :create_team, :setup_team]
+
+ test "renders", %{conn: conn} do
+ resp =
+ conn
+ |> get(Routes.sso_path(conn, :sso_settings))
+ |> html_response(200)
+ |> text()
+
+ assert resp =~ "Start Configuring SSO"
+ end
+ end
+
+ describe "live" do
+ setup [:create_user, :log_in, :create_team, :setup_team]
+
+ test "init setup - basic walk through", %{conn: conn} do
+ {lv, _html} = get_lv(conn)
+ lv |> element("form#sso-init") |> render_submit()
+ html = render(lv)
+
+ assert element_exists?(html, "form#sso-sp-config")
+
+ lv |> element("form#sso-idp-form") |> render_submit()
+ lv |> element("form#sso-idp-config") |> render_submit()
+
+ text = text(render(lv))
+
+ assert text =~ "Sign-in URL can't be blank"
+ assert text =~ "Entity ID can't be blank"
+ assert text =~ "Certificate in PEM format can't be blank"
+
+ lv
+ |> element("form#sso-idp-config")
+ |> render_submit(%{
+ saml_config: %{
+ idp_signin_url: "http://signin.example.com",
+ idp_entity_id: "abc123",
+ idp_cert_pem: @cert_pem
+ }
+ })
+
+ lv
+ |> element("form#sso-add-domain")
+ |> render_submit()
+
+ text = text(render(lv))
+ assert text =~ "Domain can't be blank"
+
+ lv
+ |> element("form#sso-add-domain")
+ |> render_submit(%{
+ domain: %{
+ domain: "example.com"
+ }
+ })
+
+ text = render(lv) |> text()
+ assert text =~ "Verifying domain"
+
+ lv |> element("form#show-manage") |> render_submit()
+
+ html = render(lv)
+ text = text(html)
+
+ assert text =~ "example.com"
+ assert text =~ "-BEGIN CERTIFICATE-"
+
+ sp_entity_id = text_of_attr(html, "#sp-entity-id", "value")
+ integration_identifier = sp_entity_id |> Path.split() |> List.last()
+ {:ok, integration} = SSO.get_integration(integration_identifier)
+
+ assert integration.config.idp_signin_url == "http://signin.example.com"
+ assert integration.config.idp_entity_id == "abc123"
+ assert [%{domain: "example.com"}] = integration.sso_domains
+ end
+
+ test "renders integration summary", %{conn: conn, team: team} do
+ setup_integration(team, "example.com")
+
+ {_lv, html} = get_lv(conn)
+
+ assert element_exists?(html, "h2 a#sso-manage-config")
+ assert element_exists?(html, "h2 a#sso-domains-config")
+ assert element_exists?(html, "h2 a#sso-policy-config")
+ end
+
+ test "edit idp config", %{conn: conn, team: team} do
+ setup_integration(team, "example.com")
+
+ {lv, _html} = get_lv(conn)
+
+ lv |> element("form#show-idp-form") |> render_submit()
+
+ html = render(lv)
+
+ assert element_exists?(html, "input#sso-idp-config_idp_signin_url")
+ assert element_exists?(html, "input#sso-idp-config_idp_entity_id")
+ assert element_exists?(html, "textarea#sso-idp-config_idp_cert_pem")
+
+ lv
+ |> element("form#sso-idp-config")
+ |> render_submit(%{
+ saml_config: %{
+ idp_signin_url: "http://updated.example.com",
+ idp_entity_id: "zxc345",
+ idp_cert_pem: @cert_pem
+ }
+ })
+
+ html = render(lv)
+ assert element_exists?(html, "h2 a#sso-manage-config")
+
+ assert text_of_attr(html, "input#sso-idp-config_idp_signin_url", "value") ==
+ "http://updated.example.com"
+
+ assert text_of_attr(html, "input#sso-idp-config_idp_entity_id", "value") == "zxc345"
+ end
+
+ test "add another domain", %{conn: conn, team: team} do
+ setup_integration(team, "org.example.com")
+
+ {lv, _html} = get_lv(conn)
+
+ lv |> element("form#show-domain-setup") |> render_submit()
+
+ lv
+ |> element("form#sso-add-domain")
+ |> render_submit(%{
+ domain: %{
+ domain: "new.example.com"
+ }
+ })
+
+ html = render(lv)
+ assert text(html) =~ "Verifying domain new.example.com"
+
+ lv |> element("form#show-manage") |> render_submit()
+
+ text = text(render(lv))
+ assert text =~ "org.example.com"
+ assert text =~ "new.example.com"
+ end
+
+ test "policy update", %{conn: conn, team: team} do
+ setup_integration(team, "org.example.com")
+ {lv, html} = get_lv(conn)
+
+ assert text_of_attr(
+ html,
+ ~s|#sso-policy_sso_default_role option[selected="selected"]|,
+ "value"
+ ) == "viewer"
+
+ assert text_of_attr(html, ~s|#sso-policy_sso_session_timeout_minutes|, "value") == "360"
+
+ lv
+ |> element("form#sso-policy")
+ |> render_submit(%{
+ policy: %{
+ sso_default_role: "owner",
+ sso_session_timeout_minutes: "710"
+ }
+ })
+
+ html = render(lv)
+
+ assert text_of_attr(
+ html,
+ ~s|#sso-policy_sso_default_role option[selected="selected"]|,
+ "value"
+ ) == "owner"
+
+ assert text_of_attr(html, ~s|#sso-policy_sso_session_timeout_minutes|, "value") == "710"
+ end
+
+ test "force SSO toggle", %{conn: conn, team: team, user: user} do
+ setup_integration(team, "org.example.com")
+ {_lv, html} = get_lv(conn)
+
+ assert element_exists?(html, "button#enable-force-sso-toggle[disabled]")
+
+ user
+ |> Ecto.Changeset.change(totp_enabled: true, totp_secret: "secret")
+ |> Plausible.Repo.update!()
+
+ identity = new_identity("Lance Wurst", "[email protected]")
+ {:ok, _, _, _sso_user} = SSO.provision_user(identity)
+
+ {lv, html} = get_lv(conn)
+
+ refute element_exists?(html, "button#enable-force-sso-toggle[disabled]")
+
+ lv
+ |> element("#enable-force-sso-toggle")
+ |> render_click()
+
+ assert Plausible.Repo.reload(team).policy.force_sso == :all_but_owners
+ end
+
+ defp setup_integration(team, domain) do
+ integration = SSO.initiate_saml_integration(team)
+ {:ok, sso_domain} = SSO.Domains.add(integration, domain)
+ SSO.Domains.verify(sso_domain, skip_checks?: true)
+
+ {:ok, _integration} =
+ SSO.update_integration(integration, %{
+ idp_signin_url: "https://#{domain}",
+ idp_entity_id: "some-entity",
+ idp_cert_pem: @cert_pem
+ })
+ end
+
+ defp get_lv(conn) do
+ conn = assign(conn, :live_module, PlausibleWeb.Live.SSOManagement)
+ {:ok, lv, html} = live(conn, Routes.sso_path(conn, :sso_settings))
+ {lv, html}
+ 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)
+ }
+ end
+ end
+ end
+end