Skip to main content
Version: 4.2

Recipe: Account rules

A correct password is not always enough:

  • Protocol access. A shared mailbox may be read over IMAP but must not send mail over SMTP. A kiosk account may only use webmail.
  • Account lock. When an employee leaves, or after a phishing incident, an account must be locked now and unlocked automatically later, without touching the directory or resetting the password.

Both rules apply after the password was checked, so they are subject sources.

Interfaces: subject sources, policy registry script.
Download: account-rules.tar.gz

What happens​

  1. The backend checks the password, or Nauthilus answers from its login cache.
  2. protocol_access.lua looks up which protocols the account may use and refuses others.
  3. account_lock.lua reads a lock that an administrator stored in Valkey and refuses the account until the lock expires.
  4. Both emit policy attributes; two rules in nauthilus.yml refuse the login with a clear message.

Subject sources run for every login, also when the password check came from the cache. A lock therefore takes effect at once, without flushing anything.

Start and test​

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

Lock an account until a point in time, in UTC:

docker compose exec valkey valkey-cli HSET cookbook:lock:alice until 2030-01-01T00:00:00Z reason offboarding

Remove the lock early with docker compose exec valkey valkey-cli DEL cookbook:lock:alice.

The stack​

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

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:28084: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

The configuration​

nauthilus/nauthilus.yml
# Nauthilus configuration of the "Account rules" Lua Cookbook recipe.
# Interfaces shown: subject sources and a policy registry script.

runtime:
instance_name: "cookbook-account-rules"

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: "cookbookPasswordNonce04"
encryption_secret: "cookbookEncryption04"

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"

backends:
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
subject_vm_pool_size: 2

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

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

providers:
lua_subject_protocol_access:
kind: lua_subject
script_path: "/etc/nauthilus/lua/subject/protocol_access.lua"
targets: [{action: authenticate}]
executions: [host_sync]
lua_subject_account_lock:
kind: lua_subject
script_path: "/etc/nauthilus/lua/subject/account_lock.lua"
targets: [{action: authenticate}]
executions: [host_sync]

# Subject sources run at subject_analysis, after the backend checked the password.
domain_plans:
account_rules:
checkpoints:
auth_backend:
providers:
- name: backend_order
use: authn/auth_backend
actions: [authenticate]
subject_analysis:
providers:
- name: protocol_access
use: authn/lua_subject_protocol_access
actions: [authenticate]
- name: account_lock
use: authn/lua_subject_account_lock
actions: [authenticate]
auth_decision:
providers: []

# The rules run at subject_analysis, right after the subject source that emits their attribute.
policy_sets:
account_rules:
visibility: private
rules:
- name: protocol_not_allowed
checkpoint: subject_analysis
actions: [authenticate]
require_providers: [protocol_access]
if:
attribute: lua.plugin.cookbook.protocol.denied
is: true
then:
decision: deny
reason: protocol_not_allowed
response_message:
from: literal
text: "This account may not use this service"
- name: account_locked
checkpoint: subject_analysis
actions: [authenticate]
require_providers: [account_lock]
if:
attribute: lua.plugin.cookbook.lock.active
is: true
then:
decision: deny
reason: account_locked
response_message:
from: literal
text: "This account is locked"

targets:
- namespace: authn
action: authenticate
schema: authn/authenticate/v1
mode: enforce
default_policy: authn/standard_auth
domain_plan: authn/account_rules
plans:
subject_analysis:
policy_sets: [authn/account_rules]
  • subject_vm_pool_size sizes the pool of prepared Lua VMs for subject sources.
  • providers define the two subject sources (kind: lua_subject).
  • domain_plans.account_rules runs them at the subject_analysis checkpoint, after auth_backend.
  • The rules run at subject_analysis, the checkpoint of the subject sources. require_providers makes each rule wait for the subject source that emits its attribute. Each rule answers with deny and its own response_message, so users and helpdesk see why a login failed.
  • The target binds the rules with plans.subject_analysis.policy_sets.
Since Nauthilus 4.1.3

Rules at subject_analysis see the attributes that subject sources emit there since 4.1.3. In earlier releases put such rules at auth_decision and leave out require_providers, which only names providers of the rule's own checkpoint.

The account data​

nauthilus/lua/demo_users.lua
-- demo_users.lua
-- Shared module of the "Account rules" recipe: the demo accounts and the protocols each one may use. backend.lua
-- checks passwords with it, and subject/protocol_access.lua reads the protocol list from it. In a real installation
-- this would be a lookup in your directory or database.

local M = {}

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

-- find returns the record of one account or nil.
function M.find(account)
return M.USERS[account or ""]
end

return M
nauthilus/lua/backend.lua
-- backend.lua
-- The smallest useful Lua backend: it checks the demo accounts of demo_users.lua. The recipes "Flat-file users" and
-- "SQL users" show real account sources.

local nauthilus_password = require("nauthilus_password")
local demo_users = require("demo_users")

function nauthilus_backend_verify_password(request)
local backend_result = nauthilus_backend_result.new()
local user = demo_users.find(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,
allowed_protocols = user.allowed_protocols,
})

return nauthilus_builtin.BACKEND_RESULT_OK, backend_result
end

The demo accounts live in a module that the backend and protocol_access.lua share. In a real installation the subject source would ask your directory or database instead; the SQL users recipe shows how.

Protocol access​

nauthilus/lua/subject/protocol_access.lua
-- subject/protocol_access.lua
-- Subject source of the "Account rules" recipe. It runs after the backend checked the password and looks up which
-- protocols the account may use. A user who may only read mail over IMAP is refused for SMTP, even with the right
-- password. The lookup also runs when Nauthilus answered the password check from its cache.

local nauthilus_policy = require("nauthilus_policy")
local demo_users = require("demo_users")

-- allows reports whether the comma-separated list contains the protocol.
local function allows(list, protocol)
for item in string.gmatch(list or "", "[^,%s]+") do
if string.lower(item) == protocol then
return true
end
end

return false
end

function nauthilus_call_subject(request)
-- Only a successful login is interesting: a wrong password is rejected anyway.
if not request.authenticated then
return nauthilus_builtin.SUBJECT_ACCEPT, nauthilus_builtin.SUBJECT_RESULT_OK
end

local account = request.account

if account == nil or account == "" then
account = request.username
end

local user = demo_users.find(account)
local protocol = string.lower(request.protocol or "")

-- Accounts without a list may use every protocol.
if user == nil or user.allowed_protocols == nil or allows(user.allowed_protocols, protocol) then
return nauthilus_builtin.SUBJECT_ACCEPT, nauthilus_builtin.SUBJECT_RESULT_OK
end

nauthilus_builtin.custom_log_add("protocol_denied", protocol)
nauthilus_policy.emit_attribute({ id = "lua.plugin.cookbook.protocol.denied", value = true })

return nauthilus_builtin.SUBJECT_REJECT, nauthilus_builtin.SUBJECT_RESULT_OK
end

A subject source defines nauthilus_call_subject(request) and returns an action and a result code.

  • Check request.authenticated first. A wrong password is rejected anyway; the script must neither accept it nor spend time on it. Forgetting this check is the classic mistake with subject sources.
  • request.account is the canonical account name that the backend returned; request.username is what the user typed. Rules about an account should use the account.
  • SUBJECT_REJECT refuses the login on its own. The emitted attribute adds the rule with the clear message.
Backend attributes in subject sources

nauthilus_backend.get_current_backend_result() in a subject source returns the attributes that earlier subject sources applied, not the attributes of the password backend. A subject source therefore cannot read allowed_protocols from there; this recipe reads the account data from the shared module instead.

Account lock​

nauthilus/lua/subject/account_lock.lua
-- subject/account_lock.lua
-- Subject source of the "Account rules" recipe. An administrator locks an account for a while, for example during
-- offboarding or after a phishing incident, by writing a Redis hash:
-- valkey-cli HSET cookbook:lock:bob until 2030-01-01T00:00:00Z reason "offboarding"
-- Until that time every login of the account is refused, even with the right password. After the time has passed
-- the lock is ignored and the script deletes it.

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

-- parse_utc turns "2030-01-01T00:00:00Z" into seconds since 1970, or nil.
local function parse_utc(value)
local year, month, day, hour, min, sec =
string.match(value or "", "^(%d%d%d%d)-(%d%d)-(%d%d)T(%d%d):(%d%d):(%d%d)Z$")

if year == nil then
return nil
end

-- Days from 1970-01-01 to the given date (proleptic Gregorian calendar).
local y, m = tonumber(year), tonumber(month)

if m <= 2 then
y, m = y - 1, m + 12
end

local days = 365 * y + math.floor(y / 4) - math.floor(y / 100) + math.floor(y / 400)
+ math.floor((153 * (m - 3) + 2) / 5) + tonumber(day) - 719469

return days * 86400 + tonumber(hour) * 3600 + tonumber(min) * 60 + tonumber(sec)
end

function nauthilus_call_subject(request)
local account = request.account

if account == nil or account == "" then
account = request.username
end

local key = "cookbook:lock:" .. account
local lock, err = nauthilus_redis.redis_hgetall("default", key)

if err ~= nil then
return nauthilus_builtin.SUBJECT_ACCEPT, nauthilus_builtin.SUBJECT_RESULT_FAIL
end

if lock == nil or lock["until"] == nil then
return nauthilus_builtin.SUBJECT_ACCEPT, nauthilus_builtin.SUBJECT_RESULT_OK
end

local locked_until = parse_utc(lock["until"])

if locked_until == nil or locked_until <= os.time() then
nauthilus_redis.redis_del("default", key)

return nauthilus_builtin.SUBJECT_ACCEPT, nauthilus_builtin.SUBJECT_RESULT_OK
end

nauthilus_builtin.custom_log_add("account_lock", lock.reason or "locked")
nauthilus_policy.emit_attribute({ id = "lua.plugin.cookbook.lock.active", value = true })
nauthilus_policy.emit_attribute({ id = "lua.plugin.cookbook.lock.until", value = lock["until"] })

return nauthilus_builtin.SUBJECT_REJECT, nauthilus_builtin.SUBJECT_RESULT_OK
end
  • The lock is a Valkey hash with until (UTC, RFC 3339) and an optional reason. Anything that can write to Valkey can lock an account: a script of your HR process, a ticket system, or a custom hook like those of the Admin toolkit.
  • parse_utc converts the time into seconds since 1970 with integer arithmetic, so the result does not depend on the time zone of the server.
  • An expired lock is deleted on the next login of the account.
  • The script emits two attributes: lock.active for the rule, and lock.until, which further rules or a policy report can use to show when the lock ends.

The policy registry script​

nauthilus/lua/policy/registry.lua
-- policy/registry.lua
-- Policy registry script of the "Account rules" recipe. It declares the attributes that the two subject sources
-- emit, so that the policy rules in nauthilus.yml can test them.

local function register(id, value_type, description, details)
nauthilus_policy.register_attribute({
id = id,
stage = "subject_analysis",
operations = { "authenticate" },
category = "subject",
type = value_type,
description = description,
details = details,
})
end

register("lua.plugin.cookbook.protocol.denied", "bool", "Whether the account may not use the requested protocol.")
register("lua.plugin.cookbook.lock.active", "bool", "Whether an administrator locked the account.")
register("lua.plugin.cookbook.lock.until", "string", "Until when the account is locked (UTC, RFC 3339).")

The attributes are declared with stage = "subject_analysis", the checkpoint where the subject sources emit them.

What the test checks​

test.sh
#!/usr/bin/env bash
# Checks the "Account rules" 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:28084}"

# Start from a clean state: no locks, no cached logins.
valkey FLUSHALL >/dev/null

section "Protocol access (subject/protocol_access.lua)"
auth bob bob-secret imap 192.0.2.10
expect_auth_status "OK" "bob may use IMAP"

auth bob bob-secret smtp 192.0.2.10
expect_auth_status "This account may not use this service" "bob may not use SMTP, even with the right password"

auth bob wrong-password smtp 192.0.2.10
expect_auth_status "Invalid login or password" "a wrong password still gives the normal answer"

auth alice alice-secret smtp 192.0.2.11
expect_auth_status "OK" "alice may use SMTP"

auth alice alice-secret pop3 192.0.2.11
expect_auth_status "OK" "alice may use POP3"

section "Account lock (subject/account_lock.lua)"
valkey HSET cookbook:lock:alice until 2030-01-01T00:00:00Z reason offboarding >/dev/null
auth alice alice-secret imap 192.0.2.11
expect_auth_status "This account is locked" "a locked account is refused, even from the login cache"

auth bob bob-secret imap 192.0.2.10
expect_auth_status "OK" "other accounts are not affected"

valkey HSET cookbook:lock:alice until 2020-01-01T00:00:00Z >/dev/null
auth alice alice-secret imap 192.0.2.11
expect_auth_status "OK" "an expired lock is ignored"
expect_equal 0 "$(valkey EXISTS cookbook:lock:alice)" "the expired lock was deleted"

section "Many requests"
wrong=0
for i in $(seq 1 100); do
auth bob bob-secret smtp "192.0.2.$(( (i % 200) + 1 ))"
[ "$(header Auth-Status)" = "This account may not use this service" ] || wrong=$((wrong + 1))
auth alice alice-secret imap "198.51.100.$(( (i % 200) + 1 ))"
[ "$(header Auth-Status)" = "OK" ] || wrong=$((wrong + 1))
done
expect_equal 0 "$wrong" "200 logins got the expected answer"

finish

Ideas for your own changes​

  • Lock all accounts of a domain: look up cookbook:lock:@example.test as well.
  • Allow a protocol only from the company network, using request.client_ip and the network matching of the Admin toolkit.
  • Select a mail store for the account with nauthilus_backend.select_backend_server, see Backend monitoring.