2023-10-27 01:19:08 +00:00
|
|
|
local util = require("util")
|
|
|
|
|
2022-12-06 18:53:20 +00:00
|
|
|
function log(msg)
|
|
|
|
ngx.log(ngx.STDERR, tostring(msg))
|
|
|
|
end
|
|
|
|
|
|
|
|
local ctx = {}
|
|
|
|
|
|
|
|
function ctx:setWantedScripts(graph)
|
|
|
|
self._wanted_scripts = graph
|
|
|
|
end
|
|
|
|
|
2022-12-06 21:24:25 +00:00
|
|
|
function ctx:loadFromConfig(conf)
|
|
|
|
ctx:setWantedScripts(conf.wantedScripts)
|
|
|
|
ctx:loadChain()
|
|
|
|
end
|
|
|
|
|
2023-10-27 01:19:08 +00:00
|
|
|
|
2022-12-06 18:53:20 +00:00
|
|
|
function ctx:loadChain()
|
|
|
|
self.compiled_chain = {}
|
|
|
|
for module_name, module_config in pairs(self._wanted_scripts) do
|
2022-12-06 21:24:25 +00:00
|
|
|
local module = require('scripts.' .. module_name)
|
2023-10-27 01:19:08 +00:00
|
|
|
local module_config_readonly = table.readonly(module_config)
|
|
|
|
local module_state = module.init(module_config_readonly)
|
|
|
|
table.insert(self.compiled_chain, {module, module_config_readonly, module_state})
|
2022-12-06 18:53:20 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
function ctx:onRequest()
|
|
|
|
local request_uri = ngx.var.uri
|
|
|
|
|
|
|
|
-- find out which modules to call based on their regexes
|
|
|
|
local callbacks_to_call = {}
|
|
|
|
for _, filter in ipairs(self.compiled_chain) do
|
|
|
|
local module, module_config, state = unpack(filter)
|
|
|
|
|
|
|
|
for callback_regex, callback_function in pairs(module.callbacks) do
|
2023-10-27 01:19:08 +00:00
|
|
|
local match = ngx.re.match(request_uri, callback_regex)
|
2022-12-06 18:53:20 +00:00
|
|
|
if match then
|
2022-12-07 04:49:00 +00:00
|
|
|
table.insert(callbacks_to_call, {module, callback_function, module_config, state})
|
2022-12-06 18:53:20 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2022-12-07 04:49:00 +00:00
|
|
|
for _, tuple in ipairs(callbacks_to_call) do
|
|
|
|
local module, callback_function, config, state = unpack(tuple)
|
2022-12-06 18:53:20 +00:00
|
|
|
local status_code, body = callback_function(config, state)
|
|
|
|
if status_code ~= nil then
|
2022-12-07 04:49:00 +00:00
|
|
|
log('filtered by module ' .. module.name)
|
2022-12-06 18:53:20 +00:00
|
|
|
ngx.status = status_code
|
|
|
|
ngx.say(body or "request denied")
|
|
|
|
ngx.exit(status_code)
|
2023-10-27 01:19:08 +00:00
|
|
|
return
|
2022-12-06 18:53:20 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
return ctx
|