basic API to be used in swarm mode

This commit is contained in:
bunkerity 2021-03-12 10:42:31 +01:00
parent 781e4c8cbb
commit 7509ec2f2c
5 changed files with 64 additions and 0 deletions

20
confs/global/api.conf Normal file
View File

@ -0,0 +1,20 @@
rewrite_by_lua_block {
local api = require "api"
if api.is_api_call() then
ngx.header.content_type = 'text/plain'
if api.do_api_call() then
ngx.log(ngx.WARN, "[API] API call " .. ngx.var.request_uri .. " successfull from " .. ngx.var.remote_addr)
ngx.say("ok")
else
ngx.log(ngx.WARN, "[API] API call " .. ngx.var.request_uri .. " failed from " .. ngx.var.remote_addr)
ngx.say("ko")
end
ngx.exit(ngx.HTTP_OK)
end
ngx.exit(ngx.OK)
}

View File

@ -111,4 +111,7 @@ http {
# server config(s)
%INCLUDE_SERVER%
# API
%USE_API%
}

View File

@ -126,3 +126,5 @@ USE_ANTIBOT="${USE_ANTIBOT-no}"
ANTIBOT_RECAPTCHA_SCORE="${ANTIBOT_RECAPTCHA_SCORE-0.7}"
ANTIBOT_SESSION_SECRET="${ANTIBOT_SESSION_SECRET-random}"
USE_CROWDSEC="${USE_CROWDSEC-no}"
USE_API="${USE_API-no}"
API_URI="${API_URI-random}"

View File

@ -305,6 +305,17 @@ else
replace_in_file "/etc/nginx/nginx.conf" "%USE_CROWDSEC%" ""
fi
# API
if [ "$USE_API" = "yes" ] ; then
replace_in_file "/etc/nginx/nginx.conf" "%USE_API%" "include /etc/nginx/api.conf;"
if [ "$API_URI" = "random" ] ; then
API_URI="/$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)"
fi
replace_in_file "/usr/local/lib/lua/api.lua" "%API_URI%" "$API_URI"
else
replace_in_file "/etc/nginx/nginx.conf" "%USE_API%" ""
fi
# create empty logs
touch /var/log/access.log
touch /var/log/error.log

28
lua/api.lua Normal file
View File

@ -0,0 +1,28 @@
local M = {}
local api_uri = "%API_URI%"
local api_list = {}
api_list["^/reload$"] = function ()
return os.execute("/usr/sbin/nginx -s reload") == 0
end
function M.is_api_call ()
if ngx.var.request_uri:sub(1, #api_uri) .. "/" == api_uri .. "/" then
for uri, code in pairs(api_list) do
if string.match(ngx.var.request_uri:sub(#api_uri + 1), uri) then
return true
end
end
end
return false
end
function M.do_api_call ()
for uri, code in pairs(api_list) do
if string.match(ngx.var.request_uri:sub(#api_uri + 1), uri) then
return code()
end
end
end
return M