Recipe: Country rules per account
Some accounts should only log in from certain countries. Accounting works from the EU, the US team from the US, and everyone else from anywhere. When an administrator changes the region of an account, the rule applies at the next login.
This recipe shows how a native Go plugin and a Lua script work together. Neither of them decides anything:
- The bundled GeoIP plugin knows where the client is. It provides the fact
plugin.geoip.country_iso. - A Lua environment source knows which region an account belongs to. It provides the fact
lua.plugin.cookbook.account.region. - Policy rules in
nauthilus.ymlcombine both facts and decide.
Shown: native Go plugin, Lua environment source, policy registry script, condition sets.
Download: geo-regions.tar.gz
What happens
Both providers run at the pre_auth checkpoint, before the password is checked. A login from a forbidden country is
refused without testing the password, so the answer does not tell an attacker whether a guessed password was right.
The Lua script cannot read the plugin's facts, and the plugin knows nothing about accounts. That is intended: each component delivers what it knows, and the decision stays in the configuration, where an administrator can read it.
Start and test
docker compose up -d --wait
./test.sh
Give alice a region and try two logins:
docker compose exec valkey valkey-cli SET cookbook:region:alice eu
curl -i -u mailserver:mailserver-backchannel-secret -H 'Content-Type: application/json' \
-d '{"username":"alice","password":"alice-secret","protocol":"imap","client_ip":"198.51.100.10"}' \
http://127.0.0.1:28087/api/v1/auth/json
The address 198.51.100.10 lies in the US network of the demo database, so the answer is HTTP 403 with
Auth-Status: Login from this country is not allowed for this account. With 192.0.2.10 (Germany) alice logs in.
Remove the region with docker compose exec valkey valkey-cli DEL cookbook:region:alice.
The stack
# Lua Cookbook recipe "Country rules per account".
# Start with: docker compose up -d --wait Test with: ./test.sh Stop with: docker compose down
name: cookbook-geo-regions
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:28087:8080"
volumes:
- ./nauthilus/nauthilus.yml:/etc/nauthilus/nauthilus.yml:ro
- ./nauthilus/lua:/etc/nauthilus/lua:ro
- ./nauthilus/geoip:/etc/nauthilus/geoip:ro
healthcheck:
test: ["CMD", "/usr/app/healthcheck", "--url", "http://127.0.0.1:8080/healthz"]
interval: 5s
timeout: 3s
retries: 30
The Nauthilus image already contains the bundled plugins below /usr/local/lib/nauthilus/plugins: geoip.so,
clickhouse.so, haveibeenpwnd.so, and reputation.so. The stack only mounts the GeoIP database next to the
configuration and the Lua scripts.
The GeoIP database
{
"records": [
{
"cidr": "192.0.2.0/24",
"country_iso": "DE",
"country_name": "Germany",
"city_name": "Berlin",
"asn": 64500,
"asn_org": "Example Access GmbH"
},
{
"cidr": "198.51.100.0/24",
"country_iso": "US",
"country_name": "United States",
"city_name": "New York",
"asn": 64501,
"asn_org": "Example Broadband Inc."
},
{
"cidr": "203.0.113.0/24",
"country_iso": "BR",
"country_name": "Brazil",
"city_name": "Sao Paulo",
"asn": 64502,
"asn_org": "Exemplo Telecom Ltda."
}
]
}
The plugin reads MaxMind databases and, for tests and development, this JSON format. The three networks are reserved for documentation (RFC 5737), so the demo needs neither a license nor internet access. The most specific network that contains the client address wins. Add your own networks, for example your office network with your home country, to try the rules with real addresses.
The configuration
# Nauthilus configuration of the "Country rules per account" Lua Cookbook recipe.
# Shown: a bundled native Go plugin (GeoIP) and a Lua environment source, combined by policy rules.
runtime:
instance_name: "cookbook-geo-regions"
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: "cookbookPasswordNonce07"
encryption_secret: "cookbookEncryption07"
# Native Go plugins. The Nauthilus image ships geoip.so below /usr/local/lib/nauthilus/plugins.
plugins:
# A checksum or signature is verified when one is configured. This recipe configures none, so it runs with every
# image; in production pin the artifact with checksum (sha256:...) or a minisign signature.
verification_policy: when_present
allowed_dirs:
- /usr/local/lib/nauthilus/plugins
modules:
- name: geoip
type: go
path: /usr/local/lib/nauthilus/plugins/geoip.so
optional: false
config:
# One fact provider: it looks up the client address of every authentication request.
decision_bindings:
- component: environment
targets: [authn/authenticate]
input: {fact: nauthilus.request.client.ip, category: environment}
output_schema: geoip.facts.v1
# The demo database is a small JSON file. Production uses a licensed MaxMind database (database_format: mmdb).
database_path: /etc/nauthilus/geoip/geoip.json
database_format: json
# A JSON database is as old as its file. Data older than max_stale_age (at most 365 days) is "unavailable";
# refresh the demo file with: touch nauthilus/geoip/geoip.json
freshness: {max_age: 8760h, max_stale_age: 8760h}
lookup_timeout: 50ms
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
environment_vm_pool_size: 2
search:
- protocol:
- "imap"
- "smtp"
cache_name: "demo"
policy:
namespaces:
authn:
# Country lists the rules use. Policy rules reference them as "@string.<name>".
condition_sets:
strings:
eu_countries: [AT, BE, DE, DK, ES, FI, FR, IE, IT, LU, NL, PL, PT, SE]
us_countries: [US]
# The registry script declares the attribute that environment/account_region.lua emits.
schema_contributions:
lua:
registry_scripts:
- "/etc/nauthilus/lua/policy/registry.lua"
providers:
# The GeoIP plugin's provider. The key "environment" matches the component of its decision binding, so the
# provider's identity is authn/plugin.geoip.environment. produced_facts must name every fact the plugin can
# return with this configuration; the host rejects an answer with an undeclared fact.
environment:
kind: native
module: geoip
targets: [{action: authenticate}]
produced_facts:
- plugin.geoip.lookup_state
- plugin.geoip.ip
- plugin.geoip.data_stale
- plugin.geoip.data_age_seconds
- plugin.geoip.network
- plugin.geoip.matched
- plugin.geoip.country_iso
- plugin.geoip.country_name
- plugin.geoip.city_name
- plugin.geoip.asn
- plugin.geoip.asn_org
- plugin.geoip.asn_prefix
- plugin.geoip.asn_registry
- plugin.geoip.asn_country_iso
- plugin.geoip.asn_allocated
- plugin.geoip.asn_status
failure: indeterminate
timeout: 50ms
# The Lua environment source.
lua_environment_account_region:
kind: lua_environment
script_path: "/etc/nauthilus/lua/environment/account_region.lua"
targets: [{action: authenticate}]
executions: [host_sync]
# Both providers run at pre_auth, before the password is checked.
domain_plans:
geo_regions:
checkpoints:
pre_auth:
providers:
- name: geoip
use: authn/plugin.geoip.environment
actions: [authenticate]
- name: account_region
use: authn/lua_environment_account_region
actions: [authenticate]
auth_backend:
providers:
- name: backend_order
use: authn/auth_backend
actions: [authenticate]
auth_decision:
providers: []
# Each rule combines the Lua fact (the account's region) with the plugin fact (the client's country).
policy_sets:
geo_regions:
visibility: private
rules:
- name: eu_account_outside_eu
checkpoint: pre_auth
actions: [authenticate]
require_providers: [geoip, account_region]
if:
all:
- attribute: lua.plugin.cookbook.account.region
eq: eu
- attribute: plugin.geoip.country_iso
not_in: "@string.eu_countries"
then:
decision: deny
reason: country_not_allowed
response_message:
from: literal
text: "Login from this country is not allowed for this account"
- name: us_account_outside_us
checkpoint: pre_auth
actions: [authenticate]
require_providers: [geoip, account_region]
if:
all:
- attribute: lua.plugin.cookbook.account.region
eq: us
- attribute: plugin.geoip.country_iso
not_in: "@string.us_countries"
then:
decision: deny
reason: country_not_allowed
response_message:
from: literal
text: "Login from this country is not allowed for this account"
# A rule with a missing fact does not match. Without this rule, an address the database does not know
# (no country) would let a restricted account through. lookup_state is always present: fresh, stale,
# not_found, or unavailable.
- name: restricted_account_unknown_location
checkpoint: pre_auth
actions: [authenticate]
require_providers: [geoip, account_region]
if:
all:
- attribute: lua.plugin.cookbook.account.region
in: [eu, us]
- attribute: plugin.geoip.lookup_state
not_in: [fresh, stale]
then:
decision: deny
reason: country_unknown
response_message:
from: literal
text: "Login location unknown, login not allowed for this account"
targets:
- namespace: authn
action: authenticate
schema: authn/authenticate/v1
mode: enforce
default_policy: authn/standard_auth
domain_plan: authn/geo_regions
plans:
pre_auth:
policy_sets: [authn/geo_regions]
Loading the plugin
plugins.allowed_dirslists the directories from which Nauthilus loads native plugins.plugins.modulesloadsgeoip.sounder the module namegeoip.optional: falsestops Nauthilus from starting when the plugin cannot be loaded, so a broken plugin never goes unnoticed.verification_policy: when_presentverifies a checksum or signature only when one is configured. The recipe configures none, so it works with every image. In production pin the artifact withchecksum: sha256:...or a minisignsignature; see Native Go plugins. Native plugins are trusted code in the Nauthilus process, not a sandbox.configis the plugin's own configuration. Nauthilus passes it to the plugin, which checks it strictly; an unknown key or a wrong value stops the start with a clear error.decision_bindingsregisters one fact provider. Itscomponentnameenvironmentbecomes part of the provider identityauthn/plugin.geoip.environment.inputnames the fact that holds the client address.database_pathanddatabase_formatpoint to the JSON file.freshnesssays how old the data may be. A JSON database is as old as its file; aftermax_stale_age(at most 365 days) the plugin reportsunavailable. Runtouch nauthilus/geoip/geoip.jsonto make an old demo file fresh again.
Wiring both providers into the policy
condition_sets.stringsholds the country lists. Rules reference them as@string.eu_countries.providers.environmentdeclares the plugin's provider (kind: native).produced_factsmust name every fact the plugin can return with this configuration. Nauthilus rejects an answer that contains an undeclared fact; the request then ends as a temporary failure.providers.lua_environment_account_regiondeclares the Lua environment source.domain_plans.geo_regionsruns both providers atpre_auth. The plugin's provider is used by its identityauthn/plugin.geoip.environment, the Lua source byauthn/lua_environment_account_region.
The rules
eu_account_outside_euandus_account_outside_usdeny when the account's region is set and the client's country isnot_inthe region's list.restricted_account_unknown_locationcloses a gap. A rule whose fact is missing does not match: an address the database does not know has no country, so without this rule a restricted account would get through. The plugin always reportsplugin.geoip.lookup_state(fresh,stale,not_found, orunavailable), and the rule denies restricted accounts unless the location is known.require_providersmakes each rule wait for both providers.- Accounts without a region never match a rule, so the built-in rules of
authn/standard_authdecide as usual.
The Lua environment source
-- environment/account_region.lua
-- Environment source of the "Country rules per account" recipe. It reads the region an administrator assigned to the
-- account and emits it as the policy attribute lua.plugin.cookbook.account.region:
-- valkey-cli SET cookbook:region:alice eu
-- An account without a region is not emitted and may log in from everywhere. The script does not know the client's
-- country: the native GeoIP plugin provides that fact, and the policy rules in nauthilus.yml combine both.
local nauthilus_redis = require("nauthilus_redis")
local nauthilus_policy = require("nauthilus_policy")
-- Regions the policy rules know. Anything else is ignored, so a typo cannot lock an account out by accident.
local KNOWN_REGIONS = { eu = true, us = true }
function nauthilus_call_environment(request)
local region, err = nauthilus_redis.redis_get("default", "cookbook:region:" .. (request.username or ""))
if err ~= nil then
return nauthilus_builtin.ENVIRONMENT_TRIGGER_NO,
nauthilus_builtin.ENVIRONMENT_ABORT_NO,
nauthilus_builtin.ENVIRONMENT_RESULT_FAIL
end
if type(region) == "string" and KNOWN_REGIONS[string.lower(region)] then
region = string.lower(region)
nauthilus_builtin.custom_log_add("account_region", region)
nauthilus_policy.emit_attribute({ id = "lua.plugin.cookbook.account.region", value = region })
end
return nauthilus_builtin.ENVIRONMENT_TRIGGER_NO,
nauthilus_builtin.ENVIRONMENT_ABORT_NO,
nauthilus_builtin.ENVIRONMENT_RESULT_OK
end
- The region comes from Valkey, so an administrator, a script, or a custom hook can change it at any time.
- Only the known regions
euandusare emitted. A typo such asmarsis ignored instead of locking the account. - The script always returns "not triggered". It only delivers a fact; the decision is the policy's.
nauthilus_builtin.custom_log_addaddsaccount_region=euto the log line of the request.
The policy registry script
-- policy/registry.lua
-- Policy registry script of the "Country rules per account" recipe. It declares the attribute that
-- environment/account_region.lua emits, so that the rules in nauthilus.yml can test it.
nauthilus_policy.register_attribute({
id = "lua.plugin.cookbook.account.region",
stage = "pre_auth",
operations = { "authenticate" },
category = "environment",
type = "string",
description = "Region from which the account may log in (eu or us).",
})
The attribute is a string emitted at pre_auth. Native plugins declare their facts in their own code; Lua declares
its attributes in a registry script.
What the test checks
#!/usr/bin/env bash
# Checks the "Country rules per account" 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:28087}"
# Addresses of the demo GeoIP database (nauthilus/geoip/geoip.json) and one it does not know.
GERMANY=192.0.2.10
USA=198.51.100.10
BRAZIL=203.0.113.10
UNKNOWN=10.9.9.9
NOT_ALLOWED="Login from this country is not allowed for this account"
UNKNOWN_LOCATION="Login location unknown, login not allowed for this account"
# Start from a clean state: no regions, no cached logins.
valkey FLUSHALL >/dev/null
section "Native plugin loaded"
if docker compose logs nauthilus 2>/dev/null | grep -q "Required plugin module registration failed"; then
fail "the GeoIP plugin failed to register"
else
pass "the GeoIP plugin registered"
fi
section "Accounts without a region"
for ip in $GERMANY $USA $BRAZIL $UNKNOWN; do
auth bob bob-secret imap "$ip"
expect_auth_status "OK" "bob logs in from $ip"
done
section "Account with region eu"
valkey SET cookbook:region:alice eu >/dev/null
auth alice alice-secret imap $GERMANY
expect_auth_status "OK" "alice (eu) logs in from Germany"
auth alice alice-secret imap $USA
expect_auth_status "$NOT_ALLOWED" "alice (eu) is refused from the USA"
auth alice alice-secret imap $BRAZIL
expect_auth_status "$NOT_ALLOWED" "alice (eu) is refused from Brazil"
auth alice alice-secret imap $UNKNOWN
expect_auth_status "$UNKNOWN_LOCATION" "alice (eu) is refused from an address without a known location"
auth alice wrong-password imap $USA
expect_auth_status "$NOT_ALLOWED" "the rule answers before the password is checked"
section "The administrator changes the region"
valkey SET cookbook:region:alice us >/dev/null
auth alice alice-secret imap $USA
expect_auth_status "OK" "alice (us) logs in from the USA at once"
auth alice alice-secret imap $GERMANY
expect_auth_status "$NOT_ALLOWED" "alice (us) is now refused from Germany"
valkey SET cookbook:region:alice mars >/dev/null
auth alice alice-secret imap $BRAZIL
expect_auth_status "OK" "an unknown region value is ignored instead of locking the account"
valkey DEL cookbook:region:alice >/dev/null
auth alice alice-secret imap $BRAZIL
expect_auth_status "OK" "without a region alice logs in from everywhere again"
section "Many requests"
valkey SET cookbook:region:alice eu >/dev/null
wrong=0
for i in $(seq 1 100); do
auth alice alice-secret imap "192.0.2.$(( (i % 200) + 1 ))"
[ "$(header Auth-Status)" = "OK" ] || wrong=$((wrong + 1))
auth alice alice-secret imap "198.51.100.$(( (i % 200) + 1 ))"
[ "$(header Auth-Status)" = "$NOT_ALLOWED" ] || wrong=$((wrong + 1))
done
expect_equal 0 "$wrong" "200 logins got the expected answer"
valkey DEL cookbook:region:alice >/dev/null
finish
Ideas for your own changes
- Add a region
dachwith[DE, AT, CH]: one more condition set, one more rule, anddachinKNOWN_REGIONS. - Allow every country from your office network: add it to
geoip.jsonand a rule condition onplugin.geoip.network. - Use a licensed MaxMind database: set
database_pathto the.mmdbfile anddatabase_format: mmdb. - Let the Login journal POST-action record the country as well. Lua cannot read plugin facts, but a native POST-action such as the bundled ClickHouse plugin receives them.