From 3caf616fa2d40fce925cb40d1e57375094167e58 Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <dgustafsson@postgresql.org>
Date: Tue, 3 Nov 2026 18:30:58 +0100
Subject: [PATCH v2] oauth: Recheck oauth_validator_libraries during
 authentication

The validator allowlist is only enforced while parsing pg_hba.conf.
If changing oauth_validator_libraries makes an existing oauth line
invalid, the HBA reload fails and the old lines stay in use, so a
removed validator keeps authenticating users.  In particular, when
setting the list to the empty string, the server doesn't refuse an
OAuth connection, as documented.

Backpatch down to v18 where OAuth was introduced.

Author: Zsolt Parragi <zsolt.parragi@percona.com>
Reviewed-by: Daniel Gustafsson <daniel@yesql.se>
Discussion: https://postgr.es/m/CAN4CZFNbWXwC=s4t9Xu1kitLsQvTe-EwpVtFCjixWCHBxRTraQ@mail.gmail.com
Backpatch-through: 18
---
 src/backend/libpq/auth-oauth.c                   |  8 ++++++++
 src/test/modules/oauth_validator/t/001_server.pl | 10 ++++++++++
 2 files changed, 18 insertions(+)

diff --git a/src/backend/libpq/auth-oauth.c b/src/backend/libpq/auth-oauth.c
index fb830065fba..8715e5086db 100644
--- a/src/backend/libpq/auth-oauth.c
+++ b/src/backend/libpq/auth-oauth.c
@@ -109,6 +109,7 @@ static void *
 oauth_init(Port *port, const char *selected_mech, const char *shadow_pass)
 {
 	struct oauth_ctx *ctx;
+	char	   *err_msg;
 
 	if (strcmp(selected_mech, OAUTHBEARER_NAME) != 0)
 		ereport(ERROR,
@@ -127,6 +128,13 @@ oauth_init(Port *port, const char *selected_mech, const char *shadow_pass)
 	ctx->issuer = port->hba->oauth_issuer;
 	ctx->scope = port->hba->oauth_scope;
 
+	/*
+	 * If a change to oauth_validator_libraries caused the last reload to
+	 * fail, we're still using the old HBA lines, and their validator may no
+	 * longer be permitted. Check again before loading it.
+	 */
+	check_oauth_validator(port->hba, COMMERROR, &err_msg);
+
 	load_validator_library(port->hba->oauth_validator);
 
 	return ctx;
diff --git a/src/test/modules/oauth_validator/t/001_server.pl b/src/test/modules/oauth_validator/t/001_server.pl
index 444de01ea5d..339cf7bd18c 100644
--- a/src/test/modules/oauth_validator/t/001_server.pl
+++ b/src/test/modules/oauth_validator/t/001_server.pl
@@ -143,6 +143,16 @@ $log_start = $node->wait_for_log(
 	$log_start);
 $bgconn->query_safe('SELECT 1');
 
+# The failed reload leaves the old HBA lines in place, but their validator is
+# no longer allowed so the connection shall be refused.
+$node->connect_fails(
+	"user=test dbname=postgres oauth_issuer=$issuer oauth_client_id=f02c6361-0635",
+	"validator removed from oauth_validator_libraries is not used",
+	expected_stderr => qr/could not fetch OpenID discovery document/,
+	log_like => [
+		qr/parameter "oauth_validator_libraries" must be set for authentication method "oauth"/
+	]);
+
 $node->append_conf('postgresql.conf',
 	"oauth_validator_libraries = 'validator'");
 $node->reload;
-- 
2.39.3 (Apple Git-146)

