Skip to main content
Version: Next

Recipe: Policy API

Nauthilus is not only for logins. Its Policy API answers any yes-or-no question that you describe in the configuration. In this recipe a VPN gateway asks: "May a member of this group connect now?" Staff may connect on working days from 07:00 to 19:00, contractors for a shorter time, administrators always.

Interface: generic policy provider (kind: lua) with policy.facts.collect and policy.effects.execute.
Download: policy-api.tar.gz

What happens​

  1. The VPN gateway sends POST /api/v1/policy/decisions with the user's group and its local weekday and hour.
  2. Nauthilus checks the gateway's credential and that it may ask this question with these facts.
  3. The Lua provider looks the group up in a schedule and returns the fact lua.office_hours.allowed.
  4. A rule permits or denies. A deny also runs the obligation audit-denial, which calls back into the same script.
  5. The gateway reads effect from the answer: permit, deny, or indeterminate.

Start and test​

The Policy API accepts Basic credentials only over TLS. setup.sh creates a self-signed certificate for 127.0.0.1 once:

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

Ask by hand:

curl --cacert tls/server.crt -u vpn-gateway:vpn-gateway-policy-secret \
-H 'Content-Type: application/json' \
-d '{
"version": "1",
"target": {"namespace": "vpn", "action": "connect"},
"subject": {"type": "user", "id": "alice", "attributes": {"group": {"string": "staff"}}},
"environment": {"service": "vpn", "attributes": {"weekday": {"string": "mon"}, "hour": {"integer": "9"}}}
}' \
https://127.0.0.1:28086/api/v1/policy/decisions
{"decision_id":"decision-…","effect":"permit","request_id":"request-…",
"status":{"code":"permit","message":"The policy explicitly permitted the operation.","retryable":false}}

The stack​

docker-compose.yml
# Lua Cookbook recipe "Policy API".
# Start with: ./setup.sh && docker compose up -d --wait Test with: ./test.sh Stop with: docker compose down
name: cookbook-policy-api

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:28086:8443"
volumes:
- ./nauthilus/nauthilus.yml:/etc/nauthilus/nauthilus.yml:ro
- ./nauthilus/lua:/etc/nauthilus/lua:ro
- ./tls:/etc/nauthilus/tls:ro
healthcheck:
test: ["CMD", "/usr/app/healthcheck", "--url", "https://127.0.0.1:8443/healthz", "--tls-skip-verify"]
interval: 5s
timeout: 3s
retries: 30
setup.sh
#!/usr/bin/env sh
# Creates a self-signed TLS certificate for 127.0.0.1 and localhost in ./tls. The Policy API accepts Basic
# credentials only over TLS, so Nauthilus serves HTTPS in this recipe. Run once before docker compose up.
set -eu
cd "$(dirname "$0")"
mkdir -p tls

if [ ! -f tls/server.key ]; then
openssl req -x509 -newkey rsa:2048 -nodes -days 365 \
-keyout tls/server.key -out tls/server.crt \
-subj "/CN=localhost" \
-addext "subjectAltName=DNS:localhost,IP:127.0.0.1" 2>/dev/null
# Nauthilus runs as user 65532 in the container and must be able to read the key.
chmod 0644 tls/server.key tls/server.crt
fi

echo "TLS certificate: $(pwd)/tls/server.crt"

The configuration​

nauthilus/nauthilus.yml
# Nauthilus configuration of the "Policy API" Lua Cookbook recipe.
# Interface shown: a generic policy provider (kind: lua) behind the Policy HTTP API.

runtime:
instance_name: "cookbook-policy-api"

servers:
http:
address: "0.0.0.0:8443"
# Policy Basic credentials are accepted only over TLS. setup.sh creates the self-signed demo certificate.
tls:
enabled: true
cert: "/etc/nauthilus/tls/server.crt"
key: "/etc/nauthilus/tls/server.key"

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

storage:
redis:
primary:
address: "valkey:6379"
database_number: 0
prefix: "nt:"
# Demo values only. Generate your own random strings for a real installation.
password_nonce: "cookbookPasswordNonce06"
encryption_secret: "cookbookEncryption06"

# Nauthilus always starts its backchannel HTTP API, which needs at least one credential. This recipe does not use it.
auth:
backchannel:
basic_auth:
enabled: true
users:
- username: "unused"
password: "unused-backchannel-secret"
scopes:
- "nauthilus:authenticate"

policy:
# The Policy HTTP API: POST /api/v1/policy/decisions
api:
enabled: true
http:
enabled: true
grpc:
enabled: false
clients:
# One client profile per caller. It says which target the caller may ask about and which facts it may send.
- principal: vpn-gateway
authentication_kinds: [basic]
authentication:
basic:
username: vpn-gateway
# Demo value only.
password: "vpn-gateway-policy-secret"
targets:
- namespace: vpn
actions: [connect]
allowed_schemas: [vpn/connect/v1]
allowed_subject_attributes: [group]
allowed_resource_attributes: []
allowed_environment_attributes: [weekday, hour]
allowed_input_attributes: []

namespaces:
vpn:
# The schema lists every fact of a "vpn/connect" request: three from the caller, one from Lua.
schema_contributions:
static:
connect:
versions:
v1:
facts:
- {attribute: subject.group, category: subject, type: string, allowed_sources: [caller]}
- {attribute: environment.weekday, category: environment, type: string, allowed_sources: [caller]}
- {attribute: environment.hour, category: environment, type: integer, allowed_sources: [caller]}
- {attribute: lua.office_hours.allowed, category: environment, type: boolean, allowed_sources: [lua]}

providers:
office_hours:
kind: lua
module: office_hours
script_path: "/etc/nauthilus/lua/office_hours.lua"
targets: [{action: connect}]
produced_facts: [lua.office_hours.allowed]
executions: [host_sync]
# If the script fails, the decision is "indeterminate" instead of a guess.
failure: indeterminate
timeout: 100ms

effects:
audit-denial:
kind: obligation
provider: vpn/office_hours
targets: [{action: connect}]
execution: host_sync
parameters:
reason:
type: string
max_length: 64
non_empty: true
required: true

# The domain plan runs the Lua provider before the rules of final_decision are evaluated.
domain_plans:
connect:
checkpoints:
final_decision:
providers:
- name: office_hours
use: vpn/office_hours
actions: [connect]

policy_sets:
connect:
rules:
- name: permit_in_office_hours
checkpoint: final_decision
if: {attribute: lua.office_hours.allowed, is: true}
then: {decision: permit}
- name: deny_outside_office_hours
checkpoint: final_decision
if: {attribute: lua.office_hours.allowed, is: false}
then:
decision: deny
obligations:
- id: vpn/audit-denial
parameters: {reason: outside_office_hours}

targets:
- namespace: vpn
action: connect
schema: vpn/connect/v1
domain_plan: vpn/connect
default_policy: vpn/connect
no_match: deny
timeouts: {evaluation: 2s, provider_default: 500ms}
plans:
final_decision: {policy_sets: [vpn/connect]}
  • runtime.servers.http.tls serves HTTPS with the certificate from setup.sh. Over plain HTTP the Policy API refuses Basic credentials with 401 policy credentials rejected.
  • auth.backchannel is not used by this recipe, but Nauthilus always starts its backchannel API and needs at least one credential for it.
  • policy.api switches on the HTTP Policy API. Each entry of clients is one caller:
    • authentication holds its Basic credential. Policy credentials are separate from backchannel credentials.
    • targets and allowed_schemas limit the questions it may ask.
    • allowed_subject_attributes and allowed_environment_attributes list the facts it may send. A request with any other fact is refused with HTTP 403.
  • policy.namespaces.vpn describes the question:
    • The schema vpn/connect/v1 lists every fact with its type and its source: three from the caller (allowed_sources: [caller]), one from Lua ([lua]). A fact from the wrong source is refused, so a caller cannot send lua.office_hours.allowed itself.
    • The provider office_hours names the script. produced_facts is the contract: the script may return only these facts. failure: indeterminate makes a broken script answer indeterminate, never a guess.
    • The effect audit-denial is an obligation with one typed parameter. Nauthilus checks the parameter before the script sees it.
    • The domain plan runs the provider at the final_decision checkpoint. use names the provider by its configured key, vpn/office_hours.
    • The rules permit when the fact is true and deny, with the obligation, when it is false.
  • policy.targets activates the question. no_match: deny denies whatever no rule decided.

The Lua provider​

nauthilus/lua/office_hours.lua
-- office_hours.lua
-- Generic policy provider of the "Policy API" recipe. A VPN gateway asks Nauthilus "may this user connect now?".
-- The gateway sends the user's group and its local weekday and hour; this script looks the group up in a schedule
-- and returns one fact, lua.office_hours.allowed. A policy rule in nauthilus.yml turns that fact into the decision.
--
-- Generic providers run in a small sandbox: a fresh Lua state per call with only the base, table, string, and math
-- libraries. There is no os, io, require, or Nauthilus module, so the caller supplies the time.

-- Which groups may connect when. Hours are "from" inclusive, "to" exclusive.
local SCHEDULE = {
admins = { days = "mon,tue,wed,thu,fri,sat,sun", from = 0, to = 24 },
staff = { days = "mon,tue,wed,thu,fri", from = 7, to = 19 },
contractors = { days = "mon,tue,wed,thu", from = 9, to = 17 },
}

-- fact_values turns the request's fact list into a table: id -> plain Lua value.
local function fact_values(facts)
local values = {}

for _, fact in ipairs(facts or {}) do
local value = fact.value or {}

if value.kind == "integer" then
values[fact.id] = tonumber(value.value)
else
values[fact.id] = value.value
end
end

return values
end

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

return false
end

-- allowed decides one request from the schedule.
local function allowed(group, weekday, hour)
local rule = SCHEDULE[group or ""]

if rule == nil or weekday == nil or hour == nil then
return false
end

return contains(rule.days, string.lower(weekday)) and hour >= rule.from and hour < rule.to
end

_G["policy.facts.collect"] = function(request)
local values = fact_values(request.facts)
local result = allowed(values["subject.group"], values["environment.weekday"], values["environment.hour"])

return {
facts = {
-- The host turns the local name "allowed" into lua.office_hours.allowed.
{ name = "allowed", value = { kind = "boolean", value = result } },
},
}
end

-- The deny rule selects the obligation vpn/audit-denial. Its typed parameters were checked by the host before this
-- callback runs. A sandboxed script cannot write anywhere, so it only validates and reports success.
_G["policy.effects.execute"] = function(request)
return { state = "succeeded" }
end

A generic provider is different from the authentication scripts of the other recipes:

  • It registers its callbacks as globals with the exact names policy.facts.collect and policy.effects.execute.
  • It runs in a sandbox: a fresh Lua state for every call, with only the base, table, string, and math libraries. There is no os, io, require, Redis, or HTTP, and nothing survives from one request to the next. Everything the script needs arrives in request or is written into the script, like SCHEDULE.
  • request.facts is a list of {id, category, value = {kind, value}}. Integers arrive as decimal strings, so fact_values converts them with tonumber.
  • The result names a fact by its local name (allowed); Nauthilus adds the provider prefix and checks type and source against the schema.
  • policy.effects.execute runs for a selected obligation. It returns succeeded, or failed with an error_class; a failed effect turns the decision into indeterminate. Without I/O there is little a sandboxed effect can do, so this one only reports success. Real side effects belong to native Go plugins or to the authentication actions of the Login journal.

What the test checks​

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

NAUTHILUS_URL="${NAUTHILUS_URL:-https://127.0.0.1:28086}"
GATEWAY="vpn-gateway:vpn-gateway-policy-secret"

# connect asks whether a user of a group may connect at a weekday and hour. Arguments: group weekday hour
connect() {
http POST /api/v1/policy/decisions --cacert tls/server.crt -u "$GATEWAY" \
-H 'Content-Type: application/json' \
-d "{
\"version\": \"1\",
\"target\": {\"namespace\": \"vpn\", \"action\": \"connect\"},
\"subject\": {\"type\": \"user\", \"id\": \"alice\", \"attributes\": {\"group\": {\"string\": \"$1\"}}},
\"environment\": {\"service\": \"vpn\", \"attributes\": {
\"weekday\": {\"string\": \"$2\"}, \"hour\": {\"integer\": \"$3\"}}}
}"
}

# expect_effect checks the decision of the last answer. Arguments: effect description
expect_effect() {
expect_body_contains "\"effect\":\"$1\"" "$2"
}

section "Office hours"
connect staff mon 9
expect_status 200 "the Policy API answers"
expect_effect permit "staff may connect on Monday at 09:00"

connect staff mon 19
expect_effect deny "staff may not connect on Monday at 19:00"
expect_body_contains '"code":"policy_denied"' "the deny comes from the rule, which also runs the audit obligation"

connect staff sat 10
expect_effect deny "staff may not connect on Saturday"

connect admins sun 3
expect_effect permit "admins may connect at any time"

connect contractors thu 16
expect_effect permit "contractors may connect on Thursday at 16:00"

connect contractors fri 10
expect_effect deny "contractors may not connect on Friday"

connect visitors mon 9
expect_effect deny "an unknown group is denied"

section "Admission"
http POST /api/v1/policy/decisions --cacert tls/server.crt -u vpn-gateway:wrong-password-1234 \
-H 'Content-Type: application/json' -d '{"version": "1", "target": {"namespace": "vpn", "action": "connect"}}'
expect_status 401 "a wrong password is rejected"

http POST /api/v1/policy/decisions --cacert tls/server.crt -u "$GATEWAY" -H 'Content-Type: application/json' \
-d '{"version": "1", "target": {"namespace": "vpn", "action": "connect"},
"subject": {"type": "user", "id": "alice", "attributes": {"department": {"string": "it"}}}}'
expect_status 403 "a fact outside the client profile is refused"

section "Many requests"
wrong=0
for hour in $(seq 0 23); do
for day in mon sat; do
connect staff "$day" "$hour"
expected=deny
[ "$day" = mon ] && [ "$hour" -ge 7 ] && [ "$hour" -lt 19 ] && expected=permit
case "$last_body" in *"\"effect\":\"$expected\""*) ;; *) wrong=$((wrong + 1)) ;; esac
done
done
expect_equal 0 "$wrong" "48 decisions over a whole Monday and Saturday are right"

finish

The test asks for every hour of a Monday and a Saturday and compares each answer with the schedule. It also checks that a wrong password and a fact outside the client profile are refused.

Ideas for your own changes​

  • Add a group night-shift that may connect from 18:00 to 06:00. Watch the wrap-around at midnight.
  • Let the gateway send resource.attributes.network and allow contractors only for one network.
  • Ask from a second caller with its own client profile and a smaller set of allowed facts.