Skip to content

ActivityPub-federated video streaming platform using P2P directly in your web browser

Send email on account locking

Chocobozzz68c451a296c3
diff --git a/packages/tests/src/api/users/login-lockout.ts b/packages/tests/src/api/users/login-lockout.ts
index 536937aab6..d4d62fe5b0 100644
--- a/packages/tests/src/api/users/login-lockout.ts
+++ b/packages/tests/src/api/users/login-lockout.ts
@@ -4,21 +4,27 @@ import { wait } from '@peertube/peertube-core-utils'
import { HttpStatusCode, PeerTubeProblemDocument, ServerErrorCode } from '@peertube/peertube-models'
import {
cleanupTests,
+ ConfigCommand,
createSingleServer,
PeerTubeServer,
setAccessTokensToServers,
- TwoFactorCommand
+ TwoFactorCommand,
+ waitJobs
} from '@peertube/peertube-server-commands'
+import { MockSmtpServer } from '@tests/shared/mock-servers/mock-email.js'
import { expect } from 'chai'
describe('Test login lockout', function () {
let server: PeerTubeServer
const userUsername = 'user1'
+ const userEmail = userUsername + '@example.com'
let userId: number
let userPassword: string
let userToken: string
+ const emails: object[] = []
+
// Sync with rates_limit.login_lockout in config/test.yaml (window is 5 seconds on a test instance)
const maxFailures = 10
const maxFailuresPerIP = 3
@@ -28,6 +34,18 @@ describe('Test login lockout', function () {
expect(body.code).to.equal(ServerErrorCode.TOO_MANY_LOGIN_FAILURES)
}
+ function expectLockedAccountEmailsCount (count: number) {
+ expect(emails).to.have.lengthOf(count)
+ if (count === 0) return
+
+ const email = emails[count - 1]
+ expect(email['to'][0]['address']).to.equal(userEmail)
+ expect(email['subject']).to.contain('temporarily locked')
+ expect(email['text']).to.contain(userUsername)
+ }
+
+ // A single IP's failures only count towards the account lock up to maxFailuresPerIP, so spread
+ // failures across a new fake IP every maxFailuresPerIP calls to actually reach the account threshold
function xForwardedForAt (index: number) {
const ipIndex = Math.floor(index / maxFailuresPerIP) + 1
@@ -64,6 +82,8 @@ describe('Test login lockout', function () {
before(async function () {
this.timeout(30000)
+ const port = await MockSmtpServer.Instance.collectEmails(emails)
+
// Increase the IP based login rate limit so this test only triggers the per-account lockout
server = await createSingleServer(1, {
rates_limit: {
@@ -71,7 +91,8 @@ describe('Test login lockout', function () {
window: '5 minutes',
max: 1000
}
- }
+ },
+ ...ConfigCommand.getEmailOverrideConfig(port)
})
await setAccessTokensToServers([ server ])
@@ -91,6 +112,9 @@ describe('Test login lockout', function () {
user: { username: userUsername, password: userPassword },
expectedStatus: HttpStatusCode.OK_200
})
+
+ await waitJobs(server)
+ expectLockedAccountEmailsCount(0)
})
it('Should have reset the counter on successful login', async function () {
@@ -102,6 +126,9 @@ describe('Test login lockout', function () {
user: { username: userUsername, password: userPassword },
expectedStatus: HttpStatusCode.OK_200
})
+
+ await waitJobs(server)
+ expectLockedAccountEmailsCount(0)
})
it('Should not lock the account from a single IP alone', async function () {
@@ -115,6 +142,9 @@ describe('Test login lockout', function () {
user: { username: userUsername, password: userPassword },
expectedStatus: HttpStatusCode.OK_200
})
+
+ await waitJobs(server)
+ expectLockedAccountEmailsCount(0)
})
it('Should lock the account after too many password failures spread over several IPs', async function () {
@@ -127,6 +157,11 @@ describe('Test login lockout', function () {
// And of course with an invalid one
await expectLockedLogin('invalid password')
+
+ await waitJobs(server)
+
+ // Only 1 email, even though 2 more requests hit the account after it was already locked
+ expectLockedAccountEmailsCount(1)
})
it('Should unlock the account after the lockout expired', async function () {
@@ -167,9 +202,16 @@ describe('Test login lockout', function () {
otpToken: TwoFactorCommand.buildOTP({ secret: otpRequest.secret }).generate(),
expectedStatus: HttpStatusCode.OK_200
})
+
+ await waitJobs(server)
+
+ // The previous lock (password failures) already sent 1 email, this OTP-triggered lock sends a 2nd one
+ expectLockedAccountEmailsCount(2)
})
after(async function () {
+ await MockSmtpServer.Instance.kill()
+
await cleanupTests([ server ])
})
})
diff --git a/server/core/assets/email-templates/my-account-login-locked/html.hbs b/server/core/assets/email-templates/my-account-login-locked/html.hbs
new file mode 100644
index 0000000000..1435b394d8
--- /dev/null
+++ b/server/core/assets/email-templates/my-account-login-locked/html.hbs
@@ -0,0 +1,9 @@
+{{#> base title=(t "Your account has been temporarily locked")}}
+ <p>
+ {{t "Your account has been temporarily locked after {maxFailures} failed login attempts, most recently from IP {ip}." maxFailures=maxFailures ip=ip}}
+ </p>
+
+ <p>
+ {{t "It will automatically unlock in about {lockoutMinutes} minutes. If this was not you, we recommend contacting your administrator." lockoutMinutes=lockoutMinutes}}
+ </p>
+{{/base}}
diff --git a/server/core/lib/auth/oauth-user.ts b/server/core/lib/auth/oauth-user.ts
index d5e329344c..123519cd2a 100644
--- a/server/core/lib/auth/oauth-user.ts
+++ b/server/core/lib/auth/oauth-user.ts
@@ -14,6 +14,7 @@ import { CONFIG } from '../../initializers/config.js'
import { OTP } from '../../initializers/constants.js'
import { OAuthTokenModel } from '../../models/oauth/oauth-token.js'
import { UserModel } from '../../models/user/user.js'
+import { Emailer } from '../emailer.js'
import { findAvailableLocalActorName } from '../local-actor.js'
import { Redis } from '../redis.js'
import { buildUser, createUserAccountAndChannelAndPlaylist, getByEmailPermissive } from '../user.js'
@@ -90,7 +91,8 @@ export async function getUserOrThrow (options: {
const passwordMatch = await user.isPasswordMatch(password)
if (passwordMatch !== true) {
- await Redis.Instance.addLoginFailure(user.id, req.ip)
+ const failures = await Redis.Instance.addLoginFailure(user.id, req.ip)
+ await notifyAccountLockedIfNeeded(user, failures, req.ip)
throwInvalidGrantError()
}
@@ -108,7 +110,8 @@ export async function getUserOrThrow (options: {
}
if (await isOTPValid({ encryptedSecret: user.otpSecret, token: oauthHeaders[OTP.HEADER_NAME] }) !== true) {
- await Redis.Instance.addLoginFailure(user.id, req.ip)
+ const failures = await Redis.Instance.addLoginFailure(user.id, req.ip)
+ await notifyAccountLockedIfNeeded(user, failures, req.ip)
throw new InvalidTwoFactorError(req.t('Invalid two factor header'))
}
@@ -119,6 +122,18 @@ export async function getUserOrThrow (options: {
return user
}
+// This is the exact failure that just crossed the threshold and locked the account: notify its owner once per lock
+function notifyAccountLockedIfNeeded (user: MUserDefault, failures: number, ip: string) {
+ if (failures < CONFIG.RATES_LIMIT.LOGIN_LOCKOUT.MAX) return Promise.resolve()
+
+ return Emailer.Instance.addAccountLoginLockedEmailJob({
+ username: user.username,
+ to: user.email,
+ language: user.getLanguage(),
+ ip
+ })
+}
+
async function handleGetUserBypass (options: {
bypassLogin?: BypassLogin
req: express.Request
diff --git a/server/core/lib/emailer.ts b/server/core/lib/emailer.ts
index b5f983b445..e002fe146c 100644
--- a/server/core/lib/emailer.ts
+++ b/server/core/lib/emailer.ts
@@ -235,6 +235,31 @@ export class Emailer {
return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
}
+ addAccountLoginLockedEmailJob (options: {
+ username: string
+ to: string
+ language: string
+ ip: string
+ }) {
+ const { username, to, language, ip } = options
+
+ const emailPayload: EmailPayload = {
+ template: 'my-account-login-locked',
+ to: { email: to, language },
+ subject: t('Your account has been temporarily locked', language),
+ locals: {
+ username,
+ ip,
+ maxFailures: CONFIG.RATES_LIMIT.LOGIN_LOCKOUT.MAX,
+ lockoutMinutes: Math.round(CONFIG.RATES_LIMIT.LOGIN_LOCKOUT.WINDOW_MS / 60000),
+
+ hideNotificationPreferencesLink: true
+ }
+ }
+
+ return JobQueue.Instance.createJobAsync({ type: 'email', payload: emailPayload })
+ }
+
addContactFormJob (options: {
fromEmail: string
diff --git a/server/core/lib/redis.ts b/server/core/lib/redis.ts
index e6a8304135..dc3e53e4a9 100644
--- a/server/core/lib/redis.ts
+++ b/server/core/lib/redis.ts
@@ -200,6 +200,9 @@ class Redis {
await this.incrementHashField(key, field)
await this.setExpiration(key, CONFIG.RATES_LIMIT.LOGIN_LOCKOUT.WINDOW_MS)
+
+ // Let the caller know the (capped) total so it can detect the exact failure that triggers the lock
+ return this.getLoginFailures(userId)
}
async getLoginFailures (userId: number) {