Skip to main content
Version: 4.1

Recipe: Admin toolkit

Two switches that every mail administrator needs sooner or later:

  • Maintenance mode. During a migration, logins should fail with a temporary error, so mail clients retry later instead of asking users for their password. Administrators must still be able to log in.
  • IP blocklist. A network that attacks you, or a client that hammers the server with an old password, should be shut out at once, without a configuration change and without a restart.

This recipe builds both as small HTTP APIs inside Nauthilus (custom hooks) and enforces them for every login (environment sources).

Interfaces: custom hooks, environment sources, policy registry script.
Download: admin-toolkit.tar.gz

What happens​

The hooks only write state; the environment sources only read it. Both use the same shared module, so the key names and the network matching exist once.

Start and test​

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

Switch maintenance on and try a login:

curl -u admin:admin-backchannel-secret -H 'Content-Type: application/json' \
-d '{"enabled": true, "message": "Mail server upgrade until 22:00"}' \
http://127.0.0.1:28083/api/v1/custom/maintenance

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:28083/api/v1/auth/json

The login gets a temporary failure with Auth-Status: Mail server upgrade until 22:00. The same login from 10.20.30.40, an address in the administrator network, still works. Switch maintenance off again with {"enabled": false}.

Block a network:

curl -u admin:admin-backchannel-secret -H 'Content-Type: application/json' \
-d '{"add": ["198.51.100.0/24"]}' http://127.0.0.1:28083/api/v1/custom/blocklist

curl -u admin:admin-backchannel-secret http://127.0.0.1:28083/api/v1/custom/blocklist

The stack​

docker-compose.yml
# Lua Cookbook recipe "Admin toolkit".
# Start with: docker compose up -d --wait Test with: ./test.sh Stop with: docker compose down
name: cookbook-admin-toolkit

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}
# Logins from these networks still work during maintenance (read by environment/maintenance.lua).
COOKBOOK_ADMIN_NETWORKS: "10.0.0.0/8"
ports:
- "127.0.0.1:28083: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

COOKBOOK_ADMIN_NETWORKS lists the networks that may still log in during maintenance. The environment source reads it with os.getenv.

The configuration​

nauthilus/nauthilus.yml
# Nauthilus configuration of the "Admin toolkit" Lua Cookbook recipe.
# Interfaces shown: custom hooks and environment sources.

runtime:
instance_name: "cookbook-admin-toolkit"

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: "cookbookPasswordNonce03"
encryption_secret: "cookbookEncryption03"

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 calls the custom hooks.
- username: "admin"
password: "admin-backchannel-secret"
scopes:
- "cookbook:admin"

backends:
order:
- "cache"
- "lua"

lua:
backend:
default:
backend_script_path: "/etc/nauthilus/lua/backend.lua"
# require() finds the bundled helpers and the recipe's shared module admin_toolkit.lua.
package_path: "/usr/app/lua-plugins.d/share/?.lua;/etc/nauthilus/lua/?.lua"
backend_number_of_workers: 2
environment_vm_pool_size: 2
hook_vm_pool_size: 2

search:
- protocol:
- "imap"
- "smtp"
cache_name: "demo"

controls:
enabled:
- "lua"

lua:
# One entry binds one HTTP method of /api/v1/custom/<http_location> to a script. Every hook requires a
# caller that holds the scope cookbook:admin.
hooks:
- http_location: "maintenance"
http_method: "GET"
script_path: "/etc/nauthilus/lua/hooks/maintenance.lua"
scopes: ["cookbook:admin"]
- http_location: "maintenance"
http_method: "POST"
script_path: "/etc/nauthilus/lua/hooks/maintenance.lua"
scopes: ["cookbook:admin"]
- http_location: "blocklist"
http_method: "GET"
script_path: "/etc/nauthilus/lua/hooks/blocklist.lua"
scopes: ["cookbook:admin"]
- http_location: "blocklist"
http_method: "POST"
script_path: "/etc/nauthilus/lua/hooks/blocklist.lua"
scopes: ["cookbook:admin"]

policy:
namespaces:
authn:
# The registry script declares the attributes that the two environment sources emit.
schema_contributions:
lua:
registry_scripts:
- "/etc/nauthilus/lua/policy/registry.lua"

# A provider definition names a Lua script. It does not run until a domain plan schedules it.
providers:
lua_environment_maintenance:
kind: lua_environment
script_path: "/etc/nauthilus/lua/environment/maintenance.lua"
targets: [{action: authenticate}]
executions: [host_sync]
lua_environment_ip_blocklist:
kind: lua_environment
script_path: "/etc/nauthilus/lua/environment/ip_blocklist.lua"
targets: [{action: authenticate}]
executions: [host_sync]

# The domain plan runs both environment sources at the pre_auth checkpoint, before the password is checked.
domain_plans:
toolkit:
checkpoints:
pre_auth:
providers:
- name: maintenance
use: authn/lua_environment_maintenance
actions: [authenticate]
- name: ip_blocklist
use: authn/lua_environment_ip_blocklist
actions: [authenticate]
# A domain plan lists every checkpoint it uses. auth_backend checks the password with the backends of
# auth.backends.order (here: cache, then backend.lua).
auth_backend:
providers:
- name: backend_order
use: authn/auth_backend
actions: [authenticate]
auth_decision:
providers: []

# Own rules. Everything not decided here falls through to the built-in rules of authn/standard_auth.
policy_sets:
toolkit:
visibility: private
rules:
# Maintenance answers with a temporary failure and the message the administrator stored with the hook.
# Mail clients retry later and do not ask the user for a new password.
- name: maintenance_tempfail
checkpoint: pre_auth
actions: [authenticate]
require_providers: [maintenance]
if:
attribute: lua.plugin.cookbook.maintenance.active
is: true
then:
decision: tempfail
reason: maintenance
response_message:
from: attribute_detail
attribute: lua.plugin.cookbook.maintenance.active
detail: status_message
fallback: "Maintenance in progress, please try again later"

# Blocked addresses are rejected before the password is checked.
- name: blocklist_deny
checkpoint: pre_auth
actions: [authenticate]
require_providers: [ip_blocklist]
if:
attribute: lua.plugin.cookbook.blocklist.matched
is: true
then:
decision: deny
reason: blocklist
response_message:
from: literal
text: "Access from your network is blocked"

# The target activates the plan and the rules for every authentication request.
targets:
- namespace: authn
action: authenticate
schema: authn/authenticate/v1
mode: enforce
default_policy: authn/standard_auth
domain_plan: authn/toolkit
plans:
pre_auth:
policy_sets: [authn/toolkit]

What is new:

  • The admin credential holds the scope cookbook:admin. You can invent scopes for your own hooks. Each hook entry lists the scopes that may call it; the mail server credential does not hold cookbook:admin and gets HTTP 403.
  • auth.controls.lua.hooks binds one HTTP method of /api/v1/custom/<http_location> to a script. GET and POST of the same location are two entries; both point to the same script, which asks for the method.
  • environment_vm_pool_size and hook_vm_pool_size size the pools of prepared Lua VMs for these two interfaces. A VM is reused for many requests; Nauthilus gives every request a fresh environment on top of it.
  • policy.namespaces.authn is where environment sources live:
    • schema_contributions.lua.registry_scripts loads the registry script that declares the recipe's policy attributes.
    • providers defines the two environment sources (kind: lua_environment). A provider definition only names a script.
    • domain_plans.toolkit schedules them. pre_auth runs before the password check; auth_backend runs the backends of auth.backends.order; auth_decision is the last checkpoint. A domain plan lists every checkpoint it uses, so auth_backend must be there, or no password would ever be checked.
    • policy_sets.toolkit holds the two rules. maintenance_tempfail answers with tempfail while the maintenance attribute is true, with the message from the attribute's status_message detail (from: attribute_detail), so clients see the text that the administrator stored; blocklist_deny answers with deny and its own text. require_providers makes a rule wait for the provider that emits its attribute.
  • policy.targets activates all of this for authenticate requests. default_policy: authn/standard_auth keeps the built-in rules for everything the recipe does not decide.

The shared module​

nauthilus/lua/admin_toolkit.lua
-- admin_toolkit.lua
-- Shared module of the "Admin toolkit" recipe. The hooks write the state, the environment sources read it, and
-- both use the key names and the IPv4 network matching from this one place.

local nauthilus_http_response = require("nauthilus_http_response")

local M = {}

-- Redis keys. A hash holds the maintenance state; a set holds the blocked addresses and networks.
M.KEY_MAINTENANCE = "cookbook:maintenance"
M.KEY_BLOCKLIST = "cookbook:blocklist"

-- ipv4_to_number turns "192.0.2.10" into a 32-bit number, or returns nil for anything else.
function M.ipv4_to_number(address)
local a, b, c, d = string.match(address or "", "^(%d+)%.(%d+)%.(%d+)%.(%d+)$")

if a == nil then
return nil
end

local value = 0

for _, octet in ipairs({ tonumber(a), tonumber(b), tonumber(c), tonumber(d) }) do
if octet > 255 then
return nil
end

value = value * 256 + octet
end

return value
end

-- parse_network turns "198.51.100.0/24" or a single address into the first and last address of the range.
-- It returns nil for an invalid entry.
function M.parse_network(entry)
local address, bits = string.match(entry or "", "^([%d%.]+)/(%d+)$")

if address == nil then
address, bits = entry, "32"
end

local base = M.ipv4_to_number(address)
local prefix = tonumber(bits)

if base == nil or prefix == nil or prefix > 32 then
return nil
end

local size = 2 ^ (32 - prefix)
local first = math.floor(base / size) * size

return first, first + size - 1
end

-- contains reports whether the client address lies in one of the networks of the list.
function M.contains(networks, client_ip)
local ip = M.ipv4_to_number(client_ip)

if ip == nil then
return false, nil
end

for _, entry in ipairs(networks) do
local first, last = M.parse_network(entry)

if first ~= nil and ip >= first and ip <= last then
return true, entry
end
end

return false, nil
end

-- split_list turns "10.0.0.0/8, 192.168.0.0/16" into { "10.0.0.0/8", "192.168.0.0/16" }.
function M.split_list(value)
local list = {}

for item in string.gmatch(value or "", "[^,%s]+") do
list[#list + 1] = item
end

return list
end

-- reply_error sets an HTTP error status and returns the body, so a hook can answer with
-- `return toolkit.reply_error(400, { error = "..." })`. Nauthilus sends the returned table as JSON with that status.
function M.reply_error(status, body)
nauthilus_http_response.set_http_status(status)

return body
end

return M
  • KEY_MAINTENANCE and KEY_BLOCKLIST name the Redis keys. Change them here and both hooks and environment sources follow.
  • ipv4_to_number and parse_network turn addresses and networks such as 198.51.100.0/24 into number ranges, so contains only compares numbers. A network is valid only if it parses; the hook refuses anything else. The module handles IPv4; extend parse_network for IPv6 the same way.
  • reply_error sets an HTTP error status and returns the body; the hook returns it, and Nauthilus sends it as JSON with that status. Before Nauthilus 4.1.3 such an answer had an empty body.

The custom hooks​

nauthilus/lua/hooks/maintenance.lua
-- hooks/maintenance.lua
-- Custom hook of the "Admin toolkit" recipe, served at /api/v1/custom/maintenance.
-- GET shows the current state
-- POST {"enabled": true, "message": "..."} switches maintenance mode on
-- POST {"enabled": false} switches it off
-- The environment source environment/maintenance.lua reads the same Redis hash for every login.

local json = require("json")
local nauthilus_redis = require("nauthilus_redis")
local nauthilus_http_request = require("nauthilus_http_request")
local toolkit = require("admin_toolkit")

-- read_state returns the maintenance hash as a table; an empty table means "off".
local function read_state()
local state, err = nauthilus_redis.redis_hgetall("default", toolkit.KEY_MAINTENANCE)

if err ~= nil then
error(err)
end

return state or {}
end

-- describe turns the stored hash into the JSON answer of the hook.
local function describe(state)
return {
enabled = state.message ~= nil,
message = state.message,
since = state.since,
}
end

function nauthilus_run_hook(request)
if nauthilus_http_request.get_http_method() == "GET" then
return describe(read_state())
end

local ok, body = pcall(json.decode, nauthilus_http_request.get_http_request_body() or "")

if not ok or type(body) ~= "table" or type(body.enabled) ~= "boolean" then
return toolkit.reply_error(400, { error = 'expected a JSON body like {"enabled": true, "message": "..."}' })
end

if body.enabled then
local message = body.message or "Maintenance in progress, please try again later"

nauthilus_redis.redis_hset("default", toolkit.KEY_MAINTENANCE, "message", message)
nauthilus_redis.redis_hset("default", toolkit.KEY_MAINTENANCE, "since", os.date("!%Y-%m-%dT%H:%M:%SZ"))
else
nauthilus_redis.redis_del("default", toolkit.KEY_MAINTENANCE)
end

return describe(read_state())
end
nauthilus/lua/hooks/blocklist.lua
-- hooks/blocklist.lua
-- Custom hook of the "Admin toolkit" recipe, served at /api/v1/custom/blocklist.
-- GET lists the blocked addresses and networks
-- POST {"add": ["198.51.100.0/24"], "remove": ["192.0.2.7"]} changes the list
-- The environment source environment/ip_blocklist.lua checks every login against this list.

local json = require("json")
local nauthilus_redis = require("nauthilus_redis")
local nauthilus_http_request = require("nauthilus_http_request")
local toolkit = require("admin_toolkit")

-- list_entries returns the sorted members of the blocklist set.
local function list_entries()
local members, err = nauthilus_redis.redis_smembers("default", toolkit.KEY_BLOCKLIST)

if err ~= nil then
error(err)
end

members = members or {}
table.sort(members)

return members
end

function nauthilus_run_hook(request)
if nauthilus_http_request.get_http_method() == "GET" then
return { entries = list_entries() }
end

local ok, body = pcall(json.decode, nauthilus_http_request.get_http_request_body() or "")

if not ok or type(body) ~= "table" then
return toolkit.reply_error(400, { error = 'expected a JSON body like {"add": ["198.51.100.0/24"], "remove": []}' })
end

-- Validate everything first, so a typo does not leave the list half changed.
local invalid = {}

for _, entry in ipairs(body.add or {}) do
if toolkit.parse_network(entry) == nil then
invalid[#invalid + 1] = entry
end
end

if #invalid > 0 then
return toolkit.reply_error(400, { error = "invalid IPv4 address or network", invalid = invalid })
end

for _, entry in ipairs(body.add or {}) do
nauthilus_redis.redis_sadd("default", toolkit.KEY_BLOCKLIST, entry)
end

for _, entry in ipairs(body.remove or {}) do
nauthilus_redis.redis_srem("default", toolkit.KEY_BLOCKLIST, entry)
end

return { entries = list_entries() }
end

A hook defines nauthilus_run_hook(request). Nauthilus checks the caller's credential and scope before it runs the script.

  • nauthilus_http_request.get_http_method() and get_http_request_body() read the request. The bundled json module decodes the body; pcall turns a malformed body into a clean HTTP 400 instead of a script error.
  • A returned table becomes the JSON answer with HTTP 200.
  • nauthilus_redis.redis_hset, redis_sadd, redis_srem, and redis_del write to Valkey through the connection that Nauthilus already holds. "default" names that connection.
  • The blocklist hook validates every entry before it changes anything, so a typo does not leave a half-changed list.

The environment sources​

nauthilus/lua/environment/maintenance.lua
-- environment/maintenance.lua
-- Environment source of the "Admin toolkit" recipe. While maintenance mode is on, it stops every login before the
-- password is checked, except logins from the administrator networks.
-- The script does not decide the login itself. It emits the registered attribute lua.plugin.cookbook.maintenance.active,
-- and the policy rule maintenance_tempfail in nauthilus.yml answers with a temporary failure, so mail clients retry
-- later instead of asking the user for a new password.

local nauthilus_redis = require("nauthilus_redis")
local nauthilus_policy = require("nauthilus_policy")
local toolkit = require("admin_toolkit")

local ADMIN_NETWORKS = toolkit.split_list(os.getenv("COOKBOOK_ADMIN_NETWORKS") or "10.0.0.0/8")

-- not_triggered is the answer for "nothing to do here": no trigger, no abort, no error.
local function not_triggered()
return nauthilus_builtin.ENVIRONMENT_TRIGGER_NO,
nauthilus_builtin.ENVIRONMENT_ABORT_NO,
nauthilus_builtin.ENVIRONMENT_RESULT_OK
end

function nauthilus_call_environment(request)
local message, err = nauthilus_redis.redis_hget("default", toolkit.KEY_MAINTENANCE, "message")

if err ~= nil then
return nauthilus_builtin.ENVIRONMENT_TRIGGER_NO,
nauthilus_builtin.ENVIRONMENT_ABORT_NO,
nauthilus_builtin.ENVIRONMENT_RESULT_FAIL
end

if message == nil or message == "" then
return not_triggered()
end

if toolkit.contains(ADMIN_NETWORKS, request.client_ip) then
nauthilus_builtin.custom_log_add("maintenance_bypass", request.client_ip)

return not_triggered()
end

nauthilus_builtin.custom_log_add("maintenance", "active")
nauthilus_policy.emit_attribute({
id = "lua.plugin.cookbook.maintenance.active",
value = true,
details = { status_message = message },
})

return not_triggered()
end
nauthilus/lua/environment/ip_blocklist.lua
-- environment/ip_blocklist.lua
-- Environment source of the "Admin toolkit" recipe. It finds logins from addresses and networks that an
-- administrator put on the blocklist with the blocklist hook. It emits the registered attribute
-- lua.plugin.cookbook.blocklist.matched, and the policy rule blocklist_deny in nauthilus.yml rejects the login.

local nauthilus_redis = require("nauthilus_redis")
local nauthilus_policy = require("nauthilus_policy")
local toolkit = require("admin_toolkit")

function nauthilus_call_environment(request)
local entries, err = nauthilus_redis.redis_smembers("default", toolkit.KEY_BLOCKLIST)

if err ~= nil then
return nauthilus_builtin.ENVIRONMENT_TRIGGER_NO,
nauthilus_builtin.ENVIRONMENT_ABORT_NO,
nauthilus_builtin.ENVIRONMENT_RESULT_FAIL
end

local blocked, entry = toolkit.contains(entries or {}, request.client_ip)

if not blocked then
return nauthilus_builtin.ENVIRONMENT_TRIGGER_NO,
nauthilus_builtin.ENVIRONMENT_ABORT_NO,
nauthilus_builtin.ENVIRONMENT_RESULT_OK
end

nauthilus_builtin.custom_log_add("blocklist_match", entry)
nauthilus_policy.emit_attribute({ id = "lua.plugin.cookbook.blocklist.matched", value = true })

-- Also report the classic "triggered" result. The policy rule decides the login either way.
return nauthilus_builtin.ENVIRONMENT_TRIGGER_YES,
nauthilus_builtin.ENVIRONMENT_ABORT_NO,
nauthilus_builtin.ENVIRONMENT_RESULT_OK
end

An environment source defines nauthilus_call_environment(request) and returns three values: triggered, abort, and a result code. It runs before the password is checked, so it sees the client address, protocol, and username, but not yet whether the password is right.

  • Both scripts emit a registered policy attribute with nauthilus_policy.emit_attribute, and a rule in nauthilus.yml makes the decision. That keeps the decision in the configuration, where an administrator looks for it, and lets a rule answer with tempfail instead of the default deny.
  • When Valkey cannot be read, the scripts report ENVIRONMENT_RESULT_FAIL instead of guessing. Nauthilus itself cannot work without Valkey either, so such a login ends as a temporary failure.
  • nauthilus_builtin.custom_log_add adds fields to the log line of the request, for example blocklist_match=198.51.100.0/24.
  • Module-level code such as ADMIN_NETWORKS = ... runs for every request, because Nauthilus executes the script anew in a fresh request environment. Keep it cheap.
Triggers are facts

Returning ENVIRONMENT_TRIGGER_YES makes the fact nauthilus.auth.lua.environment.<name>.triggered true, and the built-in rules of authn/standard_auth deny it unless a configured rule decides first. ip_blocklist.lua returns it as well; its own rule only adds the clear message. Nauthilus 4.0.0 to 4.1.2 ignored such a trigger, so use 4.1.3 or later.

The policy registry script​

nauthilus/lua/policy/registry.lua
-- policy/registry.lua
-- Policy registry script of the "Admin toolkit" recipe. Nauthilus runs it when it builds the policy snapshot, at
-- startup and after every reload. It declares the attributes that the environment sources emit, so that the policy
-- rules in nauthilus.yml can test them. Lua may only emit attributes that a registry script declared.

nauthilus_policy.register_attribute({
id = "lua.plugin.cookbook.maintenance.active",
stage = "pre_auth",
operations = { "authenticate" },
category = "environment",
type = "bool",
description = "Whether maintenance mode blocks this login.",
details = {
-- The message an administrator stored with the maintenance hook. "public" and "response_message"
-- allow the policy rule to send it to the client.
status_message = {
type = "string",
sensitivity = "public",
purpose = "response_message",
max_length = 256,
},
},
})

nauthilus_policy.register_attribute({
id = "lua.plugin.cookbook.blocklist.matched",
stage = "pre_auth",
operations = { "authenticate" },
category = "environment",
type = "bool",
description = "Whether the client address is on the administrator blocklist.",
})

Lua may only emit policy attributes that a registry script declared. The declaration fixes the attribute's type, the checkpoint (stage) where it is emitted, the operations, and optional details. Nauthilus runs the registry script when it builds the policy snapshot, at startup and after a reload, and rejects a script that emits an undeclared attribute.

The demo backend​

nauthilus/lua/backend.lua
-- backend.lua
-- The smallest useful Lua backend: two demo accounts in a Lua table. It only exists so that this recipe has
-- someone to log in as. The recipes "Flat-file users" and "SQL users" show real account sources.

local nauthilus_password = require("nauthilus_password")

-- Passwords: alice = alice-secret, bob = bob-secret (bcrypt hashes).
local USERS = {
alice = { password = "$2y$10$ngKMNlOnSLGDyr0hoKOr3.H2WNwc2hSU.ht8m2HB8TVPZZdxuTlYC", mail = "alice@example.test" },
bob = { password = "$2y$10$vUNCt8LDP9xgBCJkIRd7k.RzPdWOIqbK2ijZTTDEVb6blyR.KLJQC", mail = "bob@example.test" },
}

function nauthilus_backend_verify_password(request)
local backend_result = nauthilus_backend_result.new()
local user = USERS[request.username]

if user == nil then
backend_result:user_found(false)
backend_result:authenticated(false)

return nauthilus_builtin.BACKEND_RESULT_OK, backend_result
end

local match = request.no_auth or nauthilus_password.compare_passwords(user.password, request.password or "")

backend_result:user_found(true)
backend_result:authenticated(match == true)
backend_result:account_field("account")
backend_result:attributes({ account = request.username, mail = user.mail })

return nauthilus_builtin.BACKEND_RESULT_OK, backend_result
end

Two accounts in a Lua table, so the recipe has someone to log in as. The Flat-file users and SQL users recipes show real account sources.

What the test checks​

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

# hook calls one custom hook as the administrator. Arguments: method location [json]
hook() {
if [ $# -ge 3 ]; then
http "$1" "/api/v1/custom/$2" -u "$ADMIN" -H 'Content-Type: application/json' -d "$3"
else
http "$1" "/api/v1/custom/$2" -u "$ADMIN"
fi
}

# Start from a clean state, so the script can run more than once.
valkey DEL cookbook:maintenance cookbook:blocklist >/dev/null

section "Normal operation"
auth alice alice-secret imap 192.0.2.10
expect_auth_status "OK" "alice logs in"

section "Hook access control"
http GET /api/v1/custom/maintenance -u mailserver:mailserver-backchannel-secret
expect_status 403 "the mail server credential may not call the hooks"
http GET /api/v1/custom/maintenance
expect_status 401 "an anonymous caller may not call the hooks"

section "Maintenance mode"
hook POST maintenance '{"enabled": true, "message": "Mail server upgrade until 22:00"}'
expect_status 200 "the hook switches maintenance on"
expect_body_contains '"enabled":true' "the hook reports the new state"

hook GET maintenance
expect_body_contains 'Mail server upgrade until 22:00' "GET shows the stored message"

auth alice alice-secret imap 192.0.2.10
expect_status 500 "a login from the internet gets a temporary failure"
expect_auth_status "Mail server upgrade until 22:00" "the client sees the message stored by the administrator"

auth alice alice-secret imap 10.20.30.40
expect_auth_status "OK" "a login from the admin network 10.0.0.0/8 still works"

hook POST maintenance '{"enabled": "yes"}'
expect_status 400 "the hook rejects a malformed body"
expect_body_contains 'expected a JSON body' "the error explains the expected body"

hook POST maintenance '{"enabled": false}'
auth alice alice-secret imap 192.0.2.10
expect_auth_status "OK" "after switching maintenance off, logins work again"

section "IP blocklist"
hook POST blocklist '{"add": ["198.51.100.0/24", "203.0.113.7"]}'
expect_status 200 "the hook adds a network and an address"
expect_body_contains '"198.51.100.0/24"' "the list contains the network"

auth alice alice-secret imap 198.51.100.77
expect_auth_status "Access from your network is blocked" "a client inside 198.51.100.0/24 is rejected"

auth bob bob-secret imap 203.0.113.7
expect_auth_status "Access from your network is blocked" "the single blocked address is rejected"

auth bob bob-secret imap 203.0.113.8
expect_auth_status "OK" "the neighbour address is not blocked"

hook POST blocklist '{"add": ["300.1.1.1"]}'
expect_status 400 "the hook refuses an invalid address"
expect_body_contains '"300.1.1.1"' "the error names the invalid entry"

hook POST blocklist '{"remove": ["203.0.113.7"]}'
auth bob bob-secret imap 203.0.113.7
expect_auth_status "OK" "after removing the address, bob logs in again"

section "Many requests against a long blocklist"
# 50 networks make environment/ip_blocklist.lua loop for every login; 200 logins reuse the pooled Lua VMs.
networks=""
for i in $(seq 1 50); do networks="$networks\"10.$i.0.0/16\","; done
hook POST blocklist "{\"add\": [${networks%,}]}"

wrong=0
for i in $(seq 1 100); do
auth alice alice-secret imap "10.$(( (i % 50) + 1 )).$i.1"
[ "$(header Auth-Status)" = "Access from your network is blocked" ] || wrong=$((wrong + 1))
auth bob bob-secret imap "192.0.2.$(( (i % 200) + 1 ))"
[ "$(header Auth-Status)" = "OK" ] || wrong=$((wrong + 1))
done
expect_equal 0 "$wrong" "200 logins got the expected answer"

valkey DEL cookbook:maintenance cookbook:blocklist >/dev/null

finish

The last section puts 50 networks on the blocklist and sends 200 logins, so the matching loop runs many times in the same pooled Lua VMs.

Ideas for your own changes​

  • Let the maintenance hook accept an end time and switch maintenance off automatically.
  • Give blocklist entries a reason and an expiry, stored in a Redis hash instead of a set.
  • Allow only one protocol during maintenance, for example webmail over http.