mirror of
https://github.com/advplyr/audiobookshelf.git
synced 2026-11-19 07:08:41 +01:00
Rate-limit failed local logins in one shared bucket
This commit is contained in:
1 parent
f57ca09f6e
commit
f35f40929d
4 files changed
+172
-14
No files matched your search
+4
-5
@@ -328,7 +328,7 @@ class Auth {
|
||||
})
|
||||
|
||||
// Refresh token route
|
||||
router.post('/auth/refresh', this.authRateLimiter, async (req, res) => {
|
||||
router.post('/auth/refresh', async (req, res) => {
|
||||
let refreshToken = req.cookies.refresh_token
|
||||
|
||||
// If x-refresh-token header is present, use it instead of the cookie
|
||||
@@ -359,7 +359,7 @@ class Auth {
|
||||
})
|
||||
|
||||
// openid strategy login route (this redirects to the configured openid login provider)
|
||||
router.get('/auth/openid', this.authRateLimiter, (req, res) => {
|
||||
router.get('/auth/openid', (req, res) => {
|
||||
const authorizationUrlResponse = this.oidcAuthStrategy.getAuthorizationUrl(req)
|
||||
|
||||
if (authorizationUrlResponse.error) {
|
||||
@@ -377,12 +377,11 @@ class Auth {
|
||||
|
||||
// This will be the oauth2 callback route for mobile clients
|
||||
// It will redirect to an app-link like audiobookshelf://oauth
|
||||
router.get('/auth/openid/mobile-redirect', this.authRateLimiter, (req, res) => this.oidcAuthStrategy.handleMobileRedirect(req, res))
|
||||
router.get('/auth/openid/mobile-redirect', (req, res) => this.oidcAuthStrategy.handleMobileRedirect(req, res))
|
||||
|
||||
// openid strategy callback route (this receives the token from the configured openid login provider)
|
||||
router.get(
|
||||
'/auth/openid/callback',
|
||||
this.authRateLimiter,
|
||||
(req, res, next) => {
|
||||
const sessionKey = this.oidcAuthStrategy.getStrategy()._key
|
||||
|
||||
@@ -461,7 +460,7 @@ class Auth {
|
||||
*
|
||||
* @example /auth/openid/config?issuer=http://192.168.1.66:9000/application/o/audiobookshelf/
|
||||
*/
|
||||
router.get('/auth/openid/config', this.authRateLimiter, this.isAuthenticated, async (req, res) => {
|
||||
router.get('/auth/openid/config', this.isAuthenticated, async (req, res) => {
|
||||
if (!req.user.isAdminOrUp) {
|
||||
Logger.error(`[Auth] Non-admin user "${req.user.username}" attempted to get issuer config`)
|
||||
return res.sendStatus(403)
|
||||
|
||||
@@ -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', this.auth.authRateLimiter, MeController.updatePassword.bind(this))
|
||||
this.router.patch('/me/password', 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))
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
const { rateLimit, RateLimitRequestHandler } = require('express-rate-limit')
|
||||
const Logger = require('../Logger')
|
||||
const requestIp = require('../libs/requestIp')
|
||||
|
||||
/**
|
||||
* Factory for creating authentication rate limiters
|
||||
@@ -8,6 +7,7 @@ const requestIp = require('../libs/requestIp')
|
||||
class RateLimiterFactory {
|
||||
static DEFAULT_WINDOW_MS = 10 * 60 * 1000 // 10 minutes
|
||||
static DEFAULT_MAX = 40 // 40 attempts
|
||||
static LOCAL_LOGIN_KEY = 'local-login'
|
||||
|
||||
constructor() {
|
||||
this.authRateLimiter = null
|
||||
@@ -55,17 +55,15 @@ class RateLimiterFactory {
|
||||
max,
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
keyGenerator: (req) => {
|
||||
// Override keyGenerator to handle proxy IPs
|
||||
return requestIp.getClientIp(req) || req.ip
|
||||
},
|
||||
// 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
|
||||
const ip = requestIp.getClientIp(req) || req.ip
|
||||
|
||||
Logger.warn(`[RateLimiter] Rate limit exceeded - IP: ${ip}, Endpoint: ${method} ${endpoint}, User-Agent: ${userAgent}`)
|
||||
Logger.warn(`[RateLimiter] Rate limit exceeded - Endpoint: ${method} ${endpoint}, User-Agent: ${userAgent}`)
|
||||
|
||||
res.status(429).json({
|
||||
error: message
|
||||
@@ -73,7 +71,7 @@ class RateLimiterFactory {
|
||||
}
|
||||
})
|
||||
|
||||
Logger.debug(`[RateLimiterFactory] Created auth rate limiter: ${max} attempts per ${windowMs / 1000 / 60} minutes`)
|
||||
Logger.debug(`[RateLimiterFactory] Created auth rate limiter: ${max} failed attempts per ${windowMs / 1000 / 60} minutes`)
|
||||
|
||||
return this.authRateLimiter
|
||||
}
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
const { expect } = require('chai')
|
||||
const express = require('express')
|
||||
const http = require('http')
|
||||
const sinon = require('sinon')
|
||||
|
||||
const Logger = require('../../../server/Logger')
|
||||
const RateLimiterFactory = require('../../../server/utils/rateLimiterFactory')
|
||||
|
||||
function listen(app) {
|
||||
const server = http.createServer(app)
|
||||
return new Promise((resolve) => {
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
resolve({ server, port: server.address().port })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function closeServer(server) {
|
||||
return new Promise((resolve, reject) => {
|
||||
server.close((err) => (err ? reject(err) : resolve()))
|
||||
})
|
||||
}
|
||||
|
||||
function postLogin(port, { headers = {} } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const body = JSON.stringify({ username: 'alice', password: 'guess' })
|
||||
const req = http.request(
|
||||
{
|
||||
hostname: '127.0.0.1',
|
||||
port,
|
||||
path: '/login',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
'User-Agent': 'rate-limiter-test',
|
||||
...headers
|
||||
}
|
||||
},
|
||||
(res) => {
|
||||
let data = ''
|
||||
res.on('data', (chunk) => {
|
||||
data += chunk
|
||||
})
|
||||
res.on('end', () => {
|
||||
resolve({ status: res.statusCode, body: data, headers: res.headers })
|
||||
})
|
||||
}
|
||||
)
|
||||
req.on('error', reject)
|
||||
req.write(body)
|
||||
req.end()
|
||||
})
|
||||
}
|
||||
|
||||
describe('rateLimiterFactory', () => {
|
||||
const previousMax = process.env.RATE_LIMIT_AUTH_MAX
|
||||
const previousWindow = process.env.RATE_LIMIT_AUTH_WINDOW
|
||||
const previousMessage = process.env.RATE_LIMIT_AUTH_MESSAGE
|
||||
|
||||
beforeEach(() => {
|
||||
RateLimiterFactory.authRateLimiter = null
|
||||
process.env.RATE_LIMIT_AUTH_MAX = '3'
|
||||
process.env.RATE_LIMIT_AUTH_WINDOW = '60000'
|
||||
delete process.env.RATE_LIMIT_AUTH_MESSAGE
|
||||
sinon.stub(Logger, 'info')
|
||||
sinon.stub(Logger, 'warn')
|
||||
sinon.stub(Logger, 'debug')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
RateLimiterFactory.authRateLimiter = 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
|
||||
else process.env.RATE_LIMIT_AUTH_WINDOW = previousWindow
|
||||
if (previousMessage === undefined) delete process.env.RATE_LIMIT_AUTH_MESSAGE
|
||||
else process.env.RATE_LIMIT_AUTH_MESSAGE = previousMessage
|
||||
sinon.restore()
|
||||
})
|
||||
|
||||
it('shares one bucket across rotating client IP headers and returns 429 after max failures', async () => {
|
||||
const app = express()
|
||||
const limiter = RateLimiterFactory.getAuthRateLimiter()
|
||||
app.post('/login', limiter, (req, res) => {
|
||||
res.status(401).json({ error: 'Unauthorized' })
|
||||
})
|
||||
|
||||
const { server, port } = await listen(app)
|
||||
try {
|
||||
const statuses = []
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const result = await postLogin(port, {
|
||||
headers: {
|
||||
'X-Client-IP': `10.0.0.${i}`,
|
||||
'X-Forwarded-For': `203.0.113.${i}`
|
||||
}
|
||||
})
|
||||
statuses.push(result.status)
|
||||
}
|
||||
|
||||
expect(statuses).to.deep.equal([401, 401, 401, 429])
|
||||
} finally {
|
||||
await closeServer(server)
|
||||
}
|
||||
})
|
||||
|
||||
it('does not consume a slot for successful logins', async () => {
|
||||
const app = express()
|
||||
const limiter = RateLimiterFactory.getAuthRateLimiter()
|
||||
let attempt = 0
|
||||
app.post('/login', limiter, (req, res) => {
|
||||
attempt += 1
|
||||
if (attempt === 1) {
|
||||
return res.status(200).json({ ok: true })
|
||||
}
|
||||
res.status(401).json({ error: 'Unauthorized' })
|
||||
})
|
||||
|
||||
const { server, port } = await listen(app)
|
||||
try {
|
||||
const success = await postLogin(port)
|
||||
expect(success.status).to.equal(200)
|
||||
|
||||
const statuses = []
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const result = await postLogin(port, {
|
||||
headers: {
|
||||
'X-Client-IP': `10.1.0.${i}`
|
||||
}
|
||||
})
|
||||
statuses.push(result.status)
|
||||
}
|
||||
|
||||
expect(statuses).to.deep.equal([401, 401, 401, 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'
|
||||
|
||||
const app = express()
|
||||
const limiter = RateLimiterFactory.getAuthRateLimiter()
|
||||
app.post('/login', limiter, (req, res) => {
|
||||
res.status(401).json({ error: 'Unauthorized' })
|
||||
})
|
||||
|
||||
const { server, port } = await listen(app)
|
||||
try {
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const result = await postLogin(port)
|
||||
expect(result.status).to.equal(401)
|
||||
}
|
||||
} finally {
|
||||
await closeServer(server)
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user