Simplify/optimize url/acl matching algorithm : drop support for legacy lua regexes, only use regexes for actual regexes, otherwise use a simple 'startswith' check

This commit is contained in:
Alexandre Aubin 2023-12-23 20:39:07 +01:00
parent 493ba581bb
commit e9a335eaf7

View file

@ -49,17 +49,6 @@ function cached_jwt_verify(data, secret)
end end
end end
-- The 'match' function uses PCRE regex as default
-- If '%.' is found in the regex, we assume it's a LUA regex (legacy code)
-- 'match' returns the matched text.
function match(s, regex)
if not string.find(regex, '%%%.') then
return rex.match(s, regex)
else
return string.match(s,regex)
end
end
-- Test whether a string starts/ends with something -- Test whether a string starts/ends with something
function string.starts(String, Start) function string.starts(String, Start)
if not String then if not String then
@ -189,24 +178,27 @@ end
-- ########################################################################### -- ###########################################################################
permission = nil permission = nil
longest_url_match = "" longest_match = ""
ngx_full_url = ngx.var.host..ngx.var.uri ngx_full_url = ngx.var.host..ngx.var.uri
for permission_name, permission_infos in pairs(conf["permissions"]) do for permission_name, permission_infos in pairs(conf["permissions"]) do
if next(permission_infos['uris']) ~= nil then if next(permission_infos['uris']) ~= nil then
for _, url in pairs(permission_infos['uris']) do for _, prefix in pairs(permission_infos['uris']) do
if string.starts(url, "re:") then local match = nil
url = string.sub(url, 4, string.len(url)) if string.starts(prefix, "re:") then
end prefix = string.sub(prefix, 4, string.len(prefix))
-- We want to match the beginning of the url -- Make sure we match the prefix from the beginning of the url
if not string.starts(url, "^") then if not string.starts(prefix, "^") then
url = "^"..url prefix = "^"..prefix
end
match = rex.match(ngx_full_url, prefix)
elseif string.starts(ngx_full_url, prefix) then
match = prefix
end end
local m = match(ngx_full_url, url) if match ~= nil and string.len(match) > string.len(longest_match) then
if m ~= nil and string.len(m) > string.len(longest_url_match) then longest_match = match
longest_url_match = m
permission = permission_infos permission = permission_infos
permission["id"] = permission_name permission["id"] = permission_name
end end