Skip to main content
Version: Next

Recipe: Flat-file users

A small office, a test environment, or an appliance often has a handful of mail accounts and no directory server. This recipe keeps the accounts in one text file, similar to /etc/passwd, and lets Nauthilus check passwords against it. Adding a user means adding a line.

It is also the best first recipe: it shows how a Nauthilus stack is put together, and the other recipes build on it.

Interfaces: init script, Lua backend (password check and account listing), cache-flush callback.
Download: flatfile-users.tar.gz

What happens​

  1. When Nauthilus starts, the init script reads users.txt and stores every account in nauthilus_cache, an in-memory cache that all Lua scripts of the process share. It also creates a Prometheus counter.
  2. For every login that Nauthilus cannot answer from its Redis cache, the Lua backend looks the user up in the in-memory cache and compares the password with the stored hash.
  3. The account listing API asks the same backend for all account names.
  4. When an administrator flushes the cache for a user, the cache-flush callback tells Nauthilus the account name and one extra Redis key to delete.

Files​

flatfile-users/
├── docker-compose.yml Valkey and Nauthilus
├── test.sh the checks shown below
└── nauthilus/
├── nauthilus.yml Nauthilus configuration
├── users.txt the accounts
└── lua/
├── flatfile_users.lua shared module: parse the file, find users
├── init.lua init script
├── backend.lua Lua backend
└── cache_flush.lua cache-flush callback

Start and test​

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

Check a login by hand. The backchannel credential mailserver stands for your mail server, which asks Nauthilus whether a login is valid:

curl -i -u mailserver:mailserver-backchannel-secret \
-H 'Content-Type: application/json' \
-d '{"username":"alice","password":"alice-secret","protocol":"imap","client_ip":"192.0.2.10"}' \
http://127.0.0.1:28081/api/v1/auth/json

The answer has Auth-Status: OK and the attributes that the backend returned. A wrong password gives HTTP 403 and Auth-Status: Invalid login or password.

The stack​

docker-compose.yml
# Lua Cookbook recipe "Flat-file users".
# Start with: docker compose up -d --wait Test with: ./test.sh Stop with: docker compose down
name: cookbook-flatfile-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

nauthilus:
image: ${NAUTHILUS_IMAGE:-ghcr.io/croessner/nauthilus:v4.2.0}
depends_on:
valkey:
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:28081:8080"
volumes:
- ./nauthilus/nauthilus.yml:/etc/nauthilus/nauthilus.yml:ro
- ./nauthilus/users.txt:/etc/nauthilus/users.txt: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
  • valkey is the Redis-compatible store. Nauthilus keeps its login cache, brute-force counters, and other state there. Persistence is off, because a demo does not need it.
  • nauthilus mounts the configuration, the user file, and the Lua directory read-only. The health check asks /healthz, so docker compose up --wait returns only when Nauthilus is ready.
  • NAUTHILUS_IMAGE and NAUTHILUS_LUA_JIT choose the image and the Lua JIT, see Choose the Nauthilus image. Every setting of nauthilus.yml can be overridden by an environment variable in the same way: NAUTHILUS_ plus the upper-case key path with _ between the parts.

The configuration​

nauthilus/nauthilus.yml
# Nauthilus configuration of the "Flat-file users" Lua Cookbook recipe.
# Interfaces shown: init script, Lua backend, cache-flush callback.

runtime:
instance_name: "cookbook-flatfile-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: "cookbookPasswordNonce01"
encryption_secret: "cookbookEncryption01"

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 flushes caches.
- username: "admin"
password: "admin-backchannel-secret"
scopes:
- "nauthilus:authenticate"
- "nauthilus:list_accounts"
- "nauthilus:security_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"
init_script_paths:
- "/etc/nauthilus/lua/init.lua"
cache_flush_script_path: "/etc/nauthilus/lua/cache_flush.lua"
# require() finds the bundled helpers and the recipe's own module flatfile_users.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); without it the listing stays empty.
search:
- protocol:
- "imap"
- "smtp"
- "account-provider"
cache_name: "flatfile"

Block by block:

  • runtime names the instance and lets the HTTP server listen on port 8080 inside the container.
  • storage.redis points to Valkey. positive_cache_ttl and negative_cache_ttl say how long a successful or failed login is remembered, so a mail client that logs in every minute does not reach the backend every time. password_nonce and encryption_secret protect what Nauthilus stores in Redis; use long random values in a real installation.
  • auth.backchannel.basic_auth defines who may call the HTTP API. Each users entry is a scoped credential: mailserver may only check logins (nauthilus:authenticate); admin may also list accounts (nauthilus:list_accounts) and flush caches (nauthilus:security_write).
  • auth.backends.order is the order in which Nauthilus asks its backends: first its own Redis cache, then Lua.
  • auth.backends.lua.backend.default wires the scripts in:
    • backend_script_path: the Lua backend.
    • init_script_paths: scripts that run once at startup.
    • cache_flush_script_path: the cache-flush callback.
    • package_path: where require finds modules. The first entry holds the helpers that ship with Nauthilus, such as nauthilus_util; the second one is the recipe's own directory, so require("flatfile_users") loads flatfile_users.lua.
    • backend_number_of_workers: how many backend requests run in parallel.
  • search says which requests use this backend. imap and smtp are logins; account-provider is the protocol of the account listing (mode=list-accounts). Without it the listing answers with an empty result. cache_name names the cache namespace for these protocols.

The user file​

nauthilus/users.txt
# Flat-file user list for the Nauthilus Lua Cookbook.
# One account per line: username:password-hash:display name:mail:allowed protocols (comma separated)
# Supported hash formats: bcrypt ($2y$/$2b$/$2a$), {SSHA256}/{SSHA512}, and crypt(3) such as $6$ (SHA512-crypt).
alice:$2y$10$ngKMNlOnSLGDyr0hoKOr3.H2WNwc2hSU.ht8m2HB8TVPZZdxuTlYC:Alice Example:alice@example.test:imap,smtp
bob:$6$labsalt01$jH38X/dRFOX8aJZ/gKGi/cEmT4MMm6LuMcRH3ybCBlVM0pHaZIfKmqjjs21HEZ4vndbB65rGYTE1Y1HBqUPjb1:Bob Example:bob@example.test:imap
carol:$6$labsalt02$wszVxt5HFEIpXMd2m18dH8Kqict2XZEWMfj7KbI7MPlSFApH/GGfm7igt2ouEmXKElLY53ij2rSi8JxWm65gq/:Carol Example:carol@example.test:imap,smtp

One line per account: username:password-hash:display name:mail:protocols. The passwords are alice-secret, bob-secret, and carol-secret. Store hashes, never plain passwords. Create them with tools you already have:

htpasswd -nbB -C 10 alice 'alice-secret' | cut -d: -f2 # bcrypt
openssl passwd -6 'bob-secret' # SHA512-crypt

nauthilus_password.compare_passwords recognises bcrypt, {SSHA256}/{SSHA512}, and the usual crypt(3) formats, so hashes from an existing system usually work unchanged.

The shared module​

nauthilus/lua/flatfile_users.lua
-- flatfile_users.lua
-- Shared module of the flat-file recipe. It parses users.txt and keeps the accounts in nauthilus_cache, the in-process
-- cache that every Lua VM of this Nauthilus instance shares. The init script calls load() once at startup; the
-- backend calls ensure_loaded() so it also works when the init script did not run.

local nauthilus_cache = require("nauthilus_cache")

local M = {}

M.USERS_FILE = os.getenv("COOKBOOK_USERS_FILE") or "/etc/nauthilus/users.txt"

local KEY_LOADED = "flatfile:loaded_at"
local KEY_ACCOUNTS = "flatfile:accounts"
local KEY_USER_PREFIX = "flatfile:user:"

-- split returns the fields of a line separated by sep. Empty fields are kept, so "a::b" gives three fields.
local function split(line, sep)
local fields = {}
local start = 1

while true do
local stop = string.find(line, sep, start, true)

if stop == nil then
fields[#fields + 1] = string.sub(line, start)

return fields
end

fields[#fields + 1] = string.sub(line, start, stop - 1)
start = stop + 1
end
end

-- trim removes leading and trailing white space.
local function trim(value)
return (string.gsub(value, "^%s*(.-)%s*$", "%1"))
end

-- parse_protocols turns "imap, smtp" into a set: { imap = true, smtp = true }.
local function parse_protocols(value)
local protocols = {}

for protocol in string.gmatch(value or "", "[^,]+") do
protocol = string.lower(trim(protocol))

if protocol ~= "" then
protocols[protocol] = true
end
end

return protocols
end

-- parse_line returns one account record, or nil for comments, empty lines, and broken lines.
local function parse_line(line)
line = trim(line)

if line == "" or string.sub(line, 1, 1) == "#" then
return nil
end

local fields = split(line, ":")

if #fields < 2 or fields[1] == "" or fields[2] == "" then
return nil
end

return {
username = fields[1],
password = fields[2],
display_name = fields[3] or fields[1],
mail = fields[4] or "",
protocols = parse_protocols(fields[5]),
}
end

-- load reads the users file and replaces the cached accounts. It returns the number of accounts or nil and an error.
function M.load(path)
path = path or M.USERS_FILE

local file, err_open = io.open(path, "r")

if file == nil then
return nil, "cannot open " .. path .. ": " .. tostring(err_open)
end

local accounts = {}

for line in file:lines() do
local record = parse_line(line)

if record ~= nil then
nauthilus_cache.cache_set(KEY_USER_PREFIX .. record.username, record)
accounts[#accounts + 1] = record.username
end
end

file:close()

-- Remove accounts that were deleted from the file since the last load.
local previous = nauthilus_cache.cache_get(KEY_ACCOUNTS) or {}
local current = {}

for _, username in ipairs(accounts) do
current[username] = true
end

for _, username in ipairs(previous) do
if not current[username] then
nauthilus_cache.cache_delete(KEY_USER_PREFIX .. username)
end
end

nauthilus_cache.cache_set(KEY_ACCOUNTS, accounts)
nauthilus_cache.cache_set(KEY_LOADED, os.time())

return #accounts, nil
end

-- ensure_loaded loads the file once if no init script did it before.
function M.ensure_loaded()
if nauthilus_cache.cache_exists(KEY_LOADED) then
return true, nil
end

local _, err = M.load()

return err == nil, err
end

-- find returns the cached record of one user or nil.
function M.find(username)
local record = nauthilus_cache.cache_get(KEY_USER_PREFIX .. tostring(username or ""))

if type(record) ~= "table" then
return nil
end

return record
end

-- accounts returns the list of all usernames in file order.
function M.accounts()
return nauthilus_cache.cache_get(KEY_ACCOUNTS) or {}
end

-- loaded_at returns the Unix time of the last load or nil.
function M.loaded_at()
return nauthilus_cache.cache_get(KEY_LOADED)
end

return M

Both the init script and the backend need the user data, so the logic lives once, in a module. A module is a Lua file that returns a table of functions; require("flatfile_users") returns that table.

  • split and parse_line turn one line into a record. Comments and broken lines are skipped.
  • load reads the file and stores one cache entry per user (flatfile:user:<name>) plus the list of names. One entry per user keeps a lookup small: the backend copies only one record out of the cache, not the whole file. When a user was removed from the file, load deletes the old entry.
  • ensure_loaded loads the file on first use if no init script did, so the backend also works on its own.
  • nauthilus_cache keeps values in the memory of the Nauthilus process. It survives requests but not a restart, which is why the init script fills it at startup.

The init script​

nauthilus/lua/init.lua
-- init.lua
-- Init script of the flat-file recipe. Nauthilus runs it once when the process starts; a configuration reload does
-- not run it again. It loads users.txt into the shared in-process cache and creates the Prometheus counter that the
-- backend increments for every password check.

local nauthilus_util = require("nauthilus_util")
local nauthilus_prometheus = require("nauthilus_prometheus")
local flatfile_users = require("flatfile_users")

function nauthilus_run_hook(request)
nauthilus_prometheus.create_counter_vec(
"cookbook_flatfile_password_checks_total",
"Password checks of the flat-file Lua backend by result",
{ "result" }
)

local count, err = flatfile_users.load()

if err ~= nil then
nauthilus_util.log_error(request.logging, { caller = "init.lua", message = "loading users failed" }, err)

return
end

nauthilus_util.log_info(request.logging, {
caller = "init.lua",
message = "flat-file users loaded",
file = flatfile_users.USERS_FILE,
accounts = count,
})
end

An init script defines nauthilus_run_hook(request). Nauthilus calls it once when the process starts. A configuration reload (SIGHUP) does not run init scripts again, so after editing users.txt restart Nauthilus with docker compose restart nauthilus.

  • create_counter_vec registers the Prometheus counter that the backend increments. Metrics are created once, in an init script; the backend only increments them.
  • nauthilus_util.log_info and log_error write structured log lines. Look for them with docker compose logs nauthilus | grep init.lua.

The Lua backend​

nauthilus/lua/backend.lua
-- backend.lua
-- Lua backend of the flat-file recipe. Nauthilus calls nauthilus_backend_verify_password for every login that is not
-- answered from its Redis cache, and nauthilus_backend_list_accounts for the account listing API.

local nauthilus_util = require("nauthilus_util")
local nauthilus_password = require("nauthilus_password")
local nauthilus_prometheus = require("nauthilus_prometheus")
local flatfile_users = require("flatfile_users")

-- count_check increments the Prometheus counter created by init.lua.
local function count_check(result)
nauthilus_prometheus.increment_counter("cookbook_flatfile_password_checks_total", { result = result })
end

function nauthilus_backend_verify_password(request)
local backend_result = nauthilus_backend_result.new()

local _, err_load = flatfile_users.ensure_loaded()
nauthilus_util.if_error_raise(err_load)

local record = flatfile_users.find(request.username)

if record == nil then
count_check("unknown_user")

backend_result:user_found(false)
backend_result:authenticated(false)

return nauthilus_builtin.BACKEND_RESULT_OK, backend_result
end

-- A no-auth request (for example a Dovecot userdb lookup) only asks whether the user exists.
local authenticated = false

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

authenticated = match
end

count_check(authenticated and "ok" or "wrong_password")

-- Turn the protocol set into a sorted, comma-separated list for the response.
local protocols = {}

for protocol in pairs(record.protocols or {}) do
protocols[#protocols + 1] = protocol
end

table.sort(protocols)

backend_result:user_found(true)
backend_result:authenticated(authenticated)
backend_result:account_field("account")
backend_result:display_name_field("display_name")
backend_result:attributes({
account = record.username,
display_name = record.display_name,
mail = record.mail,
allowed_protocols = table.concat(protocols, ","),
})

return nauthilus_builtin.BACKEND_RESULT_OK, backend_result
end

function nauthilus_backend_list_accounts(request)
local _, err_load = flatfile_users.ensure_loaded()
nauthilus_util.if_error_raise(err_load)

return nauthilus_builtin.BACKEND_RESULT_OK, flatfile_users.accounts()
end

nauthilus_backend_verify_password(request) answers one login. request holds the username, the password, the protocol, the client address, and more (see common request fields). It returns a status and a nauthilus_backend_result object:

  • user_found(false) means "no such user"; authenticated(...) says whether the password matched. Nauthilus turns both into the answer for the mail server, counts failed logins for brute-force protection, and caches the result.
  • request.no_auth is true for lookups without a password, for example a Dovecot userdb query. The backend then only confirms that the user exists.
  • account_field("account") names the attribute that holds the canonical account name, here the username. display_name_field does the same for the display name.
  • attributes({...}) returns data to the caller. The JSON API puts it into the attributes object; header-based endpoints send it as X-Nauthilus-* headers.
  • nauthilus_util.if_error_raise(err) stops the script with an error. Nauthilus then answers with a temporary failure, which is the right reaction when the user file cannot be read: the mail client tries again later.

nauthilus_backend_list_accounts() returns all account names. It is used by mode=list-accounts, for example by a Dovecot doveadm that iterates over all users.

The cache-flush callback​

nauthilus/lua/cache_flush.lua
-- cache_flush.lua
-- Cache-flush callback of the flat-file recipe. Nauthilus calls it for DELETE /api/v1/cache/flush. It tells Nauthilus
-- which account belongs to the user, so no backend lookup is needed, and names one extra Redis key to delete.
-- The recipe writes that key ("<prefix>cookbook:flush-marker:<user>") in test.sh to show that the flush removes it.

local flatfile_users = require("flatfile_users")

function nauthilus_cache_flush(request)
local additional_keys = {
request.redis_prefix .. "cookbook:flush-marker:" .. request.username,
}

local record = flatfile_users.find(request.username)
local account = ""

if record ~= nil then
account = record.username
end

return additional_keys, account
end

DELETE /api/v1/cache/flush removes everything Nauthilus remembers about a user: cached logins, brute-force state, IdP sessions. The callback adds what only you know:

  • The first return value is a list of extra Redis keys to delete. Here it is a marker key that test.sh writes, to make the effect visible; in a real setup it could be a per-user key that your own scripts create.
  • The second return value is the account name. Nauthilus uses it instead of looking the account up in the backends.

Try it:

curl -X DELETE -u admin:admin-backchannel-secret -H 'Content-Type: application/json' \
-d '{"user":"alice"}' http://127.0.0.1:28081/api/v1/cache/flush

What the test checks​

test.sh
#!/usr/bin/env bash
# Checks the "Flat-file 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:28081}"
ADMIN="admin:admin-backchannel-secret"

section "Init script"
if docker compose logs nauthilus 2>/dev/null | grep -q 'flat-file users loaded'; then
pass "init.lua loaded users.txt at startup"
else
fail "init.lua did not log 'flat-file users loaded'"
fi

section "Lua backend: password checks"
auth alice alice-secret imap 192.0.2.10
expect_auth_status "OK" "alice logs in (bcrypt hash)"
expect_body_contains '"display_name":["Alice Example"]' "backend returns the display name"
expect_body_contains '"allowed_protocols":["imap,smtp"]' "backend returns the protocol list"

auth bob bob-secret imap 192.0.2.10
expect_auth_status "OK" "bob logs in (SHA512-crypt hash)"

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

auth mallory secret imap 192.0.2.12
expect_auth_status "Invalid login or password" "an unknown user is rejected"

section "Lua backend: account listing"
http GET '/api/v1/auth/json?mode=list-accounts' -u "$ADMIN" -H 'Accept: application/json'
expect_status 200 "list-accounts answers"
for account in alice bob carol; do
expect_body_contains "\"$account\"" "list-accounts contains $account"
done

section "Cache flush callback"
valkey SET nt:cookbook:flush-marker:alice 1 >/dev/null
http DELETE /api/v1/cache/flush -u "$ADMIN" -H 'Content-Type: application/json' -d '{"user":"alice"}'
expect_status 200 "cache flush answers"
expect_body_contains 'nt:cookbook:flush-marker:alice' "the flush removed the key named by cache_flush.lua"
expect_equal 0 "$(valkey EXISTS nt:cookbook:flush-marker:alice)" "the marker key is gone from Valkey"

section "Prometheus counter created by init.lua"
http GET /metrics
expect_body_contains 'cookbook_flatfile_password_checks_total{result="ok"}' "the backend counts successful checks"
expect_body_contains 'cookbook_flatfile_password_checks_total{result="wrong_password"}' "the backend counts wrong passwords"

finish

The test logs in with both hash types, with a wrong password, and as an unknown user; lists the accounts; flushes the cache and checks that the extra key is gone; and reads the Prometheus counter at /metrics. The helpers auth, http, expect_*, and valkey come from cookbook/lib/cookbook.sh.

Ideas for your own changes​

  • Add a user to users.txt, restart Nauthilus with docker compose restart nauthilus, and log in as that user.
  • Reload the file without a restart: add a custom hook that calls flatfile_users.load(), as the Admin toolkit shows for other hooks.
  • Return the allowed_protocols attribute to your mail server and let it refuse protocols, or move that check into Nauthilus with the Account rules recipe.
  • Replace the file with an HTTP call to an existing user service. The bundled http module is available in every Lua script.