api - add missing ctx fill

This commit is contained in:
florian 2023-04-24 16:06:52 +02:00
parent bcc5e6bb50
commit 4871a21040
No known key found for this signature in database
GPG Key ID: 3D80806F12602A7C
2 changed files with 37 additions and 10 deletions

View File

@ -104,6 +104,7 @@ helpers.fill_ctx = function()
data.request_uri = ngx.var.request_uri
data.request_method = ngx.var.request_method
data.http_user_agent = ngx.var.http_user_agent
data.http_host = ngx.var.http_host
data.server_name = ngx.var.server_name
-- IP data : global
local ip_is_global, err = utils.ip_is_global(data.remote_addr)

View File

@ -15,26 +15,52 @@ server {
# check IP and do the API call
access_by_lua_block {
local capi = require "bunkerweb.api"
local clogger = require "bunkerweb.logger"
local logger = clogger:new("API")
local api = capi:new()
if not ngx.var.http_host or ngx.var.http_host ~= "{{ API_SERVER_NAME }}" then
logger:log(ngx.WARN, "wrong Host header from IP " .. ngx.var.remote_addr)
-- Instantiate objects and import required modules
local logger = require "bunkerweb.logger":new("API")
local api = require "bunkerweb.api":new()
local helpers = require "bunkerweb.helpers"
-- Start API handler
logger:log(ngx.INFO, "API handler started")
-- Fill ctx
logger:log(ngx.INFO, "filling ngx.ctx ...")
local ok, ret, errors = helpers.fill_ctx()
if not ok then
logger:log(ngx.ERR, "fill_ctx() failed : " .. ret)
elseif errors then
for i, error in ipairs(errors) do
logger:log(ngx.ERR, "fill_ctx() error " .. tostring(i) .. " : " .. error)
end
end
logger:log(ngx.INFO, "ngx.ctx filled (ret = " .. ret .. ")")
-- Check host header
if not ngx.ctx.bw.http_host or ngx.ctx.bw.http_host ~= "{{ API_SERVER_NAME }}" then
logger:log(ngx.WARN, "wrong Host header from IP " .. ngx.ctx.bw.remote_addr)
return ngx.exit(ngx.HTTP_CLOSE)
end
-- Check IP
local ok, err = api:is_allowed_ip()
if not ok then
logger:log(ngx.WARN, "can't validate access from IP " .. ngx.var.remote_addr .. " : " .. err)
logger:log(ngx.WARN, "can't validate access from IP " .. ngx.ctx.bw.remote_addr .. " : " .. err)
return ngx.exit(ngx.HTTP_CLOSE)
end
logger:log(ngx.NOTICE, "validated access from IP " .. ngx.var.remote_addr)
logger:log(ngx.NOTICE, "validated access from IP " .. ngx.ctx.bw.remote_addr)
-- Do API call
local ok, err, status, resp = api:do_api_call()
if not ok then
logger:log(ngx.WARN, "call from " .. ngx.var.remote_addr .. " on " .. ngx.var.uri .. " failed : " .. err)
logger:log(ngx.WARN, "call from " .. ngx.ctx.bw.remote_addr .. " on " .. ngx.ctx.bw.uri .. " failed : " .. err)
else
logger:log(ngx.NOTICE, "successful call from " .. ngx.var.remote_addr .. " on " .. ngx.var.uri .. " : " .. err)
logger:log(ngx.NOTICE, "successful call from " .. ngx.ctx.bw.remote_addr .. " on " .. ngx.ctx.bw.uri .. " : " .. err)
end
-- Start API handler
logger:log(ngx.INFO, "API handler ended")
-- Send response
ngx.status = status
ngx.say(resp)
return ngx.exit(status)