Skip to content

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

Enforce `DISABLE_REGISTRATION` in LiveView too (#6646)

Adrian Gruntkowskif9af58d2bb60
diff --git a/lib/plausible/auth/auth.ex b/lib/plausible/auth/auth.ex
index aedf5aa28b..7ae4fe86dc 100644
--- a/lib/plausible/auth/auth.ex
+++ b/lib/plausible/auth/auth.ex
@@ -97,6 +97,8 @@ defmodule Plausible.Auth do
}
}
+ @type registration_context() :: :default | :invitation
+
@rate_limit_types Map.keys(@rate_limits)
@type rate_limit_type() :: unquote(Enum.reduce(@rate_limit_types, &{:|, [], [&1, &2]}))
@@ -122,6 +124,27 @@ defmodule Plausible.Auth do
:ok
end
+ @spec check_registration_enabled(registration_context()) ::
+ :ok | {:error, registration_context(), String.t()}
+ def check_registration_enabled(context \\ :default) do
+ disabled_for =
+ if context == :invitation do
+ [true]
+ else
+ [:invite_only, true]
+ end
+
+ selfhost_config = Application.fetch_env!(:plausible, :selfhost)
+ disable_registration = Keyword.fetch!(selfhost_config, :disable_registration)
+ first_launch? = Plausible.Release.should_be_first_launch?()
+
+ if not first_launch? and disable_registration in disabled_for do
+ {:error, disable_registration, "Registration is disabled on this instance"}
+ else
+ :ok
+ end
+ end
+
@spec find_user_by(Keyword.t()) :: Auth.User.t() | nil
def find_user_by(opts) do
Repo.get_by(Auth.User, opts)
diff --git a/lib/plausible_web/components/layouts/header.html.heex b/lib/plausible_web/components/layouts/header.html.heex
index d4c2fa00bf..3b731b9455 100644
--- a/lib/plausible_web/components/layouts/header.html.heex
+++ b/lib/plausible_web/components/layouts/header.html.heex
@@ -133,7 +133,7 @@
</li>
<li :if={ee?()} id="changelog-notification" class="relative py-2"></li>
</ul>
- <% Keyword.fetch!(Application.get_env(:plausible, :selfhost), :disable_registration) != false -> %>
+ <% Plausible.Auth.check_registration_enabled() != :ok -> %>
<ul class="flex" x-show="!document.cookie.includes('logged_in=true')">
<li>
<div class="inline-flex">
diff --git a/lib/plausible_web/controllers/auth_controller.ex b/lib/plausible_web/controllers/auth_controller.ex
index 76974cf9da..57a2cc6d8d 100644
--- a/lib/plausible_web/controllers/auth_controller.ex
+++ b/lib/plausible_web/controllers/auth_controller.ex
@@ -352,6 +352,15 @@ defmodule PlausibleWeb.AuthController do
conn |> send_resp(403, "") |> halt()
end
+ def invitation_expired(conn, _params) do
+ render(conn, "invitation_expired.html",
+ legacy_layout?: false,
+ heading: "Invitation no longer valid",
+ subtitle:
+ "This invitation has expired or was revoked. Ask your team admin to send you a new invitation. "
+ )
+ end
+
defp accept_team_invitation(conn, team_identifier, user, params \\ [])
defp accept_team_invitation(conn, no_identifier, _user, params)
diff --git a/lib/plausible_web/live/register_form.ex b/lib/plausible_web/live/register_form.ex
index bf4b5363ad..e28e9c041b 100644
--- a/lib/plausible_web/live/register_form.ex
+++ b/lib/plausible_web/live/register_form.ex
@@ -33,13 +33,7 @@ defmodule PlausibleWeb.Live.RegisterForm do
if socket.assigns.live_action == :register_from_invitation_form and
socket.assigns.invitation == nil do
- {:ok,
- assign(socket,
- invitation_expired: true,
- heading: "Invitation no longer valid",
- subtitle:
- "This invitation has expired or was revoked. Ask your team admin to send you a new invitation."
- )}
+ {:ok, redirect(socket, to: "/invitation-expired")}
else
changeset =
if invitation = socket.assigns.invitation do
@@ -77,21 +71,6 @@ defmodule PlausibleWeb.Live.RegisterForm do
end
end
- def render(%{invitation_expired: true} = assigns) do
- ~H"""
- <Layouts.auth heading={@heading} subtitle={@subtitle} flash={@flash}>
- <.auth_container class="flex gap-3 justify-center">
- <.button_link href="/register" mt?={false}>
- Start free trial
- </.button_link>
- <.button_link href="/login" theme="secondary" mt?={false}>
- Sign in
- </.button_link>
- </.auth_container>
- </Layouts.auth>
- """
- end
-
def render(assigns) do
~H"""
<Layouts.auth heading={@heading} subtitle={@subtitle} flash={@flash}>
@@ -257,27 +236,49 @@ defmodule PlausibleWeb.Live.RegisterForm do
%{"user" => _} = params,
%{assigns: %{invitation: %{} = invitation}} = socket
) do
- if PlausibleWeb.Captcha.verify(params["frc-captcha-response"]) do
- user =
- params["user"]
- |> Map.put("email", invitation.email)
- |> Auth.User.new()
+ case Plausible.Auth.check_registration_enabled(:invitation) do
+ :ok ->
+ if PlausibleWeb.Captcha.verify(params["frc-captcha-response"]) do
+ user =
+ params["user"]
+ |> Map.put("email", invitation.email)
+ |> Auth.User.new()
- with_team? = invitation.type == :site_transfer
+ with_team? = invitation.type == :site_transfer
- add_user(socket, user, with_team?: with_team?)
- else
- {:noreply, captcha_failed(socket)}
+ add_user(socket, user, with_team?: with_team?)
+ else
+ {:noreply, captcha_failed(socket)}
+ end
+
+ {:error, _, message} ->
+ socket =
+ socket
+ |> put_flash(:error, message)
+ |> redirect(to: Routes.auth_path(socket, :login_form))
+
+ {:noreply, socket}
end
end
def handle_event("register", %{"user" => _} = params, socket) do
- if PlausibleWeb.Captcha.verify(params["frc-captcha-response"]) do
- user = Auth.User.new(params["user"])
+ case Plausible.Auth.check_registration_enabled(:default) do
+ :ok ->
+ if PlausibleWeb.Captcha.verify(params["frc-captcha-response"]) do
+ user = Auth.User.new(params["user"])
- add_user(socket, user)
- else
- {:noreply, captcha_failed(socket)}
+ add_user(socket, user)
+ else
+ {:noreply, captcha_failed(socket)}
+ end
+
+ {:error, _, message} ->
+ socket =
+ socket
+ |> put_flash(:error, message)
+ |> redirect(to: Routes.auth_path(socket, :login_form))
+
+ {:noreply, socket}
end
end
diff --git a/lib/plausible_web/live/registration_context.ex b/lib/plausible_web/live/registration_context.ex
new file mode 100644
index 0000000000..cf0b5cb2aa
--- /dev/null
+++ b/lib/plausible_web/live/registration_context.ex
@@ -0,0 +1,24 @@
+defmodule PlausibleWeb.Live.RegistrationContext do
+ @moduledoc """
+ Live context toggling registration according to selfhosted state.
+ """
+
+ import Phoenix.LiveView
+
+ alias PlausibleWeb.Router.Helpers, as: Routes
+
+ def on_mount(context, _params, _session, socket) do
+ case Plausible.Auth.check_registration_enabled(context) do
+ :ok ->
+ {:cont, socket}
+
+ {:error, _, message} ->
+ socket =
+ socket
+ |> put_flash(:error, message)
+ |> redirect(to: Routes.auth_path(socket, :login_form))
+
+ {:halt, socket}
+ end
+ end
+end
diff --git a/lib/plausible_web/plugs/maybe_disable_registration.ex b/lib/plausible_web/plugs/maybe_disable_registration.ex
index 7c05a7b910..d578d3d018 100644
--- a/lib/plausible_web/plugs/maybe_disable_registration.ex
+++ b/lib/plausible_web/plugs/maybe_disable_registration.ex
@@ -6,7 +6,6 @@ defmodule PlausibleWeb.Plugs.MaybeDisableRegistration do
import Phoenix.Controller
import Plug.Conn
- alias Plausible.Release
alias PlausibleWeb.Router.Helpers, as: Routes
def init(opts) do
@@ -14,19 +13,15 @@ defmodule PlausibleWeb.Plugs.MaybeDisableRegistration do
end
def call(conn, _opts) do
- disabled_for = List.wrap(conn.assigns.disable_registration_for)
+ case Plausible.Auth.check_registration_enabled(conn.assigns.registration_context) do
+ :ok ->
+ conn
- selfhost_config = Application.get_env(:plausible, :selfhost)
- disable_registration = Keyword.fetch!(selfhost_config, :disable_registration)
- first_launch? = Release.should_be_first_launch?()
-
- if not first_launch? and disable_registration in disabled_for do
- conn
- |> put_flash(:error, "Registration is disabled on this instance")
- |> redirect(to: Routes.auth_path(conn, :login_form))
- |> halt()
- else
- conn
+ {:error, _, message} ->
+ conn
+ |> put_flash(:error, message)
+ |> redirect(to: Routes.auth_path(conn, :login_form))
+ |> halt()
end
end
end
diff --git a/lib/plausible_web/router.ex b/lib/plausible_web/router.ex
index fd2c69f891..d591d96cb2 100644
--- a/lib/plausible_web/router.ex
+++ b/lib/plausible_web/router.ex
@@ -438,21 +438,26 @@ defmodule PlausibleWeb.Router do
scope alias: Live, assigns: %{connect_live_socket: true} do
pipe_through [PlausibleWeb.RequireLoggedOutPlug, :app_layout]
- scope assigns: %{disable_registration_for: [:invite_only, true]} do
+ scope assigns: %{registration_context: :default} do
pipe_through PlausibleWeb.Plugs.MaybeDisableRegistration
- live "/register", RegisterForm, :register_form, as: :auth
+ live_session :default, on_mount: PlausibleWeb.Live.RegistrationContext do
+ live "/register", RegisterForm, :register_form, as: :auth
+ end
end
scope assigns: %{
- disable_registration_for: true,
+ registration_context: :invitation,
dogfood_page_path: "/register/invitation/:invitation_id"
} do
pipe_through PlausibleWeb.Plugs.MaybeDisableRegistration
- live "/register/invitation/:invitation_id",
- RegisterForm,
- :register_from_invitation_form, as: :auth
+ live_session :invitation,
+ on_mount: {PlausibleWeb.Live.RegistrationContext, :invitation} do
+ live "/register/invitation/:invitation_id",
+ RegisterForm,
+ :register_from_invitation_form, as: :auth
+ end
end
end
@@ -462,6 +467,8 @@ defmodule PlausibleWeb.Router do
get "/login", AuthController, :login_form
post "/login", AuthController, :login
+ get "/invitation-expired", AuthController, :invitation_expired
+
get "/login/oauth/authorize", OAuth.AuthorizeController, :authorize_form
post "/login/oauth/authorize", OAuth.AuthorizeController, :authorize
diff --git a/lib/plausible_web/templates/auth/invitation_expired.html.heex b/lib/plausible_web/templates/auth/invitation_expired.html.heex
new file mode 100644
index 0000000000..bbd4715882
--- /dev/null
+++ b/lib/plausible_web/templates/auth/invitation_expired.html.heex
@@ -0,0 +1,14 @@
+<Layouts.auth heading={@heading} subtitle={@subtitle} flash={@flash}>
+ <.auth_container class="flex gap-3 justify-center">
+ <.button_link
+ :if={Plausible.Auth.check_registration_enabled() == :ok}
+ href="/register"
+ mt?={false}
+ >
+ Start free trial
+ </.button_link>
+ <.button_link href="/login" theme="secondary" mt?={false}>
+ Sign in
+ </.button_link>
+ </.auth_container>
+</Layouts.auth>
diff --git a/lib/plausible_web/templates/auth/login_form.html.heex b/lib/plausible_web/templates/auth/login_form.html.heex
index 24bceebcaf..f94fea8de9 100644
--- a/lib/plausible_web/templates/auth/login_form.html.heex
+++ b/lib/plausible_web/templates/auth/login_form.html.heex
@@ -1,4 +1,4 @@
-<Layouts.auth heading={@heading} subtitle={@subtitle}>
+<Layouts.auth heading={@heading} subtitle={@subtitle} flash={@flash}>
<.auth_container>
<.form :let={f} for={@conn} action="/login" class="flex flex-col gap-y-6">
<div class="flex flex-col gap-y-2">
@@ -48,10 +48,7 @@
<div class="flex flex-col gap-y-2">
<p
- :if={
- Keyword.fetch!(Application.get_env(:plausible, :selfhost), :disable_registration) ==
- false
- }
+ :if={Plausible.Auth.check_registration_enabled() == :ok}
class="text-sm text-center text-gray-500 dark:text-gray-400"
>
New here? <.styled_link href="/register">Create your account</.styled_link>
diff --git a/lib/plausible_web/templates/page/index.html.heex b/lib/plausible_web/templates/page/index.html.heex
index 09d7b52012..6a7b4e0f8e 100644
--- a/lib/plausible_web/templates/page/index.html.heex
+++ b/lib/plausible_web/templates/page/index.html.heex
@@ -20,7 +20,7 @@
Login
</.styled_link>
</:item>
- <:item>
+ <:item :if={Plausible.Auth.check_registration_enabled() == :ok}>
<.styled_link href={Routes.auth_path(@conn, :register_form)}>
Register
</.styled_link>
diff --git a/test/plausible_web/controllers/auth_controller_test.exs b/test/plausible_web/controllers/auth_controller_test.exs
index 26208da92c..0e21403f2f 100644
--- a/test/plausible_web/controllers/auth_controller_test.exs
+++ b/test/plausible_web/controllers/auth_controller_test.exs
@@ -29,6 +29,16 @@ defmodule PlausibleWeb.AuthControllerTest do
end
end
+ describe "GET /invitation-expired" do
+ test "shows invitation expired notification", %{conn: conn} do
+ conn = get(conn, "/invitation-expired")
+
+ html = html_response(conn, 200)
+
+ assert html =~ "This invitation has expired or was revoked"
+ end
+ end
+
describe "POST /login (register_action = register_form)" do
test "registering sends an activation link", %{conn: conn} do
Repo.insert!(
diff --git a/test/plausible_web/live/register_form_sync_test.exs b/test/plausible_web/live/register_form_sync_test.exs
new file mode 100644
index 0000000000..4ff3b2b64e
--- /dev/null
+++ b/test/plausible_web/live/register_form_sync_test.exs
@@ -0,0 +1,207 @@
+defmodule PlausibleWeb.Live.RegisterFormSyncTest do
+ use PlausibleWeb.ConnCase, async: false
+
+ import Mox
+ import Phoenix.LiveViewTest
+
+ alias Plausible.Auth.User
+ alias Plausible.Repo
+
+ @strong_password "very-long-and-very-secret-123"
+
+ setup do
+ # A pre-existing user keeps the instance from being treated as a brand new
+ # install, where creating the very first user is allowed and registration is
+ # never disabled. Every test here depends on that.
+ inviter = new_user()
+ site = new_site(owner: inviter)
+ invitation = invite_guest(site, build(:user).email, role: :editor, inviter: inviter)
+
+ {:ok, invitation: invitation}
+ end
+
+ describe "DISABLE_REGISTRATION=invite_only" do
+ setup do
+ patch_disable_registration(:invite_only)
+ end
+
+ test "public /register is blocked on HTTP page load", %{conn: conn} do
+ conn = get(conn, "/register")
+ assert redirected_to(conn) == "/login"
+ end
+
+ test "register LiveView is disabled on invite only instance", %{conn: conn} do
+ assert {:error, {:redirect, %{to: "/login", flash: flash}}} = live(conn, "/register")
+
+ assert flash["error"] == "Registration is disabled on this instance"
+ end
+
+ test "register event over the LiveView socket cannot bypass invite_only via an invalid invitation",
+ %{conn: conn} do
+ mock_captcha_success()
+
+ assert {:error, {:redirect, %{to: "/invitation-expired"}}} =
+ live(conn, "/register/invitation/does-not-exist")
+ end
+
+ test "registration from a valid invitation still works", %{conn: conn, invitation: invitation} do
+ mock_captcha_success()
+
+ {:ok, lv, _html} = live(conn, "/register/invitation/#{invitation.invitation_id}")
+
+ lv
+ |> element("form")
+ |> render_submit(%{"user" => %{"name" => "Mary Sue", "password" => @strong_password}})
+
+ assert Repo.get_by(User, email: invitation.team_invitation.email)
+ end
+ end
+
+ describe "DISABLE_REGISTRATION=true" do
+ setup do
+ patch_disable_registration(true)
+ end
+
+ test "register LiveView is disabled on fully disabled instance", %{conn: conn} do
+ assert {:error, {:redirect, %{to: "/login", flash: flash}}} = live(conn, "/register")
+
+ assert flash["error"] == "Registration is disabled on this instance"
+ end
+
+ test "register event from a valid invitation cannot bypass a fully disabled instance",
+ %{conn: conn, invitation: invitation} do
+ assert {:error, {:redirect, %{to: "/login", flash: flash}}} =
+ live(conn, "/register/invitation/#{invitation.invitation_id}")
+
+ assert flash["error"] == "Registration is disabled on this instance"
+ end
+
+ test "register event without a valid invitation cannot bypass a fully disabled instance",
+ %{conn: conn} do
+ assert {:error, {:redirect, %{to: "/login", flash: flash}}} =
+ live(conn, "/register/invitation/does-not-exist")
+
+ assert flash["error"] == "Registration is disabled on this instance"
+ end
+ end
+
+ describe "DISABLE_REGISTRATION=true with another session open" do
+ setup do
+ # We emulate a situation where another user has a LV session running when
+ # the first user registers in the meantime.
+ patch_disable_registration(false)
+ end
+
+ test "concluding register isn't allowed for ongoing session", %{conn: conn} do
+ {:ok, lv, _html} = live(conn, "/register")
+
+ patch_disable_registration(true)
+
+ attacker_email = build(:user).email
+
+ result =
+ render_hook(lv, "register", %{
+ "user" => %{
+ "name" => "Attacker",
+ "email" => attacker_email,
+ "password" => @strong_password
+ }
+ })
+
+ refute Repo.get_by(User, email: attacker_email)
+ # flash seems to be serialized to cookie encoded format,
+ # but it's confirmed to show the right notification
+ assert {:error, {:redirect, %{to: "/login", flash: _}}} = result
+ end
+
+ test "concluding register from invitation isn't allowed for ongoing session", %{
+ conn: conn,
+ invitation: invitation
+ } do
+ {:ok, lv, _html} = live(conn, "/register/invitation/#{invitation.invitation_id}")
+
+ patch_disable_registration(true)
+
+ attacker_email = build(:user).email
+
+ result =
+ render_hook(lv, "register", %{
+ "user" => %{
+ "name" => "Attacker",
+ "email" => attacker_email,
+ "password" => @strong_password
+ }
+ })
+
+ refute Repo.get_by(User, email: attacker_email)
+ # flash seems to be serialized to cookie encoded format,
+ # but it's confirmed to show the right notification
+ assert {:error, {:redirect, %{to: "/login", flash: _}}} = result
+ end
+ end
+
+ describe "DISABLE_REGISTRATION=invite_only with another session open" do
+ setup do
+ # We emulate a situation where another user has a LV session running when
+ # the first user registers in the meantime.
+ patch_disable_registration(false)
+ end
+
+ test "concluding register isn't allowed for ongoing session", %{conn: conn} do
+ {:ok, lv, _html} = live(conn, "/register")
+
+ patch_disable_registration(:invite_only)
+
+ attacker_email = build(:user).email
+
+ result =
+ render_hook(lv, "register", %{
+ "user" => %{
+ "name" => "Attacker",
+ "email" => attacker_email,
+ "password" => @strong_password
+ }
+ })
+
+ refute Repo.get_by(User, email: attacker_email)
+ # flash seems to be serialized to cookie encoded format,
+ # but it's confirmed to show the right notification
+ assert {:error, {:redirect, %{to: "/login", flash: _}}} = result
+ end
+
+ test "concluding register from invitation is still allowed for ongoing session", %{
+ conn: conn,
+ invitation: invitation
+ } do
+ mock_captcha_success()
+ {:ok, lv, _html} = live(conn, "/register/invitation/#{invitation.invitation_id}")
+
+ patch_disable_registration(:invite_only)
+
+ lv
+ |> element("form")
+ |> render_submit(%{"user" => %{"name" => "Mary Sue", "password" => @strong_password}})
+
+ assert Repo.get_by(User, email: invitation.team_invitation.email)
+ end
+ end
+
+ defp patch_disable_registration(value) do
+ selfhost_config = Application.get_env(:plausible, :selfhost)
+ patch_env(:selfhost, Keyword.put(selfhost_config, :disable_registration, value))
+ end
+
+ # Captcha is enabled in the test env, so make it pass. Without this a guard
+ # regression would still be stopped by the captcha, and these tests would pass
+ # for the wrong reason.
+ defp mock_captcha_success do
+ stub(Plausible.HTTPClient.Mock, :post, fn _url, _headers, _body ->
+ {:ok,
+ %Finch.Response{
+ status: 200,
+ headers: [{"content-type", "application/json"}],
+ body: %{"success" => true}
+ }}
+ end)
+ end
+end
diff --git a/test/plausible_web/live/register_form_test.exs b/test/plausible_web/live/register_form_test.exs
index e4b2e5d3cc..b5913976d2 100644
--- a/test/plausible_web/live/register_form_test.exs
+++ b/test/plausible_web/live/register_form_test.exs
@@ -254,12 +254,11 @@ defmodule PlausibleWeb.Live.RegisterFormTest do
refute Repo.get_by(User, email: "[email protected]")
end
- test "renders expired invitation notice on on-existent invitation ID", %{conn: conn} do
- lv = get_liveview(conn, "/register/invitation/doesnotexist")
+ test "redirects to expired invitation notice on on-existent invitation ID", %{conn: conn} do
+ conn = assign(conn, :live_module, PlausibleWeb.Live.RegisterForm)
- html = render(lv)
-
- assert html =~ "This invitation has expired or was revoked"
+ assert {:error, {:redirect, %{to: "/invitation-expired"}}} =
+ live(conn, "/register/invitation/doesnotexist")
end
test "renders error on failed captcha", %{conn: conn, guest_invitation: guest_invitation} do