Skip to content
Proyek

bungle/lua-resty-session

Lihat di GitHub

Tentang

Pustaka sesi yang fleksibel dan aman untuk OpenResty

Alat pengembangan

Cara angka ini diukur

Pertumbuhan bintang terukur

dalam 24 jam
0
dalam 7 hari
0
dalam 15 hari
-2
dalam 1 bulan
Mengumpulkan riwayat

Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.

README.md

Asli

lua-resty-session

lua-resty-session is a secure, and flexible session library for OpenResty.

TL;DR;

  • Sessions are immutable (each save generates a new session), and lockless.
  • Session data is AES-256-GCM encrypted with a key derived using HKDF-SHA256 (on FIPS-mode it uses PBKDF2 with SHA-256 instead.
  • Session has a fixed size header that is protected with HMAC-SHA256 MAC with a key derived using HKDF-SHA256 (on FIPS-mode it uses PBKDF2 with SHA-256 instead).
  • Session data can be stored in a stateless cookie or in various backend storages.
  • A single session cookie can maintain multiple sessions across different audiences.

Note: Version 4.0.0 was a rewrite of this library with a lot of lessons learned during the years. If you still use older version, please refer old documentation.

Status

This library is considered production ready.

Synopsis

worker_processes  1;

events {
  worker_connections 1024;
}

http {
  init_by_lua_block {
    require "resty.session".init({
      remember = true,
      audience = "demo",
      secret   = "RaJKp8UQW1",
      storage  = "cookie",
    })
  }

  server {
    listen       8080;
    server_name  localhost;
    default_type text/html;

    location / {
      content_by_lua_block {
        ngx.say([[
          <html>
          <body>
            <a href=/start>Start the test</a>
          </body>
          </html>
        ]])
      }
    }

    location /start {
      content_by_lua_block {
        local session = require "resty.session".new()
        session:set_subject("OpenResty Fan")
        session:set("quote", "The quick brown fox jumps over the lazy dog")
        local ok, err = session:save()

        ngx.say(string.format([[
          <html>
          <body>
            <p>Session started (%s)</p>
            <p><a href=/started>Check if it really was</a></p>
          </body>
          </html>
        ]], err or "no error"))
      }
    }

    location /started {
      content_by_lua_block {
        local session, err = require "resty.session".start()

        ngx.say(string.format([[
          <html>
          <body>
            <p>Session was started by %s (%s)</p>
            <p><blockquote>%s</blockquote></p>
            <p><a href=/modify>Modify the session</a></p>
          </body>
          </html>
        ]],
          session:get_subject() or "Anonymous",
          err or "no error",
          session:get("quote") or "no quote"
        ))
      }
    }

    location /modify {
      content_by_lua_block {
        local session, err = require "resty.session".start()
        session:set_subject("Lua Fan")
        session:set("quote", "Lorem ipsum dolor sit amet")
        local _, err_save = session:save()

        ngx.say(string.format([[
          <html>
          <body>
            <p>Session was modified (%s)</p>
            <p><a href=/modified>Check if it is modified</a></p>
          </body>
          </html>
        ]], err or err_save or "no error"))
      }
    }

    location /modified {
      content_by_lua_block {
        local session, err = require "resty.session".start()

        ngx.say(string.format([[
          <html>
          <body>
            <p>Session was started by %s (%s)</p>
            <p><blockquote>%s</blockquote></p>
            <p><a href=/destroy>Destroy the session</a></p>
          </body>
          </html>
        ]],
          session:get_subject() or "Anonymous",
          err or "no error",
          session:get("quote")  or "no quote"
        ))
      }
    }

    location /destroy {
      content_by_lua_block {
        local ok, err = require "resty.session".destroy()

        ngx.say(string.format([[
          <html>
          <body>
            <p>Session was destroyed (%s)</p>
            <p><a href=/destroyed>Check that it really was?</a></p>
          </body>
          </html>
        ]], err or "no error"))
      }
    }

    location /destroyed {
      content_by_lua_block {
        local session, err = require "resty.session".open()

        ngx.say(string.format([[
          <html>
          <body>
            <p>Session was really destroyed, you are known as %s (%s)</p>
            <p><a href=/>Start again</a></p>
          </body>
          </html>
        ]],
          session:get_subject() or "Anonymous",
          err or "no error"
        ))
      }
    }
  }
}

Table of Contents

Installation

Using OpenResty Package Manager (opm)

❯ opm get bungle/lua-resty-session

OPM repository for lua-resty-session is located at https://opm.openresty.org/package/bungle/lua-resty-session/.

Also check the dependencies for each storage (there may be additional dependencies).

Using LuaRocks

❯ luarocks install lua-resty-session

LuaRocks repository for lua-resty-session is located at https://luarocks.org/modules/bungle/lua-resty-session.

Also check the dependencies for each storage (there may be additional dependencies).

Configuration

The configuration can be divided to generic session configuration and the server side storage configuration.

Here is an example:

init_by_lua_block {
  require "resty.session".init({
    remember = true,
    store_metadata = true,
    secret = "RaJKp8UQW1",
    secret_fallbacks = {
      "X88FuG1AkY",
      "fxWNymIpbb",
    },
    storage = "postgres",
    postgres = {
      username = "my-service",
      password = "kVgIXCE5Hg",
      database = "sessions",
    },
  })
}

Session Configuration

Session configuration can be passed to initialization, constructor, and helper functions.

Here are the possible session configuration options:

Option Default Description
secret nil Secret used for the key derivation. The secret is hashed with SHA-256 before using it. E.g. "RaJKp8UQW1".
secret_fallbacks nil Array of secrets that can be used as alternative secrets (when doing key rotation), E.g. { "6RfrAYYzYq", "MkbTkkyF9C" }.
ikm (random) Initial keying material (or ikm) can be specified directly (without using a secret) with exactly 32 bytes of data. E.g. "5ixIW4QVMk0dPtoIhn41Eh1I9enP2060"
ikm_fallbacks nil Array of initial keying materials that can be used as alternative keys (when doing key rotation), E.g. { "QvPtlPKxOKdP5MCu1oI3lOEXIVuDckp7" }.
cookie_prefix nil Cookie prefix, use nil, "__Host-" or "__Secure-".
cookie_name "session" Session cookie name, e.g. "session".
cookie_path "/" Cookie path, e.g. "/".
cookie_domain nil Cookie domain, e.g. "example.com"
cookie_http_only true Mark cookie HTTP only, use true or false.
cookie_secure nil Mark cookie secure, use nil, true or false.
cookie_priority nil Cookie priority, use nil, "Low", "Medium", or "High".
cookie_same_site "Lax" Cookie same-site policy, use nil, "Lax", "Strict", "None", or "Default"
cookie_same_party nil Mark cookie with same party flag, use nil, true, or false.
cookie_partitioned nil Mark cookie with partitioned flag, use nil, true, or false.
remember false Enable or disable persistent sessions, use nil, true, or false.
remember_safety "Medium" Remember cookie key derivation complexity, use nil, "None" (fast), "Low", "Medium", "High" or "Very High" (slow).
remember_cookie_name "remember" Persistent session cookie name, e.g. "remember".
audience "default" Session audience, e.g. "my-application".
subject nil Session subject, e.g. "[email protected]".
enforce_same_subject false When set to true, audiences need to share the same subject. The library removes non-subject matching audience data on save.
stale_ttl 10 When session is saved a new session is created, stale ttl specifies how long the old one can still be used, e.g. 10 (in seconds).
exchange_once false When set to true, a session can be saved (exchanged for a new session id) only once: the first save wins, and the old session can only be read until stale_ttl passes. See Session Exchange Configuration.
revoke nil Kinds of revocations that the sessions are checked against when they are opened, use "sid" and "subject", e.g. { "sid" }. See Session Revocation by Sid or Subject.
revoke_reuse false When set to true, a reused cookie session revokes the sessions that it was exchanged for (and its sids with revoke of "sid"). Also turns on exchange_once. See Reused Sessions.
idling_timeout 900 Idling timeout specifies how long the session can be inactive until it is considered invalid, e.g. 900 (15 minutes) (in seconds), 0 disables the checks and touching.
rolling_timeout 3600 Rolling timeout specifies how long the session can be used until it needs to be renewed, e.g. 3600 (an hour) (in seconds), 0 disables the checks and rolling.
absolute_timeout 86400 Absolute timeout limits how long the session can be renewed, until re-authentication is required, e.g. 86400 (a day) (in seconds), 0 disables the checks.
remember_rolling_timeout 604800 Remember timeout specifies how long the persistent session is considered valid, e.g. 604800 (a week) (in seconds), 0 disables the checks and rolling.
remember_absolute_timeout 2592000 Remember absolute timeout limits how long the persistent session can be renewed, until re-authentication is required, e.g. 2592000 (30 days) (in seconds), 0 disables the checks.
hash_storage_key false Whether to hash or not the storage key. With storage key hashed it is impossible to decrypt data on server side without having a cookie too, use nil, true or false.
hash_subject false Whether to hash or not the subject when store_metadata is enabled, e.g. for PII reasons.
store_metadata false Whether to also store metadata of sessions, such as collecting data of sessions for a specific audience belonging to a specific subject.
touch_threshold 60 Touch threshold controls how frequently or infrequently the session:refresh touches the cookie, e.g. 60 (a minute) (in seconds)
compression_threshold 1024 Compression threshold controls when the data is deflated, e.g. 1024 (a kilobyte) (in bytes), 0 disables compression.
bind nil Bind the session to data acquired from the HTTP request or connection, use ip, scheme, user-agent. E.g. { "scheme", "user-agent" } will calculate MAC utilizing also HTTP request Scheme and User-Agent header.
request_headers nil Set of headers to send to upstream, use id, audience, subject, timeout, idling-timeout, rolling-timeout, absolute-timeout. E.g. { "id", "timeout" } will set Session-Id and Session-Timeout request headers when set_headers is called.
response_headers nil Set of headers to send to downstream, use id, audience, subject, timeout, idling-timeout, rolling-timeout, absolute-timeout. E.g. { "id", "timeout" } will set Session-Id and Session-Timeout response headers when set_headers is called.
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.
storage_cache_ttl 0 Worker-local cache TTL for the session data of server-side storage sessions (in seconds), 0 disables it. See Session Storage Cache.
storage_cache_size 1024 Worker-local cache size for the session data of server-side storage sessions (set by the first configuration that enables the cache).
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" Whether a session is trusted when the revocation store cannot be read, use "open" (treat as not revoked) or "closed" (reject the session). Writes return their errors in both modes.
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_size 1024 Worker-local cache size for the revocation lookups, and for the revocation store errors (a cache of its own) (set by the first configuration that enables each cache).
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)
mysql nil Configuration for MySQL / MariaDB storage, e.g. { database = "sessions" } (see below)
postgres nil Configuration for Postgres storage, e.g. { database = "sessions" } (see below)
redis nil Configuration for Redis / Redis Sentinel / Redis Cluster storages, e.g. { prefix = "sessions" } (see below)
shm nil Configuration for shared memory storage, e.g. { zone = "sessions" }
["custom-storage"] nil custom storage (loaded with require "custom-storage") configuration.

Choosing the Storage

The session data can be kept in the cookie (storage = "cookie", the default), in the cookie with a revocation storage (revocation), or in a server-side storage (storage, e.g. "redis"):

Cookie Cookie + revocation Server-side storage
Infrastructure none a storage for small records that expire a storage for all the session data
I/O per request none 1 lookup on open (cached), and 1 per revoke kind 1 read on open (can be cached), and 1 per revoke kind, 1 write per save
Cookie size grows with the data (split into chunks) grows with the data (split into chunks) small, whatever the data
Large data (e.g. OIDC tokens) poor poor good
Logout ends copies of the cookie no, they stay valid until they time out yes, at once on the worker, elsewhere within revocation_cache_ttl yes, at once on the worker, elsewhere within storage_cache_ttl (off by default)
Revocation by sid or subject no yes yes
exchange_once no yes yes
Reuse detection no yes no: the old session is deleted after stale_ttl, so a reused cookie is missing
Storage outage not affected revocation_fail_mode decides whether the sessions are trusted the sessions do not open
Kept on the server nothing revocation and exchange records the encrypted session data
Records lost (e.g. evicted) - a revoked cookie is valid again the session is gone (logged out)
session.info in the cookie, info:save is a save in the cookie, info:save is a save in the storage, info:save sends no cookie
Listing sessions (store_metadata) no no yes
Best for small data, short timeouts data that fits in a cookie, when a logout has to end the session large data, session.info without new cookies, listing sessions
  • With cookie sessions, a logout only clears the cookie of that browser, and a copy of the cookie (e.g. from a log, or stolen) stays valid until its idling, rolling, or absolute timeout passes. Keep the timeouts short, or use a revocation storage.
  • A revocation storage must not drop records before they expire (see Running on Several Servers), and revocation_fail_mode decides whether the sessions are trusted ("open") or rejected ("closed") when it cannot be read (see Session Revocation Configuration).
  • With server-side storage, the session is deleted on logout, so a revocation storage is not used (revocation is ignored).

See also Session Exchange Configuration, Session Revocation by Sid or Subject, Reused Sessions, and Session Storage Cache.

Cookie Storage Configuration

When storing data to cookie, there is no additional configuration required, just set the storage to nil or "cookie".

Session Revocation Configuration

Cookie (stateless) sessions are self-contained: once issued, a cookie remains valid until it expires according to the configured timeouts. Revocation adds an optional storage-backed denylist so that destroyed sessions are rejected immediately, without waiting for the cookie to expire.

Revocation is only available when session data is stored in the cookie (storage is nil or "cookie"). Select the backend explicitly with revocation = "dshm", "file", "memcached", "mysql", "postgres", "redis", or "shm". The backend uses its normal configuration section and the same storage set/get contract used for session data. Custom storage module names and pre-built storage tables are also supported. Setting revocation = false or leaving it unset disables revocation.

On every session:open, the library checks a worker-local LRU cache for the hashed session identifier. On a cache miss, it checks the configured store. A successful lookup (true/false) is cached for revocation_cache_ttl 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. The errors are cached apart from the lookups, so that the errors of an outage do not evict the lookups that are still cached. Each cache holds revocation_cache_size entries.

The caches are shared by the configurations of a worker, and their entries are keyed by the cookie name and the session identifier. Configurations that use different revocation storages should use different cookie names, so that the state of a session cached from one storage is not used with the other.

A session revoked on another worker or server can still be read and touched until the cached lookup expires, but when a session that was opened with a cached lookup is saved, the store is checked first, so that the save cannot exchange a revoked session for a new one.

session:destroy (including a last-audience session:logout) does not read the store before it revokes. A cached true means the identifier is already revoked and no store write is made. 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.

Use revocation_fail_mode to control whether a session is trusted when the revocation storage cannot be read:

  • "open" (default): log a warning and treat the session as not revoked.
  • "closed": reject the session (session:open fails).

The fail mode only applies to reading the revocation storage. When a write fails, the result is the same in both modes: session:destroy (and session:logout of the last audience) still clears the cookies and closes the session, but returns nil and the error, as a copy of the cookie is not revoked.

Revocation applies to session:destroy (and session:logout when it destroys the last audience). It does not revoke the previous session identifier on session:save (session rotation) or partial session:logout (multiple audiences). After rotation or partial logout, the previous cookie remains usable until its timeout elapses, unless exchange_once is enabled (see Session Exchange Configuration).

Examples:

-- Redis denylist
require("resty.session").init({
  storage = "cookie",
  revocation = "redis",
  redis = {
    host = "127.0.0.1",
    password = "secret",
    prefix = "sessions",
  },
})

-- Shared memory denylist
require("resty.session").init({
  storage = "cookie",
  revocation = "shm",
  shm = {
    zone = "sessions",
    prefix = "revocations",
  },
})

-- MySQL denylist
require("resty.session").init({
  storage = "cookie",
  revocation = "mysql",
  mysql = {
    host = "127.0.0.1",
    database = "sessions",
    username = "session",
    password = "secret",
  },
})

The same pattern works for "dshm", "file", "memcached", and "postgres".

Session Exchange Configuration

Every session:save exchanges the session for a new one with a new session id. By default, the old session can still be used, and saved again, until it times out (server-side storage removes it after stale_ttl). Two requests that save the same session at the same time, or someone who replays an old cookie, can each get a new session of their own.

With exchange_once = true, a session can be exchanged only once:

  • The first save of a session wins. A later save of the same session returns nil, "session is stale" and sends no cookie (the response of the winning request carries the new cookie).
  • The old session can still be read until stale_ttl passes, so that requests that were sent with the old cookie at the same time keep working, but it cannot be saved anymore. session:refresh and session:touch of such a session return true without sending a cookie. session:is_stale tells whether the session is known to be stale.
  • session.info:save of such a session returns nil, "session is stale" (with server-side storage it checks the storage first, as saving the info of the old session would keep it for its whole lifetime).
  • After stale_ttl the old session is rejected.
  • A session that was revoked (destroyed or logged out) by another request after it was opened is not stale: session:save, session:refresh, session:touch, and session.info:save return nil, "session revoked".
  • session:destroy (and session:logout when it destroys the last audience) also revokes the sessions that the destroyed session was exchanged for, so a save that raced with a logout cannot keep the user logged in.
  • session:logout of one audience of a session that has several audiences saves the session, so it can also return nil, "session is stale". The audience is then not logged out, but the response of the other request carries the new cookie, and retrying the logout works.

Each save writes one record for the old session id with an atomic add (only if it does not exist yet). The record stores the time from which the old session is revoked and the key of the session it was exchanged for:

  • Server-side storage sessions keep the record in the session storage, next to the session data, under a key derived from the session key. It lives stale_ttl plus a few seconds.
  • Cookie sessions keep the record in the revocation storage under the revocation key of the session, so revocation must be configured. As a cookie cannot be expired on the server, the record lives as long as the old cookie could still be used: the remaining rolling and absolute timeouts, but at most idling_timeout (the remember_* timeouts for the remember cookie), plus stale_ttl. When the record cannot be written, the save fails (in both revocation fail modes), as without the record the session could be exchanged again.

The revocation storage then holds the keys of live sessions too (the sessions that a session was exchanged for). With the default hash_storage_key = false these keys are base64url encoded session ids. Set hash_storage_key = true to store hashes of the session ids instead.

All the built-in storages implement the atomic add. With a custom storage that does not (see Custom Storage Interface), enabling exchange_once raises an error.

Things to be aware of:

  • A request that is sent with the old cookie, but arrives after stale_ttl has passed (e.g. a slow upload, or a retry), is rejected. Applications that send many requests at the same time (e.g. single-page applications) may want a longer stale_ttl, such as 30 to 60 seconds. The old session can only be read during that time.
  • session:touch (and so session:refresh) checks the storage before it sends the session cookie again, so that it does not send the old cookie of a session that another request has exchanged (or returns "session revoked" for a session revoked elsewhere). This costs one storage lookup per touch, and touches are limited by touch_threshold.
  • With cookie sessions, a worker may see an exchange (or a revocation) made by another worker or server up to revocation_cache_ttl seconds late. The save itself always checks the storage.
  • The record stores absolute times, so the clocks of the servers need to be roughly in sync.
  • exchange_once does not protect against a stolen cookie. If someone saves a stolen cookie first, the cookie of the user becomes stale. A logout with it revokes the sessions that it was exchanged for only until stale_ttl passes, as after that the old session cannot be opened anymore. The sessions of the stolen cookie then stay valid until they time out, unless the application reacts to the reuse of the old cookie (see Reused Sessions).
require("resty.session").init({
  storage = "redis",
  exchange_once = true,
})

-- or with cookie sessions
require("resty.session").init({
  storage = "cookie",
  revocation = "redis",
  exchange_once = true,
})

Reused Sessions

With exchange_once and cookie sessions, an exchanged session that is used again after stale_ttl is rejected: session:open returns nil and "session reused", and session:is_reused returns true. Either the browser did not get the new cookie (e.g. a lost response, or a client that was offline for longer than stale_ttl), or someone else has a copy of the cookie. The library cannot tell these apart.

The session is then a new session, as after any session that does not open, so for example a new login replaces the reused cookie. session:get_reused gives the identity of the reused session (audience, subject, sid, and issuer), so that the application can react to it:

local session = require("resty.session").open()
local reused = session:get_reused()
if reused then
  ngx.log(ngx.WARN, "reused session of ", reused.subject)

  -- e.g. end the login of the identity provider (with revoke = { "sid" }),
  -- which ends every copy of the session
  require("resty.session").revoke({
    issuer = reused.issuer,
    sid = reused.sid,
  })
end

The library does not act on it by default. With revoke_reuse = true it revokes the sessions that the reused session was exchanged for, and with revoke = { "sid" } also the sids of its audiences. It turns on exchange_once.

Things to be aware of:

  • Any response to a reuse can be triggered by anyone that has an old copy of the cookie, e.g. from logs or a backup: revoking logs the user out, so it can be used to log the user out until the old cookie times out. A lost response logs the user out too.
  • Only cookie sessions report a reuse. The old sessions and the exchange records of server-side storage sessions are removed soon after stale_ttl, so a reused storage session is not found ("unable to load session").
  • Before 4.5.0, a reused session was reported as "session revoked".

Session Revocation by Sid or Subject

A session can be revoked without its cookie, e.g. when an OpenID Connect provider sends a back-channel logout, or when a user is to be logged out everywhere. On login, store the values that identify the session on the session (for the current audience):

session:set_subject(id_token.sub)
session:set_sid(id_token.sid)       -- the session id of the identity provider
session:set_issuer(id_token.iss)    -- needed only with more than one issuer

Enable the kinds of revocations that are checked, and revoke with the values of the logout:

require("resty.session").init({
  storage = "redis",
  revoke = { "sid", "subject" },
})

-- e.g. on a back-channel logout (after validating the logout token)
local ok, err = require("resty.session").revoke({
  issuer = logout_token.iss,
  sid = logout_token.sid,   -- or: subject = logout_token.sub
})

How it works:

  • session.revoke writes a mark with the current time. A session that has the sid (or the subject) of the mark, and that was authenticated at or before that time, is not opened anymore: session:open returns nil and "session revoked". The sessions authenticated later are not affected, so the user can log in again.
  • A session is authenticated when an audience is saved with a subject or a sid for the first time, or after session:set_subject, session:set_sid, or session:set_issuer changes the value. Sessions saved before revoke was enabled count as authenticated when they were created. The times are in seconds, so a login in the same second as a revocation of the same subject (or sid) is revoked too.
  • The time of a login that creates the session is the creation time of the session, so it does not grow the cookie. A login to an existing session (a new audience, or a new subject) stores its time (a few bytes).
  • The mark applies to every audience that has the sid (or the subject), and only to them: the other audiences of the session stay logged in, and a new login to the revoked audience keeps them.
  • The issuer is part of the mark: a mark with an issuer revokes only the sessions of that issuer, and a mark without an issuer only the sessions without one.
  • Server-side storage sessions keep the marks in the session storage. Cookie sessions keep them in the revocation storage, so revocation must be configured. The marks are stored under a hash of the issuer and the value, so they do not reveal the subjects, and they fit the storages that limit the key size (e.g. MySQL).
  • The mark is kept as long as the revoked sessions could live: the longer of absolute_timeout and remember_absolute_timeout, plus stale_ttl. When either absolute timeout is 0, give the time with ttl. The time the marks are kept is what decides how much they take in the storage: an application that does not use remember cookies can give ttl = absolute_timeout.
  • A request checks only its own audience, so before the audiences of a session are copied to a new remember cookie, the other audiences are checked too (one lookup for each, when a remember cookie is created), and the revoked ones are dropped.

Costs and things to be aware of:

  • Each enabled kind costs one storage lookup when a session that has that value is opened. Enable only the kinds that you use.
  • The lookups of cookie sessions are cached like revocation records (revocation_cache_ttl, and the errors follow revocation_fail_mode), and the lookups of storage sessions like the session data (storage_cache_ttl). The worker that revokes sees the revocation right away, the other workers and servers within the cache ttl.
  • The times of the marks come from the server that writes them, so the clocks of the servers need to be in sync.
  • Older versions of this library do not check the marks, so during a rolling upgrade the servers that are not upgraded yet still accept revoked sessions.

To log out all the sessions of an audience, change the audience (the sessions of the old audience are not opened anymore), and to log out all the sessions, change the secret without keeping the old one in secret_fallbacks. Neither needs revoke.

Running on Several Servers

With several servers (or a web farm), the storage of the sessions, of the revocation records, and of the exchange records (exchange_once) needs to be shared by all the servers:

  • Use a shared storage, such as Redis, Memcached, MySQL, Postgres, or DSHM. The shm storage and the file storage (on a local disk) are local to a server, so they only work when every client always reaches the same server. With them, revocations and exchanges are not seen by the other servers, and two servers can each exchange the same session.
  • For revocation and exchange_once, use a storage that does not drop records before they expire. A missing revocation or exchange record of a cookie session means that the cookie is valid. Memcached drops records when it runs out of memory, and so does Redis with an allkeys-* eviction policy. Prefer Redis with the noeviction policy (or a volatile-* policy with enough memory), or MySQL or Postgres.
  • With Redis replication (e.g. Redis Sentinel), a write that was confirmed by the primary can be lost when the primary fails before the write was replicated.
  • With MySQL or Postgres, connect to the primary. With replicas (or a proxy that sends reads to replicas), a record that was just written may not be read yet.
  • Keep the clocks of the servers in sync (e.g. with NTP), as the timeouts and the exchange records use absolute times.
  • The worker-local revocation cache delays the changes made by the other workers and servers by at most revocation_cache_ttl seconds (0 disables it), and so does the session storage cache by at most storage_cache_ttl seconds.

Session Storage Cache

With server-side storage, every request reads the session data from the storage, which is usually a network round trip. With storage_cache_ttl, each worker keeps the session data it has read or written in a cache (an LRU of storage_cache_size entries) for that many seconds, so most requests do not need the storage anymore. The cookie is still authenticated, and its timeouts are still checked, on every request.

The data of a session does not change, as a save creates a new session with a new session id. The cache of the worker that saves, destroys, or saves the info of a session is updated right away, but the other workers and servers may use their cached data until storage_cache_ttl passes:

  • a session destroyed elsewhere can still be read and touched there
  • session.info saved elsewhere is seen there later
  • a session exchanged elsewhere can still be read there after stale_ttl has passed

Writes do not trust the cache: when a session that was read from the cache is saved, the storage is checked first, so that a session destroyed (or expired) elsewhere is not exchanged for a new session. This costs one storage read per save, and saves are rare compared to reads (by default a refreshed session is saved after 45 minutes). session.info:save replaces the session in the storage only if it still exists, so it does not bring back a destroyed session (with the built-in storages this needs no extra read).

Use a storage_cache_ttl that is short compared to how quickly a logout needs to take effect everywhere, e.g. 5 seconds. The cache is disabled by default.

require("resty.session").init({
  storage = "redis",
  storage_cache_ttl = 5,
})

DSHM Storage Configuration

With DHSM storage you can use the following settings (set the storage to "dshm"):

Option Default Description
prefix nil The Prefix for the keys stored in DSHM.
suffix nil The suffix for the keys stored in DSHM.
host "127.0.0.1" The host to connect.
port 4321 The port to connect.
connect_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's connect method.
send_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's send method.
read_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's receive method.
keepalive_timeout nil Controls the default maximal idle time of the connections in the connection pool.
pool nil A custom name for the connection pool being used.
pool_size nil The size of the connection pool.
backlog nil A queue size to use when the connection pool is full (configured with pool_size).
ssl nil Enable SSL.
ssl_verify nil Verify server certificate.
server_name nil The server name for the new TLS extension Server Name Indication (SNI).

Please refer to ngx-distributed-shm to get necessary dependencies installed.

File Storage Configuration

With file storage you can use the following settings (set the storage to "file"):

Option Default Description
prefix nil File prefix for session file.
suffix nil File suffix (or extension without .) for session file.
pool nil Name of the thread pool under which file writing happens (available on Linux only).
path (tmp directory) Path (or directory) under which session files are created.

The implementation requires LuaFileSystem which you can install with LuaRocks:

❯ luarocks install LuaFileSystem

Memcached Storage Configuration

With file Memcached you can use the following settings (set the storage to "memcached"):

Option Default Description
prefix nil Prefix for the keys stored in memcached.
suffix nil Suffix for the keys stored in memcached.
host 127.0.0.1 The host to connect.
port 11211 The port to connect.
socket nil The socket file to connect to.
connect_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's connect method.
send_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's send method.
read_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's receive method.
keepalive_timeout nil Controls the default maximal idle time of the connections in the connection pool.
pool nil A custom name for the connection pool being used.
pool_size nil The size of the connection pool.
backlog nil A queue size to use when the connection pool is full (configured with pool_size).
ssl false Enable SSL
ssl_verify nil Verify server certificate
server_name nil The server name for the new TLS extension Server Name Indication (SNI).

MySQL / MariaDB Storage Configuration

With file MySQL / MariaDB you can use the following settings (set the storage to "mysql"):

Option Default Description
host "127.0.0.1" The host to connect.
port 3306 The port to connect.
socket nil The socket file to connect to.
username nil The database username to authenticate.
password nil Password for authentication, may be required depending on server configuration.
charset "ascii" The character set used on the MySQL connection.
database nil The database name to connect.
table_name "sessions" Name of database table to which to store session data.
table_name_meta "sessions_meta" Name of database meta data table to which to store session meta data.
max_packet_size 1048576 The upper limit for the reply packets sent from the MySQL server (in bytes).
connect_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's connect method.
send_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's send method.
read_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's receive method.
keepalive_timeout nil Controls the default maximal idle time of the connections in the connection pool.
pool nil A custom name for the connection pool being used.
pool_size nil The size of the connection pool.
backlog nil A queue size to use when the connection pool is full (configured with pool_size).
ssl false Enable SSL.
ssl_verify nil Verify server certificate.

You also need to create following tables in your database:

--
-- Database table that stores session data.
--
CREATE TABLE IF NOT EXISTS sessions (
  sid  CHAR(43) PRIMARY KEY,
  name VARCHAR(255),
  data MEDIUMTEXT,
  exp  DATETIME,
  INDEX (exp)
) CHARACTER SET ascii;

--
-- Sessions metadata table.
--
-- This is only needed if you want to store session metadata.
--
CREATE TABLE IF NOT EXISTS sessions_meta (
  aud VARCHAR(255),
  sub VARCHAR(255),
  sid CHAR(43),
  PRIMARY KEY (aud, sub, sid),
  CONSTRAINT FOREIGN KEY (sid) REFERENCES sessions(sid) ON DELETE CASCADE ON UPDATE CASCADE
) CHARACTER SET ascii;

Postgres Configuration

With file Postgres you can use the following settings (set the storage to "postgres"):

Option Default Description
host "127.0.0.1" The host to connect.
port 5432 The port to connect.
application 5432 Set the name of the connection as displayed in pg_stat_activity (defaults to "pgmoon").
username "postgres" The database username to authenticate.
password nil Password for authentication, may be required depending on server configuration.
database nil The database name to connect.
table_name "sessions" Name of database table to which to store session data (can be database schema prefixed).
table_name_meta "sessions_meta" Name of database meta data table to which to store session meta data (can be database schema prefixed).
connect_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's connect method.
send_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's send method.
read_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's receive method.
keepalive_timeout nil Controls the default maximal idle time of the connections in the connection pool.
pool nil A custom name for the connection pool being used.
pool_size nil The size of the connection pool.
backlog nil A queue size to use when the connection pool is full (configured with pool_size).
ssl false Enable SSL.
ssl_verify nil Verify server certificate.
ssl_required nil Abort the connection if the server does not support SSL connections.

You also need to create following tables in your database:

--
-- Database table that stores session data.
--
CREATE TABLE IF NOT EXISTS sessions (
  sid  TEXT PRIMARY KEY,
  name TEXT,
  data TEXT,
  exp  TIMESTAMP WITH TIME ZONE
);
CREATE INDEX ON sessions (exp);

--
-- Sessions metadata table.
--
-- This is only needed if you want to store session metadata.
--
CREATE TABLE IF NOT EXISTS sessions_meta (
  aud TEXT,
  sub TEXT,
  sid TEXT REFERENCES sessions (sid) ON DELETE CASCADE ON UPDATE CASCADE,
  PRIMARY KEY (aud, sub, sid)
);

The implementation requires pgmoon which you can install with LuaRocks:

❯ luarocks install pgmoon

Redis Configuration

The session library supports single Redis, Redis Sentinel, and Redis Cluster connections. Common configuration settings among them all:

Option Default Description
prefix nil Prefix for the keys stored in Redis.
suffix nil Suffix for the keys stored in Redis.
username nil The database username to authenticate.
password nil Password for authentication.
connect_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's connect method.
send_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's send method.
read_timeout nil Controls the default timeout value used in TCP/unix-domain socket object's receive method.
keepalive_timeout nil Controls the default maximal idle time of the connections in the connection pool.
pool nil A custom name for the connection pool being used.
pool_size nil The size of the connection pool.
backlog nil A queue size to use when the connection pool is full (configured with pool_size).
ssl false Enable SSL
ssl_verify nil Verify server certificate
server_name nil The server name for the new TLS extension Server Name Indication (SNI).

The single redis implementation is selected when you don't pass either sentinels or nodes, which would lead to selecting sentinel or cluster implementation.

Single Redis Configuration

Single Redis has following additional configuration options (set the storage to "redis"):

Option Default Description
host "127.0.0.1" The host to connect.
port 6379 The port to connect.
socket nil The socket file to connect to.
database nil The database to connect.

Redis Sentinels Configuration

Redis Sentinel has following additional configuration options (set the storage to "redis" and configure the sentinels):

Option Default Description
master nil Name of master.
role nil "master" or "slave".
socket nil The socket file to connect to.
sentinels nil Redis Sentinels.
sentinel_username nil Optional sentinel username.
sentinel_password nil Optional sentinel password.
database nil The database to connect.

The sentinels is an array of Sentinel records:

Option Default Description
host nil The host to connect.
port nil The port to connect.

The sentinel implementation is selected when you pass sentinels as part of redis configuration (and do not pass nodes, which would select cluster implementation).

The implementation requires lua-resty-redis-connector which you can install with LuaRocks:

❯ luarocks install lua-resty-redis-connector

Redis Cluster Configuration

Redis Cluster has following additional configuration options (set the storage to "redis" and configure the nodes):

Option Default Description
name nil Redis cluster name.
nodes nil Redis cluster nodes.
lock_zone nil Shared dictionary name for locks.
lock_prefix nil Shared dictionary name prefix for lock.
max_redirections nil Maximum retry attempts for redirection.
max_connection_attempts nil Maximum retry attempts for connection.
max_connection_timeout nil Maximum connection timeout in total among the retries.

The nodes is an array of Cluster node records:

Option Default Description
ip "127.0.0.1" The IP address to connect.
port 6379 The port to connect.

The cluster implementation is selected when you pass nodes as part of redis configuration.

For cluster to work properly, you need to configure lock_zone, so also add this to your Nginx configuration:

lua_shared_dict redis_cluster_locks 100k;

And set the lock_zone to "redis_cluster_locks"

The implementation requires resty-redis-cluster or kong-redis-cluster which you can install with LuaRocks:

❯ luarocks install resty-redis-cluster
# or
❯ luarocks install kong-redis-cluster

SHM Configuration

With SHM storage you can use the following settings (set the storage to "shm"):

Option Default Description
prefix nil Prefix for the keys stored in SHM.
suffix nil Suffix for the keys stored in SHM.
zone "sessions" A name of shared memory zone.

You will also need to create a shared dictionary zone in Nginx:

lua_shared_dict sessions 10m;

Note: you may need to adjust the size of shared memory zone according to your needs.

API

LDoc generated API docs can also be viewed at bungle.github.io/lua-resty-session.

Initialization

session.init

syntax: session.init(configuration)

Initialize the session library.

This function can be called on init or init_worker phases on OpenResty to set global default configuration to all session instances created by this library.

require "resty.session".init({
  audience = "my-application",
  storage = "redis",
  redis = {
    username = "session",
    password = "storage",
  },
})

See configuration for possible configuration settings.

Constructors

session.new

syntax: session = session.new(configuration)

Creates a new session instance.

local session = require "resty.session".new()
-- OR
local session = require "resty.session".new({
  audience = "my-application",
})

See configuration for possible configuration settings.

Helpers

session.open

syntax: session, err, exists = session.open(configuration)

This can be used to open a session, and it will either return an existing session or a new session. The exists (a boolean) return parameters tells whether it was existing or new session that was returned. The err (a string) contains a message of why opening might have failed (the function will still return session too).

local session = require "resty.session".open()
-- OR
local session, err, exists = require "resty.session".open({
  audience = "my-application",
})

See configuration for possible configuration settings.

session.start

syntax: session, err, exists, refreshed = session.start(configuration)

This can be used to start a session, and it will either return an existing session or a new session. In case there is an existing session, the session will be refreshed as well (as needed). The exists (a boolean) return parameters tells whether it was existing or new session that was returned. The refreshed (a boolean) tells whether the call to refresh was succesful. The err (a string) contains a message of why opening or refreshing might have failed (the function will still return session too).

local session = require "resty.session".start()
-- OR
local session, err, exists, refreshed = require "resty.session".start({
  audience = "my-application",
})

See configuration for possible configuration settings.

session.logout

syntax: ok, err, exists, logged_out = session.logout(configuration)

It logouts from a specific audience.

A single session cookie may be shared between multiple audiences (or applications), thus there is a need to be able to logout from just a single audience while keeping the session for the other audiences. The exists (a boolean) return parameters tells whether session existed. The logged_out (a boolean) return parameter signals if the session existed and was also logged out. The err (a string) contains a reason why session didn't exists or why the logout failed. The ok (truthy) will be true when session existed and was successfully logged out.

When there is only a single audience, then this can be considered equal to session.destroy.

When the last audience is logged out, the cookie will be destroyed as well and invalidated on a client.

require "resty.session".logout()
-- OR
local ok, err, exists, logged_out = require "resty.session".logout({
  audience = "my-application",
})

See configuration for possible configuration settings.

session.destroy

syntax: ok, err, exists, destroyed = session.destroy(configuration)

It destroys the whole session and clears the cookies.

A single session cookie may be shared between multiple audiences (or applications), thus there is a need to be able to logout from just a single audience while keeping the session for the other audiences. The exists (a boolean) return parameters tells whether session existed. The destroyed (a boolean) return parameter signals if the session existed and was also destroyed out. The err (a string) contains a reason why session didn't exists or why the logout failed. The ok (truthy) will be true when session existed and was successfully logged out.

require "resty.session".destroy()
-- OR
local ok, err, exists, destroyed = require "resty.session".destroy({
  cookie_name = "auth",
})

session.revoke

syntax: ok, err = session.revoke(options, configuration)

Revokes the sessions of a sid or of a subject that were authenticated at or before now, without a session cookie. The options table has either sid or subject, and optionally issuer and ttl (in seconds). The kind must be enabled with the revoke configuration. The revocation applies to every audience that has the sid or the subject, so audience is not accepted. See Session Revocation by Sid or Subject.

local ok, err = require "resty.session".revoke({
  issuer = logout_token.iss,
  sid = logout_token.sid,
})

See configuration for possible configuration settings.

Instance Methods

session:open

syntax: ok, err = session:open()

This can be used to open a session. It returns true when session was opened and validated. Otherwise, it returns nil and an error message.

Some of the error messages:

  • "missing session cookie": the request has no session cookie.
  • "session revoked": the session was destroyed or logged out (cookie sessions with a revocation storage), or revoked with session.revoke. A server-side storage session that was destroyed is not found ("unable to load session").
  • "session reused": an exchanged session was used again after stale_ttl (see Reused Sessions). Instead of comparing the message, session:is_reused tells the same, and session:get_reused gives the identity of the reused session. With revoke_reuse, an error while revoking the sessions it was exchanged for is only logged.
  • "unable to check session revocation" (followed by the error): the revocation storage could not be read, and revocation_fail_mode is "closed".
local session = require "resty.session".new()
local ok, err = session:open()
if ok then
  -- session exists

else
  -- session did not exists or was invalid
end

session:save

syntax: ok, err = session:save()

Saves the session data and issues a new session cookie with a new session id. When remember is enabled, it will also issue a new persistent cookie and possibly save the data in backend store. It returns true when session was saved. Otherwise, it returns nil and an error message. With exchange_once enabled, the error message is "session is stale" when another request has already saved (exchanged) the session (see session:is_stale), and "session revoked" when another request has destroyed (or logged out) the session after it was opened.

local session = require "resty.session".new()
session:set_subject("john")
local ok, err = session:save()
if not ok then
  -- error when saving session
end

session:touch

syntax: ok, err = session:touch()

Updates idling offset of the session by sending an updated session cookie. It only sends the client cookie and never calls any backend session store APIs. Normally the session:refresh is used to call this indirectly. In error case it returns nil and an error message, otherwise true. With exchange_once enabled, a session that another request has already saved (exchanged) is not touched, and true is returned, and a session that was revoked (destroyed or logged out) after it was opened returns nil and "session revoked".

local session, err, exists = require "resty.session".open()
if exists then
  ok, err = session:touch()
end

session:refresh

syntax: ok, err = session:refresh()

Either saves the session (creating a new session id) or touches the session depending on whether the rolling timeout is getting closer, which means by default when 3/4 of rolling timeout is spent, that is 45 minutes with default rolling timeout of an hour. The touch has a threshold, by default one minute, so it may be skipped in some cases (you can call session:touch() to force it). In error case it returns nil and an error message, otherwise true. With exchange_once enabled, a session that another request has already saved (exchanged) is not refreshed, and true is returned.

local session, err, exists = require "resty.session".open()
if exists then
  local ok, err = session:refresh()
end

The above code looks a bit like session.start() helper.

session:logout

syntax: ok, err = session:logout()

Logout either destroys the session or just clears the data for the current audience, and saves it (logging out from the current audience). In error case it returns nil and an error message, otherwise true.

local session, err, exists = require "resty.session".open()
if exists then
  local ok, err = session:logout()
end

session:destroy

syntax: ok, err = session:destroy()

Destroy the session and clear the cookies. In error case it returns nil and an error message, otherwise true. The cookies are cleared and the session closed also when the session cannot be revoked (or deleted from the storage), and then the error is returned.

local session, err, exists = require "resty.session".open()
if exists then
  local ok, err = session:destroy()
end

session:close

syntax: session:close()

Just closes the session instance so that it cannot be used anymore.

local session = require "resty.session".new()
session:set_subject("john")
local ok, err = session:save()
if not ok then
  -- error when saving session
end
session:close()

session:set_data

syntax: session:set_data(data)

Set session data. The data needs to be a table.

local session, err, exists = require "resty.session".open()
if not exists then
   session:set_data({
     cart = {},
   })
  session:save()
end

session:get_data

syntax: data = session:get_data()

Get session data.

local session, err, exists = require "resty.session".open()
if exists then
  local data = session:get_data()
  ngx.req.set_header("Authorization", "Bearer " .. data.access_token)
end

session:set

syntax: session:set(key, value)

Set a value in session.

local session, err, exists = require "resty.session".open()
if not exists then
  session:set("access-token", "eyJ...")
  session:save()
end

session:get

syntax: value = session:get(key)

Get a value from session.

local session, err, exists = require "resty.session".open()
if exists then
  local access_token = session:get("access-token")
  ngx.req.set_header("Authorization", "Bearer " .. access_token)
end

session:set_audience

syntax: session:set_audience(audience)

Set session audience.

local session = require "resty.session".new()
session.set_audience("my-service")

session:get_audience

syntax: audience = session:get_audience()

Set session subject.

session:set_subject

syntax: session:set_subject(subject)

Set session audience.

local session = require "resty.session".new()
session.set_subject("[email protected]")

session:get_subject

syntax: subject = session:get_subject()

Get session subject.

local session, err, exists = require "resty.session".open()
if exists then
  local subject = session.get_subject()
end

session:set_sid

syntax: session:set_sid(sid)

Set the session id given by an identity provider for the current audience, such as the sid claim of OpenID Connect or the SessionIndex of SAML (nil removes it). It is not the id of this session, which is the id property of session:get_property.

local session = require "resty.session".new()
session:set_sid(id_token.sid)

session:get_sid

syntax: sid = session:get_sid()

Get the session id given by an identity provider for the current audience.

local session, err, exists = require "resty.session".open()
if exists then
  local sid = session:get_sid()
end

session:set_issuer

syntax: session:set_issuer(issuer)

Set the issuer that authenticated the subject of the current audience, such as the iss claim of OpenID Connect (nil removes it). Subjects and sids are unique only within their issuer, so set it when the sessions can be authenticated by more than one issuer.

local session = require "resty.session".new()
session:set_issuer(id_token.iss)

session:get_issuer

syntax: issuer = session:get_issuer()

Get the issuer of the current audience.

local session, err, exists = require "resty.session".open()
if exists then
  local issuer = session:get_issuer()
end

session:get_property

syntax: value = session:get_property(name)

Get session property. Possible property names:

  • "id": 43 bytes session id (same as nonce, but base64 url-encoded)
  • "nonce": 32 bytes nonce (same as session id but in raw bytes)
  • "audience": Current session audience
  • "subject": Current session subject
  • "timeout": Closest timeout (in seconds) (what's left of it)
  • "idling-timeout"`: Session idling timeout (in seconds) (what's left of it)
  • "rolling-timeout"`: Session rolling timeout (in seconds) (what's left of it)
  • "absolute-timeout"`: Session absolute timeout (in seconds) (what's left of it)

Note: the returned value may be nil.

local session, err, exists = require "resty.session".open()
if exists then
  local timeout = session.get_property("timeout")
end

session:set_remember

syntax: session:set_remember(value)

Set persistent sessions on/off.

In many login forms user is given an option for "remember me". You can call this function based on what user selected.

local session = require "resty.session".new()
if ngx.var.args.remember then
  session:set_remember(true)
end
session:set_subject(ngx.var.args.username)
session:save()

session:get_remember

syntax: remember = session:get_remember()

Get state of persistent sessions.

local session, err, exists = require "resty.session".open()
if exists then
  local remember = session.get_remember()
end

session:is_existing

syntax: existing = session:is_existing()

Returns true when the request carried an existing session, that is when session:open succeeded (the same as the exists value returned by session.open and session.start), otherwise false. It keeps returning true after the session is saved, logged out, or destroyed, and stays false when a new session is saved.

local session = require "resty.session".start()
if not session:is_existing() then
  -- the user did not have a session before this request
end

session:is_stale

syntax: stale = session:is_stale()

Returns true when the session is known to be stale, that is when another request has already exchanged (saved) it with exchange_once enabled, otherwise false. A stale session can still be read, logged out, and destroyed, but session:save returns nil, "session is stale", and session:touch and session:refresh return true without sending a cookie.

With server-side storage, a session is only known to be stale after it is saved, touched, or refreshed, so false does not mean that no other request has exchanged it.

local session = require "resty.session".start()
if session:is_stale() then
  -- another request has the new session cookie
end

session:is_reused

syntax: reused = session:is_reused()

Returns true when session:open rejected the session as reused (an exchanged cookie session used again after stale_ttl), otherwise false. The session is then a new session. See Reused Sessions.

local session = require "resty.session".open()
if session:is_reused() then
  ngx.log(ngx.WARN, "reused session of ", session:get_reused().subject)
end

session:get_reused

syntax: reused = session:get_reused()

Returns the identity of the reused session ({ audience, subject, sid, issuer }) when session:is_reused returns true, otherwise nil.

local session = require "resty.session".open()
local reused = session:get_reused()
if reused then
  require "resty.session".revoke({ issuer = reused.issuer, sid = reused.sid })
end

session:is_closed

syntax: closed = session:is_closed()

Returns true when the session is closed (destroyed, logged out from its last audience, or closed), otherwise false. Most methods raise an error when they are called on a closed session.

local session = require "resty.session".open()
session:logout()
if not session:is_closed() then
  -- logged out from one audience, the session has other audiences
end

session:clear_request_cookie

syntax: ok, err = session:clear_request_cookie()

Modifies the request headers by removing the session related cookies. This is useful when you use the session library on a proxy server and don't want the session cookies to be forwarded to the upstream service. In error case it returns nil and an error message, otherwise true (which can be ignored).

local session, err, exists = require "resty.session".open()
if exists then
  session:clear_request_cookie()
end

session:set_headers

syntax: ok, err = session:set_headers(arg1, arg2, ...)

Sets request and response headers based on configuration. In error case it returns nil and an error message, otherwise true (that can be ignored).

local session, err, exists = require "resty.session".open({
  request_headers = { "audience", "subject", "id" },
  response_headers = { "timeout", "idling-timeout", "rolling-timeout", "absolute-timeout" },
})
if exists then
  session:set_headers()
end

When called without arguments it will set request headers configured with request_headers and response headers configured with response_headers.

See configuration for possible header names.

session:set_request_headers

syntax: ok, err = session:set_request_headers(arg1, arg2, ...)

Set request headers. In error case it returns nil and an error message, otherwise true (that can be ignored).

local session, err, exists = require "resty.session".open()
if exists then
  session:set_request_headers("audience", "subject", "id")
end

When called without arguments it will set request headers configured with request_headers.

See configuration for possible header names.

session:set_response_headers

syntax: ok, err = session:set_response_headers(arg1, arg2, ...)

Set request headers. In error case it returns nil and an error message, otherwise true (that can be ignored).

local session, err, exists = require "resty.session".open()
if exists then
  session:set_response_headers("timeout", "idling-timeout", "rolling-timeout", "absolute-timeout")
end

When called without arguments it will set request headers configured with response_headers.

See configuration for possible header names.

session.info:set

syntax: session.info:set(key, value)

Set a value in session information store. Session information store may be used in scenarios when you want to store data on server side storage, but do not want to create a new session and send a new session cookie. The information store data is not considered when checking authentication tag or message authentication code. Thus if you want to use this for data that needs to be encrypted, you need to encrypt value before passing it to thus function.

local session, err, exists = require "resty.session".open()
if exists then
  session.info:set("last-access", ngx.now())
  session.info:save()
end

With cookie storage this still works, but it is then almost the same as session:set.

session.info:get

syntax: value = session.info:get(key)

Get a value from session information store.

local session, err, exists = require "resty.session".open()
if exists then
  local last_access = session.info:get("last-access")
end

session.info:save

syntax: ok, err = session.info:save()

Save information. Only updates backend storage. Does not send a new cookie (except with cookie storage).

The session is only replaced in the storage if it still exists, so saving the information of a session that was destroyed elsewhere (e.g. a logout on another server) returns nil, "unable to load session" instead of bringing the session back. This is atomic with all the built-in storages except file and dshm, which check that the session exists just before they write it.

When another request has already saved (exchanged) the session, its old session is kept only for stale_ttl, but saving its information keeps it for its whole lifetime. With exchange_once, session.info:save checks this first (one storage read), and returns nil, "session is stale".

local session = require "resty.session".new()
session.info:set("last-access", ngx.now())
local ok, err = session.info:save()

Cookie Format

[ HEADER -------------------------------------------------------------------------------------]
[ Type || Flags || SID || Created at || Rolling Offset || Size || Tag || Idling Offset || Mac ]
[ 1B   || 2B    || 32B || 5B         || 4B             || 3B   || 16B || 3B            || 16B ]

and

[ PAYLOAD --]
[ Data  *B  ]

Both the HEADER and PAYLOAD are base64 url-encoded before putting in a Set-Cookie header. When using a server side storage, the PAYLOAD is not put in the cookie. With cookie storage the base64 url-encoded header is concatenated with base64 url-encoded payload.

The HEADER is fixed size 82 bytes binary or 110 bytes in base64 url-encoded form.

Header fields explained:

  • Type: number 1 binary packed in a single little endian byte (currently the only supported type).
  • Flags: binary packed flags (short) in a two byte little endian form.
  • SID: 32 bytes of crypto random data (Session ID).
  • Created at: binary packed secs from epoch in a little endian form, truncated to 5 bytes.
  • Rolling Offset: binary packed secs from creation time in a little endian form (integer).
  • Size: binary packed data size in a three byte little endian form.
  • Tag: 16 bytes of authentication tag from AES-256-GCM encryption of the data.
  • Idling Offset: binary packed secs from creation time + rolling offset in a little endian form, truncated to 3 bytes.
  • Mac: 16 bytes message authentication code of the header.

Data Encryption

  1. Initial keying material (IKM):
    1. derive IKM from secret by hashing secret with SHA-256, or
    2. use 32 byte IKM when passed to library with ikm
  2. Generate 32 bytes of crypto random session id (sid)
  3. Derive 32 byte encryption key and 12 byte initialization vector with HKDF using SHA-256 (on FIPS-mode it uses PBKDF2 with SHA-256 instead)
    1. Use HKDF extract to derive a new key from ikm to get key (this step can be done just once per ikm):
      • output length: 32
      • digest: "sha256"
      • key: <ikm>
      • mode: extract only
      • info: ""
      • salt: ""
    2. Use HKDF expand to derive 44 bytes of output:
      • output length: 44
      • digest: "sha256"
      • key: <key>
      • mode: expand only
      • info: "encryption:<sid>"
      • salt: ""
    3. The first 32 bytes of output are the encryption key (aes-key), and the last 12 bytes are the initialization vector (iv)
  4. Encrypt plaintext (JSON encoded and optionally deflated) using AES-256-GCM to get ciphertext and tag
    1. cipher: "aes-256-gcm"
    2. key: <aes-key>
    3. iv: <iv>
    4. plaintext: <plaintext>
    5. aad: use the first 47 bytes of header as aad, that includes:
      1. Type
      2. Flags
      3. Session ID
      4. Creation Time
      5. Rolling Offset
      6. Data Size

There is a variation for remember cookies on step 3, where we may use PBKDF2 instead of HKDF, depending on remember_safety setting (we also use it in FIPS-mode). The PBKDF2 settings:

Iteration counts are based on remember_safety setting ("Low", "Medium", "High", "Very High"), if remember_safety is set to "None", we will use the HDKF as above.

Note: For backwards compatibility, we disabled the SP800-132 compliance checks on FIPS-mode. This checks that the salt length is at least 128 bits, the derived key length is at least 112 bits, and that the iteration count is at least 1000. These checks are disabled by default in OpenSSL's default provider, but are enabled by default in the FIPS provider.

Cookie Header Authentication

  1. Derive 32 byte authentication key (mac_key) with HKDF using SHA-256 (on FIPS-mode it uses PBKDF2 with SHA-256 instead):
    1. Use HKDF extract to derive a new key from ikm to get key (this step can be done just once per ikm and reused with encryption key generation):
      • output length: 32
      • digest: "sha256"
      • key: <ikm>
      • mode: extract only
      • info: ""
      • salt: ""
    2. Use HKDF expand to derive 32 bytes of mac-key:
      • output length: 32
      • digest: "sha256"
      • key: <key>
      • mode: expand only
      • info: "authentication:<sid>"
      • salt: ""
  2. Calculate message authentication code using HMAC-SHA256:
    • digest: "sha256"
    • key: <mac-key>
    • message: use the first 66 bytes of header, that includes:
      1. Type
      2. Flags
      3. Session ID
      4. Creation Time
      5. Rolling Offset
      6. Data Size
      7. Tag
      8. Idling Offset

Custom Storage Interface

If you want to implement custom storage, you need to implement following interface:

---
-- <custom> backend for session library
--
-- @module <custom>


---
-- Storage
-- @section instance


local metatable = {}


metatable.__index = metatable


function metatable.__newindex()
  error("attempt to update a read-only table", 2)
end


---
-- Store session data.
--
-- @function instance:set
-- @tparam string name cookie name
-- @tparam string key session key
-- @tparam string value session value
-- @tparam number ttl session ttl
-- @tparam number current_time current time
-- @tparam[opt] string old_key old session id
-- @tparam string stale_ttl stale ttl
-- @tparam[opt] table metadata table of metadata
-- @treturn true|nil ok
-- @treturn string error message
function metatable:set(name, key, value, ttl, current_time, old_key, stale_ttl, metadata)
  -- NYI
end


---
-- Store session data only if the key does not exist (atomically). Only
-- needed with `exchange_once`.
--
-- @function instance:add
-- @tparam string name cookie name
-- @tparam string key session key
-- @tparam string value session value
-- @tparam number ttl session ttl
-- @tparam number current_time current time
-- @treturn true|false|nil `true` when added, `false` when the key already exists
-- @treturn string error message
function metatable:add(name, key, value, ttl, current_time)
  -- NYI
end


---
-- Store session data only if the key exists (atomically when the storage
-- supports it). Optional: used by `session.info:save`, so that it does not
-- bring back a session that was destroyed (or that expired) elsewhere. Without
-- it, `session.info:save` checks that the session exists before it sets it, when
-- the session was read from the storage cache.
--
-- @function instance:replace
-- @tparam string name cookie name
-- @tparam string key session key
-- @tparam string value session value
-- @tparam number ttl session ttl
-- @tparam number current_time current time
-- @treturn true|false|nil `true` when replaced, `false` when the key does not exist
-- @treturn string error message
function metatable:replace(name, key, value, ttl, current_time)
  -- NYI
end


---
-- Retrieve session data.
--
-- @function instance:get
-- @tparam string name cookie name
-- @tparam string key session key
-- @treturn string|nil session data
-- @treturn string error message
function metatable:get(name, key)
  -- NYI
end


---
-- Delete session data.
--
-- @function instance:delete
-- @tparam string name cookie name
-- @tparam string key session key
-- @tparam[opt] table metadata  session meta data
-- @treturn boolean|nil session data
-- @treturn string error message
function metatable:delete(name, key, current_time, metadata)
  -- NYI
end


local storage = {}


---
-- Constructors
-- @section constructors


---
-- Configuration
-- @section configuration


---
-- <custom> storage backend configuration
-- @field <field-name> TBD
-- @table configuration


---
-- Create a <custom> storage.
--
-- This creates a new shared memory storage instance.
--
-- @function module.new
-- @tparam[opt]  table   configuration  <custom> storage @{configuration}
-- @treturn      table                  <custom> storage instance
function storage.new(configuration)
  -- NYI
  -- return setmetatable({}, metatable)
end


return storage

Please check the existing implementations for the defails. And please make a pull-request so that we can integrate it directly to library for other users as well.

License

lua-resty-session uses two clause BSD license.

Copyright (c) 2014 – 2026 Aapo Talvensaari, 2022 – 2026 Samuele Illuminati
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this
  list of conditions and the following disclaimer in the documentation and/or
  other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES

Jelajahi proyek terkait

Memuat…