Skip to content

auth_type = plugin: delegate client authentication to plugins - #1574

Draft
ziomarco wants to merge 8 commits into
pgdogdev:mainfrom
ziomarco:split/plugin-auth-login-path
Draft

ziomarco wants to merge 8 commits into
pgdogdev:mainfrom
ziomarco:split/plugin-auth-login-path

Conversation

@ziomarco

Copy link
Copy Markdown
Contributor

Stacked on the ABI and server_role PRs; only the last three commits are new here.

This adds auth_type = "plugin", which hands client authentication to the loaded plugins through the authenticate hook. PgDog drives the wire the same way passthrough auth does, asks for a cleartext credential, and then calls each plugin's authenticate in [[plugins]] order on the Tokio blocking pool. The first plugin that does not skip decides. A Deny gives the client the usual generic authentication error and the reason only shows up in PgDog's log.

Following the RFC review, when every plugin skips the login is denied too. auth_type = "plugin" is an explicit choice and there is no fallback to password verification in this PR; I am proposing that separately so it can be discussed on its own. A plugin panic is caught inside the plugin bridge and treated as a Deny, so a buggy plugin cannot take PgDog down.

An Allow can carry a derived user, backend credentials, a server_role, a read-only flag and a provision flag. databases::add_authenticated reconciles that grant into the pools on every Allow: it fills gaps in an existing users.toml entry without ever overwriting configured values, provisions a new pool when asked, and lets a configured server_role win over a conflicting grant with a warning. Because a plugin can change which pool a login ends up on, the startup role parameter guard from the server_role PR is checked again against the effective user after an Allow.

Grants are validated in the driver before anything acts on them, since the names in them become pool identities, config entries and startup parameters: derived_user, server_user and server_role have to be non-empty, unpadded, free of control characters and at most 63 bytes, and server_password non-empty and free of control characters. Anything else denies the login with PluginInvalidGrant and logs why, rather than provisioning a user called "". Nothing a grant provisions is written to users.toml: it lives in the in-memory configuration, so a reload or restart drops it, the same as the passthrough path.

The RFC asked for a cap on concurrent plugin calls. Main already has general.background_workers sizing the blocking pool, so I dropped my own setting and the docs point there instead. The default of 0 leaves a single blocking thread, which means plugin logins run one at a time and a slow plugin also delays the backend DNS lookups that share that thread, so config load warns about that combination.

Config load also warns when plugin auth runs without tls_client_required, since the credential travels in band, and when no [[plugins]] are configured at all, since every login would be denied. The "user has no password" warning is silenced under plugin auth, where that is the normal case, and the "client connected" line reports auth: plugin instead of auth: passthrough. A plugin's deny reason follows log_connections like every other authentication failure, so a client retrying in a loop cannot flood the log, and the reason is always there at debug level. The pool launch gate is relaxed only under plugin auth and only for pools that have their own backend credentials; pools without any stay disabled until a plugin Allow provisions them.

A small cdylib test plugin and an rspec suite under integration/plugins/auth cover the good login, deny, panic, wrong and all-skip credentials, impersonation with pool provisioning, gap filling on a pre-configured pool, role escapes, a rejected grant, and a read-only pool.

🤖 Generated with Claude Code

ziomarco and others added 8 commits September 16, 2026 18:26
Plugins can now take part in client authentication. A plugin implements
Plugin::authenticate, receives the user, database, credential, client
address and TLS details as borrowed strings, and returns Skip, Allow or
Deny. Allow can carry a derived user, a server_role to assume on the
backend, backend credentials, a read-only flag and a provision flag.

No ownership crosses the FFI boundary: the owned decision stays on the
plugin's stack and each string field is streamed to the host through a
sink callback as a borrowed PdStr while the call is in progress, so
there is nothing to free on either side. A panic inside the plugin's
authenticate is caught on the plugin side and turned into a Deny, so it
never unwinds into the host as a foreign exception.

The hook is a new slot appended to PluginVtable, which is an ABI change,
so pgdog-plugin moves from 0.4.0 to 0.5.0. The loader compares
major.minor, so plugins built against 0.4 are skipped with a warning
rather than loaded against a vtable they do not match.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Store loaded plugins in an IndexMap so they are consulted in the order
they appear in pgdog.toml. HashMap iteration order was arbitrary, which
made "first plugin to answer wins" nondeterministic for router plugins
and would make ordering authentication plugins impossible.

Keep one Option<Library> slot per configured plugin instead of dropping
failed dlopen results from the vector. Previously a plugin that failed
to load shifted every later library down one index, so the next plugin
name was paired with the wrong library. Also drop the unwrap on LIBS
right after setting it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
A [[users]] entry can set server_role. The pool keeps connecting as
server_user and passes role=<server_role> in the startup packet, so the
role is the session's reset value: RESET ROLE and DISCARD ALL fall back
to it, RESET ALL leaves it untouched, and connection cleanup never
clears it.

The setting is plumbed from the user config through Address into the
pool's startup parameters, next to default_transaction_read_only. Config
load warns when a server_role user has no backend credential of its own
(no server_password, no plain password, password server_auth), since
PgDog could not open server connections for it. The users.toml JSON
schema is regenerated and example.users.toml documents the setting.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Clients on a pool with server_role must not be able to leave the role.
The query parser flags SET ROLE, RESET ROLE, SET SESSION AUTHORIZATION
(and its RESET), the set_config('role', ...) and
set_config('session_authorization', ...) spellings, and any of those
inside a multi-statement query, as Command::RoleLocked. The query engine
answers with a 42501 error, marks an open transaction as aborted, and
keeps the session alive.

Cluster::use_query_parser forces full parsing whenever server_role is
set, because the regex fast path would let SELECT set_config('role', ...)
through. Since that silently overrides query_parser = "off", the config
check now warns about it at load.

The parser cannot see every way to reach SET ROLE: a DO block, a function
body, or a computed set_config() name all bypass it. Those escapes stay
possible inside the client's own session, where the real boundary is which
roles server_user is a member of, but they must not outlive it: role is
GUC_NO_RESET_ALL, so RESET ALL leaves an escaped role in place and the
next client to check that connection out would inherit it. Pool cleanup
now resets the role on check-in for these pools, which restores the
startup-packet value, i.e. the impersonated role. A pool test escapes the
role behind the parser's back and asserts the next checkout of the same
connection is back to the impersonated one.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Client startup parameters are synced to the server as SET statements on
every checkout, and "role" is not in the untracked list. A client could
therefore send role=other_role (or options=-c role=other_role) in its
startup packet and have PgDog itself run SET "role" on the backend,
bypassing the query-level guard; DISCARD ALL would re-apply it from the
saved startup parameters.

On pools with a fixed server_role the parameter is now dropped at login
with a warning. Parameters::remove is added for this, since reset() has
transaction semantics.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
With auth_type = "plugin", PgDog asks the client for a cleartext
credential (the same wire flow as passthrough auth) and hands it to the
loaded plugins in [[plugins]] order on the Tokio blocking pool. The first
plugin that does not skip decides. Deny sends the client the generic
auth error and logs the reason only in PgDog; when every plugin skips
the login is denied as well, there is no fallback to password
verification. A plugin panic is caught by the pgdog-plugin bridge and
becomes a Deny.

An Allow may carry a derived user, backend credentials, a server_role,
a read-only flag and a provision flag. databases::add_authenticated
reconciles the grant into the pools on every Allow: it fills missing
server_user, server_password, server_role and read_only on an existing
users.toml entry, never overwrites a configured value (a configured
server_role that conflicts with the grant wins and logs a warning), and
provisions a new pool when the plugin asks for one that does not exist.
Grants are validated first: the names in them become pool identities,
config entries and startup parameters, so an empty, padded, over-long or
control-character name (or such a server_password) denies the login with
PluginInvalidGrant instead of provisioning a user PostgreSQL cannot
address.

Because a plugin can change which pool a login lands on, the startup
"role" parameter check from the server_role work is repeated against the
effective user after a plugin Allow; otherwise role=... in the startup
packet would be synced to a freshly provisioned or completed
impersonation pool. strip_startup_role now takes the user and database
explicitly to allow this.

Concurrency of plugin calls is bounded by the runtime's blocking pool,
which general.background_workers already sizes; the branch's separate
semaphore and duplicate setting are not carried over. Config load warns
when auth_type = "plugin" runs without tls_client_required (the
credential travels in plaintext), without any [[plugins]], or with
background_workers = 0, where logins serialize on the one blocking
thread that also resolves backend DNS. The "doesn't have a password"
warning is silenced for plugin auth, where a user without a configured
password is the normal case, and the connection line reports
auth: plugin rather than auth: passthrough. The JSON schema is
regenerated for the new variant.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Pools are disabled at launch when the user has no client password and no
mTLS identity, because nobody could log in to them. Under
auth_type = "plugin" a plugin vouches for every login instead, so such a
pool is useful as long as it can authenticate to Postgres on its own.

Cluster::has_backend_credentials reports whether any pool has a backend
password or an external-identity server_auth. The launch gate lets a
cluster through when plugin auth is on and that holds; pools with no
credentials at all stay disabled until a plugin Allow provisions them
through add_authenticated. Non-plugin auth types keep the previous
behaviour unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
A cdylib test plugin (integration/plugins/test-plugins/test-plugin-auth)
decides from the credential the client sends: "deny", "panic",
"secret-<user>", "impersonate:<role>" and Skip for anything else. The
rspec suite in integration/plugins/auth covers the good login, the
generic error for deny, panic, wrong and all-skip credentials (with the
deny reason only in PgDog's log), pool provisioning with role
impersonation, gap-filling server_role on a pre-configured pool, role
persistence across connection cleanup, rejection of role escapes, and
INSERT on a read-only pool.

integration/plugins/run.sh builds the plugin and runs the suite as a
second phase after the routing plugins; setup.sql creates the
impersonated roles directly in Postgres. common.sh now captures stderr
in integration/log.txt so the spec can assert on tracing output.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant