diff --git a/rootfs/etc/nginx/lua/balancer/sticky.lua b/rootfs/etc/nginx/lua/balancer/sticky.lua index 6f0aef2a9..366ee6d32 100644 --- a/rootfs/etc/nginx/lua/balancer/sticky.lua +++ b/rootfs/etc/nginx/lua/balancer/sticky.lua @@ -103,8 +103,18 @@ local function pick_new_upstream(self) end local function should_set_cookie(self) - if self.cookie_session_affinity.locations then + if self.cookie_session_affinity.locations and ngx.var.host then local locs = self.cookie_session_affinity.locations[ngx.var.host] + if locs == nil then + -- Based off of wildcard hostname in ../certificate.lua + local wildcard_host, _, err = ngx.re.sub(ngx.var.host, "^[^\\.]+\\.", "*.", "jo") + if err then + ngx.log(ngx.ERR, "error: ", err); + elseif wildcard_host then + locs = self.cookie_session_affinity.locations[wildcard_host] + end + end + if locs ~= nil then for _, path in pairs(locs) do if ngx.var.location_path == path then diff --git a/rootfs/etc/nginx/lua/test/balancer/sticky_test.lua b/rootfs/etc/nginx/lua/test/balancer/sticky_test.lua index b0e0cc30e..0c8b3297d 100644 --- a/rootfs/etc/nginx/lua/test/balancer/sticky_test.lua +++ b/rootfs/etc/nginx/lua/test/balancer/sticky_test.lua @@ -141,6 +141,41 @@ describe("Sticky", function() end) end) + context("when client doesn't have a cookie set and cookie_locations contains a matching wildcard location", function() + before_each(function () + ngx.var.host = "dev.test.com" + end) + after_each(function () + ngx.var.host = "test.com" + end) + + it("sets a cookie on the client", function() + local s = {} + cookie.new = function(self) + local cookie_instance = { + set = function(self, payload) + assert.equal(payload.key, test_backend.sessionAffinityConfig.cookieSessionAffinity.name) + assert.equal(payload.path, ngx.var.location_path) + assert.equal(payload.domain, nil) + assert.equal(payload.httponly, true) + assert.equal(payload.secure, false) + return true, nil + end, + get = function(k) return false end, + } + s = spy.on(cookie_instance, "set") + return cookie_instance, false + end + + local b = get_test_backend() + b.sessionAffinityConfig.cookieSessionAffinity.locations = {} + b.sessionAffinityConfig.cookieSessionAffinity.locations["*.test.com"] = {"/"} + local sticky_balancer_instance = sticky:new(b) + assert.has_no.errors(function() sticky_balancer_instance:balance() end) + assert.spy(s).was_called() + end) + end) + context("when client doesn't have a cookie set and location not in cookie_locations", function() it("picks an endpoint for the client", function() local sticky_balancer_instance = sticky:new(test_backend)