-- Checks if test_key exists in items map
-- items: map of key, values
-- test_key: key to search for
function map_contains(items, test_key)
    return items[string.lower(test_key)] ~= nil
  end

-- When invoked during a response, sets Cache-Control headers
-- txn: The current transaction object that gives access to response properties.
function cachecontrols_response(txn)
    headers = txn.http:res_get_headers()
    local lower_headers = {}
    for k, v in pairs(headers) do
      lower_headers[string.lower(k)] = v
    end

    if not map_contains(lower_headers, "Cache-Control") and not map_contains(lower_headers, "Expires") then
        txn.http:res_add_header("Cache-Control", "no-cache")
        txn.http:res_add_header("Pragma", "no-cache")
        txn.http:res_add_header("Expires", 0)
    end
  end

-- When invoked during a response, sets CSP Headers
-- txn: The current transaction object that gives access to response properties.
function csp_response(txn)
    headers = txn.http:res_get_headers()
    local lower_headers = {}
    for k, v in pairs(headers) do
      lower_headers[string.lower(k)] = v
    end

    if not map_contains(lower_headers, "Content-Security-Policy") then
      txn.http:res_add_header("Content-Security-Policy", "default-src 'none';frame-ancestors 'none';object-src 'none';upgrade-insecure-requests")
    end
end

-- Register the actions with HAProxy
core.register_action("cachecontrol", {"http-res"}, cachecontrols_response, 0)
core.register_action("csp", {"http-res"}, csp_response, 0)
