From 07c5f3a7ad4c72977ea0966d1efdc4859e3c29d4 Mon Sep 17 00:00:00 2001 From: Hockenba <60619916+Hockenba@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:25:56 -0500 Subject: [PATCH 01/13] feat(*): revoke every cookie of a login on destroy A cookie session gets a new session ID on every save, but destroy only revoked the ID being destroyed, so older copies of the cookie and one an attacker refreshed before the logout stayed valid until they timed out. - generate a random lineage ID on the first save and carry it, encrypted, through every rotation; a new login gets a new lineage - write a lineage mark on destroy, so every cookie of that login is rejected and other logins of the account are unaffected - key the revocation cache by the storage settings instead of the instance - keep store errors in a separate cache, per revocation_fail_mode - size the caches with $session_revocation_cache_size and $session_revocation_error_cache_size --- README.md | 60 +++++- lib/resty/session.lua | 322 +++++++++++++++++++++++++----- lib/resty/session/shm.lua | 1 + lib/resty/session/utils.lua | 40 ++++ spec/06-revocation-1_spec.lua | 355 ++++++++++++++++++++++++++++++++-- spec/07-revocation-2_spec.lua | 5 + 6 files changed, 716 insertions(+), 67 deletions(-) diff --git a/README.md b/README.md index 256da929..7b998553 100644 --- a/README.md +++ b/README.md @@ -330,8 +330,8 @@ Here are the possible session configuration options: | `storage` | `nil` | Storage is responsible of storing session data, use `nil` or `"cookie"` (data is stored in cookie), `"dshm"`, `"file"`, `"memcached"`, `"mysql"`, `"postgres"`, `"redis"`, or `"shm"`, or give a name of custom module (`"custom-storage"`), or a `table` that implements session storage interface. | | `revocation` | `nil` | Storage used for cookie session revocation records. Use `nil` or `false` to disable, a storage name such as `"shm"`, `"redis"`, `"mysql"`, or `"postgres"`, a custom storage module name, or a storage `table` with `set`/`get` methods. | | `revocation_fail_mode` | `"open"` | Behavior when the revocation store is unreachable, use `"open"` (treat as not revoked) or `"closed"` (reject the session). | -| `revocation_cache_ttl` | `5` | Worker-local cache TTL for successful revocation lookups (`true`/`false`) (in seconds). Set to `0` to disable. This is the maximum stale window before a worker observes a revocation written elsewhere. | -| `revocation_error_cache_ttl` | `5` | Worker-local cache TTL for revocation store errors (in seconds). Set to `0` to disable. `"open"` caches not-revoked; `"closed"` caches the error. | +| `revocation_cache_ttl` | `5` | Worker-local cache TTL for successful revocation lookups (in seconds). Set to `0` to disable. This is the maximum stale window before a worker observes a revocation written elsewhere. | +| `revocation_error_cache_ttl` | `5` | Worker-local cache TTL for revocation store errors (in seconds). Set to `0` to disable. Errors are cached per `revocation_fail_mode`: `"open"` caches not-revoked and `"closed"` caches the error, and one is never replayed under the other. | | `dshm` | `nil` | Configuration for dshm storage, e.g. `{ prefix = "sessions" }` (see below) | | `file` | `nil` | Configuration for file storage, e.g. `{ path = "/tmp", suffix = "session" }` (see below) | | `memcached` | `nil` | Configuration for memcached storage, e.g. `{ prefix = "sessions" }` (see below) | @@ -370,15 +370,56 @@ seconds. Store unavailability is cached for `revocation_error_cache_ttl` seconds: `"open"` caches not-revoked, and `"closed"` caches the error, so a burst of requests does not retry the store on every lookup. +Successful lookups and store errors are cached separately in each worker, up to +1024 entries each. Size them with the nginx variables +`$session_revocation_cache_size` and `$session_revocation_error_cache_size`, +defined where every request sees them, for example with a `map` in the `http` +block. Each worker reads them once, on its first revocation lookup, so changing +them needs a reload. Invalid values are ignored with a warning. + +```nginx +map $host $session_revocation_cache_size { + default 4096; +} +``` + `session:destroy` (including a last-audience `session:logout`) runs the same -cached lookup first. A cached `true` means the identifier is already revoked -and no store write is made, and a cached error is returned without contacting -the store. Otherwise the identifier is written to the selected storage with a +cached lookup first for the session id. A cached `true` means it is already +revoked and no store write is made, and a cached error is returned without +contacting the store. Otherwise the identifier is written to the selected storage with a TTL equal to the remaining session lifetime (rolling and absolute timeouts), and the local cache is updated immediately. When the write fails, the failure is cached for the same identifier under `revocation_error_cache_ttl`, so the next lookup sees it instead of the store. The revocation mark is a lightweight -sentinel; no session payload is stored. +sentinel; no session payload is stored. The lineage mark is written without a +lookup, so a remember-cookie logout may write it twice. + +Lineage lookups cache the timestamp of the mark, which is compared with each +session's creation time. Cache entries are isolated by revocation storage. +A storage is identified by its settings, whether it is given by name +(`"redis"`) or as a table: equal settings share cache entries, even from +different tables, and different settings never do. Functions and other values +that JSON cannot encode are left out of the settings, so a custom storage table +needs a plain field, such as a name, that tells it apart from other custom +storages. A revocation updates the local worker cache at once. Other workers see it when their cached lookup +expires; set `revocation_cache_ttl = 0` to check the store on every request. + +The marks live only in the revocation storage. If it loses its data, for example +Redis restarted without persistence, revoked cookies are accepted again until +they expire. + +Every save of a cookie session gives it a new session id, so revoking only the id +being destroyed would leave other cookies of the same login usable, such as one +an attacker refreshed before the logout. With revocation enabled, a random +lineage id is generated on the first save and carried, encrypted, through every +rotation. `session:destroy` revokes the lineage along with the session id, so +every cookie of that login is rejected, whether it was issued before or after +the logout. A new login starts a new lineage. The mark is kept for a full +rolling window plus `stale_ttl`, capped by the absolute timeout (the `remember_*` +windows when a remember cookie is used). Cookies issued before the lineage id +existed are revoked by their own session id only. Each cache miss costs one more +lookup, and each destroy writes one more mark; `revocation_fail_mode` applies to +both. Use `revocation_fail_mode` to control behavior when the storage is unavailable: @@ -999,6 +1040,13 @@ end Destroy the session and clear the cookies. In error case it returns `nil` and an error message, otherwise `true`. +With revocation enabled it also revokes the lineage of the session, so every +cookie of the same login is rejected (see [Session Revocation Configuration](#session-revocation-configuration)). +When a remember cookie is in use, the remember session is revoked first, and no +cookie is cleared until every revocation mark is written. With +`revocation_fail_mode` set to `"closed"`, a store failure therefore leaves the +cookies in place, and `session:destroy` can be called again. + ```lua local session, err, exists = require "resty.session".open() if exists then diff --git a/lib/resty/session.lua b/lib/resty/session.lua index 96615aa9..f477d5ad 100644 --- a/lib/resty/session.lua +++ b/lib/resty/session.lua @@ -80,6 +80,7 @@ local DATA_SIZE = 3 -- 47 local TAG_SIZE = 16 -- 63 local IDLING_OFFSET_SIZE = 3 -- 66 local MAC_SIZE = 16 -- 82 +local LINEAGE_SIZE = SID_SIZE -- as big as the session id local HEADER_TAG_SIZE = COOKIE_TYPE_SIZE + FLAGS_SIZE + SID_SIZE + CREATION_TIME_SIZE + ROLLING_OFFSET_SIZE + DATA_SIZE @@ -146,6 +147,7 @@ local DEFAULT_REQUEST_HEADERS local DEFAULT_RESPONSE_HEADERS local DEFAULT_STORAGE local DEFAULT_REVOCATION +local DEFAULT_REVOCATION_ID local DEFAULT_REVOCATION_FAIL_MODE local DEFAULT_REVOCATION_CACHE_TTL local DEFAULT_REVOCATION_ERROR_CACHE_TTL @@ -375,33 +377,100 @@ end local REVOCATION_MARK = "1" +local DEFAULT_REVOCATION_CACHE_SIZE = 1024 local REVOCATION_CACHE +local REVOCATION_ERROR_CACHE -local function get_revocation_cache_key(cookie_name, key) - return cookie_name .. ":" .. key +-- The caches are shared by every session of a worker, so their sizes are not +-- session options. Each is read once per worker, when it is created, from an +-- nginx variable, 1024 when it is not set. Define it where every request sees +-- it, for example with a `map` in the http block. +local function revocation_cache_size(name) + local size = DEFAULT_REVOCATION_CACHE_SIZE + -- nginx variables are not available in every context, for example in timers + local ok, configured = pcall(function() return var[name] end) + if ok and configured then + size = tonumber(configured) + if not size or size < 1 or size % 1 ~= 0 then + log(WARN, "[session] ignoring invalid $", name, ": ", configured) + size = DEFAULT_REVOCATION_CACHE_SIZE + end + end + + return size +end + + +-- A storage is identified by its settings, not by the table that holds them: a +-- storage given by name is created again by every session.new, and the same +-- settings can come from different tables. Equal settings share cache entries, +-- different settings never do. +local function get_revocation_id(revocation, configuration) + local name, settings + if type(revocation) == "string" then + name = revocation + settings = configuration and configuration[revocation] + + elseif type(revocation) == "table" then + name = "table" + settings = revocation + + else + return nil + end + + if type(settings) ~= "table" then + return name + end + + local fingerprint, err = utils.config_fingerprint(settings) + assert(fingerprint, "invalid session revocation configuration: " .. tostring(err)) + + return name .. "\0" .. fingerprint +end + + +local function get_revocation_cache_key(self, cookie_name, key) + return self.revocation_id .. "\0" .. cookie_name .. ":" .. key end -local function revocation_cache_get(cookie_name, key) - local cache_key = get_revocation_cache_key(cookie_name, key) +-- Store errors are kept apart from the lookups, so that an outage cannot push +-- the lookups out. An error is cached as `false` when the fail mode is open and +-- as the message when closed, so it is kept per fail mode: one policy never +-- sees the other's. +local function revocation_cache_get(self, cookie_name, key) + local cache_key = get_revocation_cache_key(self, cookie_name, key) local value = REVOCATION_CACHE:get(cache_key) - if value == true or value == false then + if value == true or value == false or type(value) == "number" then return value end + value = REVOCATION_ERROR_CACHE:get(cache_key .. ":" .. self.revocation_fail_mode) if value then return nil, value end + + return value end -local function revocation_cache_set(cookie_name, key, value, ttl) - local cache_key = get_revocation_cache_key(cookie_name, key) +local function revocation_cache_set(self, cookie_name, key, value, ttl) + local cache_key = get_revocation_cache_key(self, cookie_name, key) + REVOCATION_ERROR_CACHE:delete(cache_key .. ":open") + REVOCATION_ERROR_CACHE:delete(cache_key .. ":closed") return REVOCATION_CACHE:set(cache_key, value, ttl) end +local function revocation_error_cache_set(self, cookie_name, key, value, ttl) + local cache_key = get_revocation_cache_key(self, cookie_name, key) + REVOCATION_CACHE:delete(cache_key) + return REVOCATION_ERROR_CACHE:set(cache_key .. ":" .. self.revocation_fail_mode, value, ttl) +end + + local function handle_revocation_error(self, err, msg) if self.revocation_fail_mode == "open" then log(WARN, "[session] ", msg, ": ", err) @@ -412,25 +481,21 @@ local function handle_revocation_error(self, err, msg) end -local function is_session_revoked(self, sid, cookie_name) - if self.storage or not sid then - return false, nil - end - +local function is_revoked(self, key, cookie_name, current_time, creation_time) local revocation = self.revocation if not revocation then return false, nil end - local key, herr = self.hash_storage_key(sid) - if not key then - return nil, herr + local storage_key, err = self.hash_storage_key(key) + if not storage_key then + return nil, err end local cache_ttl = self.revocation_cache_ttl local error_cache_ttl = self.revocation_error_cache_ttl if cache_ttl > 0 or error_cache_ttl > 0 then - local value, err = revocation_cache_get(cookie_name, key) + local value, err = revocation_cache_get(self, cookie_name, storage_key) if err then return nil, err end @@ -438,33 +503,45 @@ local function is_session_revoked(self, sid, cookie_name) if value == true or value == false then return value end + + if type(value) == "number" then + return value >= creation_time, nil + end end - local current_time = time() - local data, err = revocation:get(cookie_name, key, current_time) + local data, err = revocation:get(cookie_name, storage_key, current_time) if err then local ok, revocation_err = handle_revocation_error(self, err, "unable to check session revocation") if not ok then if error_cache_ttl > 0 then - revocation_cache_set(cookie_name, key, revocation_err, error_cache_ttl) + revocation_error_cache_set(self, cookie_name, storage_key, revocation_err, error_cache_ttl) end return nil, revocation_err end if error_cache_ttl > 0 then - revocation_cache_set(cookie_name, key, false, error_cache_ttl) + revocation_error_cache_set(self, cookie_name, storage_key, false, error_cache_ttl) end return false, nil end - local revoked = data == REVOCATION_MARK + local revoked_at = tonumber(data) + local cached = data == REVOCATION_MARK or revoked_at or false if cache_ttl > 0 then - revocation_cache_set(cookie_name, key, revoked, cache_ttl) + revocation_cache_set(self, cookie_name, storage_key, cached, cache_ttl) end - return revoked, nil + return cached == true or (revoked_at ~= nil and revoked_at >= creation_time), nil +end + + +-- A lineage id is generated when a session is first saved and travels in the +-- encrypted payload through every rotation of the session id, so one logout +-- can revoke every cookie descended from the same login. +local function lineage_revocation_key(lineage) + return "lineage:" .. lineage end @@ -489,7 +566,8 @@ local function mark_session_revoked(self, remember, meta) return nil, herr end - local revoked, revocation_err = is_session_revoked(self, sid, cookie_name) + local current_time = time() + local revoked, revocation_err = is_revoked(self, sid, cookie_name, current_time, meta.creation_time) if revocation_err then return nil, revocation_err end @@ -498,7 +576,6 @@ local function mark_session_revoked(self, remember, meta) return true end - local current_time = time() local ttl = get_store_ttl(self, remember, current_time, meta.creation_time, meta.rolling_offset) local ok, err = revocation:set(cookie_name, key, REVOCATION_MARK, ttl, current_time) if not ok then @@ -511,7 +588,7 @@ local function mark_session_revoked(self, remember, meta) value = errmsg(err, "unable to check session revocation") end - revocation_cache_set(cookie_name, key, value, error_cache_ttl) + revocation_error_cache_set(self, cookie_name, key, value, error_cache_ttl) end return handle_revocation_error(self, err, "unable to mark session revoked") @@ -519,7 +596,72 @@ local function mark_session_revoked(self, remember, meta) local cache_ttl = self.revocation_cache_ttl if cache_ttl > 0 then - revocation_cache_set(cookie_name, key, true, cache_ttl) + revocation_cache_set(self, cookie_name, key, true, cache_ttl) + end + + return true +end + + +-- The lineage ids of the audiences in the session, without duplicates. +local function get_lineages(self) + local lineages = {} + local seen = {} + for i = 1, #self.data do + local lineage = self.data[i][4] + if lineage and not seen[lineage] then + seen[lineage] = true + lineages[#lineages + 1] = lineage + end + end + + return lineages +end + + +-- How long a lineage mark is kept: a full rolling window from now, since a +-- sibling cookie may have been saved just before the logout, plus the stale ttl +-- for a request still running. The absolute timeout caps it, and a remember +-- cookie uses the longer remember windows. +local function get_lineage_ttl(self, current_time, creation_time) + local ttl = get_store_ttl(self, false, current_time, creation_time) + if self.remember or self.remember_meta then + ttl = max(ttl, get_store_ttl(self, true, current_time, creation_time)) + end + + return ttl + self.stale_ttl +end + + +-- Revoke every cookie of the lineages of the session, so that a logout also +-- rejects the cookies that were rotated from the one the client presented. +local function revoke_lineages(self, meta) + local revocation = self.revocation + if self.storage or not revocation or not meta or not meta.sid or not meta.creation_time then + return true + end + + for _, lineage in ipairs(get_lineages(self)) do + local current_time = time() + local ttl = get_lineage_ttl(self, current_time, meta.creation_time) + local key, herr = self.hash_storage_key(lineage_revocation_key(lineage)) + if not key then + return nil, herr + end + + local ok, err = revocation:set(self.cookie_name, key, tostring(current_time), ttl, current_time) + if not ok then + ok, err = handle_revocation_error(self, err, "unable to mark session revoked") + if not ok then + return nil, err + end + + else + local cache_ttl = self.revocation_cache_ttl + if cache_ttl > 0 then + revocation_cache_set(self, self.cookie_name, key, current_time, min(cache_ttl, ttl)) + end + end end return true @@ -869,7 +1011,7 @@ local function open(self, remember, meta_only) end end - local revoked, err = is_session_revoked(self, sid, cookie_name) + local revoked, err = is_revoked(self, sid, cookie_name, current_time, creation_time) if err then return nil, err end @@ -1019,9 +1161,42 @@ local function open(self, remember, meta_only) local audience_index local count = #data for i = 1, count do - if data[i][2] == audience then + -- With `decode_array_with_array_mt`, cjson encodes the entry up to its length, + -- and the holes cleared below would cut off the lineage id. + setmetatable(data[i], nil) + + -- cjson decodes the JSON null of a missing subject or lineage id as userdata + if type(data[i][3]) == "userdata" then + data[i][3] = nil + end + if type(data[i][4]) == "userdata" then + data[i][4] = nil + end + + if not audience_index and data[i][2] == audience then audience_index = i - break + end + end + + if self.revocation then + for i = 1, count do + if remember or i == audience_index then + local revoked, err = false, nil + if data[i][4] then + revoked, err = is_revoked(self, lineage_revocation_key(data[i][4]), self.cookie_name, current_time, creation_time) + end + if err then + return nil, err + end + if revoked then + if remember then + self.remember_meta = {} + else + self.meta = DUMMY_META + end + return nil, "session revoked" + end + end end end @@ -1041,6 +1216,25 @@ local function open(self, remember, meta_only) end +-- Give the audience the session is using a lineage id if it has none yet. It is +-- generated once, on the first save, and every later save carries it along. It is +-- the fourth field of the entry of the audience. +local function assign_lineage(self) + local current = self.data[self.data_index] + if current[4] then + return true + end + + local lineage, err = rand_bytes(LINEAGE_SIZE) + if not lineage then + return nil, errmsg(err, "unable to generate session lineage id") + end + + current[4] = encode_base64url(lineage) + return true +end + + local function save(self, state, remember) local cookie_name local meta @@ -1096,6 +1290,13 @@ local function save(self, state, remember) local data, data_size, cookie_chunks do data = self.data + if self.revocation and not storage then + local ok, lerr = assign_lineage(self) + if not ok then + return nil, lerr + end + end + if self.enforce_same_subject then local count = #data if count > 1 then @@ -1400,7 +1601,7 @@ local function save_info(self, data, remember) end -local function destroy(self, remember) +local function destroy(self, remember, already_revoked) local cookie_name local meta if remember then @@ -1414,9 +1615,16 @@ local function destroy(self, remember) local cookie_name_size = #cookie_name local storage = self.storage - local ok, err = mark_session_revoked(self, remember, meta) - if not ok then - return nil, err + if not already_revoked then + local ok, err = mark_session_revoked(self, remember, meta) + if not ok then + return nil, err + end + + ok, err = revoke_lineages(self, meta) + if not ok then + return nil, err + end end local cookie_chunks = 1 @@ -2316,20 +2524,27 @@ function metatable:destroy() return nil, "unable to destroy nonexistent session" end + -- The remember session is revoked before any cookie is cleared, so a store + -- failure leaves the browser with cookies that can still retry the logout. + local remembered + if get_remember(self) then + remembered = self.remember_meta or open(self, true, true) + end + + if remembered then + local ok, err = mark_session_revoked(self, true, self.remember_meta or {}) + if not ok then + return nil, err + end + end + local ok, err = destroy(self) if not ok then return nil, err end - if get_remember(self) then - if not self.remember_meta then - local remembered = open(self, true, true) - if not remembered then - return true - end - end - - ok, err = destroy(self, true) + if remembered then + ok, err = destroy(self, true, true) if not ok then return nil, err end @@ -2509,8 +2724,8 @@ local session = { -- @field storage Storage is responsible of storing session data, use `nil` or `"cookie"` (data is stored in cookie), `"dshm"`, `"file"`, `"memcached"`, `"mysql"`, `"postgres"`, `"redis"`, or `"shm"`, or give a name of custom module (`"custom-storage"`), or a `table` that implements session storage interface (defaults to `nil`) -- @field revocation Storage used for cookie session revocation records, use `nil` or `false` to disable, `"dshm"`, `"file"`, `"memcached"`, `"mysql"`, `"postgres"`, `"redis"`, or `"shm"`, a custom storage module name, or a storage `table` with `set`/`get` methods (defaults to `nil`) -- @field revocation_fail_mode Behavior when the revocation store is unreachable, use `"open"` (treat as not revoked) or `"closed"` (reject the session) (defaults to `"open"`) --- @field revocation_cache_ttl Worker-local TTL for successful revocation lookups (`true`/`false`); `0` disables (defaults to `5`) (in seconds) --- @field revocation_error_cache_ttl Worker-local TTL for revocation store errors; `0` disables (defaults to `5`) (in seconds) +-- @field revocation_cache_ttl Worker-local TTL for successful revocation lookups; `0` disables (defaults to `5`) (in seconds) +-- @field revocation_error_cache_ttl Worker-local TTL for revocation store errors, kept per `revocation_fail_mode`; `0` disables (defaults to `5`) (in seconds) -- @field dshm Configuration for dshm storage, e.g. `{ prefix = "sessions" }` -- @field file Configuration for file storage, e.g. `{ path = "/tmp", suffix = "session" }` -- @field memcached Configuration for memcached storage, e.g. `{ prefix = "sessions" }` @@ -2697,6 +2912,7 @@ function session.init(configuration) DEFAULT_RESPONSE_HEADERS = opt(configuration, "response_headers") DEFAULT_STORAGE = opt(configuration, "storage") DEFAULT_REVOCATION = opt(configuration, "revocation") + DEFAULT_REVOCATION_ID = configuration and get_revocation_id(configuration.revocation, configuration) DEFAULT_REVOCATION_FAIL_MODE = opt(configuration, "revocation_fail_mode", "open") DEFAULT_REVOCATION_CACHE_TTL = opt(configuration, "revocation_cache_ttl", 5) DEFAULT_REVOCATION_ERROR_CACHE_TTL = opt(configuration, "revocation_error_cache_ttl", 5) @@ -2758,6 +2974,16 @@ function session.new(configuration) local response_headers = opt(configuration, "response_headers", DEFAULT_RESPONSE_HEADERS) local storage = opt(configuration, "storage", DEFAULT_STORAGE) local revocation = opt(configuration, "revocation", DEFAULT_REVOCATION) + local revocation_id + if revocation then + local raw = configuration and configuration.revocation + if raw == nil then + revocation_id = DEFAULT_REVOCATION_ID + + else + revocation_id = get_revocation_id(raw, configuration) + end + end local revocation_fail_mode = opt(configuration, "revocation_fail_mode", DEFAULT_REVOCATION_FAIL_MODE) local revocation_cache_ttl = opt(configuration, "revocation_cache_ttl", DEFAULT_REVOCATION_CACHE_TTL) local revocation_error_cache_ttl = opt(configuration, "revocation_error_cache_ttl", DEFAULT_REVOCATION_ERROR_CACHE_TTL) @@ -2817,8 +3043,9 @@ function session.new(configuration) local cookie_flags = FLAGS_BUFFER:get() - if REVOCATION_CACHE == nil and revocation and revocation_cache_ttl > 0 then - REVOCATION_CACHE = assert(require("resty.lrucache").new(1024)) + if REVOCATION_CACHE == nil and revocation and (revocation_cache_ttl > 0 or revocation_error_cache_ttl > 0) then + REVOCATION_CACHE = assert(require("resty.lrucache").new(revocation_cache_size("session_revocation_cache_size"))) + REVOCATION_ERROR_CACHE = assert(require("resty.lrucache").new(revocation_cache_size("session_revocation_error_cache_size"))) end local self = setmetatable({ @@ -2842,6 +3069,7 @@ function session.new(configuration) flags = flags, storage = storage, revocation = revocation, + revocation_id = revocation_id, revocation_fail_mode = revocation_fail_mode, revocation_cache_ttl = revocation_cache_ttl, revocation_error_cache_ttl = revocation_error_cache_ttl, diff --git a/lib/resty/session/shm.lua b/lib/resty/session/shm.lua index 9844f4ab..7133c779 100644 --- a/lib/resty/session/shm.lua +++ b/lib/resty/session/shm.lua @@ -299,6 +299,7 @@ function storage.new(configuration) return setmetatable({ prefix = prefix, suffix = suffix, + zone = zone, dict = dict, }, metatable) end diff --git a/lib/resty/session/utils.lua b/lib/resty/session/utils.lua index b5b88749..64714e91 100644 --- a/lib/resty/session/utils.lua +++ b/lib/resty/session/utils.lua @@ -859,6 +859,45 @@ end +local config_fingerprint do + local cjson + + --- + -- Fingerprint of a configuration table. + -- + -- The table is encoded as JSON with sorted keys and hashed, so equal settings + -- give the same fingerprint whichever table they come from, and credentials + -- are not kept in it. Values that cannot be encoded, such as functions and + -- userdata, are left out, at any depth. Returns `nil` and an error when the + -- table cannot be encoded at all, for example when it refers to itself. + -- + -- @function utils.config_fingerprint + -- @tparam table configuration configuration table + -- @treturn string|nil fingerprint + -- @treturn string error message + -- + -- @usage + -- local fingerprint = require("resty.session.utils").config_fingerprint({ + -- host = "127.0.0.1", + -- port = 6379, + -- }) + config_fingerprint = function(configuration) + if not cjson then + cjson = require("cjson.safe").new() + cjson.encode_sort_keys(true) + cjson.encode_skip_unsupported_value_types(true) + end + + local encoded, err = cjson.encode(configuration) + if not encoded then + return nil, err + end + + return encode_base64url(assert(sha256(encoded))) + end +end + + local load_storage do local DSHM local FILE @@ -1194,6 +1233,7 @@ return { encrypt_aes_256_gcm = encrypt_aes_256_gcm, decrypt_aes_256_gcm = decrypt_aes_256_gcm, hmac_sha256 = hmac_sha256, + config_fingerprint = config_fingerprint, load_storage = load_storage, errmsg = errmsg, get_name = get_name, diff --git a/spec/06-revocation-1_spec.lua b/spec/06-revocation-1_spec.lua index b88f2932..eb3f593b 100644 --- a/spec/06-revocation-1_spec.lua +++ b/spec/06-revocation-1_spec.lua @@ -137,6 +137,7 @@ for _, st in ipairs({ describe("[#" .. st .. "] session: revocation lifecycle", function() local cookie_name = "session_cookie" + local cookie_index = 0 local test_key = "test_key" local value = "test_data" @@ -149,8 +150,8 @@ for _, st in ipairs({ return extract_cookie(cookie_name, cookies["Set-Cookie"]) end - local function open_session(session_cookie) - local s = session.new() + local function open_session(session_cookie, configuration) + local s = session.new(configuration) session.__set_ngx_var({ ["cookie_" .. cookie_name] = session_cookie, }) @@ -164,6 +165,9 @@ for _, st in ipairs({ end before_each(function() + -- Lineage marks share the worker cache across session instances. + cookie_index = cookie_index + 1 + cookie_name = "session_cookie_" .. st .. "_" .. cookie_index local conf = { cookie_name = cookie_name, storage = "cookie", @@ -350,11 +354,15 @@ describe("session: revocation cache", function() return s, ok, err end + local fake_stores = 0 + local function initialize(cache_ttl) get_count = 0 set_count = 0 revoked = false + fake_stores = fake_stores + 1 store = { + name = "fake-store-" .. fake_stores, get = function() get_count = get_count + 1 return revoked and "1" or nil @@ -397,7 +405,7 @@ describe("session: revocation cache", function() s, ok, err = open_session() assert.is_true(ok) assert.is_nil(err) - assert.equals(1, get_count) + assert.equals(2, get_count) s:close() end) @@ -410,13 +418,13 @@ describe("session: revocation cache", function() ok, err = s:destroy() assert.is_true(ok) assert.is_nil(err) - assert.equals(1, set_count) + assert.equals(2, set_count) local reopened reopened, ok, err = open_session() assert.is_nil(ok) assert.equals("session revoked", err) - assert.equals(1, get_count) + assert.equals(2, get_count) reopened:close() end) @@ -433,7 +441,7 @@ describe("session: revocation cache", function() s, ok, err = open_session() assert.is_true(ok) assert.is_nil(err) - assert.equals(2, get_count) + assert.equals(4, get_count) s:close() end) @@ -448,7 +456,7 @@ describe("session: revocation cache", function() s, ok, err = open_session() assert.is_true(ok) assert.is_nil(err) - assert.equals(2, get_count) + assert.equals(4, get_count) s:close() end) @@ -480,7 +488,7 @@ describe("session: revocation cache", function() s, ok, err = open_session() assert.is_true(ok) assert.is_nil(err) - assert.equals(1, get_count) + assert.equals(2, get_count) s:close() end) @@ -516,7 +524,54 @@ describe("session: revocation cache", function() s:close() end) - it("skips the revocation write when the lookup is already revoked", function() + it("does not reuse a cached open fail-mode error under a closed fail mode", function() + get_count = 0 + store = { + get = function() + get_count = get_count + 1 + return nil, "connection refused" + end, + set = function() + return true + end, + } + + session.init({ + cookie_name = cookie_name, + storage = "cookie", + revocation = store, + revocation_fail_mode = "open", + revocation_error_cache_ttl = 5, + }) + + local s, ok, err = open_session() + assert.is_true(ok) + assert.is_nil(err) + s:close() + + session.init({ + cookie_name = cookie_name, + storage = "cookie", + revocation = store, + revocation_fail_mode = "closed", + revocation_error_cache_ttl = 5, + }) + + s, ok, err = open_session() + assert.is_nil(ok) + assert.matches("unable to check session revocation", err) + assert.equals(3, get_count) + s:close() + + -- each policy still caches its own interpretation of the error + s, ok, err = open_session() + assert.is_nil(ok) + assert.matches("unable to check session revocation", err) + assert.equals(3, get_count) + s:close() + end) + + it("skips the session id write when it is already revoked", function() local s, ok, err = open_session() assert.is_true(ok) assert.is_nil(err) @@ -524,20 +579,21 @@ describe("session: revocation cache", function() local other, ook, oerr = open_session() assert.is_true(ook) assert.is_nil(oerr) - assert.equals(1, get_count) + assert.equals(2, get_count) session.__set_ngx_header(cookies) ok, err = s:destroy() assert.is_true(ok) assert.is_nil(err) - assert.equals(1, set_count) + assert.equals(2, set_count) session.__set_ngx_header(cookies) ook, oerr = other:destroy() assert.is_true(ook) assert.is_nil(oerr) - assert.equals(1, get_count) - assert.equals(1, set_count) + assert.equals(2, get_count) + -- the lineage mark is written again, without a lookup first + assert.equals(3, set_count) end) it("caches a failed revocation write for later lookups", function() @@ -581,7 +637,278 @@ describe("session: revocation cache", function() reopened, ok, err = open_session() assert.is_nil(ok) assert.matches("unable to check session revocation", err) - assert.equals(1, get_count) + assert.equals(2, get_count) reopened:close() end) end) + + +describe("session: revocation lineage", function() + local cookie_name = "lineage_cookie" + local marks + local ttls + local fail_lineage_writes + + local store = { + get = function(_, _, key) + return marks[key] + end, + set = function(_, _, key, value, ttl) + -- session id marks carry "1"; lineage marks carry the time they were written + if fail_lineage_writes and value ~= "1" then + return nil, "connection refused" + end + marks[key] = value + ttls[key] = ttl + return true + end, + } + + local function initialize(fail_mode) + marks = {} + ttls = {} + fail_lineage_writes = false + session.init({ + cookie_name = cookie_name, + storage = "cookie", + revocation = store, + revocation_fail_mode = fail_mode, + revocation_cache_ttl = 0, + revocation_error_cache_ttl = 0, + }) + end + + local function login() + local cookies = {} + session.__set_ngx_header(cookies) + local s = session.new() + s:set("test_key", "test_data") + local ok, err = s:save() + assert.is_true(ok) + assert.is_nil(err) + return extract_cookie(cookie_name, cookies["Set-Cookie"]) + end + + local function open(cookie) + session.__set_ngx_var({ + ["cookie_" .. cookie_name] = cookie, + }) + local s = session.new() + local ok, err = s:open() + return s, ok, err + end + + -- what a refresh does to a cookie: open it and save it under a new session id + local function rotate(cookie) + local s, ok, err = open(cookie) + assert.is_true(ok) + assert.is_nil(err) + local cookies = {} + session.__set_ngx_header(cookies) + ok, err = s:save() + assert.is_true(ok) + assert.is_nil(err) + local rotated = extract_cookie(cookie_name, cookies["Set-Cookie"]) + assert.not_equals(cookie, rotated) + return rotated + end + + local function destroy(cookie) + local s, ok, err = open(cookie) + assert.is_true(ok) + assert.is_nil(err) + session.__set_ngx_header({}) + return s:destroy() + end + + it("revokes the whole lineage whichever cookie of it is presented at logout", function() + -- a chain of rotations plus a fork made from the original cookie + local names = { "original", "rotated", "rotated again", "forked from original" } + + for logout_index = 1, #names do + initialize("closed") + + local original = login() + local rotated = rotate(original) + local cookies = { + original, + rotated, + rotate(rotated), + rotate(original), + } + + local ok, err = destroy(cookies[logout_index]) + assert.is_true(ok, "logout with the " .. names[logout_index] .. " cookie") + assert.is_nil(err) + + for index, cookie in ipairs(cookies) do + local s, opened, oerr = open(cookie) + assert.is_nil(opened, names[index] .. " cookie after logout with the " + .. names[logout_index] .. " cookie") + assert.equals("session revoked", oerr) + s:close() + end + + -- a different login is not part of the lineage + local other = login() + local s, opened, oerr = open(other) + assert.is_true(opened) + assert.is_nil(oerr) + s:close() + end + end) + + it("revokes cookies rotated from a revoked cookie after the logout", function() + initialize("closed") + + local original = login() + local s, ok, err = open(original) + assert.is_true(ok) + assert.is_nil(err) + + -- the attacker holds an open session while the user logs out + local cookies = {} + session.__set_ngx_header(cookies) + ok, err = destroy(rotate(original)) + assert.is_true(ok) + assert.is_nil(err) + + session.__set_ngx_header(cookies) + s:save() + local late = extract_cookie(cookie_name, cookies["Set-Cookie"]) + local opened, oerr + s, opened, oerr = open(late) + assert.is_nil(opened) + assert.equals("session revoked", oerr) + s:close() + end) + + it("keeps another login usable when one login logs out", function() + initialize("closed") + + local first = login() + local second = login() + assert.is_true(destroy(first)) + + local s, opened, err = open(second) + assert.is_true(opened) + assert.is_nil(err) + s:close() + end) + + it("keeps the lineage mark for a full rolling window", function() + initialize("closed") + + local ok = destroy(login()) + assert.is_true(ok) + + local lineage_ttl + for key, value in pairs(marks) do + if value ~= "1" then + lineage_ttl = ttls[key] + end + end + + -- a full default rolling window plus the stale ttl, shorter than what is left + -- of the absolute timeout: a cookie saved right before the logout is covered + assert.equals(3600 + 10, lineage_ttl) + end) + + it("rejects the logout when the lineage mark cannot be written and the fail mode is closed", function() + initialize("closed") + + local cookie = login() + fail_lineage_writes = true + + local ok, err = destroy(cookie) + assert.is_nil(ok) + assert.matches("unable to mark session revoked", err) + end) + + it("does not add a lineage id when revocation is disabled", function() + session.init({ + cookie_name = cookie_name, + storage = "cookie", + revocation = false, + }) + + local cookie = login() + local s, ok = open(cookie) + assert.is_true(ok) + -- the lineage id is the fourth field of the payload entry + assert.is_nil(s.data[s.data_index][4]) + s:close() + end) +end) + + +describe("session: revocation cache with a named backend", function() + local cookie_name = "named_backend_cookie" + local gets + + before_each(function() + gets = 0 + -- a named backend is instantiated again by every session.new + package.loaded["counting-revocation"] = { + new = function() + return { + get = function() + gets = gets + 1 + end, + set = function() + return true + end, + } + end, + } + session.init({ cookie_name = cookie_name, storage = "cookie" }) + end) + + -- a new table on every call, like a caller that builds its configuration per request + local function configuration(host) + return { + cookie_name = cookie_name, + storage = "cookie", + revocation = "counting-revocation", + ["counting-revocation"] = { host = host }, + } + end + + local function login(host) + local cookies = {} + session.__set_ngx_header(cookies) + local s = session.new(configuration(host)) + s:set("test_key", "test_data") + assert.is_true(s:save()) + return extract_cookie(cookie_name, cookies["Set-Cookie"]) + end + + local function open(cookie, host) + session.__set_ngx_var({ ["cookie_" .. cookie_name] = cookie }) + local s = session.new(configuration(host)) + local ok, err = s:open() + s:close() + return ok, err + end + + it("shares cache entries between sessions given equal backend settings", function() + local cookie = login("redis-a") + + for _ = 1, 3 do + assert.is_true(open(cookie, "redis-a")) + end + + -- the session id and its lineage are each looked up once + assert.equals(2, gets) + end) + + it("does not share cache entries between different backend settings", function() + local cookie = login("redis-a") + + assert.is_true(open(cookie, "redis-a")) + assert.equals(2, gets) + + assert.is_true(open(cookie, "redis-b")) + assert.equals(4, gets) + end) +end) diff --git a/spec/07-revocation-2_spec.lua b/spec/07-revocation-2_spec.lua index 87e5bd8d..766f0d14 100644 --- a/spec/07-revocation-2_spec.lua +++ b/spec/07-revocation-2_spec.lua @@ -277,6 +277,7 @@ describe("Revocation tests 2 session: revocation_fail_mode", function() cookie_name = cookie_name, storage = "cookie", revocation = { + name = "fake-store-1", set = function() return nil, "connection refused" end, @@ -298,6 +299,7 @@ describe("Revocation tests 2 session: revocation_fail_mode", function() cookie_name = cookie_name, storage = "cookie", revocation = { + name = "fake-store-2", set = function() return nil, "connection refused" end, @@ -329,6 +331,7 @@ describe("Revocation tests 2 session: revocation_fail_mode", function() cookie_name = cookie_name, storage = "cookie", revocation = { + name = "fake-store-3", set = function() return nil, "connection refused" end, @@ -347,6 +350,7 @@ describe("Revocation tests 2 session: revocation_fail_mode", function() it("destroy: closed fail mode fails when marking revoked fails", function() local s = session.new({ revocation = { + name = "fake-store-4", set = function() return nil, "connection refused" end, @@ -405,6 +409,7 @@ describe("Revocation tests 2 session: Fields validation", function() it("new rejects a store table without set and get", function() local ok, err = pcall(session.new, { revocation = { + name = "fake-store-6", set = function() end, }, }) From 6197ae02311a4a4690d018a2357b30ba0189ddf4 Mon Sep 17 00:00:00 2001 From: Hockenba <60619916+Hockenba@users.noreply.github.com> Date: Mon, 23 Nov 2026 10:33:30 -0500 Subject: [PATCH 02/13] fix(revocation): write the lineage mark before the session id mark If the second write of a logout failed in closed mode, a retry found the session id mark, rejected the cookie on open and never wrote the missing lineage mark, so a cookie rotated earlier stayed valid. Writing the lineage mark first means a failure between the two writes still revokes every cookie of the login, and a logout that fails on the first write can be retried. --- README.md | 4 ++- lib/resty/session.lua | 15 ++++++++--- spec/06-revocation-1_spec.lua | 50 ++++++++++++++++++++++++++++++++++- 3 files changed, 64 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7b998553..f3fc4c95 100644 --- a/README.md +++ b/README.md @@ -419,7 +419,9 @@ rolling window plus `stale_ttl`, capped by the absolute timeout (the `remember_* windows when a remember cookie is used). Cookies issued before the lineage id existed are revoked by their own session id only. Each cache miss costs one more lookup, and each destroy writes one more mark; `revocation_fail_mode` applies to -both. +both. The lineage mark is written before the session id mark, so a failed +logout can be retried: if only the second write fails, every cookie of the login is +already revoked. Use `revocation_fail_mode` to control behavior when the storage is unavailable: diff --git a/lib/resty/session.lua b/lib/resty/session.lua index f477d5ad..fb20ac5e 100644 --- a/lib/resty/session.lua +++ b/lib/resty/session.lua @@ -1616,12 +1616,15 @@ local function destroy(self, remember, already_revoked) local storage = self.storage if not already_revoked then - local ok, err = mark_session_revoked(self, remember, meta) + -- The lineage mark goes first: it rejects every cookie of the login, so a + -- failure between the two writes cannot leave a cookie that the retry of the + -- logout (which sees the session id mark and does not destroy) would miss. + local ok, err = revoke_lineages(self, meta) if not ok then return nil, err end - ok, err = revoke_lineages(self, meta) + ok, err = mark_session_revoked(self, remember, meta) if not ok then return nil, err end @@ -2532,7 +2535,13 @@ function metatable:destroy() end if remembered then - local ok, err = mark_session_revoked(self, true, self.remember_meta or {}) + -- the lineage first, as in destroy + local ok, err = revoke_lineages(self, self.meta) + if not ok then + return nil, err + end + + ok, err = mark_session_revoked(self, true, self.remember_meta or {}) if not ok then return nil, err end diff --git a/spec/06-revocation-1_spec.lua b/spec/06-revocation-1_spec.lua index eb3f593b..fc819513 100644 --- a/spec/06-revocation-1_spec.lua +++ b/spec/06-revocation-1_spec.lua @@ -648,6 +648,7 @@ describe("session: revocation lineage", function() local marks local ttls local fail_lineage_writes + local fail_sid_writes local store = { get = function(_, _, key) @@ -655,7 +656,7 @@ describe("session: revocation lineage", function() end, set = function(_, _, key, value, ttl) -- session id marks carry "1"; lineage marks carry the time they were written - if fail_lineage_writes and value ~= "1" then + if (fail_lineage_writes and value ~= "1") or (fail_sid_writes and value == "1") then return nil, "connection refused" end marks[key] = value @@ -668,6 +669,7 @@ describe("session: revocation lineage", function() marks = {} ttls = {} fail_lineage_writes = false + fail_sid_writes = false session.init({ cookie_name = cookie_name, storage = "cookie", @@ -823,6 +825,52 @@ describe("session: revocation lineage", function() local ok, err = destroy(cookie) assert.is_nil(ok) assert.matches("unable to mark session revoked", err) + -- nothing was written, not even the session id mark + assert.is_nil(next(marks)) + end) + + it("can retry a logout whose lineage mark could not be written", function() + initialize("closed") + + local original = login() + local rotated = rotate(original) + fail_lineage_writes = true + + local ok, err = destroy(rotated) + assert.is_nil(ok) + assert.matches("unable to mark session revoked", err) + assert.is_nil(next(marks)) + + -- the cookie is still usable, so the browser can send the logout again + fail_lineage_writes = false + assert.is_true(destroy(rotated)) + + for _, cookie in ipairs({ original, rotated }) do + local _, opened, open_err = open(cookie) + assert.is_falsy(opened) + assert.equals("session revoked", open_err) + end + end) + + it("revokes the whole lineage when only the session id mark could not be written", function() + initialize("closed") + + local original = login() + local rotated = rotate(original) + fail_sid_writes = true + + local ok, err = destroy(rotated) + assert.is_nil(ok) + assert.matches("unable to mark session revoked", err) + + -- the lineage mark was written first, so a retry that never reaches destroy + -- still finds every cookie of the login revoked + fail_sid_writes = false + for _, cookie in ipairs({ original, rotated }) do + local _, opened, open_err = open(cookie) + assert.is_falsy(opened) + assert.equals("session revoked", open_err) + end end) it("does not add a lineage id when revocation is disabled", function() From 7ae12e1c2206c77f9e62abd2c25d9dd4f6ba84fb Mon Sep 17 00:00:00 2001 From: Hockenba <60619916+Hockenba@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:11:47 -0500 Subject: [PATCH 03/13] test(revocation): fail the session id mark write in the cached write error spec The lineage mark is written first now, so the spec fails the session id mark, which is the write whose error is cached. --- spec/06-revocation-1_spec.lua | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/spec/06-revocation-1_spec.lua b/spec/06-revocation-1_spec.lua index fc819513..25d3e837 100644 --- a/spec/06-revocation-1_spec.lua +++ b/spec/06-revocation-1_spec.lua @@ -604,9 +604,14 @@ describe("session: revocation cache", function() get_count = get_count + 1 return nil end, - set = function() + set = function(_, _, _, value) set_count = set_count + 1 - return nil, "connection refused" + -- the lineage mark is written first and succeeds; the session id mark + -- (which carries "1") fails + if value == "1" then + return nil, "connection refused" + end + return true end, } @@ -626,12 +631,14 @@ describe("session: revocation cache", function() ok, err = s:destroy() assert.is_nil(ok) assert.matches("unable to mark session revoked", err) - assert.equals(1, set_count) + -- the lineage mark, then the session id mark that fails + assert.equals(2, set_count) ok, err = s:destroy() assert.is_nil(ok) assert.matches("unable to check session revocation", err) - assert.equals(1, set_count) + -- the lineage mark is written again; the cached error stops the session id write + assert.equals(3, set_count) local reopened reopened, ok, err = open_session() From c935f32ab2d61654789823ac66a91978bcc556bb Mon Sep 17 00:00:00 2001 From: Hockenba <60619916+Hockenba@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:26:14 -0500 Subject: [PATCH 04/13] fix(utils): fingerprint a configuration without cjson options config_fingerprint used the encode_sort_keys and encode_skip_unsupported_value_types methods of cjson, which not every cjson build has, so the revocation specs failed on the OpenResty job. Write the configuration in a canonical form with sorted keys instead, and leave out functions and userdata as before. --- lib/resty/session/utils.lua | 90 ++++++++++++++++++++++++++++++------- spec/01-utils_spec.lua | 44 ++++++++++++++++++ 2 files changed, 118 insertions(+), 16 deletions(-) diff --git a/lib/resty/session/utils.lua b/lib/resty/session/utils.lua index 64714e91..354af86f 100644 --- a/lib/resty/session/utils.lua +++ b/lib/resty/session/utils.lua @@ -860,16 +860,80 @@ end local config_fingerprint do - local cjson + local type = type + local sort = table.sort + local concat = table.concat + + -- Appends a canonical form of the value to parts: tables are written with + -- their keys sorted, so equal tables always give equal text. Values that + -- cannot be part of a setting (functions, userdata, threads) are left out. + -- Returns false when the table refers to itself. + local function canonical(value, parts, seen) + local value_type = type(value) + if value_type == "string" then + parts[#parts + 1] = fmt("s%d:%s", #value, value) + + elseif value_type == "number" then + parts[#parts + 1] = fmt("n%.17g", value) + + elseif value_type == "boolean" then + parts[#parts + 1] = value and "t" or "f" + + elseif value_type == "table" then + if seen[value] then + return false + end + + seen[value] = true + + local keys = {} + for key, item in pairs(value) do + local key_type = type(key) + local item_type = type(item) + if (key_type == "string" or key_type == "number") + and (item_type == "string" or item_type == "number" + or item_type == "boolean" or item_type == "table") + then + keys[#keys + 1] = key + end + end + + -- numbers before strings, each in their own order + sort(keys, function(a, b) + local a_type, b_type = type(a), type(b) + if a_type ~= b_type then + return a_type == "number" + end + + return a < b + end) + + parts[#parts + 1] = "{" + for _, key in ipairs(keys) do + canonical(key, parts, seen) + parts[#parts + 1] = "=" + if not canonical(value[key], parts, seen) then + return false + end + + parts[#parts + 1] = "," + end + + parts[#parts + 1] = "}" + seen[value] = nil + end + + return true + end --- -- Fingerprint of a configuration table. -- - -- The table is encoded as JSON with sorted keys and hashed, so equal settings - -- give the same fingerprint whichever table they come from, and credentials - -- are not kept in it. Values that cannot be encoded, such as functions and - -- userdata, are left out, at any depth. Returns `nil` and an error when the - -- table cannot be encoded at all, for example when it refers to itself. + -- The table is written in a canonical form, with sorted keys, and hashed, so + -- equal settings give the same fingerprint whichever table they come from, and + -- credentials are not kept in it. Values that cannot be part of a setting, such + -- as functions and userdata, are left out, at any depth. Returns `nil` and an + -- error when the table refers to itself. -- -- @function utils.config_fingerprint -- @tparam table configuration configuration table @@ -882,18 +946,12 @@ local config_fingerprint do -- port = 6379, -- }) config_fingerprint = function(configuration) - if not cjson then - cjson = require("cjson.safe").new() - cjson.encode_sort_keys(true) - cjson.encode_skip_unsupported_value_types(true) - end - - local encoded, err = cjson.encode(configuration) - if not encoded then - return nil, err + local parts = {} + if not canonical(configuration, parts, {}) then + return nil, "configuration refers to itself" end - return encode_base64url(assert(sha256(encoded))) + return encode_base64url(assert(sha256(concat(parts)))) end end diff --git a/spec/01-utils_spec.lua b/spec/01-utils_spec.lua index 95cb53c7..7f593a1f 100644 --- a/spec/01-utils_spec.lua +++ b/spec/01-utils_spec.lua @@ -136,6 +136,50 @@ describe("Testing utils", function() end end) end) + describe("config_fingerprint", function() + local config_fingerprint = utils.config_fingerprint + + it("gives equal settings the same fingerprint, whichever table they come from", function() + local one = config_fingerprint({ host = "127.0.0.1", port = 6379, nodes = { { ip = "a" }, { ip = "b" } } }) + local two = config_fingerprint({ nodes = { { ip = "a" }, { ip = "b" } }, port = 6379, host = "127.0.0.1" }) + + assert.is_string(one) + assert.equal(one, two) + end) + + it("tells different settings apart", function() + local base = config_fingerprint({ host = "127.0.0.1", port = 6379 }) + + assert.not_equal(base, config_fingerprint({ host = "127.0.0.1", port = 6380 })) + assert.not_equal(base, config_fingerprint({ host = "127.0.0.2", port = 6379 })) + assert.not_equal(base, config_fingerprint({ host = "127.0.0.1", port = "6379" })) + assert.not_equal(base, config_fingerprint({ host = "127.0.0.1", port = 6379, ssl = false })) + assert.not_equal(config_fingerprint({ list = { "a", "b" } }), config_fingerprint({ list = { "b", "a" } })) + -- a value cannot be moved from one key to the next + assert.not_equal(config_fingerprint({ a = "bc" }), config_fingerprint({ ab = "c" })) + end) + + it("leaves out values that are not settings, at any depth", function() + local plain = config_fingerprint({ host = "127.0.0.1", nested = { port = 6379 } }) + local with_values = config_fingerprint({ + host = "127.0.0.1", + get = function() end, + nested = { port = 6379, set = function() end }, + }) + + assert.equal(plain, with_values) + end) + + it("returns an error for a table that refers to itself", function() + local configuration = { host = "127.0.0.1" } + configuration.self = configuration + + local fingerprint, err = config_fingerprint(configuration) + assert.is_nil(fingerprint) + assert.is_string(err) + end) + end) + describe("load_storage", function() -- "dshm" is disabled as it currently cannot be checked by CI for _, strategy in ipairs({ "memcached", "mysql", "postgres", "redis" }) do From a64d6b385c89bb5575d68745ede427eb7918de0a Mon Sep 17 00:00:00 2001 From: Hockenba <60619916+Hockenba@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:26:14 -0500 Subject: [PATCH 05/13] fix(revocation): retry a logout across several audiences A cookie is rejected on open once the lineage mark of its audience is stored. With several audiences that mark could be stored before a failing write of another audience, and the retry then stopped at open() with the other lineage still valid. Write the lineage of the audience in use last. --- README.md | 6 +-- lib/resty/session.lua | 17 +++++++- spec/06-revocation-1_spec.lua | 76 +++++++++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f3fc4c95..31657cde 100644 --- a/README.md +++ b/README.md @@ -419,9 +419,9 @@ rolling window plus `stale_ttl`, capped by the absolute timeout (the `remember_* windows when a remember cookie is used). Cookies issued before the lineage id existed are revoked by their own session id only. Each cache miss costs one more lookup, and each destroy writes one more mark; `revocation_fail_mode` applies to -both. The lineage mark is written before the session id mark, so a failed -logout can be retried: if only the second write fails, every cookie of the login is -already revoked. +both. The lineage marks are written before the session id mark, and the one of the +audience in use last, so a failed logout can be retried: the session still opens +until its own mark is stored, and by then every other mark is already written. Use `revocation_fail_mode` to control behavior when the storage is unavailable: diff --git a/lib/resty/session.lua b/lib/resty/session.lua index fb20ac5e..36cbcf29 100644 --- a/lib/resty/session.lua +++ b/lib/resty/session.lua @@ -603,10 +603,21 @@ local function mark_session_revoked(self, remember, meta) end --- The lineage ids of the audiences in the session, without duplicates. +-- The lineage ids of the audiences in the session, without duplicates, and with +-- the one of the audience in use last. A cookie is rejected on open as soon as the +-- mark of that audience is stored, so it has to be the last mark written: when a +-- write fails, the retry of the logout still opens the session and writes the +-- marks again, instead of stopping at a cookie that is already revoked while the +-- lineages of the other audiences are not. local function get_lineages(self) local lineages = {} local seen = {} + local current = self.data[self.data_index] + current = current and current[4] + if current then + seen[current] = true + end + for i = 1, #self.data do local lineage = self.data[i][4] if lineage and not seen[lineage] then @@ -615,6 +626,10 @@ local function get_lineages(self) end end + if current then + lineages[#lineages + 1] = current + end + return lineages end diff --git a/spec/06-revocation-1_spec.lua b/spec/06-revocation-1_spec.lua index 25d3e837..0ee82a00 100644 --- a/spec/06-revocation-1_spec.lua +++ b/spec/06-revocation-1_spec.lua @@ -656,6 +656,8 @@ describe("session: revocation lineage", function() local ttls local fail_lineage_writes local fail_sid_writes + local fail_lineage_write_number + local lineage_writes local store = { get = function(_, _, key) @@ -666,6 +668,12 @@ describe("session: revocation lineage", function() if (fail_lineage_writes and value ~= "1") or (fail_sid_writes and value == "1") then return nil, "connection refused" end + if value ~= "1" then + lineage_writes = lineage_writes + 1 + if lineage_writes == fail_lineage_write_number then + return nil, "connection refused" + end + end marks[key] = value ttls[key] = ttl return true @@ -677,6 +685,8 @@ describe("session: revocation lineage", function() ttls = {} fail_lineage_writes = false fail_sid_writes = false + fail_lineage_write_number = nil + lineage_writes = 0 session.init({ cookie_name = cookie_name, storage = "cookie", @@ -880,6 +890,72 @@ describe("session: revocation lineage", function() end end) + it("can retry a logout that failed after the first of the lineage marks of several audiences", function() + initialize("closed") + + local function open_audience(cookie, audience) + session.__set_ngx_var({ + ["cookie_" .. cookie_name] = cookie, + }) + local s = session.new({ audience = audience }) + local ok, err = s:open() + return s, ok, err + end + + -- one cookie with two audiences, each with a lineage of its own + local cookies = {} + session.__set_ngx_header(cookies) + local first = session.new({ audience = "aud-a" }) + first:set("test_key", "test_data") + assert.is_true(first:save()) + local cookie = extract_cookie(cookie_name, cookies["Set-Cookie"]) + + local second, _, err = open_audience(cookie, "aud-b") + assert.equals("missing session audience", err) + cookies = {} + session.__set_ngx_header(cookies) + second:set("test_key", "test_data") + assert.is_true(second:save()) + cookie = extract_cookie(cookie_name, cookies["Set-Cookie"]) + + local current, ok = open_audience(cookie, "aud-a") + assert.is_true(ok) + local lineages = {} + for _, entry in ipairs(current.data) do + assert.is_string(entry[4]) + lineages[entry[4]] = true + end + assert.equals(2, #current.data) + assert.is_true(lineages[current.data[1][4]] and lineages[current.data[2][4]] and + current.data[1][4] ~= current.data[2][4]) + current:close() + + -- the second lineage mark cannot be written + fail_lineage_write_number = 2 + local logging_out, opened = open_audience(cookie, "aud-a") + assert.is_true(opened) + session.__set_ngx_header({}) + local destroyed, destroy_err = logging_out:destroy() + assert.is_nil(destroyed) + assert.matches("unable to mark session revoked", destroy_err) + + -- the store works again, and a new request retries with the original cookie: + -- the session still opens, because the mark of its audience is the last one + fail_lineage_write_number = nil + local retry, retry_opened, retry_err = open_audience(cookie, "aud-a") + assert.is_true(retry_opened) + assert.is_nil(retry_err) + session.__set_ngx_header({}) + assert.is_true(retry:destroy()) + + for _, audience in ipairs({ "aud-a", "aud-b" }) do + local rejected, rejected_ok, rejected_err = open_audience(cookie, audience) + assert.is_falsy(rejected_ok) + assert.equals("session revoked", rejected_err) + rejected:close() + end + end) + it("does not add a lineage id when revocation is disabled", function() session.init({ cookie_name = cookie_name, From 3db128bbffe057a6c0345d9b16268e1376099b7e Mon Sep 17 00:00:00 2001 From: Hockenba <60619916+Hockenba@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:42:51 -0500 Subject: [PATCH 06/13] fix(utils): fingerprint a configuration with cjson again Use cjson for the fingerprint, as encode_json and decode_json do, instead of a second serializer. It needs a cjson build with encode_sort_keys and encode_skip_unsupported_value_types, which the README now says. --- README.md | 3 +- lib/resty/session/utils.lua | 90 +++++++------------------------------ 2 files changed, 18 insertions(+), 75 deletions(-) diff --git a/README.md b/README.md index 31657cde..fc0abb0e 100644 --- a/README.md +++ b/README.md @@ -401,7 +401,8 @@ A storage is identified by its settings, whether it is given by name different tables, and different settings never do. Functions and other values that JSON cannot encode are left out of the settings, so a custom storage table needs a plain field, such as a name, that tells it apart from other custom -storages. A revocation updates the local worker cache at once. Other workers see it when their cached lookup +storages. The settings are encoded with cjson, so this needs a cjson build with +`encode_sort_keys` and `encode_skip_unsupported_value_types`. A revocation updates the local worker cache at once. Other workers see it when their cached lookup expires; set `revocation_cache_ttl = 0` to check the store on every request. The marks live only in the revocation storage. If it loses its data, for example diff --git a/lib/resty/session/utils.lua b/lib/resty/session/utils.lua index 354af86f..64714e91 100644 --- a/lib/resty/session/utils.lua +++ b/lib/resty/session/utils.lua @@ -860,80 +860,16 @@ end local config_fingerprint do - local type = type - local sort = table.sort - local concat = table.concat - - -- Appends a canonical form of the value to parts: tables are written with - -- their keys sorted, so equal tables always give equal text. Values that - -- cannot be part of a setting (functions, userdata, threads) are left out. - -- Returns false when the table refers to itself. - local function canonical(value, parts, seen) - local value_type = type(value) - if value_type == "string" then - parts[#parts + 1] = fmt("s%d:%s", #value, value) - - elseif value_type == "number" then - parts[#parts + 1] = fmt("n%.17g", value) - - elseif value_type == "boolean" then - parts[#parts + 1] = value and "t" or "f" - - elseif value_type == "table" then - if seen[value] then - return false - end - - seen[value] = true - - local keys = {} - for key, item in pairs(value) do - local key_type = type(key) - local item_type = type(item) - if (key_type == "string" or key_type == "number") - and (item_type == "string" or item_type == "number" - or item_type == "boolean" or item_type == "table") - then - keys[#keys + 1] = key - end - end - - -- numbers before strings, each in their own order - sort(keys, function(a, b) - local a_type, b_type = type(a), type(b) - if a_type ~= b_type then - return a_type == "number" - end - - return a < b - end) - - parts[#parts + 1] = "{" - for _, key in ipairs(keys) do - canonical(key, parts, seen) - parts[#parts + 1] = "=" - if not canonical(value[key], parts, seen) then - return false - end - - parts[#parts + 1] = "," - end - - parts[#parts + 1] = "}" - seen[value] = nil - end - - return true - end + local cjson --- -- Fingerprint of a configuration table. -- - -- The table is written in a canonical form, with sorted keys, and hashed, so - -- equal settings give the same fingerprint whichever table they come from, and - -- credentials are not kept in it. Values that cannot be part of a setting, such - -- as functions and userdata, are left out, at any depth. Returns `nil` and an - -- error when the table refers to itself. + -- The table is encoded as JSON with sorted keys and hashed, so equal settings + -- give the same fingerprint whichever table they come from, and credentials + -- are not kept in it. Values that cannot be encoded, such as functions and + -- userdata, are left out, at any depth. Returns `nil` and an error when the + -- table cannot be encoded at all, for example when it refers to itself. -- -- @function utils.config_fingerprint -- @tparam table configuration configuration table @@ -946,12 +882,18 @@ local config_fingerprint do -- port = 6379, -- }) config_fingerprint = function(configuration) - local parts = {} - if not canonical(configuration, parts, {}) then - return nil, "configuration refers to itself" + if not cjson then + cjson = require("cjson.safe").new() + cjson.encode_sort_keys(true) + cjson.encode_skip_unsupported_value_types(true) + end + + local encoded, err = cjson.encode(configuration) + if not encoded then + return nil, err end - return encode_base64url(assert(sha256(concat(parts)))) + return encode_base64url(assert(sha256(encoded))) end end From 83d192297db633780cc4e6adcb4169d7e9353754 Mon Sep 17 00:00:00 2001 From: Hockenba <60619916+Hockenba@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:09:00 -0500 Subject: [PATCH 07/13] chore(ci): test on OpenResty 1.31.9.1 The fingerprint of a revocation storage uses the encode_sort_keys option of cjson, which the cjson of OpenResty has from 1.31.8.1. Build the test image on 1.31.9.1 and say in the README which OpenResty has the option. --- README.md | 3 ++- dev/Dockerfile | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fc0abb0e..d29a5db3 100644 --- a/README.md +++ b/README.md @@ -402,7 +402,8 @@ different tables, and different settings never do. Functions and other values that JSON cannot encode are left out of the settings, so a custom storage table needs a plain field, such as a name, that tells it apart from other custom storages. The settings are encoded with cjson, so this needs a cjson build with -`encode_sort_keys` and `encode_skip_unsupported_value_types`. A revocation updates the local worker cache at once. Other workers see it when their cached lookup +`encode_sort_keys` and `encode_skip_unsupported_value_types`, for example the one in +OpenResty 1.31.8.1 or later. A revocation updates the local worker cache at once. Other workers see it when their cached lookup expires; set `revocation_cache_ttl = 0` to check the store on every request. The marks live only in the revocation storage. If it loses its data, for example diff --git a/dev/Dockerfile b/dev/Dockerfile index c40cc39b..3e8721f4 100644 --- a/dev/Dockerfile +++ b/dev/Dockerfile @@ -1,4 +1,4 @@ -FROM openresty/openresty:1.27.1.2-0-noble +FROM openresty/openresty:1.31.9.1-0-noble ENV DEBIAN_FRONTEND noninteractive ENV TEST_NGINX_BINARY openresty From 80bcf4b383d473ed3fdb3f5a8caecf90e8c56b85 Mon Sep 17 00:00:00 2001 From: Hockenba <60619916+Hockenba@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:26:47 -0500 Subject: [PATCH 08/13] refactor(revocation): name the lineage helpers like the rest, fail clearly without the cjson options Name the helpers like the functions next to them: mark_lineages_revoked like mark_session_revoked, and get_revocation_cache_size and get_lineage_revocation_key like the other getters. Raise an error that says what is missing when cjson has no encode_sort_keys or encode_skip_unsupported_value_types, and only identify the revocation storage of sessions that use it, so sessions with server-side storage are not affected. --- README.md | 2 +- lib/resty/session.lua | 45 +++++++++++++++++++------------------ lib/resty/session/utils.lua | 16 ++++++++++--- spec/01-utils_spec.lua | 22 ++++++++++++++++++ 4 files changed, 59 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index d29a5db3..e0319682 100644 --- a/README.md +++ b/README.md @@ -403,7 +403,7 @@ that JSON cannot encode are left out of the settings, so a custom storage table needs a plain field, such as a name, that tells it apart from other custom storages. The settings are encoded with cjson, so this needs a cjson build with `encode_sort_keys` and `encode_skip_unsupported_value_types`, for example the one in -OpenResty 1.31.8.1 or later. A revocation updates the local worker cache at once. Other workers see it when their cached lookup +OpenResty 1.31.8.1 or later. Without them, configuring revocation raises an error. A revocation updates the local worker cache at once. Other workers see it when their cached lookup expires; set `revocation_cache_ttl = 0` to check the store on every request. The marks live only in the revocation storage. If it loses its data, for example diff --git a/lib/resty/session.lua b/lib/resty/session.lua index 36cbcf29..2e9d44f4 100644 --- a/lib/resty/session.lua +++ b/lib/resty/session.lua @@ -386,7 +386,7 @@ local REVOCATION_ERROR_CACHE -- session options. Each is read once per worker, when it is created, from an -- nginx variable, 1024 when it is not set. Define it where every request sees -- it, for example with a `map` in the http block. -local function revocation_cache_size(name) +local function get_revocation_cache_size(name) local size = DEFAULT_REVOCATION_CACHE_SIZE -- nginx variables are not available in every context, for example in timers local ok, configured = pcall(function() return var[name] end) @@ -540,7 +540,7 @@ end -- A lineage id is generated when a session is first saved and travels in the -- encrypted payload through every rotation of the session id, so one logout -- can revoke every cookie descended from the same login. -local function lineage_revocation_key(lineage) +local function get_lineage_revocation_key(lineage) return "lineage:" .. lineage end @@ -648,9 +648,9 @@ local function get_lineage_ttl(self, current_time, creation_time) end --- Revoke every cookie of the lineages of the session, so that a logout also --- rejects the cookies that were rotated from the one the client presented. -local function revoke_lineages(self, meta) +-- Mark the lineages of the session revoked, so that a logout also rejects the +-- cookies that were rotated from the one the client presented. +local function mark_lineages_revoked(self, meta) local revocation = self.revocation if self.storage or not revocation or not meta or not meta.sid or not meta.creation_time then return true @@ -659,7 +659,7 @@ local function revoke_lineages(self, meta) for _, lineage in ipairs(get_lineages(self)) do local current_time = time() local ttl = get_lineage_ttl(self, current_time, meta.creation_time) - local key, herr = self.hash_storage_key(lineage_revocation_key(lineage)) + local key, herr = self.hash_storage_key(get_lineage_revocation_key(lineage)) if not key then return nil, herr end @@ -1198,7 +1198,7 @@ local function open(self, remember, meta_only) if remember or i == audience_index then local revoked, err = false, nil if data[i][4] then - revoked, err = is_revoked(self, lineage_revocation_key(data[i][4]), self.cookie_name, current_time, creation_time) + revoked, err = is_revoked(self, get_lineage_revocation_key(data[i][4]), self.cookie_name, current_time, creation_time) end if err then return nil, err @@ -1631,10 +1631,10 @@ local function destroy(self, remember, already_revoked) local storage = self.storage if not already_revoked then - -- The lineage mark goes first: it rejects every cookie of the login, so a - -- failure between the two writes cannot leave a cookie that the retry of the + -- The lineage marks go first: they reject every cookie of the login, so a + -- failure between the writes cannot leave a cookie that the retry of the -- logout (which sees the session id mark and does not destroy) would miss. - local ok, err = revoke_lineages(self, meta) + local ok, err = mark_lineages_revoked(self, meta) if not ok then return nil, err end @@ -2550,8 +2550,8 @@ function metatable:destroy() end if remembered then - -- the lineage first, as in destroy - local ok, err = revoke_lineages(self, self.meta) + -- the lineage marks first, as in destroy + local ok, err = mark_lineages_revoked(self, self.meta) if not ok then return nil, err end @@ -2936,7 +2936,7 @@ function session.init(configuration) DEFAULT_RESPONSE_HEADERS = opt(configuration, "response_headers") DEFAULT_STORAGE = opt(configuration, "storage") DEFAULT_REVOCATION = opt(configuration, "revocation") - DEFAULT_REVOCATION_ID = configuration and get_revocation_id(configuration.revocation, configuration) + DEFAULT_REVOCATION_ID = configuration and not DEFAULT_STORAGE and get_revocation_id(configuration.revocation, configuration) or nil DEFAULT_REVOCATION_FAIL_MODE = opt(configuration, "revocation_fail_mode", "open") DEFAULT_REVOCATION_CACHE_TTL = opt(configuration, "revocation_cache_ttl", 5) DEFAULT_REVOCATION_ERROR_CACHE_TTL = opt(configuration, "revocation_error_cache_ttl", 5) @@ -2998,6 +2998,14 @@ function session.new(configuration) local response_headers = opt(configuration, "response_headers", DEFAULT_RESPONSE_HEADERS) local storage = opt(configuration, "storage", DEFAULT_STORAGE) local revocation = opt(configuration, "revocation", DEFAULT_REVOCATION) + local revocation_fail_mode = opt(configuration, "revocation_fail_mode", DEFAULT_REVOCATION_FAIL_MODE) + local revocation_cache_ttl = opt(configuration, "revocation_cache_ttl", DEFAULT_REVOCATION_CACHE_TTL) + local revocation_error_cache_ttl = opt(configuration, "revocation_error_cache_ttl", DEFAULT_REVOCATION_ERROR_CACHE_TTL) + + if storage then + revocation = nil + end + local revocation_id if revocation then local raw = configuration and configuration.revocation @@ -3008,13 +3016,6 @@ function session.new(configuration) revocation_id = get_revocation_id(raw, configuration) end end - local revocation_fail_mode = opt(configuration, "revocation_fail_mode", DEFAULT_REVOCATION_FAIL_MODE) - local revocation_cache_ttl = opt(configuration, "revocation_cache_ttl", DEFAULT_REVOCATION_CACHE_TTL) - local revocation_error_cache_ttl = opt(configuration, "revocation_error_cache_ttl", DEFAULT_REVOCATION_ERROR_CACHE_TTL) - - if storage then - revocation = nil - end if cookie_prefix == "__Host-" then cookie_name = cookie_prefix .. cookie_name @@ -3068,8 +3069,8 @@ function session.new(configuration) local cookie_flags = FLAGS_BUFFER:get() if REVOCATION_CACHE == nil and revocation and (revocation_cache_ttl > 0 or revocation_error_cache_ttl > 0) then - REVOCATION_CACHE = assert(require("resty.lrucache").new(revocation_cache_size("session_revocation_cache_size"))) - REVOCATION_ERROR_CACHE = assert(require("resty.lrucache").new(revocation_cache_size("session_revocation_error_cache_size"))) + REVOCATION_CACHE = assert(require("resty.lrucache").new(get_revocation_cache_size("session_revocation_cache_size"))) + REVOCATION_ERROR_CACHE = assert(require("resty.lrucache").new(get_revocation_cache_size("session_revocation_error_cache_size"))) end local self = setmetatable({ diff --git a/lib/resty/session/utils.lua b/lib/resty/session/utils.lua index 64714e91..76118892 100644 --- a/lib/resty/session/utils.lua +++ b/lib/resty/session/utils.lua @@ -871,6 +871,10 @@ local config_fingerprint do -- userdata, are left out, at any depth. Returns `nil` and an error when the -- table cannot be encoded at all, for example when it refers to itself. -- + -- It needs a cjson with `encode_sort_keys` and + -- `encode_skip_unsupported_value_types`, as in OpenResty 1.31.8.1 or later, and + -- raises an error without them. + -- -- @function utils.config_fingerprint -- @tparam table configuration configuration table -- @treturn string|nil fingerprint @@ -883,9 +887,15 @@ local config_fingerprint do -- }) config_fingerprint = function(configuration) if not cjson then - cjson = require("cjson.safe").new() - cjson.encode_sort_keys(true) - cjson.encode_skip_unsupported_value_types(true) + local instance = require("cjson.safe").new() + if not instance.encode_sort_keys or not instance.encode_skip_unsupported_value_types then + error("cjson has no encode_sort_keys or encode_skip_unsupported_value_types, " + .. "which session revocation needs (OpenResty 1.31.8.1 or later has them)", 2) + end + + instance.encode_sort_keys(true) + instance.encode_skip_unsupported_value_types(true) + cjson = instance end local encoded, err = cjson.encode(configuration) diff --git a/spec/01-utils_spec.lua b/spec/01-utils_spec.lua index 7f593a1f..b982e4a6 100644 --- a/spec/01-utils_spec.lua +++ b/spec/01-utils_spec.lua @@ -170,6 +170,28 @@ describe("Testing utils", function() assert.equal(plain, with_values) end) + it("raises an error when cjson cannot sort keys", function() + local utils_module = package.loaded["resty.session.utils"] + local cjson_module = package.loaded["cjson.safe"] + finally(function() + package.loaded["resty.session.utils"] = utils_module + package.loaded["cjson.safe"] = cjson_module + end) + + -- a cjson without encode_sort_keys, as in older OpenResty releases + package.loaded["cjson.safe"] = { + new = function() + return { encode = function() return "{}" end } + end, + } + package.loaded["resty.session.utils"] = nil + local fresh = require("resty.session.utils") + + local ok, err = pcall(fresh.config_fingerprint, { host = "127.0.0.1" }) + assert.is_false(ok) + assert.matches("encode_sort_keys", err, 1, true) + end) + it("returns an error for a table that refers to itself", function() local configuration = { host = "127.0.0.1" } configuration.self = configuration From 7a9d0d1a522af8f4fc388179434e5a6a354e16a8 Mon Sep 17 00:00:00 2001 From: Hockenba <60619916+Hockenba@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:40:31 -0500 Subject: [PATCH 09/13] fix(revocation): plain lineage marks, check every lineage of a cookie opened for another audience, write each mark once A lineage belongs to one login, so a lineage mark rejects its cookies without comparing times, as the session id mark does; the comparison let clock skew between nodes keep the rotated cookies valid. A cookie opened for an audience it does not have is checked against all its lineages, so saving it for the new audience cannot carry a logged-out login on. A remember-cookie logout writes the lineage marks once. A storage named by an alias that load_storage accepts is identified by the same settings it reads. --- README.md | 36 ++++++++------- lib/resty/session.lua | 83 ++++++++++++++++++++--------------- spec/06-revocation-1_spec.lua | 43 ++++++++++++++---- 3 files changed, 101 insertions(+), 61 deletions(-) diff --git a/README.md b/README.md index e0319682..7df59369 100644 --- a/README.md +++ b/README.md @@ -391,20 +391,22 @@ TTL equal to the remaining session lifetime (rolling and absolute timeouts), and the local cache is updated immediately. When the write fails, the failure is cached for the same identifier under `revocation_error_cache_ttl`, so the next lookup sees it instead of the store. The revocation mark is a lightweight -sentinel; no session payload is stored. The lineage mark is written without a -lookup, so a remember-cookie logout may write it twice. - -Lineage lookups cache the timestamp of the mark, which is compared with each -session's creation time. Cache entries are isolated by revocation storage. -A storage is identified by its settings, whether it is given by name -(`"redis"`) or as a table: equal settings share cache entries, even from -different tables, and different settings never do. Functions and other values -that JSON cannot encode are left out of the settings, so a custom storage table -needs a plain field, such as a name, that tells it apart from other custom -storages. The settings are encoded with cjson, so this needs a cjson build with -`encode_sort_keys` and `encode_skip_unsupported_value_types`, for example the one in -OpenResty 1.31.8.1 or later. Without them, configuring revocation raises an error. A revocation updates the local worker cache at once. Other workers see it when their cached lookup -expires; set `revocation_cache_ttl = 0` to check the store on every request. +sentinel; no session payload is stored. Lineage marks are written without a +lookup. + +Cache entries are isolated by revocation storage. A storage is identified by its +settings, whether it is given by name (`"redis"`) or as a table: equal settings +share cache entries, even from different tables, and different settings never +do. Functions and other values that JSON cannot encode are left out of the +settings, so a custom storage table needs a plain field, such as a name, that +tells it apart from other custom storages. The settings are encoded with cjson, +so this needs a cjson build with `encode_sort_keys` and +`encode_skip_unsupported_value_types`, for example the one in OpenResty 1.31.8.1 +or later. Without them, configuring revocation raises an error. + +A revocation updates the local worker cache at once. Other workers see it when +their cached lookup expires; set `revocation_cache_ttl = 0` to check the store on +every request. The marks live only in the revocation storage. If it loses its data, for example Redis restarted without persistence, revoked cookies are accepted again until @@ -418,8 +420,10 @@ rotation. `session:destroy` revokes the lineage along with the session id, so every cookie of that login is rejected, whether it was issued before or after the logout. A new login starts a new lineage. The mark is kept for a full rolling window plus `stale_ttl`, capped by the absolute timeout (the `remember_*` -windows when a remember cookie is used). Cookies issued before the lineage id -existed are revoked by their own session id only. Each cache miss costs one more +windows when a remember cookie is used). A remember cookie, or a cookie opened for +an audience it does not have, is checked against the lineages of all its +audiences. Cookies issued before the lineage id existed are revoked by their own +session id only. Each cache miss costs one more lookup, and each destroy writes one more mark; `revocation_fail_mode` applies to both. The lineage marks are written before the session id mark, and the one of the audience in use last, so a failed logout can be retried: the session still opens diff --git a/lib/resty/session.lua b/lib/resty/session.lua index 2e9d44f4..086ee432 100644 --- a/lib/resty/session.lua +++ b/lib/resty/session.lua @@ -402,6 +402,18 @@ local function get_revocation_cache_size(name) end +-- Storages that load_storage accepts under two names. Whichever is given, it +-- reads the settings of the first name, or else of the second. +local REVOCATION_STORAGE_NAMES = { + memcached = { "memcached", "memcache" }, + memcache = { "memcached", "memcache" }, + mysql = { "mysql", "mariadb" }, + mariadb = { "mysql", "mariadb" }, + postgres = { "postgres", "postgresql" }, + postgresql = { "postgres", "postgresql" }, +} + + -- A storage is identified by its settings, not by the table that holds them: a -- storage given by name is created again by every session.new, and the same -- settings can come from different tables. Equal settings share cache entries, @@ -409,8 +421,15 @@ end local function get_revocation_id(revocation, configuration) local name, settings if type(revocation) == "string" then - name = revocation - settings = configuration and configuration[revocation] + local names = REVOCATION_STORAGE_NAMES[revocation] + if names then + name = names[1] + settings = configuration and (configuration[names[1]] or configuration[names[2]]) + + else + name = revocation + settings = configuration and configuration[revocation] + end elseif type(revocation) == "table" then name = "table" @@ -443,7 +462,7 @@ end local function revocation_cache_get(self, cookie_name, key) local cache_key = get_revocation_cache_key(self, cookie_name, key) local value = REVOCATION_CACHE:get(cache_key) - if value == true or value == false or type(value) == "number" then + if value == true or value == false then return value end @@ -481,7 +500,7 @@ local function handle_revocation_error(self, err, msg) end -local function is_revoked(self, key, cookie_name, current_time, creation_time) +local function is_revoked(self, key, cookie_name, current_time) local revocation = self.revocation if not revocation then return false, nil @@ -503,10 +522,6 @@ local function is_revoked(self, key, cookie_name, current_time, creation_time) if value == true or value == false then return value end - - if type(value) == "number" then - return value >= creation_time, nil - end end local data, err = revocation:get(cookie_name, storage_key, current_time) @@ -527,13 +542,12 @@ local function is_revoked(self, key, cookie_name, current_time, creation_time) return false, nil end - local revoked_at = tonumber(data) - local cached = data == REVOCATION_MARK or revoked_at or false + local revoked = data == REVOCATION_MARK if cache_ttl > 0 then - revocation_cache_set(self, cookie_name, storage_key, cached, cache_ttl) + revocation_cache_set(self, cookie_name, storage_key, revoked, cache_ttl) end - return cached == true or (revoked_at ~= nil and revoked_at >= creation_time), nil + return revoked, nil end @@ -567,7 +581,7 @@ local function mark_session_revoked(self, remember, meta) end local current_time = time() - local revoked, revocation_err = is_revoked(self, sid, cookie_name, current_time, meta.creation_time) + local revoked, revocation_err = is_revoked(self, sid, cookie_name, current_time) if revocation_err then return nil, revocation_err end @@ -664,7 +678,7 @@ local function mark_lineages_revoked(self, meta) return nil, herr end - local ok, err = revocation:set(self.cookie_name, key, tostring(current_time), ttl, current_time) + local ok, err = revocation:set(self.cookie_name, key, REVOCATION_MARK, ttl, current_time) if not ok then ok, err = handle_revocation_error(self, err, "unable to mark session revoked") if not ok then @@ -674,7 +688,7 @@ local function mark_lineages_revoked(self, meta) else local cache_ttl = self.revocation_cache_ttl if cache_ttl > 0 then - revocation_cache_set(self, self.cookie_name, key, current_time, min(cache_ttl, ttl)) + revocation_cache_set(self, self.cookie_name, key, true, min(cache_ttl, ttl)) end end end @@ -1026,7 +1040,7 @@ local function open(self, remember, meta_only) end end - local revoked, err = is_revoked(self, sid, cookie_name, current_time, creation_time) + local revoked, err = is_revoked(self, sid, cookie_name, current_time) if err then return nil, err end @@ -1193,12 +1207,15 @@ local function open(self, remember, meta_only) end end + -- A remember cookie, or a cookie without the audience, is checked for the + -- lineages of all its audiences: a cookie saved for a new audience would carry + -- them along, and with them a login that was logged out. if self.revocation then for i = 1, count do - if remember or i == audience_index then + if remember or not audience_index or i == audience_index then local revoked, err = false, nil if data[i][4] then - revoked, err = is_revoked(self, get_lineage_revocation_key(data[i][4]), self.cookie_name, current_time, creation_time) + revoked, err = is_revoked(self, get_lineage_revocation_key(data[i][4]), self.cookie_name, current_time) end if err then return nil, err @@ -1631,15 +1648,7 @@ local function destroy(self, remember, already_revoked) local storage = self.storage if not already_revoked then - -- The lineage marks go first: they reject every cookie of the login, so a - -- failure between the writes cannot leave a cookie that the retry of the - -- logout (which sees the session id mark and does not destroy) would miss. - local ok, err = mark_lineages_revoked(self, meta) - if not ok then - return nil, err - end - - ok, err = mark_session_revoked(self, remember, meta) + local ok, err = mark_session_revoked(self, remember, meta) if not ok then return nil, err end @@ -2542,27 +2551,29 @@ function metatable:destroy() return nil, "unable to destroy nonexistent session" end - -- The remember session is revoked before any cookie is cleared, so a store - -- failure leaves the browser with cookies that can still retry the logout. + -- The lineage marks go first: they reject every cookie of the login, so a + -- failure before the session id marks cannot leave a cookie that the retry of + -- the logout (which stops at a session id mark and does not destroy) would + -- miss. The remember session is revoked before any cookie is cleared, so a + -- store failure leaves the browser with cookies that can still retry. + local ok, err = mark_lineages_revoked(self, self.meta) + if not ok then + return nil, err + end + local remembered if get_remember(self) then remembered = self.remember_meta or open(self, true, true) end if remembered then - -- the lineage marks first, as in destroy - local ok, err = mark_lineages_revoked(self, self.meta) - if not ok then - return nil, err - end - ok, err = mark_session_revoked(self, true, self.remember_meta or {}) if not ok then return nil, err end end - local ok, err = destroy(self) + ok, err = destroy(self) if not ok then return nil, err end diff --git a/spec/06-revocation-1_spec.lua b/spec/06-revocation-1_spec.lua index 0ee82a00..0eba6656 100644 --- a/spec/06-revocation-1_spec.lua +++ b/spec/06-revocation-1_spec.lua @@ -17,6 +17,14 @@ local time = ngx.time local it = it +-- lineage marks are stored under the base64url of "lineage:", which always +-- starts like this, while a session id mark is the base64url of the session id +local LINEAGE_KEY_PREFIX = "bGluZWFnZT" +local function is_lineage_key(key) + return key:sub(1, #LINEAGE_KEY_PREFIX) == LINEAGE_KEY_PREFIX +end + + local storage_configs = { file = { suffix = "revocation", @@ -604,11 +612,10 @@ describe("session: revocation cache", function() get_count = get_count + 1 return nil end, - set = function(_, _, _, value) + set = function(_, _, key) set_count = set_count + 1 - -- the lineage mark is written first and succeeds; the session id mark - -- (which carries "1") fails - if value == "1" then + -- the lineage mark is written first and succeeds; the session id mark fails + if not is_lineage_key(key) then return nil, "connection refused" end return true @@ -664,11 +671,11 @@ describe("session: revocation lineage", function() return marks[key] end, set = function(_, _, key, value, ttl) - -- session id marks carry "1"; lineage marks carry the time they were written - if (fail_lineage_writes and value ~= "1") or (fail_sid_writes and value == "1") then + local lineage = is_lineage_key(key) + if (fail_lineage_writes and lineage) or (fail_sid_writes and not lineage) then return nil, "connection refused" end - if value ~= "1" then + if lineage then lineage_writes = lineage_writes + 1 if lineage_writes == fail_lineage_write_number then return nil, "connection refused" @@ -822,8 +829,8 @@ describe("session: revocation lineage", function() assert.is_true(ok) local lineage_ttl - for key, value in pairs(marks) do - if value ~= "1" then + for key in pairs(marks) do + if is_lineage_key(key) then lineage_ttl = ttls[key] end end @@ -956,6 +963,24 @@ describe("session: revocation lineage", function() end end) + it("rejects a logged out login when its cookie is opened for another audience", function() + initialize("closed") + + local original = login() + local rotated = rotate(original) + assert.is_true(destroy(original)) + + -- the rotated cookie has its own session id, so only the lineage tells it is + -- logged out; opening it for an audience it does not have must not carry it on + session.__set_ngx_var({ + ["cookie_" .. cookie_name] = rotated, + }) + local s = session.new({ audience = "another" }) + local ok, err = s:open() + assert.is_falsy(ok) + assert.equals("session revoked", err) + end) + it("does not add a lineage id when revocation is disabled", function() session.init({ cookie_name = cookie_name, From 55ad2550da8ef9ce3121a76e7cf5f9eb23a5da7c Mon Sep 17 00:00:00 2001 From: Hockenba <60619916+Hockenba@users.noreply.github.com> Date: Tue, 24 Nov 2026 14:52:15 -0500 Subject: [PATCH 10/13] test(revocation): a storage named by an alias has the identity of its settings --- spec/06-revocation-1_spec.lua | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/spec/06-revocation-1_spec.lua b/spec/06-revocation-1_spec.lua index 0eba6656..cf1b850a 100644 --- a/spec/06-revocation-1_spec.lua +++ b/spec/06-revocation-1_spec.lua @@ -1068,3 +1068,29 @@ describe("session: revocation cache with a named backend", function() assert.equals(4, gets) end) end) + + +describe("session: revocation storage aliases", function() + -- building a session does not connect to the storage, so no backend is needed + local function revocation_id(configuration) + configuration.storage = "cookie" + return session.new(configuration).revocation_id + end + + it("identifies a storage given by an alias by the settings load_storage reads", function() + -- load_storage reads the settings of the first name, or else of the second, + -- whichever of the two names is given + for _, names in ipairs({ { "memcached", "memcache" }, { "mysql", "mariadb" } }) do + local name, alias = names[1], names[2] + local one = { host = "127.0.0.1", port = 1 } + local other = { host = "127.0.0.1", port = 2 } + + local by_name = revocation_id({ revocation = name, [name] = one }) + assert.is_string(by_name) + assert.equals(by_name, revocation_id({ revocation = alias, [name] = one })) + assert.equals(by_name, revocation_id({ revocation = alias, [alias] = one })) + assert.equals(by_name, revocation_id({ revocation = name, [alias] = one })) + assert.not_equals(by_name, revocation_id({ revocation = alias, [alias] = other })) + end + end) +end) From 126b9d0f75d995bbf533375a75a4ac7c38eed96e Mon Sep 17 00:00:00 2001 From: Hockenba <60619916+Hockenba@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:03:07 -0500 Subject: [PATCH 11/13] refactor(revocation): shorter comments and README, name the lineage check in open() Move the lineage check of open() into is_lineage_revoked, name the vague locals, shorten the comments and the README revocation text, and keep the README wording of master where it still applies. --- README.md | 93 +++++++++++------------- lib/resty/session.lua | 139 +++++++++++++++++------------------- lib/resty/session/utils.lua | 15 ++-- 3 files changed, 116 insertions(+), 131 deletions(-) diff --git a/README.md b/README.md index 7df59369..da2799f0 100644 --- a/README.md +++ b/README.md @@ -330,8 +330,8 @@ Here are the possible session configuration options: | `storage` | `nil` | Storage is responsible of storing session data, use `nil` or `"cookie"` (data is stored in cookie), `"dshm"`, `"file"`, `"memcached"`, `"mysql"`, `"postgres"`, `"redis"`, or `"shm"`, or give a name of custom module (`"custom-storage"`), or a `table` that implements session storage interface. | | `revocation` | `nil` | Storage used for cookie session revocation records. Use `nil` or `false` to disable, a storage name such as `"shm"`, `"redis"`, `"mysql"`, or `"postgres"`, a custom storage module name, or a storage `table` with `set`/`get` methods. | | `revocation_fail_mode` | `"open"` | Behavior when the revocation store is unreachable, use `"open"` (treat as not revoked) or `"closed"` (reject the session). | -| `revocation_cache_ttl` | `5` | Worker-local cache TTL for successful revocation lookups (in seconds). Set to `0` to disable. This is the maximum stale window before a worker observes a revocation written elsewhere. | -| `revocation_error_cache_ttl` | `5` | Worker-local cache TTL for revocation store errors (in seconds). Set to `0` to disable. Errors are cached per `revocation_fail_mode`: `"open"` caches not-revoked and `"closed"` caches the error, and one is never replayed under the other. | +| `revocation_cache_ttl` | `5` | Worker-local cache TTL for successful revocation lookups (`true`/`false`) (in seconds). Set to `0` to disable. This is the maximum stale window before a worker observes a revocation written elsewhere. | +| `revocation_error_cache_ttl` | `5` | Worker-local cache TTL for revocation store errors (in seconds). Set to `0` to disable. `"open"` caches not-revoked; `"closed"` caches the error; each is kept apart. | | `dshm` | `nil` | Configuration for dshm storage, e.g. `{ prefix = "sessions" }` (see below) | | `file` | `nil` | Configuration for file storage, e.g. `{ path = "/tmp", suffix = "session" }` (see below) | | `memcached` | `nil` | Configuration for memcached storage, e.g. `{ prefix = "sessions" }` (see below) | @@ -370,12 +370,11 @@ seconds. Store unavailability is cached for `revocation_error_cache_ttl` seconds: `"open"` caches not-revoked, and `"closed"` caches the error, so a burst of requests does not retry the store on every lookup. -Successful lookups and store errors are cached separately in each worker, up to -1024 entries each. Size them with the nginx variables -`$session_revocation_cache_size` and `$session_revocation_error_cache_size`, -defined where every request sees them, for example with a `map` in the `http` -block. Each worker reads them once, on its first revocation lookup, so changing -them needs a reload. Invalid values are ignored with a warning. +Lookups and store errors are cached separately in each worker, up to 1024 +entries each. Change the sizes with the nginx variables +`$session_revocation_cache_size` and `$session_revocation_error_cache_size`, for +example with a `map` in the `http` block. Each worker reads them once, so a change +needs a reload; invalid values are ignored with a warning. ```nginx map $host $session_revocation_cache_size { @@ -384,9 +383,9 @@ map $host $session_revocation_cache_size { ``` `session:destroy` (including a last-audience `session:logout`) runs the same -cached lookup first for the session id. A cached `true` means it is already -revoked and no store write is made, and a cached error is returned without -contacting the store. Otherwise the identifier is written to the selected storage with a +cached lookup first. A cached `true` means the identifier is already revoked +and no store write is made, and a cached error is returned without contacting +the store. Otherwise the identifier is written to the selected storage with a TTL equal to the remaining session lifetime (rolling and absolute timeouts), and the local cache is updated immediately. When the write fails, the failure is cached for the same identifier under `revocation_error_cache_ttl`, so the @@ -394,40 +393,35 @@ next lookup sees it instead of the store. The revocation mark is a lightweight sentinel; no session payload is stored. Lineage marks are written without a lookup. -Cache entries are isolated by revocation storage. A storage is identified by its -settings, whether it is given by name (`"redis"`) or as a table: equal settings -share cache entries, even from different tables, and different settings never -do. Functions and other values that JSON cannot encode are left out of the -settings, so a custom storage table needs a plain field, such as a name, that -tells it apart from other custom storages. The settings are encoded with cjson, -so this needs a cjson build with `encode_sort_keys` and -`encode_skip_unsupported_value_types`, for example the one in OpenResty 1.31.8.1 -or later. Without them, configuring revocation raises an error. - -A revocation updates the local worker cache at once. Other workers see it when -their cached lookup expires; set `revocation_cache_ttl = 0` to check the store on -every request. - -The marks live only in the revocation storage. If it loses its data, for example -Redis restarted without persistence, revoked cookies are accepted again until -they expire. - -Every save of a cookie session gives it a new session id, so revoking only the id -being destroyed would leave other cookies of the same login usable, such as one +Cache entries are kept per revocation storage, identified by its settings: +equal settings share entries, different settings never do. Functions and other +values JSON cannot encode are left out, so a custom storage table needs a plain +field, such as a name, that tells it apart. The settings are encoded with cjson, +which needs `encode_sort_keys` and `encode_skip_unsupported_value_types` +(OpenResty 1.31.8.1 or later); without them, configuring revocation raises an +error. + +A revocation updates the local worker cache at once; other workers see it when +their cached lookup expires. Set `revocation_cache_ttl` and +`revocation_error_cache_ttl` to `0` to check the store on every request. The +marks live only in the revocation storage: if it loses its data, revoked cookies +are accepted again until they expire. + +Every save gives a cookie session a new session id, so revoking only the +destroyed id would leave the other cookies of the same login usable, such as one an attacker refreshed before the logout. With revocation enabled, a random -lineage id is generated on the first save and carried, encrypted, through every -rotation. `session:destroy` revokes the lineage along with the session id, so -every cookie of that login is rejected, whether it was issued before or after -the logout. A new login starts a new lineage. The mark is kept for a full -rolling window plus `stale_ttl`, capped by the absolute timeout (the `remember_*` -windows when a remember cookie is used). A remember cookie, or a cookie opened for -an audience it does not have, is checked against the lineages of all its -audiences. Cookies issued before the lineage id existed are revoked by their own -session id only. Each cache miss costs one more -lookup, and each destroy writes one more mark; `revocation_fail_mode` applies to -both. The lineage marks are written before the session id mark, and the one of the -audience in use last, so a failed logout can be retried: the session still opens -until its own mark is stored, and by then every other mark is already written. +lineage id is created on the first save and kept, encrypted, through every +rotation. `session:destroy` revokes it along with the session id, so every cookie +of that login is rejected; a new login starts a new lineage. The lineage mark is +kept for a full rolling window plus `stale_ttl`, capped by the absolute timeout +(the `remember_*` windows for a remember cookie). A remember cookie, or a cookie +opened for an audience it does not have, is checked against the lineages of all +its audiences. Cookies issued before lineage ids existed are revoked by their +own session id only. + +Lineage marks cost one more lookup on a cache miss and one more write per +audience on destroy. They are written before the session id mark, with the +audience in use last, so a failed logout can be retried. Use `revocation_fail_mode` to control behavior when the storage is unavailable: @@ -1048,12 +1042,11 @@ end Destroy the session and clear the cookies. In error case it returns `nil` and an error message, otherwise `true`. -With revocation enabled it also revokes the lineage of the session, so every -cookie of the same login is rejected (see [Session Revocation Configuration](#session-revocation-configuration)). -When a remember cookie is in use, the remember session is revoked first, and no -cookie is cleared until every revocation mark is written. With -`revocation_fail_mode` set to `"closed"`, a store failure therefore leaves the -cookies in place, and `session:destroy` can be called again. +With revocation enabled it also revokes the session's lineage, so every cookie +of the same login is rejected (see [Session Revocation Configuration](#session-revocation-configuration)). +No cookie is cleared until every revocation mark is written, so with +`revocation_fail_mode = "closed"` a store failure leaves the cookies in place and +`session:destroy` can be called again. ```lua local session, err, exists = require "resty.session".open() diff --git a/lib/resty/session.lua b/lib/resty/session.lua index 086ee432..28c51c9b 100644 --- a/lib/resty/session.lua +++ b/lib/resty/session.lua @@ -382,13 +382,11 @@ local REVOCATION_CACHE local REVOCATION_ERROR_CACHE --- The caches are shared by every session of a worker, so their sizes are not --- session options. Each is read once per worker, when it is created, from an --- nginx variable, 1024 when it is not set. Define it where every request sees --- it, for example with a `map` in the http block. +-- The caches are per worker, so their sizes come from nginx variables, read once +-- when the caches are created (default 1024). local function get_revocation_cache_size(name) local size = DEFAULT_REVOCATION_CACHE_SIZE - -- nginx variables are not available in every context, for example in timers + -- nginx variables are not available in every context, such as timers local ok, configured = pcall(function() return var[name] end) if ok and configured then size = tonumber(configured) @@ -402,8 +400,8 @@ local function get_revocation_cache_size(name) end --- Storages that load_storage accepts under two names. Whichever is given, it --- reads the settings of the first name, or else of the second. +-- Storages load_storage accepts under two names: it reads the settings of the +-- first name, or else of the second. local REVOCATION_STORAGE_NAMES = { memcached = { "memcached", "memcache" }, memcache = { "memcached", "memcache" }, @@ -414,10 +412,8 @@ local REVOCATION_STORAGE_NAMES = { } --- A storage is identified by its settings, not by the table that holds them: a --- storage given by name is created again by every session.new, and the same --- settings can come from different tables. Equal settings share cache entries, --- different settings never do. +-- A storage is identified by its settings, not by the table holding them, so +-- equal settings share cache entries and different settings never do. local function get_revocation_id(revocation, configuration) local name, settings if type(revocation) == "string" then @@ -455,10 +451,8 @@ local function get_revocation_cache_key(self, cookie_name, key) end --- Store errors are kept apart from the lookups, so that an outage cannot push --- the lookups out. An error is cached as `false` when the fail mode is open and --- as the message when closed, so it is kept per fail mode: one policy never --- sees the other's. +-- Store errors have their own cache, so an outage cannot evict the lookups, and +-- are kept per fail mode, so one policy never reads the other's result. local function revocation_cache_get(self, cookie_name, key) local cache_key = get_revocation_cache_key(self, cookie_name, key) local value = REVOCATION_CACHE:get(cache_key) @@ -551,14 +545,31 @@ local function is_revoked(self, key, cookie_name, current_time) end --- A lineage id is generated when a session is first saved and travels in the --- encrypted payload through every rotation of the session id, so one logout --- can revoke every cookie descended from the same login. +-- A lineage id is created on the first save and kept through every rotation of +-- the session id, so one logout can revoke every cookie of the same login. local function get_lineage_revocation_key(lineage) return "lineage:" .. lineage end +-- Whether the lineage of the audience in use is revoked. A remember cookie, or a +-- cookie without that audience, is checked for all its lineages, since a cookie +-- saved for another audience carries them along. +local function is_lineage_revoked(self, data, audience_index, remember, current_time) + for i = 1, #data do + local lineage = data[i][4] + if lineage and (remember or not audience_index or i == audience_index) then + local revoked, err = is_revoked(self, get_lineage_revocation_key(lineage), self.cookie_name, current_time) + if revoked or err then + return revoked, err + end + end + end + + return false, nil +end + + local function mark_session_revoked(self, remember, meta) if self.storage then return true @@ -617,19 +628,16 @@ local function mark_session_revoked(self, remember, meta) end --- The lineage ids of the audiences in the session, without duplicates, and with --- the one of the audience in use last. A cookie is rejected on open as soon as the --- mark of that audience is stored, so it has to be the last mark written: when a --- write fails, the retry of the logout still opens the session and writes the --- marks again, instead of stopping at a cookie that is already revoked while the --- lineages of the other audiences are not. +-- The lineage ids of the session's audiences, without duplicates, with the one of +-- the audience in use last: once its mark is stored the cookie no longer opens, +-- so writing it last lets a failed logout be retried. local function get_lineages(self) local lineages = {} local seen = {} - local current = self.data[self.data_index] - current = current and current[4] - if current then - seen[current] = true + local entry = self.data[self.data_index] + local current_lineage = entry and entry[4] + if current_lineage then + seen[current_lineage] = true end for i = 1, #self.data do @@ -640,18 +648,17 @@ local function get_lineages(self) end end - if current then - lineages[#lineages + 1] = current + if current_lineage then + lineages[#lineages + 1] = current_lineage end return lineages end --- How long a lineage mark is kept: a full rolling window from now, since a --- sibling cookie may have been saved just before the logout, plus the stale ttl --- for a request still running. The absolute timeout caps it, and a remember --- cookie uses the longer remember windows. +-- A full rolling window from now (a sibling cookie may have been saved just +-- before the logout) plus the stale ttl, capped by the absolute timeout; the +-- remember windows when a remember cookie is used. local function get_lineage_ttl(self, current_time, creation_time) local ttl = get_store_ttl(self, false, current_time, creation_time) if self.remember or self.remember_meta then @@ -662,8 +669,8 @@ local function get_lineage_ttl(self, current_time, creation_time) end --- Mark the lineages of the session revoked, so that a logout also rejects the --- cookies that were rotated from the one the client presented. +-- Marks the session's lineages revoked, so a logout also rejects the cookies +-- rotated from the presented one. local function mark_lineages_revoked(self, meta) local revocation = self.revocation if self.storage or not revocation or not meta or not meta.sid or not meta.creation_time then @@ -1190,11 +1197,11 @@ local function open(self, remember, meta_only) local audience_index local count = #data for i = 1, count do - -- With `decode_array_with_array_mt`, cjson encodes the entry up to its length, - -- and the holes cleared below would cut off the lineage id. + -- with `decode_array_with_array_mt`, the holes cleared below would cut off + -- the lineage id when the entry is encoded again setmetatable(data[i], nil) - -- cjson decodes the JSON null of a missing subject or lineage id as userdata + -- cjson decodes a missing subject or lineage id (JSON null) as userdata if type(data[i][3]) == "userdata" then data[i][3] = nil end @@ -1207,28 +1214,19 @@ local function open(self, remember, meta_only) end end - -- A remember cookie, or a cookie without the audience, is checked for the - -- lineages of all its audiences: a cookie saved for a new audience would carry - -- them along, and with them a login that was logged out. if self.revocation then - for i = 1, count do - if remember or not audience_index or i == audience_index then - local revoked, err = false, nil - if data[i][4] then - revoked, err = is_revoked(self, get_lineage_revocation_key(data[i][4]), self.cookie_name, current_time) - end - if err then - return nil, err - end - if revoked then - if remember then - self.remember_meta = {} - else - self.meta = DUMMY_META - end - return nil, "session revoked" - end + local revoked, err = is_lineage_revoked(self, data, audience_index, remember, current_time) + if err then + return nil, err + end + + if revoked then + if remember then + self.remember_meta = {} + else + self.meta = DUMMY_META end + return nil, "session revoked" end end @@ -1248,9 +1246,8 @@ local function open(self, remember, meta_only) end --- Give the audience the session is using a lineage id if it has none yet. It is --- generated once, on the first save, and every later save carries it along. It is --- the fourth field of the entry of the audience. +-- Gives the audience in use a lineage id (the fourth field of its entry) on the +-- first save; later saves carry it along. local function assign_lineage(self) local current = self.data[self.data_index] if current[4] then @@ -1323,9 +1320,9 @@ local function save(self, state, remember) local data, data_size, cookie_chunks do data = self.data if self.revocation and not storage then - local ok, lerr = assign_lineage(self) + local ok, lineage_err = assign_lineage(self) if not ok then - return nil, lerr + return nil, lineage_err end end @@ -2551,11 +2548,9 @@ function metatable:destroy() return nil, "unable to destroy nonexistent session" end - -- The lineage marks go first: they reject every cookie of the login, so a - -- failure before the session id marks cannot leave a cookie that the retry of - -- the logout (which stops at a session id mark and does not destroy) would - -- miss. The remember session is revoked before any cookie is cleared, so a - -- store failure leaves the browser with cookies that can still retry. + -- Lineage marks first: a retry of a failed logout stops at a stored session id + -- mark, so every lineage mark must be written before one. Cookies are cleared + -- only after all marks are written, so a store failure leaves them to retry. local ok, err = mark_lineages_revoked(self, self.meta) if not ok then return nil, err @@ -3019,12 +3014,12 @@ function session.new(configuration) local revocation_id if revocation then - local raw = configuration and configuration.revocation - if raw == nil then + local configured = configuration and configuration.revocation + if configured == nil then revocation_id = DEFAULT_REVOCATION_ID else - revocation_id = get_revocation_id(raw, configuration) + revocation_id = get_revocation_id(configured, configuration) end end diff --git a/lib/resty/session/utils.lua b/lib/resty/session/utils.lua index 76118892..5951712e 100644 --- a/lib/resty/session/utils.lua +++ b/lib/resty/session/utils.lua @@ -865,15 +865,12 @@ local config_fingerprint do --- -- Fingerprint of a configuration table. -- - -- The table is encoded as JSON with sorted keys and hashed, so equal settings - -- give the same fingerprint whichever table they come from, and credentials - -- are not kept in it. Values that cannot be encoded, such as functions and - -- userdata, are left out, at any depth. Returns `nil` and an error when the - -- table cannot be encoded at all, for example when it refers to itself. - -- - -- It needs a cjson with `encode_sort_keys` and - -- `encode_skip_unsupported_value_types`, as in OpenResty 1.31.8.1 or later, and - -- raises an error without them. + -- A hash of the table encoded as JSON with sorted keys, so equal settings give + -- the same fingerprint whichever table holds them. Functions and other values + -- JSON cannot encode are left out. Returns `nil` and an error when the table + -- cannot be encoded, such as when it refers to itself. Needs a cjson with + -- `encode_sort_keys` and `encode_skip_unsupported_value_types` (OpenResty + -- 1.31.8.1 or later), and raises an error without them. -- -- @function utils.config_fingerprint -- @tparam table configuration configuration table From 4c4d74334573aa2e0d708a8666f1125d9a911b2d Mon Sep 17 00:00:00 2001 From: Hockenba <60619916+Hockenba@users.noreply.github.com> Date: Tue, 24 Nov 2026 15:20:33 -0500 Subject: [PATCH 12/13] test(revocation): logout with a remember cookie revokes it and writes each mark once --- spec/06-revocation-1_spec.lua | 45 +++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/spec/06-revocation-1_spec.lua b/spec/06-revocation-1_spec.lua index cf1b850a..df527276 100644 --- a/spec/06-revocation-1_spec.lua +++ b/spec/06-revocation-1_spec.lua @@ -981,6 +981,51 @@ describe("session: revocation lineage", function() assert.equals("session revoked", err) end) + it("revokes the remember cookie on logout, writing each mark once", function() + initialize("closed") + + local cookies = {} + session.__set_ngx_header(cookies) + local remembered = session.new({ remember = true }) + remembered:set("test_key", "test_data") + assert.is_true(remembered:save()) + local cookie = extract_cookie(cookie_name, cookies["Set-Cookie"]) + local remember_cookie = extract_cookie("remember", cookies["Set-Cookie"]) + assert.not_equals("", cookie) + assert.not_equals("", remember_cookie) + + session.__set_ngx_var({ + ["cookie_" .. cookie_name] = cookie, + cookie_remember = remember_cookie, + }) + local logging_out = session.new({ remember = true }) + assert.is_true(logging_out:open()) + session.__set_ngx_header({}) + assert.is_true(logging_out:destroy()) + + -- one lineage mark, written once, and a session id mark for each cookie + local lineage_marks, sid_marks = 0, 0 + for key in pairs(marks) do + if is_lineage_key(key) then + lineage_marks = lineage_marks + 1 + else + sid_marks = sid_marks + 1 + end + end + assert.equals(1, lineage_writes) + assert.equals(1, lineage_marks) + assert.equals(2, sid_marks) + + -- the remember cookie alone no longer restores the session + session.__set_ngx_var({ + cookie_remember = remember_cookie, + }) + local restored = session.new({ remember = true }) + local ok, err = restored:open() + assert.is_falsy(ok) + assert.is_string(err) + end) + it("does not add a lineage id when revocation is disabled", function() session.init({ cookie_name = cookie_name, From 807e4da1df7368c377e3e4073b335768abbd9863 Mon Sep 17 00:00:00 2001 From: Hockenba <60619916+Hockenba@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:08:31 -0500 Subject: [PATCH 13/13] refactor(utils): keep the storage aliases in one place Add get_storage_settings, which gives the name and settings of a storage, also when it is given by an alias, and use it in load_storage and for the revocation storage identity, so a new alias cannot be missed in one of them. --- lib/resty/session.lua | 22 +-------- lib/resty/session/utils.lua | 92 +++++++++++++++++++++++++++---------- spec/01-utils_spec.lua | 33 +++++++++++++ 3 files changed, 102 insertions(+), 45 deletions(-) diff --git a/lib/resty/session.lua b/lib/resty/session.lua index 28c51c9b..bb697e38 100644 --- a/lib/resty/session.lua +++ b/lib/resty/session.lua @@ -400,32 +400,12 @@ local function get_revocation_cache_size(name) end --- Storages load_storage accepts under two names: it reads the settings of the --- first name, or else of the second. -local REVOCATION_STORAGE_NAMES = { - memcached = { "memcached", "memcache" }, - memcache = { "memcached", "memcache" }, - mysql = { "mysql", "mariadb" }, - mariadb = { "mysql", "mariadb" }, - postgres = { "postgres", "postgresql" }, - postgresql = { "postgres", "postgresql" }, -} - - -- A storage is identified by its settings, not by the table holding them, so -- equal settings share cache entries and different settings never do. local function get_revocation_id(revocation, configuration) local name, settings if type(revocation) == "string" then - local names = REVOCATION_STORAGE_NAMES[revocation] - if names then - name = names[1] - settings = configuration and (configuration[names[1]] or configuration[names[2]]) - - else - name = revocation - settings = configuration and configuration[revocation] - end + name, settings = utils.get_storage_settings(revocation, configuration) elseif type(revocation) == "table" then name = "table" diff --git a/lib/resty/session/utils.lua b/lib/resty/session/utils.lua index 5951712e..610a4e09 100644 --- a/lib/resty/session/utils.lua +++ b/lib/resty/session/utils.lua @@ -905,6 +905,49 @@ local config_fingerprint do end +local get_storage_settings do + -- storages also accepted under a second name + local ALIASES = { + memcache = "memcached", + mariadb = "mysql", + postgresql = "postgres", + } + + local SECOND_NAMES = {} + for alias, name in pairs(ALIASES) do + SECOND_NAMES[name] = alias + end + + --- + -- Name and settings of a storage. + -- + -- A storage accepted under two names, such as `"postgres"` and `"postgresql"`, + -- gets the first name, and the settings under either name, the first preferred. + -- + -- @function utils.get_storage_settings + -- @tparam string storage name of the storage + -- @tparam[opt] table configuration session configuration + -- @treturn string name of the storage + -- @treturn table|nil settings of the storage + -- + -- @usage + -- local name, settings = require("resty.session.utils").get_storage_settings("postgresql", { + -- postgres = { + -- host = "127.0.0.1", + -- } + -- }) + get_storage_settings = function(storage, configuration) + local name = ALIASES[storage] or storage + if not configuration then + return name + end + + local second_name = SECOND_NAMES[name] + return name, configuration[name] or (second_name and configuration[second_name]) + end +end + + local load_storage do local DSHM local FILE @@ -933,73 +976,73 @@ local load_storage do -- } -- }) load_storage = function(storage, configuration) - if storage == "cookie" then + local name, settings = get_storage_settings(storage, configuration) + if name == "cookie" then return nil - elseif storage == "dshm" then + elseif name == "dshm" then if not DSHM then DSHM = require("resty.session.dshm") end - return DSHM.new(configuration and configuration.dshm) + return DSHM.new(settings) - elseif storage == "file" then + elseif name == "file" then if not FILE then FILE = require("resty.session.file") end - return FILE.new(configuration and configuration.file) + return FILE.new(settings) - elseif storage == "memcached" or storage == "memcache" then + elseif name == "memcached" then if not MEMCACHED then MEMCACHED = require("resty.session.memcached") end - return MEMCACHED.new(configuration and configuration.memcached or configuration.memcache) + return MEMCACHED.new(settings) - elseif storage == "mysql" or storage == "mariadb" then + elseif name == "mysql" then if not MYSQL then MYSQL = require("resty.session.mysql") end - return MYSQL.new(configuration and configuration.mysql or configuration.mariadb) + return MYSQL.new(settings) - elseif storage == "postgres" or storage == "postgresql" then + elseif name == "postgres" then if not POSTGRES then POSTGRES = require("resty.session.postgres") end - return POSTGRES.new(configuration and configuration.postgres or configuration.postgresql) + return POSTGRES.new(settings) - elseif storage == "redis" then - local cfg = configuration and configuration.redis - if cfg then - if cfg.nodes then + elseif name == "redis" then + if settings then + if settings.nodes then if not REDIS_CLUSTER then REDIS_CLUSTER = require("resty.session.redis.cluster") end - return REDIS_CLUSTER.new(cfg) + return REDIS_CLUSTER.new(settings) - elseif cfg.sentinels then + elseif settings.sentinels then if not REDIS_SENTINEL then REDIS_SENTINEL = require("resty.session.redis.sentinel") end - return REDIS_SENTINEL.new(cfg) + return REDIS_SENTINEL.new(settings) end end if not REDIS then REDIS = require("resty.session.redis") end - return REDIS.new(cfg) + return REDIS.new(settings) - elseif storage == "shm" then + elseif name == "shm" then if not SHM then SHM = require("resty.session.shm") end - return SHM.new(configuration and configuration.shm) + return SHM.new(settings) else - if not CUSTOM[storage] then - CUSTOM[storage] = require(storage) + if not CUSTOM[name] then + CUSTOM[name] = require(name) end - return CUSTOM[storage].new(configuration and configuration[storage]) + return CUSTOM[name].new(settings) end end end @@ -1241,6 +1284,7 @@ return { decrypt_aes_256_gcm = decrypt_aes_256_gcm, hmac_sha256 = hmac_sha256, config_fingerprint = config_fingerprint, + get_storage_settings = get_storage_settings, load_storage = load_storage, errmsg = errmsg, get_name = get_name, diff --git a/spec/01-utils_spec.lua b/spec/01-utils_spec.lua index b982e4a6..c4833d88 100644 --- a/spec/01-utils_spec.lua +++ b/spec/01-utils_spec.lua @@ -202,6 +202,39 @@ describe("Testing utils", function() end) end) + describe("get_storage_settings", function() + it("gives a storage with two names the first one, and the settings of either", function() + local settings = { host = "127.0.0.1" } + local preferred = { host = "127.0.0.2" } + for _, names in ipairs({ { "memcached", "memcache" }, { "mysql", "mariadb" }, { "postgres", "postgresql" } }) do + local name, alias = names[1], names[2] + local found_name, found_settings = utils.get_storage_settings(alias, { [alias] = settings }) + assert.equal(name, found_name) + assert.equal(settings, found_settings) + + found_name, found_settings = utils.get_storage_settings(name, { [alias] = settings }) + assert.equal(name, found_name) + assert.equal(settings, found_settings) + + -- the settings of the first name are preferred + found_name, found_settings = utils.get_storage_settings(alias, { [name] = preferred, [alias] = settings }) + assert.equal(name, found_name) + assert.equal(preferred, found_settings) + end + end) + + it("keeps any other name as it is", function() + local settings = {} + local name, found_settings = utils.get_storage_settings("custom-storage", { ["custom-storage"] = settings }) + assert.equal("custom-storage", name) + assert.equal(settings, found_settings) + + name, found_settings = utils.get_storage_settings("redis") + assert.equal("redis", name) + assert.is_nil(found_settings) + end) + end) + describe("load_storage", function() -- "dshm" is disabled as it currently cannot be checked by CI for _, strategy in ipairs({ "memcached", "mysql", "postgres", "redis" }) do