Skip to content

Gate requests at an NGINX edge

Put POST /v1/decide on the request path, in NGINX, before your origin does any work. Two configurations follow. Every file they need is on this page:

  • OpenResty, access_by_lua_block and lua-resty-http. Use this one.
  • njs, an auth_request subrequest that translates the decide response into a status auth_request understands.

Both map the caller’s own credential to that caller’s Ordainer agent key, ask for one tool, and either proxy the request or stop it. The sample log_format records the decide request id. It does not record the agent key or the Authorization header.

A later section shows why a plain auth_request location, with no translation step, cannot do this with the current decide API.

auth_request sends an internal subrequest and looks only at the status code. 2xx allows the request. 401 and 403 deny it. Any other status is an error, and NGINX answers the caller 500. The subrequest body is discarded. Response headers are kept only when you copy them with auth_request_set (a 401 also passes WWW-Authenticate).

Decide does not speak those codes:

What you need What POST /v1/decide does What auth_request does with that
Method and body POST /v1/decide only. GET on that path is 405. tool is read only from the JSON body. The agent key is Authorization: Bearer. The Idempotency-Key header is accepted when the body has no idempotency_key. The subrequest is GET with no body unless the internal location sets proxy_method POST, proxy_set_body, and Content-Type. The body can be set that way. The body is not why this fails.
A deny allow and every deny are HTTP 200. The answer is the JSON field decision. There is no decision header. Any 2xx allows the request. The body is never read, so every deny is proxied.
429 and 503 429 (rate_limited, concurrency_limited, too_many_failed_auth, safety_limit_reached) carries Retry-After. 503 (decide_timeout, db_unavailable, db_timeout) carries Retry-After: 1. 401 is a key error. Only 401 and 403 are passed on. 429 and 503 become 500. Retry-After does not reach the caller, and a 429 cannot be told apart from an outage.

The njs configuration below still uses auth_request, but the subrequest returns only 204 or 403. The real status is put back afterwards. The OpenResty configuration does not use auth_request at all.

A plain auth_request location that posts to decide proxies every deny, and turns a 429 into a 500 with no Retry-After.

The route chooses tool. Do not copy tool from the caller, and do not forward the caller’s body to decide. In this recipe the body has tool, for example agent.run, and on OpenResty it also has lease unless you turn it off (see below). njs omits lease unless you opt in. Send the mapped agent key as Authorization: Bearer, and send Idempotency-Key set to NGINX’s $request_id (32 hex characters, inside the 1–255 character limit). The retry uses that same value. A 409 idempotency_conflict means this edge reused one idempotency key for a different tool or mode. That is a bug in the edge. Block it and alert. Do not retry it.

Each attempt waits 300 ms (connect, send, and read). That sits above the server deadline of 250 ms (DECIDE_DEADLINE_MS), so a finished 503 decide_timeout usually arrives as a response rather than a client timeout. On a connect error, a timeout, or any 5xx, try once more with the same idempotency key, after 50 ms. Worst case is about 650 ms, the same budget as the Node SDK. In OpenResty the 300 ms applies to the connect, the send, and each read separately, so a decide that sends its answer a few bytes at a time can stretch one attempt. The njs timer bounds the whole attempt. The SDK retries a timeout, a network error, or a 503, and applies its fail mode to a 500 without a second try. This edge retries every 5xx once, including 500 internal_error, 502, and 504 from a proxy in front of the API. A 2xx or a 4xx is not retried.

The first decide on each worker after a start or reload can use the retry path or, in fail-closed mode, return 503, when DNS plus TLS takes more than 300 ms. js_fetch_keepalive 8 in the njs configuration keeps the warmed connection for later calls in that worker only. A single warmup request cannot warm every worker when worker_processes is auto.

Then:

Answer What the edge does
200 with decision: "allow" Proxy. Forward X-Request-Id upstream as X-Ordainer-Request-Id.
200 with decision: "deny" and mode: "shadow" Proxy. A shadow deny is a would-deny: the call runs. See Shadow mode.
200 with decision: "deny" and mode enforce, or with no mode Stop the request. quota_exceeded, test_limit_reached and concurrency_exhausted are 429. Every other reason, including tool_not_in_plan and a reason you have not seen before, is 403. The body keeps reason and, when decide sent them, explanation and message.
HTTP 429 Pass the status, the body, and Retry-After through. This blocks in both fail modes.
400, 401, and any other 4xx Pass the status and the body through, block, and log ordainer_alert with the status, error.code, and request id. Do not log the key.
Connect error, timeout, or 5xx after the retry Fail open by default: proxy, and log ordainer_fail_open. Set ORDAINER_FAIL_MODE=closed to answer 503 with Retry-After: 5 and error.code edge_unavailable instead. That code is this edge’s, not an API code.
200 whose body is not a decision Same as an outage: fail open, or fail closed when that is selected.
njs backstop (the /_ordainer subrequest or the handler stalls past proxy_read_timeout 2s) Answer 503 edge_unavailable with Retry-After: 5 in either fail mode. The origin is not reached. A decide outage does not hit this path: the 300 ms timer settles that first, at about 650 ms.

A decide the edge gave up on can still be counted. If both attempts miss the 300 ms budget, fail-closed answers 503 and the origin does not run, but a late in-flight decide can still commit one allow against the quota. The retry reuses the same idempotency key, so that count is at most one per caller request. In fail-open the origin still runs, so the count is close to correct. With a lease, that late allow also holds a session until its TTL, because the edge never saw lease.id and can’t release it. This happens on OpenResty (default TTL 120 s) and on njs when you have opted in to lease. A retry that succeeds gets the same lease back through the idempotency key and, on OpenResty, releases it normally; on njs the slot still ends at the TTL. With session_limit 1 and fail-closed, one cold-start 503 can lock the key for 2 minutes.

explanation is a sentence on a quota_exceeded deny, in either mode. Do not parse it. An enforce test_limit_reached deny may include message instead. tool_not_in_plan also sets tool_in_plan to false. Treat an unknown reason on a deny as a deny. The field list is on Decide.

For a 429 the edge builds from a deny (quota_exceeded or test_limit_reached), Retry-After is the seconds until resets_at, at least 1 and at most 3600. A 403 built from a deny (tool_not_in_plan, or any other reason) has no Retry-After. For tool_not_in_plan, waiting does not change the answer. concurrency_exhausted is also a 429, but with a short Retry-After of 1: decide’s resets_at is the plan’s period end, not the time a session frees up, so the edge does not use it. The body’s resets_at is still the plan’s period end. Callers should follow Retry-After. Decide’s own 429 already has Retry-After; the edge copies that value and does not replace it. Error bodies from the API keep their shape, {"error":{"code","message","request_id"}}. Branch on error.code. The list is on Errors.

The OpenResty recipe sends lease on decide (default ttl_s 120; set ORDAINER_LEASE_TTL_S, or a non-positive value to omit lease). The njs recipe omits lease unless you set a positive ORDAINER_LEASE_TTL_S (unset or 0 means no lease). On njs, the session limit isn’t enforced at the edge unless you opt in. When the agent key has a session limit and lease was sent, an allow returns lease.id. At the limit, enforce answers HTTP 200 deny concurrency_exhausted and takes no lease; that deny is retryable and clears when one of the key’s running sessions is released or its lease runs out. See Finishing a session.

A 429 is not an outage. rate_limited, concurrency_limited, and too_many_failed_auth all block, in fail open and in fail closed. The Node SDK rewrites too_many_failed_auth into its own 500 response. This edge does not: the caller sees the API’s 429, body, and Retry-After.

429 safety_limit_reached is the exception in the SDK. It means shadow calls passed 10 times the monthly test limit, and the Node SDK (1.2.0 and later) runs the call in every fail mode. This edge blocks that 429 like every other 429, so the safety signal is not dropped on the floor. Set ORDAINER_SAFETY_LIMIT=allow to proxy it, which matches the SDK.

The agent key is sent only on the decide request. The proxy to your origin keeps the caller’s own Authorization header. Do not replace it with the Ordainer key.

access_by_lua_block runs in the access phase, where a cosocket is allowed. The block calls POST /v1/decide. On allow it returns, and proxy_pass continues. On a block it writes the status and the body and exits. After the response, log_by_lua_block schedules a 0-delay timer that releases the session lease. Cosockets are not allowed in the log phase, so the HTTP call cannot run directly in log_by_lua.

You need three files: nginx.conf, the check in ordainer.lua, and the key map in keys.lua. The check uses lua-resty-http (httpc:set_timeout(300) and request_uri). Install it into OpenResty’s lualib/resty/ (this recipe was run with the lua-resty-http v0.15 release, whose _VERSION field still reads 0.14).

The origin is 127.0.0.1:3000 and the tool is agent.run. Change both for your route.

/usr/local/openresty/nginx/conf/nginx.conf
# Debian and Ubuntu name the group nogroup. Elsewhere it may be nobody.
user nobody nogroup;
worker_processes auto;
error_log logs/error.log warn;
# Workers see only the environment variables listed here.
env ORDAINER_DECIDE_URL;
env ORDAINER_FAIL_MODE;
env ORDAINER_SAFETY_LIMIT;
env ORDAINER_LEASE_TTL_S;
events {
worker_connections 1024;
}
http {
lua_package_path "/etc/nginx/lua/?.lua;;";
lua_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
lua_ssl_verify_depth 5;
# Must resolve api.ordainer.dev. ipv6=off keeps a missing AAAA answer
# from spending the 300 ms attempt budget.
resolver 1.1.1.1 valid=10s ipv6=off;
resolver_timeout 1s;
# No $http_authorization: the caller token and the agent key are never logged.
log_format ordainer '$remote_addr [$time_local] "$request" $status '
'rid=$request_id ordainer_rid=$ordainer_request_id '
'decision=$ordainer_decision reason=$ordainer_reason '
'rt=$request_time';
access_log logs/access.log ordainer;
upstream origin {
server 127.0.0.1:3000;
keepalive 16;
}
server {
listen 8080;
server_tokens off;
location / {
# The route picks the tool. Never take it from the caller.
set $ordainer_tool "agent.run";
# Declared before the access phase: ordainer.lua writes them and the
# log_format reads them.
set $ordainer_request_id "-";
set $ordainer_decision "-";
set $ordainer_reason "-";
set $ordainer_mode "-";
access_by_lua_block {
require("ordainer").gate()
}
log_by_lua_block {
require("ordainer").release_after()
}
add_header X-Ordainer-Request-Id $ordainer_request_id always;
add_header X-Edge-Request-Id $request_id always;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Ordainer-Request-Id $ordainer_request_id;
proxy_set_header X-Ordainer-Decision $ordainer_decision;
proxy_set_header X-Ordainer-Reason $ordainer_reason;
proxy_set_header X-Ordainer-Mode $ordainer_mode;
# The origin may trust X-Ordainer-* headers. Set or clear every one
# this edge uses so a caller's copy never reaches the origin.
proxy_set_header X-Ordainer-Tool $ordainer_tool;
proxy_set_header X-Ordainer-Status "";
proxy_set_header X-Ordainer-Retry-After "";
proxy_set_header X-Ordainer-Body "";
proxy_pass http://origin;
}
}
}
/etc/nginx/lua/ordainer.lua
-- Edge check for POST /v1/decide. Called from access_by_lua_block.
--
-- Rules (match the decide API and the Node SDK's outage behaviour, with the
-- differences noted on this page):
-- * POST JSON {"tool": <route tool>} with Authorization: Bearer <mapped key>
-- and Idempotency-Key = this request's id, reused on the one retry.
-- When ORDAINER_LEASE_TTL_S is a positive integer (default 120), the body
-- also includes lease.
-- * 300 ms per attempt. One retry on connect error, timeout, or any 5xx.
-- 50 ms between them. No retry of a 2xx or a 4xx.
-- * Allow, and a deny whose mode is shadow: proxy. After an allow that
-- returned lease.id, log_by_lua schedules ngx.timer.at(0) to POST
-- /v1/leases/:id/release (300 ms). A finish failure is logged with the
-- request id only and never changes the client response.
-- * Enforce deny: 429 for quota_exceeded and test_limit_reached (Retry-After
-- until resets_at, capped at 3600), 429 for concurrency_exhausted with
-- Retry-After 1, 403 for every other reason.
-- * API 429: pass status, body, and Retry-After through. Always blocks,
-- unless ORDAINER_SAFETY_LIMIT=allow and the code is safety_limit_reached.
-- * 400 and 401, and every other 4xx: pass the body through, block, and log
-- ordainer_alert. 409 idempotency_conflict means this edge reused one
-- idempotency key for a different tool or mode.
-- * After the retry, connect errors, timeouts, and 5xx follow
-- ORDAINER_FAIL_MODE (default open). Closed answers 503 edge_unavailable.
-- The Ordainer key and the caller token are never written to a log line.
-- X-Ordainer-Request-Id and X-Edge-Request-Id on the caller response come from
-- add_header ... always in nginx.conf, so they are not set here as well.
local http = require("resty.http")
local cjson = require("cjson.safe")
local keys = require("keys")
local M = {}
local TIMEOUT_MS = 300
local RETRY_PAUSE = 0.05
local RETRY_AFTER_CAP = 3600
local function getenv(name, fallback)
local value = os.getenv(name)
if value == nil or value == "" then return fallback end
return value
end
local function fail_mode()
if getenv("ORDAINER_FAIL_MODE", "open") == "closed" then return "closed" end
return "open"
end
local function safety_allows()
return getenv("ORDAINER_SAFETY_LIMIT", "block") == "allow"
end
local function decide_url()
return getenv("ORDAINER_DECIDE_URL", "https://api.ordainer.dev/v1/decide")
end
-- Nil means do not send lease. Default 120, capped at the API max of 3600.
local function lease_ttl_s()
local value = getenv("ORDAINER_LEASE_TTL_S", "120")
local n = tonumber(value)
if n == nil or n < 1 then return nil end
n = math.floor(n)
if n > 3600 then n = 3600 end
return n
end
local function release_url(lease_id)
local decide = decide_url()
local base = decide:gsub("/v1/decide/?$", "")
return base .. "/v1/leases/" .. lease_id .. "/release"
end
-- Stash what the timer needs. ngx.ctx is gone once the timer runs, so
-- release_after copies these into upvalues. Never log the key.
local function remember_lease(agent_key, body, rid)
local lease = body and body.lease
if type(lease) ~= "table" or type(lease.id) ~= "string" or lease.id == "" then
return
end
if type(agent_key) ~= "string" or agent_key == "" then return end
ngx.ctx.ordainer_lease = { id = lease.id, key = agent_key, rid = rid }
end
local function header_value(headers, name)
if type(headers) ~= "table" then return nil end
local value = headers[name] or headers[string.lower(name)]
if type(value) == "table" then value = value[1] end
if type(value) ~= "string" or value == "" then return nil end
return value
end
local function caller_token()
local header = ngx.var.http_authorization or ""
return header:match("^[Bb]earer%s+(%S+)%s*$")
end
-- add_header and proxy_set_header copy these variables as they are, so a
-- CR, LF or NUL from the decide body would split a header. Use a space.
local function one_line(value)
return (string.gsub(value, "[\r\n%z]+", " "))
end
local function set_request_id(rid)
if type(rid) ~= "string" or rid == "" then return end
ngx.var.ordainer_request_id = one_line(rid)
end
local function alert(status, code, rid)
ngx.log(ngx.ERR, "ordainer_alert status=", tostring(status),
" code=", code or "-", " request_id=", rid or "-")
end
local function note(kind, detail, rid)
ngx.log(ngx.ERR, "ordainer_", kind, " detail=", detail or "-",
" request_id=", rid or "-")
end
local function finish(status, payload, extra)
ngx.status = status
ngx.header["Content-Type"] = "application/json; charset=utf-8"
ngx.header["Cache-Control"] = "no-store"
if extra then
for name, value in pairs(extra) do
if value ~= nil and value ~= "" then ngx.header[name] = value end
end
end
ngx.print(cjson.encode(payload))
return ngx.exit(status)
end
local function pass_through(status, res, rid)
set_request_id(rid)
ngx.status = status
ngx.header["Content-Type"] = header_value(res.headers, "content-type") or "application/json; charset=utf-8"
ngx.header["Cache-Control"] = "no-store"
local retry = header_value(res.headers, "retry-after")
if retry then ngx.header["Retry-After"] = retry end
ngx.print(res.body or "")
return ngx.exit(status)
end
local function closed_body(rid)
return finish(503, {
error = {
code = "edge_unavailable",
message = "This call was not run. The edge could not get a decision. Try again in a minute.",
request_id = rid,
},
}, { ["Retry-After"] = "5" })
end
local function give_up(kind, detail, rid)
-- Keep a request id we already parsed (a 5xx body, for example) on the
-- fail-open proxy and in the access log. A timeout that never got a
-- response has nothing to keep.
if rid then set_request_id(rid) end
if fail_mode() == "closed" then
alert(503, kind, rid)
return closed_body(rid)
end
note("fail_open", kind .. ":" .. (detail or "-"), rid)
return
end
local HTTP_MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }
local HTTP_WDAYS = { "Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed" }
-- Days since 1970-01-01 for a civil UTC date. Independent of the process timezone.
local function days_from_civil(y, m, d)
y = y - (m <= 2 and 1 or 0)
local era = math.floor(y >= 0 and y / 400 or (y - 399) / 400)
local yoe = y - era * 400
local doy = math.floor((153 * (m + (m > 2 and -3 or 9)) + 2) / 5) + d - 1
local doe = yoe * 365 + math.floor(yoe / 4) - math.floor(yoe / 100) + doy
return era * 146097 + doe - 719468
end
-- Seconds until resets_at, minimum 1, maximum 3600.
-- ngx.parse_http_time reads the GMT date, and ngx.time is UTC, so TZ does not matter.
local function retry_after_until(resets_at)
if type(resets_at) ~= "string" then return "1" end
local y, mo, d, h, mi, s = resets_at:match("^(%d%d%d%d)%-(%d%d)%-(%d%d)T(%d%d):(%d%d):(%d%d)")
if not y then return "1" end
y, mo, d = tonumber(y), tonumber(mo), tonumber(d)
h, mi, s = tonumber(h), tonumber(mi), tonumber(s)
local month = HTTP_MONTHS[mo]
if not month or not y or not d or not h or not mi or not s then return "1" end
local days = days_from_civil(y, mo, d)
local wday = HTTP_WDAYS[(days % 7) + 1]
local http_date = string.format("%s, %02d %s %04d %02d:%02d:%02d GMT", wday, d, month, y, h, mi, s)
local reset = ngx.parse_http_time(http_date)
if not reset then return "1" end
local sec = reset - ngx.time()
if sec < 1 then return "1" end
if sec > RETRY_AFTER_CAP then return tostring(RETRY_AFTER_CAP) end
return tostring(sec)
end
local function call_decide(agent_key, tool, idempotency_key)
local payload = { tool = tool }
local ttl = lease_ttl_s()
if ttl then payload.lease = { ttl_s = ttl } end
local httpc = http.new()
httpc:set_timeout(TIMEOUT_MS)
local res, err = httpc:request_uri(decide_url(), {
method = "POST",
body = cjson.encode(payload),
headers = {
["Authorization"] = "Bearer " .. agent_key,
["Content-Type"] = "application/json",
["Idempotency-Key"] = idempotency_key,
["Accept"] = "application/json",
},
ssl_verify = true,
keepalive = false,
})
if not res then return nil, err or "network_error" end
return res, nil
end
local function request_id_of(res, body)
local rid = header_value(res.headers, "x-request-id")
if rid then return rid end
if type(body) ~= "table" then return nil end
if type(body.request_id) == "string" then return body.request_id end
if type(body.error) == "table" and type(body.error.request_id) == "string" then
return body.error.request_id
end
return nil
end
local function error_code(body, status)
if type(body) == "table" and type(body.error) == "table" and type(body.error.code) == "string" then
return body.error.code
end
return "http_" .. tostring(status)
end
function M.gate()
local token = caller_token()
if not token then
alert(401, "missing_caller", nil)
return finish(401, {
error = {
code = "missing_caller",
message = "Send the caller credential as Authorization: Bearer.",
request_id = nil,
},
})
end
local agent_key = keys.lookup(token)
if not agent_key then
alert(401, "unknown_caller", nil)
return finish(401, {
error = {
code = "unknown_caller",
message = "This edge has no Ordainer agent key for this caller.",
request_id = nil,
},
})
end
local tool = ngx.var.ordainer_tool
if type(tool) ~= "string" or tool == "" then tool = "agent.run" end
local idempotency_key = ngx.var.request_id
local res, err
for attempt = 1, 2 do
local one, one_err = call_decide(agent_key, tool, idempotency_key)
local retry = (not one) or one.status >= 500
if one then
res = one
err = nil
else
err = one_err or "network_error"
end
if not retry or attempt == 2 then break end
ngx.sleep(RETRY_PAUSE)
end
if not res then
return give_up(err or "network_error", "no_response", nil)
end
local body = cjson.decode(res.body or "")
local rid = request_id_of(res, body)
local status = res.status
if status == 429 then
local code = error_code(body, status)
if code == "safety_limit_reached" and safety_allows() then
set_request_id(rid)
note("safety_limit_allow", code, rid)
return
end
return pass_through(429, res, rid)
end
if status >= 500 then
return give_up(error_code(body, status), "http_" .. tostring(status), rid)
end
if status >= 400 then
local code = error_code(body, status)
alert(status, code, rid)
return pass_through(status, res, rid)
end
if status ~= 200 or type(body) ~= "table" or (body.decision ~= "allow" and body.decision ~= "deny") then
return give_up("bad_response", "http_" .. tostring(status), rid)
end
set_request_id(rid)
ngx.var.ordainer_decision = one_line(body.decision or "")
ngx.var.ordainer_reason = one_line(type(body.reason) == "string" and body.reason or "")
ngx.var.ordainer_mode = one_line(type(body.mode) == "string" and body.mode or "")
if body.decision == "allow" or body.mode == "shadow" then
remember_lease(agent_key, body, rid)
return
end
local reason = type(body.reason) == "string" and body.reason or "deny"
local out_status, retry_after
if reason == "quota_exceeded" or reason == "test_limit_reached" then
out_status, retry_after = 429, retry_after_until(body.resets_at)
elseif reason == "concurrency_exhausted" then
-- resets_at is the plan period end, not when a session frees. Use a short wait.
out_status, retry_after = 429, "1"
else
out_status, retry_after = 403, nil
end
local payload = {
decision = "deny",
reason = reason,
mode = body.mode or "enforce",
remaining = body.remaining,
limit = body.limit,
resets_at = body.resets_at,
request_id = body.request_id or rid,
}
if type(body.explanation) == "string" then payload.explanation = body.explanation end
if type(body.message) == "string" then payload.message = body.message end
if body.tool_in_plan == false then payload.tool_in_plan = false end
local extra = {}
if out_status == 429 then extra["Retry-After"] = retry_after end
ngx.log(ngx.NOTICE, "ordainer_deny status=", tostring(out_status),
" reason=", reason, " request_id=", payload.request_id or "-")
return finish(out_status, payload, extra)
end
-- Called from log_by_lua_block. Cosockets are not allowed in the log phase,
-- so the HTTP call runs on a 0-delay timer. The client response is already
-- on its way; a finish timeout or error cannot change it.
function M.release_after()
local job = ngx.ctx.ordainer_lease
if type(job) ~= "table" or type(job.id) ~= "string" or job.id == "" then
return
end
local id, key, rid = job.id, job.key, job.rid
if type(key) ~= "string" or key == "" then return end
local url = release_url(id)
local ok, err = ngx.timer.at(0, function(premature)
if premature then return end
local httpc = http.new()
httpc:set_timeout(TIMEOUT_MS)
local res, herr = httpc:request_uri(url, {
method = "POST",
body = "{}",
headers = {
["Authorization"] = "Bearer " .. key,
["Content-Type"] = "application/json",
["Accept"] = "application/json",
["X-Ordainer-Request-Id"] = rid or "",
},
ssl_verify = true,
keepalive = false,
})
if not res then
ngx.log(ngx.ERR, "ordainer_lease_finish_failed detail=", herr or "network_error",
" request_id=", rid or "-")
return
end
if res.status >= 400 then
ngx.log(ngx.ERR, "ordainer_lease_finish_failed status=", tostring(res.status),
" request_id=", rid or "-")
end
end)
if not ok then
ngx.log(ngx.ERR, "ordainer_lease_finish_schedule_failed detail=", err or "-",
" request_id=", rid or "-")
end
end
return M
/etc/nginx/lua/keys.lua
-- /etc/nginx/lua/keys.lua: caller credential -> Ordainer agent key.
-- chmod 600, owned by the worker user (nobody above). Never log the token or the key.
local MAP = {
["caller_demo_token"] = "ord_test_PLACEHOLDER000000000000000000001",
}
local function lookup(token)
if type(token) ~= "string" or token == "" then return nil end
return MAP[token]
end
return { lookup = lookup }

Every variable that log_format reads and ordainer.lua writes ($ordainer_request_id, $ordainer_decision, $ordainer_reason, $ordainer_mode) is declared with set in the location, before the access phase runs. add_header and proxy_set_header copy those variables as they are, so the check replaces a CR, LF or NUL from the decide body with a space before it writes them. $request_id is the idempotency key. $ordainer_request_id is filled from the decide response header X-Request-Id. Leave $http_authorization out of log_format. The Lua code never passes the agent key or the caller token to ngx.log.

resolver is required so the cosocket can resolve the decide host. Use one that can resolve api.ordainer.dev, with ipv6=off, so a missing AAAA answer does not spend the 300 ms budget. Turn TLS verification on (ssl_verify = true in the check) and point lua_ssl_trusted_certificate at your CA bundle.

The decide URL comes from ORDAINER_DECIDE_URL, the fail mode from ORDAINER_FAIL_MODE, and the safety-limit choice from ORDAINER_SAFETY_LIMIT. NGINX passes them to workers only because the env lines list them. The defaults are https://api.ordainer.dev/v1/decide, open and block.

njs runs inside auth_request. ngx.fetch calls decide. The handler then returns a status auth_request accepts:

  • allow, shadow deny, or fail open: 204
  • anything you want the caller to see as a block: 403, with X-Ordainer-Status set to the real status (429, 403, 401, 400, …), X-Ordainer-Retry-After set when there is a Retry-After, and X-Ordainer-Body holding the JSON body

A header value cannot hold a line break, so the handler replaces CR and LF in those values with a space. JSON allows a line break only between tokens, so the body stays valid JSON. auth_request_set copies those headers onto the main request. error_page 403 500 = @ordainer_block hands a block to ordainer.block, which answers the caller with the real status, Retry-After, and the Ordainer JSON body. The = keeps the named location’s status. Upstream responses are not rewritten: proxy_intercept_errors stays off, so a 403 from your origin is still that origin’s 403.

You need three files: nginx.conf, the handler in ordainer.js, and the key map in keys.js. Install NGINX and the njs module from the nginx.org packages (nginx and nginx-module-njs). The origin is 127.0.0.1:3000 and the tool is agent.run, set in the map. Change both for your route.

/etc/nginx/nginx.conf
# nginx.org packages: nginx and nginx-module-njs
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
load_module modules/ngx_http_js_module.so;
# Workers see only the environment variables listed here (process.env in njs).
env ORDAINER_DECIDE_URL;
env ORDAINER_FAIL_MODE;
env ORDAINER_SAFETY_LIMIT;
env ORDAINER_LEASE_TTL_S;
events {
worker_connections 1024;
}
http {
js_import ordainer from /etc/nginx/njs/ordainer.js;
js_fetch_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
# Closes a decide fetch the handler gave up on (300 ms timer) after 1 s
# without a read or write, instead of the 60 s default.
js_fetch_timeout 1s;
# Default is 0: every ngx.fetch opens a new TCP/TLS connection. The pool
# is per worker. A small pool keeps the warmed decide connection for later
# calls in this worker only.
js_fetch_keepalive 8;
# ngx.fetch needs a resolver for api.ordainer.dev. ipv6=off keeps a
# missing AAAA answer from spending the 300 ms attempt budget.
resolver 1.1.1.1 valid=10s ipv6=off;
resolver_timeout 1s;
# No $http_authorization: the caller token and the agent key are never logged.
log_format ordainer '$remote_addr [$time_local] "$request" $status '
'rid=$request_id ordainer_rid=$ordainer_request_id '
'decision=$ordainer_decision reason=$ordainer_reason '
'rt=$request_time';
access_log /var/log/nginx/access.log ordainer;
# The route picks the tool. Never take it from the caller. Add a line per
# path if routes need different tools.
map $uri $ordainer_tool {
default "agent.run";
}
upstream origin {
server 127.0.0.1:3000;
keepalive 16;
}
server {
listen 8080;
server_tokens off;
location / {
# The auth subrequest has its own $request_id and URI, so copy the
# idempotency key and the tool before auth_request runs.
set $edge_request_id $request_id;
set $edge_tool $ordainer_tool;
set $ordainer_status "";
set $ordainer_retry_after "";
set $ordainer_request_id "-";
set $ordainer_body "";
set $ordainer_decision "";
set $ordainer_reason "";
set $ordainer_mode "";
auth_request /_ordainer;
auth_request_set $ordainer_status $upstream_http_x_ordainer_status;
auth_request_set $ordainer_retry_after $upstream_http_x_ordainer_retry_after;
auth_request_set $ordainer_request_id $upstream_http_x_ordainer_request_id;
auth_request_set $ordainer_body $upstream_http_x_ordainer_body;
auth_request_set $ordainer_decision $upstream_http_x_ordainer_decision;
auth_request_set $ordainer_reason $upstream_http_x_ordainer_reason;
auth_request_set $ordainer_mode $upstream_http_x_ordainer_mode;
# A block comes back as 403. A check that stalls past the backstop on
# /_ordainer comes back as 500. The named location returns the real
# status, Retry-After and the Ordainer JSON body, or 503 for the 500.
error_page 403 500 = @ordainer_block;
add_header X-Ordainer-Request-Id $ordainer_request_id always;
add_header X-Edge-Request-Id $edge_request_id always;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Ordainer-Request-Id $ordainer_request_id;
proxy_set_header X-Ordainer-Decision $ordainer_decision;
proxy_set_header X-Ordainer-Reason $ordainer_reason;
proxy_set_header X-Ordainer-Mode $ordainer_mode;
# The origin may trust X-Ordainer-* headers. Set or clear every one
# this edge uses so a caller's copy never reaches the origin.
proxy_set_header X-Ordainer-Tool $edge_tool;
proxy_set_header X-Ordainer-Status "";
proxy_set_header X-Ordainer-Retry-After "";
proxy_set_header X-Ordainer-Body "";
proxy_pass http://origin;
}
# auth_request exposes $upstream_http_* only from a proxied response, so
# the subrequest proxies to the loopback server below, where js_content runs.
location = /_ordainer {
internal;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host 127.0.0.1;
proxy_set_header X-Edge-Id $edge_request_id;
proxy_set_header X-Ordainer-Tool $edge_tool;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_buffer_size 16k;
proxy_buffers 4 16k;
# Backstop only. The check answers within about 650 ms.
proxy_connect_timeout 1s;
proxy_send_timeout 1s;
proxy_read_timeout 2s;
proxy_pass http://127.0.0.1:8081/;
}
location @ordainer_block {
internal;
js_content ordainer.block;
}
}
# Loopback only. Do not publish this port.
server {
listen 127.0.0.1:8081;
server_tokens off;
access_log off;
location / {
js_content ordainer.check;
}
}
}
/etc/nginx/njs/ordainer.js
// njs auth_request shim for POST /v1/decide.
// location /_ordainer calls check(). A deny or an API error becomes HTTP 403
// plus X-Ordainer-Status / X-Ordainer-Retry-After / X-Ordainer-Body.
// error_page 403 = @ordainer_block calls block(), which returns the real status.
// Allow is HTTP 204 so auth_request lets the request through.
// The agent key and the caller token are never logged.
// ORDAINER_DECIDE_URL, ORDAINER_FAIL_MODE, ORDAINER_SAFETY_LIMIT and
// ORDAINER_LEASE_TTL_S come from process.env. Workers see them only when
// nginx.conf lists them with env.
// njs filters and js_set are synchronous and can't fetch, so this handler
// can't release after the response. Unset or 0 ORDAINER_LEASE_TTL_S omits
// lease (the default). A positive value opts in; the lease then ends at
// expires_at.
import keys from './keys.js';
const TIMEOUT_MS = 300;
const RETRY_PAUSE_MS = 50;
function env(name, fallback) {
const value = process.env[name];
return value ? String(value) : fallback;
}
function decideUrl() {
return env('ORDAINER_DECIDE_URL', 'https://api.ordainer.dev/v1/decide');
}
function failMode() {
return env('ORDAINER_FAIL_MODE', 'open') === 'closed' ? 'closed' : 'open';
}
function safetyAllows() {
return env('ORDAINER_SAFETY_LIMIT', 'block') === 'allow';
}
// 0 or unset means omit lease. A positive value is capped at the API max of 3600.
function leaseTtlS() {
const raw = env('ORDAINER_LEASE_TTL_S', '0');
const n = Number(raw);
if (!isFinite(n) || n < 1) return 0;
return Math.min(Math.floor(n), 3600);
}
function header(headers, name) {
if (!headers) return '';
if (typeof headers.get === 'function') {
const value = headers.get(name);
if (value) return String(value);
}
const lower = name.toLowerCase();
if (headers[name]) return String(headers[name]);
if (headers[lower]) return String(headers[lower]);
return '';
}
function callerToken(r) {
const raw = r.headersIn.Authorization || r.headersIn.authorization || '';
const match = /^Bearer\s+(\S+)\s*$/i.exec(raw);
return match ? match[1] : '';
}
function headerIn(r, name) {
return r.headersIn[name] || r.headersIn[name.toLowerCase()] || '';
}
function edgeId(r) {
// The auth subrequest proxies to the local js listener, which does not share
// the parent variables. The proxy passes the parent id in this header.
const fromHeader = headerIn(r, 'X-Edge-Id');
if (fromHeader && fromHeader !== '-') return fromHeader;
const fromParent = r.variables.edge_request_id;
if (fromParent && fromParent !== '-') return fromParent;
return r.variables.request_id || '';
}
function toolOf(r) {
const fromHeader = headerIn(r, 'X-Ordainer-Tool');
if (fromHeader) return fromHeader;
const tool = r.variables.ordainer_tool;
if (tool) return tool;
return 'agent.run';
}
function parseJson(text) {
if (!text) return null;
try {
return JSON.parse(text);
} catch (e) {
return null;
}
}
function errorCode(body, status) {
if (body && body.error && typeof body.error.code === 'string') return body.error.code;
return 'http_' + String(status);
}
function requestIdOf(res, body) {
const fromHeader = header(res.headers, 'x-request-id');
if (fromHeader) return fromHeader;
if (body && typeof body.request_id === 'string') return body.request_id;
if (body && body.error && typeof body.error.request_id === 'string') return body.error.request_id;
return '';
}
function retryAfterUntil(resetsAt) {
if (typeof resetsAt !== 'string') return '1';
const ms = Date.parse(resetsAt);
if (!isFinite(ms)) return '1';
let sec = Math.ceil((ms - Date.now()) / 1000);
if (sec < 1) sec = 1;
if (sec > 3600) sec = 3600;
return String(sec);
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// ngx.fetch has no per-call timeout, and js_fetch_timeout only limits the gap
// between two reads or writes. Race the fetch against the 300 ms budget so the
// attempt actually ends.
// settled stops the late fetch from clearing a timer that already fired.
function withTimeout(promise, ms) {
return new Promise((resolve, reject) => {
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
reject(new Error('timeout'));
}, ms);
promise.then((value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
}, (err) => {
if (settled) return;
settled = true;
clearTimeout(timer);
reject(err);
});
});
}
function logLine(r, kind, status, code, rid) {
r.error('ordainer_' + kind + ' status=' + String(status) + ' code=' + (code || '-') + ' request_id=' + (rid || '-'));
}
function blockResult(status, bodyText, retryAfter, rid, decision, reason, mode) {
return {
action: 'block',
status: status,
body: bodyText,
retryAfter: retryAfter || '',
requestId: rid || '',
decision: decision || '',
reason: reason || '',
mode: mode || '',
};
}
function allowResult(rid, decision, reason, mode) {
return {
action: 'allow',
requestId: rid || '',
decision: decision || '',
reason: reason || '',
mode: mode || '',
};
}
function giveUp(kind, detail, rid) {
if (failMode() === 'closed') {
return blockResult(503, JSON.stringify({
error: {
code: 'edge_unavailable',
message: 'This call was not run. The edge could not get a decision. Try again in a minute.',
request_id: rid || null,
},
}), '5', rid, '', kind, '');
}
return {
action: 'allow',
failOpen: true,
requestId: rid || '',
decision: '',
reason: '',
mode: '',
detail: kind + ':' + (detail || '-'),
};
}
function denyResult(body, rid) {
const reason = typeof body.reason === 'string' ? body.reason : 'deny';
const mode = typeof body.mode === 'string' ? body.mode : 'enforce';
const payload = {
decision: 'deny',
reason: reason,
mode: mode,
remaining: body.remaining,
limit: body.limit,
resets_at: body.resets_at,
request_id: typeof body.request_id === 'string' ? body.request_id : (rid || null),
};
if (typeof body.explanation === 'string') payload.explanation = body.explanation;
if (typeof body.message === 'string') payload.message = body.message;
if (body.tool_in_plan === false) payload.tool_in_plan = false;
let status;
let retryAfter;
if (reason === 'quota_exceeded' || reason === 'test_limit_reached') {
status = 429;
retryAfter = retryAfterUntil(body.resets_at);
} else if (reason === 'concurrency_exhausted') {
// resets_at is the plan period end, not when a session frees. Use a short wait.
status = 429;
retryAfter = '1';
} else {
status = 403;
retryAfter = '';
}
return blockResult(
status,
JSON.stringify(payload),
retryAfter,
payload.request_id || rid,
'deny',
reason,
mode,
);
}
async function callDecide(agentKey, tool, idem) {
const url = decideUrl();
const payload = { tool: tool };
const ttl = leaseTtlS();
if (ttl) payload.lease = { ttl_s: ttl };
const options = {
method: 'POST',
body: JSON.stringify(payload),
headers: {
Authorization: 'Bearer ' + agentKey,
'Content-Type': 'application/json',
'Idempotency-Key': idem,
Accept: 'application/json',
},
};
if (url.indexOf('https://') === 0) options.verify = true;
const res = await ngx.fetch(url, options);
const text = await res.text();
return { status: res.status, text: text, headers: res.headers };
}
async function evaluate(r) {
const token = callerToken(r);
if (!token) {
logLine(r, 'alert', 401, 'missing_caller', '');
return blockResult(401, JSON.stringify({
error: {
code: 'missing_caller',
message: 'Send the caller credential as Authorization: Bearer.',
request_id: null,
},
}), '', '', '', 'missing_caller', '');
}
const agentKey = keys.lookup(token);
if (!agentKey) {
logLine(r, 'alert', 401, 'unknown_caller', '');
return blockResult(401, JSON.stringify({
error: {
code: 'unknown_caller',
message: 'This edge has no Ordainer agent key for this caller.',
request_id: null,
},
}), '', '', '', 'unknown_caller', '');
}
const tool = toolOf(r);
const idem = edgeId(r);
let res = null;
let netErr = 'network_error';
for (let attempt = 1; attempt <= 2; attempt += 1) {
let retry = false;
try {
const one = await withTimeout(callDecide(agentKey, tool, idem), TIMEOUT_MS);
res = one;
netErr = '';
retry = one.status >= 500;
} catch (e) {
netErr = 'timeout_or_connect';
retry = true;
}
if (!retry || attempt === 2) break;
await sleep(RETRY_PAUSE_MS);
}
if (!res) return giveUp(netErr, 'no_response', '');
const body = parseJson(res.text);
const rid = requestIdOf(res, body);
const status = res.status;
if (status === 429) {
const code = errorCode(body, status);
if (code === 'safety_limit_reached' && safetyAllows()) {
logLine(r, 'safety_limit_allow', 429, code, rid);
return allowResult(rid, '', code, '');
}
return blockResult(429, res.text || '', header(res.headers, 'retry-after'), rid, '', code, '');
}
if (status >= 500) {
const outcome = giveUp(errorCode(body, status), 'http_' + String(status), rid);
if (outcome.action === 'block') logLine(r, 'alert', 503, errorCode(body, status), rid);
return outcome;
}
if (status >= 400) {
const code = errorCode(body, status);
logLine(r, 'alert', status, code, rid);
return blockResult(status, res.text || '', header(res.headers, 'retry-after'), rid, '', code, '');
}
if (status !== 200 || !body || (body.decision !== 'allow' && body.decision !== 'deny')) {
const outcome = giveUp('bad_response', 'http_' + String(status), rid);
if (outcome.action === 'block') logLine(r, 'alert', 503, 'bad_response', rid);
return outcome;
}
if (body.decision === 'allow' || body.mode === 'shadow') {
return allowResult(
rid,
body.decision,
typeof body.reason === 'string' ? body.reason : '',
typeof body.mode === 'string' ? body.mode : '',
);
}
const denied = denyResult(body, rid);
r.log('ordainer_deny status=' + String(denied.status) + ' reason=' + denied.reason + ' request_id=' + (denied.requestId || '-'));
return denied;
}
// A header value cannot hold CR, LF or NUL, and setting one throws. JSON
// allows a line break only between tokens, so a space keeps the body valid.
function oneLine(value) {
return String(value).replace(/[\r\n\0]+/g, ' ');
}
function respond(r, outcome) {
if (outcome.failOpen) {
logLine(r, 'fail_open', 0, outcome.detail || 'outage', outcome.requestId);
}
if (outcome.requestId) r.headersOut['X-Ordainer-Request-Id'] = oneLine(outcome.requestId);
if (outcome.decision) r.headersOut['X-Ordainer-Decision'] = oneLine(outcome.decision);
if (outcome.reason) r.headersOut['X-Ordainer-Reason'] = oneLine(outcome.reason);
if (outcome.mode) r.headersOut['X-Ordainer-Mode'] = oneLine(outcome.mode);
if (outcome.action === 'block') {
r.headersOut['X-Ordainer-Status'] = String(outcome.status);
if (outcome.retryAfter) r.headersOut['X-Ordainer-Retry-After'] = oneLine(outcome.retryAfter);
if (outcome.body) r.headersOut['X-Ordainer-Body'] = oneLine(outcome.body);
// Pass an empty body. With no body, the 403 is not sent until the
// abandoned decide fetch settles, which can hold the caller for the
// whole outage.
r.return(403, '');
return;
}
r.return(204);
}
async function check(r) {
try {
const outcome = await evaluate(r);
respond(r, outcome);
} catch (e) {
if (failMode() === 'closed') {
logLine(r, 'alert', 503, 'edge_exception', '');
respond(r, blockResult(503, JSON.stringify({
error: {
code: 'edge_unavailable',
message: 'This call was not run. The edge could not get a decision. Try again in a minute.',
request_id: null,
},
}), '5', '', '', 'edge_exception', ''));
return;
}
respond(r, { action: 'allow', failOpen: true, detail: 'edge_exception', requestId: '' });
}
}
function block(r) {
// Pass the real 4xx or 5xx through. When the subrequest named no status
// (the check stalled past the /_ordainer backstop), answer 503.
let status = parseInt(r.variables.ordainer_status, 10);
let retry = r.variables.ordainer_retry_after || '';
if (!(status >= 400 && status <= 599)) {
status = 503;
retry = '5';
}
if (retry && retry !== '-') r.headersOut['Retry-After'] = retry;
const rid = r.variables.ordainer_request_id || '';
if (rid && rid !== '-') r.headersOut['X-Ordainer-Request-Id'] = rid;
const edge = r.variables.edge_request_id || r.variables.request_id || '';
if (edge && edge !== '-') r.headersOut['X-Edge-Request-Id'] = edge;
r.headersOut['Content-Type'] = 'application/json; charset=utf-8';
r.headersOut['Cache-Control'] = 'no-store';
let body = r.variables.ordainer_body || '';
if (!body || body === '-') {
body = JSON.stringify({
error: {
code: 'edge_unavailable',
message: 'This call was not run. The edge could not get a decision. Try again in a minute.',
request_id: null,
},
});
}
r.return(status, body);
}
export default { check, block };
/etc/nginx/njs/keys.js
// /etc/nginx/njs/keys.js: caller credential -> Ordainer agent key.
// chmod 600, owned by the worker user (nginx above). Never log the token or the key.
const MAP = {
caller_demo_token: 'ord_test_PLACEHOLDER000000000000000000001',
};
function lookup(token) {
if (typeof token !== 'string' || !Object.prototype.hasOwnProperty.call(MAP, token)) return null;
return MAP[token];
}
export default { lookup };

ngx.fetch needs resolver. js_fetch_trusted_certificate is how verify checks the API certificate. Each njs attempt is limited to 300 ms for the whole fetch (DNS, connect, TLS, and the response). That is not the same budget as OpenResty, where 300 ms applies to each operation (connect, send, and each read). ngx.fetch has no per-call timeout, and js_fetch_timeout only limits the gap between two reads or writes, so the handler races the fetch against a 300 ms timer. The first decide on each worker after a start or reload can use the retry path or, in fail-closed mode, return 503 when DNS plus TLS takes more than 300 ms. js_fetch_keepalive 8 keeps the warmed connection for later calls in that worker only. A single warmup request cannot warm every worker when worker_processes is auto. js_fetch_timeout 1s closes a fetch the handler gave up on after a second without a read or write, instead of holding the connection for the 60 s default. The handler then answers the subrequest with r.return(403, ''). The empty body matters: with no body, njs does not send the 403 until the abandoned fetch settles, which holds the caller for the whole outage. proxy_read_timeout 2s on /_ordainer is a backstop if the handler itself stalls. auth_request turns that timeout into a 500, and error_page 403 500 sends it to ordainer.block, which answers 503 edge_unavailable with Retry-After: 5 in either fail mode. The idempotency key is $edge_request_id, copied from the main request’s $request_id before auth_request runs, because the subrequest has its own $request_id. The loopback server receives that id in X-Edge-Id and the route’s tool in X-Ordainer-Tool. Copy the tool into $edge_tool before auth_request: the subrequest’s own URI is /_ordainer, so a map on $uri would not see the caller’s path there. The loopback listener is bound to 127.0.0.1 and is not published. The auth subrequest sends no body, so it also clears Content-Length.

In njs, a 401 body larger than 16 KB still blocks with status 401, but the body is replaced with edge_unavailable (upstream sent too big header). OpenResty passes the full body.

The handler reads ORDAINER_DECIDE_URL, ORDAINER_FAIL_MODE and ORDAINER_SAFETY_LIMIT from process.env, which holds only the variables the env lines list. The defaults are the same as for OpenResty.

The caller’s credential is not an Ordainer key. The edge looks up the Ordainer key and uses it only on the decide request.

Two places to keep the map:

  • A file the worker can read, mode 600, owned by the worker user: keys.lua or keys.js above. The value on this page is a placeholder, ord_test_ followed by PLACEHOLDER and digits. Replace it with your agent key. Do not commit a real key.
  • Redis, if you already have it next to NGINX. Look up by a hash of the caller credential, with a short timeout. Do not log the credential or the value that comes back.

A missing or unknown caller credential is 401 from the edge (missing_caller or unknown_caller) and does not call decide. A decide 401 (missing_key, unknown_key, revoked_key, old_key_format) or 400 (invalid_json, invalid_request, invalid_idempotency_key) means the edge’s own request is wrong. The ordainer_alert line is the page-worthy one: status, error.code, and request id.

Every decide response carries X-Request-Id. On a decision it equals request_id. On an error it equals error.request_id. The edge copies it to:

  • the upstream request, as X-Ordainer-Request-Id
  • the caller response, as the same header
  • the access log, as ordainer_rid

Quote that id when you write to support. A 4xx from the API has no audit row; the id is still how support finds the server log line.

On the request to your origin, both configurations set X-Ordainer-Request-Id, X-Ordainer-Decision, X-Ordainer-Reason, X-Ordainer-Mode, and X-Ordainer-Tool (the route’s tool), and clear X-Ordainer-Status, X-Ordainer-Retry-After, and X-Ordainer-Body. A caller’s copy of any of those never reaches the origin. Other X-Ordainer-* names from the caller are passed as sent, so have the origin read only these.

Read mode on a 200 deny. In shadow, proxy the request and still forward the request id, the decision, and the reason (X-Ordainer-Decision, X-Ordainer-Reason, X-Ordainer-Mode) so the origin can log the would-deny. Both configurations above do this. In enforce, stop the request. Leaving mode out of the decide body lets the plan’s mode apply. Pinning "mode":"shadow" or "mode":"enforce" on the edge would ignore the console switch.

Fail open and shadow are different. Shadow is what to do with a real deny. Fail open is what to do when decide does not answer. A week of shadow traffic wants the default, fail open, so an outage does not become an outage of your own. A tool that must not run without a decision sets ORDAINER_FAIL_MODE=closed. See Fail open vs fail closed.

Run these on the Linux host where NGINX runs, with your origin listening on 127.0.0.1:3000, a test agent key in the key map, and NGINX started with the files above. Check the configuration first with nginx -t (openresty -t for OpenResty).

An allow is proxied to the origin, and the response carries X-Ordainer-Request-Id:

Terminal window
curl -i -H "Authorization: Bearer caller_demo_token" http://127.0.0.1:8080/

A key whose plan does not include agent.run gets 403 with the Ordainer body ("reason":"tool_not_in_plan", "tool_in_plan":false), and the origin is not called. A key past its plan’s cap gets 429 with Retry-After. A caller credential that is not in the map gets 401 unknown_caller from the edge, with no decide call:

Terminal window
curl -i -H "Authorization: Bearer not-in-the-map" http://127.0.0.1:8080/

To see what an outage does, restart NGINX with ORDAINER_DECIDE_URL pointing at a port where nothing listens, for example http://127.0.0.1:9/v1/decide. With the default fail mode the request is proxied, and the error log has an ordainer_fail_open line. With ORDAINER_FAIL_MODE=closed the answer is 503 with Retry-After: 5 and error.code edge_unavailable, and the origin is not called. Keep the test key out of the shell history and out of the access log.

Decide takes a session lease when the body includes lease (for example "lease":{"ttl_s":120}) and the agent key has a session limit. An allow then returns lease.id. Without a session limit on the key, decide takes no lease and returns no lease. At the limit, enforce answers HTTP 200 deny concurrency_exhausted and takes no lease; map that deny as described in What the edge does. When the session ends, release it with POST /v1/leases/:id/release. The call is idempotent: a second release is a 200 and does not drive the count below zero. If the session may outlast its TTL, extend it first with POST /v1/leases/:id/extend. If finish never arrives, the lease ends at expires_at and the slot frees itself.

The OpenResty recipe above does the release after the origin responds. This treats one proxied request as one session. If your origin hands work off and answers before it finishes (for example a 202 for a background job), don’t release at the edge. Have the origin release or extend the lease instead. If a request can run longer than ttl_s, raise ORDAINER_LEASE_TTL_S: the lease ends at its TTL even while the origin is still working. The default is 120 s. Release uses the same per-key request rate as decide, so each allowed request is two calls against that rate. log_by_lua schedules ngx.timer.at(0), and the timer POSTs {} to /v1/leases/:id/release with a 300 ms budget, carrying the decide request id as X-Ordainer-Request-Id. Cosockets are not allowed in the log phase, so the HTTP call cannot run directly in log_by_lua. The client response is already on its way; a finish timeout or error is logged with the request id only and cannot change what the caller already received. The agent key is not written to a log line. Under heavy load, ngx.timer.at can fail (lua_max_pending_timers, default 1024) and the release is skipped and logged; the lease then ends at its TTL.

njs cannot release after the response. Its header filter, body filter and js_set handlers run synchronously and can’t call ngx.fetch, and njs has no log-phase handler that can. The njs recipe does not send lease by default (ORDAINER_LEASE_TTL_S unset or 0 omits it). If you opt in by setting a positive ORDAINER_LEASE_TTL_S, every allowed request holds a session for that full TTL, however quickly the origin answers. The lease is not released early: it ends at the TTL, so retries can keep getting 429 until then. With a session limit of N, njs then lets at most N requests through in any TTL window, and the rest get 429 concurrency_exhausted with Retry-After: 1 until the oldest lease runs out. Use OpenResty when the slot should be freed as soon as the origin returns.