Skip to content

Lightweight server monitoring with historical data, docker stats, and alerts.

feat: rate limit sign-in attempts (#2641)

Daniel Jeremiah3ae9011ac4df
diff --git a/internal/hub/rate_limit_test.go b/internal/hub/rate_limit_test.go
new file mode 100644
index 000000000..ffb8c0d06
--- /dev/null
+++ b/internal/hub/rate_limit_test.go
@@ -0,0 +1,147 @@
+//go:build testing
+
+package hub_test
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ beszelTests "github.com/henrygd/beszel/internal/tests"
+ "github.com/pocketbase/dbx"
+ "github.com/pocketbase/pocketbase/core"
+ "github.com/stretchr/testify/require"
+)
+
+const requestLimitMigration = "1792483200_enable_request_limits.go"
+
+var signInRule = core.RateLimitRule{Label: "*:auth", MaxRequests: 10, Duration: 60}
+
+func TestPasswordSignInIsRateLimited(t *testing.T) {
+ testHub, handler := firstUserTestMux(t)
+ defer testHub.Cleanup()
+
+ settings := testHub.Settings()
+ require.True(t, settings.RateLimits.Enabled)
+ require.Equal(t, []core.RateLimitRule{signInRule}, settings.RateLimits.Rules)
+
+ user, err := beszelTests.CreateUser(testHub, "[email protected]", "password123")
+ require.NoError(t, err)
+ user.SetVerified(true)
+ require.NoError(t, testHub.Save(user))
+
+ for range signInRule.MaxRequests {
+ response := postPasswordSignIn(handler, "[email protected]", "password123")
+ require.Equal(t, http.StatusOK, response.Code, response.Body.String())
+ }
+
+ limited := postPasswordSignIn(handler, "[email protected]", "password123")
+ require.Equal(t, http.StatusTooManyRequests, limited.Code, limited.Body.String())
+}
+
+func TestRequestLimitMigration(t *testing.T) {
+ pbDefaults := []core.RateLimitRule{
+ {Label: "*:auth", MaxRequests: 2, Duration: 3},
+ {Label: "*:create", MaxRequests: 20, Duration: 5},
+ {Label: "/api/batch", MaxRequests: 3, Duration: 1},
+ {Label: "/api/", MaxRequests: 300, Duration: 10},
+ }
+ // If this fails after a PocketBase upgrade, the defaults changed and the
+ // migration's frozen list no longer removes them on new installs.
+ require.Equal(t, pbDefaults, core.NewBaseApp(core.BaseAppConfig{DataDir: t.TempDir()}).Settings().RateLimits.Rules)
+
+ tests := []struct {
+ name string
+ rules []core.RateLimitRule
+ expected []core.RateLimitRule
+ }{
+ {
+ name: "untouched defaults are replaced by sign-in rule",
+ rules: pbDefaults,
+ expected: []core.RateLimitRule{signInRule},
+ },
+ {
+ name: "no rules adds sign-in rule",
+ rules: nil,
+ expected: []core.RateLimitRule{signInRule},
+ },
+ {
+ name: "customized rules are kept",
+ rules: []core.RateLimitRule{
+ {Label: "*:auth", MaxRequests: 7, Duration: 11},
+ {Label: "*:create", MaxRequests: 17, Duration: 9},
+ {Label: "/api/batch", Audience: "@guest", MaxRequests: 3, Duration: 1},
+ {Label: "/api/", MaxRequests: 600, Duration: 10},
+ },
+ expected: []core.RateLimitRule{
+ {Label: "*:auth", MaxRequests: 7, Duration: 11},
+ {Label: "*:create", MaxRequests: 17, Duration: 9},
+ {Label: "/api/batch", Audience: "@guest", MaxRequests: 3, Duration: 1},
+ {Label: "/api/", MaxRequests: 600, Duration: 10},
+ },
+ },
+ {
+ name: "custom rules without auth rule get sign-in rule prepended",
+ rules: append([]core.RateLimitRule{{Label: "*:create", MaxRequests: 17, Duration: 9}}, pbDefaults[2:]...),
+ expected: []core.RateLimitRule{
+ signInRule,
+ {Label: "*:create", MaxRequests: 17, Duration: 9},
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ testHub, err := beszelTests.NewTestHub(t.TempDir())
+ require.NoError(t, err)
+ defer testHub.Cleanup()
+
+ settings := testHub.Settings()
+ settings.RateLimits.Enabled = false
+ settings.RateLimits.Rules = tt.rules
+ require.NoError(t, testHub.Save(settings))
+
+ _, err = testHub.DB().Delete(core.DefaultMigrationsTable, dbx.HashExp{"file": requestLimitMigration}).Execute()
+ require.NoError(t, err)
+ require.NoError(t, testHub.RunAppMigrations())
+
+ settings = testHub.Settings()
+ require.True(t, settings.RateLimits.Enabled)
+ require.Equal(t, tt.expected, settings.RateLimits.Rules)
+ })
+ }
+}
+
+func TestRequestLimitMigrationRunsOnce(t *testing.T) {
+ testHub, err := beszelTests.NewTestHub(t.TempDir())
+ require.NoError(t, err)
+ defer testHub.Cleanup()
+
+ // Administrator changes after the migration must survive another startup.
+ adminRules := []core.RateLimitRule{{Label: "*:auth", MaxRequests: 13, Duration: 19}}
+ settings := testHub.Settings()
+ settings.RateLimits.Enabled = false
+ settings.RateLimits.Rules = adminRules
+ require.NoError(t, testHub.Save(settings))
+
+ require.NoError(t, testHub.ClearBootstrap())
+ require.NoError(t, testHub.Bootstrap())
+ require.NoError(t, testHub.RunAllMigrations())
+
+ settings = testHub.Settings()
+ require.False(t, settings.RateLimits.Enabled)
+ require.Equal(t, adminRules, settings.RateLimits.Rules)
+}
+
+func postPasswordSignIn(handler http.Handler, identity string, password string) *httptest.ResponseRecorder {
+ body := jsonReader(map[string]string{
+ "identity": identity,
+ "password": password,
+ })
+ request := httptest.NewRequest(http.MethodPost, "/api/collections/users/auth-with-password", body)
+ request.RemoteAddr = "203.0.113.8:4242"
+ request.Header.Set("Content-Type", "application/json")
+ recorder := httptest.NewRecorder()
+ handler.ServeHTTP(recorder, request)
+ return recorder
+}
diff --git a/internal/migrations/1792483200_enable_request_limits.go b/internal/migrations/1792483200_enable_request_limits.go
new file mode 100644
index 000000000..5fdedf8e9
--- /dev/null
+++ b/internal/migrations/1792483200_enable_request_limits.go
@@ -0,0 +1,45 @@
+package migrations
+
+import (
+ "slices"
+
+ "github.com/pocketbase/pocketbase/core"
+ m "github.com/pocketbase/pocketbase/migrations"
+)
+
+// signInRateLimitRule limits password, OTP, and OAuth2 sign-in attempts per client address.
+var signInRateLimitRule = core.RateLimitRule{Label: "*:auth", MaxRequests: 10, Duration: 60}
+
+// untouchedDefaultRateLimitRules are PocketBase's default non-auth rules. They are
+// frozen here rather than read from core.NewSettings() so the migration stays
+// deterministic if PocketBase changes its defaults.
+var untouchedDefaultRateLimitRules = []core.RateLimitRule{
+ {Label: "*:auth", MaxRequests: 2, Duration: 3},
+ {Label: "*:create", MaxRequests: 20, Duration: 5},
+ {Label: "/api/batch", MaxRequests: 3, Duration: 1},
+ {Label: "/api/", MaxRequests: 300, Duration: 10},
+}
+
+// Enables request limits for sign-in only. Unmodified PocketBase default rules are
+// removed so bulk UI actions and agent connections (which may share a reverse proxy
+// address) are not throttled. Rules customized by an administrator are kept.
+func init() {
+ m.Register(func(app core.App) error {
+ settings := app.Settings()
+ settings.RateLimits.Enabled = true
+
+ rules := slices.DeleteFunc(slices.Clone(settings.RateLimits.Rules), func(r core.RateLimitRule) bool {
+ return slices.Contains(untouchedDefaultRateLimitRules, r)
+ })
+
+ hasAuthRule := slices.ContainsFunc(rules, func(r core.RateLimitRule) bool {
+ return r.Label == signInRateLimitRule.Label
+ })
+ if !hasAuthRule {
+ rules = append([]core.RateLimitRule{signInRateLimitRule}, rules...)
+ }
+
+ settings.RateLimits.Rules = rules
+ return app.Save(settings)
+ }, nil)
+}
diff --git a/internal/site/src/components/login/auth-form.tsx b/internal/site/src/components/login/auth-form.tsx
index 5847134a1..7980671aa 100644
--- a/internal/site/src/components/login/auth-form.tsx
+++ b/internal/site/src/components/login/auth-form.tsx
@@ -2,7 +2,7 @@ import { t } from "@lingui/core/macro"
import { Trans } from "@lingui/react/macro"
import { getPagePath } from "@nanostores/router"
import { KeyIcon, LoaderCircle, LockIcon, LogInIcon, MailIcon } from "lucide-react"
-import type { AuthMethodsList, AuthProviderInfo, OAuth2AuthConfig } from "pocketbase"
+import type { AuthMethodsList, AuthProviderInfo, ClientResponseError, OAuth2AuthConfig } from "pocketbase"
import { useCallback, useEffect, useState } from "react"
import * as v from "valibot"
import { buttonVariants } from "@/components/ui/button"
@@ -38,7 +38,15 @@ const RegisterSchema = v.looseObject({
passwordConfirm: passwordSchema,
})
-export const showLoginFaliedToast = (description = t`Please check your credentials and try again`) => {
+export const showLoginFaliedToast = (err?: unknown, description = t`Please check your credentials and try again`) => {
+ if ((err as ClientResponseError | undefined)?.status === 429) {
+ toast({
+ title: t`Too many login attempts`,
+ description: t`Please wait a moment and try again.`,
+ variant: "destructive",
+ })
+ return
+ }
toast({
title: t`Login attempt failed`,
description,
@@ -112,7 +120,7 @@ export function UserAuthForm({
} catch (err: any) {
const mfaId = err?.response?.mfaId
if (!mfaId) {
- showLoginFaliedToast()
+ showLoginFaliedToast(err)
throw err
}
setMfaId(mfaId)
@@ -121,7 +129,7 @@ export function UserAuthForm({
setOtpId(otpId)
} catch (err) {
console.log({ err })
- showLoginFaliedToast()
+ showLoginFaliedToast(err)
}
} finally {
setIsLoading(false)
@@ -152,7 +160,7 @@ export function UserAuthForm({
const authWindow = window.open()
if (!authWindow) {
setIsOauthLoading(false)
- showLoginFaliedToast(t`Please enable pop-ups for this site`)
+ showLoginFaliedToast(undefined, t`Please enable pop-ups for this site`)
return
}
oAuthOpts.urlCallback = (url) => {
@@ -164,7 +172,7 @@ export function UserAuthForm({
.then(() => {
$authenticated.set(pb.authStore.isValid)
})
- .catch(showLoginFaliedToast)
+ .catch((err: unknown) => showLoginFaliedToast(err))
.finally(() => {
setIsOauthLoading(false)
})
@@ -197,7 +205,7 @@ export function UserAuthForm({
pb.collection("users")
.authWithOAuth2Code(provider.name, code, provider.codeVerifier, `${window.location.origin}${basePath}`)
.then(() => $authenticated.set(pb.authStore.isValid))
- .catch((e: unknown) => showLoginFaliedToast((e as Error).message))
+ .catch((e: unknown) => showLoginFaliedToast(e, (e as Error).message))
.finally(() => setIsOauthLoading(false))
}
}
diff --git a/internal/site/src/components/login/otp-forms.tsx b/internal/site/src/components/login/otp-forms.tsx
index d5314cd4b..682dc5f21 100644
--- a/internal/site/src/components/login/otp-forms.tsx
+++ b/internal/site/src/components/login/otp-forms.tsx
@@ -22,7 +22,7 @@ export function OtpInputForm({ otpId, mfaId }: { otpId: string; mfaId: string })
$authenticated.set(true)
})
.catch((err) => {
- showLoginFaliedToast(err.message)
+ showLoginFaliedToast(err, err.message)
})
}
@@ -56,7 +56,7 @@ export function OtpRequestForm() {
const { otpId } = await pb.collection("users").requestOTP(email)
setOtpId(otpId)
} catch (e: any) {
- showLoginFaliedToast(e?.message)
+ showLoginFaliedToast(e, e?.message)
} finally {
setIsLoading(false)
setEmail("")
diff --git a/supplemental/CHANGELOG.md b/supplemental/CHANGELOG.md
index c1136a8ee..a0eda85e2 100644
--- a/supplemental/CHANGELOG.md
+++ b/supplemental/CHANGELOG.md
@@ -1,3 +1,7 @@
+## 0.21.2
+
+- Limit sign-in attempts to 10 per minute per address (#2642)
+
## 0.21.1
For developers using the agent as a Go package, `Agent.Start` now requires a `context.Context`.