diff --git a/src/default.main b/src/default.main index cf40383..6ceb234 100644 --- a/src/default.main +++ b/src/default.main @@ -1,5 +1,6 @@ env JASIMA_MATOMO_HOST; env JASIMA_PROXY_HOST; env JASIMA_DEFAULT_ZONE; +env JASIMA_API_KEY; worker_processes auto; \ No newline at end of file diff --git a/src/lua/access.lua b/src/lua/access.lua index 7eee0f9..40f073e 100644 --- a/src/lua/access.lua +++ b/src/lua/access.lua @@ -1,3 +1,4 @@ +local api = require "api" local config = require "config" local geo = require "geo" local psl = require "psl" @@ -5,6 +6,10 @@ local utils = require "utils" local headers = ngx.req.get_headers() +if headers["Jasima-Api-Key"] then + api.handle_api_request(headers["Jasima-Api-Key"]) +end + local jasima_key = config.get_jasima_key() ngx.ctx.jasima_key = jasima_key if not jasima_key then diff --git a/src/lua/api.lua b/src/lua/api.lua new file mode 100644 index 0000000..d42eeb0 --- /dev/null +++ b/src/lua/api.lua @@ -0,0 +1,47 @@ +local cjson = require "cjson.safe" +local redis = require "resty.redis" + +local _M = {} + +function _M.handle_api_request(api_key) + if api_key ~= os.getenv("JASIMA_API_KEY") then + ngx.exit(401) + end + if ngx.var.request_uri == "/update" then + ngx.req.read_body() + local body_data = ngx.req.get_body_data() + if not body_data then + ngx.status = 400 + ngx.say("No request body") + ngx.exit(400) + end + local config = cjson.decode(body_data) + + local red = redis:new() + red:set_timeout(1000) + red:set_keepalive(10000, 100) + + local ok, err = red:connect("redis", 6379) + if not ok then return nil, "Redis connect failed: " .. err end + + for jasima_key, rewrite_config in pairs(config.origins) do + local key = "jasima:config:" .. jasima_key + red:set(key, cjson.encode(rewrite_config)) + end + + for pool, poolmap in pairs(config.pools) do + local key = "jasima:poolmap:" .. pool + red:set(key, cjson.encode(poolmap)) + end + + if not config.pools.public then + -- This is a default and things break if we don't have it + red:set("jasima:poolmap:public", "{}") + end + + ngx.exit(200) + end + ngx.exit(404) +end + +return _M