diff --git a/apisix/plugins/hmac-auth.lua b/apisix/plugins/hmac-auth.lua index 73cb947d3c03..9a63db977ad2 100644 --- a/apisix/plugins/hmac-auth.lua +++ b/apisix/plugins/hmac-auth.lua @@ -244,7 +244,16 @@ local function generate_signature(ctx, secret_key, params) -- whether to encode the uri parameters if type(param) == "table" then + local vals = {} for _, val in pairs(param) do + if type(val) == "boolean" then + val = "" + end + core.table.insert(vals, val) + end + core.table.sort(vals) + + for _, val in pairs(vals) do core.table.insert(query_tab, encode_or_not(key) .. "=" .. encode_or_not(val)) end else diff --git a/t/plugin/hmac-auth3.t b/t/plugin/hmac-auth3.t index bc66dc6569f1..d90dcbcdb4d3 100644 --- a/t/plugin/hmac-auth3.t +++ b/t/plugin/hmac-auth3.t @@ -532,3 +532,64 @@ plugin_attr: } --- response_body passed + + + +=== TEST 10: Test sort table param. +--- config + location /t { + content_by_lua_block { + local ngx_time = ngx.time + local ngx_http_time = ngx.http_time + local core = require("apisix.core") + local t = require("lib.test_admin") + local hmac = require("resty.hmac") + local ngx_encode_base64 = ngx.encode_base64 + + local secret_key = "my-secret-key" + local timestamp = ngx_time() + local gmt = ngx_http_time(timestamp) + local access_key = "my-access-key" + local custom_header_a = "asld$%dfasf" + local custom_header_b = "23879fmsldfk" + local body = "{\"name\": \"world\"}" + + local signing_string = { + "POST", + "/hello", + "a=&a=1&a=2&a1a=123&c=&name=123", + access_key, + gmt, + "x-custom-header-a:" .. custom_header_a, + "x-custom-header-b:" .. custom_header_b + } + signing_string = core.table.concat(signing_string, "\n") .. "\n" + core.log.info("signing_string:", signing_string) + + local signature = hmac:new(secret_key, hmac.ALGOS.SHA256):final(signing_string) + local body_digest = hmac:new(secret_key, hmac.ALGOS.SHA256):final(body) + + core.log.info("signature:", ngx_encode_base64(signature)) + local headers = {} + headers["X-HMAC-SIGNATURE"] = ngx_encode_base64(signature) + headers["X-HMAC-ALGORITHM"] = "hmac-sha256" + headers["Date"] = gmt + headers["X-HMAC-DIGEST"] = ngx_encode_base64(body_digest) + headers["X-HMAC-ACCESS-KEY"] = access_key + headers["X-HMAC-SIGNED-HEADERS"] = "x-custom-header-a;x-custom-header-b" + headers["x-custom-header-a"] = custom_header_a + headers["x-custom-header-b"] = custom_header_b + + local code, body = t.test('/hello?c=&a1a=123&name=123&a&a=2&a=1', + ngx.HTTP_POST, + body, + nil, + headers + ) + + ngx.status = code + ngx.say(body) + } + } +--- response_body +passed