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
Simplify TOTP core logic and add email notifications (#3563)
Adrian Gruntkowski86b9d1680d5b
diff --git a/lib/plausible/auth/totp.ex b/lib/plausible/auth/totp.exindex a6a64b88d8..a5cae91983 100644--- a/lib/plausible/auth/totp.ex+++ b/lib/plausible/auth/totp.ex@@ -73,6 +73,7 @@ defmodule Plausible.Auth.TOTP doalias Plausible.Authalias Plausible.Auth.TOTPalias Plausible.Repo+ alias PlausibleWeb.Email@issuer_name "Plausible Analytics"@recovery_codes_count 10@@ -82,6 +83,11 @@ defmodule Plausible.Auth.TOTP douser.totp_enabled and not is_nil(user.totp_secret)end+ @spec initiated?(Auth.User.t()) :: boolean()+ def initiated?(user) do+ not user.totp_enabled and not is_nil(user.totp_secret)+ end+@spec initiate(Auth.User.t()) ::{:ok, Auth.User.t(), %{totp_uri: String.t(), secret: String.t()}}| {:error, :not_verified | :already_setup}@@ -108,7 +114,8 @@ defmodule Plausible.Auth.TOTP doend@spec enable(Auth.User.t(), String.t(), Keyword.t()) ::- {:ok, Auth.User.t()} | {:error, :invalid_code | :not_initiated}+ {:ok, Auth.User.t(), %{recovery_codes: [String.t()]}}+ | {:error, :invalid_code | :not_initiated}def enable(user, code, opts \\ [])def enable(%{totp_secret: nil}, _, _) do@@ -117,57 +124,74 @@ defmodule Plausible.Auth.TOTP dodef enable(user, code, opts) dowith {:ok, user} <- do_validate_code(user, code, opts) do- user =- user- |> change(totp_enabled: true)- |> Repo.update!()+ {:ok, {user, recovery_codes}} =+ Repo.transaction(fn ->+ user =+ user+ |> change(totp_enabled: true)+ |> Repo.update!()- {:ok, user}+ {:ok, recovery_codes} = do_generate_recovery_codes(user)++ {user, recovery_codes}+ end)++ user+ |> Email.two_factor_enabled_email()+ |> Plausible.Mailer.send()++ {:ok, user, %{recovery_codes: recovery_codes}}endend@spec disable(Auth.User.t(), String.t()) :: {:ok, Auth.User.t()} | {:error, :invalid_password}def disable(user, password) doif Auth.Password.match?(password, user.password_hash) do- Repo.transaction(fn ->- {_, _} =+ {:ok, user} =+ Repo.transaction(fn ->+ {_, _} =+ user+ |> recovery_codes_query()+ |> Repo.delete_all()+user- |> recovery_codes_query()- |> Repo.delete_all()+ |> change(+ totp_enabled: false,+ totp_secret: nil,+ totp_last_used_at: nil+ )+ |> Repo.update!()+ end)- user- |> change(- totp_enabled: false,- totp_secret: nil,- totp_last_used_at: nil- )- |> Repo.update!()- end)+ user+ |> Email.two_factor_disabled_email()+ |> Plausible.Mailer.send()++ {:ok, user}else{:error, :invalid_password}endend- @spec generate_recovery_codes_protected(Auth.User.t(), String.t()) ::+ @spec generate_recovery_codes(Auth.User.t(), String.t()) ::{:ok, [String.t()]} | {:error, :invalid_password | :not_enabled}- def generate_recovery_codes_protected(%{totp_enabled: false}) do+ def generate_recovery_codes(%{totp_enabled: false}) do{:error, :not_enabled}end- def generate_recovery_codes_protected(user, password) do+ def generate_recovery_codes(user, password) doif Auth.Password.match?(password, user.password_hash) do- generate_recovery_codes(user)+ do_generate_recovery_codes(user)else{:error, :invalid_password}endend- @spec generate_recovery_codes(Auth.User.t()) :: {:ok, [String.t()]} | {:error, :not_enabled}- def generate_recovery_codes(%{totp_enabled: false}) do+ defp do_generate_recovery_codes(%{totp_enabled: false}) do{:error, :not_enabled}end- def generate_recovery_codes(user) do+ defp do_generate_recovery_codes(user) doRepo.transaction(fn ->{_, _} =user@@ -194,8 +218,8 @@ defmodule Plausible.Auth.TOTP doend)end- @spec validate_code(Auth.User.t(), String.t()) ::- {:ok, Auth.User.t(), Keyword.t()} | {:error, :invalid_code | :not_enabled}+ @spec validate_code(Auth.User.t(), String.t(), Keyword.t()) ::+ {:ok, Auth.User.t()} | {:error, :invalid_code | :not_enabled}def validate_code(user, code, opts \\ [])def validate_code(%{totp_enabled: false}, _, _) do@@ -208,7 +232,7 @@ defmodule Plausible.Auth.TOTP do@spec use_recovery_code(Auth.User.t(), String.t()) :::ok | {:error, :invalid_code | :not_enabled}- def user_recovery_code(%{totp_enabled: false}, _) do+ def use_recovery_code(%{totp_enabled: false}, _) do{:error, :not_enabled}enddiff --git a/lib/plausible_web/email.ex b/lib/plausible_web/email.exindex a12bfb06db..81368c8be2 100644--- a/lib/plausible_web/email.ex+++ b/lib/plausible_web/email.ex@@ -68,6 +68,22 @@ defmodule PlausibleWeb.Email do|> render("password_reset_email.html", reset_link: reset_link)end+ def two_factor_enabled_email(user) do+ priority_email()+ |> to(user)+ |> tag("two-factor-enabled-email")+ |> subject("Plausible two-factor authentication enabled")+ |> render("two_factor_enabled_email.html", user: user)+ end++ def two_factor_disabled_email(user) do+ priority_email()+ |> to(user)+ |> tag("two-factor-disabled-email")+ |> subject("Plausible two-factor authentication disabled")+ |> render("two_factor_disabled_email.html", user: user)+ end+def trial_one_week_reminder(user) dobase_email()|> to(user)diff --git a/lib/plausible_web/templates/email/two_factor_disabled_email.html.heex b/lib/plausible_web/templates/email/two_factor_disabled_email.html.heexnew file mode 100644index 0000000000..640302db68--- /dev/null+++ b/lib/plausible_web/templates/email/two_factor_disabled_email.html.heex@@ -0,0 +1 @@+Two-factor authentication is now disabled on your account.diff --git a/lib/plausible_web/templates/email/two_factor_enabled_email.html.heex b/lib/plausible_web/templates/email/two_factor_enabled_email.html.heexnew file mode 100644index 0000000000..b1abdabc9c--- /dev/null+++ b/lib/plausible_web/templates/email/two_factor_enabled_email.html.heex@@ -0,0 +1 @@+Two-factor authentication is now enabled on your account.diff --git a/test/plausible/auth/totp_test.exs b/test/plausible/auth/totp_test.exsindex 64059418ef..00ea22d100 100644--- a/test/plausible/auth/totp_test.exs+++ b/test/plausible/auth/totp_test.exs@@ -1,5 +1,6 @@defmodule Plausible.Auth.TOTPTest douse Plausible.DataCase, async: true+ use Bamboo.Testalias Plausible.Auth.TOTPalias Plausible.Auth.TOTP.RecoveryCode@@ -8,11 +9,22 @@ defmodule Plausible.Auth.TOTPTest dodescribe "enabled?/1" dotest "Returns user's TOTP state" do- assert TOTP.enabled?(insert(:user, totp_enabled: true, totp_secret: "secret"))refute TOTP.enabled?(insert(:user, totp_enabled: false, totp_secret: nil))- # these shouldn't happen under normal circumstances but we do check- # totp_secret presence just to be safe and avoid undefined behaviorrefute TOTP.enabled?(insert(:user, totp_enabled: false, totp_secret: "secret"))+ assert TOTP.enabled?(insert(:user, totp_enabled: true, totp_secret: "secret"))+ # this shouldn't happen under normal circumstances but we do check+ # totp_secret presence just to be safe and avoid undefined behavior+ refute TOTP.enabled?(insert(:user, totp_enabled: true, totp_secret: nil))+ end+ end++ describe "initiated?/1" do+ test "Returns true only when user's TOTP setup is initiated but not finalized" do+ refute TOTP.initiated?(insert(:user, totp_enabled: false, totp_secret: nil))+ refute TOTP.initiated?(insert(:user, totp_enabled: true, totp_secret: "secret"))+ assert TOTP.initiated?(insert(:user, totp_enabled: false, totp_secret: "secret"))+ # this shouldn't happen under normal circumstances but we do check+ # totp_secret presence just to be safe and avoid undefined behaviorrefute TOTP.enabled?(insert(:user, totp_enabled: true, totp_secret: nil))endend@@ -49,7 +61,7 @@ defmodule Plausible.Auth.TOTPTest douser = insert(:user){:ok, user, _} = TOTP.initiate(user)code = NimbleTOTP.verification_code(user.totp_secret)- {:ok, user} = TOTP.enable(user, code)+ {:ok, user, _} = TOTP.enable(user, code)assert TOTP.initiate(user) == {:error, :already_setup}end@@ -67,29 +79,62 @@ defmodule Plausible.Auth.TOTPTest do{:ok, user, _} = TOTP.initiate(user)code = NimbleTOTP.verification_code(user.totp_secret)- assert {:ok, user} = TOTP.enable(user, code)+ assert {:ok, user, %{recovery_codes: recovery_codes}} = TOTP.enable(user, code)++ assert_email_delivered_with(+ to: [{user.name, user.email}],+ subject: "Plausible two-factor authentication enabled"+ )assert user.totp_enabledassert byte_size(user.totp_secret) > 0++ persisted_recovery_codes = Repo.all(RecoveryCode)++ assert length(recovery_codes) == 10+ assert length(persisted_recovery_codes) == 10++ Enum.each(persisted_recovery_codes, fn recovery_code ->+ assert recovery_code.user_id == user.id+ assert byte_size(recovery_code.code_digest) > 0+ end)++ Enum.each(recovery_codes, fn code_string ->+ assert byte_size(code_string) > 0+ assert :ok = TOTP.use_recovery_code(user, code_string)+ end)endtest "succeeds for user who has TOTP enabled already" douser = insert(:user){:ok, user, _} = TOTP.initiate(user)code = NimbleTOTP.verification_code(user.totp_secret, time: System.os_time(:second) - 30)- {:ok, user} = TOTP.enable(user, code)+ {:ok, user, %{recovery_codes: [recovery_code | recovery_codes]}} = TOTP.enable(user, code)+ :ok = TOTP.use_recovery_code(user, recovery_code)- assert {:ok, updated_user} = TOTP.enable(user, code, allow_reuse?: true)+ assert {:ok, updated_user, %{recovery_codes: new_recovery_codes}} =+ TOTP.enable(user, code, allow_reuse?: true)assert updated_user.id == user.idassert updated_user.totp_enabledassert updated_user.totp_secret == user.totp_secret++ assert Enum.uniq(recovery_codes ++ new_recovery_codes) ==+ recovery_codes ++ new_recovery_codes++ assert length(new_recovery_codes) == 10++ Enum.each(new_recovery_codes, fn code_string ->+ assert byte_size(code_string) > 0+ assert :ok = TOTP.use_recovery_code(user, code_string)+ end)endtest "fails when TOTP setup is not initiated" douser = insert(:user)assert {:error, :not_initiated} = TOTP.enable(user, "123456")+ assert_no_emails_delivered()endtest "fails when invalid code is provided" do@@ -97,6 +142,7 @@ defmodule Plausible.Auth.TOTPTest do{:ok, user, _} = TOTP.initiate(user)assert {:error, :invalid_code} = TOTP.enable(user, "1234")+ assert_no_emails_delivered()endend@@ -105,10 +151,20 @@ defmodule Plausible.Auth.TOTPTest douser = insert(:user, password: "VeryStrongVerySecret"){:ok, user, _} = TOTP.initiate(user)code = NimbleTOTP.verification_code(user.totp_secret)- {:ok, user} = TOTP.enable(user, code)+ {:ok, user, _} = TOTP.enable(user, code)++ assert_email_delivered_with(+ to: [{user.name, user.email}],+ subject: "Plausible two-factor authentication enabled"+ )assert {:ok, updated_user} = TOTP.disable(user, "VeryStrongVerySecret")+ assert_email_delivered_with(+ to: [{user.name, user.email}],+ subject: "Plausible two-factor authentication disabled"+ )+assert updated_user.id == user.idrefute updated_user.totp_enabledassert is_nil(updated_user.totp_secret)@@ -130,73 +186,27 @@ defmodule Plausible.Auth.TOTPTest douser = insert(:user, password: "VeryStrongVerySecret"){:ok, user, _} = TOTP.initiate(user)code = NimbleTOTP.verification_code(user.totp_secret)- {:ok, user} = TOTP.enable(user, code)-- assert {:error, :invalid_password} = TOTP.disable(user, "invalid")- end- end-- describe "generate_recovery_codes/1" do- test "generates recovery codes for user with enabled TOTP" do- user = insert(:user)- {:ok, user, _} = TOTP.initiate(user)- code = NimbleTOTP.verification_code(user.totp_secret)- {:ok, user} = TOTP.enable(user, code)-- assert {:ok, codes} = TOTP.generate_recovery_codes(user)-- persisted_codes = Repo.all(RecoveryCode)-- assert length(codes) == 10- assert length(persisted_codes) == 10-- Enum.each(persisted_codes, fn recovery_code ->- assert recovery_code.user_id == user.id- assert byte_size(recovery_code.code_digest) > 0- end)-- Enum.each(codes, fn code ->- assert byte_size(code) > 0- assert :ok = TOTP.use_recovery_code(user, code)- end)- end-- test "regenerates recovery codes when generated already" do- user = insert(:user)- {:ok, user, _} = TOTP.initiate(user)- code = NimbleTOTP.verification_code(user.totp_secret)- {:ok, user} = TOTP.enable(user, code)-- assert {:ok, [code | codes]} = TOTP.generate_recovery_codes(user)- assert :ok = TOTP.use_recovery_code(user, code)-- assert {:ok, new_codes} = TOTP.generate_recovery_codes(user)-- assert Enum.uniq(codes ++ new_codes) == codes ++ new_codes+ {:ok, user, _} = TOTP.enable(user, code)- assert length(new_codes) == 10-- Enum.each(new_codes, fn code ->- assert byte_size(code) > 0- assert :ok = TOTP.use_recovery_code(user, code)- end)- end+ assert_email_delivered_with(+ to: [{user.name, user.email}],+ subject: "Plausible two-factor authentication enabled"+ )- test "fails when user has TOTP disabled" do- user = insert(:user)+ assert {:error, :invalid_password} = TOTP.disable(user, "invalid")- assert {:error, :not_enabled} = TOTP.generate_recovery_codes(user)+ assert_no_emails_delivered()endend- describe "generate_recovery_codes_protected/1" do+ describe "generate_recovery_codes/1" dotest "generates recovery codes for user with enabled TOTP" douser = insert(:user, password: "VeryStrongVerySecret"){:ok, user, _} = TOTP.initiate(user)code = NimbleTOTP.verification_code(user.totp_secret)- {:ok, user} = TOTP.enable(user, code)+ {:ok, user, _} = TOTP.enable(user, code)- assert {:ok, codes} = TOTP.generate_recovery_codes_protected(user, "VeryStrongVerySecret")+ assert {:ok, codes} = TOTP.generate_recovery_codes(user, "VeryStrongVerySecret")persisted_codes = Repo.all(RecoveryCode)@@ -218,16 +228,16 @@ defmodule Plausible.Auth.TOTPTest douser = insert(:user, password: "VeryStrongVerySecret")assert {:error, :not_enabled} =- TOTP.generate_recovery_codes_protected(user, "VeryStrongVerySecret")+ TOTP.generate_recovery_codes(user, "VeryStrongVerySecret")endtest "fails when invalid password provided" douser = insert(:user, password: "VeryStrongVerySecret"){:ok, user, _} = TOTP.initiate(user)code = NimbleTOTP.verification_code(user.totp_secret)- {:ok, user} = TOTP.enable(user, code)+ {:ok, user, _} = TOTP.enable(user, code)- assert {:error, :invalid_password} = TOTP.generate_recovery_codes_protected(user, "invalid")+ assert {:error, :invalid_password} = TOTP.generate_recovery_codes(user, "invalid")endend@@ -236,7 +246,7 @@ defmodule Plausible.Auth.TOTPTest douser = insert(:user){:ok, user, _} = TOTP.initiate(user)code = NimbleTOTP.verification_code(user.totp_secret, time: System.os_time(:second) - 30)- {:ok, user} = TOTP.enable(user, code)+ {:ok, user, _} = TOTP.enable(user, code)new_code = NimbleTOTP.verification_code(user.totp_secret)# making sure that generated OTP codes are different@@ -251,7 +261,7 @@ defmodule Plausible.Auth.TOTPTest douser = insert(:user){:ok, user, _} = TOTP.initiate(user)code = NimbleTOTP.verification_code(user.totp_secret, time: System.os_time(:second) - 30)- {:ok, user} = TOTP.enable(user, code)+ {:ok, user, _} = TOTP.enable(user, code)assert {:error, :invalid_code} = TOTP.validate_code(user, code)end@@ -260,7 +270,7 @@ defmodule Plausible.Auth.TOTPTest douser = insert(:user){:ok, user, _} = TOTP.initiate(user)code = NimbleTOTP.verification_code(user.totp_secret)- {:ok, user} = TOTP.enable(user, code)+ {:ok, user, _} = TOTP.enable(user, code)assert {:error, :invalid_code} = TOTP.validate_code(user, "1234")end@@ -276,11 +286,11 @@ defmodule Plausible.Auth.TOTPTest dodescribe "use_recovery_code/2" dotest "succeeds when valid recovery code provided but fails when trying to reuse it" do- user = insert(:user)+ user = insert(:user, password: "VeryStrongVerySecret"){:ok, user, _} = TOTP.initiate(user)code = NimbleTOTP.verification_code(user.totp_secret)- {:ok, user} = TOTP.enable(user, code)- {:ok, [code | codes]} = TOTP.generate_recovery_codes(user)+ {:ok, user, _} = TOTP.enable(user, code)+ {:ok, [code | codes]} = TOTP.generate_recovery_codes(user, "VeryStrongVerySecret")assert :ok = TOTP.use_recovery_code(user, code)assert {:error, :invalid_code} = TOTP.use_recovery_code(user, code)@@ -289,11 +299,11 @@ defmodule Plausible.Auth.TOTPTest doendtest "fails when provided code is invalid" do- user = insert(:user)+ user = insert(:user, password: "VeryStrongVerySecret"){:ok, user, _} = TOTP.initiate(user)code = NimbleTOTP.verification_code(user.totp_secret)- {:ok, user} = TOTP.enable(user, code)- {:ok, _} = TOTP.generate_recovery_codes(user)+ {:ok, user, _} = TOTP.enable(user, code)+ {:ok, _} = TOTP.generate_recovery_codes(user, "VeryStrongVerySecret")assert {:error, :invalid_code} = TOTP.use_recovery_code(user, "INVALID")end@@ -302,7 +312,7 @@ defmodule Plausible.Auth.TOTPTest douser = insert(:user){:ok, user, _} = TOTP.initiate(user)code = NimbleTOTP.verification_code(user.totp_secret)- {:ok, user} = TOTP.enable(user, code)+ {:ok, user, _} = TOTP.enable(user, code)assert {:error, :invalid_code} = TOTP.use_recovery_code(user, "INVALID")end@@ -311,11 +321,11 @@ defmodule Plausible.Auth.TOTPTest douser = insert(:user, password: "VeryStrongVerySecret"){:ok, user, _} = TOTP.initiate(user)code = NimbleTOTP.verification_code(user.totp_secret)- {:ok, user} = TOTP.enable(user, code)- {:ok, [code | _]} = TOTP.generate_recovery_codes(user)+ {:ok, user, _} = TOTP.enable(user, code)+ {:ok, [code | _]} = TOTP.generate_recovery_codes(user, "VeryStrongVerySecret"){:ok, user} = TOTP.disable(user, "VeryStrongVerySecret")- assert {:error, :not_enabled} = TOTP.user_recovery_code(user, code)+ assert {:error, :not_enabled} = TOTP.use_recovery_code(user, code)endendend