ActivityPub-federated video streaming platform using P2P directly in your web browser
Introduce per account rate limit
Chocobozzz3305fb62be27
diff --git a/config/config-schema.json b/config/config-schema.jsonindex 2941e3f66a..e99cb39ff4 100644--- a/config/config-schema.json+++ b/config/config-schema.json@@ -230,6 +230,38 @@}},"additionalProperties": false+ },+ "report_abuse": {+ "description": "Abuse reports, limited per authenticated user (each report notifies all moderators)",+ "type": "object",+ "properties": {+ "window": {+ "description": "20 attempts in 1 hour",+ "type": "string",+ "default": "1 hour"+ },+ "max": {+ "type": "integer",+ "default": 20+ }+ },+ "additionalProperties": false+ },+ "comments": {+ "description": "Comment/reply creation, limited per authenticated user",+ "type": "object",+ "properties": {+ "window": {+ "description": "60 attempts in 5 minutes",+ "type": "string",+ "default": "5 minutes"+ },+ "max": {+ "type": "integer",+ "default": 60+ }+ },+ "additionalProperties": false}},"additionalProperties": falsediff --git a/config/default.yaml b/config/default.yamlindex f63a1af603..fe0762f38a 100644--- a/config/default.yaml+++ b/config/default.yaml@@ -66,6 +66,14 @@ rates_limit:# 5 attempts in 5 secondswindow: 5 secondsmax: 5+ report_abuse: # Abuse reports, limited per authenticated user (each report notifies all moderators)+ # 20 attempts in 1 hour+ window: 1 hour+ max: 20+ create_comment: # Comment/reply creation, limited per authenticated user+ # 60 attempts in 5 minutes+ window: 5 minutes+ max: 60oauth2:token_lifetime:diff --git a/config/production.yaml.example b/config/production.yaml.exampleindex 8e52b735b4..441d7d57da 100644--- a/config/production.yaml.example+++ b/config/production.yaml.example@@ -64,6 +64,14 @@ rates_limit:# 5 attempts in 5 secondswindow: 5 secondsmax: 5+ report_abuse: # Abuse reports, limited per authenticated user (each report notifies all moderators)+ # 20 attempts in 1 hour+ window: 1 hour+ max: 20+ create_comment: # Comment/reply creation, limited per authenticated user+ # 60 attempts in 5 minutes+ window: 5 minutes+ max: 60oauth2:token_lifetime:diff --git a/config/test.yaml b/config/test.yamlindex 079988429a..6737e8a653 100644--- a/config/test.yaml+++ b/config/test.yaml@@ -19,6 +19,12 @@ rates_limit:api:window: 10 secondsmax: 500+ report_abuse:+ window: 10 seconds+ max: 500+ create_comment:+ window: 10 seconds+ max: 500database:hostname: '127.0.0.1'diff --git a/packages/models/src/server/server-error-code.enum.ts b/packages/models/src/server/server-error-code.enum.tsindex 53c54e2369..81a482a72f 100644--- a/packages/models/src/server/server-error-code.enum.ts+++ b/packages/models/src/server/server-error-code.enum.ts@@ -45,6 +45,11 @@ export const ServerErrorCode = {MISSING_TWO_FACTOR: 'missing_two_factor',TOO_LONG_PASSWORD: 'too_long_password',INVALID_TWO_FACTOR: 'invalid_two_factor',+ /**+ * Too many password/OTP login failures for this account: login is temporarily+ * locked independently of the source IP+ */+ TOO_MANY_LOGIN_FAILURES: 'too_many_login_failures',ACCOUNT_BLOCKED: 'account_blocked',EMAIL_NOT_VERIFIED: 'email_not_verified',diff --git a/packages/tests/src/api/server/reverse-proxy.ts b/packages/tests/src/api/server/reverse-proxy.tsindex 47e6df5a68..bd6c526b0d 100644--- a/packages/tests/src/api/server/reverse-proxy.ts+++ b/packages/tests/src/api/server/reverse-proxy.ts@@ -94,7 +94,8 @@ describe('Test application behind a reverse proxy', function () {})it('Should rate limit logins', async function () {- const user = { username: 'root', password: 'fail' }+ // Use an account that does not exist so the IP rate limiter is tested, not the per-account login lockout+ const user = { username: 'unknown-user', password: 'fail' }for (let i = 0; i < 18; i++) {await server.login.login({ user, expectedStatus: HttpStatusCode.BAD_REQUEST_400 })diff --git a/packages/tests/src/api/server/user-rate-limits.ts b/packages/tests/src/api/server/user-rate-limits.tsnew file mode 100644index 0000000000..d481ea0f65--- /dev/null+++ b/packages/tests/src/api/server/user-rate-limits.ts@@ -0,0 +1,101 @@+/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { HttpStatusCode } from '@peertube/peertube-models'+import { cleanupTests, createSingleServer, PeerTubeServer, setAccessTokensToServers } from '@peertube/peertube-server-commands'++describe('Test per-user rate limits', function () {+ let server: PeerTubeServer+ let user1Token: string+ let user2Token: string+ let videoId: number++ before(async function () {+ this.timeout(60000)++ server = await createSingleServer(1, {+ rates_limit: {+ report_abuse: {+ window: '5 minutes',+ max: 3+ },+ create_comment: {+ window: '5 minutes',+ max: 3+ }+ }+ })+ await setAccessTokensToServers([ server ])++ user1Token = await server.users.generateUserAndToken('user1')+ user2Token = await server.users.generateUserAndToken('user2')++ const { id } = await server.videos.upload()+ videoId = id+ })++ describe('Abuse reports', function () {+ it('Should rate limit abuse reports of a user', async function () {+ for (let i = 0; i < 3; i++) {+ await server.abuses.report({ videoId, reason: 'abuse reason ' + i, token: user1Token })+ }++ await server.abuses.report({+ videoId,+ reason: 'abuse reason 4',+ token: user1Token,+ expectedStatus: HttpStatusCode.TOO_MANY_REQUESTS_429+ })+ })++ it('Should not limit abuse reports of another user', async function () {+ await server.abuses.report({ videoId, reason: 'abuse reason user 2', token: user2Token })+ })++ it('Should not limit abuse reports of an admin', async function () {+ for (let i = 0; i < 4; i++) {+ await server.abuses.report({ videoId, reason: 'admin abuse reason ' + i })+ }+ })+ })++ describe('Comments', function () {+ it('Should rate limit comments of a user', async function () {+ for (let i = 0; i < 3; i++) {+ await server.comments.createThread({ videoId, text: 'comment ' + i, token: user1Token })+ }++ await server.comments.createThread({+ videoId,+ text: 'comment 4',+ token: user1Token,+ expectedStatus: HttpStatusCode.TOO_MANY_REQUESTS_429+ })+ })++ it('Should also rate limit comment replies', async function () {+ const created = await server.comments.createThread({ videoId, text: 'thread of user 2', token: user2Token })++ await server.comments.addReply({+ videoId,+ toCommentId: created.id,+ text: 'reply',+ token: user1Token,+ expectedStatus: HttpStatusCode.TOO_MANY_REQUESTS_429+ })+ })++ it('Should not limit comments of another user', async function () {+ await server.comments.createThread({ videoId, text: 'comment of user 2', token: user2Token })+ })++ it('Should not limit comments of an admin', async function () {+ for (let i = 0; i < 4; i++) {+ await server.comments.createThread({ videoId, text: 'admin comment ' + i })+ }+ })+ })++ after(async function () {+ await cleanupTests([ server ])+ })+})diff --git a/packages/tests/src/api/users/login-lockout.ts b/packages/tests/src/api/users/login-lockout.tsnew file mode 100644index 0000000000..a49523f315--- /dev/null+++ b/packages/tests/src/api/users/login-lockout.ts@@ -0,0 +1,154 @@+/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */++import { wait } from '@peertube/peertube-core-utils'+import { HttpStatusCode, PeerTubeProblemDocument, ServerErrorCode } from '@peertube/peertube-models'+import {+ cleanupTests,+ createSingleServer,+ PeerTubeServer,+ setAccessTokensToServers,+ TwoFactorCommand+} from '@peertube/peertube-server-commands'+import { expect } from 'chai'++describe('Test login lockout', function () {+ let server: PeerTubeServer++ const userUsername = 'user1'+ let userId: number+ let userPassword: string+ let userToken: string++ // Sync with LOGIN_LOCKOUT constants (lifetime is 5 seconds on a test instance)+ const maxFailures = 10+ const lifetimeMs = 5000++ function expectLockout (body: PeerTubeProblemDocument) {+ expect(body.code).to.equal(ServerErrorCode.TOO_MANY_LOGIN_FAILURES)+ }++ async function failLogin (password: string, otpToken?: string) {+ const { body } = await server.login.loginAndGetResponse({+ user: { username: userUsername, password },+ otpToken,+ expectedStatus: HttpStatusCode.BAD_REQUEST_400+ })++ return body as unknown as PeerTubeProblemDocument+ }++ async function expectLockedLogin (password: string, otpToken?: string) {+ const { body } = await server.login.loginAndGetResponse({+ user: { username: userUsername, password },+ otpToken,+ expectedStatus: HttpStatusCode.TOO_MANY_REQUESTS_429+ })++ expectLockout(body as unknown as PeerTubeProblemDocument)+ }++ before(async function () {+ this.timeout(30000)++ // Increase the IP based login rate limit so this test only triggers the per-account lockout+ server = await createSingleServer(1, {+ rates_limit: {+ login: {+ window: '5 minutes',+ max: 1000+ }+ }+ })++ await setAccessTokensToServers([ server ])++ const res = await server.users.generate(userUsername)+ userId = res.userId+ userPassword = res.password+ userToken = res.token+ })++ it('Should not lock the account below the failure threshold', async function () {+ this.timeout(30000)++ for (let i = 0; i < maxFailures - 1; i++) {+ await failLogin('invalid password')+ }++ await server.login.login({+ user: { username: userUsername, password: userPassword },+ expectedStatus: HttpStatusCode.OK_200+ })+ })++ it('Should have reset the counter on successful login', async function () {+ this.timeout(30000)++ for (let i = 0; i < maxFailures - 1; i++) {+ await failLogin('invalid password')+ }++ await server.login.login({+ user: { username: userUsername, password: userPassword },+ expectedStatus: HttpStatusCode.OK_200+ })+ })++ it('Should lock the account after too many password failures', async function () {+ this.timeout(30000)++ for (let i = 0; i < maxFailures; i++) {+ await failLogin('invalid password')+ }++ // Even with the correct password+ await expectLockedLogin(userPassword)++ // And of course with an invalid one+ await expectLockedLogin('invalid password')+ })++ it('Should unlock the account after the lockout expired', async function () {+ this.timeout(30000)++ await wait(lifetimeMs + 2000)++ await server.login.login({+ user: { username: userUsername, password: userPassword },+ expectedStatus: HttpStatusCode.OK_200+ })+ })++ it('Should also lock the account on OTP failures', async function () {+ this.timeout(60000)++ // Enable two factor auth+ const { otpRequest } = await server.twoFactor.request({ userId, token: userToken, currentPassword: userPassword })+ await server.twoFactor.confirmRequest({+ userId,+ token: userToken,+ otpToken: TwoFactorCommand.buildOTP({ secret: otpRequest.secret }).generate(),+ requestToken: otpRequest.requestToken+ })++ for (let i = 0; i < maxFailures; i++) {+ const body = await failLogin(userPassword, '123456')+ expect(body.code).to.equal(ServerErrorCode.INVALID_TWO_FACTOR)+ }++ // Locked, even with the correct password and OTP token+ await expectLockedLogin(userPassword, TwoFactorCommand.buildOTP({ secret: otpRequest.secret }).generate())++ await wait(lifetimeMs + 2000)++ await server.login.loginAndGetResponse({+ user: { username: userUsername, password: userPassword },+ otpToken: TwoFactorCommand.buildOTP({ secret: otpRequest.secret }).generate(),+ expectedStatus: HttpStatusCode.OK_200+ })+ })++ after(async function () {+ await cleanupTests([ server ])+ })+})diff --git a/server/core/controllers/api/abuse.ts b/server/core/controllers/api/abuse.tsindex c57c3426e8..af73e7ab4f 100644--- a/server/core/controllers/api/abuse.ts+++ b/server/core/controllers/api/abuse.ts@@ -1,12 +1,13 @@-import express from 'express'+import { abusePredefinedReasonsMap } from '@peertube/peertube-core-utils'+import { AbuseCreate, AbuseState, HttpStatusCode, UserRight } from '@peertube/peertube-models'import { logger } from '@server/helpers/logger.js'+import { CONFIG } from '@server/initializers/config.js'import { createAccountAbuse, createVideoAbuse, createVideoCommentAbuse } from '@server/lib/moderation.js'import { Notifier } from '@server/lib/notifier/index.js'import { AbuseMessageModel } from '@server/models/abuse/abuse-message.js'import { AbuseModel } from '@server/models/abuse/abuse.js'import { getServerActor } from '@server/models/application/application.js'-import { abusePredefinedReasonsMap } from '@peertube/peertube-core-utils'-import { AbuseCreate, AbuseState, HttpStatusCode, UserRight } from '@peertube/peertube-models'+import express from 'express'import { getFormattedObjects } from '../../helpers/utils.js'import { sequelizeTypescript } from '../../initializers/database.js'import {@@ -20,6 +21,7 @@ import {asyncMiddleware,asyncRetryTransactionMiddleware,authenticate,+ buildRateLimiter,checkAbuseValidForMessagesValidator,deleteAbuseMessageValidator,ensureUserHasRight,@@ -35,6 +37,14 @@ const abuseRouter = express.Router()abuseRouter.use(apiRateLimiter)+// Each accepted report notifies every moderator (in-app + email) and can federate a Flag activity+// So also limit reports per user+const reportAbuseRateLimiter = buildRateLimiter({+ windowMs: CONFIG.RATES_LIMIT.REPORT_ABUSE.WINDOW_MS,+ max: CONFIG.RATES_LIMIT.REPORT_ABUSE.MAX,+ perUserKey: true+})+abuseRouter.get('/',openapiOperationDoc({ operationId: 'getAbuses' }),@@ -54,7 +64,13 @@ abuseRouter.put(asyncMiddleware(abuseUpdateValidator),asyncRetryTransactionMiddleware(updateAbuse))-abuseRouter.post('/', authenticate, asyncMiddleware(abuseReportValidator), asyncRetryTransactionMiddleware(reportAbuse))+abuseRouter.post(+ '/',+ authenticate,+ reportAbuseRateLimiter,+ asyncMiddleware(abuseReportValidator),+ asyncRetryTransactionMiddleware(reportAbuse)+)abuseRouter.delete('/:id',authenticate,diff --git a/server/core/controllers/api/users/token.ts b/server/core/controllers/api/users/token.tsindex eaa2916e9c..9760aa213a 100644--- a/server/core/controllers/api/users/token.ts+++ b/server/core/controllers/api/users/token.ts@@ -4,9 +4,9 @@ import { buildUUID } from '@peertube/peertube-node-utils'import { logger } from '@server/helpers/logger.js'import { CONFIG } from '@server/initializers/config.js'import { OTP } from '@server/initializers/constants.js'-import { getAuthNameFromRefreshGrant, consumeBypassFromExternalAuth, getBypassFromPasswordGrant } from '@server/lib/auth/external-auth.js'+import { consumeBypassFromExternalAuth, getAuthNameFromRefreshGrant, getBypassFromPasswordGrant } from '@server/lib/auth/external-auth.js'import { BypassLogin, revokeToken } from '@server/lib/auth/oauth-model.js'-import { handleOAuthToken, MissingTwoFactorError } from '@server/lib/auth/oauth.js'+import { handleOAuthToken, MissingTwoFactorError, TooManyLoginFailuresError } from '@server/lib/auth/oauth.js'import { Hooks } from '@server/lib/plugins/hooks.js'import {asyncMiddleware,@@ -122,6 +122,8 @@ async function handleToken (req: express.Request, res: express.Response, next: elogger.debug('Missing two factor error', { err })} else if (err instanceof InvalidGrantError) {logger.debug('Invalid grant', { err })+ } else if (err instanceof TooManyLoginFailuresError) {+ logger.debug('Too many login failures', { err })} else {logger.warn('Login error', { err })}diff --git a/server/core/controllers/api/videos/comment.ts b/server/core/controllers/api/videos/comment.tsindex 506dc9ba05..3ad56e5636 100644--- a/server/core/controllers/api/videos/comment.ts+++ b/server/core/controllers/api/videos/comment.ts@@ -13,6 +13,7 @@ import { MCommentFormattable } from '@server/types/models/index.js'import express from 'express'import { CommentAuditView, auditLoggerFactory, getAuditIdFromRes } from '../../../helpers/audit-logger.js'import { getFormattedObjects } from '../../../helpers/utils.js'+import { CONFIG } from '../../../initializers/config.js'import { Notifier } from '../../../lib/notifier/index.js'import { Hooks } from '../../../lib/plugins/hooks.js'import { approveComment, buildFormattedCommentTree, createLocalVideoComment, removeComment } from '../../../lib/video-comment.js'@@ -20,6 +21,7 @@ import {asyncMiddleware,asyncRetryTransactionMiddleware,authenticate,+ buildRateLimiter,ensureUserHasRight,optionalAuthenticate,paginationValidator,@@ -42,6 +44,14 @@ import { VideoCommentModel } from '../../../models/video/video-comment.js'const auditLogger = auditLoggerFactory('comments')const videoCommentRouter = express.Router()+// Each comment fans out notifications and ActivityPub deliveries to followers+// So also limit comment creation per user+const createCommentRateLimiter = buildRateLimiter({+ windowMs: CONFIG.RATES_LIMIT.CREATE_COMMENT.WINDOW_MS,+ max: CONFIG.RATES_LIMIT.CREATE_COMMENT.MAX,+ perUserKey: true+})+videoCommentRouter.get('/:videoId/comment-threads',paginationValidator,@@ -62,12 +72,14 @@ videoCommentRouter.get(videoCommentRouter.post('/:videoId/comment-threads',authenticate,+ createCommentRateLimiter,asyncMiddleware(addVideoCommentThreadValidator),asyncRetryTransactionMiddleware(addVideoCommentThread))videoCommentRouter.post('/:videoId/comments/:commentId',authenticate,+ createCommentRateLimiter,asyncMiddleware(addVideoCommentReplyValidator),asyncRetryTransactionMiddleware(addVideoCommentReply))diff --git a/server/core/initializers/config.ts b/server/core/initializers/config.tsindex ece47506af..d110b68088 100644--- a/server/core/initializers/config.ts+++ b/server/core/initializers/config.ts@@ -382,6 +382,14 @@ const CONFIG = {DOWNLOAD_GENERATE_VIDEO: {WINDOW_MS: parseDurationToMs(config.get<string>('rates_limit.download_generate_video.window')),MAX: config.get<number>('rates_limit.download_generate_video.max')+ },+ REPORT_ABUSE: {+ WINDOW_MS: parseDurationToMs(config.get<string>('rates_limit.report_abuse.window')),+ MAX: config.get<number>('rates_limit.report_abuse.max')+ },+ CREATE_COMMENT: {+ WINDOW_MS: parseDurationToMs(config.get<string>('rates_limit.create_comment.window')),+ MAX: config.get<number>('rates_limit.create_comment.max')}},TRUST_PROXY: config.get<string[]>('trust_proxy'),diff --git a/server/core/initializers/constants.ts b/server/core/initializers/constants.tsindex 558d649dcb..0313db5590 100644--- a/server/core/initializers/constants.ts+++ b/server/core/initializers/constants.ts@@ -942,6 +942,12 @@ export const USER_PASSWORD_RESET_LIFETIME = 60000 * 60 // 60 minutesexport const USER_PASSWORD_CREATE_LIFETIME = 60000 * 60 * 24 * 7 // 7 daysexport const TWO_FACTOR_AUTH_REQUEST_TOKEN_LIFETIME = 60000 * 10 // 10 minutes++// Lock the account (independently of the source IP) after too many password/OTP login failures+export const LOGIN_LOCKOUT = {+ MAX_FAILURES: 10,+ LIFETIME: 60000 * 5 // 5 minutes+}export let JWT_TOKEN_USER_EXPORT_FILE_LIFETIME: `${number} minutes` | `${number} seconds` = '15 minutes'export const EMAIL_VERIFY_LIFETIME = 60000 * 60 // 60 minutes@@ -1310,6 +1316,7 @@ if (process.env.PRODUCTION_CONSTANTS !== 'true') {REDUNDANCY.VIDEOS.RANDOMIZED_FACTOR = 1CONTACT_FORM_LIFETIME = 1000 // 1 second+ LOGIN_LOCKOUT.LIFETIME = 5000 // 5 secondsJOB_ATTEMPTS['email'] = 1diff --git a/server/core/lib/auth/oauth-model.ts b/server/core/lib/auth/oauth-model.tsindex 3c878f7f23..95ffd4560a 100644--- a/server/core/lib/auth/oauth-model.ts+++ b/server/core/lib/auth/oauth-model.ts@@ -10,13 +10,15 @@ import { MUser, MUserDefault } from '@server/types/models/user/user.js'import express from 'express'import { logger } from '../../helpers/logger.js'import { CONFIG } from '../../initializers/config.js'+import { LOGIN_LOCKOUT } from '../../initializers/constants.js'import { OAuthClientModel } from '../../models/oauth/oauth-client.js'import { OAuthTokenModel } from '../../models/oauth/oauth-token.js'import { UserModel } from '../../models/user/user.js'import { findAvailableLocalActorName } from '../local-actor.js'+import { Redis } from '../redis.js'import { buildUser, createUserAccountAndChannelAndPlaylist, getByEmailPermissive } from '../user.js'import { ExternalUser } from './external-auth.js'-import { AccountBlockedError, EmailNotVerifiedError, TooLongPasswordError } from './oauth.js'+import { AccountBlockedError, EmailNotVerifiedError, TooLongPasswordError, TooManyLoginFailuresError } from './oauth.js'import { TokensCache } from './tokens-cache.js'type TokenInfo = {@@ -159,8 +161,17 @@ async function getUser (usernameOrEmail?: string, password?: string, options?: {if (isRootAuthDisabled(user)) return null+ // Check the per-account login failures counter so a locked account cannot have its password/OTP brute-forced+ if (await Redis.Instance.getLoginFailures(user.id) >= LOGIN_LOCKOUT.MAX_FAILURES) {+ throw new TooManyLoginFailuresError(req.t('Too many login attempts for this account. Please try again later.'))+ }+const passwordMatch = await user.isPasswordMatch(password)- if (passwordMatch !== true) return null+ if (passwordMatch !== true) {+ await Redis.Instance.addLoginFailure(user.id)++ return null+ }if (isUserPasswordTooLong(password)) {throw new TooLongPasswordError(req.t('Password is too long. Please reset it using the password reset procedure.'))@@ -170,7 +181,6 @@ async function getUser (usernameOrEmail?: string, password?: string, options?: {if (CONFIG.SIGNUP.REQUIRES_EMAIL_VERIFICATION && user.emailVerified === false) {// Keep this message sync with the client- // TODO: use custom server codethrow new EmailNotVerifiedError(req.t('User email is not verified.'))}diff --git a/server/core/lib/auth/oauth.ts b/server/core/lib/auth/oauth.tsindex 701660ff1b..f989f3591b 100644--- a/server/core/lib/auth/oauth.ts+++ b/server/core/lib/auth/oauth.ts@@ -13,6 +13,7 @@ import { sha1 } from '@peertube/peertube-node-utils'import { randomBytesPromise } from '@server/helpers/core-utils.js'import { isOTPValid } from '@server/helpers/otp.js'import { CONFIG } from '@server/initializers/config.js'+import { Redis } from '@server/lib/redis.js'import { UserRegistrationModel } from '@server/models/user/user-registration.js'import { MOAuthClient } from '@server/types/models/index.js'import express from 'express'@@ -45,6 +46,11 @@ class InvalidTwoFactorError extends Error {name = ServerErrorCode.INVALID_TWO_FACTOR}+class TooManyLoginFailuresError extends Error {+ code = HttpStatusCode.TOO_MANY_REQUESTS_429+ name = ServerErrorCode.TOO_MANY_LOGIN_FAILURES+}+class RegistrationWaitingForApproval extends Error {code = HttpStatusCode.BAD_REQUEST_400name = ServerErrorCode.ACCOUNT_WAITING_FOR_APPROVAL@@ -150,6 +156,7 @@ export {InvalidTwoFactorError,MissingTwoFactorError,TooLongPasswordError,+ TooManyLoginFailuresError,AccountBlockedError,EmailNotVerifiedError}@@ -201,10 +208,14 @@ async function handlePasswordGrant (options: {}if (await isOTPValid({ encryptedSecret: user.otpSecret, token: options.oauthRequest.headers[OTP.HEADER_NAME] }) !== true) {+ await Redis.Instance.addLoginFailure(user.id)+throw new InvalidTwoFactorError(req.t('Invalid two factor header'))}}+ await Redis.Instance.deleteLoginFailures(user.id)+const now = new Date()const token = await buildToken({diff --git a/server/core/lib/redis.ts b/server/core/lib/redis.tsindex 9f6c27fade..7bf7810462 100644--- a/server/core/lib/redis.ts+++ b/server/core/lib/redis.ts@@ -10,6 +10,7 @@ import {AP_CLEANER,CONTACT_FORM_LIFETIME,EMAIL_VERIFY_LIFETIME,+ LOGIN_LOCKOUT,RESUMABLE_UPLOAD_SESSION_LIFETIME,TWO_FACTOR_AUTH_REQUEST_TOKEN_LIFETIME,USER_PASSWORD_CREATE_LIFETIME,@@ -190,6 +191,29 @@ class Redis {return this.getValue(this.generateTwoFactorRequestKey(userId, requestToken))}+ /* ************ Login failures ************ */++ async addLoginFailure (userId: number) {+ const key = this.generateLoginFailureKey(userId)++ const failures = await this.increment(key)+ await this.setExpiration(key, LOGIN_LOCKOUT.LIFETIME)++ return failures+ }++ async getLoginFailures (userId: number) {+ const value = await this.getValue(this.generateLoginFailureKey(userId))++ return value+ ? parseInt(value, 10)+ : 0+ }++ deleteLoginFailures (userId: number) {+ return this.removeValue(this.generateLoginFailureKey(userId))+ }+/* ************ Email verification ************ */async setUserVerifyEmailVerificationString (userId: number) {@@ -487,6 +511,10 @@ class Redis {return 'two-factor-request-' + userId + '-' + token}+ private generateLoginFailureKey (userId: number) {+ return 'login-failure-' + userId+ }+private generateUserVerifyEmailKey (userId: number) {return 'verify-email-user-' + userId}diff --git a/server/core/middlewares/rate-limiter.ts b/server/core/middlewares/rate-limiter.tsindex f3c51104e6..390247c21f 100644--- a/server/core/middlewares/rate-limiter.ts+++ b/server/core/middlewares/rate-limiter.ts@@ -1,10 +1,11 @@-import express from 'express'-import RateLimit, { Options as RateLimitHandlerOptions } from 'express-rate-limit'import { UserRole, UserRoleType } from '@peertube/peertube-models'+import { getAuthUser } from '@server/helpers/express-utils.js'+import { logger, loggerTagsFactory } from '@server/helpers/logger.js'import { CONFIG } from '@server/initializers/config.js'import { RunnerModel } from '@server/models/runner/runner.js'+import express from 'express'+import RateLimit, { ipKeyGenerator, Options as RateLimitHandlerOptions } from 'express-rate-limit'import { optionalAuthenticate } from './auth.js'-import { logger, loggerTagsFactory } from '@server/helpers/logger.js'const lTags = loggerTagsFactory('rate-limit')@@ -14,12 +15,25 @@ export function buildRateLimiter (options: {windowMs: numbermax: numberskipFailedRequests?: boolean++ // Key the counter on the authenticated user instead of the source IP+ perUserKey?: boolean}) {return RateLimit({windowMs: options.windowMs,max: options.max,skipFailedRequests: options.skipFailedRequests,+ keyGenerator: options.perUserKey === true+ ? (req: express.Request, res: express.Response) => {+ const user = getAuthUser(res)++ return user+ ? 'user-' + user.id+ : ipKeyGenerator(req.ip)+ }+ : undefined,+handler: (req, res, next, options) => {// Bypass rate limit for registered runnersif (req.body?.runnerToken) {