Database-backed users: how ProxyAuth keeps memory and the database in sync
Was this useful?
0 unique visitors
Every login, every route check, every TOTP verification in ProxyAuth
reads users from memory. A database round-trip on each request would be
a strange price for data that changes rarely. But once accounts live in
PostgreSQL or MySQL instead of config.json, something has to keep that
in-memory copy honest — including about rows that no longer exist.
Configuration
{
"databases": {
"db_type": "postgres",
"host": "127.0.0.1",
"port": 5432,
"db_name": "proxyauth",
"user": "proxyauth",
"password": "...",
"connect_timeout_secs": 5,
"refresh_interval_secs": 30,
"incremental_window_secs": 300,
"full_refresh_interval_secs": 300,
"deleted_retention_secs": 86400,
"purge_interval_secs": 3600
}
}
db_type is "postgres" or "mysql", and connection parameters are
given individually, not as a URL. File-based and database accounts
coexist; a request is checked against both.
connect_timeout_secs deserves attention. It bounds every blocking
database call. Without it, a database that accepts TCP but never answers
can hang a call for the OS default — often 30 to 130 seconds — and that
is also how long a restart can appear stuck, since a call already in
flight keeps running after SIGTERM.
Two scans, two jobs
Incremental — every refresh_interval_secs (30 s). An indexed
query for rows changed within the last incremental_window_secs
(300 s). This is what makes a new or edited account usable within
seconds.
The window is deliberately longer than the interval. Consecutive scans
overlap, so a change landing on a tick boundary is still seen by at
least one of them. Seeing it twice is harmless: re-applying the same
update is a no-op. Keep incremental_window_secs at least as long as
refresh_interval_secs, ideally several times longer.
Full — every full_refresh_interval_secs (300 s). Reads the whole
table. Slower, and it exists for one reason the incremental scan
structurally cannot cover: a deleted row cannot match
modified_at >= cutoff, because it is not there. A time-window query
only sees rows that still exist.
A deleted account is only ever concluded from a genuinely fresh full read, never from a cache.
Setting refresh_interval_secs: 0 leaves only the full scan. Setting
full_refresh_interval_secs: 0 means hard deletions only take effect on
the next restart.
Two kinds of deletion
| How | What happens | Noticed by |
|---|---|---|
proxyauth db-delete-user (soft) | deleted = TRUE, modified_at touched; row purged after deleted_retention_secs | the incremental scan, within seconds |
raw DELETE FROM users (hard) | the trg_log_user_delete trigger writes the username to deleted_users_log | the log, then the full scan as backstop |
The trigger turns “a row vanished” into a row that can be read like any
other change. Without it, a raw DELETE would keep access open until
the next full scan. A TRUNCATE, which skips row triggers, is still
caught by the full scan.
The purge loop (purge_interval_secs, hourly) removes soft-deleted rows
past deleted_retention_secs (24 h). That window gives every instance
time to see the deletion before the evidence disappears, and leaves a
short audit trail. Running the purge on several instances at once is
harmless.
When a database user disappears, its in-memory slot is poisoned, not removed. Tokens carry a user index; removing a slot would shift every index after it and make issued tokens point at the wrong people. A token pointing at a poisoned slot is rejected.
The schema, created for you
Seven tables, one trigger, two indexes, created at startup and re-checked on every start — no migration step, no SQL file to keep in sync with the binary.
users id, username (unique), password (Argon2id), otpkey,
created_at, modified_at (indexed), deleted,
must_change_password
user_allow user_id → cidr
user_roles user_id → role (free text)
groups id, name (unique)
user_groups user_id, group_id — UNIQUE(user_id, group_id)
user_email user_id → email, is_primary
deleted_users_log username, deleted_at (indexed)
Every child table cascades on delete; deleted_users_log deliberately
does not, since it must outlive the row it records.
Migrations are idempotent. PostgreSQL uses ADD COLUMN IF NOT EXISTS
(9.6+). On MySQL/MariaDB the ALTER is attempted and a “duplicate
column” error is read as “already migrated”. The trigger is dropped and
recreated on each start; an “already exists” race with a second instance
counts as success.
The account needs DDL rights for the first start — tables, indexes,
a function and a trigger. If your runtime account is restricted to
SELECT/INSERT/UPDATE/DELETE, create the schema by hand from the DDL in
the documentation and keep the runtime account narrow.
How a read happens
Five simple queries, joined in memory:
SELECT id, username, password, otpkey, must_change_password
FROM users WHERE deleted = FALSE;
SELECT user_id, cidr AS value FROM user_allow;
SELECT user_id, role AS value FROM user_roles;
SELECT user_groups.user_id, groups.name AS value
FROM user_groups JOIN groups ON groups.id = user_groups.group_id;
SELECT user_id, email AS address, is_primary FROM user_email;
string_agg and GROUP_CONCAT would each need their own dialect;
assembling in the application is cheaper than maintaining two versions.
Editing rows by hand
It works — the incremental scan picks it up. Two rules: hash the
password with Argon2id before inserting (nothing re-hashes a value
already in the column), and on PostgreSQL set modified_at yourself.
MySQL maintains it with ON UPDATE CURRENT_TIMESTAMP; PostgreSQL does
not. db-add-user handles both, which is why it is the recommended
path.
LMDB: a safety net, not a replica
Every successful full read is mirrored into a local LMDB cache. Its job is narrow: stand in when the database cannot be reached at all, most importantly at startup. If ProxyAuth and its database restart together, ProxyAuth serves logins from the last known-good snapshot instead of starting with zero accounts.
It is written only after a real read succeeds, read only when a real read fails, and it holds password hashes — so its directory is owner-only.
It is read-only for almost everything: db-add-user and
db-delete-user require a live connection and refuse otherwise.
One exception: TOTP enrollment, reset and self-service re-enrollment
patch the affected user’s otpkey in the cache immediately, alongside
the database write. Otherwise a reset followed by a database outage
would fall back to the old secret — silently undoing the reset during
exactly the outage the cache exists for.
The CLI
proxyauth db-add-user --username alice --groups ops --roles admin \
--email alice@example.com --primary-email alice@example.com \
--must-change-password # prompts for the password if omitted
proxyauth db-delete-user --username alice
proxyauth db-sync-cache # full read into the cache now
proxyauth db-restore-from-cache # rebuild an emptied database
proxyauth db-clear-cache
db-sync-cache refuses to overwrite a non-empty cache with an empty
result unless --force is given. db-restore-from-cache refuses if the
database already has users unless forced, and never runs automatically.
--email is authoritative: omitting it clears the addresses on file.
When none of this runs
Both refresh loops stand down while BlakeGate backup mode is active and connected: an external endpoint pushes state instead, and the database becomes a write target. Two systems claiming the same in-memory state at once is not a fight worth having. BlakeGate is still experimental; see its own post.
Sharing accounts is not sharing tokens
Two instances with the same databases block share users, but still
reject each other’s tokens until their build constants agree. That is
the job of sync — see
sync groups.
A cheap overlapping scan for changes, an expensive full scan for disappearances, a trigger so a raw DELETE is not invisible, and a cache that only speaks when the database cannot. The defaults are the numbers that made sense once all of it was worked through.