Continuous re-validation of session credentials

Started by Ajit Awekar5 months ago8 messageshackers
Jump to latest
#1Ajit Awekar
ajitpostgres@gmail.com

Hi,

Today PG validates a client's credentials only once, at connection
time. After that the backend runs until the client disconnects, even if
the
basis for the original authentication decision has gone away. In
particular:

- the role's VALID UNTIL passes, or the role is dropped (ALTER ROLE ...
VALID UNTIL / DROP ROLE);
- the OAuth bearer token the session authenticated with expires;
- the TLS client certificate the session authenticated with reaches its
notAfter date.

In all of these cases a long-lived session keeps running with credentials
that
would be rejected on a fresh connection. For environments with short-lived
credentials (OAuth tokens, short-lived certs, time-boxed accounts) this is a
real gap: revoking access has no effect on already-established sessions.

This patch series adds an optional mechanism to periodically re-validate
the
credentials of an active session and terminate it (FATAL) once they are no
longer valid.

A per-backend timer (CREDENTIAL_VALIDATION_TIMEOUT) fires every
credential_validation_interval seconds and sets a pending flag.

Validation has two layers:
- A baseline, auth-method-independent check (role still exists and has
not
passed rolvaliduntil), applied to every authenticated session.
- Optional method-specific validators, registered via
RegisterCredentialValidator(), for OAuth token expiry and client
certificate expiry.

The framework is deliberately extensible: adding re-validation for a new
authentication method needs only three small steps -- add a
CredentialValidationType, implement a "bool validator(void)" callback that
returns whether the credential is still valid, and register it with
RegisterCredentialValidator(). The certificate and OAuth validators in
0002
and 0003 are themselves examples of plugging into the framework this way,
so methods such as LDAP, RADIUS, or GSSAPI/Kerberos credential lifetimes
could be added later without touching the core.

Two GUCs :
credential_validation_enabled (bool, default off)
credential_validation_interval (int, 5..3600 s, default 60)

Patch series
------------

0001 Framework + baseline role-validity check (rolvaliduntil / role
existence). Useful on its own for password/md5/scram sessions.
0002 TLS client certificate expiry. The cert presented at connect time
is
retained on the Port, so its notAfter is re-checked locally with no
network round-trip.
0003 OAuth token expiry. This adds an optional expire_cb callback to
OAuthValidatorCallbacks; to stay ABI-compatible the validator magic
is
versioned (V1 = existing layout, V2 = adds expire_cb), and the
server
accepts both.

Request a review.

Thanks & Best Regards,
Ajit

Attachments:

0003-Add-OAuth-token-expiry-to-credential-validation.patchapplication/octet-stream; name=0003-Add-OAuth-token-expiry-to-credential-validation.patchDownload+102-8
0001-Add-continuous-credential-validation-framework.patchapplication/octet-stream; name=0001-Add-continuous-credential-validation-framework.patchDownload+768-1
0002-Add-TLS-client-certificate-expiry-to-credential-vali.patchapplication/octet-stream; name=0002-Add-TLS-client-certificate-expiry-to-credential-vali.patchDownload+236-2
#2Ajit Awekar
ajitpostgres@gmail.com
In reply to: Ajit Awekar (#1)
Re: Continuous re-validation of session credentials

Hi,

Attached is v2 of the patch set, rebased on the current master.

The only functional change from the previous version is a fix for the
cfbot failure. The earlier version src/test/modules/test_misc/t/
003_check_guc.pl
due to the tab in the trailing spaces.

Thanks & Best Regards,
Ajit

On Tue, 16 Jun 2026 at 17:44, Ajit Awekar <ajitpostgres@gmail.com> wrote:

Show quoted text

Hi,

Today PG validates a client's credentials only once, at connection
time. After that the backend runs until the client disconnects, even if
the
basis for the original authentication decision has gone away. In
particular:

- the role's VALID UNTIL passes, or the role is dropped (ALTER ROLE ...
VALID UNTIL / DROP ROLE);
- the OAuth bearer token the session authenticated with expires;
- the TLS client certificate the session authenticated with reaches its
notAfter date.

In all of these cases a long-lived session keeps running with credentials
that
would be rejected on a fresh connection. For environments with short-lived
credentials (OAuth tokens, short-lived certs, time-boxed accounts) this is
a
real gap: revoking access has no effect on already-established sessions.

This patch series adds an optional mechanism to periodically re-validate
the
credentials of an active session and terminate it (FATAL) once they are no
longer valid.

A per-backend timer (CREDENTIAL_VALIDATION_TIMEOUT) fires every
credential_validation_interval seconds and sets a pending flag.

Validation has two layers:
- A baseline, auth-method-independent check (role still exists and has
not
passed rolvaliduntil), applied to every authenticated session.
- Optional method-specific validators, registered via
RegisterCredentialValidator(), for OAuth token expiry and client
certificate expiry.

The framework is deliberately extensible: adding re-validation for a new
authentication method needs only three small steps -- add a
CredentialValidationType, implement a "bool validator(void)" callback that
returns whether the credential is still valid, and register it with
RegisterCredentialValidator(). The certificate and OAuth validators in
0002
and 0003 are themselves examples of plugging into the framework this
way,
so methods such as LDAP, RADIUS, or GSSAPI/Kerberos credential lifetimes
could be added later without touching the core.

Two GUCs :
credential_validation_enabled (bool, default off)
credential_validation_interval (int, 5..3600 s, default 60)

Patch series
------------

0001 Framework + baseline role-validity check (rolvaliduntil / role
existence). Useful on its own for password/md5/scram sessions.
0002 TLS client certificate expiry. The cert presented at connect time
is
retained on the Port, so its notAfter is re-checked locally with no
network round-trip.
0003 OAuth token expiry. This adds an optional expire_cb callback to
OAuthValidatorCallbacks; to stay ABI-compatible the validator
magic is
versioned (V1 = existing layout, V2 = adds expire_cb), and the
server
accepts both.

Request a review.

Thanks & Best Regards,
Ajit

Attachments:

0003-Add-OAuth-token-expiry-to-credential-validation.patchapplication/octet-stream; name=0003-Add-OAuth-token-expiry-to-credential-validation.patchDownload+102-8
0002-Add-TLS-client-certificate-expiry-to-credential-vali.patchapplication/octet-stream; name=0002-Add-TLS-client-certificate-expiry-to-credential-vali.patchDownload+236-2
0001-Add-continuous-credential-validation-framework.patchapplication/octet-stream; name=0001-Add-continuous-credential-validation-framework.patchDownload+768-1
#3Ajit Awekar
ajitpostgres@gmail.com
In reply to: Ajit Awekar (#2)
Re: Continuous re-validation of session credentials

Hi,

Following up on the ongoing work for continuous credential validation, I
would like to propose the next two patches in the series.

These patches extend the continuous validation framework to handle both
GSSAPI/Kerberos and LDAP (Search+Bind) authenticated sessions.
Patch 4/5: Add GSS credential expiry to credential validation

This patch introduces method-specific validation for GSSAPI/Kerberos
sessions (CVT_GSS).The GSS security context established at authentication
carries a lifetime derived from the client's Kerberos ticket. We introduce
a helper be_gssapi_get_context_expired() which utilizes gss_context_time()
on the acceptor context retained on the Port. This is a purely local check
that requires no round-trip to the KDC. If the context lifetime has
elapsed, the session is safely terminated.

postgres=> select system_user;
system_user
-----------------------
gss:test1@EXAMPLE.COM
(1 row)

postgres=> select current_user;
current_user
--------------
test1

postgres=> select current_time;
FATAL: session credentials have expired
HINT: Please reconnect to establish a new authenticated session.
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.
The connection to the server was lost. Attempting reset: Failed.

(1 row)

Patch 5/5: Add LDAP account-existence check to credential validation

This patch adds validation support for LDAP sessions (CVT_LDAP).

Unlike token- or certificate-based authentication, an LDAP session does
not retain a credential with an intrinsic expiry date. Instead, "validity"
is defined as the account's continued existence within the directory.

During each validation cycle, the backend connects and re-binds using the
configured search credentials (ldapbinddn / ldapbindpasswd), then re-runs
the configured search filter. If the search yields exactly zero entries,
the account is considered deleted or disabled, and the session is
terminated.

postgres=> SELECT current_user;
current_user
--------------
test1
(1 row)

postgres=> select system_user;
system_user
----------------------------------
ldap:uid=test1,dc=example,dc=net. <= After this I fired ldapdelete
and got validation error on next validation cycle
(1 row)

postgres=> select current_time;
FATAL: session credentials have expired
HINT: Please reconnect to establish a new authenticated session.
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.
The connection to the server was lost. Attempting reset: Failed.

(1 row)

Thanks & Best regards,

Ajit

On Fri, 26 Jun 2026 at 11:21, Ajit Awekar <ajitpostgres@gmail.com> wrote:

Show quoted text

Hi,

Attached is v2 of the patch set, rebased on the current master.

The only functional change from the previous version is a fix for the
cfbot failure. The earlier version src/test/modules/test_misc/t/
003_check_guc.pl
due to the tab in the trailing spaces.

Thanks & Best Regards,
Ajit

On Tue, 16 Jun 2026 at 17:44, Ajit Awekar <ajitpostgres@gmail.com> wrote:

Hi,

Today PG validates a client's credentials only once, at connection
time. After that the backend runs until the client disconnects, even if
the
basis for the original authentication decision has gone away. In
particular:

- the role's VALID UNTIL passes, or the role is dropped (ALTER ROLE ...
VALID UNTIL / DROP ROLE);
- the OAuth bearer token the session authenticated with expires;
- the TLS client certificate the session authenticated with reaches its
notAfter date.

In all of these cases a long-lived session keeps running with credentials
that
would be rejected on a fresh connection. For environments with
short-lived
credentials (OAuth tokens, short-lived certs, time-boxed accounts) this
is a
real gap: revoking access has no effect on already-established sessions.

This patch series adds an optional mechanism to periodically re-validate
the
credentials of an active session and terminate it (FATAL) once they are no
longer valid.

A per-backend timer (CREDENTIAL_VALIDATION_TIMEOUT) fires every
credential_validation_interval seconds and sets a pending flag.

Validation has two layers:
- A baseline, auth-method-independent check (role still exists and
has not
passed rolvaliduntil), applied to every authenticated session.
- Optional method-specific validators, registered via
RegisterCredentialValidator(), for OAuth token expiry and client
certificate expiry.

The framework is deliberately extensible: adding re-validation for a new
authentication method needs only three small steps -- add a
CredentialValidationType, implement a "bool validator(void)" callback
that
returns whether the credential is still valid, and register it with
RegisterCredentialValidator(). The certificate and OAuth validators in
0002
and 0003 are themselves examples of plugging into the framework this
way,
so methods such as LDAP, RADIUS, or GSSAPI/Kerberos credential lifetimes
could be added later without touching the core.

Two GUCs :
credential_validation_enabled (bool, default off)
credential_validation_interval (int, 5..3600 s, default 60)

Patch series
------------

0001 Framework + baseline role-validity check (rolvaliduntil / role
existence). Useful on its own for password/md5/scram sessions.
0002 TLS client certificate expiry. The cert presented at connect
time is
retained on the Port, so its notAfter is re-checked locally with
no
network round-trip.
0003 OAuth token expiry. This adds an optional expire_cb callback to
OAuthValidatorCallbacks; to stay ABI-compatible the validator
magic is
versioned (V1 = existing layout, V2 = adds expire_cb), and the
server
accepts both.

Request a review.

Thanks & Best Regards,
Ajit

Attachments:

t248558_3
0001-Add-continuous-credential-validation-framework.patchapplication/octet-stream; name=0001-Add-continuous-credential-validation-framework.patchDownload+768-1
0003-Add-OAuth-token-expiry-to-credential-validation.patchapplication/octet-stream; name=0003-Add-OAuth-token-expiry-to-credential-validation.patchDownload+102-8
0004-Add-GSS-credential-expiry-to-credential-validation.patchapplication/octet-stream; name=0004-Add-GSS-credential-expiry-to-credential-validation.patchDownload+255-11
0002-Add-TLS-client-certificate-expiry-to-credential-vali.patchapplication/octet-stream; name=0002-Add-TLS-client-certificate-expiry-to-credential-vali.patchDownload+245-2
0005-Add-LDAP-account-existence-check-to-credential-valid.patchapplication/octet-stream; name=0005-Add-LDAP-account-existence-check-to-credential-valid.patchDownload+361-1
#4Ajit Awekar
ajitpostgres@gmail.com
In reply to: Ajit Awekar (#3)
Re: Continuous re-validation of session credentials

Hi Hackers,

Attached is v2 of the series, with three fixes folded into 0001 (no
changes to 0002-0005):

1. Standby servers

CheckCredentialValidity() no longer skips validation under
RecoveryInProgress(). Hot-standby sessions run continuously "in
recovery", so this was silently disabling the feature for read
replicas -- all the checks involved are read-only/local, so
there's no reason to exclude them.

2. Set Session Authorization

ValidateRoleValidity() now checks GetAuthenticatedUserId()
instead of GetSessionUserId(), so a superuser can't mask the
login role's expiry/removal by switching session authorization.
This also keeps it consistent with the method-specific
validators, which always check the fixed login identity. Added
regression coverage.

3. Walsenders

EnableCredentialValidationTimeout() and CheckCredentialValidity()
now explicitly skip AmWalSenderProcess()

Request a review.

Thanks & Best Regards,
Ajit

On Wed, 1 Jul 2026 at 17:45, Ajit Awekar <ajitpostgres@gmail.com> wrote:

Show quoted text

Hi,

Following up on the ongoing work for continuous credential validation, I
would like to propose the next two patches in the series.

These patches extend the continuous validation framework to handle both
GSSAPI/Kerberos and LDAP (Search+Bind) authenticated sessions.
Patch 4/5: Add GSS credential expiry to credential validation

This patch introduces method-specific validation for GSSAPI/Kerberos
sessions (CVT_GSS).The GSS security context established at authentication
carries a lifetime derived from the client's Kerberos ticket. We introduce
a helper be_gssapi_get_context_expired() which utilizes gss_context_time()
on the acceptor context retained on the Port. This is a purely local
check that requires no round-trip to the KDC. If the context lifetime has
elapsed, the session is safely terminated.

postgres=> select system_user;
system_user
-----------------------
gss:test1@EXAMPLE.COM
(1 row)

postgres=> select current_user;
current_user
--------------
test1

postgres=> select current_time;
FATAL: session credentials have expired
HINT: Please reconnect to establish a new authenticated session.
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.
The connection to the server was lost. Attempting reset: Failed.

(1 row)

Patch 5/5: Add LDAP account-existence check to credential validation

This patch adds validation support for LDAP sessions (CVT_LDAP).

Unlike token- or certificate-based authentication, an LDAP session does
not retain a credential with an intrinsic expiry date. Instead, "validity"
is defined as the account's continued existence within the directory.

During each validation cycle, the backend connects and re-binds using the
configured search credentials (ldapbinddn / ldapbindpasswd), then re-runs
the configured search filter. If the search yields exactly zero entries,
the account is considered deleted or disabled, and the session is
terminated.

postgres=> SELECT current_user;
current_user
--------------
test1
(1 row)

postgres=> select system_user;
system_user
----------------------------------
ldap:uid=test1,dc=example,dc=net. <= After this I fired ldapdelete and got validation error on next validation cycle
(1 row)

postgres=> select current_time;
FATAL: session credentials have expired
HINT: Please reconnect to establish a new authenticated session.
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Failed.
The connection to the server was lost. Attempting reset: Failed.

(1 row)

Thanks & Best regards,

Ajit

On Fri, 26 Jun 2026 at 11:21, Ajit Awekar <ajitpostgres@gmail.com> wrote:

Hi,

Attached is v2 of the patch set, rebased on the current master.

The only functional change from the previous version is a fix for the
cfbot failure. The earlier version src/test/modules/test_misc/t/
003_check_guc.pl
due to the tab in the trailing spaces.

Thanks & Best Regards,
Ajit

On Tue, 16 Jun 2026 at 17:44, Ajit Awekar <ajitpostgres@gmail.com> wrote:

Hi,

Today PG validates a client's credentials only once, at connection
time. After that the backend runs until the client disconnects, even if
the
basis for the original authentication decision has gone away. In
particular:

- the role's VALID UNTIL passes, or the role is dropped (ALTER ROLE
...
VALID UNTIL / DROP ROLE);
- the OAuth bearer token the session authenticated with expires;
- the TLS client certificate the session authenticated with reaches
its
notAfter date.

In all of these cases a long-lived session keeps running with
credentials that
would be rejected on a fresh connection. For environments with
short-lived
credentials (OAuth tokens, short-lived certs, time-boxed accounts) this
is a
real gap: revoking access has no effect on already-established sessions.

This patch series adds an optional mechanism to periodically re-validate
the
credentials of an active session and terminate it (FATAL) once they are
no
longer valid.

A per-backend timer (CREDENTIAL_VALIDATION_TIMEOUT) fires every
credential_validation_interval seconds and sets a pending flag.

Validation has two layers:
- A baseline, auth-method-independent check (role still exists and
has not
passed rolvaliduntil), applied to every authenticated session.
- Optional method-specific validators, registered via
RegisterCredentialValidator(), for OAuth token expiry and client
certificate expiry.

The framework is deliberately extensible: adding re-validation for a new
authentication method needs only three small steps -- add a
CredentialValidationType, implement a "bool validator(void)" callback
that
returns whether the credential is still valid, and register it with
RegisterCredentialValidator(). The certificate and OAuth validators in
0002
and 0003 are themselves examples of plugging into the framework this
way,
so methods such as LDAP, RADIUS, or GSSAPI/Kerberos credential
lifetimes
could be added later without touching the core.

Two GUCs :
credential_validation_enabled (bool, default off)
credential_validation_interval (int, 5..3600 s, default 60)

Patch series
------------

0001 Framework + baseline role-validity check (rolvaliduntil / role
existence). Useful on its own for password/md5/scram sessions.
0002 TLS client certificate expiry. The cert presented at connect
time is
retained on the Port, so its notAfter is re-checked locally with
no
network round-trip.
0003 OAuth token expiry. This adds an optional expire_cb callback to
OAuthValidatorCallbacks; to stay ABI-compatible the validator
magic is
versioned (V1 = existing layout, V2 = adds expire_cb), and the
server
accepts both.

Request a review.

Thanks & Best Regards,
Ajit

Attachments:

t248558_4
v2-0003-Add-OAuth-token-expiry-to-credential-validation.patchapplication/octet-stream; name=v2-0003-Add-OAuth-token-expiry-to-credential-validation.patchDownload+102-8
v2-0005-Add-LDAP-account-existence-check-to-credential-valid.patchapplication/octet-stream; name=v2-0005-Add-LDAP-account-existence-check-to-credential-valid.patchDownload+361-1
v2-0001-Add-continuous-credential-validation-framework.patchapplication/octet-stream; name=v2-0001-Add-continuous-credential-validation-framework.patchDownload+879-1
v2-0004-Add-GSS-credential-expiry-to-credential-validation.patchapplication/octet-stream; name=v2-0004-Add-GSS-credential-expiry-to-credential-validation.patchDownload+261-11
v2-0002-Add-TLS-client-certificate-expiry-to-credential-vali.patchapplication/octet-stream; name=v2-0002-Add-TLS-client-certificate-expiry-to-credential-vali.patchDownload+245-2
#5Jakub Wartak
jakub.wartak@enterprisedb.com
In reply to: Ajit Awekar (#4)
Re: Continuous re-validation of session credentials

On Thu, Sep 17, 2026 at 2:02 PM Ajit Awekar <ajitpostgres@gmail.com> wrote:

Hi Hackers,

Attached is v2 of the series, with three fixes folded into 0001 (no
changes to 0002-0005):

[..]

Hi Ajit, I've played with the patchset a bit, but just with the 0001+0002
parts. The basic funtionality works (as advertised :)), however to me it looks
there are certain glaps that needs to be closed, see below:

1. With credential_validation_enabled=on, it looks like any ERROR resets the
validation timeout. Technically the code after sigsetjmp() in postgres.c
is used for error handling in main loop and the thing there calls
disable_all_timeouts(), so with the patchset if one has rogue user
that is intentionally calling something like below in constant loop:
SELECT /* stealing */ somedata FROM somewhere;
SELECT 0/0; -- to generate division by 0 and reset
it won't disconnect him at and he will be able to carry on with selects as
long as he wants to as those ERRORs, seem to reset the timeout machinery.
If I stops erroring, then yes it will be invalidated. Perhaps some
additional timeout of last successful validation would be needed to protect
against that (?) somewhere nearby where EnableValidationTimeout() (??)

2. Dunno if that is issue or not, but superusers can disarm the credential
invalidation mechanics completley silently via SET, because it's
PGC_SUSET. This somewhat means that remote superuser authed by e.g.
LDAP (and with it's cred invalidated there), could bypass this, contrary
to what feature says and docs are silent about this too. So my question
to wider auidence would be like this: should this be PGC_SIGHUP (so at
least one could log disabling that GUC for everybody by superuser
OR should that be documented some risks for superuser with this as this
might save us from some future low-score-CVE-but-still-CVE I think).

3. 0001 says "Replication connections are out of scope for this feature"
wihtin EnableCredentialValidationTimeout(), but I think it needs to be
more detailed and explictly make distinction between physical rep and
logical replication. I've tested both scenarios and for physical I think
it is OK to be disabled (just mention it in docs explictlly?). However,
for logical replication one can still request "replication=database"
which is logical replication connection and still issue SQL commands
there and cred. invalidation won't ever kick in (!!), so at least some
comment/docs within 0001 need to be fixed or cover that scenario (expired
but idle user connection with REPLICATION priv won't be ever invalidated).
But I really think this escalates too quickly because if that's known
issue, then it can be quickly abused by superusers: superuser (which e.g
has been authed by e.g. LDAP and whom have and have this REPLICATION priv
by defintiion) can simply keep logical rep connection open (psql
replication=database) and won't be ever terminated as v2 stands today.

4. I have one doubt: all of his is implemented at the command execution
boundary, which means idle session won't be terminated which kind of may
look confusing to some DBAs ("I have configured cred invalidations, users
are expired but they are still visible in the pg_stat_activity")
or maybe that would be be fine, but then we should mention in docs enabling
idle_session_timeout to avoid that situation. However I've noticed
that this seems to be kind of sligthly inconsistent with how
idle_session_timeout is implemented today: idle_session_timeout shuts down
even idle sessions right on time, and not on command boundary, but
maybe that's OK.

5. IMHO the new tests take way too much time:
postgresql:authentication / authentication/008_continuous_validation ~57s
postgresql:ssl / ssl/005_cert_continuous_validation ~23
sadly shortening timeouts maybe have CI/buildfarm failures, dunno how to
solve that, maybe some sleeps could be reduced, but how else we could
test for time-based capability like that??

6. You seem to be using "CVT" shortcut in the patch, but I don't see place
where the shortcut is explained (maybe in enum CredentialValidationType?)

7. Could we add more detailed logging to the server log using errdetail_log()
on which exact validator failed and for which user exactly? Today with
default logging setting I get some user killed like that we just get
logmsg like:
[43601]: HINT: Please reconnect to establish a new authenticated session
[43601]: HINT: Please reconnect to establish a new authenticated session

which is not helpful at all in terms of saying which user and why got the
issue. Only if libpq attempts to auto-reconnect then we get:
[43636]: DETAIL: User "localuser" has an expired password.
[43636]: DETAIL: User "localuser" has an expired password.

but that might be not always be true (and anyway it's hard connect those
two PIDs are related).

8. With 0002 (TLS cert invalidation after now() being "notAfter"), I've got
this:
FATAL: session credentials have expired
HINT: Please reconnect to establish a new authenticated session.
-- new session below:
LOG: could not accept SSL connection: certificate verify failed
DETAIL: Client certificate verification failed at depth 0: certificate
has expired. Failed certificate data (unverified): subject "/CN=localuser",
serial number 2, issuer "/CN=myrootca".

Anyway the above worked to invalidate for hostssl's auth-method "cert"
configuration, but with with more advanced combined (two-factor) setup
it did not:
# TYPE DB USER ADDRESS METHOD
# does work:
#hostssl all all 0.0.0.0/0 cert
# below doesn't work??? fallback to rolpasswdvalid??:
hostssl all all 0.0.0.0/0 scram-sha-256 clientcert=verify-full

my already exisitng valid connection (at the connection time) was never
invalidated, instead it has shown this @ ~09:05 GMT something odd from
the start:

$ psql "host=db.example.com dbname=postgres user=localuser \
sslmode=verify-full sslcert=client.crt sslkey=client.key \
slrootcert=root.crt"
Password for user localuser:
WARNING: role password will expire soon
DETAIL: The password for role "localuser" will expire in 12 hours.
psql (20devel)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,
compression: off, ALPN: postgresql)
[.. and much later @ 11:11 CEST it was still working
postgres=> select now();
now
-------------------------------
2026-09-24 11:11:33.519307+02
(1 row)

so it has shown that rolpasswdvalid is going to expire in 12 hours, but
the cert is going to expire much quicker, the cert was valid just till
11:06 CEST (just ignore +/- 2h due to TZ): Validity ()
Not Before: Sep 24 08:54:10 2026 GMT
Not After : Sep 24 09:06:21 2026 GMT

   so to me it looks like it is taking pg_authid.rolvaliduntil (based on
   uaSCRAM rather than minimum of those two (?)). Next attempt to
   re-connect after some time of course is  impossible due to "SSL error:
   sslv3 alert certificate expired" (so the cert is really expired, it's
   just gap in the 2FA case where the v2-0002 fails to recheck cert
   credentials). In auth-validate at the end of CheckCredentialValidity(),
   with the below force-rechecking of CVT_CERT in case of success of
   rolpasswdvalid (e.g. SCRAM) itself:
      [..]
      +       /* 2FA re-check */
      +       if (result &&
      +               validation_type != CVT_CERT &&
      +               validators[CVT_CERT] != NULL &&
      +               MyProcPort != NULL &&
      +               MyProcPort->hba != NULL &&
      +               MyProcPort->hba->clientcert != clientCertOff) {
      +               elog(DEBUG1, "credential validation 2FA too: CVT_CERT");
      +               result = validators[CVT_CERT] ();
      +       }
      +
              return result
      }

it seems to be behave OKayish with this code, but I'm not expert on auth
on those matters. Anyway I'm just attaching steps to repro all of this
(selfsigned CA and see next follow-up steps in #9 too).

9. TLS revocation lists (CRL) seem also not being rechecked, e.g. given a
previous client.key would be stolen and the CA would revoke it like below:

cat > crl.cnf << EOF
[ca]
default_ca = myca
[myca]
database = demoCA/index.txt
default_md = sha256
default_crl_days = 3650
EOF
# revoke client.crt (basically update's just CA db in mydemo/*)
openssl ca -config crl.cnf -revoke client.crt -cert root.crt\
-keyfile root.key
# renerate CRL and save it root.crl
openssl ca -config crl.cnf -gencrl -cert root.crt -keyfile root.key \
-out root.crl
# make it effective
echo "ssl_crl_file = 'root.crl'" >> postgresql.auto.conf
pg_ctl reload

Now altough, the certificate has been revoked, the v2-0002 would have to be
taught to be smart enough to terminate such backend(s). Reconnecting of
course fails with: "SSL error: sslv3 alert certificate revoked", so the cert
is really revoked, it's just some missing code in the patchset for checking
actual cert status for not being revoked.

Kind of similiar thing or open question would is if such implementation
shouldn't verify intermediary CA revokes too (to verify full trust chain),
but I'm not that deep into how x509/OpenSSL API works, so I cannot answer
help with that (I don't know how heavy/inefficent that is). It feels kind
of heavyweight, because be_tls_init() seems to be (re)loading in postmaster,
so if the CRL is updated (with SIGHUP) that could potentially mean we should
do the pricey loading of CRL every now and then, just to get up to date
CRL data, so we revoked from actual information(???) Or maybe we should
somehow cache it on every SIGHUP... or maybe take just document it as known
issue and it doesn't work with CRL ??

10.Altough I haven't reviewed the remaining ones, qq, don't we do miss PAM
here ? I've never used but if auth-method=pam would be deployed and the
password would expire (PAM_ACCT_EXPIRED?) we should also invalidate the
session, or is that out of scope for now from patch list?

-J.

Attachments:

ssl_setup_selfsigned_CA_steps.txttext/plain; charset=US-ASCII; name=ssl_setup_selfsigned_CA_steps.txtDownload
#6Ajit Awekar
ajitpostgres@gmail.com
In reply to: Jakub Wartak (#5)
Re: Continuous re-validation of session credentials

Thanks a lot Jakub for the detailed review.

1. Repeated errors resetting the timeout. Fixed: the next-validation
deadline is now tracked independently of disable_all_timeouts(); error
recovery re-arms at that same deadline instead of granting a fresh
interval.

2. Superuser silently disables validation. Fixed: the two GUCs are now
PGC_SU_BACKEND, not PGC_SUSET — settable only at session start, not via
SET afterward. Rationale documented in config.sgml

3. Logical replication skipping validation. Confirmed and fixed. The
walsender skip was unconditional; now scoped to
AmWalSenderProcess() && !am_db_walsender, so only physical replication
stays exempt. A logical walsender's streaming loop is serviced by a new
hook alongside the existing config-reload handling. New regression test
added, plus manual verification against an actively-streaming
pg_recvlogical session.

4. Idle sessions are not terminated in real time. Fixed: validation also
runs from the idle-wait point (ProcessClientReadInterrupt()), not only
at the next command boundary.

5. Test runtime (~57s/~23s). Down to ~22-30s by consolidating
independent scenarios into shared validation windows, without
shortening any timeout/interval values.

6. "CVT" unexplained. Comment added: CVT_ = CredentialValidationType.

7. Insufficient log detail. Each validator now logs specifics via
errdetail_log() (which check, which user, why).

8. Combined auth methods (clientcert=verify-full alongside
scram-sha-256). Fixed: the client cert is now explicitly re-checked
whenever the HBA line required one, regardless of the primary method's
validator.

9. CRL revocation never rechecked mid-session. Fixed for the core case
(ssl_crl_file, rechecked periodically). Two related items are
deliberately out of scope, now documented in config.sgml:
intermediate-CA revocation (the initial handshake already validates the
full chain) and ssl_crl_dir (not consulted by the periodic recheck).

10. PAM is not addressed yet proposing to keep it out of
scope as a follow-up patch

Please find the attached V3 patchset. Request a review.

Thanks & Best Regards,
Ajit

On Thu, 24 Sept 2026 at 16:32, Jakub Wartak <jakub.wartak@enterprisedb.com>
wrote:

Show quoted text

On Thu, Sep 17, 2026 at 2:02 PM Ajit Awekar <ajitpostgres@gmail.com>
wrote:

Hi Hackers,

Attached is v2 of the series, with three fixes folded into 0001 (no
changes to 0002-0005):

[..]

Hi Ajit, I've played with the patchset a bit, but just with the 0001+0002
parts. The basic funtionality works (as advertised :)), however to me it
looks
there are certain glaps that needs to be closed, see below:

1. With credential_validation_enabled=on, it looks like any ERROR resets
the
validation timeout. Technically the code after sigsetjmp() in postgres.c
is used for error handling in main loop and the thing there calls
disable_all_timeouts(), so with the patchset if one has rogue user
that is intentionally calling something like below in constant loop:
SELECT /* stealing */ somedata FROM somewhere;
SELECT 0/0; -- to generate division by 0 and reset
it won't disconnect him at and he will be able to carry on with selects
as
long as he wants to as those ERRORs, seem to reset the timeout
machinery.
If I stops erroring, then yes it will be invalidated. Perhaps some
additional timeout of last successful validation would be needed to
protect
against that (?) somewhere nearby where EnableValidationTimeout() (??)

2. Dunno if that is issue or not, but superusers can disarm the credential
invalidation mechanics completley silently via SET, because it's
PGC_SUSET. This somewhat means that remote superuser authed by e.g.
LDAP (and with it's cred invalidated there), could bypass this, contrary
to what feature says and docs are silent about this too. So my question
to wider auidence would be like this: should this be PGC_SIGHUP (so at
least one could log disabling that GUC for everybody by superuser
OR should that be documented some risks for superuser with this as this
might save us from some future low-score-CVE-but-still-CVE I think).

3. 0001 says "Replication connections are out of scope for this feature"
wihtin EnableCredentialValidationTimeout(), but I think it needs to be
more detailed and explictly make distinction between physical rep and
logical replication. I've tested both scenarios and for physical I think
it is OK to be disabled (just mention it in docs explictlly?). However,
for logical replication one can still request "replication=database"
which is logical replication connection and still issue SQL commands
there and cred. invalidation won't ever kick in (!!), so at least some
comment/docs within 0001 need to be fixed or cover that scenario
(expired
but idle user connection with REPLICATION priv won't be ever
invalidated).
But I really think this escalates too quickly because if that's known
issue, then it can be quickly abused by superusers: superuser (which e.g
has been authed by e.g. LDAP and whom have and have this REPLICATION
priv
by defintiion) can simply keep logical rep connection open (psql
replication=database) and won't be ever terminated as v2 stands today.

4. I have one doubt: all of his is implemented at the command execution
boundary, which means idle session won't be terminated which kind of may
look confusing to some DBAs ("I have configured cred invalidations,
users
are expired but they are still visible in the pg_stat_activity")
or maybe that would be be fine, but then we should mention in docs
enabling
idle_session_timeout to avoid that situation. However I've noticed
that this seems to be kind of sligthly inconsistent with how
idle_session_timeout is implemented today: idle_session_timeout shuts
down
even idle sessions right on time, and not on command boundary, but
maybe that's OK.

5. IMHO the new tests take way too much time:
postgresql:authentication / authentication/008_continuous_validation
~57s
postgresql:ssl / ssl/005_cert_continuous_validation ~23
sadly shortening timeouts maybe have CI/buildfarm failures, dunno how to
solve that, maybe some sleeps could be reduced, but how else we could
test for time-based capability like that??

6. You seem to be using "CVT" shortcut in the patch, but I don't see place
where the shortcut is explained (maybe in enum
CredentialValidationType?)

7. Could we add more detailed logging to the server log using
errdetail_log()
on which exact validator failed and for which user exactly? Today with
default logging setting I get some user killed like that we just get
logmsg like:
[43601] FATAL: session credentials have expired
[43601] HINT: Please reconnect to establish a new authenticated
session

which is not helpful at all in terms of saying which user and why got
the
issue. Only if libpq attempts to auto-reconnect then we get:
[43636] FATAL: password authentication failed for user "localuser"
[43636] DETAIL: User "localuser" has an expired password.

but that might be not always be true (and anyway it's hard connect those
two PIDs are related).

8. With 0002 (TLS cert invalidation after now() being "notAfter"), I've got
this:
FATAL: session credentials have expired
HINT: Please reconnect to establish a new authenticated session.
-- new session below:
LOG: could not accept SSL connection: certificate verify failed
DETAIL: Client certificate verification failed at depth 0: certificate
has expired. Failed certificate data (unverified): subject
"/CN=localuser",
serial number 2, issuer "/CN=myrootca".

Anyway the above worked to invalidate for hostssl's auth-method "cert"
configuration, but with with more advanced combined (two-factor) setup
it did not:
# TYPE DB USER ADDRESS METHOD
# does work:
#hostssl all all 0.0.0.0/0 cert
# below doesn't work??? fallback to rolpasswdvalid??:
hostssl all all 0.0.0.0/0 scram-sha-256
clientcert=verify-full

my already exisitng valid connection (at the connection time) was never
invalidated, instead it has shown this @ ~09:05 GMT something odd from
the start:

$ psql "host=db.example.com dbname=postgres user=localuser \
sslmode=verify-full sslcert=client.crt sslkey=client.key \
slrootcert=root.crt"
Password for user localuser:
WARNING: role password will expire soon
DETAIL: The password for role "localuser" will expire in 12 hours.
psql (20devel)
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384,
compression: off, ALPN: postgresql)
[.. and much later @ 11:11 CEST it was still working
postgres=> select now();
now
-------------------------------
2026-09-24 11:11:33.519307+02
(1 row)

so it has shown that rolpasswdvalid is going to expire in 12 hours, but
the cert is going to expire much quicker, the cert was valid just till
11:06 CEST (just ignore +/- 2h due to TZ): Validity ()
Not Before: Sep 24 08:54:10 2026 GMT
Not After : Sep 24 09:06:21 2026 GMT

so to me it looks like it is taking pg_authid.rolvaliduntil (based on
uaSCRAM rather than minimum of those two (?)). Next attempt to
re-connect after some time of course is  impossible due to "SSL error:
sslv3 alert certificate expired" (so the cert is really expired, it's
just gap in the 2FA case where the v2-0002 fails to recheck cert
credentials). In auth-validate at the end of CheckCredentialValidity(),
with the below force-rechecking of CVT_CERT in case of success of
rolpasswdvalid (e.g. SCRAM) itself:
[..]
+       /* 2FA re-check */
+       if (result &&
+               validation_type != CVT_CERT &&
+               validators[CVT_CERT] != NULL &&
+               MyProcPort != NULL &&
+               MyProcPort->hba != NULL &&
+               MyProcPort->hba->clientcert != clientCertOff) {
+               elog(DEBUG1, "credential validation 2FA too:
CVT_CERT");
+               result = validators[CVT_CERT] ();
+       }
+
return result
}

it seems to be behave OKayish with this code, but I'm not expert on auth
on those matters. Anyway I'm just attaching steps to repro all of this
(selfsigned CA and see next follow-up steps in #9 too).

9. TLS revocation lists (CRL) seem also not being rechecked, e.g. given a
previous client.key would be stolen and the CA would revoke it like
below:

cat > crl.cnf << EOF
[ca]
default_ca = myca
[myca]
database = demoCA/index.txt
default_md = sha256
default_crl_days = 3650
EOF
# revoke client.crt (basically update's just CA db in mydemo/*)
openssl ca -config crl.cnf -revoke client.crt -cert root.crt\
-keyfile root.key
# renerate CRL and save it root.crl
openssl ca -config crl.cnf -gencrl -cert root.crt -keyfile root.key \
-out root.crl
# make it effective
echo "ssl_crl_file = 'root.crl'" >> postgresql.auto.conf
pg_ctl reload

Now altough, the certificate has been revoked, the v2-0002 would have
to be
taught to be smart enough to terminate such backend(s). Reconnecting of
course fails with: "SSL error: sslv3 alert certificate revoked", so the
cert
is really revoked, it's just some missing code in the patchset for
checking
actual cert status for not being revoked.

Kind of similiar thing or open question would is if such implementation
shouldn't verify intermediary CA revokes too (to verify full trust
chain),
but I'm not that deep into how x509/OpenSSL API works, so I cannot
answer
help with that (I don't know how heavy/inefficent that is). It feels
kind
of heavyweight, because be_tls_init() seems to be (re)loading in
postmaster,
so if the CRL is updated (with SIGHUP) that could potentially mean we
should
do the pricey loading of CRL every now and then, just to get up to date
CRL data, so we revoked from actual information(???) Or maybe we should
somehow cache it on every SIGHUP... or maybe take just document it as
known
issue and it doesn't work with CRL ??

10.Altough I haven't reviewed the remaining ones, qq, don't we do miss PAM
here ? I've never used but if auth-method=pam would be deployed and the
password would expire (PAM_ACCT_EXPIRED?) we should also invalidate the
session, or is that out of scope for now from patch list?

-J.

Attachments:

t248558_6
v3-0001-Add-continuous-credential-validation-framework.patchapplication/octet-stream; name=v3-0001-Add-continuous-credential-validation-framework.patchDownload+1199-1
v3-0002-Add-TLS-client-certificate-expiry-and-revocation-che.patchapplication/octet-stream; name=v3-0002-Add-TLS-client-certificate-expiry-and-revocation-che.patchDownload+618-3
#7Jakub Wartak
jakub.wartak@enterprisedb.com
In reply to: Ajit Awekar (#6)
Re: Continuous re-validation of session credentials

On Tue, Sep 29, 2026 at 2:12 PM Ajit Awekar <ajitpostgres@gmail.com> wrote:

Thanks a lot Jakub for the detailed review.

1. Repeated errors resetting the timeout. Fixed: the next-validation
deadline is now tracked independently of disable_all_timeouts(); error
recovery re-arms at that same deadline instead of granting a fresh
interval.

2. Superuser silently disables validation. Fixed: the two GUCs are now
PGC_SU_BACKEND, not PGC_SUSET — settable only at session start, not via
SET afterward. Rationale documented in config.sgml

3. Logical replication skipping validation. Confirmed and fixed. The
walsender skip was unconditional; now scoped to
AmWalSenderProcess() && !am_db_walsender, so only physical replication
stays exempt. A logical walsender's streaming loop is serviced by a new
hook alongside the existing config-reload handling. New regression test
added, plus manual verification against an actively-streaming
pg_recvlogical session.

4. Idle sessions are not terminated in real time. Fixed: validation also
runs from the idle-wait point (ProcessClientReadInterrupt()), not only
at the next command boundary.

5. Test runtime (~57s/~23s). Down to ~22-30s by consolidating
independent scenarios into shared validation windows, without
shortening any timeout/interval values.

6. "CVT" unexplained. Comment added: CVT_ = CredentialValidationType.

7. Insufficient log detail. Each validator now logs specifics via
errdetail_log() (which check, which user, why).

8. Combined auth methods (clientcert=verify-full alongside
scram-sha-256). Fixed: the client cert is now explicitly re-checked
whenever the HBA line required one, regardless of the primary method's
validator.

9. CRL revocation never rechecked mid-session. Fixed for the core case
(ssl_crl_file, rechecked periodically). Two related items are
deliberately out of scope, now documented in config.sgml:
intermediate-CA revocation (the initial handshake already validates the
full chain) and ssl_crl_dir (not consulted by the periodic recheck).

10. PAM is not addressed yet proposing to keep it out of
scope as a follow-up patch

Please find the attached V3 patchset. Request a review.

Hi Ajit, this is just about v3-0002 TLS tests mainly, I haven't looked
at the code of v3 yet nor verified the above, but for now:

0. As it stands this won't even compile with v3-0001 applied alone, it
complains with:

../src/backend/libpq/auth-validate-methods.c: In function
‘ValidateRoleValidity’:
../src/backend/libpq/auth-validate-methods.c:58:17: warning:
implicit declaration of function
‘SetCredentialValidationFailureDetail’
[-Wimplicit-function-declaration]
58 | SetCredentialValidationFailureDetail("role
validity check failed for user \"%s\": role no longer exists",
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

SetCredentialValidationFailureDetail() is defined later in v3-0002

../src/backend/libpq/auth-validate-methods.c:59:114: error: invalid
use of undefined type ‘struct Port’
59 |
MyProcPort ? MyProcPort->user_name :
"?");

it's because +#include "libpq/libpq-be.h" is missing in v3-0001

1. The cfbot complains that thing won't fly on Windows (both MSVC and mingw),
so I've started looking if I can repro 005_cert_continuous_validation:

# Running: pg_ctl --pgdata
D:/a/postgres-cfbot/postgres-cfbot/build/testrun/ssl/005_cert_continuous_validation/data/t_005_cert_continuous_validation_main_data/pgdata
--mode immediate stop
waiting for server to shut down.............. failed
pg_ctl: server does not shut down
# pg_ctl stop failed: 256
# Stale postmaster.pid file for node "main": PID 7204 no longer exists
[00:08:07.665](11.073s) # Looks like your test exited with 25 just after 3.
Warning: unable to close filehandle GEN6 properly: Bad file
descriptor during global destruction.
Warning: unable to close filehandle GEN11 properly: Bad file
descriptor during global destruction.

1b.Dunno what's happening in the above, because I've got even different error
in my env at first:

[10:18:38.476](0.347s) # === Test 1: pure client-certificate
authentication ===
# Running: openssl req -new -key
C:/git/postgres-public-ci/src/test/ssl/ssl/client.key -subj
/CN=ssltestuser -out
C:\git\postgres-public-ci\build\testrun\ssl\005_cert_continuous_validation\data\tmp_test_cK2y/short1.csr
Can't open "Z:/extlib/_5040x__/ssl\/openssl.cnf" for reading, No
such file or directory
30070000:error:80000003:system library:BIO_new_file:No such
process:crypto/bio/bss_file.c:67:calling
fopen(Z:/extlib/_5040x__/ssl\/openssl.cnf, r)
30070000:error:10000080:BIO routines:BIO_new_file:no such
file:crypto/bio/bss_file.c:75:

the issue seems to be that there seems to be no "-config" in openssl in
that new mint function for openssl req and at least here for some reason
this distribtution of OpenSSL tries to use some arbirary non-existent path
and fails (Z:\)

1c.Then I've got the similiar error as cfbot:
Running: openssl ca -batch -notext -config
C:\git\postgres-public-ci\build\testrun\ssl\005_cert_continuous_validation\data\tmp_test__8AE/ca.config
-name short_client_ca -startdate 0261014101030Z -enddate
20261014101545Z -in
C:\git\postgres-public-ci\build\testrun\ssl\005_cert_continuous_validation\data\tmp_test__8AE/short1.csr
-out C:\git\postgres-public-i\build\testrun\ssl\005_cert_continuous_validation\data\tmp_test__8AE/short1.crt
[..]
Write out database with 1 new entries
Database updated
[11:15:30.186](0.150s) # die: process ended prematurely at
C:/git/postgres-public-ci/src/test/perl/PostgreSQL/Test/BackgroundPsql.pm
line 163.
[11:15:30.187](0.000s) 1..3
[..]
# Stale postmaster.pid file for node "main": PID 7080 no longer exists
[11:15:41.442](11.255s) # Looks like your test exited with 25 just after 3.
Warning: unable to close filehandle GEN5 properly: Bad file
descriptor during global destruction.
Warning: unable to close filehandle GEN10 properly: Bad file
descriptor during global destruction.

so it's just all noise because pg log has:

2026-10-14 11:15:30.178 BST client backend[3588] [unknown] LOG:
connection received: host=DESKTOP-485UKSK port=52761
2026-10-14 11:15:30.186 BST client backend[3588] [unknown] FATAL:
connection requires a valid client certificate

so the whole setup just didn't work out? It looks like somehow the 005 even
the "test1" (short1) CA setup didn't even connect in the first place? (it was
not valid from start?)

2. Which brought me to this summary: I think the whole
005_cert_continuous_validation.pl test should be somehow refactored:
the other ssl tests simply rely on already generated/existing CA and mostly
nothing is generated in the tests runtime (see ../sslfiles.mk and somehow
use sslconfig.conf (that's ncluded from postgresql.conf). I'm not expert on
that, but test possibly could be much easier to follow/debug/understand if
it used generic parts of ssl testing infrastructure and just generate
CRL where necessary instead of repeating whole openssl config/CA setup
thing, which causes those portability issues above, but YMMV.

-J.

#8Daniel Gustafsson
daniel@yesql.se
In reply to: Jakub Wartak (#7)
Re: Continuous re-validation of session credentials

On 14 Oct 2026, at 13:28, Jakub Wartak <jakub.wartak@enterprisedb.com> wrote:

I think the whole 005_cert_continuous_validation.pl test should be somehow
refactored: the other ssl tests simply rely on already generated/existing CA
and mostly nothing is generated in the tests runtime (see ../sslfiles.mk and
somehow use sslconfig.conf (that's ncluded from postgresql.conf).

+1, any CA/cert/key/CRL used in testing should be defined in src/test/ssl/conf
and be added to sslfiles.mk such that they can be regenerated in a single pass.

--
Daniel Gustafsson