Files
nginx_lua_waf/config/rate_limit_config.lua
2026-05-06 17:36:25 +08:00

118 lines
3.0 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- IP速率限制统一配置模块
-- 从公共配置加载,提供便捷的访问接口
local _M = {}
local common_config = require "config.common_config"
-- 处置策略枚举
_M.ACTION_ALLOW = "allow" -- 放行
_M.ACTION_RATE_LIMIT = "rate_limit" -- 限制速率返回429
_M.ACTION_BLOCK = "block" -- 封禁返回403
-- ============================================
-- 预设配置模板(可选使用)
-- ============================================
_M.presets = {
-- 宽松模式:放行
allow_all = {
time_window = 60,
max_requests = 10000,
action = _M.ACTION_ALLOW
},
-- 标准模式:限制速率
standard = {
time_window = 60,
max_requests = 100,
action = _M.ACTION_RATE_LIMIT
},
-- 严格模式:封禁
strict = {
time_window = 60,
max_requests = 50,
action = _M.ACTION_BLOCK
},
-- API接口保护
api_protection = {
time_window = 60,
max_requests = 30,
action = _M.ACTION_RATE_LIMIT,
status_code = 429,
message = "API rate limit exceeded"
},
-- 登录防暴力破解
login_protection = {
time_window = 300,
max_requests = 10,
action = _M.ACTION_BLOCK,
message = "Too many login attempts"
}
}
-- ============================================
-- 配置管理函数
-- ============================================
-- 获取配置(从公共配置读取)
function _M.get_config()
return common_config.rate_limit
end
-- 更新配置
function _M.update_config(new_config)
local cfg = common_config.rate_limit
for k, v in pairs(new_config) do
cfg[k] = v
end
-- 如果没有手动指定状态码根据action自动设置
if not new_config.status_code then
if cfg.action == _M.ACTION_RATE_LIMIT then
cfg.status_code = 429
elseif cfg.action == _M.ACTION_BLOCK then
cfg.status_code = 403
else
cfg.status_code = 200
end
end
-- 如果没有手动指定消息根据action自动设置
if not new_config.message then
if cfg.action == _M.ACTION_RATE_LIMIT then
cfg.message = "Rate limit exceeded. Please try again later."
elseif cfg.action == _M.ACTION_BLOCK then
cfg.message = "Access denied."
else
cfg.message = ""
end
end
end
-- 应用预设配置
function _M.apply_preset(preset_name)
local preset = _M.presets[preset_name]
if preset then
_M.update_config(preset)
return true
end
return false
end
-- 快速配置函数
-- @param time_window: 时间窗口(秒)
-- @param max_requests: 最大请求次数
-- @param action: 处置策略allow/rate_limit/block
function _M.configure(time_window, max_requests, action)
_M.update_config({
time_window = time_window,
max_requests = max_requests,
action = action
})
end
return _M