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.initiate_saml_integration` and `SSO.update_integration` (#5416)
Adrian Gruntkowskid7fe32000a67
diff --git a/extra/lib/plausible/auth/sso.ex b/extra/lib/plausible/auth/sso.exnew file mode 100644index 0000000000..4b76ab1c96--- /dev/null+++ b/extra/lib/plausible/auth/sso.ex@@ -0,0 +1,31 @@+defmodule Plausible.Auth.SSO do+ @moduledoc """+ API for SSO.+ """++ alias Plausible.Auth.SSO+ alias Plausible.Repo+ alias Plausible.Teams++ @spec initiate_saml_integration(Teams.Team.t()) :: SSO.Integration.t()+ def initiate_saml_integration(team) do+ changeset = SSO.Integration.init_changeset(team)++ Repo.insert!(changeset,+ on_conflict: [set: [updated_at: NaiveDateTime.utc_now()]],+ conflict_target: :team_id,+ returning: true+ )+ end++ @spec update_integration(SSO.Integration.t(), map()) ::+ {:ok, SSO.Integration.t()} | {:error, Ecto.Changeset.t()}+ def update_integration(integration, params) do+ changeset = SSO.Integration.update_changeset(integration, params)++ case Repo.update(changeset) do+ {:ok, integration} -> {:ok, integration}+ {:error, changeset} -> {:error, changeset.changes.config}+ end+ end+enddiff --git a/extra/lib/plausible/auth/sso/integration.ex b/extra/lib/plausible/auth/sso/integration.exindex 72857c0a1a..e8d51b40e3 100644--- a/extra/lib/plausible/auth/sso/integration.ex+++ b/extra/lib/plausible/auth/sso/integration.ex@@ -46,10 +46,24 @@ defmodule Plausible.Auth.SSO.Integration doenddef update_changeset(integration, config_params) do- params = %{config: Map.merge(%{__type__: :saml}, config_params)}+ params = tag_params(:saml, config_params)integration|> cast(params, [])- |> cast_polymorphic_embed(:config)+ |> cast_polymorphic_embed(:config,+ with: [+ saml: &SSO.SAMLConfig.update_changeset/2+ ]+ )+ end++ defp tag_params(type, params) when is_atom(type) and is_map(params) do+ case Enum.take(params, 1) do+ [{key, _}] when is_binary(key) ->+ %{"config" => Map.merge(%{"__type__" => Atom.to_string(type)}, params)}++ _ ->+ %{config: Map.merge(%{__type__: type}, params)}+ endendenddiff --git a/extra/lib/plausible/auth/sso/saml_config.ex b/extra/lib/plausible/auth/sso/saml_config.exindex 44db632b48..94774cd719 100644--- a/extra/lib/plausible/auth/sso/saml_config.ex+++ b/extra/lib/plausible/auth/sso/saml_config.ex@@ -17,6 +17,7 @@ defmodule Plausible.Auth.SSO.SAMLConfig do@type t() :: %__MODULE__{}@fields [:idp_signin_url, :idp_entity_id, :idp_cert_pem, :idp_metadata]+ @required_fields @fields -- [:idp_metadata]embedded_schema dofield :idp_signin_url, :string@@ -29,4 +30,34 @@ defmodule Plausible.Auth.SSO.SAMLConfig dostruct|> cast(params, @fields)end++ def update_changeset(struct, params) do+ struct+ |> cast(params, @fields)+ |> validate_required(@required_fields)+ |> validate_url(:idp_signin_url)+ |> validate_pem(:idp_cert_pem)+ end++ defp validate_url(changeset, field) do+ if url = get_change(changeset, field) do+ case URI.new(url) do+ {:ok, uri} when uri.scheme in ["http", "https"] -> changeset+ _ -> add_error(changeset, field, "invalid URL", validation: :url)+ end+ else+ changeset+ end+ end++ defp validate_pem(changeset, field) do+ if pem = get_change(changeset, field) do+ case X509.Certificate.from_pem(pem) do+ {:ok, _cert} -> changeset+ {:error, _} -> add_error(changeset, field, "invalid certificate", validation: :cert_pem)+ end+ else+ changeset+ end+ endenddiff --git a/mix.exs b/mix.exsindex 912c513acc..228a133d95 100644--- a/mix.exs+++ b/mix.exs@@ -116,6 +116,7 @@ defmodule Plausible.MixProject do{:plug, "~> 1.13", override: true},{:plug_cowboy, "~> 2.3"},{:polymorphic_embed, "~> 5.0"},+ {:x509, "~> 0.8.10"},{:postgrex, "~> 0.19.0"},{:prom_ex, "~> 1.8"},{:peep, "~> 3.4"},diff --git a/mix.lock b/mix.lockindex 8939903b61..b71d237f06 100644--- a/mix.lock+++ b/mix.lock@@ -159,7 +159,7 @@"unicode_util_compat": {:hex, :unicode_util_compat, "0.7.0", "bc84380c9ab48177092f43ac89e4dfa2c6d62b40b8bd132b1059ecc7232f9a78", [:rebar3], [], "hexpm", "25eee6d67df61960cf6a794239566599b09e17e668d3700247bc498638152521"},"websock": {:hex, :websock, "0.5.3", "2f69a6ebe810328555b6fe5c831a851f485e303a7c8ce6c5f675abeb20ebdadc", [:mix], [], "hexpm", "6105453d7fac22c712ad66fab1d45abdf049868f253cf719b625151460b8b453"},"websock_adapter": {:hex, :websock_adapter, "0.5.8", "3b97dc94e407e2d1fc666b2fb9acf6be81a1798a2602294aac000260a7c4a47d", [:mix], [{:bandit, ">= 0.6.0", [hex: :bandit, repo: "hexpm", optional: true]}, {:plug, "~> 1.14", [hex: :plug, repo: "hexpm", optional: false]}, {:plug_cowboy, "~> 2.6", [hex: :plug_cowboy, repo: "hexpm", optional: true]}, {:websock, "~> 0.5", [hex: :websock, repo: "hexpm", optional: false]}], "hexpm", "315b9a1865552212b5f35140ad194e67ce31af45bcee443d4ecb96b5fd3f3782"},- "x509": {:hex, :x509, "0.8.9", "03c47e507171507d3d3028d802f48dd575206af2ef00f764a900789dfbe17476", [:mix], [], "hexpm", "ea3fb16a870a199cb2c45908a2c3e89cc934f0434173dc0c828136f878f11661"},+ "x509": {:hex, :x509, "0.8.10", "5d1ec6d5f4db31982f9dc34e6a1eebd631d04599e0b6c1c259f1dadd4495e11f", [:mix], [], "hexpm", "a191221665af28b9bdfff0c986ef55f80e126d8ce751bbdf6cefa846410140c0"},"yamerl": {:hex, :yamerl, "0.10.0", "4ff81fee2f1f6a46f1700c0d880b24d193ddb74bd14ef42cb0bcf46e81ef2f8e", [:rebar3], [], "hexpm", "346adb2963f1051dc837a2364e4acf6eb7d80097c0f53cbdc3046ec8ec4b4e6e"},"zstream": {:hex, :zstream, "0.6.5", "ad4c5631f0da986ddcf8b23d0d2c696c09cedb1c3ace027fb2312a809df6f8b8", [:mix], [], "hexpm", "de908d8a050f6aabf5f4931aa41dab49419e3c8b95cfee01461a8c84fdde005e"},"zxcvbn": {:git, "https://github.com/techgaun/zxcvbn-elixir.git", "5c9684590f4ecf00af2d391f90db9ce93bd4e996", []},diff --git a/test/plausible/auth/sso/integration_test.exs b/test/plausible/auth/sso/integration_test.exsdeleted file mode 100644index b7988a18e0..0000000000--- a/test/plausible/auth/sso/integration_test.exs+++ /dev/null@@ -1,45 +0,0 @@-defmodule Plausible.Auth.SSO.IntegrationTest do- use Plausible.DataCase, async: true- use Plausible-- on_ee do- use Plausible.Teams.Test-- alias Plausible.Auth.SSO-- describe "init_changeset/1" do- test "inits integration" do- team = new_site().team-- assert %{valid?: true} = changeset = SSO.Integration.init_changeset(team)- assert {:ok, integration} = Repo.insert(changeset)- assert integration.team_id == team.id- assert is_binary(integration.identifier)- assert %SSO.SAMLConfig{} = integration.config- end- end-- describe "update_changeset/2" do- test "updates config" do- team = new_site().team- integration = team |> SSO.Integration.init_changeset() |> Repo.insert!()-- assert %{valid?: true} =- changeset =- SSO.Integration.update_changeset(integration, %{- idp_signin_url: "https://example.com",- idp_entity_id: "some_id",- idp_cert_pem: "SOMECERT"- })-- assert {:ok, integration} = Repo.update(changeset)-- assert %SSO.SAMLConfig{- idp_signin_url: "https://example.com",- idp_entity_id: "some_id",- idp_cert_pem: "SOMECERT"- } = integration.config- end- end- end-enddiff --git a/test/plausible/auth/sso_test.exs b/test/plausible/auth/sso_test.exsnew file mode 100644index 0000000000..c0f087942b--- /dev/null+++ b/test/plausible/auth/sso_test.exs@@ -0,0 +1,166 @@+defmodule Plausible.Auth.SSOTest do+ use Plausible.DataCase, async: true+ use Plausible++ on_ee do+ use Plausible.Teams.Test++ alias Plausible.Auth.SSO++ describe "initiate_saml_integration/1" do+ test "initiates new saml integration" do+ team = new_site().team++ integration = SSO.initiate_saml_integration(team)++ assert integration.team_id == team.id+ assert is_binary(integration.identifier)+ assert %SSO.SAMLConfig{} = integration.config+ end++ test "does nothing if integration is already initiated" do+ team = new_site().team++ integration = SSO.initiate_saml_integration(team)+ another_integration = SSO.initiate_saml_integration(team)++ assert integration.id == another_integration.id+ assert integration.config == another_integration.config+ end+ end++ describe "update_integration/2" do+ @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-----+ """++ test "updates integration" do+ 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: @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+ end++ test "optionally accepts metadata" do+ 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: @cert_pem,+ idp_metadata: "<some-metadata></some-metadata>"+ })++ assert integration.config.idp_metadata == "<some-metadata></some-metadata>"+ end++ test "works with string keys" do+ 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" => @cert_pem+ })+ end++ test "returns error on missing parameters" do+ team = new_site().team+ integration = SSO.initiate_saml_integration(team)++ assert {:error, changeset} = SSO.update_integration(integration, %{})++ assert %{+ idp_signin_url: [:required],+ idp_entity_id: [:required],+ idp_cert_pem: [:required]+ } =+ Ecto.Changeset.traverse_errors(changeset, fn {_msg, opts} ->+ opts[:validation]+ end)+ end++ test "returns error on invalid signin url" do+ team = new_site().team+ integration = SSO.initiate_saml_integration(team)++ assert {:error, changeset} =+ SSO.update_integration(integration, %{+ idp_signin_url: "invalid-url",+ idp_entity_id: "some-entity",+ idp_cert_pem: @cert_pem+ })++ assert %{+ idp_signin_url: [:url]+ } =+ Ecto.Changeset.traverse_errors(changeset, fn {_msg, opts} ->+ opts[:validation]+ end)+ end++ test "returns error on invalid certificate" do+ team = new_site().team+ integration = SSO.initiate_saml_integration(team)++ assert {:error, changeset} =+ SSO.update_integration(integration, %{+ idp_signin_url: "https://example.com",+ idp_entity_id: "some-entity",+ idp_cert_pem: "INVALID CERT"+ })++ assert %{+ idp_cert_pem: [:cert_pem]+ } =+ Ecto.Changeset.traverse_errors(changeset, fn {_msg, opts} ->+ opts[:validation]+ end)+ end+ end+ end+end