Rate-limit failed password changes per user

This commit is contained in:
mikiher committed 2026-11-07 18:48:05 +02:00
1 parent f35f40929d
commit 420c2b28ed
4 files changed
+227 -45

No files matched your search

+1
View File
@@ -22,6 +22,7 @@ class Auth {
/** @type {import('express-rate-limit').RateLimitRequestHandler} */
this.authRateLimiter = RateLimiterFactory.getAuthRateLimiter()
this.passwordChangeRateLimiter = RateLimiterFactory.getPasswordChangeRateLimiter()
this.tokenManager = new TokenManager()
this.localAuthStrategy = new LocalAuthStrategy()
+1 -1
View File
@@ -188,7 +188,7 @@ class ApiRouter {
this.router.post('/me/item/:id/bookmark', MeController.createBookmark.bind(this))
this.router.patch('/me/item/:id/bookmark', MeController.updateBookmark.bind(this))
this.router.delete('/me/item/:id/bookmark/:time', MeController.removeBookmark.bind(this))
this.router.patch('/me/password', MeController.updatePassword.bind(this))
this.router.patch('/me/password', this.auth.passwordChangeRateLimiter, MeController.updatePassword.bind(this))
this.router.get('/me/items-in-progress', MeController.getAllLibraryItemsInProgress.bind(this))
this.router.get('/me/series/:id/remove-from-continue-listening', MeController.removeSeriesFromContinueListening.bind(this))
this.router.get('/me/series/:id/readd-to-continue-listening', MeController.readdSeriesFromContinueListening.bind(this))
+120 -44
View File
@@ -8,9 +8,95 @@ class RateLimiterFactory {
static DEFAULT_WINDOW_MS = 10 * 60 * 1000 // 10 minutes
static DEFAULT_MAX = 40 // 40 attempts
static LOCAL_LOGIN_KEY = 'local-login'
static UNKNOWN_USER_KEY = 'unknown-user'
constructor() {
this.authRateLimiter = null
this.passwordChangeRateLimiter = null
this.disabledLimiter = null
}
/**
* Shared window, max, and message. Null when rate limiting is disabled.
* @returns {{ windowMs: number, max: number, message: string } | null}
*/
getLimiterConfig() {
// Disable by setting max to 0
if (process.env.RATE_LIMIT_AUTH_MAX === '0') {
return null
}
let windowMs = RateLimiterFactory.DEFAULT_WINDOW_MS
if (parseInt(process.env.RATE_LIMIT_AUTH_WINDOW) > 0) {
windowMs = parseInt(process.env.RATE_LIMIT_AUTH_WINDOW)
}
let max = RateLimiterFactory.DEFAULT_MAX
if (parseInt(process.env.RATE_LIMIT_AUTH_MAX) > 0) {
max = parseInt(process.env.RATE_LIMIT_AUTH_MAX)
}
let message = 'Too many authentication requests'
if (process.env.RATE_LIMIT_AUTH_MESSAGE) {
message = process.env.RATE_LIMIT_AUTH_MESSAGE
}
return { windowMs, max, message }
}
/**
* Log non-default limiter settings once per process.
* @param {{ windowMs: number, max: number }} config
*/
logCustomLimiterConfig(config) {
if (this.loggedCustomConfig) return
this.loggedCustomConfig = true
if (config.windowMs !== RateLimiterFactory.DEFAULT_WINDOW_MS) {
Logger.info(`[RateLimiterFactory] Authentication rate limiting window set to ${config.windowMs}ms by ENV variable`)
}
if (config.max !== RateLimiterFactory.DEFAULT_MAX) {
Logger.info(`[RateLimiterFactory] Authentication rate limiting max set to ${config.max} by ENV variable`)
}
}
/**
* @returns {RateLimitRequestHandler}
*/
getDisabledLimiter() {
if (!this.disabledLimiter) {
this.disabledLimiter = (req, res, next) => next()
}
return this.disabledLimiter
}
/**
* @param {{ windowMs: number, max: number, message: string }} config
* @param {(req: import('express').Request) => string} keyGenerator
* @returns {RateLimitRequestHandler}
*/
createLimiter(config, keyGenerator) {
return rateLimit({
windowMs: config.windowMs,
max: config.max,
standardHeaders: true,
legacyHeaders: false,
keyGenerator,
skipSuccessfulRequests: true,
handler: (req, res) => {
const userAgent = req.get('User-Agent') || 'Unknown'
const endpoint = req.path
const method = req.method
const userId = req.user?.id
const userLabel = userId ? `, User: ${userId}` : ''
Logger.warn(`[RateLimiter] Rate limit exceeded - Endpoint: ${method} ${endpoint}${userLabel}, User-Agent: ${userAgent}`)
res.status(429).json({
error: config.message
})
}
})
}
/**
@@ -22,59 +108,49 @@ class RateLimiterFactory {
return this.authRateLimiter
}
// Disable by setting max to 0
if (process.env.RATE_LIMIT_AUTH_MAX === '0') {
this.authRateLimiter = (req, res, next) => next()
const config = this.getLimiterConfig()
if (!config) {
Logger.info(`[RateLimiterFactory] Authentication rate limiting disabled by ENV variable`)
this.authRateLimiter = this.getDisabledLimiter()
return this.authRateLimiter
}
let windowMs = RateLimiterFactory.DEFAULT_WINDOW_MS
if (parseInt(process.env.RATE_LIMIT_AUTH_WINDOW) > 0) {
windowMs = parseInt(process.env.RATE_LIMIT_AUTH_WINDOW)
if (windowMs !== RateLimiterFactory.DEFAULT_WINDOW_MS) {
Logger.info(`[RateLimiterFactory] Authentication rate limiting window set to ${windowMs}ms by ENV variable`)
}
}
this.logCustomLimiterConfig(config)
let max = RateLimiterFactory.DEFAULT_MAX
if (parseInt(process.env.RATE_LIMIT_AUTH_MAX) > 0) {
max = parseInt(process.env.RATE_LIMIT_AUTH_MAX)
if (max !== RateLimiterFactory.DEFAULT_MAX) {
Logger.info(`[RateLimiterFactory] Authentication rate limiting max set to ${max} by ENV variable`)
}
}
// One process-wide bucket of failed local logins. Do not key on client IP headers.
this.authRateLimiter = this.createLimiter(config, () => RateLimiterFactory.LOCAL_LOGIN_KEY)
let message = 'Too many authentication requests'
if (process.env.RATE_LIMIT_AUTH_MESSAGE) {
message = process.env.RATE_LIMIT_AUTH_MESSAGE
}
this.authRateLimiter = rateLimit({
windowMs,
max,
standardHeaders: true,
legacyHeaders: false,
// One process-wide bucket of failed local logins. Do not key on client IP headers.
keyGenerator: () => RateLimiterFactory.LOCAL_LOGIN_KEY,
skipSuccessfulRequests: true,
handler: (req, res) => {
const userAgent = req.get('User-Agent') || 'Unknown'
const endpoint = req.path
const method = req.method
Logger.warn(`[RateLimiter] Rate limit exceeded - Endpoint: ${method} ${endpoint}, User-Agent: ${userAgent}`)
res.status(429).json({
error: message
})
}
})
Logger.debug(`[RateLimiterFactory] Created auth rate limiter: ${max} failed attempts per ${windowMs / 1000 / 60} minutes`)
Logger.debug(`[RateLimiterFactory] Created auth rate limiter: ${config.max} failed attempts per ${config.windowMs / 1000 / 60} minutes`)
return this.authRateLimiter
}
/**
* Failed current-password checks on PATCH /me/password, keyed by the authenticated user.
* @returns {RateLimitRequestHandler}
*/
getPasswordChangeRateLimiter() {
if (this.passwordChangeRateLimiter) {
return this.passwordChangeRateLimiter
}
const config = this.getLimiterConfig()
if (!config) {
this.passwordChangeRateLimiter = this.getDisabledLimiter()
return this.passwordChangeRateLimiter
}
this.logCustomLimiterConfig(config)
this.passwordChangeRateLimiter = this.createLimiter(config, (req) => {
const userId = req.user?.id
return userId ? String(userId) : RateLimiterFactory.UNKNOWN_USER_KEY
})
Logger.debug(`[RateLimiterFactory] Created password change rate limiter: ${config.max} failed attempts per ${config.windowMs / 1000 / 60} minutes`)
return this.passwordChangeRateLimiter
}
}
module.exports = new RateLimiterFactory()
@@ -21,6 +21,51 @@ function closeServer(server) {
})
}
function patchPassword(port, { userId, headers = {} } = {}) {
return new Promise((resolve, reject) => {
const body = JSON.stringify({ password: 'current', newPassword: 'next' })
const req = http.request(
{
hostname: '127.0.0.1',
port,
path: '/me/password',
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
'User-Agent': 'rate-limiter-test',
'x-user-id': userId,
...headers
}
},
(res) => {
res.resume()
res.on('end', () => resolve({ status: res.statusCode }))
}
)
req.on('error', reject)
req.write(body)
req.end()
})
}
function passwordChangeApp(limiter) {
const app = express()
app.patch(
'/me/password',
(req, res, next) => {
const userId = req.get('x-user-id')
if (userId) req.user = { id: userId }
next()
},
limiter,
(req, res) => {
res.status(400).send('Invalid password')
}
)
return app
}
function postLogin(port, { headers = {} } = {}) {
return new Promise((resolve, reject) => {
const body = JSON.stringify({ username: 'alice', password: 'guess' })
@@ -60,6 +105,7 @@ describe('rateLimiterFactory', () => {
beforeEach(() => {
RateLimiterFactory.authRateLimiter = null
RateLimiterFactory.passwordChangeRateLimiter = null
process.env.RATE_LIMIT_AUTH_MAX = '3'
process.env.RATE_LIMIT_AUTH_WINDOW = '60000'
delete process.env.RATE_LIMIT_AUTH_MESSAGE
@@ -70,6 +116,7 @@ describe('rateLimiterFactory', () => {
afterEach(() => {
RateLimiterFactory.authRateLimiter = null
RateLimiterFactory.passwordChangeRateLimiter = null
if (previousMax === undefined) delete process.env.RATE_LIMIT_AUTH_MAX
else process.env.RATE_LIMIT_AUTH_MAX = previousMax
if (previousWindow === undefined) delete process.env.RATE_LIMIT_AUTH_WINDOW
@@ -138,6 +185,64 @@ describe('rateLimiterFactory', () => {
}
})
it('limits password changes per user and ignores client IP headers', async () => {
const app = passwordChangeApp(RateLimiterFactory.getPasswordChangeRateLimiter())
const { server, port } = await listen(app)
try {
const alice = []
for (let i = 0; i < 4; i++) {
const result = await patchPassword(port, {
userId: 'alice',
headers: {
'X-Client-IP': `10.2.0.${i}`,
'X-Forwarded-For': `198.51.100.${i}`
}
})
alice.push(result.status)
}
const bob = await patchPassword(port, { userId: 'bob' })
expect(alice).to.deep.equal([400, 400, 400, 429])
expect(bob.status).to.equal(400)
expect(Logger.warn.calledWithMatch(/User: alice/)).to.equal(true)
} finally {
await closeServer(server)
}
})
it('does not consume a password-change slot for a successful update', async () => {
let attempt = 0
const app = express()
const limiter = RateLimiterFactory.getPasswordChangeRateLimiter()
app.patch(
'/me/password',
(req, res, next) => {
req.user = { id: 'alice' }
next()
},
limiter,
(req, res) => {
attempt += 1
res.status(attempt === 1 ? 200 : 400).send(attempt === 1 ? 'ok' : 'Invalid password')
}
)
const { server, port } = await listen(app)
try {
const success = await patchPassword(port, { userId: 'alice' })
expect(success.status).to.equal(200)
const statuses = []
for (let i = 0; i < 4; i++) {
const result = await patchPassword(port, { userId: 'alice' })
statuses.push(result.status)
}
expect(statuses).to.deep.equal([400, 400, 400, 429])
} finally {
await closeServer(server)
}
})
it('can be disabled with RATE_LIMIT_AUTH_MAX=0', async () => {
RateLimiterFactory.authRateLimiter = null
process.env.RATE_LIMIT_AUTH_MAX = '0'