public inbox for [email protected]  
help / color / mirror / Atom feed
From: Jacob Champion <[email protected]>
To: PostgreSQL Hackers <[email protected]>
Cc: Chao Li <[email protected]>
Cc: Zsolt Parragi <[email protected]>
Subject: Re: [oauth] Stabilize the libpq-oauth ABI (and allow alternative implementations?)
Date: Tue, 24 Feb 2026 14:51:16 -0800
Message-ID: <CAOYmi+mEU_q9sr1PMmE-4rLwFN=OjyndDwFZvpsMU3RNJLrM9g@mail.gmail.com> (raw)
In-Reply-To: <CAOYmi+mwzS4xfgomL1Lte+W1hRk+zahhZLnRMDJ8nYxoHUWt_w@mail.gmail.com>
References: <CAOYmi+mrGg+n_X2MOLgeWcj3v_M00gR8uz_D7mM8z=dX1JYVbg@mail.gmail.com>
	<[email protected]>
	<CAOYmi+mwzS4xfgomL1Lte+W1hRk+zahhZLnRMDJ8nYxoHUWt_w@mail.gmail.com>

On Tue, Dec 16, 2025 at 9:40 AM Jacob Champion
<[email protected]> wrote:
> Open questions remain:
> 1) 0004: Any objections to putting PQExpBuffer into libpq-fe.h?

Tom sounded lukewarm to this on the Discord, so I looked into
replacing the new usage with a simple char*.

That actually exposed a bug: appending error data during cleanup
doesn't help us at all, because we've already stopped using the error
buffer. In fact my whole idea of adding things to conn->errorMessage
during a teardown operation has been nearly useless from the
beginning. Elsewhere in libpq, we handle cases like these (which
should ideally just not happen) by printing warnings to stderr, so
v3-0001 does that instead.

Besides exposing a bug, switching to char* means anyone who's not
programming in C and already has code that handles pointer ownership
across the boundary can continue to make use of that, instead of
adapting to a completely new API for this one particular use case. We
already have the cleanup-callback requirement for the token anyway;
it's fine.

> 2) 0004: Thoughts on the v2 inheritance struct style as opposed to
> relying on implementations to double-check the struct length?

Still feels half-dozen or the other to me, so I'm planning to move
ahead with the inheritance model. I'll look into
VALGRIND_MAKE_MEM_NOACCESS (and/or other ways to catch people
scribbling where they shouldn't) for v4.

> 3) 0005: Should I add the thread lock to an init() API, or expose a
> new PQgetThreadLock() that other code can use?

v3-0002 implements PQgetThreadLock(). The conversation with Nico
Williams at [1] cemented this for me; it's entirely possible that
implementations will need the lock at other times besides
initialization, say if they're mixing OAuth with Kerberos. Adding a
way to retrieve it doesn't actually expose new functionality --
applications could always get at our internal implementation by
calling PQregisterThreadLock(NULL) -- but libraries can't use that API
safely.

Also, clients can probably make use of some of the newer ways of doing
this kind of initialization (pthread_once, etc.) that weren't in wide
use back when the init-function design showed up. We may not ever
actually need a separate init function, and if I'm wrong we can always
add one.

I think I'll put this in its own top-level thread for comment.

>    (In other words, a plugin architecture causes the compile-time
>    and run-time dependency arrows to point in opposite directions, so
>    plugins won't be able to rely on the LIBPQ_HAS_* macros to determine
>    what APIs are available to them.)
>
>    (TODO: Are there implications for our use of RTLD_NOW at dlopen() time?

To answer my own question, yes: any future libpq-oauth plugin that
needs PG20+ APIs will have to lazy-load them (weak symbol
declarations, etc.) or else accept that long-running applications may
fail OAuth connections until they restart.

A more general plugin system would need to solve this. For example, we
could load RTLD_LAZY, check for a minimum libpq version declared by
the plugin, and then either upgrade the bindings with RTLD_NOW, or
dlclose() and bail. But I don't think I need to be solving a
nonexistent problem now.

--Jacob

[1] https://postgr.es/m/aSSp03wmNMngi/Oe%40ubby


Attachments:

  [application/x-patch] v3-0001-oauth-Report-cleanup-errors-as-warnings-on-stderr.patch (2.2K, 2-v3-0001-oauth-Report-cleanup-errors-as-warnings-on-stderr.patch)
  download | inline diff:
From 0bc540fbb7e46c7e2988aaec468e6682f3349644 Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email protected]>
Date: Fri, 30 Jan 2026 16:41:26 -0800
Subject: [PATCH v3 1/6] oauth: Report cleanup errors as warnings on stderr

Using conn->errorMessage for these "shouldn't-happen" cases will only
work if the connection itself fails. Our SSL and password callbacks
print WARNINGs when they find themselves in similar situations, so
follow their lead.
---
 src/interfaces/libpq-oauth/oauth-curl.c | 18 ++++++++----------
 1 file changed, 8 insertions(+), 10 deletions(-)

diff --git a/src/interfaces/libpq-oauth/oauth-curl.c b/src/interfaces/libpq-oauth/oauth-curl.c
index 691e7ec1d9f..19024f6aaa7 100644
--- a/src/interfaces/libpq-oauth/oauth-curl.c
+++ b/src/interfaces/libpq-oauth/oauth-curl.c
@@ -293,10 +293,8 @@ free_async_ctx(PGconn *conn, struct async_ctx *actx)
 	 * no bugs above. But if we do hit them, surfacing those errors somehow
 	 * might be the only way to have a chance to debug them.
 	 *
-	 * TODO: At some point it'd be nice to have a standard way to warn about
-	 * teardown failures. Appending to the connection's error message only
-	 * helps if the bug caused a connection failure; otherwise it'll be
-	 * buried...
+	 * Print them as warnings to stderr, following the example of similar
+	 * situations in fe-secure-openssl.c and fe-connect.c.
 	 */
 
 	if (actx->curlm && actx->curl)
@@ -304,9 +302,9 @@ free_async_ctx(PGconn *conn, struct async_ctx *actx)
 		CURLMcode	err = curl_multi_remove_handle(actx->curlm, actx->curl);
 
 		if (err)
-			libpq_append_conn_error(conn,
-									"libcurl easy handle removal failed: %s",
-									curl_multi_strerror(err));
+			fprintf(stderr,
+					libpq_gettext("WARNING: libcurl easy handle removal failed: %s\n"),
+					curl_multi_strerror(err));
 	}
 
 	if (actx->curl)
@@ -324,9 +322,9 @@ free_async_ctx(PGconn *conn, struct async_ctx *actx)
 		CURLMcode	err = curl_multi_cleanup(actx->curlm);
 
 		if (err)
-			libpq_append_conn_error(conn,
-									"libcurl multi handle cleanup failed: %s",
-									curl_multi_strerror(err));
+			fprintf(stderr,
+					libpq_gettext("WARNING: libcurl multi handle cleanup failed: %s\n"),
+					curl_multi_strerror(err));
 	}
 
 	free_provider(&actx->provider);
-- 
2.34.1



  [application/x-patch] v3-0002-libpq-Add-PQgetThreadLock-to-mirror-PQregisterThr.patch (3.0K, 3-v3-0002-libpq-Add-PQgetThreadLock-to-mirror-PQregisterThr.patch)
  download | inline diff:
From 074645e5b414e2f095b5703e5ce2a45006c13d81 Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email protected]>
Date: Thu, 19 Feb 2026 12:39:16 -0800
Subject: [PATCH v3 2/6] libpq: Add PQgetThreadLock() to mirror
 PQregisterThreadLock()

Allow libpq clients to retrieve the current pg_g_threadlock pointer with
PQgetThreadLock(). Single-threaded applications could already do this in
a convoluted way:

    pgthreadlock_t tlock;

    tlock = PQregisterThreadLock(NULL);
    PQregisterThreadLock(tlock);    /* re-register the callback */

    /* use tlock */

But a generic library can't do that without potentially breaking
concurrent libpq connections.

The motivation for doing this now is the libpq-oauth plugin, which
currently relies on direct injection of pg_g_threadlock, and should
ideally not.
---
 src/interfaces/libpq/exports.txt  |  1 +
 src/interfaces/libpq/libpq-fe.h   | 10 ++++++++--
 src/interfaces/libpq/fe-connect.c |  7 +++++++
 3 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/src/interfaces/libpq/exports.txt b/src/interfaces/libpq/exports.txt
index dbbae642d76..1e3d5bd5867 100644
--- a/src/interfaces/libpq/exports.txt
+++ b/src/interfaces/libpq/exports.txt
@@ -210,3 +210,4 @@ PQgetAuthDataHook         207
 PQdefaultAuthDataHook     208
 PQfullProtocolVersion     209
 appendPQExpBufferVA       210
+PQgetThreadLock           211
diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h
index 905f2f33ab8..29b16efbb1d 100644
--- a/src/interfaces/libpq/libpq-fe.h
+++ b/src/interfaces/libpq/libpq-fe.h
@@ -63,6 +63,10 @@ extern "C"
 /* Indicates presence of the PQAUTHDATA_PROMPT_OAUTH_DEVICE authdata hook */
 #define LIBPQ_HAS_PROMPT_OAUTH_DEVICE 1
 
+/* Features added in PostgreSQL v19: */
+/* Indicates presence of PQgetThreadLock */
+#define LIBPQ_HAS_GET_THREAD_LOCK
+
 /*
  * Option flags for PQcopyResult
  */
@@ -462,12 +466,14 @@ extern PQnoticeProcessor PQsetNoticeProcessor(PGconn *conn,
  *	   Used to set callback that prevents concurrent access to
  *	   non-thread safe functions that libpq needs.
  *	   The default implementation uses a libpq internal mutex.
- *	   Only required for multithreaded apps that use kerberos
- *	   both within their app and for postgresql connections.
+ *	   Only required for multithreaded apps that use Kerberos or
+ *	   older (non-threadsafe) versions of Curl both within their
+ *	   app and for postgresql connections.
  */
 typedef void (*pgthreadlock_t) (int acquire);
 
 extern pgthreadlock_t PQregisterThreadLock(pgthreadlock_t newhandler);
+extern pgthreadlock_t PQgetThreadLock(void);
 
 /* === in fe-trace.c === */
 extern void PQtrace(PGconn *conn, FILE *debug_port);
diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index a0d2f749811..0c5f0d47b20 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -8381,3 +8381,10 @@ PQregisterThreadLock(pgthreadlock_t newhandler)
 
 	return prev;
 }
+
+pgthreadlock_t
+PQgetThreadLock(void)
+{
+	Assert(pg_g_threadlock);
+	return pg_g_threadlock;
+}
-- 
2.34.1



  [application/x-patch] v3-0003-libpq-Introduce-PQAUTHDATA_OAUTH_BEARER_TOKEN_V2.patch (24.5K, 4-v3-0003-libpq-Introduce-PQAUTHDATA_OAUTH_BEARER_TOKEN_V2.patch)
  download | inline diff:
From b431ee7a1e006d84cdc43ea3b81676f101f635d1 Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email protected]>
Date: Mon, 1 Dec 2025 15:07:26 -0800
Subject: [PATCH v3 3/6] libpq: Introduce PQAUTHDATA_OAUTH_BEARER_TOKEN_V2

For the libpq-oauth module to eventually make use of the
PGoauthBearerRequest API, it needs some additional functionality: the
derived Issuer ID for the authorization server needs to be provided by
libpq, and error messages need to be built without relying on PGconn
internals. These features seem useful for application hooks, too, so
that they don't each have to reinvent the wheel.

The original plan was for additions to PGoauthBearerRequest to be made
without a version bump to the PGauthData type, and then applications
would simply check a LIBPQ_HAS_* macro at compile time to decide whether
they could use the new features. That theoretically works for
applications linked against libpq, since it's not safe to downgrade
libpq from the version you've compiled against.

That strategy won't work for plugins, though, due to a complication
first noticed during the libpq-oauth module split: it's normal for a
plugin on disk to be *newer* than the libpq that's loading it, because
you might have upgraded your installation while an application was
running. (In other words, a plugin architecture causes the compile-time
and run-time dependency arrows to point in opposite directions, so
plugins won't be able to rely on the LIBPQ_HAS_* macros to determine
what APIs are available to them.)

Instead, add a new struct which extends the "v1" PGoauthBearerRequest.
When an application hook receives PQAUTHDATA_OAUTH_BEARER_TOKEN_V2, it
may safely downcast the request pointer it receives in its callbacks to
make use of the new functionality. libpq will first try the new version,
then fall back to the old before giving up.

Reviewed-by: Chao Li <[email protected]>
Reviewed-by: Zsolt Parragi <[email protected]>
Discussion: https://postgr.es/m/CAOYmi%2BmrGg%2Bn_X2MOLgeWcj3v_M00gR8uz_D7mM8z%3DdX1JYVbg%40mail.gmail.com
---
 doc/src/sgml/libpq.sgml                       | 83 ++++++++++++++++
 src/tools/pgindent/typedefs.list              |  1 +
 src/interfaces/libpq/libpq-fe.h               | 31 +++++-
 src/interfaces/libpq/fe-auth-oauth.c          | 87 +++++++++++------
 .../oauth_validator/oauth_hook_client.c       | 97 ++++++++++++++++++-
 .../modules/oauth_validator/t/002_client.pl   | 38 +++++++-
 6 files changed, 301 insertions(+), 36 deletions(-)

diff --git a/doc/src/sgml/libpq.sgml b/doc/src/sgml/libpq.sgml
index 21e1ba34a4e..4bbc51e7095 100644
--- a/doc/src/sgml/libpq.sgml
+++ b/doc/src/sgml/libpq.sgml
@@ -10345,6 +10345,7 @@ PQauthDataHook_type PQgetAuthDataHook(void);
         <indexterm><primary>PQAUTHDATA_PROMPT_OAUTH_DEVICE</primary></indexterm>
        </term>
        <listitem>
+        <para><emphasis>Available in PostgreSQL 18 and later.</emphasis></para>
         <para>
          Replaces the default user prompt during the builtin device
          authorization client flow. <replaceable>data</replaceable> points to
@@ -10397,6 +10398,7 @@ typedef struct _PGpromptOAuthDevice
         <indexterm><primary>PQAUTHDATA_OAUTH_BEARER_TOKEN</primary></indexterm>
        </term>
        <listitem>
+        <para><emphasis>Available in PostgreSQL 18 and later.</emphasis></para>
         <para>
          Adds a custom implementation of a flow, replacing the builtin flow if
          it is <link linkend="configure-option-with-libcurl">installed</link>.
@@ -10404,6 +10406,13 @@ typedef struct _PGpromptOAuthDevice
          user/issuer/scope combination, if one is available without blocking, or
          else set up an asynchronous callback to retrieve one.
         </para>
+        <note>
+         <para>
+          For <productname>PostgreSQL</productname> releases 19 and later,
+          applications should prefer
+          <link linkend="libpq-oauth-authdata-oauth-bearer-token-v2"><literal>PQAUTHDATA_OAUTH_BEARER_TOKEN_V2</literal></link>.
+         </para>
+        </note>
         <para>
          <replaceable>data</replaceable> points to an instance
          of <symbol>PGoauthBearerRequest</symbol>, which should be filled in
@@ -10499,6 +10508,80 @@ typedef struct PGoauthBearerRequest
         </para>
        </listitem>
       </varlistentry>
+
+      <varlistentry id="libpq-oauth-authdata-oauth-bearer-token-v2">
+       <term>
+        <symbol>PQAUTHDATA_OAUTH_BEARER_TOKEN_V2</symbol>
+        <indexterm>
+         <primary>PQAUTHDATA_OAUTH_BEARER_TOKEN_V2</primary>
+         <secondary>PQAUTHDATA_OAUTH_BEARER_TOKEN</secondary>
+        </indexterm>
+       </term>
+       <listitem>
+        <para><emphasis>Available in PostgreSQL 19 and later.</emphasis></para>
+        <para>
+         Provides all the functionality of
+         <link linkend="libpq-oauth-authdata-oauth-bearer-token"><literal>PQAUTHDATA_OAUTH_BEARER_TOKEN</literal></link>,
+         and adds the ability to set custom error messages and inspect the
+         OAuth issuer ID that the client expects to use.
+        </para>
+        <para>
+         <replaceable>data</replaceable> points to an instance
+         of <symbol>PGoauthBearerRequestV2</symbol>, which should be filled in
+         by the implementation:
+<synopsis>
+typedef struct
+{
+    PGoauthBearerRequest v1;    /* see the PGoauthBearerRequest struct, above */
+
+    /* Hook inputs (constant across all calls) */
+    const char *issuer;            /* the issuer identifier (RFC 9207) in use */
+
+    /* Hook outputs */
+    const char *error;             /* hook-defined error message */
+} PGoauthBearerRequestV2;
+</synopsis>
+        </para>
+        <para>
+         When a <literal>PQAUTHDATA_OAUTH_BEARER_TOKEN_V2</literal> hook is in
+         use, <application>libpq</application> additionally guarantees that the
+         <literal>request</literal> pointer that is provided to the
+         <replaceable>v1.async</replaceable> and <replaceable>v1.cleanup</replaceable>
+         callbacks may be safely cast to <literal>(PGoauthBearerRequestV2&nbsp;*)</literal>.
+         Implementations must otherwise follow the v1 API, as described above,
+         using the <replaceable>v1</replaceable> struct member.
+        </para>
+        <warning>
+         <para>
+          Casting to <literal>(PGoauthBearerRequestV2&nbsp;*)</literal> is
+          <emphasis>only</emphasis> safe when the hook type is
+          <literal>PQAUTHDATA_OAUTH_BEARER_TOKEN_V2</literal>. Applications may
+          crash or misbehave if a hook attempts to use v2 features with the v1
+          hook type.
+         </para>
+        </warning>
+        <para>
+         In addition to the functionality of the version 1 API, the v2 struct
+         provides an additional input and output for the hook:
+        </para>
+        <para>
+         <replaceable>issuer</replaceable> contains the issuer identifier, as
+         defined in <ulink url="https://datatracker.ietf.org/doc/html/rfc9207">RFC 9207</ulink>,
+         that is in use for the current connection. This identifier is
+         determined by <xref linkend="libpq-connect-oauth-issuer"/>.
+         To avoid mix-up attacks, custom flows should ensure that any discovery
+         metadata provided by the authorization server matches this issuer ID.
+        </para>
+        <para>
+         <replaceable>error</replaceable> may be set to point to a custom
+         error message when a flow fails. The message will be included as part
+         of <link linkend="libpq-PQerrorMessage"><literal>PQerrorMessage()</literal></link>.
+         Hooks must free any error message allocations during the
+         <replaceable>v1.cleanup</replaceable> callback.
+        </para>
+       </listitem>
+      </varlistentry>
+
      </variablelist>
     </para>
    </sect3>
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 241945734ec..53a183a14f0 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -1925,6 +1925,7 @@ PGdataValue
 PGlobjfuncs
 PGnotify
 PGoauthBearerRequest
+PGoauthBearerRequestV2
 PGpipelineStatus
 PGpromptOAuthDevice
 PGresAttDesc
diff --git a/src/interfaces/libpq/libpq-fe.h b/src/interfaces/libpq/libpq-fe.h
index 29b16efbb1d..1a61206bdc5 100644
--- a/src/interfaces/libpq/libpq-fe.h
+++ b/src/interfaces/libpq/libpq-fe.h
@@ -66,6 +66,8 @@ extern "C"
 /* Features added in PostgreSQL v19: */
 /* Indicates presence of PQgetThreadLock */
 #define LIBPQ_HAS_GET_THREAD_LOCK
+/* Indicates presence of the PQAUTHDATA_OAUTH_BEARER_TOKEN_V2 authdata hook */
+#define LIBPQ_HAS_OAUTH_BEARER_TOKEN_V2 1
 
 /*
  * Option flags for PQcopyResult
@@ -197,7 +199,9 @@ typedef enum
 {
 	PQAUTHDATA_PROMPT_OAUTH_DEVICE, /* user must visit a device-authorization
 									 * URL */
-	PQAUTHDATA_OAUTH_BEARER_TOKEN,	/* server requests an OAuth Bearer token */
+	PQAUTHDATA_OAUTH_BEARER_TOKEN,	/* server requests an OAuth Bearer token
+									 * (v2 is preferred; see below) */
+	PQAUTHDATA_OAUTH_BEARER_TOKEN_V2,	/* newest API for OAuth Bearer tokens */
 } PGauthData;
 
 /* PGconn encapsulates a connection to the backend.
@@ -735,6 +739,7 @@ extern int	PQenv2encoding(void);
 
 /* === in fe-auth.c === */
 
+/* Authdata for PQAUTHDATA_PROMPT_OAUTH_DEVICE */
 typedef struct _PGpromptOAuthDevice
 {
 	const char *verification_uri;	/* verification URI to visit */
@@ -755,6 +760,7 @@ typedef struct _PGpromptOAuthDevice
 #define PQ_SOCKTYPE int
 #endif
 
+/* Authdata for PQAUTHDATA_OAUTH_BEARER_TOKEN */
 typedef struct PGoauthBearerRequest
 {
 	/* Hook inputs (constant across all calls) */
@@ -788,7 +794,8 @@ typedef struct PGoauthBearerRequest
 
 	/*
 	 * Callback to clean up custom allocations. A hook implementation may use
-	 * this to free request->token and any resources in request->user.
+	 * this to free request->token and any resources in request->user. V2
+	 * implementations should additionally free request->error, if set.
 	 *
 	 * This is technically optional, but highly recommended, because there is
 	 * no other indication as to when it is safe to free the token.
@@ -813,6 +820,26 @@ typedef struct PGoauthBearerRequest
 
 #undef PQ_SOCKTYPE
 
+/* Authdata for PQAUTHDATA_OAUTH_BEARER_TOKEN_V2 */
+typedef struct
+{
+	PGoauthBearerRequest v1;	/* see the PGoauthBearerRequest struct, above */
+
+	/* Hook inputs (constant across all calls) */
+	const char *issuer;			/* the issuer identifier (RFC 9207) in use, as
+								 * derived from the connection's oauth_issuer */
+
+	/* Hook outputs */
+
+	/*
+	 * Hook-defined error message which will be included in the connection's
+	 * PQerrorMessage() output when the flow fails. libpq does not take
+	 * ownership of this pointer; any allocations should be freed during the
+	 * cleanup callback.
+	 */
+	const char *error;
+} PGoauthBearerRequestV2;
+
 extern char *PQencryptPassword(const char *passwd, const char *user);
 extern char *PQencryptPasswordConn(PGconn *conn, const char *passwd, const char *user, const char *algorithm);
 extern PGresult *PQchangePassword(PGconn *conn, const char *user, const char *passwd);
diff --git a/src/interfaces/libpq/fe-auth-oauth.c b/src/interfaces/libpq/fe-auth-oauth.c
index 67879d64b39..b64d05a13e3 100644
--- a/src/interfaces/libpq/fe-auth-oauth.c
+++ b/src/interfaces/libpq/fe-auth-oauth.c
@@ -675,6 +675,25 @@ cleanup:
 	return success;
 }
 
+/*
+ * Helper for handling flow failures. If anything was put into request->error,
+ * it's added to conn->errorMessage here.
+ */
+static void
+report_user_flow_error(PGconn *conn, const PGoauthBearerRequestV2 *request)
+{
+	appendPQExpBufferStr(&conn->errorMessage,
+						 libpq_gettext("user-defined OAuth flow failed"));
+
+	if (request->error)
+	{
+		appendPQExpBufferStr(&conn->errorMessage, ": ");
+		appendPQExpBufferStr(&conn->errorMessage, request->error);
+	}
+
+	appendPQExpBufferChar(&conn->errorMessage, '\n');
+}
+
 /*
  * Callback implementation of conn->async_auth() for a user-defined OAuth flow.
  * Delegates the retrieval of the token to the application's async callback.
@@ -687,20 +706,23 @@ static PostgresPollingStatusType
 run_user_oauth_flow(PGconn *conn)
 {
 	fe_oauth_state *state = conn->sasl_state;
-	PGoauthBearerRequest *request = state->async_ctx;
+	PGoauthBearerRequestV2 *request = state->async_ctx;
 	PostgresPollingStatusType status;
 
-	if (!request->async)
+	if (!request->v1.async)
 	{
 		libpq_append_conn_error(conn,
 								"user-defined OAuth flow provided neither a token nor an async callback");
 		return PGRES_POLLING_FAILED;
 	}
 
-	status = request->async(conn, request, &conn->altsock);
+	status = request->v1.async(conn,
+							   (PGoauthBearerRequest *) request,
+							   &conn->altsock);
+
 	if (status == PGRES_POLLING_FAILED)
 	{
-		libpq_append_conn_error(conn, "user-defined OAuth flow failed");
+		report_user_flow_error(conn, request);
 		return status;
 	}
 	else if (status == PGRES_POLLING_OK)
@@ -710,14 +732,14 @@ run_user_oauth_flow(PGconn *conn)
 		 * onto the original string, since it may not be safe for us to free()
 		 * it.)
 		 */
-		if (!request->token)
+		if (!request->v1.token)
 		{
 			libpq_append_conn_error(conn,
 									"user-defined OAuth flow did not provide a token");
 			return PGRES_POLLING_FAILED;
 		}
 
-		conn->oauth_token = strdup(request->token);
+		conn->oauth_token = strdup(request->v1.token);
 		if (!conn->oauth_token)
 		{
 			libpq_append_conn_error(conn, "out of memory");
@@ -739,19 +761,20 @@ run_user_oauth_flow(PGconn *conn)
 }
 
 /*
- * Cleanup callback for the async user flow. Delegates most of its job to the
- * user-provided cleanup implementation, then disconnects the altsock.
+ * Cleanup callback for the async user flow. Delegates most of its job to
+ * PGoauthBearerRequestV2.cleanup(), then disconnects the altsock and frees the
+ * request itself.
  */
 static void
 cleanup_user_oauth_flow(PGconn *conn)
 {
 	fe_oauth_state *state = conn->sasl_state;
-	PGoauthBearerRequest *request = state->async_ctx;
+	PGoauthBearerRequestV2 *request = state->async_ctx;
 
 	Assert(request);
 
-	if (request->cleanup)
-		request->cleanup(conn, request);
+	if (request->v1.cleanup)
+		request->v1.cleanup(conn, (PGoauthBearerRequest *) request);
 	conn->altsock = PGINVALID_SOCKET;
 
 	free(request);
@@ -975,8 +998,8 @@ use_builtin_flow(PGconn *conn, fe_oauth_state *state)
  * token for presentation to the server.
  *
  * If the application has registered a custom flow handler using
- * PQAUTHDATA_OAUTH_BEARER_TOKEN, it may either return a token immediately (e.g.
- * if it has one cached for immediate use), or set up for a series of
+ * PQAUTHDATA_OAUTH_BEARER_TOKEN[_V2], it may either return a token immediately
+ * (e.g. if it has one cached for immediate use), or set up for a series of
  * asynchronous callbacks which will be managed by run_user_oauth_flow().
  *
  * If the default handler is used instead, a Device Authorization flow is used
@@ -990,27 +1013,37 @@ static bool
 setup_token_request(PGconn *conn, fe_oauth_state *state)
 {
 	int			res;
-	PGoauthBearerRequest request = {
-		.openid_configuration = conn->oauth_discovery_uri,
-		.scope = conn->oauth_scope,
+	PGoauthBearerRequestV2 request = {
+		.v1 = {
+			.openid_configuration = conn->oauth_discovery_uri,
+			.scope = conn->oauth_scope,
+		},
+		.issuer = conn->oauth_issuer_id,
 	};
 
-	Assert(request.openid_configuration);
+	Assert(request.v1.openid_configuration);
+	Assert(request.issuer);
+
+	/*
+	 * The client may have overridden the OAuth flow. Try the v2 hook first,
+	 * then fall back to the v1 implementation.
+	 */
+	res = PQauthDataHook(PQAUTHDATA_OAUTH_BEARER_TOKEN_V2, conn, &request);
+	if (res == 0)
+		res = PQauthDataHook(PQAUTHDATA_OAUTH_BEARER_TOKEN, conn, &request);
 
-	/* The client may have overridden the OAuth flow. */
-	res = PQauthDataHook(PQAUTHDATA_OAUTH_BEARER_TOKEN, conn, &request);
 	if (res > 0)
 	{
-		PGoauthBearerRequest *request_copy;
+		PGoauthBearerRequestV2 *request_copy;
 
-		if (request.token)
+		if (request.v1.token)
 		{
 			/*
 			 * We already have a token, so copy it into the conn. (We can't
 			 * hold onto the original string, since it may not be safe for us
 			 * to free() it.)
 			 */
-			conn->oauth_token = strdup(request.token);
+			conn->oauth_token = strdup(request.v1.token);
 			if (!conn->oauth_token)
 			{
 				libpq_append_conn_error(conn, "out of memory");
@@ -1018,8 +1051,8 @@ setup_token_request(PGconn *conn, fe_oauth_state *state)
 			}
 
 			/* short-circuit */
-			if (request.cleanup)
-				request.cleanup(conn, &request);
+			if (request.v1.cleanup)
+				request.v1.cleanup(conn, (PGoauthBearerRequest *) &request);
 			return true;
 		}
 
@@ -1038,7 +1071,7 @@ setup_token_request(PGconn *conn, fe_oauth_state *state)
 	}
 	else if (res < 0)
 	{
-		libpq_append_conn_error(conn, "user-defined OAuth flow failed");
+		report_user_flow_error(conn, &request);
 		goto fail;
 	}
 	else if (!use_builtin_flow(conn, state))
@@ -1050,8 +1083,8 @@ setup_token_request(PGconn *conn, fe_oauth_state *state)
 	return true;
 
 fail:
-	if (request.cleanup)
-		request.cleanup(conn, &request);
+	if (request.v1.cleanup)
+		request.v1.cleanup(conn, (PGoauthBearerRequest *) &request);
 	return false;
 }
 
diff --git a/src/test/modules/oauth_validator/oauth_hook_client.c b/src/test/modules/oauth_validator/oauth_hook_client.c
index 60dd1dcdaa0..5bddc0f807a 100644
--- a/src/test/modules/oauth_validator/oauth_hook_client.c
+++ b/src/test/modules/oauth_validator/oauth_hook_client.c
@@ -20,6 +20,7 @@
 
 #include "getopt_long.h"
 #include "libpq-fe.h"
+#include "pqexpbuffer.h"
 
 static int	handle_auth_data(PGauthData type, PGconn *conn, void *data);
 static PostgresPollingStatusType async_cb(PGconn *conn,
@@ -36,13 +37,16 @@ usage(char *argv[])
 
 	printf("recognized flags:\n");
 	printf("  -h, --help              show this message\n");
+	printf("  -v VERSION              select the hook API version (default 2)\n");
 	printf("  --expected-scope SCOPE  fail if received scopes do not match SCOPE\n");
 	printf("  --expected-uri URI      fail if received configuration link does not match URI\n");
+	printf("  --expected-issuer ISS   fail if received issuer does not match ISS (v2 only)\n");
 	printf("  --misbehave=MODE        have the hook fail required postconditions\n"
 		   "                          (MODEs: no-hook, fail-async, no-token, no-socket)\n");
 	printf("  --no-hook               don't install OAuth hooks\n");
 	printf("  --hang-forever          don't ever return a token (combine with connect_timeout)\n");
 	printf("  --token TOKEN           use the provided TOKEN value\n");
+	printf("  --error ERRMSG          fail instead, with the given ERRMSG (v2 only)\n");
 	printf("  --stress-async          busy-loop on PQconnectPoll rather than polling\n");
 }
 
@@ -51,9 +55,12 @@ static bool no_hook = false;
 static bool hang_forever = false;
 static bool stress_async = false;
 static const char *expected_uri = NULL;
+static const char *expected_issuer = NULL;
 static const char *expected_scope = NULL;
 static const char *misbehave_mode = NULL;
 static char *token = NULL;
+static char *errmsg = NULL;
+static int	hook_version = PQAUTHDATA_OAUTH_BEARER_TOKEN_V2;
 
 int
 main(int argc, char *argv[])
@@ -68,6 +75,8 @@ main(int argc, char *argv[])
 		{"hang-forever", no_argument, NULL, 1004},
 		{"misbehave", required_argument, NULL, 1005},
 		{"stress-async", no_argument, NULL, 1006},
+		{"expected-issuer", required_argument, NULL, 1007},
+		{"error", required_argument, NULL, 1008},
 		{0}
 	};
 
@@ -75,7 +84,7 @@ main(int argc, char *argv[])
 	PGconn	   *conn;
 	int			c;
 
-	while ((c = getopt_long(argc, argv, "h", long_options, NULL)) != -1)
+	while ((c = getopt_long(argc, argv, "hv:", long_options, NULL)) != -1)
 	{
 		switch (c)
 		{
@@ -83,6 +92,18 @@ main(int argc, char *argv[])
 				usage(argv);
 				return 0;
 
+			case 'v':
+				if (strcmp(optarg, "1") == 0)
+					hook_version = PQAUTHDATA_OAUTH_BEARER_TOKEN;
+				else if (strcmp(optarg, "2") == 0)
+					hook_version = PQAUTHDATA_OAUTH_BEARER_TOKEN_V2;
+				else
+				{
+					usage(argv);
+					return 1;
+				}
+				break;
+
 			case 1000:			/* --expected-scope */
 				expected_scope = optarg;
 				break;
@@ -111,6 +132,14 @@ main(int argc, char *argv[])
 				stress_async = true;
 				break;
 
+			case 1007:			/* --expected-issuer */
+				expected_issuer = optarg;
+				break;
+
+			case 1008:			/* --error */
+				errmsg = optarg;
+				break;
+
 			default:
 				usage(argv);
 				return 1;
@@ -167,16 +196,24 @@ main(int argc, char *argv[])
 
 /*
  * PQauthDataHook implementation. Replaces the default client flow by handling
- * PQAUTHDATA_OAUTH_BEARER_TOKEN.
+ * PQAUTHDATA_OAUTH_BEARER_TOKEN[_V2].
  */
 static int
 handle_auth_data(PGauthData type, PGconn *conn, void *data)
 {
-	PGoauthBearerRequest *req = data;
+	PGoauthBearerRequest *req;
+	PGoauthBearerRequestV2 *req2 = NULL;
+
+	Assert(hook_version == PQAUTHDATA_OAUTH_BEARER_TOKEN ||
+		   hook_version == PQAUTHDATA_OAUTH_BEARER_TOKEN_V2);
 
-	if (no_hook || (type != PQAUTHDATA_OAUTH_BEARER_TOKEN))
+	if (no_hook || type != hook_version)
 		return 0;
 
+	req = data;
+	if (type == PQAUTHDATA_OAUTH_BEARER_TOKEN_V2)
+		req2 = data;
+
 	if (hang_forever)
 	{
 		/* Start asynchronous processing. */
@@ -221,6 +258,44 @@ handle_auth_data(PGauthData type, PGconn *conn, void *data)
 		}
 	}
 
+	if (expected_issuer)
+	{
+		if (!req2)
+		{
+			fprintf(stderr, "--expected-issuer cannot be combined with -v1\n");
+			return -1;
+		}
+
+		if (!req2->issuer)
+		{
+			fprintf(stderr, "expected issuer \"%s\", got NULL\n", expected_issuer);
+			return -1;
+		}
+
+		if (strcmp(expected_issuer, req2->issuer) != 0)
+		{
+			fprintf(stderr, "expected issuer \"%s\", got \"%s\"\n", expected_issuer, req2->issuer);
+			return -1;
+		}
+	}
+
+	if (errmsg)
+	{
+		if (token)
+		{
+			fprintf(stderr, "--error cannot be combined with --token\n");
+			return -1;
+		}
+		else if (!req2)
+		{
+			fprintf(stderr, "--error cannot be combined with -v1\n");
+			return -1;
+		}
+
+		req2->error = errmsg;
+		return -1;
+	}
+
 	req->token = token;
 	return 1;
 }
@@ -273,6 +348,20 @@ misbehave_cb(PGconn *conn, PGoauthBearerRequest *req, pgsocket *altsock)
 	if (strcmp(misbehave_mode, "fail-async") == 0)
 	{
 		/* Just fail "normally". */
+		if (errmsg)
+		{
+			PGoauthBearerRequestV2 *req2;
+
+			if (hook_version == PQAUTHDATA_OAUTH_BEARER_TOKEN)
+			{
+				fprintf(stderr, "--error cannot be combined with -v1\n");
+				exit(1);
+			}
+
+			req2 = (PGoauthBearerRequestV2 *) req;
+			req2->error = errmsg;
+		}
+
 		return PGRES_POLLING_FAILED;
 	}
 	else if (strcmp(misbehave_mode, "no-token") == 0)
diff --git a/src/test/modules/oauth_validator/t/002_client.pl b/src/test/modules/oauth_validator/t/002_client.pl
index d66cd0b4a5f..12af35b7d96 100644
--- a/src/test/modules/oauth_validator/t/002_client.pl
+++ b/src/test/modules/oauth_validator/t/002_client.pl
@@ -78,9 +78,9 @@ sub test
 	my $log_start = -s $node->logfile;
 	my ($stdout, $stderr) = run_command(\@cmd);
 
-	if (defined($params{expected_stdout}))
+	if ($params{expect_success})
 	{
-		like($stdout, $params{expected_stdout}, "$test_name: stdout matches");
+		like($stdout, qr/connection succeeded/, "$test_name: stdout matches");
 	}
 
 	if (defined($params{expected_stderr}))
@@ -110,11 +110,24 @@ test(
 	flags => [
 		"--token", "my-token",
 		"--expected-uri", "$issuer/.well-known/openid-configuration",
+		"--expected-issuer", "$issuer",
 		"--expected-scope", $scope,
 	],
-	expected_stdout => qr/connection succeeded/,
+	expect_success => 1,
 	log_like => [qr/oauth_validator: token="my-token", role="$user"/]);
 
+# Make sure the v1 hook continues to work.
+test(
+	"v1 synchronous hook can provide a token",
+	flags => [
+		"-v1",
+		"--token" => "my-token-v1",
+		"--expected-uri" => "$issuer/.well-known/openid-configuration",
+		"--expected-scope" => $scope,
+	],
+	expect_success => 1,
+	log_like => [qr/oauth_validator: token="my-token-v1", role="$user"/]);
+
 if ($ENV{with_libcurl} ne 'yes')
 {
 	# libpq should help users out if no OAuth support is built in.
@@ -126,6 +139,15 @@ if ($ENV{with_libcurl} ne 'yes')
 	);
 }
 
+# v2 synchronous flows should be able to set custom error messages.
+test(
+	"basic synchronous hook can set error messages",
+	flags => [
+		"--error" => "a custom error message",
+	],
+	expected_stderr =>
+	  qr/user-defined OAuth flow failed: a custom error message/);
+
 # connect_timeout should work if the flow doesn't respond.
 $common_connstr = "$common_connstr connect_timeout=1";
 test(
@@ -165,4 +187,14 @@ foreach my $c (@cases)
 		expected_stderr => $c->{'expected_error'});
 }
 
+# v2 async flows should be able to set error messages, too.
+test(
+	"asynchronous hook can set error messages",
+	flags => [
+		"--misbehave" => "fail-async",
+		"--error" => "async error message",
+	],
+	expected_stderr =>
+	  qr/user-defined OAuth flow failed: async error message/);
+
 done_testing();
-- 
2.34.1



  [application/x-patch] v3-0004-libpq-oauth-Use-the-PGoauthBearerRequestV2-API.patch (43.8K, 5-v3-0004-libpq-oauth-Use-the-PGoauthBearerRequestV2-API.patch)
  download | inline diff:
From 59a5e8e27d67047bba2afeb151c64a357624d942 Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email protected]>
Date: Thu, 23 Oct 2025 12:24:20 -0700
Subject: [PATCH v3 4/6] libpq-oauth: Use the PGoauthBearerRequestV2 API

Switch the private libpq-oauth ABI to the public PGoauthBearerRequestV2
API. A huge amount of glue code can be removed as part of this, and several
code paths can be deduplicated. Additionally, the shared library no
longer needs to change its name for every major release; it's now just
"libpq-oauth.so".

Reviewed-by: Chao Li <[email protected]>
Reviewed-by: Zsolt Parragi <[email protected]>
Discussion: https://postgr.es/m/CAOYmi%2BmrGg%2Bn_X2MOLgeWcj3v_M00gR8uz_D7mM8z%3DdX1JYVbg%40mail.gmail.com
---
 src/interfaces/libpq-oauth/README        |  67 ++---
 src/interfaces/libpq-oauth/exports.txt   |   3 +-
 src/interfaces/libpq-oauth/meson.build   |   4 +-
 src/interfaces/libpq-oauth/Makefile      |   9 +-
 src/interfaces/libpq-oauth/oauth-curl.h  |   6 +-
 src/interfaces/libpq-oauth/oauth-utils.h |  43 +--
 src/interfaces/libpq/fe-auth-oauth.h     |   7 +-
 src/interfaces/libpq-oauth/oauth-curl.c  | 336 ++++++++++++++---------
 src/interfaces/libpq-oauth/oauth-utils.c |  77 +-----
 src/interfaces/libpq/fe-auth-oauth.c     | 198 +++++++------
 10 files changed, 333 insertions(+), 417 deletions(-)

diff --git a/src/interfaces/libpq-oauth/README b/src/interfaces/libpq-oauth/README
index 553962d644e..a27a8238d4b 100644
--- a/src/interfaces/libpq-oauth/README
+++ b/src/interfaces/libpq-oauth/README
@@ -10,48 +10,33 @@ results in a failed connection.
 
 = Load-Time ABI =
 
-This module ABI is an internal implementation detail, so it's subject to change
-across major releases; the name of the module (libpq-oauth-MAJOR) reflects this.
-The module exports the following symbols:
-
-- PostgresPollingStatusType pg_fe_run_oauth_flow(PGconn *conn);
-- void pg_fe_cleanup_oauth_flow(PGconn *conn);
-
-pg_fe_run_oauth_flow and pg_fe_cleanup_oauth_flow are implementations of
-conn->async_auth and conn->cleanup_async_auth, respectively.
-
-At the moment, pg_fe_run_oauth_flow() relies on libpq's pg_g_threadlock and
-libpq_gettext(), which must be injected by libpq using this initialization
-function before the flow is run:
-
-- void libpq_oauth_init(pgthreadlock_t threadlock,
-						libpq_gettext_func gettext_impl,
-						conn_errorMessage_func errmsg_impl,
-						conn_oauth_client_id_func clientid_impl,
-						conn_oauth_client_secret_func clientsecret_impl,
-						conn_oauth_discovery_uri_func discoveryuri_impl,
-						conn_oauth_issuer_id_func issuerid_impl,
-						conn_oauth_scope_func scope_impl,
-						conn_sasl_state_func saslstate_impl,
-						set_conn_altsock_func setaltsock_impl,
-						set_conn_oauth_token_func settoken_impl);
-
-It also relies on access to several members of the PGconn struct. Not only can
-these change positions across minor versions, but the offsets aren't necessarily
-stable within a single minor release (conn->errorMessage, for instance, can
-change offsets depending on configure-time options). Therefore the necessary
-accessors (named conn_*) and mutators (set_conn_*) are injected here. With this
-approach, we can safely search the standard dlopen() paths (e.g. RPATH,
-LD_LIBRARY_PATH, the SO cache) for an implementation module to use, even if that
-module wasn't compiled at the same time as libpq -- which becomes especially
-important during "live upgrade" situations where a running libpq application has
-the libpq-oauth module updated out from under it before it's first loaded from
-disk.
+As of v19, this module ABI is public and cannot change incompatibly without also
+changing the entry points. Both libpq and libpq-oauth must gracefully handle
+situations where the other library is of a different release version, past or
+future, since upgrades to the libraries may happen in either order.
+
+(Don't assume that package version dependencies from libpq-oauth to libpq will
+simplify the situation! Since libpq delay-loads libpq-oauth, we still have to
+handle cases where a long-running client application has a libpq that's older
+than a newly upgraded plugin.)
+
+The module exports the following symbol:
+
+- int pg_start_oauthbearer(PGconn *conn, PGoauthBearerRequestV2 *request);
+
+The module then behaves as if it had received a PQAUTHDATA_OAUTH_BEARER_TOKEN_V2
+request via the PQauthDataHook API, and it either fills in an existing token or
+populates the necessary callbacks for a token to be obtained asynchronously.
+(See the documentation for PGoauthBearerRequest.) The function returns zero on
+success and nonzero on failure.
+
+Additionally, libpq-oauth relies on libpq's libpq_gettext(), which must be
+injected by libpq using this initialization function before the flow is run:
+
+- void libpq_oauth_init(libpq_gettext_func gettext_impl);
 
 = Static Build =
 
 The static library libpq.a does not perform any dynamic loading. If the builtin
-flow is enabled, the application is expected to link against libpq-oauth.a
-directly to provide the necessary symbols. (libpq.a and libpq-oauth.a must be
-part of the same build. Unlike the dynamic module, there are no translation
-shims provided.)
+flow is enabled, the application is expected to link against libpq-oauth.a to
+provide the necessary symbol, or else implement pg_start_oauthbearer() itself.
diff --git a/src/interfaces/libpq-oauth/exports.txt b/src/interfaces/libpq-oauth/exports.txt
index 6891a83dbf9..7bc12b860d7 100644
--- a/src/interfaces/libpq-oauth/exports.txt
+++ b/src/interfaces/libpq-oauth/exports.txt
@@ -1,4 +1,3 @@
 # src/interfaces/libpq-oauth/exports.txt
 libpq_oauth_init          1
-pg_fe_run_oauth_flow      2
-pg_fe_cleanup_oauth_flow  3
+pg_start_oauthbearer      2
diff --git a/src/interfaces/libpq-oauth/meson.build b/src/interfaces/libpq-oauth/meson.build
index d8a0c04095a..59bce4903e5 100644
--- a/src/interfaces/libpq-oauth/meson.build
+++ b/src/interfaces/libpq-oauth/meson.build
@@ -35,9 +35,7 @@ libpq_oauth_st = static_library('libpq-oauth',
 
 # This is an internal module; we don't want an SONAME and therefore do not set
 # SO_MAJOR_VERSION.
-libpq_oauth_name = 'libpq-oauth-@0@'.format(pg_version_major)
-
-libpq_oauth_so = shared_module(libpq_oauth_name,
+libpq_oauth_so = shared_module('libpq-oauth',
   libpq_oauth_sources + libpq_oauth_so_sources,
   include_directories: [libpq_oauth_inc, postgres_inc],
   c_args: libpq_oauth_so_c_args,
diff --git a/src/interfaces/libpq-oauth/Makefile b/src/interfaces/libpq-oauth/Makefile
index a5f2d65fcad..e90482566b1 100644
--- a/src/interfaces/libpq-oauth/Makefile
+++ b/src/interfaces/libpq-oauth/Makefile
@@ -16,13 +16,10 @@ include $(top_builddir)/src/Makefile.global
 PGFILEDESC = "libpq-oauth - device authorization OAuth support"
 
 # This is an internal module; we don't want an SONAME and therefore do not set
-# SO_MAJOR_VERSION.
-NAME = pq-oauth-$(MAJORVERSION)
-
-# Force the name "libpq-oauth" for both the static and shared libraries. The
-# staticlib doesn't need version information in its name.
+# SO_MAJOR_VERSION. This requires an explicit override for the shared library
+# name.
+NAME = pq-oauth
 override shlib := lib$(NAME)$(DLSUFFIX)
-override stlib := libpq-oauth.a
 
 override CPPFLAGS := -I$(libpq_srcdir) -I$(top_builddir)/src/port $(CPPFLAGS) $(LIBCURL_CPPFLAGS)
 override CFLAGS += $(PTHREAD_CFLAGS)
diff --git a/src/interfaces/libpq-oauth/oauth-curl.h b/src/interfaces/libpq-oauth/oauth-curl.h
index 686e7b4df3f..1d4dd766217 100644
--- a/src/interfaces/libpq-oauth/oauth-curl.h
+++ b/src/interfaces/libpq-oauth/oauth-curl.h
@@ -17,8 +17,8 @@
 
 #include "libpq-fe.h"
 
-/* Exported async-auth callbacks. */
-extern PGDLLEXPORT PostgresPollingStatusType pg_fe_run_oauth_flow(PGconn *conn);
-extern PGDLLEXPORT void pg_fe_cleanup_oauth_flow(PGconn *conn);
+/* Exported flow callback. */
+extern PGDLLEXPORT int pg_start_oauthbearer(PGconn *conn,
+											PGoauthBearerRequestV2 *request);
 
 #endif							/* OAUTH_CURL_H */
diff --git a/src/interfaces/libpq-oauth/oauth-utils.h b/src/interfaces/libpq-oauth/oauth-utils.h
index 9f4d5b692d2..293e9936989 100644
--- a/src/interfaces/libpq-oauth/oauth-utils.h
+++ b/src/interfaces/libpq-oauth/oauth-utils.h
@@ -15,53 +15,13 @@
 #ifndef OAUTH_UTILS_H
 #define OAUTH_UTILS_H
 
-#include "fe-auth-oauth.h"
 #include "libpq-fe.h"
 #include "pqexpbuffer.h"
 
-/*
- * A bank of callbacks to safely access members of PGconn, which are all passed
- * to libpq_oauth_init() by libpq.
- *
- * Keep these aligned with the definitions in fe-auth-oauth.c as well as the
- * static declarations in oauth-curl.c.
- */
-#define DECLARE_GETTER(TYPE, MEMBER) \
-	typedef TYPE (*conn_ ## MEMBER ## _func) (PGconn *conn); \
-	extern conn_ ## MEMBER ## _func conn_ ## MEMBER;
-
-#define DECLARE_SETTER(TYPE, MEMBER) \
-	typedef void (*set_conn_ ## MEMBER ## _func) (PGconn *conn, TYPE val); \
-	extern set_conn_ ## MEMBER ## _func set_conn_ ## MEMBER;
-
-DECLARE_GETTER(PQExpBuffer, errorMessage);
-DECLARE_GETTER(char *, oauth_client_id);
-DECLARE_GETTER(char *, oauth_client_secret);
-DECLARE_GETTER(char *, oauth_discovery_uri);
-DECLARE_GETTER(char *, oauth_issuer_id);
-DECLARE_GETTER(char *, oauth_scope);
-DECLARE_GETTER(fe_oauth_state *, sasl_state);
-
-DECLARE_SETTER(pgsocket, altsock);
-DECLARE_SETTER(char *, oauth_token);
-
-#undef DECLARE_GETTER
-#undef DECLARE_SETTER
-
 typedef char *(*libpq_gettext_func) (const char *msgid);
 
 /* Initializes libpq-oauth. */
-extern PGDLLEXPORT void libpq_oauth_init(pgthreadlock_t threadlock,
-										 libpq_gettext_func gettext_impl,
-										 conn_errorMessage_func errmsg_impl,
-										 conn_oauth_client_id_func clientid_impl,
-										 conn_oauth_client_secret_func clientsecret_impl,
-										 conn_oauth_discovery_uri_func discoveryuri_impl,
-										 conn_oauth_issuer_id_func issuerid_impl,
-										 conn_oauth_scope_func scope_impl,
-										 conn_sasl_state_func saslstate_impl,
-										 set_conn_altsock_func setaltsock_impl,
-										 set_conn_oauth_token_func settoken_impl);
+extern PGDLLEXPORT void libpq_oauth_init(libpq_gettext_func gettext_impl);
 
 /*
  * Duplicated APIs, copied from libpq (primarily libpq-int.h, which we cannot
@@ -75,7 +35,6 @@ typedef enum
 	PG_BOOL_NO					/* No (false) */
 } PGTernaryBool;
 
-extern void libpq_append_conn_error(PGconn *conn, const char *fmt,...) pg_attribute_printf(2, 3);
 extern bool oauth_unsafe_debugging_enabled(void);
 extern int	pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending);
 extern void pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe);
diff --git a/src/interfaces/libpq/fe-auth-oauth.h b/src/interfaces/libpq/fe-auth-oauth.h
index 5c8a24b76fa..511284614f7 100644
--- a/src/interfaces/libpq/fe-auth-oauth.h
+++ b/src/interfaces/libpq/fe-auth-oauth.h
@@ -27,11 +27,6 @@ enum fe_oauth_step
 	FE_OAUTH_SERVER_ERROR,
 };
 
-/*
- * This struct is exported to the libpq-oauth module. If changes are needed
- * during backports to stable branches, please keep ABI compatibility (no
- * changes to existing members, add new members at the end, etc.).
- */
 typedef struct
 {
 	enum fe_oauth_step step;
@@ -39,12 +34,12 @@ typedef struct
 	PGconn	   *conn;
 	void	   *async_ctx;
 
+	bool		builtin;
 	void	   *builtin_flow;
 } fe_oauth_state;
 
 extern void pqClearOAuthToken(PGconn *conn);
 extern bool oauth_unsafe_debugging_enabled(void);
-extern bool use_builtin_flow(PGconn *conn, fe_oauth_state *state);
 
 /* Mechanisms in fe-auth-oauth.c */
 extern const pg_fe_sasl_mech pg_oauth_mech;
diff --git a/src/interfaces/libpq-oauth/oauth-curl.c b/src/interfaces/libpq-oauth/oauth-curl.c
index 19024f6aaa7..cebe0a24ad0 100644
--- a/src/interfaces/libpq-oauth/oauth-curl.c
+++ b/src/interfaces/libpq-oauth/oauth-curl.c
@@ -29,7 +29,6 @@
 #endif
 
 #include "common/jsonapi.h"
-#include "fe-auth-oauth.h"
 #include "mb/pg_wchar.h"
 #include "oauth-curl.h"
 
@@ -44,23 +43,10 @@
 
 #else							/* !USE_DYNAMIC_OAUTH */
 
-/*
- * Static builds may rely on PGconn offsets directly. Keep these aligned with
- * the bank of callbacks in oauth-utils.h.
- */
+/* Static builds may make use of libpq internals directly. */
+#include "fe-auth-oauth.h"
 #include "libpq-int.h"
 
-#define conn_errorMessage(CONN) (&CONN->errorMessage)
-#define conn_oauth_client_id(CONN) (CONN->oauth_client_id)
-#define conn_oauth_client_secret(CONN) (CONN->oauth_client_secret)
-#define conn_oauth_discovery_uri(CONN) (CONN->oauth_discovery_uri)
-#define conn_oauth_issuer_id(CONN) (CONN->oauth_issuer_id)
-#define conn_oauth_scope(CONN) (CONN->oauth_scope)
-#define conn_sasl_state(CONN) (CONN->sasl_state)
-
-#define set_conn_altsock(CONN, VAL) do { CONN->altsock = VAL; } while (0)
-#define set_conn_oauth_token(CONN, VAL) do { CONN->oauth_token = VAL; } while (0)
-
 #endif							/* USE_DYNAMIC_OAUTH */
 
 /* One final guardrail against accidental inclusion... */
@@ -227,6 +213,15 @@ enum OAuthStep
  */
 struct async_ctx
 {
+	/* relevant connection options cached from the PGconn */
+	char	   *client_id;		/* oauth_client_id */
+	char	   *client_secret;	/* oauth_client_secret (may be NULL) */
+
+	/* options cached from the PGoauthBearerRequest (we don't own these) */
+	const char *discovery_uri;
+	const char *issuer_id;
+	const char *scope;
+
 	enum OAuthStep step;		/* where are we in the flow? */
 
 	int			timerfd;		/* descriptor for signaling async timeouts */
@@ -286,7 +281,7 @@ struct async_ctx
  * Tears down the Curl handles and frees the async_ctx.
  */
 static void
-free_async_ctx(PGconn *conn, struct async_ctx *actx)
+free_async_ctx(PGoauthBearerRequestV2 *req, struct async_ctx *actx)
 {
 	/*
 	 * In general, none of the error cases below should ever happen if we have
@@ -339,29 +334,72 @@ free_async_ctx(PGconn *conn, struct async_ctx *actx)
 	if (actx->timerfd >= 0)
 		close(actx->timerfd);
 
+	free(actx->client_id);
+	free(actx->client_secret);
+
 	free(actx);
 }
 
 /*
- * Release resources used for the asynchronous exchange and disconnect the
- * altsock.
- *
- * This is called either at the end of a successful authentication, or during
- * pqDropConnection(), so we won't leak resources even if PQconnectPoll() never
- * calls us back.
+ * Release resources used for the asynchronous exchange.
  */
-void
-pg_fe_cleanup_oauth_flow(PGconn *conn)
+static void
+pg_fe_cleanup_oauth_flow(PGconn *conn, PGoauthBearerRequest *request)
 {
-	fe_oauth_state *state = conn_sasl_state(conn);
+	struct async_ctx *actx = request->user;
+
+	/* request->cleanup is only set after actx has been allocated. */
+	Assert(actx);
+
+	free_async_ctx((PGoauthBearerRequestV2 *) request, actx);
+	request->user = NULL;
+
+	/* libpq has made its own copy of the token; clear ours now. */
+	if (request->token)
+	{
+		explicit_bzero(request->token, strlen(request->token));
+		free(request->token);
+		request->token = NULL;
+	}
+}
+
+/*
+ * Builds an error message from actx and stores it in req->error. The allocation
+ * is backed by actx->work_data (which will be reset first).
+ */
+static void
+append_actx_error(PGoauthBearerRequestV2 *req, struct async_ctx *actx)
+{
+	PQExpBuffer errbuf = &actx->work_data;
+
+	resetPQExpBuffer(errbuf);
+
+	/*
+	 * Assemble the three parts of our error: context, body, and detail. See
+	 * also the documentation for struct async_ctx.
+	 */
+	if (actx->errctx)
+		appendPQExpBuffer(errbuf, "%s: ", actx->errctx);
+
+	if (PQExpBufferDataBroken(actx->errbuf))
+		appendPQExpBufferStr(errbuf, libpq_gettext("out of memory"));
+	else
+		appendPQExpBufferStr(errbuf, actx->errbuf.data);
 
-	if (state->async_ctx)
+	if (actx->curl_err[0])
 	{
-		free_async_ctx(conn, state->async_ctx);
-		state->async_ctx = NULL;
+		appendPQExpBuffer(errbuf, " (libcurl: %s)", actx->curl_err);
+
+		/* Sometimes libcurl adds a newline to the error buffer. :( */
+		if (errbuf->len >= 2 && errbuf->data[errbuf->len - 2] == '\n')
+		{
+			errbuf->data[errbuf->len - 2] = ')';
+			errbuf->data[errbuf->len - 1] = '\0';
+			errbuf->len--;
+		}
 	}
 
-	set_conn_altsock(conn, PGINVALID_SOCKET);
+	req->error = errbuf->data;
 }
 
 /*
@@ -2197,7 +2235,7 @@ static bool
 check_issuer(struct async_ctx *actx, PGconn *conn)
 {
 	const struct provider *provider = &actx->provider;
-	const char *oauth_issuer_id = conn_oauth_issuer_id(conn);
+	const char *oauth_issuer_id = actx->issuer_id;
 
 	Assert(oauth_issuer_id);	/* ensured by setup_oauth_parameters() */
 	Assert(provider->issuer);	/* ensured by parse_provider() */
@@ -2300,8 +2338,8 @@ check_for_device_flow(struct async_ctx *actx)
 static bool
 add_client_identification(struct async_ctx *actx, PQExpBuffer reqbody, PGconn *conn)
 {
-	const char *oauth_client_id = conn_oauth_client_id(conn);
-	const char *oauth_client_secret = conn_oauth_client_secret(conn);
+	const char *oauth_client_id = actx->client_id;
+	const char *oauth_client_secret = actx->client_secret;
 
 	bool		success = false;
 	char	   *username = NULL;
@@ -2384,11 +2422,10 @@ cleanup:
 static bool
 start_device_authz(struct async_ctx *actx, PGconn *conn)
 {
-	const char *oauth_scope = conn_oauth_scope(conn);
+	const char *oauth_scope = actx->scope;
 	const char *device_authz_uri = actx->provider.device_authorization_endpoint;
 	PQExpBuffer work_buffer = &actx->work_data;
 
-	Assert(conn_oauth_client_id(conn)); /* ensured by setup_oauth_parameters() */
 	Assert(device_authz_uri);	/* ensured by check_for_device_flow() */
 
 	/* Construct our request body. */
@@ -2476,7 +2513,6 @@ start_token_request(struct async_ctx *actx, PGconn *conn)
 	const char *device_code = actx->authz.device_code;
 	PQExpBuffer work_buffer = &actx->work_data;
 
-	Assert(conn_oauth_client_id(conn)); /* ensured by setup_oauth_parameters() */
 	Assert(token_uri);			/* ensured by parse_provider() */
 	Assert(device_code);		/* ensured by parse_device_authz() */
 
@@ -2655,7 +2691,7 @@ prompt_user(struct async_ctx *actx, PGconn *conn)
  * function will not try to reinitialize Curl on successive calls.
  */
 static bool
-initialize_curl(PGconn *conn)
+initialize_curl(PGoauthBearerRequestV2 *req)
 {
 	/*
 	 * Don't let the compiler play tricks with this variable. In the
@@ -2689,8 +2725,7 @@ initialize_curl(PGconn *conn)
 		goto done;
 	else if (init_successful == PG_BOOL_NO)
 	{
-		libpq_append_conn_error(conn,
-								"curl_global_init previously failed during OAuth setup");
+		req->error = libpq_gettext("curl_global_init previously failed during OAuth setup");
 		goto done;
 	}
 
@@ -2708,8 +2743,7 @@ initialize_curl(PGconn *conn)
 	 */
 	if (curl_global_init(CURL_GLOBAL_ALL & ~CURL_GLOBAL_WIN32) != CURLE_OK)
 	{
-		libpq_append_conn_error(conn,
-								"curl_global_init failed during OAuth setup");
+		req->error = libpq_gettext("curl_global_init failed during OAuth setup");
 		init_successful = PG_BOOL_NO;
 		goto done;
 	}
@@ -2730,11 +2764,11 @@ initialize_curl(PGconn *conn)
 		 * In a downgrade situation, the damage is already done. Curl global
 		 * state may be corrupted. Be noisy.
 		 */
-		libpq_append_conn_error(conn, "libcurl is no longer thread-safe\n"
-								"\tCurl initialization was reported thread-safe when libpq\n"
-								"\twas compiled, but the currently installed version of\n"
-								"\tlibcurl reports that it is not. Recompile libpq against\n"
-								"\tthe installed version of libcurl.");
+		req->error = libpq_gettext("libcurl is no longer thread-safe\n"
+								   "\tCurl initialization was reported thread-safe when libpq\n"
+								   "\twas compiled, but the currently installed version of\n"
+								   "\tlibcurl reports that it is not. Recompile libpq against\n"
+								   "\tthe installed version of libcurl.");
 		init_successful = PG_BOOL_NO;
 		goto done;
 	}
@@ -2764,54 +2798,16 @@ done:
  * provider.
  */
 static PostgresPollingStatusType
-pg_fe_run_oauth_flow_impl(PGconn *conn)
+pg_fe_run_oauth_flow_impl(PGconn *conn, PGoauthBearerRequestV2 *request,
+						  int *altsock)
 {
-	fe_oauth_state *state = conn_sasl_state(conn);
-	struct async_ctx *actx;
+	struct async_ctx *actx = request->v1.user;
 	char	   *oauth_token = NULL;
-	PQExpBuffer errbuf;
-
-	if (!initialize_curl(conn))
-		return PGRES_POLLING_FAILED;
-
-	if (!state->async_ctx)
-	{
-		/*
-		 * Create our asynchronous state, and hook it into the upper-level
-		 * OAuth state immediately, so any failures below won't leak the
-		 * context allocation.
-		 */
-		actx = calloc(1, sizeof(*actx));
-		if (!actx)
-		{
-			libpq_append_conn_error(conn, "out of memory");
-			return PGRES_POLLING_FAILED;
-		}
-
-		actx->mux = PGINVALID_SOCKET;
-		actx->timerfd = -1;
-
-		/* Should we enable unsafe features? */
-		actx->debugging = oauth_unsafe_debugging_enabled();
-
-		state->async_ctx = actx;
-
-		initPQExpBuffer(&actx->work_data);
-		initPQExpBuffer(&actx->errbuf);
-
-		if (!setup_multiplexer(actx))
-			goto error_return;
-
-		if (!setup_curl_handles(actx))
-			goto error_return;
-	}
-
-	actx = state->async_ctx;
 
 	do
 	{
 		/* By default, the multiplexer is the altsock. Reassign as desired. */
-		set_conn_altsock(conn, actx->mux);
+		*altsock = actx->mux;
 
 		switch (actx->step)
 		{
@@ -2876,7 +2872,7 @@ pg_fe_run_oauth_flow_impl(PGconn *conn)
 
 					if (!expired)
 					{
-						set_conn_altsock(conn, actx->timerfd);
+						*altsock = actx->timerfd;
 						return PGRES_POLLING_READING;
 					}
 
@@ -2893,7 +2889,7 @@ pg_fe_run_oauth_flow_impl(PGconn *conn)
 		{
 			case OAUTH_STEP_INIT:
 				actx->errctx = libpq_gettext("failed to fetch OpenID discovery document");
-				if (!start_discovery(actx, conn_oauth_discovery_uri(conn)))
+				if (!start_discovery(actx, actx->discovery_uri))
 					goto error_return;
 
 				actx->step = OAUTH_STEP_DISCOVERY;
@@ -2933,10 +2929,10 @@ pg_fe_run_oauth_flow_impl(PGconn *conn)
 					goto error_return;
 
 				/*
-				 * Hook any oauth_token into the PGconn immediately so that
-				 * the allocation isn't lost in case of an error.
+				 * Hook any oauth_token into the request struct immediately so
+				 * that the allocation isn't lost in case of an error.
 				 */
-				set_conn_oauth_token(conn, oauth_token);
+				request->v1.token = oauth_token;
 
 				if (!actx->user_prompted)
 				{
@@ -2965,7 +2961,7 @@ pg_fe_run_oauth_flow_impl(PGconn *conn)
 				 * the client wait directly on the timerfd rather than the
 				 * multiplexer.
 				 */
-				set_conn_altsock(conn, actx->timerfd);
+				*altsock = actx->timerfd;
 
 				actx->step = OAUTH_STEP_WAIT_INTERVAL;
 				actx->running = 1;
@@ -2991,48 +2987,21 @@ pg_fe_run_oauth_flow_impl(PGconn *conn)
 	return oauth_token ? PGRES_POLLING_OK : PGRES_POLLING_READING;
 
 error_return:
-	errbuf = conn_errorMessage(conn);
-
-	/*
-	 * Assemble the three parts of our error: context, body, and detail. See
-	 * also the documentation for struct async_ctx.
-	 */
-	if (actx->errctx)
-		appendPQExpBuffer(errbuf, "%s: ", actx->errctx);
-
-	if (PQExpBufferDataBroken(actx->errbuf))
-		appendPQExpBufferStr(errbuf, libpq_gettext("out of memory"));
-	else
-		appendPQExpBufferStr(errbuf, actx->errbuf.data);
-
-	if (actx->curl_err[0])
-	{
-		appendPQExpBuffer(errbuf, " (libcurl: %s)", actx->curl_err);
-
-		/* Sometimes libcurl adds a newline to the error buffer. :( */
-		if (errbuf->len >= 2 && errbuf->data[errbuf->len - 2] == '\n')
-		{
-			errbuf->data[errbuf->len - 2] = ')';
-			errbuf->data[errbuf->len - 1] = '\0';
-			errbuf->len--;
-		}
-	}
-
-	appendPQExpBufferChar(errbuf, '\n');
+	append_actx_error(request, actx);
 
 	return PGRES_POLLING_FAILED;
 }
 
 /*
- * The top-level entry point. This is a convenient place to put necessary
- * wrapper logic before handing off to the true implementation, above.
+ * The top-level entry point for the flow. This is a convenient place to put
+ * necessary wrapper logic before handing off to the true implementation, above.
  */
-PostgresPollingStatusType
-pg_fe_run_oauth_flow(PGconn *conn)
+static PostgresPollingStatusType
+pg_fe_run_oauth_flow(PGconn *conn, struct PGoauthBearerRequest *request,
+					 int *altsock)
 {
 	PostgresPollingStatusType result;
-	fe_oauth_state *state = conn_sasl_state(conn);
-	struct async_ctx *actx;
+	struct async_ctx *actx = request->user;
 #ifndef WIN32
 	sigset_t	osigset;
 	bool		sigpipe_pending;
@@ -3059,20 +3028,16 @@ pg_fe_run_oauth_flow(PGconn *conn)
 	masked = (pq_block_sigpipe(&osigset, &sigpipe_pending) == 0);
 #endif
 
-	result = pg_fe_run_oauth_flow_impl(conn);
+	result = pg_fe_run_oauth_flow_impl(conn,
+									   (PGoauthBearerRequestV2 *) request,
+									   altsock);
 
 	/*
 	 * To assist with finding bugs in comb_multiplexer() and
 	 * drain_timer_events(), when we're in debug mode, track the total number
 	 * of calls to this function and print that at the end of the flow.
-	 *
-	 * Be careful that state->async_ctx could be NULL if early initialization
-	 * fails during the first call.
 	 */
-	actx = state->async_ctx;
-	Assert(actx || result == PGRES_POLLING_FAILED);
-
-	if (actx && actx->debugging)
+	if (actx->debugging)
 	{
 		actx->dbg_num_calls++;
 		if (result == PGRES_POLLING_OK || result == PGRES_POLLING_FAILED)
@@ -3093,3 +3058,102 @@ pg_fe_run_oauth_flow(PGconn *conn)
 
 	return result;
 }
+
+/*
+ * Callback registration for OAUTHBEARER. libpq calls this once per OAuth
+ * connection.
+ */
+int
+pg_start_oauthbearer(PGconn *conn, PGoauthBearerRequestV2 *request)
+{
+	struct async_ctx *actx;
+
+	if (!initialize_curl(request))
+		return -1;
+
+	/*
+	 * Create our asynchronous state, and hook it into the upper-level OAuth
+	 * state immediately, so any failures below won't leak the context
+	 * allocation.
+	 */
+	actx = calloc(1, sizeof(*actx));
+	if (!actx)
+		goto oom;
+
+	actx->mux = PGINVALID_SOCKET;
+	actx->timerfd = -1;
+
+	/*
+	 * Now we have a valid (but still useless) actx, so we can fill in the
+	 * request object. From this point onward, failures will result in a call
+	 * to pg_fe_cleanup_oauth_flow(). Further cleanup logic belongs there.
+	 */
+	request->v1.async = pg_fe_run_oauth_flow;
+	request->v1.cleanup = pg_fe_cleanup_oauth_flow;
+	request->v1.user = actx;
+
+	/*
+	 * Now finish filling in the actx.
+	 */
+
+	/* Should we enable unsafe features? */
+	actx->debugging = oauth_unsafe_debugging_enabled();
+
+	initPQExpBuffer(&actx->work_data);
+	initPQExpBuffer(&actx->errbuf);
+
+	/* Pull relevant connection options. */
+	{
+		PQconninfoOption *conninfo = PQconninfo(conn);
+
+		if (!conninfo)
+			goto oom;
+
+		for (PQconninfoOption *opt = conninfo; opt->keyword; opt++)
+		{
+			if (!opt->val)
+				continue;		/* simplifies the strdup logic below */
+
+			if (strcmp(opt->keyword, "oauth_client_id") == 0)
+			{
+				actx->client_id = strdup(opt->val);
+				if (!actx->client_id)
+					goto oom;
+			}
+			else if (strcmp(opt->keyword, "oauth_client_secret") == 0)
+			{
+				actx->client_secret = strdup(opt->val);
+				if (!actx->client_secret)
+					goto oom;
+			}
+		}
+
+		PQconninfoFree(conninfo);
+	}
+
+	actx->discovery_uri = request->v1.openid_configuration;
+	actx->issuer_id = request->issuer;
+	actx->scope = request->v1.scope;
+
+	Assert(actx->client_id);	/* ensured by setup_oauth_parameters() */
+	Assert(actx->issuer_id);	/* ensured by setup_oauth_parameters() */
+	Assert(actx->discovery_uri);	/* ensured by oauth_exchange() */
+
+	if (!setup_multiplexer(actx))
+	{
+		append_actx_error(request, actx);
+		return -1;
+	}
+
+	if (!setup_curl_handles(actx))
+	{
+		append_actx_error(request, actx);
+		return -1;
+	}
+
+	return 0;
+
+oom:
+	request->error = libpq_gettext("out of memory");
+	return -1;
+}
diff --git a/src/interfaces/libpq-oauth/oauth-utils.c b/src/interfaces/libpq-oauth/oauth-utils.c
index 4ebe7d0948c..ccb0d9bf2c5 100644
--- a/src/interfaces/libpq-oauth/oauth-utils.c
+++ b/src/interfaces/libpq-oauth/oauth-utils.c
@@ -35,85 +35,18 @@
 pgthreadlock_t pg_g_threadlock;
 static libpq_gettext_func libpq_gettext_impl;
 
-conn_errorMessage_func conn_errorMessage;
-conn_oauth_client_id_func conn_oauth_client_id;
-conn_oauth_client_secret_func conn_oauth_client_secret;
-conn_oauth_discovery_uri_func conn_oauth_discovery_uri;
-conn_oauth_issuer_id_func conn_oauth_issuer_id;
-conn_oauth_scope_func conn_oauth_scope;
-conn_sasl_state_func conn_sasl_state;
-
-set_conn_altsock_func set_conn_altsock;
-set_conn_oauth_token_func set_conn_oauth_token;
-
 /*-
  * Initializes libpq-oauth by setting necessary callbacks.
  *
- * The current implementation relies on the following private implementation
- * details of libpq:
- *
- * - pg_g_threadlock: protects libcurl initialization if the underlying Curl
- *   installation is not threadsafe
- *
- * - libpq_gettext: translates error messages using libpq's message domain
- *
- * The implementation also needs access to several members of the PGconn struct,
- * which are not guaranteed to stay in place across minor versions. Accessors
- * (named conn_*) and mutators (named set_conn_*) are injected here.
+ * The current implementation relies on libpq_gettext to translate error
+ * messages using libpq's message domain, so libpq injects it here. We also use
+ * this chance to initialize our threadlock.
  */
 void
-libpq_oauth_init(pgthreadlock_t threadlock_impl,
-				 libpq_gettext_func gettext_impl,
-				 conn_errorMessage_func errmsg_impl,
-				 conn_oauth_client_id_func clientid_impl,
-				 conn_oauth_client_secret_func clientsecret_impl,
-				 conn_oauth_discovery_uri_func discoveryuri_impl,
-				 conn_oauth_issuer_id_func issuerid_impl,
-				 conn_oauth_scope_func scope_impl,
-				 conn_sasl_state_func saslstate_impl,
-				 set_conn_altsock_func setaltsock_impl,
-				 set_conn_oauth_token_func settoken_impl)
+libpq_oauth_init(libpq_gettext_func gettext_impl)
 {
-	pg_g_threadlock = threadlock_impl;
+	pg_g_threadlock = PQgetThreadLock();
 	libpq_gettext_impl = gettext_impl;
-	conn_errorMessage = errmsg_impl;
-	conn_oauth_client_id = clientid_impl;
-	conn_oauth_client_secret = clientsecret_impl;
-	conn_oauth_discovery_uri = discoveryuri_impl;
-	conn_oauth_issuer_id = issuerid_impl;
-	conn_oauth_scope = scope_impl;
-	conn_sasl_state = saslstate_impl;
-	set_conn_altsock = setaltsock_impl;
-	set_conn_oauth_token = settoken_impl;
-}
-
-/*
- * Append a formatted string to the error message buffer of the given
- * connection, after translating it.  This is a copy of libpq's internal API.
- */
-void
-libpq_append_conn_error(PGconn *conn, const char *fmt,...)
-{
-	int			save_errno = errno;
-	bool		done;
-	va_list		args;
-	PQExpBuffer errorMessage = conn_errorMessage(conn);
-
-	Assert(fmt[strlen(fmt) - 1] != '\n');
-
-	if (PQExpBufferBroken(errorMessage))
-		return;					/* already failed */
-
-	/* Loop in case we have to retry after enlarging the buffer. */
-	do
-	{
-		errno = save_errno;
-		va_start(args, fmt);
-		done = appendPQExpBufferVA(errorMessage, libpq_gettext(fmt), args);
-		va_end(args);
-	} while (!done);
-
-	appendPQExpBufferChar(errorMessage, '\n');
 }
 
 #ifdef ENABLE_NLS
diff --git a/src/interfaces/libpq/fe-auth-oauth.c b/src/interfaces/libpq/fe-auth-oauth.c
index b64d05a13e3..904f43e90ea 100644
--- a/src/interfaces/libpq/fe-auth-oauth.c
+++ b/src/interfaces/libpq/fe-auth-oauth.c
@@ -78,7 +78,7 @@ oauth_init(PGconn *conn, const char *password,
  * This handles only mechanism state tied to the connection lifetime; state
  * stored in state->async_ctx is freed up either immediately after the
  * authentication handshake succeeds, or before the mechanism is cleaned up on
- * failure. See pg_fe_cleanup_oauth_flow() and cleanup_user_oauth_flow().
+ * failure. See pg_fe_cleanup_oauth_flow() and cleanup_oauth_flow().
  */
 static void
 oauth_free(void *opaq)
@@ -680,30 +680,54 @@ cleanup:
  * it's added to conn->errorMessage here.
  */
 static void
-report_user_flow_error(PGconn *conn, const PGoauthBearerRequestV2 *request)
+report_flow_error(PGconn *conn, const PGoauthBearerRequestV2 *request)
 {
-	appendPQExpBufferStr(&conn->errorMessage,
-						 libpq_gettext("user-defined OAuth flow failed"));
+	fe_oauth_state *state = conn->sasl_state;
+	const char *errmsg = request->error;
+
+	/*
+	 * User-defined flows are called out explicitly so that the user knows who
+	 * to blame. Builtin flows don't need that extra message length; we expect
+	 * them to always fill in request->error on failure anyway.
+	 */
+	if (state->builtin)
+	{
+		if (!errmsg)
+		{
+			/*
+			 * Don't turn a bug here into a crash in production, but don't
+			 * bother translating either.
+			 */
+			Assert(false);
+			errmsg = "builtin flow failed but did not provide an error message";
+		}
 
-	if (request->error)
+		appendPQExpBufferStr(&conn->errorMessage, errmsg);
+	}
+	else
 	{
-		appendPQExpBufferStr(&conn->errorMessage, ": ");
-		appendPQExpBufferStr(&conn->errorMessage, request->error);
+		appendPQExpBufferStr(&conn->errorMessage,
+							 libpq_gettext("user-defined OAuth flow failed"));
+		if (errmsg)
+		{
+			appendPQExpBufferStr(&conn->errorMessage, ": ");
+			appendPQExpBufferStr(&conn->errorMessage, errmsg);
+		}
 	}
 
 	appendPQExpBufferChar(&conn->errorMessage, '\n');
 }
 
 /*
- * Callback implementation of conn->async_auth() for a user-defined OAuth flow.
- * Delegates the retrieval of the token to the application's async callback.
+ * Callback implementation of conn->async_auth() for OAuth flows. Delegates the
+ * retrieval of the token to the PGoauthBearerRequestV2.async() callback.
  *
- * This will be called multiple times as needed; the application is responsible
- * for setting an altsock to signal and returning the correct PGRES_POLLING_*
+ * This will be called multiple times as needed; the callback is responsible for
+ * setting an altsock to signal and returning the correct PGRES_POLLING_*
  * statuses for use by PQconnectPoll().
  */
 static PostgresPollingStatusType
-run_user_oauth_flow(PGconn *conn)
+run_oauth_flow(PGconn *conn)
 {
 	fe_oauth_state *state = conn->sasl_state;
 	PGoauthBearerRequestV2 *request = state->async_ctx;
@@ -711,6 +735,7 @@ run_user_oauth_flow(PGconn *conn)
 
 	if (!request->v1.async)
 	{
+		Assert(!state->builtin);	/* be very noisy if our code does this */
 		libpq_append_conn_error(conn,
 								"user-defined OAuth flow provided neither a token nor an async callback");
 		return PGRES_POLLING_FAILED;
@@ -722,7 +747,7 @@ run_user_oauth_flow(PGconn *conn)
 
 	if (status == PGRES_POLLING_FAILED)
 	{
-		report_user_flow_error(conn, request);
+		report_flow_error(conn, request);
 		return status;
 	}
 	else if (status == PGRES_POLLING_OK)
@@ -734,6 +759,7 @@ run_user_oauth_flow(PGconn *conn)
 		 */
 		if (!request->v1.token)
 		{
+			Assert(!state->builtin);
 			libpq_append_conn_error(conn,
 									"user-defined OAuth flow did not provide a token");
 			return PGRES_POLLING_FAILED;
@@ -752,6 +778,7 @@ run_user_oauth_flow(PGconn *conn)
 	/* The hook wants the client to poll the altsock. Make sure it set one. */
 	if (conn->altsock == PGINVALID_SOCKET)
 	{
+		Assert(!state->builtin);
 		libpq_append_conn_error(conn,
 								"user-defined OAuth flow did not provide a socket for polling");
 		return PGRES_POLLING_FAILED;
@@ -761,12 +788,16 @@ run_user_oauth_flow(PGconn *conn)
 }
 
 /*
- * Cleanup callback for the async user flow. Delegates most of its job to
+ * Cleanup callback for the async flow. Delegates most of its job to
  * PGoauthBearerRequestV2.cleanup(), then disconnects the altsock and frees the
  * request itself.
+ *
+ * This is called either at the end of a successful authentication, or during
+ * pqDropConnection(), so we won't leak resources even if PQconnectPoll() never
+ * calls us back.
  */
 static void
-cleanup_user_oauth_flow(PGconn *conn)
+cleanup_oauth_flow(PGconn *conn)
 {
 	fe_oauth_state *state = conn->sasl_state;
 	PGoauthBearerRequestV2 *request = state->async_ctx;
@@ -786,12 +817,16 @@ cleanup_user_oauth_flow(PGconn *conn)
  *
  * There are three potential implementations of use_builtin_flow:
  *
- * 1) If the OAuth client is disabled at configuration time, return false.
+ * 1) If the OAuth client is disabled at configuration time, return zero.
  *    Dependent clients must provide their own flow.
  * 2) If the OAuth client is enabled and USE_DYNAMIC_OAUTH is defined, dlopen()
  *    the libpq-oauth plugin and use its implementation.
  * 3) Otherwise, use flow callbacks that are statically linked into the
  *    executable.
+ *
+ * For caller convenience, the return value follows the convention of
+ * PQauthDataHook: zero means no implementation is provided, negative indicates
+ * failure, and positive indicates success.
  */
 
 #if !defined(USE_LIBCURL)
@@ -800,10 +835,10 @@ cleanup_user_oauth_flow(PGconn *conn)
  * This configuration doesn't support the builtin flow.
  */
 
-bool
-use_builtin_flow(PGconn *conn, fe_oauth_state *state)
+static int
+use_builtin_flow(PGconn *conn, fe_oauth_state *state, PGoauthBearerRequestV2 *request)
 {
-	return false;
+	return 0;
 }
 
 #elif defined(USE_DYNAMIC_OAUTH)
@@ -814,36 +849,6 @@ use_builtin_flow(PGconn *conn, fe_oauth_state *state)
 
 typedef char *(*libpq_gettext_func) (const char *msgid);
 
-/*
- * Define accessor/mutator shims to inject into libpq-oauth, so that it doesn't
- * depend on the offsets within PGconn. (These have changed during minor version
- * updates in the past.)
- */
-
-#define DEFINE_GETTER(TYPE, MEMBER) \
-	typedef TYPE (*conn_ ## MEMBER ## _func) (PGconn *conn); \
-	static TYPE conn_ ## MEMBER(PGconn *conn) { return conn->MEMBER; }
-
-/* Like DEFINE_GETTER, but returns a pointer to the member. */
-#define DEFINE_GETTER_P(TYPE, MEMBER) \
-	typedef TYPE (*conn_ ## MEMBER ## _func) (PGconn *conn); \
-	static TYPE conn_ ## MEMBER(PGconn *conn) { return &conn->MEMBER; }
-
-#define DEFINE_SETTER(TYPE, MEMBER) \
-	typedef void (*set_conn_ ## MEMBER ## _func) (PGconn *conn, TYPE val); \
-	static void set_conn_ ## MEMBER(PGconn *conn, TYPE val) { conn->MEMBER = val; }
-
-DEFINE_GETTER_P(PQExpBuffer, errorMessage);
-DEFINE_GETTER(char *, oauth_client_id);
-DEFINE_GETTER(char *, oauth_client_secret);
-DEFINE_GETTER(char *, oauth_discovery_uri);
-DEFINE_GETTER(char *, oauth_issuer_id);
-DEFINE_GETTER(char *, oauth_scope);
-DEFINE_GETTER(fe_oauth_state *, sasl_state);
-
-DEFINE_SETTER(pgsocket, altsock);
-DEFINE_SETTER(char *, oauth_token);
-
 /*
  * Loads the libpq-oauth plugin via dlopen(), initializes it, and plugs its
  * callbacks into the connection's async auth handlers.
@@ -852,27 +857,19 @@ DEFINE_SETTER(char *, oauth_token);
  * handle the use case where the build supports loading a flow but a user does
  * not want to install it. Troubleshooting of linker/loader failures can be done
  * via PGOAUTHDEBUG.
+ *
+ * The lifetime of *request ends shortly after this call, so it must be copied
+ * to longer-lived storage.
  */
-bool
-use_builtin_flow(PGconn *conn, fe_oauth_state *state)
+static int
+use_builtin_flow(PGconn *conn, fe_oauth_state *state, PGoauthBearerRequestV2 *request)
 {
 	static bool initialized = false;
 	static pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER;
 	int			lockerr;
 
-	void		(*init) (pgthreadlock_t threadlock,
-						 libpq_gettext_func gettext_impl,
-						 conn_errorMessage_func errmsg_impl,
-						 conn_oauth_client_id_func clientid_impl,
-						 conn_oauth_client_secret_func clientsecret_impl,
-						 conn_oauth_discovery_uri_func discoveryuri_impl,
-						 conn_oauth_issuer_id_func issuerid_impl,
-						 conn_oauth_scope_func scope_impl,
-						 conn_sasl_state_func saslstate_impl,
-						 set_conn_altsock_func setaltsock_impl,
-						 set_conn_oauth_token_func settoken_impl);
-	PostgresPollingStatusType (*flow) (PGconn *conn);
-	void		(*cleanup) (PGconn *conn);
+	void		(*init) (libpq_gettext_func gettext_impl);
+	int			(*start_flow) (PGconn *conn, PGoauthBearerRequestV2 *request);
 
 	/*
 	 * On macOS only, load the module using its absolute install path; the
@@ -885,9 +882,9 @@ use_builtin_flow(PGconn *conn, fe_oauth_state *state)
 	 */
 	const char *const module_name =
 #if defined(__darwin__)
-		LIBDIR "/libpq-oauth-" PG_MAJORVERSION DLSUFFIX;
+		LIBDIR "/libpq-oauth" DLSUFFIX;
 #else
-		"libpq-oauth-" PG_MAJORVERSION DLSUFFIX;
+		"libpq-oauth" DLSUFFIX;
 #endif
 
 	state->builtin_flow = dlopen(module_name, RTLD_NOW | RTLD_LOCAL);
@@ -903,12 +900,11 @@ use_builtin_flow(PGconn *conn, fe_oauth_state *state)
 		if (oauth_unsafe_debugging_enabled())
 			fprintf(stderr, "failed dlopen for libpq-oauth: %s\n", dlerror());
 
-		return false;
+		return 0;
 	}
 
 	if ((init = dlsym(state->builtin_flow, "libpq_oauth_init")) == NULL
-		|| (flow = dlsym(state->builtin_flow, "pg_fe_run_oauth_flow")) == NULL
-		|| (cleanup = dlsym(state->builtin_flow, "pg_fe_cleanup_oauth_flow")) == NULL)
+		|| (start_flow = dlsym(state->builtin_flow, "pg_start_oauthbearer")) == NULL)
 	{
 		/*
 		 * This is more of an error condition than the one above, but due to
@@ -918,7 +914,7 @@ use_builtin_flow(PGconn *conn, fe_oauth_state *state)
 			fprintf(stderr, "failed dlsym for libpq-oauth: %s\n", dlerror());
 
 		dlclose(state->builtin_flow);
-		return false;
+		return 0;
 	}
 
 	/*
@@ -938,56 +934,40 @@ use_builtin_flow(PGconn *conn, fe_oauth_state *state)
 		Assert(false);
 
 		libpq_append_conn_error(conn, "failed to lock mutex (%d)", lockerr);
-		return false;
+		return 0;
 	}
 
 	if (!initialized)
 	{
-		init(pg_g_threadlock,
+		init(
 #ifdef ENABLE_NLS
-			 libpq_gettext,
+			 libpq_gettext
 #else
-			 NULL,
+			 NULL
 #endif
-			 conn_errorMessage,
-			 conn_oauth_client_id,
-			 conn_oauth_client_secret,
-			 conn_oauth_discovery_uri,
-			 conn_oauth_issuer_id,
-			 conn_oauth_scope,
-			 conn_sasl_state,
-			 set_conn_altsock,
-			 set_conn_oauth_token);
+			);
 
 		initialized = true;
 	}
 
 	pthread_mutex_unlock(&init_mutex);
 
-	/* Set our asynchronous callbacks. */
-	conn->async_auth = flow;
-	conn->cleanup_async_auth = cleanup;
-
-	return true;
+	return (start_flow(conn, request) == 0) ? 1 : -1;
 }
 
 #else
 
 /*
- * Use the builtin flow in libpq-oauth.a (see libpq-oauth/oauth-curl.h).
+ * For static builds, we can just call pg_start_oauthbearer() directly. It's
+ * provided by libpq-oauth.a.
  */
 
-extern PostgresPollingStatusType pg_fe_run_oauth_flow(PGconn *conn);
-extern void pg_fe_cleanup_oauth_flow(PGconn *conn);
+extern int	pg_start_oauthbearer(PGconn *conn, PGoauthBearerRequestV2 *request);
 
-bool
-use_builtin_flow(PGconn *conn, fe_oauth_state *state)
+static int
+use_builtin_flow(PGconn *conn, fe_oauth_state *state, PGoauthBearerRequestV2 *request)
 {
-	/* Set our asynchronous callbacks. */
-	conn->async_auth = pg_fe_run_oauth_flow;
-	conn->cleanup_async_auth = pg_fe_cleanup_oauth_flow;
-
-	return true;
+	return (pg_start_oauthbearer(conn, request) == 0) ? 1 : -1;
 }
 
 #endif							/* USE_LIBCURL */
@@ -1000,11 +980,11 @@ use_builtin_flow(PGconn *conn, fe_oauth_state *state)
  * If the application has registered a custom flow handler using
  * PQAUTHDATA_OAUTH_BEARER_TOKEN[_V2], it may either return a token immediately
  * (e.g. if it has one cached for immediate use), or set up for a series of
- * asynchronous callbacks which will be managed by run_user_oauth_flow().
+ * asynchronous callbacks which will be managed by run_oauth_flow().
  *
  * If the default handler is used instead, a Device Authorization flow is used
- * for the connection if support has been compiled in. (See
- * fe-auth-oauth-curl.c for implementation details.)
+ * for the connection if support has been compiled in. (See oauth-curl.c for
+ * implementation details.)
  *
  * If neither a custom handler nor the builtin flow is available, the connection
  * fails here.
@@ -1026,11 +1006,17 @@ setup_token_request(PGconn *conn, fe_oauth_state *state)
 
 	/*
 	 * The client may have overridden the OAuth flow. Try the v2 hook first,
-	 * then fall back to the v1 implementation.
+	 * then fall back to the v1 implementation. If neither is available, try
+	 * the builtin flow.
 	 */
 	res = PQauthDataHook(PQAUTHDATA_OAUTH_BEARER_TOKEN_V2, conn, &request);
 	if (res == 0)
 		res = PQauthDataHook(PQAUTHDATA_OAUTH_BEARER_TOKEN, conn, &request);
+	if (res == 0)
+	{
+		state->builtin = true;
+		res = use_builtin_flow(conn, state, &request);
+	}
 
 	if (res > 0)
 	{
@@ -1065,16 +1051,16 @@ setup_token_request(PGconn *conn, fe_oauth_state *state)
 
 		*request_copy = request;
 
-		conn->async_auth = run_user_oauth_flow;
-		conn->cleanup_async_auth = cleanup_user_oauth_flow;
+		conn->async_auth = run_oauth_flow;
+		conn->cleanup_async_auth = cleanup_oauth_flow;
 		state->async_ctx = request_copy;
 	}
 	else if (res < 0)
 	{
-		report_user_flow_error(conn, &request);
+		report_flow_error(conn, &request);
 		goto fail;
 	}
-	else if (!use_builtin_flow(conn, state))
+	else
 	{
 		libpq_append_conn_error(conn, "no OAuth flows are available (try installing the libpq-oauth package)");
 		goto fail;
-- 
2.34.1



  [application/x-patch] v3-0005-libpq-oauth-Never-link-against-libpq-s-encoding-f.patch (3.2K, 6-v3-0005-libpq-oauth-Never-link-against-libpq-s-encoding-f.patch)
  download | inline diff:
From 60c2a28939056ee6080a505cccb53636b136676b Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email protected]>
Date: Wed, 3 Dec 2025 09:53:44 -0800
Subject: [PATCH v3 5/6] libpq-oauth: Never link against libpq's encoding
 functions

Now that libpq-oauth doesn't have to match the major version of libpq,
some things in pg_wchar.h are technically unsafe for us to use. (See
b6c7cfac8 for a fuller discussion.) This is unlikely to be a problem --
we only care about UTF-8 in the context of OAuth right now -- but if
anyone did introduce a way to hit it, it'd be extremely difficult to
debug or reproduce, and it'd be a potential security vulnerability to
boot.

Define USE_PRIVATE_ENCODING_FUNCS so that anyone who tries to add a
dependency on the exported APIs will simply fail to link the shared
module.

Reviewed-by: Chao Li <[email protected]>
Reviewed-by: Zsolt Parragi <[email protected]>
Discussion: https://postgr.es/m/CAOYmi%2BmrGg%2Bn_X2MOLgeWcj3v_M00gR8uz_D7mM8z%3DdX1JYVbg%40mail.gmail.com
---
 src/interfaces/libpq-oauth/meson.build | 10 +++++++++-
 src/interfaces/libpq-oauth/Makefile    | 11 +++++++++--
 2 files changed, 18 insertions(+), 3 deletions(-)

diff --git a/src/interfaces/libpq-oauth/meson.build b/src/interfaces/libpq-oauth/meson.build
index 59bce4903e5..c769af8e6e6 100644
--- a/src/interfaces/libpq-oauth/meson.build
+++ b/src/interfaces/libpq-oauth/meson.build
@@ -12,7 +12,15 @@ libpq_oauth_sources = files(
 libpq_oauth_so_sources = files(
   'oauth-utils.c',
 )
-libpq_oauth_so_c_args = ['-DUSE_DYNAMIC_OAUTH']
+libpq_oauth_so_c_args = [
+  '-DUSE_DYNAMIC_OAUTH',
+
+  # A bit of forward-looking paranoia: don't allow anyone to accidentally depend
+  # on the encoding IDs coming from libpq. They're not guaranteed to match the
+  # IDs in use by our version of pgcommon, now that we allow the major version
+  # of libpq to differ from the major version of libpq-oauth.
+  '-DUSE_PRIVATE_ENCODING_FUNCS',
+]
 
 export_file = custom_target('libpq-oauth.exports',
   kwargs: gen_export_kwargs,
diff --git a/src/interfaces/libpq-oauth/Makefile b/src/interfaces/libpq-oauth/Makefile
index e90482566b1..231349034d1 100644
--- a/src/interfaces/libpq-oauth/Makefile
+++ b/src/interfaces/libpq-oauth/Makefile
@@ -24,6 +24,14 @@ override shlib := lib$(NAME)$(DLSUFFIX)
 override CPPFLAGS := -I$(libpq_srcdir) -I$(top_builddir)/src/port $(CPPFLAGS) $(LIBCURL_CPPFLAGS)
 override CFLAGS += $(PTHREAD_CFLAGS)
 
+override CPPFLAGS_SHLIB := -DUSE_DYNAMIC_OAUTH
+
+# A bit of forward-looking paranoia: don't allow libpq-oauth.so to accidentally
+# depend on the encoding IDs coming from libpq. They're not guaranteed to match
+# the IDs in use by our version of pgcommon, now that we allow the major version
+# of libpq to differ from the major version of libpq-oauth.
+override CPPFLAGS_SHLIB += -DUSE_PRIVATE_ENCODING_FUNCS
+
 OBJS = \
 	$(WIN32RES)
 
@@ -34,8 +42,7 @@ OBJS_SHLIB = \
 	oauth-curl_shlib.o \
 	oauth-utils.o \
 
-oauth-utils.o: override CPPFLAGS += -DUSE_DYNAMIC_OAUTH
-oauth-curl_shlib.o: override CPPFLAGS_SHLIB += -DUSE_DYNAMIC_OAUTH
+oauth-utils.o: override CPPFLAGS += $(CPPFLAGS_SHLIB)
 
 # Add shlib-/stlib-specific objects.
 $(shlib): override OBJS += $(OBJS_SHLIB)
-- 
2.34.1



  [application/x-patch] v3-0006-WIP-Introduce-third-party-OAuth-flow-plugins.patch (38.3K, 7-v3-0006-WIP-Introduce-third-party-OAuth-flow-plugins.patch)
  download | inline diff:
From b6974d5c8e2e3c2f407b7eb2b72256f8096df785 Mon Sep 17 00:00:00 2001
From: Jacob Champion <[email protected]>
Date: Wed, 3 Dec 2025 15:47:23 -0800
Subject: [PATCH v3 6/6] WIP: Introduce third-party OAuth flow plugins?

This experimental commit promotes the pg_start_oauthbearer API to a
public header (libpq-oauth.h) and adds a PGOAUTHMODULE environment
variable that overrides the load path for the plugin, allowing users to
provide their own. The libpq_oauth_init function is now optional, and
will remain undocumented. (Modules that don't provide it are marked as
user-defined.)

This is a relatively small amount of implementation change, but
unfortunately the tests have a large amount of code motion to be able to
share logic between the test executable and plugin. I might need to
split that into multiple squash! commits to make it more easily
reviewable.

TODO: figure out PGDLLEXPORT, which we do not currently provide publicly
TODO: lock down PGOAUTHMODULE as necessary to avoid introducing exciting
      new vulnerabilities
TODO: how hard would it be to support Windows here?

Reviewed-by: Zsolt Parragi <[email protected]>
Discussion: https://postgr.es/m/CAOYmi%2BmrGg%2Bn_X2MOLgeWcj3v_M00gR8uz_D7mM8z%3DdX1JYVbg%40mail.gmail.com
---
 src/interfaces/libpq/meson.build              |   1 +
 src/interfaces/libpq/Makefile                 |   2 +
 src/interfaces/libpq-oauth/oauth-curl.h       |  24 --
 src/interfaces/libpq/fe-auth-oauth.h          |   2 +-
 src/interfaces/libpq/libpq-oauth.h            |  52 +++
 src/interfaces/libpq-oauth/oauth-curl.c       |   2 +-
 src/interfaces/libpq/fe-auth-oauth.c          | 121 ++++--
 src/test/modules/oauth_validator/meson.build  |  15 +
 src/test/modules/oauth_validator/Makefile     |  10 +-
 .../oauth_validator/oauth_test_common.h       |  26 ++
 src/test/modules/oauth_validator/oauth_flow.c |  69 ++++
 .../oauth_validator/oauth_hook_client.c       | 319 +--------------
 .../oauth_validator/oauth_test_common.c       | 374 ++++++++++++++++++
 .../modules/oauth_validator/t/002_client.pl   |  56 ++-
 14 files changed, 687 insertions(+), 386 deletions(-)
 delete mode 100644 src/interfaces/libpq-oauth/oauth-curl.h
 create mode 100644 src/interfaces/libpq/libpq-oauth.h
 create mode 100644 src/test/modules/oauth_validator/oauth_test_common.h
 create mode 100644 src/test/modules/oauth_validator/oauth_flow.c
 create mode 100644 src/test/modules/oauth_validator/oauth_test_common.c

diff --git a/src/interfaces/libpq/meson.build b/src/interfaces/libpq/meson.build
index c5ecd9c3a87..caff7194eaf 100644
--- a/src/interfaces/libpq/meson.build
+++ b/src/interfaces/libpq/meson.build
@@ -128,6 +128,7 @@ pkgconfig.generate(
 install_headers(
   'libpq-fe.h',
   'libpq-events.h',
+  'libpq-oauth.h',
 )
 
 install_headers(
diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile
index bf4baa92917..d787f5a30df 100644
--- a/src/interfaces/libpq/Makefile
+++ b/src/interfaces/libpq/Makefile
@@ -155,6 +155,7 @@ $(top_builddir)/src/port/pg_config_paths.h:
 install: all installdirs install-lib
 	$(INSTALL_DATA) $(srcdir)/libpq-fe.h '$(DESTDIR)$(includedir)'
 	$(INSTALL_DATA) $(srcdir)/libpq-events.h '$(DESTDIR)$(includedir)'
+	$(INSTALL_DATA) $(srcdir)/libpq-oauth.h '$(DESTDIR)$(includedir)'
 	$(INSTALL_DATA) $(srcdir)/libpq-int.h '$(DESTDIR)$(includedir_internal)'
 	$(INSTALL_DATA) $(srcdir)/fe-auth-sasl.h '$(DESTDIR)$(includedir_internal)'
 	$(INSTALL_DATA) $(srcdir)/pqexpbuffer.h '$(DESTDIR)$(includedir_internal)'
@@ -177,6 +178,7 @@ installdirs: installdirs-lib
 uninstall: uninstall-lib
 	rm -f '$(DESTDIR)$(includedir)/libpq-fe.h'
 	rm -f '$(DESTDIR)$(includedir)/libpq-events.h'
+	rm -f '$(DESTDIR)$(includedir)/libpq-oauth.h'
 	rm -f '$(DESTDIR)$(includedir_internal)/libpq-int.h'
 	rm -f '$(DESTDIR)$(includedir_internal)/fe-auth-sasl.h'
 	rm -f '$(DESTDIR)$(includedir_internal)/pqexpbuffer.h'
diff --git a/src/interfaces/libpq-oauth/oauth-curl.h b/src/interfaces/libpq-oauth/oauth-curl.h
deleted file mode 100644
index 1d4dd766217..00000000000
--- a/src/interfaces/libpq-oauth/oauth-curl.h
+++ /dev/null
@@ -1,24 +0,0 @@
-/*-------------------------------------------------------------------------
- *
- * oauth-curl.h
- *
- *	  Definitions for OAuth Device Authorization module
- *
- * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
- * Portions Copyright (c) 1994, Regents of the University of California
- *
- * src/interfaces/libpq-oauth/oauth-curl.h
- *
- *-------------------------------------------------------------------------
- */
-
-#ifndef OAUTH_CURL_H
-#define OAUTH_CURL_H
-
-#include "libpq-fe.h"
-
-/* Exported flow callback. */
-extern PGDLLEXPORT int pg_start_oauthbearer(PGconn *conn,
-											PGoauthBearerRequestV2 *request);
-
-#endif							/* OAUTH_CURL_H */
diff --git a/src/interfaces/libpq/fe-auth-oauth.h b/src/interfaces/libpq/fe-auth-oauth.h
index 511284614f7..5c95187f6d8 100644
--- a/src/interfaces/libpq/fe-auth-oauth.h
+++ b/src/interfaces/libpq/fe-auth-oauth.h
@@ -35,7 +35,7 @@ typedef struct
 	void	   *async_ctx;
 
 	bool		builtin;
-	void	   *builtin_flow;
+	void	   *flow_module;
 } fe_oauth_state;
 
 extern void pqClearOAuthToken(PGconn *conn);
diff --git a/src/interfaces/libpq/libpq-oauth.h b/src/interfaces/libpq/libpq-oauth.h
new file mode 100644
index 00000000000..2a62b330b1c
--- /dev/null
+++ b/src/interfaces/libpq/libpq-oauth.h
@@ -0,0 +1,52 @@
+/*-------------------------------------------------------------------------
+ *
+ * libpq-oauth.h
+ *	  This file contains structs and functions used by custom OAuth plugins.
+ *
+ * Copyright (c) 2025, PostgreSQL Global Development Group
+ *
+ * src/interfaces/libpq/libpq-oauth.h
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef LIBPQ_OAUTH_H
+#define LIBPQ_OAUTH_H
+
+#include "libpq-fe.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/* XXX can't rely on c.h, but duplicating this is asking for trouble */
+#ifndef PGDLLEXPORT
+#ifdef _WIN32
+#define PGDLLEXPORT __declspec (dllexport)
+#elif defined(__has_attribute)
+#if __has_attribute(visibility)
+#define PGDLLEXPORT __attribute__((visibility("default")))
+#else
+#define PGDLLEXPORT
+#endif
+#else
+#define PGDLLEXPORT
+#endif
+#endif
+
+/*
+ * V1 API
+ *
+ * Flow plugins must provide an implementation of this callback.
+ *
+ * TODO: provide a magic struct that allows backwards but not forwards compat?
+ */
+extern PGDLLEXPORT int pg_start_oauthbearer(PGconn *conn,
+											PGoauthBearerRequestV2 *request);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif							/* LIBPQ_OAUTH_H */
diff --git a/src/interfaces/libpq-oauth/oauth-curl.c b/src/interfaces/libpq-oauth/oauth-curl.c
index cebe0a24ad0..961ff8b49ac 100644
--- a/src/interfaces/libpq-oauth/oauth-curl.c
+++ b/src/interfaces/libpq-oauth/oauth-curl.c
@@ -29,8 +29,8 @@
 #endif
 
 #include "common/jsonapi.h"
+#include "libpq-oauth.h"
 #include "mb/pg_wchar.h"
-#include "oauth-curl.h"
 
 #ifdef USE_DYNAMIC_OAUTH
 
diff --git a/src/interfaces/libpq/fe-auth-oauth.c b/src/interfaces/libpq/fe-auth-oauth.c
index 904f43e90ea..ea0daddf4e8 100644
--- a/src/interfaces/libpq/fe-auth-oauth.c
+++ b/src/interfaces/libpq/fe-auth-oauth.c
@@ -17,6 +17,8 @@
 
 #ifdef USE_DYNAMIC_OAUTH
 #include <dlfcn.h>
+#else
+#include "libpq-oauth.h"
 #endif
 
 #include "common/base64.h"
@@ -880,41 +882,67 @@ use_builtin_flow(PGconn *conn, fe_oauth_state *state, PGoauthBearerRequestV2 *re
 	 * On the other platforms, load the module using only the basename, to
 	 * rely on the runtime linker's standard search behavior.
 	 */
-	const char *const module_name =
+	const char *module_name =
 #if defined(__darwin__)
 		LIBDIR "/libpq-oauth" DLSUFFIX;
 #else
 		"libpq-oauth" DLSUFFIX;
 #endif
 
-	state->builtin_flow = dlopen(module_name, RTLD_NOW | RTLD_LOCAL);
-	if (!state->builtin_flow)
+	/*-
+	 * Additionally, the user may override the module path explicitly to be
+	 * able to provide their own module, via PGOAUTHMODULE.
+	 *
+	 * TODO: have to think about _all_ the security ramifications of this. What
+	 * existing protections in LD_LIBRARY_PATH (and/or SIP) are we potentially
+	 * bypassing? Should we check the permissions of the file somehow...?
+	 * TODO: maybe disallow anything not underneath LIBDIR? or PKGLIBDIR?
+	 * Should it have a naming convention?
+	 */
+	const char *env = getenv("PGOAUTHMODULE");
+
+	if (env && env[0])
+		module_name = env;
+	else
+		state->builtin = true;
+
+	state->flow_module = dlopen(module_name, RTLD_NOW | RTLD_LOCAL);
+	if (!state->flow_module)
 	{
 		/*
 		 * For end users, this probably isn't an error condition, it just
 		 * means the flow isn't installed. Developers and package maintainers
-		 * may want to debug this via the PGOAUTHDEBUG envvar, though.
+		 * may want to debug this via the PGOAUTHDEBUG envvar, though, and we
+		 * should be more noisy if users tried to provide a PGOAUTHMODULE.
 		 *
 		 * Note that POSIX dlerror() isn't guaranteed to be threadsafe.
 		 */
 		if (oauth_unsafe_debugging_enabled())
-			fprintf(stderr, "failed dlopen for libpq-oauth: %s\n", dlerror());
+			fprintf(stderr, "failed dlopen for %s: %s\n", module_name, dlerror());
+
+		if (state->builtin)
+			return 0;
 
-		return 0;
+		request->error = libpq_gettext("plugin could not be loaded");
+		return -1;
 	}
 
-	if ((init = dlsym(state->builtin_flow, "libpq_oauth_init")) == NULL
-		|| (start_flow = dlsym(state->builtin_flow, "pg_start_oauthbearer")) == NULL)
+	if ((start_flow = dlsym(state->flow_module, "pg_start_oauthbearer")) == NULL)
 	{
 		/*
 		 * This is more of an error condition than the one above, but due to
 		 * the dlerror() threadsafety issue, lock it behind PGOAUTHDEBUG too.
 		 */
 		if (oauth_unsafe_debugging_enabled())
-			fprintf(stderr, "failed dlsym for libpq-oauth: %s\n", dlerror());
+			fprintf(stderr, "failed dlsym for %s: %s\n", module_name, dlerror());
+
+		dlclose(state->flow_module);
+
+		if (state->builtin)
+			return 0;
 
-		dlclose(state->builtin_flow);
-		return 0;
+		request->error = libpq_gettext("plugin entry point could not be located");
+		return -1;
 	}
 
 	/*
@@ -923,34 +951,46 @@ use_builtin_flow(PGconn *conn, fe_oauth_state *state, PGoauthBearerRequestV2 *re
 	 */
 
 	/*
-	 * We need to inject necessary function pointers into the module. This
-	 * only needs to be done once -- even if the pointers are constant,
-	 * assigning them while another thread is executing the flows feels like
-	 * tempting fate.
+	 * Our libpq-oauth.so provides a special initialization function for libpq
+	 * integration. It's not a problem if we don't find this; it just means
+	 * that a user-defined module is being used.
 	 */
-	if ((lockerr = pthread_mutex_lock(&init_mutex)) != 0)
+	init = dlsym(state->flow_module, "libpq_oauth_init");
+
+	if (!init)
+		state->builtin = false; /* adjust our error messages */
+	else
 	{
-		/* Should not happen... but don't continue if it does. */
-		Assert(false);
+		/*
+		 * We need to inject necessary function pointers into the module. This
+		 * only needs to be done once -- even if the pointers are constant,
+		 * assigning them while another thread is executing the flows feels
+		 * like tempting fate.
+		 */
+		if ((lockerr = pthread_mutex_lock(&init_mutex)) != 0)
+		{
+			/* Should not happen... but don't continue if it does. */
+			Assert(false);
 
-		libpq_append_conn_error(conn, "failed to lock mutex (%d)", lockerr);
-		return 0;
-	}
+			libpq_append_conn_error(conn, "failed to lock mutex (%d)", lockerr);
+			return 0;
+		}
 
-	if (!initialized)
-	{
-		init(
+		if (!initialized)
+		{
+			init(
 #ifdef ENABLE_NLS
-			 libpq_gettext
+				 libpq_gettext
 #else
-			 NULL
+				 NULL
 #endif
-			);
+				);
 
-		initialized = true;
-	}
+			initialized = true;
+		}
 
-	pthread_mutex_unlock(&init_mutex);
+		pthread_mutex_unlock(&init_mutex);
+	}
 
 	return (start_flow(conn, request) == 0) ? 1 : -1;
 }
@@ -967,6 +1007,7 @@ extern int	pg_start_oauthbearer(PGconn *conn, PGoauthBearerRequestV2 *request);
 static int
 use_builtin_flow(PGconn *conn, fe_oauth_state *state, PGoauthBearerRequestV2 *request)
 {
+	state->builtin = true;
 	return (pg_start_oauthbearer(conn, request) == 0) ? 1 : -1;
 }
 
@@ -1013,10 +1054,7 @@ setup_token_request(PGconn *conn, fe_oauth_state *state)
 	if (res == 0)
 		res = PQauthDataHook(PQAUTHDATA_OAUTH_BEARER_TOKEN, conn, &request);
 	if (res == 0)
-	{
-		state->builtin = true;
 		res = use_builtin_flow(conn, state, &request);
-	}
 
 	if (res > 0)
 	{
@@ -1054,19 +1092,18 @@ setup_token_request(PGconn *conn, fe_oauth_state *state)
 		conn->async_auth = run_oauth_flow;
 		conn->cleanup_async_auth = cleanup_oauth_flow;
 		state->async_ctx = request_copy;
+
+		return true;
 	}
-	else if (res < 0)
-	{
+
+	/*
+	 * Failure cases: either we tried to set up a flow and failed, or there
+	 * was no flow to try.
+	 */
+	if (res < 0)
 		report_flow_error(conn, &request);
-		goto fail;
-	}
 	else
-	{
 		libpq_append_conn_error(conn, "no OAuth flows are available (try installing the libpq-oauth package)");
-		goto fail;
-	}
-
-	return true;
 
 fail:
 	if (request.v1.cleanup)
diff --git a/src/test/modules/oauth_validator/meson.build b/src/test/modules/oauth_validator/meson.build
index c4b73e05297..71412f0ecab 100644
--- a/src/test/modules/oauth_validator/meson.build
+++ b/src/test/modules/oauth_validator/meson.build
@@ -50,6 +50,7 @@ test_install_libs += magic_validator
 
 oauth_hook_client_sources = files(
   'oauth_hook_client.c',
+  'oauth_test_common.c',
 )
 
 if host_system == 'windows'
@@ -67,6 +68,19 @@ oauth_hook_client = executable('oauth_hook_client',
 )
 testprep_targets += oauth_hook_client
 
+oauth_flow = shared_module('oauth_flow',
+  files(
+    'oauth_flow.c',
+    'oauth_test_common.c',
+  ),
+  include_directories: [postgres_inc],
+  dependencies: [frontend_shlib_code, libpq],
+  kwargs: default_lib_args + {
+    'install': false,
+  },
+)
+testprep_targets += oauth_flow
+
 tests += {
   'name': 'oauth_validator',
   'sd': meson.current_source_dir(),
@@ -80,6 +94,7 @@ tests += {
       'PYTHON': python.full_path(),
       'with_libcurl': oauth_flow_supported ? 'yes' : 'no',
       'with_python': 'yes',
+      'flow_module_path': oauth_flow.full_path(),
     },
     'deps': [oauth_hook_client],
   },
diff --git a/src/test/modules/oauth_validator/Makefile b/src/test/modules/oauth_validator/Makefile
index cb64f0f1437..a17c4259aea 100644
--- a/src/test/modules/oauth_validator/Makefile
+++ b/src/test/modules/oauth_validator/Makefile
@@ -14,11 +14,13 @@ PGFILEDESC = "validator - test OAuth validator module"
 
 PROGRAM = oauth_hook_client
 PGAPPICON = win32
-OBJS = $(WIN32RES) oauth_hook_client.o
+OBJS = $(WIN32RES) oauth_hook_client.o oauth_test_common.o
 
 PG_CPPFLAGS = -I$(libpq_srcdir)
 PG_LIBS_INTERNAL += $(libpq_pgport)
 
+EXTRA_CLEAN = oauth_flow$(DLSUFFIX) oauth_flow.o
+
 NO_INSTALLCHECK = 1
 
 TAP_TESTS = 1
@@ -33,8 +35,14 @@ top_builddir = ../../../..
 include $(top_builddir)/src/Makefile.global
 include $(top_srcdir)/contrib/contrib-global.mk
 
+all: oauth_flow$(DLSUFFIX)
+
+oauth_flow$(DLSUFFIX): oauth_flow.o oauth_test_common.o
+	$(CC) $(CFLAGS) $^ $(LDFLAGS) $(libpq_pgport_shlib) $(LDFLAGS_SL) -shared -o $@
+
 export PYTHON
 export with_libcurl
 export with_python
+export flow_module_path := $(abs_top_builddir)/$(subdir)/oauth_flow$(DLSUFFIX)
 
 endif
diff --git a/src/test/modules/oauth_validator/oauth_test_common.h b/src/test/modules/oauth_validator/oauth_test_common.h
new file mode 100644
index 00000000000..33e72e30440
--- /dev/null
+++ b/src/test/modules/oauth_validator/oauth_test_common.h
@@ -0,0 +1,26 @@
+/*-------------------------------------------------------------------------
+ *
+ * oauth_test_common.h
+ *	  Shared functionality for oauth_hook_client and oauth_flow
+ *
+ * Copyright (c) 2025, PostgreSQL Global Development Group
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef OAUTH_TEST_COMMON_H
+#define OAUTH_TEST_COMMON_H
+
+/*
+ * Only public headers can be here, since oauth_flow.c is trying to test only
+ * the public API.
+ */
+#include "libpq-fe.h"
+
+extern int	stress_async;		/* for oauth_hook_client */
+
+extern char *oauth_test_parse_argv(int argc, char *argv[], int for_plugin);
+extern int	oauth_test_authdata_hook(PGauthData type, PGconn *conn, void *data);
+extern int	oauth_test_start_flow(PGconn *conn, PGoauthBearerRequestV2 *request);
+
+#endif							/* OAUTH_TEST_COMMON_H */
diff --git a/src/test/modules/oauth_validator/oauth_flow.c b/src/test/modules/oauth_validator/oauth_flow.c
new file mode 100644
index 00000000000..8068a45ae29
--- /dev/null
+++ b/src/test/modules/oauth_validator/oauth_flow.c
@@ -0,0 +1,69 @@
+/*-------------------------------------------------------------------------
+ *
+ * oauth_flow.c
+ *	  Test plugin for clientside OAuth flows
+ *
+ * Copyright (c) 2025, PostgreSQL Global Development Group
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#include <stdlib.h>
+#include <string.h>
+
+/* Since we want to test the public API, only include public headers here. */
+#include "libpq-fe.h"
+#include "libpq-oauth.h"
+#include "oauth_test_common.h"
+
+static void
+load_test_flags(void)
+{
+	int			argc;
+	char	  **argv;
+	char	   *env = getenv("OAUTH_TEST_FLAGS");
+	int			flag_count;
+	int			i;
+
+	if (!env || !env[0])
+	{
+		fprintf(stderr, "OAUTH_TEST_FLAGS must be set\n");
+		exit(1);
+	}
+
+	flag_count = 1;
+	for (char *c = env; *c; c++)
+	{
+		if (*c == '\x01')
+			flag_count++;
+	}
+
+	argc = flag_count + 1;
+	argv = malloc(sizeof(*argv) * (argc + 1));
+	if (!argv)
+	{
+		fprintf(stderr, "out of memory");
+		exit(1);
+	}
+
+	argv[0] = "[plugin test]";
+	for (i = 1; i < flag_count; i++)
+	{
+		argv[i] = env;
+
+		env = strchr(env, '\x01');
+		*env++ = '\0';
+	}
+	argv[flag_count] = env;
+	argv[argc] = NULL;
+
+	oauth_test_parse_argv(argc, argv, 1 /* plugin */ );
+}
+
+int
+pg_start_oauthbearer(PGconn *conn, PGoauthBearerRequestV2 *request)
+{
+	load_test_flags();
+
+	return oauth_test_start_flow(conn, request);
+}
diff --git a/src/test/modules/oauth_validator/oauth_hook_client.c b/src/test/modules/oauth_validator/oauth_hook_client.c
index 5bddc0f807a..5f932acc571 100644
--- a/src/test/modules/oauth_validator/oauth_hook_client.c
+++ b/src/test/modules/oauth_validator/oauth_hook_client.c
@@ -18,144 +18,18 @@
 
 #include <sys/socket.h>
 
-#include "getopt_long.h"
 #include "libpq-fe.h"
-#include "pqexpbuffer.h"
 
-static int	handle_auth_data(PGauthData type, PGconn *conn, void *data);
-static PostgresPollingStatusType async_cb(PGconn *conn,
-										  PGoauthBearerRequest *req,
-										  pgsocket *altsock);
-static PostgresPollingStatusType misbehave_cb(PGconn *conn,
-											  PGoauthBearerRequest *req,
-											  pgsocket *altsock);
-
-static void
-usage(char *argv[])
-{
-	printf("usage: %s [flags] CONNINFO\n\n", argv[0]);
-
-	printf("recognized flags:\n");
-	printf("  -h, --help              show this message\n");
-	printf("  -v VERSION              select the hook API version (default 2)\n");
-	printf("  --expected-scope SCOPE  fail if received scopes do not match SCOPE\n");
-	printf("  --expected-uri URI      fail if received configuration link does not match URI\n");
-	printf("  --expected-issuer ISS   fail if received issuer does not match ISS (v2 only)\n");
-	printf("  --misbehave=MODE        have the hook fail required postconditions\n"
-		   "                          (MODEs: no-hook, fail-async, no-token, no-socket)\n");
-	printf("  --no-hook               don't install OAuth hooks\n");
-	printf("  --hang-forever          don't ever return a token (combine with connect_timeout)\n");
-	printf("  --token TOKEN           use the provided TOKEN value\n");
-	printf("  --error ERRMSG          fail instead, with the given ERRMSG (v2 only)\n");
-	printf("  --stress-async          busy-loop on PQconnectPoll rather than polling\n");
-}
-
-/* --options */
-static bool no_hook = false;
-static bool hang_forever = false;
-static bool stress_async = false;
-static const char *expected_uri = NULL;
-static const char *expected_issuer = NULL;
-static const char *expected_scope = NULL;
-static const char *misbehave_mode = NULL;
-static char *token = NULL;
-static char *errmsg = NULL;
-static int	hook_version = PQAUTHDATA_OAUTH_BEARER_TOKEN_V2;
+#include "oauth_test_common.h"
 
 int
 main(int argc, char *argv[])
 {
-	static const struct option long_options[] = {
-		{"help", no_argument, NULL, 'h'},
-
-		{"expected-scope", required_argument, NULL, 1000},
-		{"expected-uri", required_argument, NULL, 1001},
-		{"no-hook", no_argument, NULL, 1002},
-		{"token", required_argument, NULL, 1003},
-		{"hang-forever", no_argument, NULL, 1004},
-		{"misbehave", required_argument, NULL, 1005},
-		{"stress-async", no_argument, NULL, 1006},
-		{"expected-issuer", required_argument, NULL, 1007},
-		{"error", required_argument, NULL, 1008},
-		{0}
-	};
-
-	const char *conninfo;
+	const char *conninfo = oauth_test_parse_argv(argc, argv, 0 /* hook */ );
 	PGconn	   *conn;
-	int			c;
-
-	while ((c = getopt_long(argc, argv, "hv:", long_options, NULL)) != -1)
-	{
-		switch (c)
-		{
-			case 'h':
-				usage(argv);
-				return 0;
-
-			case 'v':
-				if (strcmp(optarg, "1") == 0)
-					hook_version = PQAUTHDATA_OAUTH_BEARER_TOKEN;
-				else if (strcmp(optarg, "2") == 0)
-					hook_version = PQAUTHDATA_OAUTH_BEARER_TOKEN_V2;
-				else
-				{
-					usage(argv);
-					return 1;
-				}
-				break;
-
-			case 1000:			/* --expected-scope */
-				expected_scope = optarg;
-				break;
-
-			case 1001:			/* --expected-uri */
-				expected_uri = optarg;
-				break;
-
-			case 1002:			/* --no-hook */
-				no_hook = true;
-				break;
-
-			case 1003:			/* --token */
-				token = optarg;
-				break;
-
-			case 1004:			/* --hang-forever */
-				hang_forever = true;
-				break;
-
-			case 1005:			/* --misbehave */
-				misbehave_mode = optarg;
-				break;
-
-			case 1006:			/* --stress-async */
-				stress_async = true;
-				break;
-
-			case 1007:			/* --expected-issuer */
-				expected_issuer = optarg;
-				break;
-
-			case 1008:			/* --error */
-				errmsg = optarg;
-				break;
-
-			default:
-				usage(argv);
-				return 1;
-		}
-	}
-
-	if (argc != optind + 1)
-	{
-		usage(argv);
-		return 1;
-	}
-
-	conninfo = argv[optind];
 
 	/* Set up our OAuth hooks. */
-	PQsetAuthDataHook(handle_auth_data);
+	PQsetAuthDataHook(oauth_test_authdata_hook);
 
 	/* Connect. (All the actual work is in the hook.) */
 	if (stress_async)
@@ -193,190 +67,3 @@ main(int argc, char *argv[])
 	PQfinish(conn);
 	return 0;
 }
-
-/*
- * PQauthDataHook implementation. Replaces the default client flow by handling
- * PQAUTHDATA_OAUTH_BEARER_TOKEN[_V2].
- */
-static int
-handle_auth_data(PGauthData type, PGconn *conn, void *data)
-{
-	PGoauthBearerRequest *req;
-	PGoauthBearerRequestV2 *req2 = NULL;
-
-	Assert(hook_version == PQAUTHDATA_OAUTH_BEARER_TOKEN ||
-		   hook_version == PQAUTHDATA_OAUTH_BEARER_TOKEN_V2);
-
-	if (no_hook || type != hook_version)
-		return 0;
-
-	req = data;
-	if (type == PQAUTHDATA_OAUTH_BEARER_TOKEN_V2)
-		req2 = data;
-
-	if (hang_forever)
-	{
-		/* Start asynchronous processing. */
-		req->async = async_cb;
-		return 1;
-	}
-
-	if (misbehave_mode)
-	{
-		if (strcmp(misbehave_mode, "no-hook") != 0)
-			req->async = misbehave_cb;
-		return 1;
-	}
-
-	if (expected_uri)
-	{
-		if (!req->openid_configuration)
-		{
-			fprintf(stderr, "expected URI \"%s\", got NULL\n", expected_uri);
-			return -1;
-		}
-
-		if (strcmp(expected_uri, req->openid_configuration) != 0)
-		{
-			fprintf(stderr, "expected URI \"%s\", got \"%s\"\n", expected_uri, req->openid_configuration);
-			return -1;
-		}
-	}
-
-	if (expected_scope)
-	{
-		if (!req->scope)
-		{
-			fprintf(stderr, "expected scope \"%s\", got NULL\n", expected_scope);
-			return -1;
-		}
-
-		if (strcmp(expected_scope, req->scope) != 0)
-		{
-			fprintf(stderr, "expected scope \"%s\", got \"%s\"\n", expected_scope, req->scope);
-			return -1;
-		}
-	}
-
-	if (expected_issuer)
-	{
-		if (!req2)
-		{
-			fprintf(stderr, "--expected-issuer cannot be combined with -v1\n");
-			return -1;
-		}
-
-		if (!req2->issuer)
-		{
-			fprintf(stderr, "expected issuer \"%s\", got NULL\n", expected_issuer);
-			return -1;
-		}
-
-		if (strcmp(expected_issuer, req2->issuer) != 0)
-		{
-			fprintf(stderr, "expected issuer \"%s\", got \"%s\"\n", expected_issuer, req2->issuer);
-			return -1;
-		}
-	}
-
-	if (errmsg)
-	{
-		if (token)
-		{
-			fprintf(stderr, "--error cannot be combined with --token\n");
-			return -1;
-		}
-		else if (!req2)
-		{
-			fprintf(stderr, "--error cannot be combined with -v1\n");
-			return -1;
-		}
-
-		req2->error = errmsg;
-		return -1;
-	}
-
-	req->token = token;
-	return 1;
-}
-
-static PostgresPollingStatusType
-async_cb(PGconn *conn, PGoauthBearerRequest *req, pgsocket *altsock)
-{
-	if (hang_forever)
-	{
-		/*
-		 * This code tests that nothing is interfering with libpq's handling
-		 * of connect_timeout.
-		 */
-		static pgsocket sock = PGINVALID_SOCKET;
-
-		if (sock == PGINVALID_SOCKET)
-		{
-			/* First call. Create an unbound socket to wait on. */
-#ifdef WIN32
-			WSADATA		wsaData;
-			int			err;
-
-			err = WSAStartup(MAKEWORD(2, 2), &wsaData);
-			if (err)
-			{
-				perror("WSAStartup failed");
-				return PGRES_POLLING_FAILED;
-			}
-#endif
-			sock = socket(AF_INET, SOCK_DGRAM, 0);
-			if (sock == PGINVALID_SOCKET)
-			{
-				perror("failed to create datagram socket");
-				return PGRES_POLLING_FAILED;
-			}
-		}
-
-		/* Make libpq wait on the (unreadable) socket. */
-		*altsock = sock;
-		return PGRES_POLLING_READING;
-	}
-
-	req->token = token;
-	return PGRES_POLLING_OK;
-}
-
-static PostgresPollingStatusType
-misbehave_cb(PGconn *conn, PGoauthBearerRequest *req, pgsocket *altsock)
-{
-	if (strcmp(misbehave_mode, "fail-async") == 0)
-	{
-		/* Just fail "normally". */
-		if (errmsg)
-		{
-			PGoauthBearerRequestV2 *req2;
-
-			if (hook_version == PQAUTHDATA_OAUTH_BEARER_TOKEN)
-			{
-				fprintf(stderr, "--error cannot be combined with -v1\n");
-				exit(1);
-			}
-
-			req2 = (PGoauthBearerRequestV2 *) req;
-			req2->error = errmsg;
-		}
-
-		return PGRES_POLLING_FAILED;
-	}
-	else if (strcmp(misbehave_mode, "no-token") == 0)
-	{
-		/* Callbacks must assign req->token before returning OK. */
-		return PGRES_POLLING_OK;
-	}
-	else if (strcmp(misbehave_mode, "no-socket") == 0)
-	{
-		/* Callbacks must assign *altsock before asking for polling. */
-		return PGRES_POLLING_READING;
-	}
-	else
-	{
-		fprintf(stderr, "unrecognized --misbehave mode: %s\n", misbehave_mode);
-		exit(1);
-	}
-}
diff --git a/src/test/modules/oauth_validator/oauth_test_common.c b/src/test/modules/oauth_validator/oauth_test_common.c
new file mode 100644
index 00000000000..eba8c32eace
--- /dev/null
+++ b/src/test/modules/oauth_validator/oauth_test_common.c
@@ -0,0 +1,374 @@
+/*-------------------------------------------------------------------------
+ *
+ * oauth_test_common.c
+ *	  Shared functionality for oauth_hook_client and oauth_flow
+ *
+ * Copyright (c) 2025, PostgreSQL Global Development Group
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#include "postgres_fe.h"
+
+#include <sys/socket.h>
+
+#include "getopt_long.h"
+#include "libpq-fe.h"
+#include "pqexpbuffer.h"
+
+#include "oauth_test_common.h"
+
+static PostgresPollingStatusType async_cb(PGconn *conn,
+										  PGoauthBearerRequest *req,
+										  pgsocket *altsock);
+static PostgresPollingStatusType misbehave_cb(PGconn *conn,
+											  PGoauthBearerRequest *req,
+											  pgsocket *altsock);
+
+/* --options */
+static bool no_hook = false;
+static bool hang_forever = false;
+static const char *expected_uri = NULL;
+static const char *expected_issuer = NULL;
+static const char *expected_scope = NULL;
+static const char *misbehave_mode = NULL;
+static char *token = NULL;
+static char *errmsg = NULL;
+static int	hook_version = PQAUTHDATA_OAUTH_BEARER_TOKEN_V2;
+
+/*
+ * XXX: stress_async is exported for the benefit of oauth_hook_client. Since
+ * we only use public headers (libpq-fe.h) for oauth_flow, it needs to be an int
+ * rather than a bool.
+ */
+int			stress_async = false;
+
+static void
+usage(char *argv[])
+{
+	printf("usage: %s [flags] CONNINFO\n\n", argv[0]);
+
+	printf("recognized flags:\n");
+	printf("  -h, --help              show this message\n");
+	printf("  -v VERSION              select the hook API version (default 2)\n");
+	printf("  --expected-scope SCOPE  fail if received scopes do not match SCOPE\n");
+	printf("  --expected-uri URI      fail if received configuration link does not match URI\n");
+	printf("  --expected-issuer ISS   fail if received issuer does not match ISS (v2 only)\n");
+	printf("  --misbehave=MODE        have the hook fail required postconditions\n"
+		   "                          (MODEs: no-hook, fail-async, no-token, no-socket)\n");
+	printf("  --no-hook               don't install OAuth hooks\n");
+	printf("  --hang-forever          don't ever return a token (combine with connect_timeout)\n");
+	printf("  --token TOKEN           use the provided TOKEN value\n");
+	printf("  --error ERRMSG          fail instead, with the given ERRMSG (v2 only)\n");
+	printf("  --stress-async          busy-loop on PQconnectPoll rather than polling\n");
+}
+
+char *
+oauth_test_parse_argv(int argc, char *argv[], int for_plugin)
+{
+	static const struct option long_options[] = {
+		{"help", no_argument, NULL, 'h'},
+
+		{"expected-scope", required_argument, NULL, 1000},
+		{"expected-uri", required_argument, NULL, 1001},
+		{"no-hook", no_argument, NULL, 1002},
+		{"token", required_argument, NULL, 1003},
+		{"hang-forever", no_argument, NULL, 1004},
+		{"misbehave", required_argument, NULL, 1005},
+		{"stress-async", no_argument, NULL, 1006},
+		{"expected-issuer", required_argument, NULL, 1007},
+		{"error", required_argument, NULL, 1008},
+		{0}
+	};
+
+	int			c;
+
+	if (for_plugin)
+	{
+		/* The "real" argv has already been parsed. Reset optind. */
+		optind = 1;
+	}
+
+	while ((c = getopt_long(argc, argv, "hv:", long_options, NULL)) != -1)
+	{
+		switch (c)
+		{
+			case 'h':
+				usage(argv);
+				exit(0);
+
+			case 'v':
+				if (strcmp(optarg, "1") == 0)
+					hook_version = PQAUTHDATA_OAUTH_BEARER_TOKEN;
+				else if (strcmp(optarg, "2") == 0)
+					hook_version = PQAUTHDATA_OAUTH_BEARER_TOKEN_V2;
+				else
+				{
+					usage(argv);
+					exit(1);
+				}
+				break;
+
+			case 1000:			/* --expected-scope */
+				expected_scope = optarg;
+				break;
+
+			case 1001:			/* --expected-uri */
+				expected_uri = optarg;
+				break;
+
+			case 1002:			/* --no-hook */
+				no_hook = true;
+				break;
+
+			case 1003:			/* --token */
+				token = optarg;
+				break;
+
+			case 1004:			/* --hang-forever */
+				hang_forever = true;
+				break;
+
+			case 1005:			/* --misbehave */
+				misbehave_mode = optarg;
+				break;
+
+			case 1006:			/* --stress-async */
+				stress_async = true;
+				break;
+
+			case 1007:			/* --expected-issuer */
+				expected_issuer = optarg;
+				break;
+
+			case 1008:			/* --error */
+				errmsg = optarg;
+				break;
+
+			default:
+				usage(argv);
+				exit(1);
+		}
+	}
+
+	if (argc != (for_plugin ? optind : optind + 1))
+	{
+		usage(argv);
+		exit(1);
+	}
+
+	return argv[optind];
+}
+
+/*
+ * PQauthDataHook implementation. Replaces the default client flow by handling
+ * PQAUTHDATA_OAUTH_BEARER_TOKEN[_V2].
+ */
+int
+oauth_test_authdata_hook(PGauthData type, PGconn *conn, void *data)
+{
+	PGoauthBearerRequest *req;
+	PGoauthBearerRequestV2 *req2 = NULL;
+
+	Assert(hook_version == PQAUTHDATA_OAUTH_BEARER_TOKEN ||
+		   hook_version == PQAUTHDATA_OAUTH_BEARER_TOKEN_V2);
+
+	if (no_hook || type != hook_version)
+		return 0;
+
+	req = data;
+	if (type == PQAUTHDATA_OAUTH_BEARER_TOKEN_V2)
+		req2 = data;
+
+	if (hang_forever)
+	{
+		/* Start asynchronous processing. */
+		req->async = async_cb;
+		return 1;
+	}
+
+	if (misbehave_mode)
+	{
+		if (strcmp(misbehave_mode, "no-hook") != 0)
+			req->async = misbehave_cb;
+		return 1;
+	}
+
+	if (expected_uri)
+	{
+		if (!req->openid_configuration)
+		{
+			fprintf(stderr, "expected URI \"%s\", got NULL\n", expected_uri);
+			return -1;
+		}
+
+		if (strcmp(expected_uri, req->openid_configuration) != 0)
+		{
+			fprintf(stderr, "expected URI \"%s\", got \"%s\"\n", expected_uri, req->openid_configuration);
+			return -1;
+		}
+	}
+
+	if (expected_scope)
+	{
+		if (!req->scope)
+		{
+			fprintf(stderr, "expected scope \"%s\", got NULL\n", expected_scope);
+			return -1;
+		}
+
+		if (strcmp(expected_scope, req->scope) != 0)
+		{
+			fprintf(stderr, "expected scope \"%s\", got \"%s\"\n", expected_scope, req->scope);
+			return -1;
+		}
+	}
+
+	if (expected_issuer)
+	{
+		if (!req2)
+		{
+			fprintf(stderr, "--expected-issuer cannot be combined with -v1\n");
+			return -1;
+		}
+
+		if (!req2->issuer)
+		{
+			fprintf(stderr, "expected issuer \"%s\", got NULL\n", expected_issuer);
+			return -1;
+		}
+
+		if (strcmp(expected_issuer, req2->issuer) != 0)
+		{
+			fprintf(stderr, "expected issuer \"%s\", got \"%s\"\n", expected_issuer, req2->issuer);
+			return -1;
+		}
+	}
+
+	if (errmsg)
+	{
+		if (token)
+		{
+			fprintf(stderr, "--error cannot be combined with --token\n");
+			return -1;
+		}
+		else if (!req2)
+		{
+			fprintf(stderr, "--error cannot be combined with -v1\n");
+			return -1;
+		}
+
+		req2->error = errmsg;
+		return -1;
+	}
+
+	req->token = token;
+	return 1;
+}
+
+/*
+ * Sets up a request for a plugin module (pg_start_oauthbearer()) rather than
+ * using the hook.
+ */
+int
+oauth_test_start_flow(PGconn *conn, PGoauthBearerRequestV2 *request)
+{
+	int			ret;
+
+	/*
+	 * We can still defer to the hook above to avoid copying code; we just
+	 * have to translate the return value.
+	 */
+	ret = oauth_test_authdata_hook(PQAUTHDATA_OAUTH_BEARER_TOKEN_V2, conn,
+								   request);
+
+	if (ret == 0)
+	{
+		/* This is a bug in the test. */
+		fprintf(stderr, "plugin tests cannot make use of -v1 or --no-hook\n");
+		exit(1);
+	}
+
+	return (ret == 1) ? 0 : -1;
+}
+
+static PostgresPollingStatusType
+async_cb(PGconn *conn, PGoauthBearerRequest *req, pgsocket *altsock)
+{
+	if (hang_forever)
+	{
+		/*
+		 * This code tests that nothing is interfering with libpq's handling
+		 * of connect_timeout.
+		 */
+		static pgsocket sock = PGINVALID_SOCKET;
+
+		if (sock == PGINVALID_SOCKET)
+		{
+			/* First call. Create an unbound socket to wait on. */
+#ifdef WIN32
+			WSADATA		wsaData;
+			int			err;
+
+			err = WSAStartup(MAKEWORD(2, 2), &wsaData);
+			if (err)
+			{
+				perror("WSAStartup failed");
+				return PGRES_POLLING_FAILED;
+			}
+#endif
+			sock = socket(AF_INET, SOCK_DGRAM, 0);
+			if (sock == PGINVALID_SOCKET)
+			{
+				perror("failed to create datagram socket");
+				return PGRES_POLLING_FAILED;
+			}
+		}
+
+		/* Make libpq wait on the (unreadable) socket. */
+		*altsock = sock;
+		return PGRES_POLLING_READING;
+	}
+
+	req->token = token;
+	return PGRES_POLLING_OK;
+}
+
+static PostgresPollingStatusType
+misbehave_cb(PGconn *conn, PGoauthBearerRequest *req, pgsocket *altsock)
+{
+	if (strcmp(misbehave_mode, "fail-async") == 0)
+	{
+		/* Just fail "normally". */
+		if (errmsg)
+		{
+			PGoauthBearerRequestV2 *req2;
+
+			if (hook_version == PQAUTHDATA_OAUTH_BEARER_TOKEN)
+			{
+				fprintf(stderr, "--error cannot be combined with -v1\n");
+				exit(1);
+			}
+
+			req2 = (PGoauthBearerRequestV2 *) req;
+			req2->error = errmsg;
+		}
+
+		return PGRES_POLLING_FAILED;
+	}
+	else if (strcmp(misbehave_mode, "no-token") == 0)
+	{
+		/* Callbacks must assign req->token before returning OK. */
+		return PGRES_POLLING_OK;
+	}
+	else if (strcmp(misbehave_mode, "no-socket") == 0)
+	{
+		/* Callbacks must assign *altsock before asking for polling. */
+		return PGRES_POLLING_READING;
+	}
+	else
+	{
+		fprintf(stderr, "unrecognized --misbehave mode: %s\n", misbehave_mode);
+		exit(1);
+	}
+}
diff --git a/src/test/modules/oauth_validator/t/002_client.pl b/src/test/modules/oauth_validator/t/002_client.pl
index 12af35b7d96..b50451efb74 100644
--- a/src/test/modules/oauth_validator/t/002_client.pl
+++ b/src/test/modules/oauth_validator/t/002_client.pl
@@ -1,6 +1,6 @@
 #
 # Exercises the API for custom OAuth client flows, using the oauth_hook_client
-# test driver.
+# test driver and the oauth_flow custom plugin.
 #
 # Copyright (c) 2021-2026, PostgreSQL Global Development Group
 #
@@ -20,6 +20,10 @@ if (!$ENV{PG_TEST_EXTRA} || $ENV{PG_TEST_EXTRA} !~ /\boauth\b/)
 	  'Potentially unsafe test oauth not enabled in PG_TEST_EXTRA';
 }
 
+my $plugin_supported = (
+		 check_pg_config("#define HAVE_SYS_EVENT_H 1")
+	  or check_pg_config("#define HAVE_SYS_EPOLL_H 1"));
+
 #
 # Cluster Setup
 #
@@ -72,6 +76,8 @@ sub test
 		$flags = $params{flags};
 	}
 
+	# First run the oauth_hook_client, which uses PQauthDataHook to insert a new
+	# OAuth flow.
 	my @cmd = ("oauth_hook_client", @{$flags}, $common_connstr);
 	note "running '" . join("' '", @cmd) . "'";
 
@@ -103,6 +109,37 @@ sub test
 		$node->log_check("$test_name: log matches",
 			$log_start, log_like => $params{log_like});
 	}
+
+  SKIP:
+	{
+		last SKIP if $params{hook_only};
+		skip "OAuth modules are not supported on this platform"
+		  unless $plugin_supported;
+
+		# Run the same test with psql itself, loading the oauth_flow.so module.
+		local $ENV{PGOAUTHMODULE} = $ENV{flow_module_path};
+
+		# Flags are passed to the module via OAUTH_TEST_FLAGS, with 0x01 as a
+		# separator.
+		local $ENV{OAUTH_TEST_FLAGS} = join("\x01", @{$flags});
+
+		if ($params{expect_success})
+		{
+			$node->connect_ok(
+				$common_connstr,
+				"[plugin flow] $test_name",
+				expected_stderr => $params{expected_stderr},
+				log_like => $params{log_like});
+		}
+		else
+		{
+			$node->connect_fails(
+				$common_connstr,
+				"[plugin flow] $test_name",
+				expected_stderr => $params{expected_stderr},
+				log_like => $params{log_like});
+		}
+	}
 }
 
 test(
@@ -119,6 +156,7 @@ test(
 # Make sure the v1 hook continues to work.
 test(
 	"v1 synchronous hook can provide a token",
+	hook_only => 1,    # plugins don't support API v1
 	flags => [
 		"-v1",
 		"--token" => "my-token-v1",
@@ -133,6 +171,7 @@ if ($ENV{with_libcurl} ne 'yes')
 	# libpq should help users out if no OAuth support is built in.
 	test(
 		"fails without custom hook installed",
+		hook_only => 1,    # plugins can't use --no-hook
 		flags => ["--no-hook"],
 		expected_stderr =>
 		  qr/no OAuth flows are available \(try installing the libpq-oauth package\)/
@@ -197,4 +236,19 @@ test(
 	expected_stderr =>
 	  qr/user-defined OAuth flow failed: async error message/);
 
+SKIP:
+{
+	skip "OAuth modules are not supported on this platform"
+	  unless $plugin_supported;
+
+	# Make sure a misaimed PGOAUTHMODULE gives the correct error message.
+	local $ENV{PGOAUTHMODULE} = $node->basedir . '/nonexistent.so';
+
+	$node->connect_fails(
+		$common_connstr,
+		"PGOAUTHMODULE error messages",
+		expected_stderr =>
+		  qr/user-defined OAuth flow failed: plugin could not be loaded/);
+}
+
 done_testing();
-- 
2.34.1



view thread (2+ messages)  latest in thread

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: [email protected]
  Cc: [email protected], [email protected], [email protected]
  Subject: Re: [oauth] Stabilize the libpq-oauth ABI (and allow alternative implementations?)
  In-Reply-To: <CAOYmi+mEU_q9sr1PMmE-4rLwFN=OjyndDwFZvpsMU3RNJLrM9g@mail.gmail.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox