Skip to main content
Version: 4.1

Recipe: SQL users

Many installations already have their accounts in a database: a hosting panel, a CRM, or a self-written user administration. This recipe lets Nauthilus authenticate against such a table without copying the accounts anywhere. It also stores TOTP secrets and recovery codes in the same database when users enrol a second factor.

Interfaces: Lua backend with password check, account listing, and MFA callbacks.
Download: sql-users.tar.gz

Read Flat-file users first; this page only explains what is new.

What happens​

  1. MariaDB creates the tables and three demo accounts on its first start.
  2. For a login, the Lua backend looks the user up by login name or mail address, with a read-only database user, and compares the password hash.
  3. Disabled accounts are treated as unknown, and the account listing leaves them out.
  4. When a user enrols TOTP or recovery codes, Nauthilus calls the MFA callbacks of the backend, which write with a second database user that may change only those columns.

Start and test​

docker compose up -d --wait
./test.sh

MariaDB keeps its data in the volume mariadb_data. docker compose down -v removes it, and the next start imports the demo data again.

The stack​

docker-compose.yml
# Lua Cookbook recipe "SQL users".
# Start with: docker compose up -d --wait Test with: ./test.sh Stop with: docker compose down -v
name: cookbook-sql-users

services:
valkey:
image: valkey/valkey:8-alpine
command: ["valkey-server", "--save", "", "--appendonly", "no"]
healthcheck:
test: ["CMD", "valkey-cli", "ping"]
interval: 5s
timeout: 3s
retries: 20

mariadb:
image: mariadb:11.8
environment:
MARIADB_DATABASE: cookbook
MARIADB_ROOT_PASSWORD: cookbook-root
volumes:
# Runs 01-schema.sql once, when the database volume is created.
- ./mariadb/initdb:/docker-entrypoint-initdb.d:ro
- mariadb_data:/var/lib/mysql
healthcheck:
test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"]
interval: 5s
timeout: 5s
retries: 30

nauthilus:
image: ${NAUTHILUS_IMAGE:-ghcr.io/croessner/nauthilus:v4.2.0}
depends_on:
valkey:
condition: service_healthy
mariadb:
condition: service_healthy
environment:
# Optional switch for the Lua JIT (Nauthilus 4.2 and later; earlier releases ignore it).
NAUTHILUS_AUTH_BACKENDS_LUA_BACKEND_DEFAULT_JIT: ${NAUTHILUS_LUA_JIT:-true}
ports:
- "127.0.0.1:28082:8080"
volumes:
- ./nauthilus/nauthilus.yml:/etc/nauthilus/nauthilus.yml:ro
- ./nauthilus/lua:/etc/nauthilus/lua:ro
healthcheck:
test: ["CMD", "/usr/app/healthcheck", "--url", "http://127.0.0.1:8080/healthz"]
interval: 5s
timeout: 3s
retries: 30

volumes:
mariadb_data:

MariaDB runs every file in /docker-entrypoint-initdb.d once, when its data volume is new. Nauthilus waits until the database health check reports InnoDB as ready.

The database​

mariadb/initdb/01-schema.sql
-- Account table of the "SQL users" recipe. The Lua backend reads it with a read-only connection for logins and
-- writes the MFA columns through a second connection.
CREATE TABLE accounts (
id INT NOT NULL AUTO_INCREMENT,
username VARCHAR(255) NOT NULL,
account VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
display_name VARCHAR(255) NOT NULL,
mail VARCHAR(255) NOT NULL,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
totp_secret VARCHAR(255) NULL,
PRIMARY KEY (id),
UNIQUE KEY username_idx (username),
UNIQUE KEY account_idx (account)
);

CREATE TABLE recovery_codes (
account_id INT NOT NULL,
code VARCHAR(255) NOT NULL,
PRIMARY KEY (account_id, code),
FOREIGN KEY (account_id) REFERENCES accounts (id) ON DELETE CASCADE
);

-- alice: alice-secret ({SSHA512}), bob: bob-secret (bcrypt), dave: dave-secret but disabled.
INSERT INTO accounts (username, account, password, display_name, mail, enabled) VALUES
('alice', 'alice@example.test',
'{SSHA512}bIs2FISYSUHHJuB7yzQJBQbnSc2TUG1toOZKJ96a0H5teLaswlqMRRMGbXq99MuZvKvW5aHXJQdPjoL/foemUmNvb2tib29r',
'Alice Example', 'alice@example.test', TRUE),
('bob', 'bob@example.test',
'$2y$10$vUNCt8LDP9xgBCJkIRd7k.RzPdWOIqbK2ijZTTDEVb6blyR.KLJQC',
'Bob Example', 'bob@example.test', TRUE),
('dave', 'dave@example.test',
'$2y$10$jTeWfTpO/LLsuC9Z61sbzuKwZBUZKNJUf1rJPuXPZJElxlkcdn77S',
'Dave Example (disabled)', 'dave@example.test', FALSE);

-- Two database users: one that can only read, one that may change the MFA columns.
CREATE USER 'nauthilus_ro'@'%' IDENTIFIED BY 'cookbook-ro';
GRANT SELECT ON cookbook.* TO 'nauthilus_ro'@'%';

CREATE USER 'nauthilus_mfa'@'%' IDENTIFIED BY 'cookbook-mfa';
GRANT SELECT, UPDATE (totp_secret) ON cookbook.accounts TO 'nauthilus_mfa'@'%';
GRANT SELECT, INSERT, DELETE ON cookbook.recovery_codes TO 'nauthilus_mfa'@'%';
  • accounts has a login name (username), the canonical account name (account, here the mail address), the password hash, display data, an enabled flag, and a column for the TOTP secret.
  • recovery_codes holds the one-time recovery codes of an account.
  • Two database users separate the duties: nauthilus_ro can only read, nauthilus_mfa can only change the TOTP column and the recovery codes. A mistake or an attack in the login path cannot change passwords.

The configuration​

nauthilus/nauthilus.yml
# Nauthilus configuration of the "SQL users" Lua Cookbook recipe.
# Interfaces shown: Lua backend with password check, account listing, and MFA callbacks.

runtime:
instance_name: "cookbook-sql-users"

servers:
http:
address: "0.0.0.0:8080"

observability:
log:
level: "info"
json: false

storage:
redis:
primary:
address: "valkey:6379"
database_number: 0
prefix: "nt:"
positive_cache_ttl: "1h"
negative_cache_ttl: "5m"
# Demo values only. Generate your own random strings for a real installation.
password_nonce: "cookbookPasswordNonce02"
encryption_secret: "cookbookEncryption02"

auth:
backchannel:
basic_auth:
enabled: true
# Scoped credentials: each caller holds only the scopes it needs. Demo passwords only.
users:
# The mail server (or curl in test.sh) checks logins.
- username: "mailserver"
password: "mailserver-backchannel-secret"
scopes:
- "nauthilus:authenticate"
# The administrator lists accounts and manages TOTP state.
- username: "admin"
password: "admin-backchannel-secret"
scopes:
- "nauthilus:authenticate"
- "nauthilus:list_accounts"
- "nauthilus:mfa_write"

backends:
# "cache" answers repeated logins from Redis; "lua" asks backend.lua.
order:
- "cache"
- "lua"

lua:
backend:
default:
backend_script_path: "/etc/nauthilus/lua/backend.lua"
# require() finds the bundled helpers and files in /etc/nauthilus/lua.
package_path: "/usr/app/lua-plugins.d/share/?.lua;/etc/nauthilus/lua/?.lua"
backend_number_of_workers: 2

# Which requests use this Lua backend. "account-provider" is the protocol of the account listing
# (mode=list-accounts) and "idp" the one of MFA changes; without them those calls find no backend.
search:
- protocol:
- "imap"
- "smtp"
- "account-provider"
- "idp"
cache_name: "sql"

New compared with the flat-file recipe:

  • The admin credential holds nauthilus:mfa_write, the scope of the MFA backchannel API, instead of the cache-flush scope.
  • search adds the protocol idp. Nauthilus looks the user up with this protocol before it changes MFA data, so the backend must be responsible for it.

The Lua backend​

nauthilus/lua/backend.lua
-- backend.lua
-- Lua backend of the "SQL users" recipe. Accounts live in MariaDB. Logins and lookups use a read-only database
-- user; the MFA callbacks use a second user that may only change the TOTP column and the recovery-code table.

local nauthilus_util = require("nauthilus_util")
local nauthilus_password = require("nauthilus_password")
local db = require("db")

local READ_DSN = os.getenv("COOKBOOK_DB_READ_DSN") or "nauthilus_ro:cookbook-ro@tcp(mariadb:3306)/cookbook"
local MFA_DSN = os.getenv("COOKBOOK_DB_MFA_DSN") or "nauthilus_mfa:cookbook-mfa@tcp(mariadb:3306)/cookbook"

-- shared = true keeps one connection pool per DSN for the whole Nauthilus process instead of one per request.
local READ_OPTIONS = { shared = true, max_connections = 8, read_only = true }
local MFA_OPTIONS = { shared = true, max_connections = 2, read_only = false }

-- run executes one prepared statement and closes it. kind is "query" (returns rows) or "exec" (returns counts).
-- Closing matters: MariaDB keeps every prepared statement of a connection until it is closed.
local function run(dsn, options, kind, sql, ...)
local conn, err_open = db.open("mysql", dsn, options)
nauthilus_util.if_error_raise(err_open)

local statement, err_prepare = conn:stmt(sql)
nauthilus_util.if_error_raise(err_prepare)

local result, err_run = statement[kind](statement, ...)
statement:close()
nauthilus_util.if_error_raise(err_run)

return result
end

-- first_row returns the first row of a query result as a table keyed by column name, or nil.
local function first_row(result)
if result.rows == nil or #result.rows == 0 then
return nil
end

local record = {}

for index, column in ipairs(result.columns) do
record[column] = result.rows[1][index]
end

return record
end

-- find_account looks a user up by login name or by mail address.
local function find_account(username)
return first_row(run(READ_DSN, READ_OPTIONS, "query",
"SELECT id, username, account, password, display_name, mail, enabled, totp_secret " ..
"FROM accounts WHERE username = ? OR account = ? LIMIT 1",
username, username))
end

-- is_enabled reads the BOOLEAN column, which the driver may return as a number or a string.
local function is_enabled(value)
return value == 1 or value == "1" or value == true
end

function nauthilus_backend_verify_password(request)
local backend_result = nauthilus_backend_result.new()
local record = find_account(request.username)

if record == nil or not is_enabled(record.enabled) then
backend_result:user_found(false)
backend_result:authenticated(false)

return nauthilus_builtin.BACKEND_RESULT_OK, backend_result
end

local authenticated = true

if not request.no_auth then
local match, err_compare = nauthilus_password.compare_passwords(record.password, request.password or "")
nauthilus_util.if_error_raise(err_compare)

authenticated = match
end

local attributes = {
account = record.account,
display_name = record.display_name,
mail = record.mail,
}

-- Nauthilus reads the TOTP secret from the field named by totp_secret_field below.
if record.totp_secret ~= nil and record.totp_secret ~= "" then
attributes.totp_secret = record.totp_secret
end

backend_result:user_found(true)
backend_result:authenticated(authenticated)
backend_result:account_field("account")
backend_result:display_name_field("display_name")
backend_result:totp_secret_field("totp_secret")
backend_result:attributes(attributes)

return nauthilus_builtin.BACKEND_RESULT_OK, backend_result
end

function nauthilus_backend_list_accounts(request)
local result = run(READ_DSN, READ_OPTIONS, "query",
"SELECT account FROM accounts WHERE enabled = TRUE ORDER BY id")
local accounts = {}

for _, row in ipairs(result.rows or {}) do
accounts[#accounts + 1] = row[1]
end

return nauthilus_builtin.BACKEND_RESULT_OK, accounts
end

-- MFA callbacks. Nauthilus calls them when a user enrolls or removes TOTP, for example through the identity
-- provider or the MFA backchannel API.

function nauthilus_backend_add_totp(request)
run(MFA_DSN, MFA_OPTIONS, "exec",
"UPDATE accounts SET totp_secret = ? WHERE username = ? OR account = ?",
request.totp_secret, request.username, request.username)

return nauthilus_builtin.BACKEND_RESULT_OK
end

function nauthilus_backend_delete_totp(request)
run(MFA_DSN, MFA_OPTIONS, "exec",
"UPDATE accounts SET totp_secret = NULL WHERE username = ? OR account = ?",
request.username, request.username)

return nauthilus_builtin.BACKEND_RESULT_OK
end

function nauthilus_backend_add_totp_recovery_codes(request)
local record = find_account(request.username)

if record == nil then
return nauthilus_builtin.BACKEND_RESULT_FAIL
end

-- New codes replace the old ones.
run(MFA_DSN, MFA_OPTIONS, "exec", "DELETE FROM recovery_codes WHERE account_id = ?", record.id)

for _, code in ipairs(request.totp_recovery_codes or {}) do
run(MFA_DSN, MFA_OPTIONS, "exec",
"INSERT INTO recovery_codes (account_id, code) VALUES (?, ?)", record.id, code)
end

return nauthilus_builtin.BACKEND_RESULT_OK
end

function nauthilus_backend_delete_totp_recovery_codes(request)
local record = find_account(request.username)

if record ~= nil then
run(MFA_DSN, MFA_OPTIONS, "exec", "DELETE FROM recovery_codes WHERE account_id = ?", record.id)
end

return nauthilus_builtin.BACKEND_RESULT_OK
end

How it works:

  • db.open comes from the bundled gopher-lua-libs. With shared = true, Nauthilus keeps one connection pool per DSN for the whole process, so a login does not open a new database connection. read_only = true only marks transactions as read-only; the real protection is the database user nauthilus_ro, which may only SELECT.
  • run is the only function that talks to the database. It prepares a statement, runs it with bound parameters, and closes it. Bound parameters (?) keep user input out of the SQL text, so a username such as x' OR '1'='1 is only ever a value. Closing matters as well: MariaDB keeps every prepared statement until it is closed, and after max_prepared_stmt_count (16382 by default) statements it refuses new ones, which would make every login fail. The test checks that no statement stays open.
  • find_account accepts the login name or the mail address.
  • nauthilus_backend_verify_password treats a disabled account like an unknown one, so a disabled user learns nothing from the answer. totp_secret_field("totp_secret") tells Nauthilus which attribute holds the TOTP secret, so the identity provider can ask for a second factor.
  • nauthilus_backend_list_accounts returns the enabled accounts.
  • The MFA callbacks are called by the identity provider's MFA self-service and by the MFA backchannel API. Each returns BACKEND_RESULT_OK or BACKEND_RESULT_FAIL. nauthilus_backend_add_totp_recovery_codes receives the codes as request.totp_recovery_codes, a Lua list.

Try the MFA API by hand. Use the account name (the mail address), because Nauthilus checks that the user it looked up is the user named in the request:

curl -u admin:admin-backchannel-secret -H 'Content-Type: application/json' \
-d '{"backend":"lua","username":"bob@example.test","codes":["aaaa-1111","bbbb-2222"]}' \
http://127.0.0.1:28082/api/v1/mfa-backchannel/totp/recovery-codes

docker compose exec mariadb mariadb -uroot -pcookbook-root cookbook -e 'SELECT * FROM recovery_codes'
Since Nauthilus 4.1.3

nauthilus_backend_add_totp receives request.totp_secret since 4.1.3. Earlier 4.x releases called it with an empty value, so the secret was not stored.

WebAuthn credentials use four more callbacks (nauthilus_backend_get_webauthn_credentials and others), see Backend plugins. They follow the same pattern.

What the test checks​

test.sh
#!/usr/bin/env bash
# Checks the "SQL users" recipe. Start the stack first: docker compose up -d --wait
cd "$(dirname "$0")" || exit 1
. ../lib/cookbook.sh

NAUTHILUS_URL="${NAUTHILUS_URL:-http://127.0.0.1:28082}"
ADMIN="admin:admin-backchannel-secret"

# sql runs one statement as the MariaDB root user and prints the result without headers.
sql() {
docker compose exec -T mariadb mariadb -uroot -pcookbook-root -N -B cookbook -e "$1"
}

# mfa calls the MFA backchannel API. Arguments: method path json
mfa() {
http "$1" "/api/v1/mfa-backchannel$2" -u "$ADMIN" -H 'Content-Type: application/json' -d "$3"
}

section "Lua backend: password checks"
auth alice alice-secret imap 192.0.2.10
expect_auth_status "OK" "alice logs in with her username ({SSHA512} hash)"
expect_body_contains '"account":["alice@example.test"]' "the account field is the mail address"

auth alice@example.test alice-secret imap 192.0.2.10
expect_auth_status "OK" "alice logs in with her mail address"

auth bob bob-secret smtp 192.0.2.10
expect_auth_status "OK" "bob logs in (bcrypt hash)"

auth bob not-bobs-password imap 192.0.2.11
expect_auth_status "Invalid login or password" "a wrong password is rejected"

auth dave dave-secret imap 192.0.2.12
expect_auth_status "Invalid login or password" "the disabled account dave is rejected"

section "Lua backend: account listing"
http GET '/api/v1/auth/json?mode=list-accounts' -u "$ADMIN" -H 'Accept: application/json'
expect_body_contains '"alice@example.test"' "list-accounts contains alice"
expect_body_contains '"bob@example.test"' "list-accounts contains bob"
case "$last_body" in
*dave*) fail "list-accounts must not contain the disabled account dave" ;;
*) pass "list-accounts leaves out the disabled account dave" ;;
esac

section "Lua backend: MFA callbacks"
mfa POST /totp/recovery-codes '{"backend":"lua","username":"bob@example.test","codes":["aaaa-1111","bbbb-2222"]}'
expect_status 200 "recovery codes are accepted"
expect_equal "2" "$(sql 'SELECT COUNT(*) FROM recovery_codes')" "nauthilus_backend_add_totp_recovery_codes stored two codes"

mfa DELETE /totp/recovery-codes '{"backend":"lua","username":"bob@example.test"}'
expect_equal "0" "$(sql 'SELECT COUNT(*) FROM recovery_codes')" "nauthilus_backend_delete_totp_recovery_codes removed them"

mfa POST /totp '{"backend":"lua","username":"bob@example.test","totp_secret":"JBSWY3DPEHPK3PXP"}'
expect_status 200 "a TOTP secret is accepted"
expect_equal "JBSWY3DPEHPK3PXP" "$(sql "SELECT totp_secret FROM accounts WHERE username = 'bob'")" "nauthilus_backend_add_totp stored the secret"

sql "UPDATE accounts SET totp_secret = 'JBSWY3DPEHPK3PXP' WHERE username = 'bob'"
mfa DELETE /totp '{"backend":"lua","username":"bob@example.test"}'
expect_equal "NULL" "$(sql "SELECT totp_secret FROM accounts WHERE username = 'bob'")" "nauthilus_backend_delete_totp removed the secret"

section "Prepared statements are closed"
for i in $(seq 1 30); do auth "bob" "bob-secret-$i" imap "192.0.2.$((i + 20))"; done
expect_equal "0" "$(sql "SHOW GLOBAL STATUS LIKE 'Prepared_stmt_count'" | awk '{ print $2 }')" "MariaDB holds no open prepared statements"

finish

Ideas for your own changes​

  • Point COOKBOOK_DB_READ_DSN and COOKBOOK_DB_MFA_DSN (environment of the nauthilus service) at your own database and adapt the column names in find_account.
  • Use PostgreSQL: db.open("postgres", "postgres://user:pass@host/db?sslmode=disable", options); placeholders are $1, $2, … instead of ?.
  • Return more attributes, for example a quota or a mail store, for your mail server.