Skip to content

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

Limit team name length and content (#6617)

Artur Patab7e86f6d26e4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e9ecae6424..1ec7e111a4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -45,6 +45,7 @@ All notable changes to this project will be documented in this file.
- Moved tracking options (outbound links, file downloads, form submissions) from the installation page to the general site settings, where they can be toggled without going through the installation flow
- Replaced HCaptcha with Friendly Captcha
- Redesigned funnel report on dashboard to be more consistent with the rest of the UI. It now includes a `Strict`/`Sequential` label, and percentage drop-off between individual funnel steps is now visible by default.
+- Team names are now limited to 50 characters and cannot contain URLs with an explicit scheme (e.g. `https://`)
### Fixed
diff --git a/e2e/tests/dashboard/team-setup.spec.ts b/e2e/tests/dashboard/team-setup.spec.ts
index 0a66f6e910..47a0926da5 100644
--- a/e2e/tests/dashboard/team-setup.spec.ts
+++ b/e2e/tests/dashboard/team-setup.spec.ts
@@ -1,6 +1,6 @@
import { test, expect } from '@playwright/test'
-import { setupSite } from '../fixtures'
-import { expectLiveViewConnected } from '../test-utils'
+import { register, setupSite } from '../fixtures'
+import { expectLiveViewConnected, randomID } from '../test-utils'
test('submitting team name via Enter key does not crash', async ({
page,
@@ -69,3 +69,69 @@ test('create team is blocked while the name is rejected', async ({
'Fixed Team Name'
)
})
+
+test('creating a team when the user name is long', async ({
+ page,
+ request
+}) => {
+ const userID = randomID()
+ // exactly 55 characters, prefixed with a unique ID so that `register` finds
+ // exactly one activation e-mail for this user
+ const longName = `${userID}${'a'.repeat(55)}`.slice(0, 55)
+ // the user name gets shortened to fit the 50 character team name limit
+ const expectedTeamName = `${longName.slice(0, 43)}'s team`
+
+ const user = {
+ name: longName,
+ email: `email-${userID}@example.com`,
+ password: 'VeryStrongVerySecret'
+ }
+
+ await register({ page, request, user })
+ await setupSite({ page, request, user })
+
+ await page.goto('/team/setup', { waitUntil: 'commit' })
+
+ await expectLiveViewConnected(page)
+
+ // the page mounts instead of crashing on the over-long suggested name
+ await expect(page.getByRole('button', { name: 'Create Team' })).toBeVisible()
+
+ const nameInput = page.locator('input[name="team[name]"]')
+
+ await expect(nameInput).toHaveValue(expectedTeamName)
+
+ await test.step('a name over the limit is rejected', async () => {
+ await nameInput.fill('b'.repeat(51))
+
+ await expect(page.locator('#update-team-form')).toContainText(
+ 'should be at most 50 character(s)'
+ )
+ await expect(
+ page.getByRole('button', { name: 'Create Team' })
+ ).toBeDisabled()
+ })
+
+ await test.step('a name carrying a URL scheme is rejected', async () => {
+ await nameInput.fill('Cheap meds at https://spam.example.com')
+
+ await expect(page.locator('#update-team-form')).toContainText(
+ 'cannot contain a URL'
+ )
+ await expect(
+ page.getByRole('button', { name: 'Create Team' })
+ ).toBeDisabled()
+ })
+
+ await nameInput.fill('Chosen Team Name')
+
+ await page.getByRole('button', { name: 'Create Team' }).click()
+
+ await expect(page).toHaveURL(/\/settings\/team\/general/)
+
+ await expectLiveViewConnected(page)
+
+ await expect(page.locator('input[name="team[name]"]')).toHaveValue(
+ 'Chosen Team Name'
+ )
+})
diff --git a/lib/plausible/teams/team.ex b/lib/plausible/teams/team.ex
index bd4872c3df..0f4608b9e8 100644
--- a/lib/plausible/teams/team.ex
+++ b/lib/plausible/teams/team.ex
@@ -21,6 +21,13 @@ defmodule Plausible.Teams.Team do
@trial_accept_traffic_until_offset_days 14
@subscription_accept_traffic_until_offset_days 30
+ @max_name_length 50
+ # `teams.name` is a varchar(255), which counts code points. Capping bytes
+ # keeps the column safe, since a code point is never shorter than a byte.
+ @max_name_bytes 255
+ @suggested_name_suffix "'s team"
+ @suggested_name_fallback "My team"
+
on_ee do
@derive {Plausible.Audit.Encoder,
only: [
@@ -84,6 +91,35 @@ defmodule Plausible.Teams.Team do
timestamps()
end
+ @doc """
+ Builds the team name suggested for a user, shortening the user's name as
+ needed, so that the result stays within the name length limit.
+
+ Falls back to a generic name when the user's name would make the suggestion
+ invalid, so that the suggestion is always safe to persist.
+ """
+ def suggested_name(user_name) when is_binary(user_name) do
+ room = @max_name_length - String.length(@suggested_name_suffix)
+
+ suggested =
+ user_name
+ |> String.slice(0, room)
+ |> String.trim_trailing()
+ |> Kernel.<>(@suggested_name_suffix)
+
+ if valid_suggestion?(suggested) do
+ suggested
+ else
+ @suggested_name_fallback
+ end
+ end
+
+ def suggested_name(_user_name), do: @suggested_name_fallback
+
+ defp valid_suggestion?(name) do
+ byte_size(name) <= @max_name_bytes and not contains_scheme?(name)
+ end
+
def crm_changeset(team, params) do
team
|> cast(params, [
@@ -93,6 +129,7 @@ defmodule Plausible.Teams.Team do
:allow_next_upgrade_override,
:accept_traffic_until
])
+ |> validate_name()
|> maybe_bump_accept_traffic_until()
end
@@ -100,6 +137,7 @@ defmodule Plausible.Teams.Team do
team
|> cast(attrs, [:name])
|> validate_required(:name)
+ |> validate_name()
|> start_trial(today)
|> maybe_bump_accept_traffic_until()
|> maybe_set_identifier()
@@ -109,6 +147,7 @@ defmodule Plausible.Teams.Team do
team
|> cast(attrs, [:name])
|> validate_required(:name)
+ |> validate_name()
|> validate_exclusion(:name, [Plausible.Teams.default_name()])
end
@@ -133,6 +172,23 @@ defmodule Plausible.Teams.Team do
change(team, trial_expiry_date: Date.utc_today() |> Date.shift(day: -1))
end
+ defp validate_name(changeset) do
+ changeset
+ |> validate_length(:name, max: @max_name_length)
+ |> validate_length(:name, count: :bytes, max: @max_name_bytes)
+ |> validate_change(:name, fn :name, name ->
+ if contains_scheme?(name) do
+ [name: "cannot contain a URL"]
+ else
+ []
+ end
+ end)
+ end
+
+ # Team names end up in invitation e-mails, so reject names carrying an
+ # explicit URL scheme. Bare hostnames are deliberately left alone.
+ defp contains_scheme?(name), do: String.contains?(name, "://")
+
defp maybe_set_identifier(changeset) do
if get_field(changeset, :identifier) do
changeset
diff --git a/lib/plausible_web/live/team_management.ex b/lib/plausible_web/live/team_management.ex
index 939509ffca..be42a2a796 100644
--- a/lib/plausible_web/live/team_management.ex
+++ b/lib/plausible_web/live/team_management.ex
@@ -33,13 +33,16 @@ defmodule PlausibleWeb.Live.TeamManagement do
defp setup_team_name(
%{assigns: %{current_user: current_user, current_team: current_team}} = socket
) do
+ suggested_name = Teams.Team.suggested_name(current_user.name)
+
current_team =
current_team
- |> Teams.Team.name_changeset(%{name: "#{current_user.name}'s team"})
+ |> Teams.Team.name_changeset(%{name: suggested_name})
|> Plausible.Repo.update!()
assign(socket,
current_team: current_team,
+ suggested_name: suggested_name,
team_name_form: to_form(Teams.Team.name_changeset(current_team, %{})),
locked?: Plausible.Teams.Billing.solo?(current_team)
)
@@ -76,7 +79,7 @@ defmodule PlausibleWeb.Live.TeamManagement do
>
<.input
type="text"
- placeholder={"#{@current_user.name}'s team"}
+ placeholder={@suggested_name}
autofocus={not @locked?}
field={f[:name]}
label="Name"
diff --git a/test/plausible/teams/team_test.exs b/test/plausible/teams/team_test.exs
new file mode 100644
index 0000000000..1914b632d0
--- /dev/null
+++ b/test/plausible/teams/team_test.exs
@@ -0,0 +1,161 @@
+defmodule Plausible.Teams.TeamTest do
+ use Plausible.DataCase, async: true
+
+ alias Plausible.Teams.Team
+
+ @too_long_error {"should be at most %{count} character(s)",
+ [count: 50, validation: :length, kind: :max, type: :string]}
+ @too_many_bytes_error {"should be at most %{count} byte(s)",
+ [count: 255, validation: :length, kind: :max, type: :binary]}
+ @url_error {"cannot contain a URL", []}
+
+ describe "name_changeset/2" do
+ test "accepts a name at exactly the limit" do
+ assert Team.name_changeset(%Team{}, %{name: String.duplicate("a", 50)}).errors == []
+ end
+
+ test "rejects a name one character over the limit" do
+ assert Team.name_changeset(%Team{}, %{name: String.duplicate("a", 51)}).errors == [
+ name: @too_long_error
+ ]
+ end
+
+ test "rejects a name that fits the limit but overflows the column" do
+ # 50 graphemes of family emoji is 350 code points in a varchar(255)
+ name = String.duplicate("πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦", 50)
+
+ assert String.length(name) == 50
+ assert Team.name_changeset(%Team{}, %{name: name}).errors == [name: @too_many_bytes_error]
+ end
+
+ test "rejects names carrying a URL scheme" do
+ for name <- [
+ "https://spam.example.com",
+ "http://spam.example.com/buy?x=1",
+ "Cheap meds at https://spam.example.com",
+ "ftp://spam.example.com",
+ "HTTPS://SPAM.EXAMPLE.COM"
+ ] do
+ assert Team.name_changeset(%Team{}, %{name: name}).errors == [name: @url_error],
+ "expected #{inspect(name)} to be rejected"
+ end
+ end
+
+ test "accepts names without a scheme, bare hostnames included" do
+ for name <- [
+ "My Team",
+ "spam.example.com",
+ "www.spam.example.com",
+ "Team example.co.uk",
+ "Vue.js Team",
+ "St. Louis Marketing",
+ "Smith & Co.",
+ "A-Team!"
+ ] do
+ assert Team.name_changeset(%Team{}, %{name: name}).errors == [],
+ "expected #{inspect(name)} to be accepted"
+ end
+ end
+ end
+
+ describe "changeset/3 and crm_changeset/2" do
+ test "reject a name over the limit" do
+ name = String.duplicate("a", 51)
+
+ assert Team.changeset(%Team{}, %{name: name}).errors == [name: @too_long_error]
+ assert Team.crm_changeset(%Team{}, %{name: name}).errors == [name: @too_long_error]
+ end
+
+ test "reject a name carrying a URL scheme" do
+ name = "https://spam.example.com"
+
+ assert Team.changeset(%Team{}, %{name: name}).errors == [name: @url_error]
+ assert Team.crm_changeset(%Team{}, %{name: name}).errors == [name: @url_error]
+ end
+ end
+
+ describe "names already stored in violation of the rules" do
+ test "stay valid as long as the name is not changed" do
+ for stored <- [String.duplicate("a", 80), "https://spam.example.com"] do
+ team = new_user(team: [name: stored]) |> team_of()
+
+ assert team.name == stored
+ assert Team.name_changeset(team).errors == []
+ assert Team.name_changeset(team, %{name: stored}).errors == []
+ end
+ end
+
+ test "can be renamed to a name within the limit" do
+ team = new_user(team: [name: String.duplicate("a", 80)]) |> team_of()
+
+ assert {:ok, team} = Repo.update(Team.name_changeset(team, %{name: "Shorter"}))
+ assert team.name == "Shorter"
+ end
+
+ test "cannot be renamed to another name over the limit" do
+ team = new_user(team: [name: String.duplicate("a", 80)]) |> team_of()
+
+ assert Team.name_changeset(team, %{name: String.duplicate("b", 51)}).errors == [
+ name: @too_long_error
+ ]
+
+ assert Team.name_changeset(team, %{name: "https://spam.example.com"}).errors == [
+ name: @url_error
+ ]
+ end
+ end
+
+ describe "suggested_name/1" do
+ test "appends the suffix to a short name" do
+ assert Team.suggested_name("Jane") == "Jane's team"
+ end
+
+ test "shortens a long name so that the result fits the limit" do
+ assert Team.suggested_name(String.duplicate("a", 55)) ==
+ String.duplicate("a", 43) <> "'s team"
+ end
+
+ test "trims the whitespace that shortening leaves behind" do
+ assert Team.suggested_name(String.duplicate("a", 42) <> " Smith") ==
+ String.duplicate("a", 42) <> "'s team"
+ end
+
+ test "falls back to a generic name when shortening still overflows the column" do
+ assert Team.suggested_name(String.duplicate("πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦", 36)) == "My team"
+ end
+
+ test "falls back to a generic name when the user has no name" do
+ assert Team.suggested_name(nil) == "My team"
+ end
+
+ test "falls back to a generic name when the user name carries a URL scheme" do
+ assert Team.suggested_name("Cheap meds https://spam.example.com") == "My team"
+ end
+
+ test "falls back to a generic name when a URL scheme survives shortening" do
+ assert Team.suggested_name("https://spam.example.com " <> String.duplicate("a", 55)) ==
+ "My team"
+ end
+
+ test "keeps the shortened name when shortening cuts the URL scheme off" do
+ assert Team.suggested_name(String.duplicate("a", 50) <> " https://spam.example.com") ==
+ String.duplicate("a", 43) <> "'s team"
+ end
+
+ test "always returns a name the changeset accepts" do
+ for user_name <- [
+ "Jane",
+ nil,
+ String.duplicate("a", 55),
+ String.duplicate("πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦", 36),
+ "Cheap meds https://spam.example.com"
+ ] do
+ suggested = Team.suggested_name(user_name)
+
+ assert Team.name_changeset(%Team{}, %{name: suggested}).errors == [],
+ "expected #{inspect(suggested)} to be accepted"
+ end
+ end
+ end
+end
diff --git a/test/plausible_web/controllers/settings_controller_test.exs b/test/plausible_web/controllers/settings_controller_test.exs
index 9aaf3917c3..a4d59a392f 100644
--- a/test/plausible_web/controllers/settings_controller_test.exs
+++ b/test/plausible_web/controllers/settings_controller_test.exs
@@ -1656,6 +1656,78 @@ defmodule PlausibleWeb.SettingsControllerTest do
assert text(html_response(conn, 200)) =~ "can't be blank"
end
+ test "POST /settings/team/general/name - name longer than the limit", %{
+ conn: conn,
+ user: user
+ } do
+ {:ok, team} = Plausible.Teams.get_or_create(user)
+ team = Plausible.Teams.complete_setup(team)
+ conn = set_current_team(conn, team)
+
+ conn =
+ post(conn, Routes.settings_path(conn, :update_team_name), %{
+ "team" => %{"name" => String.duplicate("a", 51)}
+ })
+
+ assert text(html_response(conn, 200)) =~ "should be at most 50 character(s)"
+ assert Repo.reload!(team).name == "My personal sites"
+ end
+
+ test "POST /settings/team/general/name - name containing a URL", %{
+ conn: conn,
+ user: user
+ } do
+ {:ok, team} = Plausible.Teams.get_or_create(user)
+ team = Plausible.Teams.complete_setup(team)
+ conn = set_current_team(conn, team)
+
+ conn =
+ post(conn, Routes.settings_path(conn, :update_team_name), %{
+ "team" => %{"name" => "Cheap meds at https://spam.example.com"}
+ })
+
+ assert text(html_response(conn, 200)) =~ "cannot contain a URL"
+ assert Repo.reload!(team).name == "My personal sites"
+ end
+
+ test "GET /settings/team/general - team name already longer than the limit", %{
+ conn: conn,
+ user: user
+ } do
+ {:ok, team} = Plausible.Teams.get_or_create(user)
+ team = Plausible.Teams.complete_setup(team)
+
+ long_name = String.duplicate("a", 80)
+ team = team |> Ecto.Changeset.change(name: long_name) |> Repo.update!()
+
+ conn = set_current_team(conn, team)
+
+ html = html_response(get(conn, Routes.settings_path(conn, :team_general)), 200)
+
+ assert text_of_attr(html, "input#team_name", "value") == long_name
+ end
+
+ test "POST /settings/team/general/name - renaming a team whose name is over the limit", %{
+ conn: conn,
+ user: user
+ } do
+ {:ok, team} = Plausible.Teams.get_or_create(user)
+ team = Plausible.Teams.complete_setup(team)
+ team = team |> Ecto.Changeset.change(name: String.duplicate("a", 80)) |> Repo.update!()
+
+ conn = set_current_team(conn, team)
+
+ conn =
+ post(conn, Routes.settings_path(conn, :update_team_name), %{
+ "team" => %{"name" => "Shorter name"}
+ })
+
+ assert redirected_to(conn, 302) ==
+ Routes.settings_path(conn, :team_general) <> "#update-name"
+
+ assert Repo.reload!(team).name == "Shorter name"
+ end
+
test "POST /settings/team/leave", %{conn: conn, user: user} do
{:ok, team} = Plausible.Teams.get_or_create(user)
team = Plausible.Teams.complete_setup(team)
diff --git a/test/plausible_web/live/team_setup_test.exs b/test/plausible_web/live/team_setup_test.exs
index 91a7ca6d2e..9089500d46 100644
--- a/test/plausible_web/live/team_setup_test.exs
+++ b/test/plausible_web/live/team_setup_test.exs
@@ -25,6 +25,49 @@ defmodule PlausibleWeb.Live.TeamSetupTest do
end
end
+ describe "/team/setup - suggested team name" do
+ test "shortens a long user name to fit the limit", %{conn: conn} do
+ user = new_user(name: String.duplicate("a", 55))
+ {:ok, conn: conn} = log_in(%{user: user, conn: conn})
+ {:ok, team} = Teams.get_or_create(user)
+
+ {_lv, html} = get_child_lv(conn, with_html?: true)
+
+ expected = String.duplicate("a", 43) <> "'s team"
+
+ assert text_of_attr(html, ~s|input#update-team-form_name[name="team[name]"]|, "value") ==
+ expected
+
+ assert Repo.reload!(team).name == expected
+ end
+
+ test "falls back to a generic name when the user name carries a URL scheme", %{conn: conn} do
+ user = new_user(name: "Cheap meds https://spam.example.com")
+ {:ok, conn: conn} = log_in(%{user: user, conn: conn})
+ {:ok, team} = Teams.get_or_create(user)
+
+ {_lv, html} = get_child_lv(conn, with_html?: true)
+
+ assert text_of_attr(html, ~s|input#update-team-form_name[name="team[name]"]|, "value") ==
+ "My team"
+
+ assert Repo.reload!(team).name == "My team"
+ end
+
+ test "falls back to a generic name when shortening overflows the column", %{conn: conn} do
+ user = new_user(name: String.duplicate("πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦", 36))
+ {:ok, conn: conn} = log_in(%{user: user, conn: conn})
+ {:ok, team} = Teams.get_or_create(user)
+
+ {_lv, html} = get_child_lv(conn, with_html?: true)
+
+ assert text_of_attr(html, ~s|input#update-team-form_name[name="team[name]"]|, "value") ==
+ "My team"
+
+ assert Repo.reload!(team).name == "My team"
+ end
+ end
+
describe "/team/setup - main differences from team management" do
setup [:create_user, :log_in, :create_team]
@@ -95,6 +138,32 @@ defmodule PlausibleWeb.Live.TeamSetupTest do
assert Repo.reload!(team).name == "#{user.name}'s team"
end
+ test "setting team name containing a URL is rejected", %{conn: conn, team: team} do
+ lv = get_child_lv(conn)
+
+ type_into_input(lv, "team[name]", "Team Name 1")
+ _ = render(lv)
+
+ type_into_input(lv, "team[name]", "Cheap meds at https://spam.example.com")
+
+ assert render(lv) =~ "cannot contain a URL"
+ assert element_exists?(render(lv), "button#save-layout[disabled]")
+ assert Repo.reload!(team).name == "Team Name 1"
+ end
+
+ test "setting team name longer than the limit is rejected", %{conn: conn, team: team} do
+ lv = get_child_lv(conn)
+
+ type_into_input(lv, "team[name]", "Team Name 1")
+ _ = render(lv)
+
+ type_into_input(lv, "team[name]", String.duplicate("a", 51))
+
+ assert render(lv) =~ "should be at most 50 character(s)"
+ assert element_exists?(render(lv), "button#save-layout[disabled]")
+ assert Repo.reload!(team).name == "Team Name 1"
+ end
+
test "creating the team is blocked while the name is rejected", %{conn: conn, team: team} do
lv = get_child_lv(conn)