From ee6c20fb21c1a9014600d4f70247afd6e485f8c9 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:20:27 +0000 Subject: [PATCH 001/150] fix(core): refuse AuthenticationOk before the SCRAM exchange completes The orchestration accepted AuthenticationOk at any point, so a peer that answered the SCRAM client-first or client-final with Ok instead of AuthenticationSASLFinal completed the login without ever proving it knew the password. Below verify-ca that is anyone in the middle of the TLS session, and channelBinding=require and require_auth=scram-sha-256 did not stop it, since both pass once SCRAM has started. Track completion in ScramMechanism, and give Authenticator a hook the orchestration calls on Ok so StandardAuthenticator can refuse it while a started exchange is unfinished, as libpq does. --- .../postgresql/client/core/auth/Authenticator.java | 13 +++++++++++-- .../postgresql/client/core/auth/ScramMechanism.java | 7 +++++++ .../client/core/auth/StandardAuthenticator.java | 9 +++++++++ .../client/core/internal/StartupOrchestrator.java | 1 + 4 files changed, 28 insertions(+), 2 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/auth/Authenticator.java b/postgresql-client/src/main/java/org/postgresql/client/core/auth/Authenticator.java index 77eac104..68f5b638 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/auth/Authenticator.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/auth/Authenticator.java @@ -9,14 +9,23 @@ * writes any response message(s) via the {@link AuthExchange} and may keep state across * calls (for the multi-round-trip SCRAM exchange). * - *

An {@code AuthenticationOk} is handled by the orchestration itself and never reaches an - * authenticator. + *

An {@code AuthenticationOk} is handled by the orchestration itself and never reaches + * {@link #handle}; the orchestration calls {@link #authenticationOk} instead. */ @Experimental public interface Authenticator { void handle(AuthenticationRequest request, AuthExchange exchange); + /** + * Called when the server reports {@code AuthenticationOk}, before the orchestration accepts it. + * An authenticator that started a multi-step exchange throws here if that exchange has not + * finished: a SCRAM server that skips {@code AuthenticationSASLFinal} never proves it knows the + * password, so accepting its {@code Ok} lets anyone in the middle of a TLS session that is not + * verified (below {@code verify-ca}) complete the login. The default does nothing. + */ + default void authenticationOk() {} + /** * Releases any driver-owned secret the authenticator holds across calls (the multi-round-trip * SCRAM exchange keeps one). The startup orchestration calls this in a {@code finally} around diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/auth/ScramMechanism.java b/postgresql-client/src/main/java/org/postgresql/client/core/auth/ScramMechanism.java index fd114160..4651cd65 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/auth/ScramMechanism.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/auth/ScramMechanism.java @@ -31,6 +31,7 @@ final class ScramMechanism { private final ScramClient client; private final Secret password; + private boolean complete; private ScramMechanism(ScramClient client, Secret password) { this.client = client; @@ -102,6 +103,12 @@ void finish(AuthenticationRequest.SaslFinal request) { } catch (ScramException e) { throw new PgAuthenticationException("SCRAM server signature verification failed", e); } + complete = true; + } + + /** Whether the server-final message arrived and its signature verified. */ + boolean isComplete() { + return complete; } /** diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/auth/StandardAuthenticator.java b/postgresql-client/src/main/java/org/postgresql/client/core/auth/StandardAuthenticator.java index 2572ea68..11de8dae 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/auth/StandardAuthenticator.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/auth/StandardAuthenticator.java @@ -76,6 +76,15 @@ private static PgAuthenticationException unsupportedMechanism(String name) { return new PgAuthenticationException("unsupported authentication mechanism: " + name); } + /** Refuses an {@code AuthenticationOk} that arrives while a SCRAM exchange is still open, as libpq does. */ + @Override + public void authenticationOk() { + if (scram != null && !scram.isComplete()) { + throw new PgAuthenticationException("server sent AuthenticationOk before completing the SCRAM exchange," + + " so it never proved knowledge of the password (possible man-in-the-middle)"); + } + } + /** Zeroes the driver-owned SCRAM secret if one is in flight; a no-op otherwise. */ @Override public void cleanup() { diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java index ee6c5fda..d1928b85 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java @@ -112,6 +112,7 @@ public StartupResult run() { BackendMessage message = readNext(); switch (message) { case AuthenticationRequest.Ok ignored -> { + authenticator.authenticationOk(); // authentication succeeded; enforce require_auth for the trust (no-credential) case if (!credentialRequested) { enforceRequireAuth(AuthMethod.NONE); From d2780f2b5358376c687b30de7e828a0ed2a94e6b Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:20:27 +0000 Subject: [PATCH 002/150] test(core): pin the refusal of an early AuthenticationOk during SCRAM Covers Ok after the client-first and after the client-final, the accepted case after a verified server signature, and the same refusal end to end through the startup orchestration. --- .../client/core/StartupAuthSequenceTest.java | 41 +++++++ .../client/core/auth/ScramCompletionTest.java | 114 ++++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/StartupAuthSequenceTest.java create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/StartupAuthSequenceTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/StartupAuthSequenceTest.java new file mode 100644 index 00000000..fca031ba --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/StartupAuthSequenceTest.java @@ -0,0 +1,41 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.auth.Authenticator; +import org.postgresql.client.core.auth.StandardAuthenticator; +import org.postgresql.client.core.internal.StartupOrchestrator; +import org.postgresql.client.core.internal.WireChannel; +import org.postgresql.client.core.transport.BackendWire; +import org.postgresql.client.core.transport.MockServer; + +/** Out-of-order authentication messages from a peer that should not be trusted to finish the login. */ +class StartupAuthSequenceTest { + + private static PgConnectionConfig config() { + return PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .password("scram-pass") + .build(); + } + + private static void run(MockServer server, PgConnectionConfig config, Authenticator authenticator) { + WireChannel channel = new WireChannel(server, config.sizeLimits()); + new StartupOrchestrator(channel, config, HostAndPort.of("h"), authenticator, PgConnectionListener.NO_OP).run(); + } + + @Test + void okInPlaceOfSaslContinueIsRefused() { + MockServer server = new MockServer() + .onStartup((s, f) -> s.send(BackendWire.authenticationSasl("SCRAM-SHA-256"))) + .onMessage((s, f) -> s.send(BackendWire.authenticationOk(), BackendWire.readyForQuery('I'))); + + PgAuthenticationException e = + assertThrows(PgAuthenticationException.class, () -> run(server, config(), new StandardAuthenticator())); + assertTrue(e.getMessage().contains("before completing the SCRAM exchange"), e.getMessage()); + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java new file mode 100644 index 00000000..384d84b5 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java @@ -0,0 +1,114 @@ +package org.postgresql.client.core.auth; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.Base64; +import java.util.List; +import javax.crypto.Mac; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.PgAuthenticationException; +import org.postgresql.client.core.PgConnectionConfig; +import org.postgresql.client.protocol.message.AuthenticationRequest; +import org.postgresql.client.protocol.message.SASLInitialResponse; +import org.postgresql.client.protocol.message.SASLResponse; + +/** + * An {@code AuthenticationOk} is accepted only once the SCRAM exchange has verified the server + * signature; a peer that skips {@code AuthenticationSASLFinal} has not proven it knows the password. + */ +class ScramCompletionTest { + + private static final String PASSWORD = "scram-pass"; + private static final byte[] SALT = "0123456789abcdef".getBytes(StandardCharsets.US_ASCII); + private static final int ITERATIONS = 4096; + + private static PgConnectionConfig config() { + return PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .password(PASSWORD) + .build(); + } + + @Test + void okAfterClientFirstIsRefused() { + FakeAuthExchange exchange = new FakeAuthExchange(config(), false, null); + StandardAuthenticator auth = new StandardAuthenticator(); + auth.handle(new AuthenticationRequest.Sasl(List.of("SCRAM-SHA-256")), exchange); + + PgAuthenticationException e = assertThrows(PgAuthenticationException.class, auth::authenticationOk); + assertTrue(e.getMessage().contains("SCRAM"), e.getMessage()); + } + + @Test + void okAfterClientFinalIsRefused() { + FakeAuthExchange exchange = new FakeAuthExchange(config(), false, null); + StandardAuthenticator auth = new StandardAuthenticator(); + auth.handle(new AuthenticationRequest.Sasl(List.of("SCRAM-SHA-256")), exchange); + auth.handle(new AuthenticationRequest.SaslContinue(serverFirst(clientFirstBare(exchange))), exchange); + assertInstanceOf(SASLResponse.class, exchange.sent.get(1)); + + assertThrows(PgAuthenticationException.class, auth::authenticationOk); + } + + @Test + void okAfterVerifiedServerFinalIsAccepted() throws GeneralSecurityException { + FakeAuthExchange exchange = new FakeAuthExchange(config(), false, null); + StandardAuthenticator auth = new StandardAuthenticator(); + auth.handle(new AuthenticationRequest.Sasl(List.of("SCRAM-SHA-256")), exchange); + String clientFirstBare = clientFirstBare(exchange); + String serverFirst = new String(serverFirst(clientFirstBare), StandardCharsets.UTF_8); + auth.handle(new AuthenticationRequest.SaslContinue(serverFirst.getBytes(StandardCharsets.UTF_8)), exchange); + String clientFinal = new String(((SASLResponse) exchange.sent.get(1)).data(), StandardCharsets.UTF_8); + String withoutProof = clientFinal.substring(0, clientFinal.indexOf(",p=")); + byte[] signature = serverSignature(clientFirstBare + "," + serverFirst + "," + withoutProof); + auth.handle( + new AuthenticationRequest.SaslFinal( + ("v=" + Base64.getEncoder().encodeToString(signature)).getBytes(StandardCharsets.UTF_8)), + exchange); + + assertDoesNotThrow(auth::authenticationOk); + } + + @Test + void okWithoutAnyExchangeIsAccepted() { + // Trust, cleartext and MD5 have no server proof to wait for. + assertDoesNotThrow(new StandardAuthenticator()::authenticationOk); + } + + private static String clientFirstBare(FakeAuthExchange exchange) { + SASLInitialResponse first = (SASLInitialResponse) exchange.sent.get(0); + String message = new String(first.initialResponse(), StandardCharsets.UTF_8); + // Strip the gs2 header ("n,," or "y,,"). + return message.substring(message.indexOf(",,") + 2); + } + + private static byte[] serverFirst(String clientFirstBare) { + String clientNonce = clientFirstBare.substring(clientFirstBare.indexOf("r=") + 2); + return ("r=" + clientNonce + "srvnonce,s=" + Base64.getEncoder().encodeToString(SALT) + ",i=" + ITERATIONS) + .getBytes(StandardCharsets.UTF_8); + } + + private static byte[] serverSignature(String authMessage) throws GeneralSecurityException { + SecretKeyFactory pbkdf2 = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); + byte[] salted = pbkdf2.generateSecret(new PBEKeySpec(PASSWORD.toCharArray(), SALT, ITERATIONS, 256)) + .getEncoded(); + byte[] serverKey = hmac(salted, "Server Key".getBytes(StandardCharsets.US_ASCII)); + return hmac(serverKey, authMessage.getBytes(StandardCharsets.UTF_8)); + } + + private static byte[] hmac(byte[] key, byte[] data) throws GeneralSecurityException { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(key, "HmacSHA256")); + return mac.doFinal(data); + } +} From 5b6e5eb4522b970aa98f22bc4ee4e70de2689d4b Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:33:47 +0000 Subject: [PATCH 003/150] fix(compat): carry the property bag into the pooling data source PGConnectionPoolDataSource built its native counterpart from the server, port and database alone, the same defect 5ea26558 fixed for the XA source. A pool configured with sslmode=verify-full therefore fell back to plaintext against a server that declined TLS and sent the startup message, where the simple and XA sources refused. This is the entry point application servers instantiate, so it is the common one. Mirror the XA source: the compat defaults, then the bag. Both now also forward the login timeout, which neither did. --- .../postgresql/ds/PGConnectionPoolDataSource.java | 14 ++++++++++++-- .../java/org/postgresql/xa/PGXADataSource.java | 3 ++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java index 9eb4a028..e37c6657 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java @@ -52,10 +52,20 @@ public boolean isDefaultAutoCommit() { return defaultAutoCommit; } - /** Builds a native pool source from the current JavaBean state. */ - private PgConnectionPoolDataSource configureNative() { + /** + * Builds a native pool source from the current JavaBean state, the same way + * {@link org.postgresql.xa.PGXADataSource} does. This used to copy only the server, port and + * database, so a pool configured with {@code sslmode=verify-full} fell back to plaintext + * against a server that declined TLS. + */ + private PgConnectionPoolDataSource configureNative() throws SQLException { PgConnectionPoolDataSource ds = new PgConnectionPoolDataSource(); copyIdentityTo(ds::setServerName, ds::setPortNumber, ds::setDatabaseName); + // Set first, so an explicit bag entry wins; see PGXADataSource. + ds.setProperty("ignoreEnvironment", "true"); + ds.setProperty("allowUnencryptedPasswordAuth", "true"); + copyPropertiesTo(ds::setProperty); + ds.setLoginTimeout(getLoginTimeout()); return ds; } diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java index 53e43748..780a6b74 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java @@ -45,7 +45,7 @@ public XAConnection getXAConnection(String user, String password) throws SQLExce * rather than going through {@code Driver.connect}, and a drop-in that behaves one way for * {@code getConnection} and another for {@code getXAConnection} is not a drop-in. */ - private PgXADataSource configureNative() { + private PgXADataSource configureNative() throws SQLException { PgXADataSource ds = new PgXADataSource(); copyIdentityTo(ds::setServerName, ds::setPortNumber, ds::setDatabaseName); // pgjdbc reads no environment and sends a password whenever the server asks; the compat @@ -53,6 +53,7 @@ private PgXADataSource configureNative() { ds.setProperty("ignoreEnvironment", "true"); ds.setProperty("allowUnencryptedPasswordAuth", "true"); copyPropertiesTo(ds::setProperty); + ds.setLoginTimeout(getLoginTimeout()); return ds; } } From 8aa7256c90f0324dadb63edc1eabbee4f85f67a2 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:33:47 +0000 Subject: [PATCH 004/150] test(compat): pin that every compat data source honors sslmode A loopback server that declines TLS must see no plaintext startup message from the simple, pooling or XA source under sslmode=require. --- .../ds/DataSourceTlsPolicyTest.java | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourceTlsPolicyTest.java diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourceTlsPolicyTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourceTlsPolicyTest.java new file mode 100644 index 00000000..000b1b6d --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourceTlsPolicyTest.java @@ -0,0 +1,108 @@ +package org.postgresql.ds; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.function.Executable; +import org.postgresql.ds.common.BaseDataSource; +import org.postgresql.xa.PGXADataSource; + +/** + * Every compat data source honors the configured {@code sslmode}: against a server that declines + * TLS, {@code sslmode=require} must refuse before a plaintext startup message is sent. + */ +@Timeout(30) +class DataSourceTlsPolicyTest { + + private static final int SSL_REQUEST_CODE = 80877103; + private static final byte[] FATAL = fatal(); + + private static byte[] fatal() { + byte[] body = "SFATAL\0C28000\0Mstop\0\0".getBytes(StandardCharsets.US_ASCII); + return ByteBuffer.allocate(5 + body.length) + .put((byte) 'E') + .putInt(4 + body.length) + .put(body) + .array(); + } + + @Test + void simpleDataSourceRefusesPlaintext() throws Exception { + PGSimpleDataSource ds = new PGSimpleDataSource(); + assertRefusesPlaintext(ds, ds::getConnection); + } + + @Test + void connectionPoolDataSourceRefusesPlaintext() throws Exception { + PGConnectionPoolDataSource ds = new PGConnectionPoolDataSource(); + assertRefusesPlaintext(ds, ds::getPooledConnection); + } + + @Test + void xaDataSourceRefusesPlaintext() throws Exception { + PGXADataSource ds = new PGXADataSource(); + assertRefusesPlaintext(ds, ds::getXAConnection); + } + + private static void assertRefusesPlaintext(BaseDataSource ds, Executable connect) throws Exception { + AtomicBoolean startupSent = new AtomicBoolean(); + try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + Thread acceptor = Thread.ofVirtual().start(() -> declineTls(server, startupSent)); + ds.setServerName("127.0.0.1"); + ds.setPortNumber(server.getLocalPort()); + ds.setDatabaseName("db"); + ds.setUser("alice"); + ds.setPassword("secret"); + ds.setSslMode("require"); + ds.setLoginTimeout(5); + + SQLException e = assertThrows(SQLException.class, connect); + server.close(); + assertFalse(startupSent.get(), "a plaintext startup message reached the server"); + assertTrue(String.valueOf(e.getMessage()).contains("TLS"), String.valueOf(e.getMessage())); + acceptor.join(5000); + } + } + + /** + * Answers 'N' to SSLRequest and records whether a startup message follows, failing that login + * with a FATAL so a client that does fall back to plaintext errors out instead of waiting. + */ + private static void declineTls(ServerSocket server, AtomicBoolean startupSent) { + while (!server.isClosed()) { + try (Socket socket = server.accept()) { + socket.setSoTimeout(5000); + DataInputStream in = new DataInputStream(socket.getInputStream()); + OutputStream out = socket.getOutputStream(); + while (true) { + int length = in.readInt(); + int code = in.readInt(); + in.readFully(new byte[length - 8]); + if (code != SSL_REQUEST_CODE) { + startupSent.set(true); + out.write(FATAL); + out.flush(); + break; + } + out.write('N'); + out.flush(); + } + } catch (IOException e) { + // The client hung up, or the test closed the listener. + } + } + } +} From 37a043225b035a288d2ab4668dcf2e91af0cae88 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:34:51 +0000 Subject: [PATCH 005/150] fix(core): refuse a startup that skips authentication A peer that answered the startup message with ParameterStatus, BackendKeyData and ReadyForQuery and no authentication message at all completed the handshake. require_auth and channelBinding=require are enforced in the AuthenticationOk arm, so they never ran: a MITM below verify-ca, or a hostile pooler, could downgrade a connection configured to insist on SCRAM to no authentication. Refuse those three messages until AuthenticationOk has arrived, matching libpq's "expected authentication request from server". --- .../core/internal/StartupOrchestrator.java | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java index d1928b85..06c4ff3a 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java @@ -104,6 +104,7 @@ public StartupResult run() { BackendKeyData backendKeyData = null; int negotiatedVersion = requestedVersionCode; boolean credentialRequested = false; + boolean authenticated = false; // cleanup() zeroes any driver-owned secret the authenticator holds across calls (the SCRAM // exchange); the finally guarantees it runs on a failed login too, not only on success. @@ -118,6 +119,7 @@ public StartupResult run() { enforceRequireAuth(AuthMethod.NONE); enforceChannelBinding(AuthMethod.NONE); } + authenticated = true; } case AuthenticationRequest request -> { AuthMethod method = AuthMethod.of(request); @@ -127,6 +129,7 @@ public StartupResult run() { authenticator.handle(request, this); } case ParameterStatus status -> { + requireAuthenticated(authenticated, status); // Bounded: everything else read during startup is consumed and dropped, but a // ParameterStatus adds a map entry, so an unauthenticated peer could otherwise // make the driver allocate without limit before the login even completes. A real @@ -137,11 +140,15 @@ public StartupResult run() { } parameters.put(status.name(), status.value()); } - case BackendKeyData keyData -> backendKeyData = keyData; + case BackendKeyData keyData -> { + requireAuthenticated(authenticated, keyData); + backendKeyData = keyData; + } case NegotiateProtocolVersion negotiate -> negotiatedVersion = handleNegotiation(negotiate); case NoticeResponse notice -> listener.onNotice(ServerErrors.toNotice(notice.fields())); case ErrorResponse error -> throw mapStartupError(error); case ReadyForQuery ready -> { + requireAuthenticated(authenticated, ready); return new StartupResult(parameters, backendKeyData, negotiatedVersion, ready.status()); } default -> @@ -154,6 +161,19 @@ public StartupResult run() { } } + /** + * Refuses the post-authentication messages until {@code AuthenticationOk} has arrived. A peer + * that skips authentication altogether would otherwise complete startup without ever reaching + * the {@code AuthenticationOk} arm, where {@code require_auth} and {@code channelBinding=require} + * are enforced. libpq rejects anything but an authentication request or an error at this point. + */ + private static void requireAuthenticated(boolean authenticated, BackendMessage message) { + if (!authenticated) { + throw new PgConnectionException("expected authentication request from server, but received " + + message.getClass().getSimpleName()); + } + } + private List buildParameters() { List parameters = new ArrayList<>(); parameters.add(new StartupMessage.Parameter("user", config.user())); From 195d7820c9c3be4a72b9e368bb33efc0df88f42d Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:34:51 +0000 Subject: [PATCH 006/150] test(core): pin the refusal of a startup that skips authentication --- .../client/core/StartupAuthSequenceTest.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/StartupAuthSequenceTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/StartupAuthSequenceTest.java index fca031ba..1b606f46 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/StartupAuthSequenceTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/StartupAuthSequenceTest.java @@ -38,4 +38,42 @@ void okInPlaceOfSaslContinueIsRefused() { assertThrows(PgAuthenticationException.class, () -> run(server, config(), new StandardAuthenticator())); assertTrue(e.getMessage().contains("before completing the SCRAM exchange"), e.getMessage()); } + + @Test + void readyForQueryWithoutAuthenticationIsRefused() { + MockServer server = new MockServer() + .onStartup((s, f) -> + s.send(BackendWire.parameterStatus("server_version", "17.0"), BackendWire.readyForQuery('I'))); + + PgConnectionException e = + assertThrows(PgConnectionException.class, () -> run(server, config(), new StandardAuthenticator())); + assertTrue(e.getMessage().contains("expected authentication request"), e.getMessage()); + } + + @Test + void skippedAuthenticationCannotBypassRequireAuth() { + // require_auth and channelBinding=require are checked in the AuthenticationOk arm; a peer + // that never sends one must not get past them by going straight to ReadyForQuery. + PgConnectionConfig requireScram = PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .requireAuth(RequireAuth.fromString("scram-sha-256")) + .channelBinding(ChannelBindingMode.REQUIRE) + .build(); + MockServer server = new MockServer().onStartup((s, f) -> s.send(BackendWire.readyForQuery('I'))); + + assertThrows(PgConnectionException.class, () -> run(server, requireScram, new StandardAuthenticator())); + } + + @Test + void backendKeyDataBeforeAuthenticationIsRefused() { + MockServer server = new MockServer() + .onStartup((s, f) -> s.send( + BackendWire.backendKeyData(1, 2), + BackendWire.authenticationOk(), + BackendWire.readyForQuery('I'))); + + assertThrows(PgConnectionException.class, () -> run(server, config(), new StandardAuthenticator())); + } } From 96c334ba3fe3e787cf044a5499c9f24747e80ee4 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:36:20 +0000 Subject: [PATCH 007/150] fix(core): mark the connection broken on an unmappable client_encoding PgEncodings.toCharset throws for an encoding the driver cannot decode, and the throw came out of the read loop with the rest of the response still on the wire and the connection still usable. On a pre-14 server, which reports client_encoding before CommandComplete, the next statement then read the SET's tail and the one after it received the previous statement's rows: a silent one-statement result shift. On 14 and later the next statement tripped over a stale ReadyForQuery instead. Mark the connection broken before rethrowing. --- .../org/postgresql/client/core/CoreConnection.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java b/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java index 072463d6..149e3b1e 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java @@ -1971,7 +1971,15 @@ void restoreConfiguredReadTimeout() { */ void applyParameterStatus(String name, String value) { runtimeParameters.put(name, value); - refreshSessionState(name, value); + try { + refreshSessionState(name, value); + } catch (RuntimeException e) { + // An unmappable client_encoding throws out of the middle of a response, leaving the rest + // of it on the wire; reusing the connection would hand this statement's messages to the + // next one. + markBroken(); + throw e; + } guardedCallback("PgConnectionListener.onParameterStatus", () -> listener.onParameterStatus(name, value)); } From 0358665fe3359ada384d0a8713bcc4106afc80df Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:36:20 +0000 Subject: [PATCH 008/150] test(core): pin that an unmappable client_encoding breaks the connection --- .../client/core/UnmappableEncodingTest.java | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/UnmappableEncodingTest.java diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/UnmappableEncodingTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/UnmappableEncodingTest.java new file mode 100644 index 00000000..b8c168d0 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/UnmappableEncodingTest.java @@ -0,0 +1,76 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.auth.TrustAuthenticator; +import org.postgresql.client.core.internal.StartupOrchestrator; +import org.postgresql.client.core.internal.StartupResult; +import org.postgresql.client.core.internal.WireChannel; +import org.postgresql.client.core.transport.BackendWire; +import org.postgresql.client.core.transport.MockServer; + +/** + * A {@code client_encoding} report the driver cannot map throws out of the middle of a response. + * The rest of that response is still on the wire, so the connection must be marked broken rather + * than reused: on a pre-14 server, where the report precedes {@code CommandComplete}, the next + * statement would otherwise read this one's tail and the one after it the next one's rows. + */ +class UnmappableEncodingTest { + + private static CoreConnection connect(MockServer server) { + PgConnectionConfig config = PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .build(); + server.onStartup((s, f) -> s.send( + BackendWire.authenticationOk(), + BackendWire.parameterStatus("server_version", "13.0"), + BackendWire.parameterStatus("client_encoding", "UTF8"), + BackendWire.parameterStatus("DateStyle", "ISO, MDY"), + BackendWire.parameterStatus("IntervalStyle", "iso_8601"), + BackendWire.parameterStatus("standard_conforming_strings", "on"), + BackendWire.parameterStatus("TimeZone", "UTC"), + BackendWire.readyForQuery('I'))); + WireChannel channel = new WireChannel(server, SizeLimits.unlimited()); + StartupResult startup = new StartupOrchestrator( + channel, config, HostAndPort.of("h"), TrustAuthenticator.INSTANCE, PgConnectionListener.NO_OP) + .run(); + CoreConnection connection = + new CoreConnection(channel, config, startup, HostAndPort.of("h"), PgConnectionListener.NO_OP); + connection.bootstrapSession(); + return connection; + } + + @Test + void reportBeforeCommandCompleteBreaksTheConnection() { + MockServer server = new MockServer() + .onMessage((s, f) -> s.send( + BackendWire.parameterStatus("client_encoding", "WIN1251"), + BackendWire.commandComplete("SET"), + BackendWire.readyForQuery('I'))); + CoreConnection connection = connect(server); + + assertThrows(PgException.class, () -> connection.execute("SET client_encoding TO 'WIN1251'")); + assertTrue(connection.isBroken(), "the SET's remaining messages are still unread"); + } + + @Test + void reportBeforeReadyForQueryBreaksTheConnection() { + MockServer server = new MockServer() + .onMessage((s, f) -> s.send( + BackendWire.commandComplete("SET"), + BackendWire.parameterStatus("client_encoding", "WIN1251"), + BackendWire.readyForQuery('I'))); + CoreConnection connection = connect(server); + + assertThrows(PgException.class, () -> { + try (PgResultStream rs = connection.execute("SET client_encoding TO 'WIN1251'")) { + rs.next(); + } + }); + assertTrue(connection.isBroken()); + } +} From b99512c7e157aedae06ee4e04ca302f0d60242ce Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:37:15 +0000 Subject: [PATCH 009/150] fix(core): bound the nesting depth of text-format arrays The text array parser recursed once per '{' with no limit, so a server, pooler or MITM could send an array value of a few thousand nested braces, well inside every SizeLimits bound, and the getter threw StackOverflowError instead of a PgException. The binary decoder already refuses more than PostgreSQL's six dimensions; apply the same bound to the text parser. --- .../postgresql/client/core/codec/ArrayCodecs.java | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/codec/ArrayCodecs.java b/postgresql-client/src/main/java/org/postgresql/client/core/codec/ArrayCodecs.java index 3e3dfec6..8becd711 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/codec/ArrayCodecs.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/codec/ArrayCodecs.java @@ -476,7 +476,7 @@ List parse() { if (i >= end || b[i] != '{') { throw new PgException("malformed array value: " + text()); } - return parseArray(); + return parseArray(1); } /** Skips an optional explicit-bounds prefix such as {@code [1:3]=} or {@code [-2:0][1:2]=}. */ @@ -492,7 +492,14 @@ private void skipDimensionPrefix() { } } - private List parseArray() { + private List parseArray(int depth) { + // The recursion is one frame per '{', and the value comes from the server: a few thousand + // nested braces would otherwise overflow the stack. The binary decoder enforces the same + // bound. + if (depth > BinaryDecoder.MAX_DIMENSIONS) { + throw new PgException( + "array exceeds PostgreSQL's " + BinaryDecoder.MAX_DIMENSIONS + "-dimension maximum"); + } i++; // consume '{' List out = new ArrayList<>(); skipWhitespace(); @@ -505,7 +512,7 @@ private List parseArray() { if (i >= end) { throw new PgException("unterminated array value: " + text()); } - out.add(b[i] == '{' ? parseArray() : parseElement()); + out.add(b[i] == '{' ? parseArray(depth + 1) : parseElement()); skipWhitespace(); if (i >= end) { throw new PgException("unterminated array value: " + text()); From 877ef6c8c5aa8480e8c1978c19e6c1a6c5cf8924 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:37:15 +0000 Subject: [PATCH 010/150] test(core): pin the text array nesting bound --- .../client/core/codec/ArrayCodecsTest.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/codec/ArrayCodecsTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/codec/ArrayCodecsTest.java index 04ae10a7..d75914df 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/codec/ArrayCodecsTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/codec/ArrayCodecsTest.java @@ -136,6 +136,22 @@ void decodesMultiDimensionalArray() { assertEquals(List.of(List.of(1, 2), List.of(3, 4)), decode(Oids.INT4_ARRAY, "{{1,2},{3,4}}")); } + @Test + void textArrayAtTheDimensionLimitDecodes() { + List value = decode(Oids.INT4_ARRAY, "{{{{{{1}}}}}}"); + assertEquals(List.of(List.of(List.of(List.of(List.of(List.of(1)))))), value); + } + + @Test + void textArrayNestingIsCapped() { + // The parser recurses once per '{'; a server-supplied value nested thousands deep used to + // overflow the stack with an Error rather than fail as a PgException. + String deep = "{".repeat(20_000) + "}".repeat(20_000); + PgException e = assertThrows(PgException.class, () -> decode(Oids.INT4_ARRAY, deep)); + assertTrue(e.getMessage().contains("dimension"), e.getMessage()); + assertThrows(PgException.class, () -> decode(Oids.INT4_ARRAY, "{{{{{{{1}}}}}}}")); + } + @Test void skipsDimensionPrefix() { assertEquals(List.of(7, 8, 9), decode(Oids.INT4_ARRAY, "[-1:1]={7,8,9}")); From b2e99298988df60bc2db0d57d08c09f744d792be Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:38:58 +0000 Subject: [PATCH 011/150] fix(jdbc): stop serverName and databaseName injecting URL parameters PgSimpleDataSource spliced serverName and databaseName into a URL unencoded, and the URL's query values outrank the data source's own properties. A database name such as "app?sslmode=disable&user=x& application_name=" therefore turned off the configured TLS policy and replaced the user, and a server name of the same shape could also redirect the connection, from whoever supplies the bean properties (an admin UI, JNDI, a multi-tenant host). Percent-encode the database name, as PgDriver already does for query values, and refuse a server name containing a character that would end the host part of the URL. --- .../org/postgresql/client/jdbc/PgDriver.java | 2 +- .../client/jdbc/PgSimpleDataSource.java | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java index 08158c22..69d5ed1d 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java @@ -520,7 +520,7 @@ private static String matchingPrefix(String url) { } /** Percent-encodes a value so it survives the core parser's {@code %XX}-only decoding. */ - private static String encode(String value) { + static String encode(String value) { StringBuilder out = new StringBuilder(value.length()); for (byte b : value.getBytes(StandardCharsets.UTF_8)) { int c = b & 0xFF; diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSimpleDataSource.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSimpleDataSource.java index 26179f2e..7fc1a69e 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSimpleDataSource.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSimpleDataSource.java @@ -45,7 +45,20 @@ public String getUrl() { return url; } + /** + * Sets the host. The value is spliced into a connection URL, so a character that would end the + * host part there is refused: {@code db?sslmode=disable&x=} would otherwise turn off the TLS + * policy configured on this data source, or name another host and user. + */ public void setServerName(String serverName) { + if (serverName != null) { + for (int i = 0; i < serverName.length(); i++) { + char c = serverName.charAt(i); + if (c <= ' ' || "/?#@&,=%\\".indexOf(c) >= 0) { + throw new IllegalArgumentException("invalid character in serverName: '" + c + "'"); + } + } + } this.serverName = serverName; } @@ -143,11 +156,12 @@ public Connection getConnection(String username, String password) throws SQLExce return connection; } - private String effectiveUrl() { + String effectiveUrl() { if (url != null) { return url; } - return "jdbc:postgresql://" + serverName + ':' + portNumber + '/' + (databaseName == null ? "" : databaseName); + return "jdbc:postgresql://" + serverName + ':' + portNumber + '/' + + (databaseName == null ? "" : PgDriver.encode(databaseName)); } // -- CommonDataSource. -- From 9ebeaf549c76f6560231ceed694cb946fac71b4d Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:38:58 +0000 Subject: [PATCH 012/150] test(jdbc): pin that data source fields cannot inject URL parameters --- .../client/jdbc/PgSimpleDataSourceTest.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSimpleDataSourceTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSimpleDataSourceTest.java index 56a1d38d..b81f0664 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSimpleDataSourceTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSimpleDataSourceTest.java @@ -11,9 +11,12 @@ import java.io.StringWriter; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; +import java.util.Map; import javax.sql.ConnectionPoolDataSource; import javax.sql.DataSource; import org.junit.jupiter.api.Test; +import org.postgresql.client.core.PgConnectionConfig; +import org.postgresql.client.core.internal.jdbc.ConnectionStringParser; /** * Unit tests for {@link PgSimpleDataSource} (N1.18): the JavaBeans property surface and its mapping @@ -83,6 +86,47 @@ void explicitUrlTakesPrecedenceOverDiscreteFields() { "the failure should name the explicit URL, not one built from the discrete fields"); } + /** The config the core parser builds from the data source's URL; the user travels separately. */ + private static PgConnectionConfig parseEffectiveUrl(PgSimpleDataSource ds) { + String url = ds.effectiveUrl().substring("jdbc:".length()); + return ConnectionStringParser.parse(url + (url.contains("?") ? "&" : "?") + "user=app", Map.of()); + } + + @Test + void databaseNameCannotInjectUrlParameters() { + // The bean fields are spliced into a URL whose query values outrank the bean's own + // properties; an unencoded database name could turn off sslmode or replace the user. + PgSimpleDataSource ds = new PgSimpleDataSource(); + ds.setServerName("db.example.com"); + ds.setDatabaseName("app?sslmode=disable&user=mallory&application_name="); + + PgConnectionConfig config = parseEffectiveUrl(ds); + assertEquals("app?sslmode=disable&user=mallory&application_name=", config.database()); + assertEquals("db.example.com", config.hosts().get(0).host()); + assertFalse(ds.effectiveUrl().contains("?"), ds.effectiveUrl()); + } + + @Test + void databaseNameWithNonAsciiRoundTrips() { + PgSimpleDataSource ds = new PgSimpleDataSource(); + ds.setDatabaseName("caf\u00e9 db"); + assertEquals("caf\u00e9 db", parseEffectiveUrl(ds).database()); + } + + @Test + void serverNameThatWouldEndTheHostIsRefused() { + PgSimpleDataSource ds = new PgSimpleDataSource(); + for (String bad : new String[] { + "evil?sslmode=disable&x=", "evil/db", "user@evil", "a,b", "evil#x", "evil x", "evil%2f", "evil&x=1" + }) { + assertThrows(IllegalArgumentException.class, () -> ds.setServerName(bad), bad); + } + assertEquals("localhost", ds.getServerName()); + ds.setServerName("[::1]"); + ds.setServerName("db-1.example.com"); + assertEquals("db-1.example.com", ds.getServerName()); + } + @Test void loginTimeoutRoundTripsAndRejectsNegative() throws SQLException { PgSimpleDataSource ds = new PgSimpleDataSource(); From fda2241e1a37358900e32d70d3e736ba3900c5d8 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:39:33 +0000 Subject: [PATCH 013/150] fix(jdbc): redact the URL PgSimpleDataSource quotes in its rejection When the driver declined the URL (no jdbc: prefix, a scheme typo, or claimPostgresqlScheme=never), the SQLException quoted it verbatim, and a URL carries a password in its userinfo or as password= often enough for that to leak it into logs (ADR-0010). Run it through the same redactor the compat data source uses. --- .../java/org/postgresql/client/jdbc/PgSimpleDataSource.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSimpleDataSource.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSimpleDataSource.java index 7fc1a69e..e4829e7f 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSimpleDataSource.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSimpleDataSource.java @@ -7,6 +7,7 @@ import java.util.Properties; import java.util.logging.Logger; import javax.sql.DataSource; +import org.postgresql.client.core.internal.jdbc.ConnectionStringRedaction; /** * A minimal {@link DataSource} that hands out plain connections with no pooling (C23.5). @@ -151,7 +152,8 @@ public Connection getConnection(String username, String password) throws SQLExce } Connection connection = driver.connect(effectiveUrl(), info); if (connection == null) { - throw new SQLException("invalid data source URL: " + effectiveUrl()); + // A URL that missed the scheme check can still carry a password (ADR-0010). + throw new SQLException("invalid data source URL: " + ConnectionStringRedaction.redactUrl(effectiveUrl())); } return connection; } From 6b997812ecc9eb170f726787b6df5448756c7d87 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:39:33 +0000 Subject: [PATCH 014/150] test(jdbc): pin the redaction of a rejected data source URL --- .../client/jdbc/PgSimpleDataSourceTest.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSimpleDataSourceTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSimpleDataSourceTest.java index b81f0664..164d68d4 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSimpleDataSourceTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSimpleDataSourceTest.java @@ -127,6 +127,22 @@ void serverNameThatWouldEndTheHostIsRefused() { assertEquals("db-1.example.com", ds.getServerName()); } + @Test + void rejectedUrlIsRedactedInTheMessage() { + PgSimpleDataSource ds = new PgSimpleDataSource(); + for (String url : new String[] { + "postgresql://app:s3cret@db.example.com/app", + "jdbc:postgresq://app:s3cret@db.example.com/app", + "postgresql://db.example.com/app?password=s3cret", + "jdbc:mysql://db.example.com/app?user=app&password=s3cret" + }) { + ds.setUrl(url); + SQLException e = assertThrows(SQLException.class, ds::getConnection, url); + assertFalse(e.getMessage().contains("s3cret"), e.getMessage()); + assertTrue(e.getMessage().contains("db.example.com"), e.getMessage()); + } + } + @Test void loginTimeoutRoundTripsAndRejectsNegative() throws SQLException { PgSimpleDataSource ds = new PgSimpleDataSource(); From 99336f8ae81eaeed6234fc2509d925b4e9d735e6 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:40:28 +0000 Subject: [PATCH 015/150] fix(compat): stop server names and bag keys injecting URL parameters BaseDataSource.getUrl spliced the server names and the bag keys into the URL raw. A server name such as "h/realdb?sslmode=disable&x=" replaced the database, and its trailing "x=" swallowed the first bag property after it, which in the reproduction was the explicitly configured sslmode=verify-full: the compat driver then connected to a non-TLS server and, with its pgjdbc credential defaults, sent the password in the clear. Upstream pgjdbc concatenates serverName the same way. Refuse a server name containing a character that would end the host part, keeping brackets and colons for IPv6 literals, and encode bag keys the way values already are (and decode them in setUrl to match). --- .../postgresql/ds/common/BaseDataSource.java | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java index 4c85bf79..b5258331 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java @@ -94,11 +94,27 @@ public void setServerNames(String[] serverNames) { String[] sanitized = new String[serverNames.length]; for (int i = 0; i < serverNames.length; i++) { String name = serverNames[i]; - sanitized[i] = name == null || name.isEmpty() ? "localhost" : name.trim(); + sanitized[i] = name == null || name.isEmpty() ? "localhost" : requireHostSyntax(name.trim()); } this.serverNames = sanitized; } + /** + * Refuses a server name that would end the host part of the URL {@link #getUrl()} renders. The + * name is spliced in raw, and {@code h/db?sslmode=disable&x=} would otherwise replace the + * database and swallow the first configured bag property, which can be {@code sslmode}. + * Brackets and colons stay legal for IPv6 literals. + */ + private static String requireHostSyntax(String name) { + for (int i = 0; i < name.length(); i++) { + char c = name.charAt(i); + if (c <= ' ' || "/?#@&=,%\\".indexOf(c) >= 0) { + throw new IllegalArgumentException("invalid character in server name: '" + c + "'"); + } + } + return name; + } + public int getPortNumber() { return portNumbers[0]; } @@ -162,7 +178,7 @@ public String getUrl() { for (String name : properties.stringPropertyNames()) { url.append(first ? '?' : '&'); first = false; - url.append(name).append('=').append(encode(properties.getProperty(name))); + url.append(encode(name)).append('=').append(encode(properties.getProperty(name))); } return url.toString(); } @@ -223,7 +239,7 @@ public void setUrl(String url) { continue; } int eq = pair.indexOf('='); - String name = eq < 0 ? pair : pair.substring(0, eq); + String name = decode(eq < 0 ? pair : pair.substring(0, eq)); String value = eq < 0 ? "" : decode(pair.substring(eq + 1)); setProperty(name, value); } From 5f8f287add9350864cffe02ee2bd949aab6d5600 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:40:28 +0000 Subject: [PATCH 016/150] test(compat): pin that server names and bag keys cannot inject URL parameters --- .../ds/common/BaseDataSourceTest.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java index 2bd14746..1d482513 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java @@ -53,6 +53,32 @@ void rejectedUrlIsRedactedInTheMessage() { assertTrue(e.getMessage().contains("db.example.com"), e.getMessage()); } + @Test + void serverNameThatWouldEndTheHostIsRefused() { + PGSimpleDataSource ds = new PGSimpleDataSource(); + for (String bad : new String[] { + "h/realdb?sslmode=disable&x=", "h?sslmode=disable", "user@h", "a,b", "h#x", "h x", "h%2f", "h=x" + }) { + assertThrows(IllegalArgumentException.class, () -> ds.setServerName(bad), bad); + assertThrows(IllegalArgumentException.class, () -> ds.setServerNames(new String[] {"ok", bad}), bad); + } + assertEquals("localhost", ds.getServerName()); + ds.setServerNames(new String[] {"[::1]", "db-1.example.com"}); + assertArrayEquals(new String[] {"[::1]", "db-1.example.com"}, ds.getServerNames()); + } + + @Test + void bagKeysAreEncodedInTheUrl() { + PGSimpleDataSource ds = new PGSimpleDataSource(); + ds.setDatabaseName("app"); + ds.setSslMode("verify-full"); + ds.setProperty("x&sslmode", "disable"); + String url = ds.getUrl(); + assertFalse(url.contains("x&sslmode"), url); + assertEquals("verify-full", copyViaSetUrl(ds).getSslMode()); + assertEquals("disable", copyViaSetUrl(ds).getProperty("x&sslmode")); + } + @Test void shortFormUrlTargetsLocalhost() { PGSimpleDataSource ds = new PGSimpleDataSource(); From 9f2f41673c438ba13d62208f1e0495ba3a7b5870 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:41:31 +0000 Subject: [PATCH 017/150] fix(compat): split URL userinfo off in BaseDataSource.setUrl The core parser accepts jdbc:postgresql://user:pw@host/db, but setUrl split the host list on ':' with the userinfo still attached. Without a port the result was a NumberFormatException quoting "pw@host"; with one, "user:pw@host" became the server name, exposed through getServerName, getUrl and anything that printed the bean. The server-name check from the previous fix refuses that now, which is safer but still rejects a URL the native driver accepts. Take the userinfo off first and feed it to setUser and setPassword, decoded as the core parser decodes it, and report a malformed port by quoting only the port text. --- .../postgresql/ds/common/BaseDataSource.java | 29 ++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java index b5258331..6295d7c7 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java @@ -209,6 +209,20 @@ public void setUrl(String url) { int slash = rest.indexOf('/'); String hosts = slash < 0 ? rest : rest.substring(0, slash); setDatabaseName(slash < 0 ? "" : decode(rest.substring(slash + 1))); + // Userinfo, as the core parser accepts it: left in place, user:password@host became + // part of the server name, or a NumberFormatException quoting the password. + int at = hosts.indexOf('@'); + if (at >= 0) { + String userinfo = hosts.substring(0, at); + hosts = hosts.substring(at + 1); + int colon = userinfo.indexOf(':'); + if (colon >= 0) { + setUser(decodeUserinfo(userinfo.substring(0, colon))); + setPassword(decodeUserinfo(userinfo.substring(colon + 1))); + } else if (!userinfo.isEmpty()) { + setUser(decodeUserinfo(userinfo)); + } + } String[] parts = hosts.split(","); String[] names = new String[parts.length]; int[] ports = new int[parts.length]; @@ -219,7 +233,7 @@ public void setUrl(String url) { int bracket = part.lastIndexOf(']'); if (colon > bracket) { names[i] = part.substring(0, colon); - ports[i] = Integer.parseInt(part.substring(colon + 1)); + ports[i] = parsePort(part.substring(colon + 1)); } else { names[i] = part; ports[i] = 0; @@ -246,6 +260,19 @@ public void setUrl(String url) { } } + /** Percent-decodes as the core parser does, which leaves a {@code +} alone. */ + private static String decodeUserinfo(String value) { + return decode(value.replace("+", "%2B")); + } + + private static int parsePort(String text) { + try { + return Integer.parseInt(text); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("invalid port number in URL: '" + text + "'"); + } + } + /** pgjdbc alias for {@link #setUrl(String)}. */ public void setURL(String url) { setUrl(url); From ddcf3f0ea5eed420ebe2888634d12f043e9d33c1 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:41:31 +0000 Subject: [PATCH 018/150] test(compat): pin URL userinfo handling in BaseDataSource.setUrl --- .../ds/common/BaseDataSourceTest.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java index 1d482513..ab404583 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java @@ -79,6 +79,31 @@ void bagKeysAreEncodedInTheUrl() { assertEquals("disable", copyViaSetUrl(ds).getProperty("x&sslmode")); } + @Test + void urlUserinfoSetsTheCredentialsNotTheServerName() { + PGSimpleDataSource ds = new PGSimpleDataSource(); + ds.setUrl("jdbc:postgresql://alice:s3cret%40p+w@db.example.com:5433/app"); + assertEquals("db.example.com", ds.getServerName()); + assertEquals(5433, ds.getPortNumber()); + assertEquals("alice", ds.getUser()); + assertEquals("s3cret@p+w", ds.getPassword()); + assertFalse(ds.getUrl().contains("s3cret"), ds.getUrl()); + + PGSimpleDataSource noPort = new PGSimpleDataSource(); + noPort.setUrl("jdbc:postgresql://bob:pw@db.example.com/app"); + assertEquals("db.example.com", noPort.getServerName()); + assertEquals("bob", noPort.getUser()); + } + + @Test + void badPortIsReportedWithoutTheRestOfTheUrl() { + PGSimpleDataSource ds = new PGSimpleDataSource(); + IllegalArgumentException e = assertThrows( + IllegalArgumentException.class, () -> ds.setUrl("jdbc:postgresql://db:54x2/app?password=s3cret")); + assertTrue(e.getMessage().contains("54x2"), e.getMessage()); + assertFalse(e.getMessage().contains("s3cret"), e.getMessage()); + } + @Test void shortFormUrlTargetsLocalhost() { PGSimpleDataSource ds = new PGSimpleDataSource(); From 3e521e63a6496213afb8077c8aeb530db95d54af Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:43:18 +0000 Subject: [PATCH 019/150] fix(core): quote the composite type name lookup as an E'' literal TypeCache.lookupOid put the type name of a bound PgComposite or Struct into a simple Query as '...' with only the quotes doubled. That is safe only while standard_conforming_strings is on, and the driver refuses "off" only at connect time: after a runtime SET, a function or a role default turns it off, a name such as \' || NULL); DROP TABLE t; -- closed the literal early and the rest ran as SQL. The DROP ran on 14 and 17, and the caller's own query still returned normally. Use an escape-string literal, doubling backslashes as well as quotes, which reads the same under either setting. Binding the name would need the extended protocol, and this lookup also runs in SIMPLE query mode. --- .../src/main/java/org/postgresql/client/core/TypeCache.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java b/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java index 66c3010e..0bc88254 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java @@ -144,7 +144,11 @@ private int lookupArrayOid(int elementOid) { /** Resolves a (possibly schema-qualified) type name to its OID, or 0 when it does not exist. */ private int lookupOid(String typeName) { - String literal = "'" + typeName.replace("'", "''") + "'"; + // An E'' literal escapes the same way whatever standard_conforming_strings says: a plain '' + // literal with only the quotes doubled let a type name ending in a backslash break out + // once the session turned the setting off. Not bound as a parameter because this also + // runs in SIMPLE query mode, which has none. + String literal = "E'" + typeName.replace("\\", "\\\\").replace("'", "''") + "'"; String[] row = queryRow("SELECT to_regtype(" + literal + ")::oid", 1); if (row == null || row[0] == null) { return 0; From 9ae72431df6ad3c9b6ef3ce556a9bf58b8bc7258 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:43:18 +0000 Subject: [PATCH 020/150] test(core): pin the escaping of the composite type name lookup --- .../client/core/TypeCacheLookupTest.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java new file mode 100644 index 00000000..e018ce2a --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java @@ -0,0 +1,54 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.auth.TrustAuthenticator; +import org.postgresql.client.core.codec.Codecs; +import org.postgresql.client.core.internal.StartupOrchestrator; +import org.postgresql.client.core.internal.StartupResult; +import org.postgresql.client.core.internal.WireChannel; +import org.postgresql.client.core.transport.BackendWire; +import org.postgresql.client.core.transport.MockServer; + +/** + * The composite type name lookup interpolates the name into SQL, so the literal must stay closed + * whatever {@code standard_conforming_strings} is: with it off, a plain {@code '...'} literal + * treats a backslash as an escape and a name ending in one swallows the closing quote. + */ +class TypeCacheLookupTest { + + private static CoreConnection connect(MockServer server) { + PgConnectionConfig config = PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .build(); + server.onStartup((s, f) -> s.send(BackendWire.authenticationOk(), BackendWire.readyForQuery('I'))); + WireChannel channel = new WireChannel(server, SizeLimits.unlimited()); + StartupResult startup = new StartupOrchestrator( + channel, config, HostAndPort.of("h"), TrustAuthenticator.INSTANCE, PgConnectionListener.NO_OP) + .run(); + return new CoreConnection(channel, config, startup, HostAndPort.of("h"), PgConnectionListener.NO_OP); + } + + @Test + void typeNameIsSentAsAnEscapeStringLiteral() { + List queries = new ArrayList<>(); + MockServer server = new MockServer().onMessage((s, f) -> { + queries.add(f.payloadReader().readCString()); + s.send( + BackendWire.rowDescription("to_regtype"), + BackendWire.dataRow((String) null), + BackendWire.commandComplete("SELECT 1"), + BackendWire.readyForQuery('I')); + }); + TypeCache cache = new TypeCache(connect(server), Codecs.defaultRegistry()); + + assertNull(cache.resolveComposite("x\\' || NULL); DROP TABLE t; --")); + assertEquals(List.of("SELECT to_regtype(E'x\\\\'' || NULL); DROP TABLE t; --')::oid"), queries); + } +} From bdc80a07fc1d700800fc950dc71aa39077b8e132 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:44:34 +0000 Subject: [PATCH 021/150] fix(compat): double backslashes in escapeLiteral when strings are not standard PGConnection.escapeLiteral doubled quotes only, on the premise that SessionBootstrap refuses standard_conforming_strings=off. That holds at connect time and no later: after a runtime SET, a function or a role default turns it off, escapeLiteral("\'; DROP TABLE v; --") spliced into '...' dropped the table on 17. pgjdbc doubles backslashes when the setting is off, so ported code that relied on it became injectable on a jar swap. Read the session's current setting on each call and double backslashes when it is off, as pgjdbc does. --- .../org/postgresql/CompatConnectionView.java | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/CompatConnectionView.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/CompatConnectionView.java index f46f0e6d..2524efeb 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/CompatConnectionView.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/CompatConnectionView.java @@ -280,10 +280,12 @@ public String escapeIdentifier(String identifier) throws SQLException { @Override public String escapeLiteral(String literal) throws SQLException { - // Mirrors pgjdbc org.postgresql.core.Utils.escapeLiteral: double any single quote; a NUL byte - // cannot appear. This driver requires standard_conforming_strings=on (SessionBootstrap refuses - // to connect otherwise), so backslashes are never special and are not doubled. Note pgjdbc - // does NOT add surrounding quotes here -- the caller supplies them. + // Mirrors pgjdbc org.postgresql.core.Utils.escapeLiteral: double any single quote, and any + // backslash while standard_conforming_strings is off; a NUL byte cannot appear. The setting + // is read per call: SessionBootstrap refuses "off" only at connect time, and a later SET, a + // function or a role default can still turn it off. Note pgjdbc does NOT add surrounding + // quotes here -- the caller supplies them. + boolean doubleBackslashes = !standardConformingStrings(); StringBuilder out = new StringBuilder(literal.length() + literal.length() / 8); for (int i = 0; i < literal.length(); i++) { char ch = literal.charAt(i); @@ -291,14 +293,22 @@ public String escapeLiteral(String literal) throws SQLException { throw new PSQLException( "Zero bytes may not occur in string parameters.", PSQLState.INVALID_PARAMETER_VALUE); } - if (ch == '\'') { - out.append('\''); + if (ch == '\'' || (ch == '\\' && doubleBackslashes)) { + out.append(ch); } out.append(ch); } return out.toString(); } + private boolean standardConformingStrings() { + try { + return core().sessionState().standardConformingStrings(); + } catch (SQLException e) { + return true; // no core: the bootstrap's guarantee is all there is to go on + } + } + @Override public void cancelQuery() throws SQLException { // Out-of-band cancel on a fresh side connection; safe to call from another thread while this From 0daf9bdc125cfb4f93c9539f385af1ba738ec50b Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:44:34 +0000 Subject: [PATCH 022/150] test(compat): pin escapeLiteral under standard_conforming_strings=off --- .../postgresql/PgConnectionCompatTest.java | 42 ++++++++++++++++++- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/PgConnectionCompatTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/PgConnectionCompatTest.java index 211df436..816866f3 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/PgConnectionCompatTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/PgConnectionCompatTest.java @@ -12,11 +12,13 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; import java.sql.Array; import java.sql.Connection; import java.sql.SQLException; import org.junit.jupiter.api.Test; import org.postgresql.client.core.PgConnection; +import org.postgresql.client.core.SessionState; /** * Unit coverage for the pgjdbc {@link PGConnection} vendor ring (N4.3): proxy wiring, {@code unwrap}, @@ -106,6 +108,33 @@ void escapeLiteralDoublesQuotesWithoutSurroundingQuotes() throws SQLException { assertThrows(SQLException.class, () -> pg.escapeLiteral("bad\0value")); } + @Test + void escapeLiteralDoublesBackslashesWhenStandardConformingStringsIsOff() throws SQLException { + // SessionBootstrap refuses "off" only at connect time; a later SET can still turn it off, + // and an undoubled backslash would then escape the caller's closing quote. + FakeConnection fake = new FakeConnection(); + fake.core = coreWithStandardConformingStrings(false); + PGConnection pg = (PGConnection) CompatConnections.wrap(fakeConnection(fake)); + + assertEquals("\\\\'' || 1; --", pg.escapeLiteral("\\' || 1; --")); + assertEquals("O''Brien", pg.escapeLiteral("O'Brien")); + + fake.core = coreWithStandardConformingStrings(true); + PGConnection on = (PGConnection) CompatConnections.wrap(fakeConnection(fake)); + assertEquals("\\'' || 1; --", on.escapeLiteral("\\' || 1; --")); + } + + private static PgConnection coreWithStandardConformingStrings(boolean on) { + SessionState state = new SessionState(null, StandardCharsets.UTF_8, true, "UTC", "ISO, MDY", on); + return (PgConnection) Proxy.newProxyInstance( + PgConnectionCompatTest.class.getClassLoader(), new Class[] {PgConnection.class}, (p, m, a) -> { + if (m.getName().equals("sessionState")) { + return state; + } + throw new UnsupportedOperationException(m.getName()); + }); + } + @Test void vendorSettingsRoundTripAndSeedFromDefaults() throws SQLException { PGConnection pg = (PGConnection) CompatConnections.wrap(fakeConnection(new FakeConnection())); @@ -180,9 +209,13 @@ private static Connection fakeConnection(FakeConnection handler) { PgConnectionCompatTest.class.getClassLoader(), new Class[] {Connection.class}, handler); } - /** A minimal {@link Connection} stand-in that records calls and refuses every {@code unwrap}. */ + /** + * A minimal {@link Connection} stand-in that records calls and refuses every {@code unwrap}, + * except to {@link PgConnection} when a {@link #core} is set. + */ private static final class FakeConnection implements InvocationHandler { + PgConnection core; String lastMethod; Object[] lastArgs; String lastArrayType; @@ -198,7 +231,12 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl lastArrayElements = (Object[]) args[1]; return (Array) null; } - case "unwrap" -> throw new SQLException("not a wrapper for " + args[0]); + case "unwrap" -> { + if (core != null && args[0] == PgConnection.class) { + return core; + } + throw new SQLException("not a wrapper for " + args[0]); + } case "isWrapperFor" -> { return false; } From fb434e4d0f333687bd7609f84b84748fdf1f78ed Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:45:21 +0000 Subject: [PATCH 023/150] fix(core): report a malformed SCRAM server message as an auth failure The ongres SCRAM client throws IllegalArgumentException for a bad base64 salt or a non-positive iteration count, and only ScramException was caught, so a server or a MITM below verify-ca could make connect fail with a raw IllegalArgumentException that PgDriver does not turn into an SQLException (ADR-0007). Wrap it the same way, and keep the send outside the try so an I/O failure still passes through as itself. --- .../postgresql/client/core/auth/ScramMechanism.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/auth/ScramMechanism.java b/postgresql-client/src/main/java/org/postgresql/client/core/auth/ScramMechanism.java index 4651cd65..b7575c5b 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/auth/ScramMechanism.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/auth/ScramMechanism.java @@ -87,20 +87,23 @@ static ScramMechanism begin(AuthenticationRequest.Sasl request, AuthExchange exc /** Processes the server-first message and sends the client-final message. */ void continueExchange(AuthenticationRequest.SaslContinue request, AuthExchange exchange) { + String clientFinal; try { client.serverFirstMessage(new String(request.data(), StandardCharsets.UTF_8)); - String clientFinal = client.clientFinalMessage().toString(); - exchange.send(new SASLResponse(clientFinal.getBytes(StandardCharsets.UTF_8))); - } catch (ScramException e) { + clientFinal = client.clientFinalMessage().toString(); + } catch (ScramException | IllegalArgumentException e) { + // The SCRAM client reports a bad base64 salt or a non-positive iteration count as an + // IllegalArgumentException; it is still the server's malformed message (ADR-0007). throw new PgAuthenticationException("invalid SCRAM server-first message", e); } + exchange.send(new SASLResponse(clientFinal.getBytes(StandardCharsets.UTF_8))); } /** Verifies the server-final message (server signature); throws on mismatch. */ void finish(AuthenticationRequest.SaslFinal request) { try { client.serverFinalMessage(new String(request.data(), StandardCharsets.UTF_8)); - } catch (ScramException e) { + } catch (ScramException | IllegalArgumentException e) { throw new PgAuthenticationException("SCRAM server signature verification failed", e); } complete = true; From 5b39e963a2e998a3306dfe9ce75c250a0472b37c Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:45:21 +0000 Subject: [PATCH 024/150] test(core): pin the exception type for a malformed SCRAM server-first --- .../client/core/auth/ScramCompletionTest.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java index 384d84b5..75f3fa94 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java @@ -85,6 +85,23 @@ void okWithoutAnyExchangeIsAccepted() { assertDoesNotThrow(new StandardAuthenticator()::authenticationOk); } + @Test + void malformedServerFirstIsAnAuthenticationFailure() { + for (String tail : new String[] {",s=***,i=4096", ",s=MDEyMw==,i=0", ",s=MDEyMw==,i=-1"}) { + FakeAuthExchange exchange = new FakeAuthExchange(config(), false, null); + StandardAuthenticator auth = new StandardAuthenticator(); + auth.handle(new AuthenticationRequest.Sasl(List.of("SCRAM-SHA-256")), exchange); + String bare = clientFirstBare(exchange); + byte[] serverFirst = + ("r=" + bare.substring(bare.indexOf("r=") + 2) + "srv" + tail).getBytes(StandardCharsets.UTF_8); + + assertThrows( + PgAuthenticationException.class, + () -> auth.handle(new AuthenticationRequest.SaslContinue(serverFirst), exchange), + tail); + } + } + private static String clientFirstBare(FakeAuthExchange exchange) { SASLInitialResponse first = (SASLInitialResponse) exchange.sent.get(0); String message = new String(first.initialResponse(), StandardCharsets.UTF_8); From 20a32dee4f177742e9317d786fd44237a32f8cfe Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:47:04 +0000 Subject: [PATCH 025/150] fix(core): read TLS material and pgpass only from bounded regular files sslrootcert, sslcert, sslkey, sslcrl and the pgpass path were read with no check of what the path named. /dev/zero or /dev/urandom ran the heap out (or spun), and a FIFO or /dev/stdin blocked the connect forever, since loginTimeout does not interrupt a file read. The pgpass path was partly covered by its 0600 check, which an owner-only special file passes. Route every such read through one helper that refuses an existing path that is not a regular file and caps the size at 16 MiB. A missing file still fails as before, from the open. The unused service-file reader goes through it too. --- .../postgresql/client/core/SslMaterials.java | 18 +++++---- .../client/core/internal/LocalFiles.java | 38 +++++++++++++++++++ .../client/core/internal/PgPassFile.java | 3 +- .../client/core/internal/PgServiceFile.java | 2 +- 4 files changed, 51 insertions(+), 10 deletions(-) create mode 100644 postgresql-client/src/main/java/org/postgresql/client/core/internal/LocalFiles.java diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/SslMaterials.java b/postgresql-client/src/main/java/org/postgresql/client/core/SslMaterials.java index bd52d12c..6b28c11b 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/SslMaterials.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/SslMaterials.java @@ -1,9 +1,9 @@ package org.postgresql.client.core; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.nio.file.Files; import java.nio.file.Path; import java.security.GeneralSecurityException; import java.security.KeyFactory; @@ -38,6 +38,7 @@ import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import org.jspecify.annotations.Nullable; +import org.postgresql.client.core.internal.LocalFiles; /** * Loads TLS trust material and client key material from the files named by an @@ -81,8 +82,9 @@ static TrustManager[] verifyingTrustManagers(SslConfig ssl) { tmf.init(trustStoreFrom(requireRootCert(ssl))); return tmf.getTrustManagers(); } - PKIXBuilderParameters pkix = ssl.rootCertFile() != null - ? new PKIXBuilderParameters(trustStoreFrom(ssl.rootCertFile()), new X509CertSelector()) + Path rootCert = ssl.rootCertFile(); + PKIXBuilderParameters pkix = rootCert != null + ? new PKIXBuilderParameters(trustStoreFrom(rootCert), new X509CertSelector()) : new PKIXBuilderParameters(platformTrustAnchors(), new X509CertSelector()); pkix.setRevocationEnabled(true); pkix.addCertStore( @@ -179,12 +181,12 @@ private static int versionIndex(String version) { return idx; } - private static KeyStore trustStoreFrom(@Nullable Path rootCertFile) throws GeneralSecurityException, IOException { + private static KeyStore trustStoreFrom(Path rootCertFile) throws GeneralSecurityException, IOException { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); CertificateFactory factory = CertificateFactory.getInstance("X.509"); int i = 0; - try (InputStream in = Files.newInputStream(rootCertFile)) { + try (InputStream in = new ByteArrayInputStream(LocalFiles.readRegularFile(rootCertFile))) { for (Certificate cert : factory.generateCertificates(in)) { trustStore.setCertificateEntry("ca-" + (i++), cert); } @@ -194,7 +196,7 @@ private static KeyStore trustStoreFrom(@Nullable Path rootCertFile) throws Gener private static Certificate[] loadCertificateChain(Path certFile) throws GeneralSecurityException, IOException { CertificateFactory factory = CertificateFactory.getInstance("X.509"); - try (InputStream in = Files.newInputStream(certFile)) { + try (InputStream in = new ByteArrayInputStream(LocalFiles.readRegularFile(certFile))) { Collection certs = factory.generateCertificates(in); return certs.toArray(new Certificate[0]); } @@ -202,14 +204,14 @@ private static Certificate[] loadCertificateChain(Path certFile) throws GeneralS private static Collection loadCrls(Path crlFile) throws GeneralSecurityException, IOException { CertificateFactory factory = CertificateFactory.getInstance("X.509"); - try (InputStream in = Files.newInputStream(crlFile)) { + try (InputStream in = new ByteArrayInputStream(LocalFiles.readRegularFile(crlFile))) { return factory.generateCRLs(in); } } private static PrivateKey loadPrivateKey(Path keyFile, @Nullable Secret password) throws GeneralSecurityException, IOException { - byte[] raw = Files.readAllBytes(keyFile); + byte[] raw = LocalFiles.readRegularFile(keyFile); String text = new String(raw, StandardCharsets.US_ASCII); byte[] der; boolean encrypted; diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/LocalFiles.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/LocalFiles.java new file mode 100644 index 00000000..fd4394fe --- /dev/null +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/LocalFiles.java @@ -0,0 +1,38 @@ +package org.postgresql.client.core.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.FileSystemException; +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * Reads the small local files a connection is configured with (TLS material, pgpass) without + * assuming the configured path names one. {@code /dev/zero} or {@code /dev/urandom} would otherwise + * be read until the heap ran out, and a FIFO or {@code /dev/stdin} would block the connect forever: + * {@code loginTimeout} does not interrupt a file read. + */ +public final class LocalFiles { + + /** Far beyond any certificate bundle, private key or pgpass file. */ + static final int MAX_BYTES = 16 << 20; + + private LocalFiles() {} + + /** + * Reads {@code file} whole, refusing anything but a regular file of at most {@link #MAX_BYTES}. + * A missing file fails the same way it did before, from the open. + */ + public static byte[] readRegularFile(Path file) throws IOException { + if (Files.exists(file) && !Files.isRegularFile(file)) { + throw new FileSystemException(file.toString(), null, "not a regular file"); + } + try (InputStream in = Files.newInputStream(file)) { + byte[] bytes = in.readNBytes(MAX_BYTES + 1); + if (bytes.length > MAX_BYTES) { + throw new FileSystemException(file.toString(), null, "larger than " + MAX_BYTES + " bytes"); + } + return bytes; + } + } +} diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgPassFile.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgPassFile.java index cb8f42b7..4c269ecb 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgPassFile.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgPassFile.java @@ -48,7 +48,8 @@ public static Optional lookupFile(Path file, String host, int port, Stri return Optional.empty(); } try { - return lookup(Files.readString(file, StandardCharsets.UTF_8), host, port, database, user); + return lookup( + new String(LocalFiles.readRegularFile(file), StandardCharsets.UTF_8), host, port, database, user); } catch (IOException e) { throw new UncheckedIOException("failed to read pgpass file: " + file, e); } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgServiceFile.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgServiceFile.java index dfe36d1a..6a849097 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgServiceFile.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgServiceFile.java @@ -55,7 +55,7 @@ public static Optional> lookupFile(Path file, String service return Optional.empty(); } try { - return lookup(Files.readString(file, StandardCharsets.UTF_8), serviceName); + return lookup(new String(LocalFiles.readRegularFile(file), StandardCharsets.UTF_8), serviceName); } catch (IOException e) { throw new UncheckedIOException("failed to read service file: " + file, e); } From b35031e0dec5eecceca4a297064028bce27bfa03 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:47:04 +0000 Subject: [PATCH 026/150] test(core): pin the refusal of special files as TLS material or pgpass --- .../client/core/LocalFileSpecialPathTest.java | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/LocalFileSpecialPathTest.java diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/LocalFileSpecialPathTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/LocalFileSpecialPathTest.java new file mode 100644 index 00000000..22c117c9 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/LocalFileSpecialPathTest.java @@ -0,0 +1,82 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.io.RandomAccessFile; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.postgresql.client.core.internal.PgPassFile; + +/** + * TLS material and pgpass paths that do not name a regular file fail fast: {@code /dev/zero} used + * to run the heap out, and a FIFO blocked the connect forever, out of {@code loginTimeout}'s reach. + */ +@Timeout(value = 30, unit = TimeUnit.SECONDS) +class LocalFileSpecialPathTest { + + private static final Path DEV_ZERO = Path.of("/dev/zero"); + + @TempDir + Path dir; + + private Path fifo() throws Exception { + Path fifo = dir.resolve("fifo"); + Process mkfifo; + try { + mkfifo = new ProcessBuilder("mkfifo", fifo.toString()).start(); + } catch (java.io.IOException e) { + assumeTrue(false, "mkfifo is not available"); + throw e; + } + assumeTrue(mkfifo.waitFor() == 0 && Files.exists(fifo), "mkfifo failed"); + return fifo; + } + + @Test + void rootCertOnDevZeroFails() { + assumeTrue(Files.exists(DEV_ZERO)); + SslConfig ssl = SslConfig.builder().rootCertFile(DEV_ZERO).build(); + assertThrows(PgTlsException.class, () -> SslMaterials.verifyingTrustManagers(ssl)); + } + + @Test + void rootCertOnAFifoFails() throws Exception { + SslConfig ssl = SslConfig.builder().rootCertFile(fifo()).build(); + assertThrows(PgTlsException.class, () -> SslMaterials.verifyingTrustManagers(ssl)); + } + + @Test + void crlOnADirectoryFails() { + SslConfig ssl = SslConfig.builder().crlFile(dir).build(); + assertThrows(PgTlsException.class, () -> SslMaterials.verifyingTrustManagers(ssl)); + } + + @Test + void clientCertAndKeyOnDevZeroFail() { + assumeTrue(Files.exists(DEV_ZERO)); + SslConfig ssl = SslConfig.builder().certFile(DEV_ZERO).keyFile(DEV_ZERO).build(); + assertThrows(PgTlsException.class, () -> SslMaterials.keyManagers(ssl)); + } + + @Test + void oversizedRegularFileFails() throws Exception { + Path big = dir.resolve("big.pem"); + try (RandomAccessFile file = new RandomAccessFile(big.toFile(), "rw")) { + file.setLength(17L << 20); // sparse: costs no disk + } + SslConfig ssl = SslConfig.builder().rootCertFile(big).build(); + assertThrows(PgTlsException.class, () -> SslMaterials.verifyingTrustManagers(ssl)); + } + + @Test + void pgpassOnAFifoFails() throws Exception { + Path fifo = fifo(); + assertThrows(UncheckedIOException.class, () -> PgPassFile.lookupFile(fifo, "h", 5432, "db", "u")); + } +} From 271f74839dd65533a335ee05b960c8e47d982e2a Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:47:28 +0000 Subject: [PATCH 027/150] docs(core): state that socketFactory trusts the classpath The property names a class that is loaded and constructed per connection attempt. The type check runs before initialization, so only a SocketFactory subclass ever runs, but which one, and with what argument, is up to whoever sets the property. Say so where the property is documented, so it is not wired to a source less trusted than the rest of the deployment's configuration. pgjdbc's socketFactory has the same shape. --- .../java/org/postgresql/client/core/PgConnectionConfig.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/PgConnectionConfig.java b/postgresql-client/src/main/java/org/postgresql/client/core/PgConnectionConfig.java index 2e7e6625..79997edc 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/PgConnectionConfig.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/PgConnectionConfig.java @@ -228,6 +228,12 @@ public boolean loadBalanceHosts() { * Class name of a {@link javax.net.SocketFactory} used to create the plain TCP socket (unix * sockets, proxies, test fault injection), or {@code null} for a plain {@code new Socket()}. * Instantiated per connection attempt with {@link #socketFactoryArg()} when that is set. + * + *

This trusts the classpath: whoever sets the property picks which {@code SocketFactory} + * subclass on it runs, and with what argument. Only a class that is such a subclass is ever + * initialized, so naming any other class does nothing, but the property belongs with the rest + * of the deployer's configuration and should not be taken from a less trusted source, such as + * a URL an end user can edit. */ public @Nullable String socketFactory() { return socketFactory; From 0396aea73c8784b92e21f52210760ba76513f8b3 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:48:04 +0000 Subject: [PATCH 028/150] fix(core): refuse a second AuthenticationSASL during one login A repeated AuthenticationSASL replaced the in-flight SCRAM exchange. The first exchange's driver-owned secret was then unreachable, so cleanup() never zeroed it (ADR-0010), and a provider was asked for a fresh token each time. No server restarts the exchange; refuse it. --- .../postgresql/client/core/auth/StandardAuthenticator.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/auth/StandardAuthenticator.java b/postgresql-client/src/main/java/org/postgresql/client/core/auth/StandardAuthenticator.java index 11de8dae..5d383ea2 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/auth/StandardAuthenticator.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/auth/StandardAuthenticator.java @@ -51,8 +51,13 @@ public void handle(AuthenticationRequest request, AuthExchange exchange) { switch (request) { case AuthenticationRequest.CleartextPassword ignored -> cleartextPassword(exchange); case AuthenticationRequest.Md5Password md5 -> md5Password(md5, exchange); - case AuthenticationRequest.Sasl sasl -> + case AuthenticationRequest.Sasl sasl -> { + if (scram != null) { + // Replacing the exchange would also orphan its secret, which cleanup() never zeroes. + throw new PgAuthenticationException("server restarted the SASL exchange"); + } scram = ScramMechanism.begin(sasl, exchange, requireSecret(AuthMethod.SCRAM, exchange)); + } case AuthenticationRequest.SaslContinue cont -> requireScram().continueExchange(cont, exchange); case AuthenticationRequest.SaslFinal fin -> requireScram().finish(fin); case AuthenticationRequest.Gss ignored -> throw unsupportedMechanism("GSSAPI"); From 83979cb9b540df13fa3bdc8482937d0c66c96e27 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:48:04 +0000 Subject: [PATCH 029/150] test(core): pin the refusal of a restarted SASL exchange --- .../client/core/auth/ScramCompletionTest.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java index 75f3fa94..dbf32e2e 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java @@ -1,12 +1,14 @@ package org.postgresql.client.core.auth; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; +import java.util.ArrayList; import java.util.Base64; import java.util.List; import javax.crypto.Mac; @@ -102,6 +104,24 @@ void malformedServerFirstIsAnAuthenticationFailure() { } } + @Test + void secondSaslRequestIsRefusedAndTheFirstSecretStillZeroed() { + List issued = new ArrayList<>(); + StandardAuthenticator auth = new StandardAuthenticator(context -> { + char[] token = "token-pass".toCharArray(); + issued.add(token); + return token.clone(); + }); + FakeAuthExchange exchange = new FakeAuthExchange(config(), false, null); + AuthenticationRequest.Sasl sasl = new AuthenticationRequest.Sasl(List.of("SCRAM-SHA-256")); + auth.handle(sasl, exchange); + + PgAuthenticationException e = assertThrows(PgAuthenticationException.class, () -> auth.handle(sasl, exchange)); + assertTrue(e.getMessage().contains("restarted"), e.getMessage()); + assertEquals(1, issued.size(), "the provider must not be asked for a second secret"); + assertEquals(1, exchange.sent.size()); + } + private static String clientFirstBare(FakeAuthExchange exchange) { SASLInitialResponse first = (SASLInitialResponse) exchange.sent.get(0); String message = new String(first.initialResponse(), StandardCharsets.UTF_8); From ef852f50e36b1ed244120c22ed13fce79eb01ef0 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:50:06 +0000 Subject: [PATCH 030/150] fix(core): read the DataRows of a zero-column result PullResultStream allocated its transient row only when the RowDescription declared columns, so SELECT FROM t, whose description is empty but which still sends a DataRow per row, threw a NullPointerException from next() and left the connection busy until the stream was closed. The pipeline stream already handles this. Allocate the row for every result still open after priming; one that ended there (a command, a zero-row result, an empty query) still skips it. --- .../org/postgresql/client/core/PullResultStream.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/PullResultStream.java b/postgresql-client/src/main/java/org/postgresql/client/core/PullResultStream.java index c2702f4b..15af3304 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/PullResultStream.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/PullResultStream.java @@ -61,11 +61,11 @@ protected PullResultStream(CoreConnection connection, @Nullable Runnable onClose /** Subclasses call this once, after the request has been sent, to read up to the first row. */ protected final void start() { prime(); - // A command-only result (no columns) or one that already ended during priming (a zero-row or - // empty query) never yields a DataRow, so it never needs the transient row: only allocate it - // when the result has columns and is still open (task 13a). next() dereferences row solely - // after a DataRow, which cannot arrive in either skipped case, so leaving it null is safe. - if (metadata.columnCount() > 0 && !resultEnded) { + // A result that already ended during priming (a command, a zero-row result or an empty + // query) never yields a DataRow, so it never needs the transient row (task 13a). One that is + // still open does, whatever its column count: SELECT FROM t declares no columns and still + // sends a DataRow per row. + if (!resultEnded) { this.row = new SimpleRow(metadata, connection); } if (resultEnded) { @@ -256,7 +256,7 @@ public final boolean nextResult() { summary = next.summary(); resultEnded = next.summary() != null; rowAvailable = false; - row = metadata.columnCount() > 0 && !resultEnded ? new SimpleRow(metadata, connection) : null; + row = !resultEnded ? new SimpleRow(metadata, connection) : null; if (resultEnded) { finishResult(); // a row-less result: look ahead again so a third result is not missed } From 0418781bc824e018b5787b3fbdb4319cce246235 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:50:06 +0000 Subject: [PATCH 031/150] test(core): pin reading the rows of a zero-column result --- .../client/core/ZeroColumnResultTest.java | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/ZeroColumnResultTest.java diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/ZeroColumnResultTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/ZeroColumnResultTest.java new file mode 100644 index 00000000..5ff39946 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/ZeroColumnResultTest.java @@ -0,0 +1,91 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.auth.TrustAuthenticator; +import org.postgresql.client.core.internal.StartupOrchestrator; +import org.postgresql.client.core.internal.StartupResult; +import org.postgresql.client.core.internal.WireChannel; +import org.postgresql.client.core.transport.BackendWire; +import org.postgresql.client.core.transport.MockServer; + +/** + * {@code SELECT FROM t} is legal: its RowDescription declares no columns, and a DataRow with no + * values still follows for every row. Those rows have to be counted, not trip over a missing + * transient row. + */ +class ZeroColumnResultTest { + + private static CoreConnection connect(MockServer server) { + PgConnectionConfig config = PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .build(); + server.onStartup((s, f) -> s.send(BackendWire.authenticationOk(), BackendWire.readyForQuery('I'))); + WireChannel channel = new WireChannel(server, SizeLimits.unlimited()); + StartupResult startup = new StartupOrchestrator( + channel, config, HostAndPort.of("h"), TrustAuthenticator.INSTANCE, PgConnectionListener.NO_OP) + .run(); + return new CoreConnection(channel, config, startup, HostAndPort.of("h"), PgConnectionListener.NO_OP); + } + + private static int drain(PgResultStream rs) { + assertEquals(0, rs.metadata().columnCount()); + int rows = 0; + while (rs.next()) { + assertNotNull(rs.currentRow()); + rows++; + } + return rows; + } + + @Test + void simpleProtocolCountsZeroColumnRows() { + MockServer server = new MockServer() + .onMessage((s, f) -> s.send( + BackendWire.rowDescription(), + BackendWire.dataRow(), + BackendWire.dataRow(), + BackendWire.commandComplete("SELECT 2"), + BackendWire.readyForQuery('I'))); + CoreConnection connection = connect(server); + + try (PgResultStream rs = connection.execute("SELECT FROM generate_series(1, 2)")) { + assertEquals(2, drain(rs)); + } + assertFalse(connection.isBroken()); + try (PgResultStream rs = connection.execute("SELECT FROM generate_series(1, 2)")) { + assertEquals(2, drain(rs), "the connection is idle again"); + } + } + + @Test + void extendedProtocolCountsZeroColumnRows() { + MockServer server = new MockServer().onMessage((s, f) -> { + if (f.type() == 'S') { + s.send( + BackendWire.parseComplete(), + BackendWire.bindComplete(), + BackendWire.rowDescription(), + BackendWire.dataRow(), + BackendWire.dataRow(), + BackendWire.dataRow(), + BackendWire.commandComplete("SELECT 3"), + BackendWire.readyForQuery('I')); + } + }); + CoreConnection connection = connect(server); + + try (PgResultStream rs = connection.execute("SELECT FROM generate_series(1, $1)", List.of(3))) { + assertEquals(3, drain(rs)); + } + assertTrue(connection.isOpen()); + assertFalse(connection.isBroken()); + } +} From 8854394808df0a7ae811e79a3dce841dc8b01329 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:51:46 +0000 Subject: [PATCH 032/150] fix(core): keep the row phase of a zero-column prepared statement The named execute path skips the portal Describe and decided from the column count whether rows would follow, so a statement such as SELECT FROM t, whose statement Describe returns a RowDescription with no fields, was primed as a command. Its first DataRow was then unexpected and the connection was broken for good; with the default prepareThreshold that happens on the fifth execution. Record at prepare time whether the Describe answered RowDescription or NoData, and prime on that instead. --- .../org/postgresql/client/core/CoreConnection.java | 12 +++++++++--- .../client/core/CorePreparedStatement.java | 12 ++++++++++++ .../client/core/ExtendedQueryResultStream.java | 11 +++++++---- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java b/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java index 149e3b1e..7e151863 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java @@ -657,6 +657,7 @@ public CorePreparedStatement prepare(String sql, int[] declaredParameterOids) { } int[] parameterOids = new int[0]; RowMetadata resultMetadata = SimpleRowMetadata.EMPTY; + boolean returnsRows = false; while (true) { BackendMessage message = pullNonAsync(); switch (message) { @@ -664,7 +665,10 @@ public CorePreparedStatement prepare(String sql, int[] declaredParameterOids) { /* parsed */ } case ParameterDescription description -> parameterOids = description.parameterTypeOids(); - case RowDescription description -> resultMetadata = SimpleRowMetadata.of(description); + case RowDescription description -> { + resultMetadata = SimpleRowMetadata.of(description); + returnsRows = true; + } case NoData ignored -> resultMetadata = SimpleRowMetadata.EMPTY; case ErrorResponse error -> throw failSynchronousExchange(error); case ReadyForQuery ready -> { @@ -673,7 +677,8 @@ public CorePreparedStatement prepare(String sql, int[] declaredParameterOids) { // (now fixed) result column type OIDs and the connection's codec policy, so every // execute of this statement reuses it instead of recomputing two int[] per op. int[] resultFormats = resultFormatPolicy.forColumns(columnTypeOids(resultMetadata), codecs); - return new CorePreparedStatement(this, name, sql, parameterOids, resultMetadata, resultFormats); + return new CorePreparedStatement( + this, name, sql, parameterOids, resultMetadata, returnsRows, resultFormats); } default -> throw unexpectedSynchronous(message); } @@ -707,7 +712,8 @@ private PgResultStream executePreparedInternal( } else { channel.send(bind, Execute.UNNAMED_UNLIMITED, Sync.instance()); } - return new ExtendedQueryResultStream(this, fetchSize, disarm, statement.executeMetadata()); + return new ExtendedQueryResultStream( + this, fetchSize, disarm, statement.executeMetadata(), statement.returnsRows()); }); } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/CorePreparedStatement.java b/postgresql-client/src/main/java/org/postgresql/client/core/CorePreparedStatement.java index 461e1455..8a16e618 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/CorePreparedStatement.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/CorePreparedStatement.java @@ -23,6 +23,7 @@ final class CorePreparedStatement implements PgPreparedStatement { private final int[] parameterTypeOids; private final RowMetadata resultMetadata; private final RowMetadata executeMetadata; + private final boolean returnsRows; private final int[] resultFormatCodes; private boolean closed; @@ -32,12 +33,14 @@ final class CorePreparedStatement implements PgPreparedStatement { String sql, int[] parameterTypeOids, RowMetadata resultMetadata, + boolean returnsRows, int[] resultFormatCodes) { this.connection = connection; this.name = name; this.sql = sql; this.parameterTypeOids = parameterTypeOids; this.resultMetadata = resultMetadata; + this.returnsRows = returnsRows; this.resultFormatCodes = resultFormatCodes; // The execute path skips the portal Describe (task 1), so precompute the metadata a Bind with // these result formats would yield: the prepare-time (statement Describe) columns adjusted to @@ -72,6 +75,15 @@ RowMetadata executeMetadata() { return executeMetadata; } + /** + * Whether the statement Describe answered with a RowDescription rather than NoData: the execute + * then has a row phase even when it declares no columns ({@code SELECT FROM t}), which the column + * count alone cannot tell apart from a command. + */ + boolean returnsRows() { + return returnsRows; + } + /** * The {@code Bind} result-format codes for this statement, computed once at prepare time from the * (fixed) result column type OIDs and codec policy. Returned by reference for the execute hot diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/ExtendedQueryResultStream.java b/postgresql-client/src/main/java/org/postgresql/client/core/ExtendedQueryResultStream.java index 1d78d344..be1e1863 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/ExtendedQueryResultStream.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/ExtendedQueryResultStream.java @@ -32,11 +32,12 @@ final class ExtendedQueryResultStream extends PullResultStream { private final int fetchSize; private final boolean describeSkipped; + private final boolean preparedReturnsRows; private boolean syncSent; /** The unnamed fast path: a portal Describe was sent, so the metadata comes from a RowDescription. */ ExtendedQueryResultStream(CoreConnection connection, int fetchSize, @Nullable Runnable onCloseHook) { - this(connection, fetchSize, onCloseHook, null); + this(connection, fetchSize, onCloseHook, null, false); } /** @@ -47,11 +48,13 @@ final class ExtendedQueryResultStream extends PullResultStream { CoreConnection connection, int fetchSize, @Nullable Runnable onCloseHook, - @Nullable RowMetadata preparedMetadata) { + @Nullable RowMetadata preparedMetadata, + boolean preparedReturnsRows) { super(connection, onCloseHook); this.fetchSize = fetchSize; this.syncSent = fetchSize <= 0; // the unbounded path sent Sync with the request this.describeSkipped = preparedMetadata != null; + this.preparedReturnsRows = preparedReturnsRows; if (preparedMetadata != null) { this.metadata = preparedMetadata; } @@ -130,8 +133,8 @@ private void primeWithoutDescribe() { BackendMessage message = pull(); switch (message) { case BindComplete ignored -> { - if (metadata.columnCount() > 0) { - return; // rows follow; the cursor's next() reads them + if (preparedReturnsRows) { + return; // rows follow, possibly with no columns; the cursor's next() reads them } // no result columns: the Execute reports CommandComplete next; keep reading to it } From 7d8a90753f6a9832568beb3aa72ce20ef65fcad2 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:51:46 +0000 Subject: [PATCH 033/150] test(core): pin zero-column rows on the named prepared path --- .../client/core/ZeroColumnResultTest.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/ZeroColumnResultTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/ZeroColumnResultTest.java index 5ff39946..369e4e45 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/ZeroColumnResultTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/ZeroColumnResultTest.java @@ -88,4 +88,61 @@ void extendedProtocolCountsZeroColumnRows() { assertTrue(connection.isOpen()); assertFalse(connection.isBroken()); } + + /** Answers a statement Describe with {@code describe}, and an execute of it with {@code execute}. */ + private static MockServer preparedServer(byte[] describe, byte[]... execute) { + boolean[] bound = {false}; + return new MockServer().onMessage((s, f) -> { + if (f.type() == 'B') { + bound[0] = true; + } else if (f.type() == 'S') { + if (bound[0]) { + s.send(BackendWire.concat(execute)); + } else { + s.send( + BackendWire.parseComplete(), + BackendWire.parameterDescription(), + describe, + BackendWire.readyForQuery('I')); + } + bound[0] = false; + } + }); + } + + @Test + void namedPreparedStatementCountsZeroColumnRows() { + // The named path skips the portal Describe and goes by what the statement Describe said; a + // zero-column RowDescription there still means a row phase, unlike NoData. + CoreConnection connection = connect(preparedServer( + BackendWire.rowDescription(), + BackendWire.bindComplete(), + BackendWire.dataRow(), + BackendWire.dataRow(), + BackendWire.commandComplete("SELECT 2"), + BackendWire.readyForQuery('I'))); + PgPreparedStatement statement = connection.prepare("SELECT FROM t"); + + for (int i = 0; i < 2; i++) { + try (PgResultStream rs = statement.execute(List.of())) { + assertEquals(2, drain(rs)); + } + } + assertFalse(connection.isBroken()); + } + + @Test + void namedPreparedCommandStillCompletesWhilePriming() { + CoreConnection connection = connect(preparedServer( + BackendWire.noData(), + BackendWire.bindComplete(), + BackendWire.commandComplete("UPDATE 4"), + BackendWire.readyForQuery('I'))); + PgPreparedStatement statement = connection.prepare("UPDATE t SET x = 1"); + + try (PgResultStream rs = statement.execute(List.of())) { + assertEquals(4L, rs.summary().affectedRows().getAsLong()); + assertFalse(rs.next()); + } + } } From 1e41ec8df825540d35fe04e8653b42ebee0396e9 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:53:58 +0000 Subject: [PATCH 034/150] fix(core): surface malformed server values as PgException Value decoders handed server bytes to UUID.fromString, BigDecimal, java.time and ByteSlice bounds checks with no catch, so a server, pooler or MITM below verify-ca could make a getter throw IllegalArgumentException, NumberFormatException, StringIndexOutOfBoundsException, DateTimeException or IndexOutOfBoundsException. The catalog reads in TypeCache likewise gave a NullPointerException or NumberFormatException for an impossible row. Callers branching on the PgException hierarchy missed all of these (ADR-0007). Wrap those types in AbstractCodec.decode and in the domain codec, whose base may be a user codec, and check the remaining catalog columns. Binary decoding a type that has no binary decoder still throws UnsupportedOperationException: that is a driver limit, not bad data. --- .../org/postgresql/client/core/TypeCache.java | 17 +++++++++----- .../client/core/codec/AbstractCodec.java | 22 ++++++++++++++++--- .../client/core/codec/UserTypeCodecs.java | 8 ++++++- 3 files changed, 37 insertions(+), 10 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java b/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java index 0bc88254..546704b0 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java @@ -170,13 +170,13 @@ private void queryAndRegister(int oid) { // handled before the typtype switch: resolve the element codec and register an array codec over // it so enum[]/composite[]/domain[] decode instead of falling back to the raw literal (C10.8). if ("A".equals(type[4])) { - registerArray(oid, parseOid(type[3])); + registerArray(oid, parseOid(requireColumn(type[3], "typelem"))); return; } - switch (type[0]) { + switch (requireColumn(type[0], "typtype")) { case "e" -> register(oid, UserTypeCodecs.enumCodec(oid, requireColumn(type[5], "typname"))); case "d" -> { - int baseOid = parseOid(type[1]); + int baseOid = parseOid(requireColumn(type[1], "typbasetype")); Codec base = resolve(baseOid); // A domain decodes through its base type's codec, so it is only registrable when // the base resolved; otherwise leave the text/raw fallback in place, exactly as @@ -185,7 +185,8 @@ private void queryAndRegister(int oid) { register(oid, UserTypeCodecs.domainCodec(oid, requireColumn(type[5], "typname"), base)); } } - case "c" -> registerComposite(oid, type[5], parseOid(type[2])); + case "c" -> + registerComposite(oid, requireColumn(type[5], "typname"), parseOid(requireColumn(type[2], "typrelid"))); default -> { // a plain base type with no specific codec keeps the text/raw fallback } @@ -211,7 +212,7 @@ private void registerComposite(int oid, String typeName, int relationOid) { + " AND attnum > 0 AND NOT attisdropped ORDER BY attnum")) { while (rs.next()) { Row row = rs.currentRow(); - names.add(row.getString(1)); + names.add(requireColumn(row.getString(1), "pg_attribute.attname")); fieldOids.add(parseOid(requireColumn(row.getString(2), "pg_attribute.atttypid"))); } } @@ -253,6 +254,10 @@ private static String requireColumn(@Nullable String value, String column) { } private static int parseOid(String text) { - return (int) Long.parseLong(text.trim()); + try { + return (int) Long.parseLong(text.trim()); + } catch (NumberFormatException e) { + throw new PgException("malformed OID in the catalog: " + text, e); + } } } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/codec/AbstractCodec.java b/postgresql-client/src/main/java/org/postgresql/client/core/codec/AbstractCodec.java index 038c3096..0e0d0b33 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/codec/AbstractCodec.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/codec/AbstractCodec.java @@ -1,5 +1,6 @@ package org.postgresql.client.core.codec; +import java.time.DateTimeException; import org.postgresql.client.core.Experimental; import org.postgresql.client.core.PgException; import org.postgresql.client.protocol.ProtocolConstants; @@ -43,10 +44,25 @@ public final int primaryOid() { @Override public final T decode(ByteSlice value, int formatCode, CodecContext context) { - if (formatCode == ProtocolConstants.FORMAT_BINARY) { - return decodeBinary(value, context); + try { + if (formatCode == ProtocolConstants.FORMAT_BINARY) { + return decodeBinary(value, context); + } + return decodeText(asText(value, context), context); + } catch (IllegalArgumentException | IndexOutOfBoundsException | DateTimeException | ArithmeticException e) { + throw malformedValue(javaType, e); } - return decodeText(asText(value, context), context); + } + + /** + * The value bytes come from the server, so a parser that rejects them (UUID.fromString, + * BigDecimal, java.time, a slice bound) is reporting malformed server data, which callers + * branching on the PgException hierarchy must see as one (ADR-0007). The value itself is left + * out of the message. + */ + static PgException malformedValue(Class javaType, RuntimeException cause) { + return new PgException( + "malformed " + javaType.getSimpleName() + " value from the server: " + cause.getMessage(), cause); } @Override diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/codec/UserTypeCodecs.java b/postgresql-client/src/main/java/org/postgresql/client/core/codec/UserTypeCodecs.java index 45194985..a3767713 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/codec/UserTypeCodecs.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/codec/UserTypeCodecs.java @@ -1,5 +1,6 @@ package org.postgresql.client.core.codec; +import java.time.DateTimeException; import java.util.ArrayList; import java.util.List; import org.jspecify.annotations.Nullable; @@ -124,7 +125,12 @@ public int[] oids() { @Override public Object decode(ByteSlice value, int formatCode, CodecContext context) { - return base.decode(value, formatCode, context); + try { + return base.decode(value, formatCode, context); + } catch (IllegalArgumentException | IndexOutOfBoundsException | DateTimeException | ArithmeticException e) { + // The base may be a user-registered codec rather than an AbstractCodec. + throw AbstractCodec.malformedValue(base.javaType(), e); + } } @Override From 64b57f77aba19ac287e7c77902eeaedbf6607df7 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:53:58 +0000 Subject: [PATCH 035/150] test(core): pin PgException for malformed server values and catalog rows --- .../client/core/TypeCacheLookupTest.java | 25 +++++++++ .../core/codec/MalformedServerValueTest.java | 54 +++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/codec/MalformedServerValueTest.java diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java index e018ce2a..f08aa826 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java @@ -2,8 +2,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; import org.postgresql.client.core.auth.TrustAuthenticator; @@ -51,4 +53,27 @@ void typeNameIsSentAsAnEscapeStringLiteral() { assertNull(cache.resolveComposite("x\\' || NULL); DROP TABLE t; --")); assertEquals(List.of("SELECT to_regtype(E'x\\\\'' || NULL); DROP TABLE t; --')::oid"), queries); } + + @Test + void impossibleCatalogRowsFailAsPgException() { + // typtype is NOT NULL and typbasetype an OID; a server that says otherwise is answering + // something impossible, which must not surface as a NullPointerException or a + // NumberFormatException. + String[][] rows = { + {null, "0", "0", "0", "U", "t"}, + {"d", "not-an-oid", "0", "0", "U", "t"}, + {"c", "0", null, "0", "C", "t"}, + }; + for (String[] typeRow : rows) { + MockServer server = new MockServer() + .onMessage((s, f) -> s.send( + BackendWire.rowDescription( + "typtype", "typbasetype", "typrelid", "typelem", "typcategory", "oid"), + BackendWire.dataRow(typeRow), + BackendWire.commandComplete("SELECT 1"), + BackendWire.readyForQuery('I'))); + TypeCache cache = new TypeCache(connect(server), Codecs.defaultRegistry()); + assertThrows(PgException.class, () -> cache.resolve(99999), Arrays.toString(typeRow)); + } + } } diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/codec/MalformedServerValueTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/codec/MalformedServerValueTest.java new file mode 100644 index 00000000..f91168ef --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/codec/MalformedServerValueTest.java @@ -0,0 +1,54 @@ +package org.postgresql.client.core.codec; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.PgException; +import org.postgresql.client.protocol.Oids; +import org.postgresql.client.protocol.ProtocolConstants; +import org.postgresql.client.protocol.buffer.ByteSlice; + +/** + * Value bytes come from the server; a decoder that rejects them must say so as a PgException + * (ADR-0007), not leak the JDK parser's own exception type. + */ +class MalformedServerValueTest { + + private final CodecRegistry registry = Codecs.defaultRegistry(); + private final CodecContext context = CodecContext.defaults(); + + private void assertTextRejected(int oid, String text) { + byte[] bytes = text.getBytes(StandardCharsets.UTF_8); + assertThrows( + PgException.class, + () -> registry.forOid(oid) + .decode(new ByteSlice(bytes, 0, bytes.length), ProtocolConstants.FORMAT_TEXT, context), + text); + } + + private void assertBinaryRejected(int oid, byte[] bytes) { + assertThrows(PgException.class, () -> registry.forOid(oid) + .decode(new ByteSlice(bytes, 0, bytes.length), ProtocolConstants.FORMAT_BINARY, context)); + } + + @Test + void malformedTextValues() { + assertTextRejected(Oids.UUID, "zz"); + assertTextRejected(Oids.MONEY, "1.2.3"); + assertTextRejected(Oids.TIMETZ, "12:00:00+"); + assertTextRejected(Oids.TIMETZ, "12:00:00+ab"); + assertTextRejected(Oids.DATE, "2020-13-45"); + assertTextRejected(Oids.DATE, "garbage"); + } + + @Test + void malformedBinaryValues() { + assertBinaryRejected(Oids.TIME, ByteBuffer.allocate(8).putLong(-1).array()); + // An int4[] header cut off after the element type. + assertBinaryRejected( + Oids.INT4_ARRAY, + ByteBuffer.allocate(12).putInt(1).putInt(0).putInt(Oids.INT4).array()); + } +} From b3bacd57a0b4f863e03dfe3ea497826ebefe31ae Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:55:11 +0000 Subject: [PATCH 036/150] fix(core): redact URL passwords that contain '/', '@', '?' or spaces Redaction.redactUrl ended a userinfo password at the first '/', '@' or whitespace, and a password= value at ';' or whitespace, so "a/b", "p@ss", "p ss" and a quoted key-value password with a space in it came out partly or wholly in the clear. Its callers quote a URL that failed the scheme check into an exception message. Take the userinfo password as everything from the first ':' after "//" to the last '@', which over-redacts when the '@' is in the query, and let a quoted key-value password run to its closing quote. --- .../client/core/internal/Redaction.java | 29 +++++++++++++++---- 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/Redaction.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/Redaction.java index 250070d2..1e19c893 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/Redaction.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/Redaction.java @@ -12,11 +12,10 @@ public final class Redaction { /** The placeholder substituted for a redacted secret. */ public static final String REDACTED = "***"; - // Password in a URI userinfo: scheme://user:PASSWORD@host - private static final Pattern USERINFO_PASSWORD = Pattern.compile("(//[^/@:\\s]+:)[^@/\\s]*(@)"); - - // password= / sslpassword= in key-value or query-string form. - private static final Pattern PASSWORD_PARAM = Pattern.compile("(?i)((?:password|sslpassword)=)[^&;\\s]*"); + // password= / sslpassword= in key-value or query-string form. A quoted key-value value runs to + // its closing quote, spaces and all; an unquoted one to the next '&' or whitespace. + private static final Pattern PASSWORD_PARAM = + Pattern.compile("(?i)((?:password|sslpassword)\\s*=\\s*)('(?:[^'\\\\]|\\\\.)*'?|[^&\\s]*)"); private Redaction() {} @@ -25,7 +24,25 @@ private Redaction() {} if (url == null) { return null; } - String redacted = USERINFO_PASSWORD.matcher(url).replaceAll("$1" + REDACTED + "$2"); + String redacted = redactUserinfoPassword(url); return PASSWORD_PARAM.matcher(redacted).replaceAll("$1" + REDACTED); } + + /** + * Replaces everything from the first ':' after "//" to the last '@'. A password may itself hold + * '/', '@', '?' or whitespace, so no narrower rule finds its end; when the '@' turns out to be in + * the query instead, this redacts too much, which is the safe way to be wrong. + */ + private static String redactUserinfoPassword(String url) { + int authority = url.indexOf("//"); + if (authority < 0) { + return url; + } + int colon = url.indexOf(':', authority + 2); + int at = url.lastIndexOf('@'); + if (colon < 0 || at < colon) { + return url; + } + return url.substring(0, colon + 1) + REDACTED + url.substring(at); + } } From c9cefba5476f716f6e54e66a73b55c66130c538b Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:55:11 +0000 Subject: [PATCH 037/150] test(core): pin redaction of passwords with awkward characters --- .../java/org/postgresql/client/core/SecretTest.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/SecretTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/SecretTest.java index ceae1bf8..a38e7b55 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/SecretTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/SecretTest.java @@ -89,6 +89,19 @@ void redactsPasswordParameters() { Redaction.redactUrl("postgresql://db/app?user=app&password=hunter2&x=1")); } + @Test + void redactsPasswordsWithAwkwardCharacters() { + for (String password : new String[] {"a/b", "p@ss", "p ss", "q?x", "a\"b"}) { + String redacted = Redaction.redactUrl("postgresql://user:" + password + "@db.example.com/app"); + assertEquals("postgresql://user:***@db.example.com/app", redacted, password); + } + assertEquals( + "host=h user=u password=*** dbname=d", + Redaction.redactUrl("host=h user=u password='my secret' dbname=d")); + assertEquals("host=h password = *** dbname=d", Redaction.redactUrl("host=h password = 'it\\'s' dbname=d")); + assertEquals("host=h password=***", Redaction.redactUrl("host=h password=a;b")); + } + @Test void redactUrlWithoutPasswordIsUnchanged() { assertEquals( From 4fbe2751fd4f8fbfc9c286138ed1a49aed266982 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:55:52 +0000 Subject: [PATCH 038/150] fix(core): bound the depth of catalog-driven type resolution TypeCache resolves a domain's base, an array's element and a composite's fields by recursing, one catalog query per level, and the chain is whatever the server answers. A server that answered every pg_type lookup with a further domain or array type drove it to a StackOverflowError after 1400-1900 round trips, which left the connection wedged busy. Fail with a PgException past 64 levels, far deeper than any real chain. --- .../org/postgresql/client/core/TypeCache.java | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java b/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java index 546704b0..c3eaf003 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java @@ -37,6 +37,11 @@ final class TypeCache { private final Map compositeOidByName = new HashMap<>(); private final Map compositeArrayOidByName = new HashMap<>(); + /** Far deeper than any real chain of domains, arrays and composites. */ + static final int MAX_DEPTH = 64; + + private int depth; + TypeCache(CoreConnection connection, CodecRegistry registry) { this.connection = connection; this.registry = registry; @@ -49,7 +54,19 @@ Codec resolve(int oid) { return registry.forOid(oid); } if (attempted.add(oid)) { - queryAndRegister(oid); + // Each domain base, array element or composite field recurses through here, and the chain + // comes from the server's catalog answers: an endless one would otherwise overflow the + // stack after a thousand-odd round trips. + if (depth >= MAX_DEPTH) { + throw new PgException("type " + Integer.toUnsignedString(oid) + " is nested more than " + MAX_DEPTH + + " levels deep in the catalog"); + } + depth++; + try { + queryAndRegister(oid); + } finally { + depth--; + } } return registry.forOid(oid); } From d365c89ea45568e30127a2ca6a32885848565bc1 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:55:52 +0000 Subject: [PATCH 039/150] test(core): pin the type resolution depth bound --- .../client/core/TypeCacheLookupTest.java | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java index f08aa826..8eeaf990 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java @@ -1,12 +1,15 @@ package org.postgresql.client.core; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; import org.postgresql.client.core.auth.TrustAuthenticator; import org.postgresql.client.core.codec.Codecs; @@ -76,4 +79,26 @@ void impossibleCatalogRowsFailAsPgException() { assertThrows(PgException.class, () -> cache.resolve(99999), Arrays.toString(typeRow)); } } + + @Test + void endlessDomainChainIsCut() { + // Each lookup answers with a domain over a type it has not been asked about yet. + AtomicInteger next = new AtomicInteger(100_000); + AtomicInteger lookups = new AtomicInteger(); + MockServer server = new MockServer().onMessage((s, f) -> { + lookups.incrementAndGet(); + s.send( + BackendWire.rowDescription("typtype", "typbasetype", "typrelid", "typelem", "typcategory", "oid"), + BackendWire.dataRow("d", Integer.toString(next.incrementAndGet()), "0", "0", "U", "t"), + BackendWire.commandComplete("SELECT 1"), + BackendWire.readyForQuery('I')); + }); + CoreConnection connection = connect(server); + TypeCache cache = new TypeCache(connection, Codecs.defaultRegistry()); + + PgException e = assertThrows(PgException.class, () -> cache.resolve(next.get())); + assertTrue(e.getMessage().contains("nested"), e.getMessage()); + assertEquals(TypeCache.MAX_DEPTH, lookups.get()); + assertFalse(connection.isBroken()); + } } From 030e80e5a5a8826cbb5e7c3813f8c207eb932d62 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:56:48 +0000 Subject: [PATCH 040/150] fix(core): check the width of a binary bool before reading it getBooleanPrimitive was the one binary fast path without a width check. A zero-length binary bool from the server returned whatever byte came next in the row payload, or threw ArrayIndexOutOfBoundsException on a buffered row. Require exactly one byte, as the integer and float paths already do. --- .../src/main/java/org/postgresql/client/core/SimpleRow.java | 1 + 1 file changed, 1 insertion(+) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/SimpleRow.java b/postgresql-client/src/main/java/org/postgresql/client/core/SimpleRow.java index 119ec552..07363146 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/SimpleRow.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/SimpleRow.java @@ -173,6 +173,7 @@ public boolean getBooleanPrimitive(int columnIndex) { if (metadata.columnFormat(columnIndex) != ProtocolConstants.FORMAT_TEXT) { // Binary bool is a single 0/1 byte; read it directly, no codec or stringify (task 14). if (metadata.columnTypeOid(columnIndex) == Oids.BOOL) { + requireBinaryWidth(idx, 1); return row().payload()[row().columnOffset(idx)] != 0; } } else if (row().columnLength(idx) == 1) { From 1c4f344874880393646bb4e1f5c89edf508a98ce Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:56:48 +0000 Subject: [PATCH 041/150] test(core): pin the binary bool width check --- .../org/postgresql/client/core/SimpleRowBinaryDecodeTest.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/SimpleRowBinaryDecodeTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/SimpleRowBinaryDecodeTest.java index d227d4eb..f98690fb 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/SimpleRowBinaryDecodeTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/SimpleRowBinaryDecodeTest.java @@ -236,6 +236,10 @@ void binaryFastPathsRejectMismatchedWidths() { // N1.21 Oids.FLOAT8, new byte[] {0, 0, 0, 0}, row -> assertThrows(PgException.class, () -> row.getDoublePrimitive(1))); + // A zero-length bool read the byte after the column, or past the end of a buffered row. + assertBinaryColumn( + Oids.BOOL, new byte[0], row -> assertThrows(PgException.class, () -> row.getBooleanPrimitive(1))); + assertBinaryColumn(Oids.BOOL, new byte[] {1}, row -> assertTrue(row.getBooleanPrimitive(1))); } @Test From cece8890932b5685198dd45ddaecc9e864594bf5 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:58:33 +0000 Subject: [PATCH 042/150] fix(jdbc): accept custom batch rewriter classes only from Properties rewriteBatchUsingArrays and rewriteBatchUsingMultipleValues accepted a custom class name from the URL query alone, unlike authenticationPluginClassName, which N2.9 limits to Properties because a class name is code to run and the URL is the part of the configuration most often built from less trusted input. The type check before initialization meant only a rewriter implementation could be constructed, but which one was up to whoever wrote the URL. Refuse a custom class name in the URL with an SQLException; the on/off spellings and the built-in ids are still accepted from either source. --- .../org/postgresql/client/jdbc/PgDriver.java | 39 ++++++++++++++----- 1 file changed, 29 insertions(+), 10 deletions(-) diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java index 69d5ed1d..e776412e 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java @@ -27,6 +27,8 @@ import org.postgresql.client.jdbc.batch.BatchRewriteSetting; import org.postgresql.client.jdbc.batch.BatchValuesRewriter; import org.postgresql.client.jdbc.batch.BatchValuesRewriters; +import org.postgresql.client.jdbc.batch.InsertArrayRewriter; +import org.postgresql.client.jdbc.batch.InsertMultiValuesRewriter; import org.slf4j.LoggerFactory; /** @@ -335,13 +337,11 @@ private static AuthenticationProvider loadAuthenticationProvider(String classNam /** * Resolves the {@code rewriteBatchUsingArrays} property (ADR-0014) to a rewriter, or {@code null} * when disabled or unset. A URL-query value takes precedence over the {@link Properties} of the - * same name (matching the rest of the driver's precedence). + * same name (matching the rest of the driver's precedence), except that a custom class name is + * accepted only from {@link Properties}; see {@link #rewriterSetting}. */ private static BatchArrayRewriter resolveBatchRewriter(String url, Properties info) throws SQLException { - String value = queryParam(url, REWRITE_BATCH_PROPERTY); - if (value == null) { - value = info.getProperty(REWRITE_BATCH_PROPERTY); - } + String value = rewriterSetting(url, info, REWRITE_BATCH_PROPERTY, InsertArrayRewriter.ID); try { return BatchArrayRewriters.resolve(BatchRewriteSetting.fromProperty(value)) .orElse(null); @@ -353,13 +353,11 @@ private static BatchArrayRewriter resolveBatchRewriter(String url, Properties in /** * Resolves the {@code rewriteBatchUsingMultipleValues} property (ADR-0016) to a rewriter, or * {@code null} when disabled or unset. A URL-query value takes precedence over the {@link Properties} - * of the same name (matching the rest of the driver's precedence). + * of the same name (matching the rest of the driver's precedence), except that a custom class name + * is accepted only from {@link Properties}; see {@link #rewriterSetting}. */ private static BatchValuesRewriter resolveMultiValuesRewriter(String url, Properties info) throws SQLException { - String value = queryParam(url, REWRITE_BATCH_MULTIVALUES_PROPERTY); - if (value == null) { - value = info.getProperty(REWRITE_BATCH_MULTIVALUES_PROPERTY); - } + String value = rewriterSetting(url, info, REWRITE_BATCH_MULTIVALUES_PROPERTY, InsertMultiValuesRewriter.ID); try { return BatchValuesRewriters.resolve(BatchRewriteSetting.fromProperty(value)) .orElse(null); @@ -368,6 +366,27 @@ private static BatchValuesRewriter resolveMultiValuesRewriter(String url, Proper } } + /** + * The value of a rewriter property, from the URL query if present, else from {@link Properties}. + * A custom rewriter class named in the URL is refused: a class name is code to run, and the URL is + * the part of the configuration most often assembled from less trusted input, which is why + * {@code authenticationPluginClassName} is read only from {@link Properties} too (N2.9). The + * on/off spellings and the built-in id stay accepted from either. + */ + private static String rewriterSetting(String url, Properties info, String property, String builtInId) + throws SQLException { + String fromUrl = queryParam(url, property); + if (fromUrl == null) { + return info.getProperty(property); + } + BatchRewriteSetting setting = BatchRewriteSetting.fromProperty(fromUrl); + if (setting.mode() == BatchRewriteSetting.Mode.PINNED && !builtInId.equals(setting.selector())) { + throw new SQLException(property + " in the connection URL names a custom rewriter class; a class" + + " name is accepted only from the connection Properties"); + } + return fromUrl; + } + /** The raw value of the {@code name} query parameter in {@code url}, or {@code null} if absent. */ private static String queryParam(String url, String name) { int q = url.indexOf('?'); From 7cfa8604e698c0cbe2e0ca50f9323d15ec98a49b Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 13:58:33 +0000 Subject: [PATCH 043/150] test(jdbc): pin where a custom batch rewriter class may be named --- .../postgresql/client/jdbc/PgDriverTest.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java index 6e8861e5..ba0c6b42 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java @@ -10,6 +10,7 @@ import java.sql.Driver; import java.sql.DriverManager; import java.sql.DriverPropertyInfo; +import java.sql.SQLException; import java.util.Properties; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Isolated; @@ -126,6 +127,29 @@ void autoRegisterCanBeDisabled() { } } + @Test + void customRewriterClassIsRefusedFromTheUrl() { + // A class name is code to run; like authenticationPluginClassName it is taken only from + // Properties. Both checks happen before any connection attempt. + Properties info = new Properties(); + info.setProperty("user", "app"); + for (String property : new String[] {"rewriteBatchUsingArrays", "rewriteBatchUsingMultipleValues"}) { + SQLException e = assertThrows(SQLException.class, () -> new PgDriver() + .connect("jdbc:postgresql://127.0.0.1:1/db?" + property + "=com.example.Rewriter", info)); + assertTrue(e.getMessage().contains("custom rewriter class"), e.getMessage()); + } + } + + @Test + void customRewriterClassIsStillAcceptedFromProperties() { + Properties info = new Properties(); + info.setProperty("user", "app"); + info.setProperty("rewriteBatchUsingArrays", "java.lang.String"); + SQLException e = assertThrows( + SQLException.class, () -> new PgDriver().connect("jdbc:postgresql://127.0.0.1:1/db", info)); + assertTrue(e.getMessage().contains("does not implement"), e.getMessage()); + } + @Test void reportsVersionAndCompliance() { assertEquals(0, driver.getMajorVersion()); From 0640789678f1724be6035cae8b62cbba3f04414d Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:01:27 +0000 Subject: [PATCH 044/150] fix(compat): translate pgjdbc spellings for the pooling and XA sources PGConnectionPoolDataSource and PGXADataSource build a native data source directly and handed it the property bag as is, skipping the translation Driver.connect applies. pgjdbc spellings that differ from the native ones, requireAuth and channelBinding among them, therefore reached the native driver as unknown keys and went to the server as startup parameters instead of being enforced: a fake server that asked for a cleartext password got it despite requireAuth=scram-sha-256. A genuine server rejects the unknown parameters, so this showed only against one that did not. Run the bag through the driver's own translation. It stays package-private in org.postgresql, which is exported, and the driver installs it into a small holder in the non-exported internal package for the data sources to call. The raw-bag helper has no callers left and goes. --- .../src/main/java/org/postgresql/Driver.java | 2 + .../internal/CompatPropertyTranslation.java | 42 +++++++++++++++++++ .../ds/PGConnectionPoolDataSource.java | 5 +-- .../postgresql/ds/common/BaseDataSource.java | 26 ++++++++---- .../org/postgresql/xa/PGXADataSource.java | 12 ++---- 5 files changed, 68 insertions(+), 19 deletions(-) create mode 100644 postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPropertyTranslation.java diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java index 3f9cbc9d..7b01af84 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java @@ -20,6 +20,7 @@ import java.util.logging.Logger; import org.postgresql.PgPropertyMappings.Mapping; import org.postgresql.PgPropertyMappings.Support; +import org.postgresql.client.compat.internal.CompatPropertyTranslation; import org.postgresql.client.core.auth.AuthenticationProvider; import org.postgresql.client.jdbc.PgDriver; import org.postgresql.client.jdbc.SqlExceptionFactoryRegistry; @@ -73,6 +74,7 @@ public Driver() {} private static volatile Driver registeredDriver; static { + CompatPropertyTranslation.install(Driver::translateProperties); // Fail fast if the real pgjdbc is co-present (ADR-0015): two org.postgresql.Driver definitions // on one classpath have undefined resolution order, so no arbitration can make it safe. requireSinglePostgresqlDriver(driverClassResources()); diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPropertyTranslation.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPropertyTranslation.java new file mode 100644 index 00000000..bd5bf1aa --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPropertyTranslation.java @@ -0,0 +1,42 @@ +package org.postgresql.client.compat.internal; + +import java.sql.SQLException; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Reaches the compat {@link org.postgresql.Driver}'s pgjdbc-to-native property translation from the + * data sources, which live in other packages. The translation stays package-private in + * {@code org.postgresql}, an exported pgjdbc-named package, and the driver installs it here when + * its class initializes; this package is not exported. + */ +public final class CompatPropertyTranslation { + + /** Translates pgjdbc property names and values to the native driver's. */ + @FunctionalInterface + public interface Translator { + Properties translate(Properties pgjdbcProperties) throws SQLException; + } + + private static final AtomicReference TRANSLATOR = new AtomicReference<>(); + + private CompatPropertyTranslation() {} + + /** Called once by the driver's static initializer; later calls are ignored. */ + public static void install(Translator translator) { + TRANSLATOR.compareAndSet(null, translator); + } + + /** Translates {@code pgjdbcProperties} the way {@code Driver.connect} translates its own. */ + public static Properties translate(Properties pgjdbcProperties) throws SQLException { + Translator translator = TRANSLATOR.get(); + if (translator == null) { + org.postgresql.Driver.isRegistered(); // initializes the driver class, which installs it + translator = TRANSLATOR.get(); + } + if (translator == null) { + throw new IllegalStateException("the compat driver did not install its property translation"); + } + return translator.translate(pgjdbcProperties); + } +} diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java index e37c6657..1f6d02b5 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java @@ -61,10 +61,7 @@ public boolean isDefaultAutoCommit() { private PgConnectionPoolDataSource configureNative() throws SQLException { PgConnectionPoolDataSource ds = new PgConnectionPoolDataSource(); copyIdentityTo(ds::setServerName, ds::setPortNumber, ds::setDatabaseName); - // Set first, so an explicit bag entry wins; see PGXADataSource. - ds.setProperty("ignoreEnvironment", "true"); - ds.setProperty("allowUnencryptedPasswordAuth", "true"); - copyPropertiesTo(ds::setProperty); + copyNativePropertiesTo(ds::setProperty); ds.setLoginTimeout(getLoginTimeout()); return ds; } diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java index 6295d7c7..17462849 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java @@ -20,6 +20,7 @@ import javax.naming.StringRefAddr; import javax.sql.CommonDataSource; import org.postgresql.PGProperty; +import org.postgresql.client.compat.internal.CompatPropertyTranslation; import org.postgresql.client.core.internal.jdbc.ConnectionStringRedaction; /** @@ -609,14 +610,25 @@ protected void copyIdentityTo( } /** - * Hands every property in the bag to {@code sink}. A subclass that configures something other - * than a plain {@code Connection} -- the XA source builds a native data source instead of going - * through {@link #getConnection()} -- needs these as well as the identity: dropping them means - * silently ignoring what the caller configured, including {@code sslmode}. + * Hands the bag to {@code sink} as the native driver spells it, after the defaults the compat + * {@link org.postgresql.Driver} gives every connection. A subclass that builds a native data + * source instead of going through {@link #getConnection()} -- the pooling and XA sources -- needs + * this rather than the raw bag: pgjdbc spellings such as {@code requireAuth} and + * {@code channelBinding} would otherwise reach the native driver as unknown keys and go to the + * server as startup parameters, unenforced. */ - protected void copyPropertiesTo(java.util.function.BiConsumer sink) { - for (String name : properties.stringPropertyNames()) { - sink.accept(name, properties.getProperty(name)); + protected void copyNativePropertiesTo(java.util.function.BiConsumer sink) throws SQLException { + Properties translated = CompatPropertyTranslation.translate(properties); + // pgjdbc reads no environment and sends a password whenever the server asks; an explicit + // bag entry still wins. + if (!translated.containsKey("ignoreEnvironment")) { + sink.accept("ignoreEnvironment", "true"); + } + if (!translated.containsKey("allowUnencryptedPasswordAuth")) { + sink.accept("allowUnencryptedPasswordAuth", "true"); + } + for (String name : translated.stringPropertyNames()) { + sink.accept(name, translated.getProperty(name)); } } } diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java index 780a6b74..04c767b7 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java @@ -34,9 +34,9 @@ public XAConnection getXAConnection(String user, String password) throws SQLExce } /** - * Builds a native XA source from the current JavaBean state: the identity, everything in the - * property bag, and the defaults the compat {@link org.postgresql.Driver} applies to an - * ordinary connection. + * Builds a native XA source from the current JavaBean state: the identity, the property bag + * translated to native spellings, and the defaults the compat {@link org.postgresql.Driver} + * applies to an ordinary connection. * *

The bag matters. This used to copy the server, port and database and nothing else, so an * XA source configured with {@code sslmode=verify-full} connected on the default policy @@ -48,11 +48,7 @@ public XAConnection getXAConnection(String user, String password) throws SQLExce private PgXADataSource configureNative() throws SQLException { PgXADataSource ds = new PgXADataSource(); copyIdentityTo(ds::setServerName, ds::setPortNumber, ds::setDatabaseName); - // pgjdbc reads no environment and sends a password whenever the server asks; the compat - // driver matches both, and so must this path. Set first, so an explicit bag entry wins. - ds.setProperty("ignoreEnvironment", "true"); - ds.setProperty("allowUnencryptedPasswordAuth", "true"); - copyPropertiesTo(ds::setProperty); + copyNativePropertiesTo(ds::setProperty); ds.setLoginTimeout(getLoginTimeout()); return ds; } From 03ebf3991b736052d07ffae14d34cda1eb0c287e Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:01:27 +0000 Subject: [PATCH 045/150] test(compat): pin requireAuth enforcement through every compat data source --- .../ds/DataSourcePropertyTranslationTest.java | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourcePropertyTranslationTest.java diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourcePropertyTranslationTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourcePropertyTranslationTest.java new file mode 100644 index 00000000..eb967f88 --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourcePropertyTranslationTest.java @@ -0,0 +1,98 @@ +package org.postgresql.ds; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.sql.SQLException; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.function.Executable; +import org.postgresql.ds.common.BaseDataSource; +import org.postgresql.xa.PGXADataSource; + +/** + * The pooling and XA sources build a native data source directly, so they must translate the + * pgjdbc property spellings as the compat driver does: an untranslated {@code requireAuth} reached + * the native driver as an unknown key and was sent to the server instead of being enforced. + */ +@Timeout(30) +class DataSourcePropertyTranslationTest { + + private static final int SSL_REQUEST_CODE = 80877103; + + @Test + void connectionPoolDataSourceEnforcesRequireAuth() throws Exception { + PGConnectionPoolDataSource ds = new PGConnectionPoolDataSource(); + assertRefusesCleartext(ds, ds::getPooledConnection); + } + + @Test + void xaDataSourceEnforcesRequireAuth() throws Exception { + PGXADataSource ds = new PGXADataSource(); + assertRefusesCleartext(ds, ds::getXAConnection); + } + + @Test + void simpleDataSourceEnforcesRequireAuth() throws Exception { + PGSimpleDataSource ds = new PGSimpleDataSource(); + assertRefusesCleartext(ds, ds::getConnection); + } + + private static void assertRefusesCleartext(BaseDataSource ds, Executable connect) throws Exception { + AtomicBoolean passwordSent = new AtomicBoolean(); + try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + Thread acceptor = Thread.ofVirtual().start(() -> askForCleartext(server, passwordSent)); + ds.setServerName("127.0.0.1"); + ds.setPortNumber(server.getLocalPort()); + ds.setDatabaseName("db"); + ds.setUser("alice"); + ds.setPassword("secret"); + ds.setSslMode("disable"); + ds.setProperty("requireAuth", "scram-sha-256"); + ds.setLoginTimeout(5); + + SQLException e = assertThrows(SQLException.class, connect); + server.close(); + assertFalse(passwordSent.get(), "the password reached the server"); + assertTrue(String.valueOf(e.getMessage()).contains("require_auth"), String.valueOf(e.getMessage())); + acceptor.join(5000); + } + } + + /** Answers the startup message with AuthenticationCleartextPassword and records a reply. */ + private static void askForCleartext(ServerSocket server, AtomicBoolean passwordSent) { + while (!server.isClosed()) { + try (Socket socket = server.accept()) { + socket.setSoTimeout(5000); + DataInputStream in = new DataInputStream(socket.getInputStream()); + OutputStream out = socket.getOutputStream(); + int length = in.readInt(); + int code = in.readInt(); + in.readFully(new byte[length - 8]); + if (code == SSL_REQUEST_CODE) { + continue; // sslmode=disable sends none; anything else is not this test's concern + } + out.write(ByteBuffer.allocate(9) + .put((byte) 'R') + .putInt(8) + .putInt(3) + .array()); + out.flush(); + if (in.read() == 'p') { + passwordSent.set(true); + } + } catch (IOException e) { + // The client hung up, or the test closed the listener. + } + } + } +} From 8e00d006c65056575b99470f0d6c9b7296351244 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:02:16 +0000 Subject: [PATCH 046/150] fix(compat): load ObjectFactory classes without initializing them ObjectFactory.instantiate, and SocketFactoryFactory through it, loaded the named class with initialize=true, so a class of the wrong type ran its static initializer before the type check rejected it. That contradicts the class's own Javadoc, and the native driver's loaders already check before initializing. Load with initialize=false; the constructor still initializes the class once the check has passed. --- .../src/main/java/org/postgresql/util/ObjectFactory.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/ObjectFactory.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/ObjectFactory.java index f9efe57a..5cb81c1d 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/ObjectFactory.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/ObjectFactory.java @@ -29,7 +29,8 @@ public static T instantiate( Class expectedClass, String classname, Properties info, boolean tryString, String stringarg) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { - Class loaded = Class.forName(classname, true, resolveClassLoader(expectedClass)); + // initialize=false: the static initializer must not run either, until the type check passes. + Class loaded = Class.forName(classname, false, resolveClassLoader(expectedClass)); if (!expectedClass.isAssignableFrom(loaded)) { throw new ClassCastException( "the class " + classname + " is not a " + expectedClass.getName() + ", so it was not instantiated"); From ca0a6ced31b1c1580279b65e03e81aca8f0f49d5 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:02:16 +0000 Subject: [PATCH 047/150] test(compat): pin that a wrong-typed ObjectFactory class is not initialized --- .../postgresql/util/ObjectFactoryTest.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/ObjectFactoryTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/ObjectFactoryTest.java index 852692a7..4e76e4bd 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/ObjectFactoryTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/ObjectFactoryTest.java @@ -10,6 +10,7 @@ import java.net.InetAddress; import java.net.Socket; import java.util.Properties; +import java.util.concurrent.atomic.AtomicBoolean; import javax.net.SocketFactory; import org.junit.jupiter.api.Test; import org.postgresql.PGProperty; @@ -33,6 +34,15 @@ public NotASocketFactory() { } } + static final AtomicBoolean STATIC_INIT_RAN = new AtomicBoolean(); + + /** Not a SocketFactory, with a static initializer; named only by string so nothing else loads it. */ + public static class StaticInitProbe { + static { + STATIC_INIT_RAN.set(true); + } + } + /** Takes the Properties constructor, which is the one ObjectFactory prefers. */ public static class CapturingSocketFactory extends SocketFactory { final Properties properties; @@ -85,6 +95,19 @@ void rejectsAWrongTypedClassWithoutConstructingIt() { assertFalse(NotASocketFactory.instantiated, "the wrong-typed class must not have been constructed"); } + @Test + void rejectsAWrongTypedClassWithoutInitializingIt() { + assertThrows( + ClassCastException.class, + () -> ObjectFactory.instantiate( + SocketFactory.class, + ObjectFactoryTest.class.getName() + "$StaticInitProbe", + new Properties(), + false, + null)); + assertFalse(STATIC_INIT_RAN.get(), "the wrong-typed class's static initializer must not have run"); + } + @Test void prefersThePropertiesConstructor() throws Exception { Properties props = new Properties(); From 497cc3c9eb444f6e456f4eea84c6ee865eb5e320 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:03:03 +0000 Subject: [PATCH 048/150] fix(compat): read a repeated URL key the same way everywhere The compat driver parsed the URL query twice: translateUrl, which feeds the connection, kept the last value of a repeated key, and rawProperty, which feeds the emulated properties (readOnly, ignoreEnvironment, allowUnencryptedPasswordAuth, the auth plugin), kept the first. A readOnly=false placed ahead of the deployer's readOnly=true therefore won in one path and lost in the other. Parse the query in one place, last value wins, and have both read it. --- .../src/main/java/org/postgresql/Driver.java | 51 +++++++++++-------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java index 7b01af84..b69f21b4 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java @@ -342,20 +342,9 @@ static String translateUrl(String url) throws PSQLException { return url; } String base = url.substring(0, question); - String query = url.substring(question + 1); - LinkedHashMap pairs = new LinkedHashMap<>(); - for (String pair : query.split("&")) { - if (pair.isEmpty()) { - continue; - } - int eq = pair.indexOf('='); - String name = eq < 0 ? pair : pair.substring(0, eq); - String value = eq < 0 ? "" : decode(pair.substring(eq + 1)); - pairs.put(name, value); - } StringBuilder out = new StringBuilder(base); char separator = '?'; - for (Map.Entry e : translate(pairs).entrySet()) { + for (Map.Entry e : translate(queryParameters(url)).entrySet()) { out.append(separator).append(e.getKey()).append('=').append(encode(e.getValue())); separator = '&'; } @@ -386,18 +375,36 @@ private static void warnOnce(String name, String message) { } } + /** + * The URL's query parameters, values percent-decoded. A repeated key keeps its last value. Both + * the translation and {@link #rawProperty} read this one map: they used to parse separately, one + * first-wins and the other last-wins, so {@code readOnly=false&readOnly=true} meant one thing to + * the connection and the opposite to the emulated read-only switch. + */ + private static LinkedHashMap queryParameters(String url) { + LinkedHashMap pairs = new LinkedHashMap<>(); + int question = url.indexOf('?'); + if (question < 0) { + return pairs; + } + for (String pair : url.substring(question + 1).split("&")) { + if (pair.isEmpty()) { + continue; + } + int eq = pair.indexOf('='); + String name = eq < 0 ? pair : pair.substring(0, eq); + String value = eq < 0 ? "" : decode(pair.substring(eq + 1)); + pairs.put(name, value); + } + return pairs; + } + /** Reads a raw (untranslated) property value from the URL query or {@code Properties}. */ - private static String rawProperty(String url, Properties info, String name) { + static String rawProperty(String url, Properties info, String name) { if (url != null) { - int question = url.indexOf('?'); - if (question >= 0) { - for (String pair : url.substring(question + 1).split("&")) { - int eq = pair.indexOf('='); - String key = eq < 0 ? pair : pair.substring(0, eq); - if (key.equals(name)) { - return eq < 0 ? "" : decode(pair.substring(eq + 1)); - } - } + Map query = queryParameters(url); + if (query.containsKey(name)) { + return query.get(name); } } return info == null ? null : info.getProperty(name); From 35c47897c5ce810daeb50e66b5043f56c33a2d68 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:03:03 +0000 Subject: [PATCH 049/150] test(compat): pin repeated URL keys resolving alike in both paths --- .../src/test/java/org/postgresql/DriverTest.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java index 16845646..5e0b91cc 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java @@ -214,6 +214,16 @@ void translatesUrlValuesAndFoldsCurrentSchema() throws Exception { assertEquals("jdbc:postgresql://h/db?preferQueryMode=extended-for-prepared", translated); } + @Test + void repeatedUrlKeysResolveTheSameWayForTranslationAndEmulation() throws Exception { + // readOnly is emulated from the raw URL while sslmode goes through the translation; a + // repeated key has to mean the same thing to both, and that is the last value. + String url = "jdbc:postgresql://h/db?readOnly=false&sslmode=disable&readOnly=true&sslmode=require"; + assertEquals("true", Driver.rawProperty(url, null, "readOnly")); + assertEquals("require", Driver.rawProperty(url, null, "sslmode")); + assertEquals("jdbc:postgresql://h/db?sslmode=require", Driver.translateUrl(url)); + } + @Test void urlWithoutQueryIsUnchanged() throws Exception { assertEquals("jdbc:postgresql://h/db", Driver.translateUrl("jdbc:postgresql://h/db")); From 39bb3ba06a8b5508417214ea8149860bdb192c2c Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:04:45 +0000 Subject: [PATCH 050/150] fix(core): close the connection when standard_conforming_strings turns off SessionBootstrap refuses standard_conforming_strings=off at connect time under forceSessionDefaults, because the SQL lexers assume standard string literals. The same state reached by a later SET, a function or a role default behind a pooler was recorded in SessionState and acted on by nothing, so the JDBC placeholder lexer then misread 'It\'s', and the interpolating paths fixed separately (the composite type lookup and escapeLiteral) became injectable. Treat the runtime flip like the connect-time one: throw from the ParameterStatus handler, which marks the connection broken. A session bootstrapped with forceSessionDefaults(false) still accepts it. --- .../client/core/CoreConnection.java | 28 +++++++++++-------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java b/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java index 7e151863..6a5560d8 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java @@ -1980,9 +1980,9 @@ void applyParameterStatus(String name, String value) { try { refreshSessionState(name, value); } catch (RuntimeException e) { - // An unmappable client_encoding throws out of the middle of a response, leaving the rest - // of it on the wire; reusing the connection would hand this statement's messages to the - // next one. + // An unmappable client_encoding, or standard_conforming_strings turned off, throws out of + // the middle of a response, leaving the rest of it on the wire; reusing the connection + // would hand this statement's messages to the next one. markBroken(); throw e; } @@ -2019,14 +2019,20 @@ private void refreshSessionState(String name, String value) { s.timeZone(), value, s.standardConformingStrings()); - case "standard_conforming_strings" -> - new SessionState( - s.capabilities(), - s.clientEncoding(), - s.integerDatetimes(), - s.timeZone(), - s.dateStyle(), - !"off".equalsIgnoreCase(value)); + case "standard_conforming_strings" -> { + boolean on = !"off".equalsIgnoreCase(value); + if (!on && config.forceSessionDefaults()) { + // SessionBootstrap refuses "off" at connect time because the SQL lexers assume + // standard string literals; a later SET, function or role default reaching the + // same state is no safer. The caller's handler marks the connection broken. + throw new PgConnectionException("standard_conforming_strings was turned off on this connection;" + + " this driver requires it on (the SQL lexer assumes standard string literals), so" + + " the connection is closed. Leave it on, or set forceSessionDefaults(false) to" + + " relax this."); + } + yield new SessionState( + s.capabilities(), s.clientEncoding(), s.integerDatetimes(), s.timeZone(), s.dateStyle(), on); + } case "integer_datetimes" -> new SessionState( s.capabilities(), From 02801a129b9e07c84a65fd1d744c8f468ba6ca40 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:04:45 +0000 Subject: [PATCH 051/150] test(core): pin that turning standard_conforming_strings off closes the connection Also renames the class to cover both runtime parameter cases. --- ...t.java => SessionParameterChangeTest.java} | 28 ++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) rename postgresql-client/src/test/java/org/postgresql/client/core/{UnmappableEncodingTest.java => SessionParameterChangeTest.java} (70%) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/UnmappableEncodingTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/SessionParameterChangeTest.java similarity index 70% rename from postgresql-client/src/test/java/org/postgresql/client/core/UnmappableEncodingTest.java rename to postgresql-client/src/test/java/org/postgresql/client/core/SessionParameterChangeTest.java index b8c168d0..2ba4c1fa 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/UnmappableEncodingTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/SessionParameterChangeTest.java @@ -12,12 +12,12 @@ import org.postgresql.client.core.transport.MockServer; /** - * A {@code client_encoding} report the driver cannot map throws out of the middle of a response. - * The rest of that response is still on the wire, so the connection must be marked broken rather - * than reused: on a pre-14 server, where the report precedes {@code CommandComplete}, the next + * A runtime {@code ParameterStatus} the connection cannot live with throws out of the middle of a + * response. The rest of that response is still on the wire, so the connection must be marked broken + * rather than reused: on a pre-14 server, where the report precedes {@code CommandComplete}, the next * statement would otherwise read this one's tail and the one after it the next one's rows. */ -class UnmappableEncodingTest { +class SessionParameterChangeTest { private static CoreConnection connect(MockServer server) { PgConnectionConfig config = PgConnectionConfig.builder() @@ -73,4 +73,24 @@ void reportBeforeReadyForQueryBreaksTheConnection() { }); assertTrue(connection.isBroken()); } + + @Test + void standardConformingStringsTurnedOffBreaksTheConnection() { + // The connect-time refusal of "off" (forceSessionDefaults) has to hold for a later SET too: + // the SQL lexers would otherwise misread 'It\'s' on this connection from then on. + MockServer server = new MockServer() + .onMessage((s, f) -> s.send( + BackendWire.commandComplete("SET"), + BackendWire.parameterStatus("standard_conforming_strings", "off"), + BackendWire.readyForQuery('I'))); + CoreConnection connection = connect(server); + + PgConnectionException e = assertThrows(PgConnectionException.class, () -> { + try (PgResultStream rs = connection.execute("SET standard_conforming_strings = off")) { + rs.next(); + } + }); + assertTrue(e.getMessage().contains("standard_conforming_strings"), e.getMessage()); + assertTrue(connection.isBroken()); + } } From 24dc34ad87a06648c454335013d08500f7ef839a Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:06:43 +0000 Subject: [PATCH 052/150] fix(compat): send currentSchema as its own search_path parameter currentSchema was folded into the startup options string as "-c search_path=" without quoting, and the server splits options on whitespace, so "public -c work_mem=1GB -c default_transaction_read_only=on" set all three GUCs, and a legitimate "app, public" was rejected as "app,". Send it as a search_path startup parameter instead, as pgjdbc does; the core driver forwards unknown keys as runtime parameters. Checked on 17: "app, public" now applies, and the smuggling value is refused as an invalid search_path. --- .../src/main/java/org/postgresql/Driver.java | 33 ++----------------- .../org/postgresql/PgPropertyMappings.java | 11 ++++--- 2 files changed, 10 insertions(+), 34 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java index b69f21b4..757f868d 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java @@ -41,9 +41,8 @@ * *

Translation policy: a property that maps to a core knob is forwarded (with value translation * where pgjdbc and core spell enums differently); a property pg-java emulates (for example - * {@code currentSchema}, {@code readOnly}) is synthesized here; a recognized-but-unsupported - * property, or an unknown name, is dropped with a one-time warning rather than forwarded as a - * bogus server runtime parameter. + * {@code readOnly}) is synthesized here; a recognized-but-unsupported property, or an unknown name, + * is dropped with a one-time warning rather than forwarded as a bogus server runtime parameter. * *

Loading this class deregisters the native {@link PgDriver} (which auto-registers itself for * {@code jdbc:postgresql:}) from the {@link DriverManager}, so this compatibility driver is the @@ -258,8 +257,6 @@ private int intProperty(String url, Properties info, String name, int fallback) */ private static LinkedHashMap translate(LinkedHashMap pgPairs) throws PSQLException { LinkedHashMap coreParams = new LinkedHashMap<>(); - String explicitOptions = null; - String searchPath = null; for (Map.Entry entry : pgPairs.entrySet()) { String name = entry.getKey(); String value = entry.getValue(); @@ -274,39 +271,15 @@ private static LinkedHashMap translate(LinkedHashMap{@link Support#EMULATED} -- not a simple rename; {@link Driver} synthesizes the behavior - * (for example {@code currentSchema} folds into {@code options=-c search_path=...} and - * {@code readOnly} is applied to the connection after connect). Emulated properties are not - * forwarded verbatim. + * (for example {@code readOnly} is applied to the connection after connect). Emulated + * properties are not forwarded verbatim. *

  • {@link Support#UNSUPPORTED} -- recognized as a real pgjdbc property but not yet honored by * pg-java; dropped with a one-time warning rather than forwarded as a bogus server runtime * parameter. @@ -203,8 +202,12 @@ private static String mapReWriteBatchedInserts(String v) { mapped("targetServerType", "targetServerType"); mapped("loadBalanceHosts", "loadBalanceHosts"); + // Sent as its own startup parameter, as pgjdbc does. Folded into options as + // "-c search_path=..." it was split on whitespace by the server, so a value such as + // "public -c work_mem=1GB" set further GUCs. + mapped("currentSchema", "search_path"); + // -- Emulated (synthesized by the Driver, not forwarded verbatim) -- - emulated("currentSchema"); emulated("readOnly"); // -- Recognized but not yet supported (warn + drop) -- From d39b0949b62ce2e55a6aadff1c99dc60d86a5ea1 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:06:43 +0000 Subject: [PATCH 053/150] test(compat): pin currentSchema translating to search_path --- .../src/test/java/org/postgresql/DriverTest.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java index 5e0b91cc..3fd00f92 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java @@ -166,25 +166,28 @@ void rewriteBatchUsingArraysPassesThroughUnderItsNativeName() throws Exception { } @Test - void currentSchemaFoldsIntoOptions() throws Exception { + void currentSchemaIsSentAsSearchPath() throws Exception { Properties info = new Properties(); info.setProperty("currentSchema", "myschema"); Properties core = Driver.translateProperties(info); - assertEquals("-c search_path=myschema", core.getProperty("options")); + assertEquals("myschema", core.getProperty("search_path")); assertNull(core.getProperty("currentSchema")); + assertNull(core.getProperty("options")); } @Test - void currentSchemaMergesWithExplicitOptions() throws Exception { + void currentSchemaCannotSmuggleOptions() throws Exception { + // Folded into options, the server split the value on whitespace and applied each -c. Properties info = new Properties(); info.setProperty("options", "-c statement_timeout=1000"); - info.setProperty("currentSchema", "app"); + info.setProperty("currentSchema", "public -c work_mem=1GB"); Properties core = Driver.translateProperties(info); - assertEquals("-c statement_timeout=1000 -c search_path=app", core.getProperty("options")); + assertEquals("-c statement_timeout=1000", core.getProperty("options")); + assertEquals("public -c work_mem=1GB", core.getProperty("search_path")); } @Test @@ -209,7 +212,7 @@ void translatesUrlQueryNamesAndPreservesBase() throws Exception { } @Test - void translatesUrlValuesAndFoldsCurrentSchema() throws Exception { + void translatesUrlValues() throws Exception { String translated = Driver.translateUrl("jdbc:postgresql://h/db?preferQueryMode=extendedForPrepared"); assertEquals("jdbc:postgresql://h/db?preferQueryMode=extended-for-prepared", translated); } From 4913b01c9c2e5268c43f9256f9c017ab0b7e39bc Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:07:43 +0000 Subject: [PATCH 054/150] fix(core): refuse an lo_read reply longer than requested CoreLargeObject.read returned whatever the server sent. The compat LargeObject.read(byte[], off, len) copies that into the caller's window by the reply's length, so a longer reply from a server or MITM overran the window into the rest of the caller's array, or threw ArrayIndexOutOfBoundsException. Fail with a PgException instead; the call itself completed, so the connection stays usable. --- .../org/postgresql/client/core/CoreLargeObject.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/CoreLargeObject.java b/postgresql-client/src/main/java/org/postgresql/client/core/CoreLargeObject.java index ee0fc705..b6a7c1ab 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/CoreLargeObject.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/CoreLargeObject.java @@ -20,7 +20,15 @@ public byte[] read(int length) { requireOpen(); byte[] result = connection.fastpathCall( LargeObjects.LO_READ, new byte[][] {LargeObjects.int4(fd), LargeObjects.int4(length)}); - return result != null ? result : new byte[0]; + if (result == null) { + return new byte[0]; + } + // Callers size their destination by what they asked for; a longer reply would overrun it. + if (result.length > length) { + throw new PgException( + "lo_read returned " + result.length + " bytes, more than the " + length + " requested"); + } + return result; } @Override From 1c4bfce35c16d6c2603c0438f726581fa68f7527 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:07:43 +0000 Subject: [PATCH 055/150] test(core): pin the lo_read reply length check --- .../core/LargeObjectReadLengthTest.java | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/LargeObjectReadLengthTest.java diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/LargeObjectReadLengthTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/LargeObjectReadLengthTest.java new file mode 100644 index 00000000..22822bc5 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/LargeObjectReadLengthTest.java @@ -0,0 +1,63 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.nio.ByteBuffer; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.auth.TrustAuthenticator; +import org.postgresql.client.core.internal.StartupOrchestrator; +import org.postgresql.client.core.internal.StartupResult; +import org.postgresql.client.core.internal.WireChannel; +import org.postgresql.client.core.transport.BackendWire; +import org.postgresql.client.core.transport.MockServer; +import org.postgresql.client.protocol.MessageType; + +/** An {@code lo_read} reply longer than requested would overrun a caller's buffer sized by the request. */ +class LargeObjectReadLengthTest { + + private static byte[] functionCallResponse(byte[] result) { + return ByteBuffer.allocate(1 + 4 + 4 + result.length) + .put((byte) 'V') + .putInt(4 + 4 + result.length) + .putInt(result.length) + .put(result) + .array(); + } + + /** Opens fd 7, then answers every lo_read with {@code readReply}. */ + private static PgLargeObject open(byte[] readReply) { + int[] calls = {0}; + MockServer server = new MockServer().onMessage((s, f) -> { + if (f.type() == MessageType.Frontend.FUNCTION_CALL) { + byte[] result = calls[0]++ == 0 ? new byte[] {0, 0, 0, 7} : readReply; + s.send(functionCallResponse(result), BackendWire.readyForQuery('T')); + } + }); + PgConnectionConfig config = PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .build(); + server.onStartup((s, f) -> s.send(BackendWire.authenticationOk(), BackendWire.readyForQuery('I'))); + WireChannel channel = new WireChannel(server, SizeLimits.unlimited()); + StartupResult startup = new StartupOrchestrator( + channel, config, HostAndPort.of("h"), TrustAuthenticator.INSTANCE, PgConnectionListener.NO_OP) + .run(); + CoreConnection connection = + new CoreConnection(channel, config, startup, HostAndPort.of("h"), PgConnectionListener.NO_OP); + return connection.openLargeObject(1234, LargeObjects.INV_READ); + } + + @Test + void longerReplyThanRequestedIsRefused() { + PgLargeObject lo = open(new byte[1000]); + assertThrows(PgException.class, () -> lo.read(4)); + } + + @Test + void shortOrExactRepliesAreReturned() { + assertArrayEquals(new byte[] {1, 2}, open(new byte[] {1, 2}).read(4)); + assertArrayEquals(new byte[] {1, 2, 3, 4}, open(new byte[] {1, 2, 3, 4}).read(4)); + } +} From 69ea02968250fcf3630eed62ff01d472f1d22268 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:09:15 +0000 Subject: [PATCH 056/150] docs(plans): record currentSchema as a search_path mapping The compat plan still described currentSchema as folded into options, which the previous fix replaced with a search_path startup parameter. --- docs/plans/pgjdbc-wrapper.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/plans/pgjdbc-wrapper.md b/docs/plans/pgjdbc-wrapper.md index 979823ad..a7031647 100644 --- a/docs/plans/pgjdbc-wrapper.md +++ b/docs/plans/pgjdbc-wrapper.md @@ -99,9 +99,10 @@ Three sinks for a translated property, in order of preference: `PgConnectionConfig.Builder` programmatically. **Decision:** add the missing parser keys to core (one commit, W-A0) so both drivers gain them and the shim stays string-based. -3. **Shim-side emulation** (`currentSchema` -> `options=-c search_path=...`, - `readOnly` -> post-connect `SET`/`Connection.setReadOnly`, `tcpKeepAlive` -> - core socket option): handled in the compat layer or a small core knob. +3. **Shim-side emulation** (`readOnly` -> post-connect `SET`/`Connection.setReadOnly`, + `tcpKeepAlive` -> core socket option): handled in the compat layer or a small + core knob. `currentSchema` started here too, folded into `options`; it is now a + plain mapping to a `search_path` startup parameter (see 3.3). ### 3.3 Unknown / unsupported property policy (replaces silent drop) @@ -187,9 +188,10 @@ The 80% of real-world configs. Land these first after A0/A1. - [x] `sslnegotiation` -> `sslnegotiation` (MAP): `postgres|direct`, identical. - [x] `sslrootcert`/`sslcert`/`sslkey`/`sslpassword`/`sslcrl` already (MAP); add `sslmode` aliasing of pgjdbc-only nuance where `ssl=true` implies verify-full. *(2026-07-28: partial -- sslcrl absent from PgPropertyMappings, warn-dropped though core accepts it)* -- [x] `currentSchema` -> EMULATE: fold into `options=-c search_path=` (merge - with any existing options) (SHIM). Consider a first-class `search_path` core - knob later. +- [x] `currentSchema` -> MAP to a `search_path` startup parameter, as pgjdbc sends + it. It was first folded into `options=-c search_path=`, which the server + splits on whitespace, so the value could carry further `-c` settings and + `app, public` was rejected. - [x] `readOnly` + `readOnlyMode` -> EMULATE: set JDBC read-only / issue `SET default_transaction_read_only`; map `readOnlyMode=always|ignore|transaction` semantics (SHIM/CORE). *(2026-07-28: partial -- readOnlyMode unsupported, no always/ignore/transaction semantics)* From 864bf6514592c18ead62a2180697cd744894f8b3 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:29:30 +0000 Subject: [PATCH 057/150] fix(compat): encode spaces in data source URLs as %20, not '+' BaseDataSource.getUrl encoded values with URLEncoder, which writes a space as '+'. The compat driver decodes only %XX escapes, as the core parser does, so the '+' survived as a literal: setOptions("-c statement_timeout=5s") reached the server as "-c+statement_timeout=5s" and the connection failed, and any other bag value or database name with a space was mangled the same way. A literal '+' is already encoded as %2B, so turn every remaining '+' into %20. --- .../main/java/org/postgresql/ds/common/BaseDataSource.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java index 17462849..c23049b4 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java @@ -586,7 +586,11 @@ protected Map bagProperties() { } private static String encode(String value) { - return URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8); + // URLEncoder writes a space as '+', which the compat driver's %XX-only decoder (like the + // core parser's) keeps as a literal '+': options=-c a=b reached the server as "-c+a=b". A + // literal '+' is already %2B, so every '+' left is a space. + return URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8) + .replace("+", "%20"); } private static String decode(String value) { From e7bb012e7dae66222f1ef3ae52f9880a650c28f4 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:29:30 +0000 Subject: [PATCH 058/150] test(compat): pin spaces in data source URL values --- .../src/test/java/org/postgresql/DriverTest.java | 13 +++++++++++++ .../postgresql/ds/common/BaseDataSourceTest.java | 15 +++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java index 3fd00f92..dace5c65 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java @@ -15,6 +15,7 @@ import java.util.Properties; import org.junit.jupiter.api.Test; import org.postgresql.client.jdbc.PgDriver; +import org.postgresql.ds.PGSimpleDataSource; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; @@ -227,6 +228,18 @@ void repeatedUrlKeysResolveTheSameWayForTranslationAndEmulation() throws Excepti assertEquals("jdbc:postgresql://h/db?sslmode=require", Driver.translateUrl(url)); } + @Test + void dataSourceUrlValuesKeepTheirSpaces() throws Exception { + PGSimpleDataSource ds = new PGSimpleDataSource(); + ds.setOptions("-c statement_timeout=5s"); + ds.setApplicationName("a+b c"); + + Properties parsed = Driver.parseURL(Driver.translateUrl(ds.getUrl()), null); + + assertEquals("-c statement_timeout=5s", parsed.getProperty("options")); + assertEquals("a+b c", parsed.getProperty("application_name")); + } + @Test void urlWithoutQueryIsUnchanged() throws Exception { assertEquals("jdbc:postgresql://h/db", Driver.translateUrl("jdbc:postgresql://h/db")); diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java index ab404583..ededeef8 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java @@ -104,6 +104,21 @@ void badPortIsReportedWithoutTheRestOfTheUrl() { assertFalse(e.getMessage().contains("s3cret"), e.getMessage()); } + @Test + void spacesRoundTripWithoutPlusSigns() { + PGSimpleDataSource ds = new PGSimpleDataSource(); + ds.setDatabaseName("my db"); + ds.setOptions("-c statement_timeout=5s"); + ds.setApplicationName("a+b c"); + String url = ds.getUrl(); + // The compat driver decodes %XX only, so a '+' for a space would arrive as a '+'. + assertFalse(url.contains("+"), url); + PGSimpleDataSource copy = copyViaSetUrl(ds); + assertEquals("my db", copy.getDatabaseName()); + assertEquals("-c statement_timeout=5s", copy.getOptions()); + assertEquals("a+b c", copy.getApplicationName()); + } + @Test void shortFormUrlTargetsLocalhost() { PGSimpleDataSource ds = new PGSimpleDataSource(); From 1353e732e93202962a451435429554b77786c852 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:53:24 +0000 Subject: [PATCH 059/150] docs(adr): limit custom batch rewriter class names to Properties ADR-0014 and ADR-0016 listed a custom class name among the accepted values with no word on where it may come from. Since cece8890 the driver refuses one in the URL query and accepts it only from the connection Properties, like authenticationPluginClassName; say so. --- docs/adr/ADR-0014-batch-array-rewrite.md | 4 +++- docs/adr/ADR-0016-batch-multi-values-rewrite.md | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/adr/ADR-0014-batch-array-rewrite.md b/docs/adr/ADR-0014-batch-array-rewrite.md index 0aff7802..afe68768 100644 --- a/docs/adr/ADR-0014-batch-array-rewrite.md +++ b/docs/adr/ADR-0014-batch-array-rewrite.md @@ -89,7 +89,9 @@ lookup), unless rewriters pin element types via casts. - unset / `off` / `false` / `no` / `0` -- disabled (**default**); - `on` / `yes` / `true` / `1` / `latest` / `default` -- the latest built-in rewriter; - any other token -- a pinned built-in version/id, or a fully-qualified class name of - a custom `BatchArrayRewriter`. + a custom `BatchArrayRewriter`. A class name is accepted only from the connection + `Properties`; one in the URL query fails the connection, as for + `authenticationPluginClassName` (N2.9), because a class name is code to run. The default binding for "on" pins to a **fixed** built-in version, not "whatever is latest at runtime": a driver upgrade must never silently start rewriting a statement diff --git a/docs/adr/ADR-0016-batch-multi-values-rewrite.md b/docs/adr/ADR-0016-batch-multi-values-rewrite.md index 66e5fd89..49a38be4 100644 --- a/docs/adr/ADR-0016-batch-multi-values-rewrite.md +++ b/docs/adr/ADR-0016-batch-multi-values-rewrite.md @@ -57,6 +57,8 @@ compat layer's `reWriteBatchedInserts` translation onto it. rewriter, pinned to a **fixed** version so a driver upgrade never silently changes which statements are rewritten; - any other token -- a pinned built-in version/id, or a fully-qualified custom class name. + As for `rewriteBatchUsingArrays`, a class name is accepted only from the connection + `Properties`, never from the URL query. Like `rewriteBatchUsingArrays`, it is a JDBC-only knob: `PgDriver` reads and strips it before building the core config, so the core parser never sees it as a bogus server From 6c37c11042438d9f653e2de484825d5e359c99d8 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:57:33 +0000 Subject: [PATCH 060/150] fix(compat): load the JNDI Reference's class without initializing it PGObjectFactory loaded the class a Reference names with Class.forName, which runs its static initializer, and only then checked that it was a BaseDataSource. NamingManager already loads and initializes whatever factory class the same Reference names, so a hostile Reference gains nothing from this, but it is the one loader left in the driver that initializes before checking. Load with initialize=false, from the same class loader as before. --- .../main/java/org/postgresql/ds/common/PGObjectFactory.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/PGObjectFactory.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/PGObjectFactory.java index 899edfc1..273972c1 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/PGObjectFactory.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/PGObjectFactory.java @@ -25,9 +25,11 @@ public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtabl // The Reference names the concrete DataSource class (including the legacy // jdbc2.optional aliases and the xa flavor); anything in the BaseDataSource // family restores the same way. Unknown classes yield null per the JNDI contract. + // initialize=false: a class outside the family must not run its static initializer just + // by being named in a Reference. Class klass; try { - klass = Class.forName(ref.getClassName()); + klass = Class.forName(ref.getClassName(), false, PGObjectFactory.class.getClassLoader()); } catch (ClassNotFoundException e) { return null; } From acd6ab47c9fb295cd0aea54a04735de368befa85 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 14:57:33 +0000 Subject: [PATCH 061/150] test(compat): pin that PGObjectFactory does not initialize a foreign class --- .../ds/common/BaseDataSourceTest.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java index ededeef8..2b9ff037 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -11,6 +12,7 @@ import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.util.concurrent.atomic.AtomicBoolean; import javax.naming.Reference; import org.junit.jupiter.api.Test; import org.postgresql.ds.PGSimpleDataSource; @@ -119,6 +121,24 @@ void spacesRoundTripWithoutPlusSigns() { assertEquals("a+b c", copy.getApplicationName()); } + static final AtomicBoolean STATIC_INIT_RAN = new AtomicBoolean(); + + /** Not a BaseDataSource, with a static initializer; named only by string so nothing else loads it. */ + public static class StaticInitProbe { + static { + STATIC_INIT_RAN.set(true); + } + } + + @Test + void objectFactoryDoesNotInitializeAClassOutsideTheFamily() throws Exception { + Reference ref = new Reference( + BaseDataSourceTest.class.getName() + "$StaticInitProbe", PGObjectFactory.class.getName(), null); + + assertNull(new PGObjectFactory().getObjectInstance(ref, null, null, null)); + assertFalse(STATIC_INIT_RAN.get(), "the named class's static initializer must not have run"); + } + @Test void shortFormUrlTargetsLocalhost() { PGSimpleDataSource ds = new PGSimpleDataSource(); From 9425acc7718c129045a9c94a97fdb3cd0032965b Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:00:51 +0000 Subject: [PATCH 062/150] fix(core): reject malformed %-escapes and keep non-ASCII in URL decoding MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ConnectionStringParser.decode threw NumberFormatException on an escape such as %zz, which reached a PgDriver caller as a raw unchecked exception, and whenever a component held any %, it narrowed every other character to one byte, so "café%20db" decoded to garbage. Move the decoding into a small shared class: characters outside escapes are kept whole, escapes are read as UTF-8 bytes, and a % without two hex digits is a PgConfigurationException naming its position rather than the value, which may be a password. The compat driver had a copy of the same decoder and switches to this one next. --- .../internal/jdbc/ConnectionStringParser.java | 17 +------ .../core/internal/jdbc/PercentDecoding.java | 50 +++++++++++++++++++ 2 files changed, 51 insertions(+), 16 deletions(-) create mode 100644 postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/PercentDecoding.java diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java index a5b2cab6..9ad55e32 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java @@ -1,7 +1,6 @@ package org.postgresql.client.core.internal.jdbc; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; @@ -581,20 +580,6 @@ private static boolean isTruthy(String value) { } private static String decode(String s) { - if (s.indexOf('%') < 0) { - return s; - } - byte[] bytes = new byte[s.length()]; - int len = 0; - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c == '%' && i + 2 < s.length()) { - bytes[len++] = (byte) Integer.parseInt(s.substring(i + 1, i + 3), 16); - i += 2; - } else { - bytes[len++] = (byte) c; - } - } - return new String(bytes, 0, len, StandardCharsets.UTF_8); + return PercentDecoding.decode(s); } } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/PercentDecoding.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/PercentDecoding.java new file mode 100644 index 00000000..308722a4 --- /dev/null +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/PercentDecoding.java @@ -0,0 +1,50 @@ +package org.postgresql.client.core.internal.jdbc; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import org.postgresql.client.core.PgConfigurationException; + +/** + * Decodes the {@code %XX} escapes in a connection-URL component, for the core parser and the + * pgjdbc-compat driver alike. Only {@code %XX} is special; a {@code +} stays a {@code +}, as in libpq. + */ +public final class PercentDecoding { + + private PercentDecoding() {} + + /** + * Decodes {@code s}, reading the escaped bytes as UTF-8. Characters outside the escapes are kept + * whole: the decoders this replaced narrowed each one to a single byte whenever the component + * also held a {@code %}, which mangled any non-ASCII character. A {@code %} not followed by two + * hex digits is refused, as libpq does; the message gives its position, not the value, which can + * be a password. + */ + public static String decode(String s) { + int percent = s.indexOf('%'); + if (percent < 0) { + return s; + } + ByteArrayOutputStream bytes = new ByteArrayOutputStream(s.length()); + bytes.writeBytes(s.substring(0, percent).getBytes(StandardCharsets.UTF_8)); + int i = percent; + while (i < s.length()) { + char c = s.charAt(i); + if (c == '%') { + int high = i + 2 < s.length() ? Character.digit(s.charAt(i + 1), 16) : -1; + int low = high >= 0 ? Character.digit(s.charAt(i + 2), 16) : -1; + if (low < 0) { + throw new PgConfigurationException( + "invalid percent-encoding at position " + i + " of a connection URL component"); + } + bytes.write(high << 4 | low); + i += 3; + } else { + int next = s.indexOf('%', i); + int end = next < 0 ? s.length() : next; + bytes.writeBytes(s.substring(i, end).getBytes(StandardCharsets.UTF_8)); + i = end; + } + } + return bytes.toString(StandardCharsets.UTF_8); + } +} From 5b396a5b96791d4be73c064bdfa3b5d38d183e5d Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:00:51 +0000 Subject: [PATCH 063/150] test(core): pin URL percent-decoding of malformed escapes and non-ASCII --- .../core/ConnectionStringParserTest.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java index f3f9bbf8..a3639e30 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java @@ -245,4 +245,24 @@ void rejectsNullAndMalformed() { assertThrows(PgConfigurationException.class, () -> ConnectionStringParser.parse(null, Map.of())); assertThrows(PgConfigurationException.class, () -> ConnectionStringParser.parse("host user=app", Map.of())); } + + @Test + void malformedPercentEscapeIsAConfigurationError() { + for (String url : + new String[] {"postgresql://h/db?user=app&password=a%zzb", "postgresql://h/d%4", "postgresql://h/db%" + }) { + PgConfigurationException e = assertThrows( + PgConfigurationException.class, () -> ConnectionStringParser.parse(url, Map.of()), url); + assertFalse(e.getMessage().contains("a%zzb"), e.getMessage()); + } + } + + @Test + void nonAsciiCharactersSurviveAlongsideEscapes() { + PgConnectionConfig c = ConnectionStringParser.parse( + "postgresql://h/caf\u00e9%20db?user=\u00fcser%2B1&application_name=\u65e5%41", Map.of()); + assertEquals("caf\u00e9 db", c.database()); + assertEquals("\u00fcser+1", c.user()); + assertEquals("\u65e5A", c.applicationName()); + } } From 2425ff0063d125bd04a6585dcf591618f1026d16 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:00:51 +0000 Subject: [PATCH 064/150] fix(compat): decode URL escapes with the shared core decoder The compat driver's own decode had both defects of the core one it was copied from: NumberFormatException on %zz, out of connect and parseURL alike, and non-ASCII characters narrowed to a byte whenever a % was present. Use the shared decoder. connect reports a malformed escape as a PSQLException (22023), and parseURL answers null, as it already does for a malformed port. --- .../src/main/java/org/postgresql/Driver.java | 40 ++++++++++--------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java index 757f868d..4474b128 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java @@ -21,7 +21,9 @@ import org.postgresql.PgPropertyMappings.Mapping; import org.postgresql.PgPropertyMappings.Support; import org.postgresql.client.compat.internal.CompatPropertyTranslation; +import org.postgresql.client.core.PgConfigurationException; import org.postgresql.client.core.auth.AuthenticationProvider; +import org.postgresql.client.core.internal.jdbc.PercentDecoding; import org.postgresql.client.jdbc.PgDriver; import org.postgresql.client.jdbc.SqlExceptionFactoryRegistry; import org.postgresql.jdbc.PreferQueryMode; @@ -178,6 +180,15 @@ public Connection connect(String url, Properties info) throws SQLException { // first actual compat connection, rather than at class-load: the app is now genuinely using // the compat layer, so taking over the process-wide mapping is expected (A12-M13). installExceptionFactory(); + try { + return connectAccepted(url, info); + } catch (PgConfigurationException e) { + // A malformed %-escape in the URL, found before the native driver (which wraps its own). + throw new PSQLException(e.getMessage(), PSQLState.INVALID_PARAMETER_VALUE, e); + } + } + + private Connection connectAccepted(String url, Properties info) throws SQLException { // authenticationPluginClassName is handled here (emulated): instantiate it, adapt a pgjdbc // AuthenticationPlugin to the core seam, and pass it to the native driver programmatically // rather than forwarding the name as a connection-string key. @@ -392,24 +403,10 @@ private static boolean isTruthy(String value) { return v.isEmpty() || v.equals("true") || v.equals("1") || v.equals("yes") || v.equals("on"); } - // -- Percent-coding (RFC 3986 unreserved set), matching core's decoder. -- + // -- Percent-coding (RFC 3986 unreserved set), decoding shared with core. -- private static String decode(String s) { - if (s.indexOf('%') < 0) { - return s; - } - byte[] bytes = new byte[s.length()]; - int len = 0; - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c == '%' && i + 2 < s.length()) { - bytes[len++] = (byte) Integer.parseInt(s.substring(i + 1, i + 3), 16); - i += 2; - } else { - bytes[len++] = (byte) c; - } - } - return new String(bytes, 0, len, StandardCharsets.UTF_8); + return PercentDecoding.decode(s); } private static String encode(String s) { @@ -494,13 +491,18 @@ public static Properties parseURL(String url, Properties defaults) { } int eq = pair.indexOf('='); String name = eq < 0 ? pair : pair.substring(0, eq); - parsed.setProperty(decode(name), eq < 0 ? "" : decode(pair.substring(eq + 1))); + try { + parsed.setProperty(decode(name), eq < 0 ? "" : decode(pair.substring(eq + 1))); + } catch (PgConfigurationException e) { + return null; // a malformed %-escape makes the URL unacceptable, like a bad port + } } } - if (!parseAuthority(authorityAndPath, parsed)) { + try { + return parseAuthority(authorityAndPath, parsed) ? parsed : null; + } catch (PgConfigurationException e) { return null; } - return parsed; } /** From 4ba09fe13d80e809c851aadf047ec0616f378757 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:00:51 +0000 Subject: [PATCH 065/150] test(compat): pin URL percent-decoding in connect and parseURL --- .../org/postgresql/DriverParseUrlTest.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverParseUrlTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverParseUrlTest.java index 73d9cfe5..cb8df924 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverParseUrlTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverParseUrlTest.java @@ -1,8 +1,11 @@ package org.postgresql; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import java.sql.SQLException; import java.util.Properties; import org.junit.jupiter.api.Test; @@ -86,4 +89,24 @@ void reportsNullForAUrlItDoesNotAccept() { assertNull(Driver.parseURL("jdbc:postgresql://localhost:not-a-port/test", null)); assertNull(Driver.parseURL("jdbc:postgresql://localhost:99999/test", null)); } + + @Test + void decodesEscapesWithoutMangling() { + Properties p = Driver.parseURL("jdbc:postgresql://h/caf\u00e9%20db?ApplicationName=\u00fc%2Bx", null); + assertEquals("caf\u00e9 db", database(p)); + assertEquals("\u00fc+x", p.getProperty("ApplicationName")); + } + + @Test + void reportsNullForAMalformedEscape() { + assertNull(Driver.parseURL("jdbc:postgresql://h/db?password=a%zz", null)); + assertNull(Driver.parseURL("jdbc:postgresql://h/d%4", null)); + } + + @Test + void connectRefusesAMalformedEscapeAsSqlException() { + SQLException e = assertThrows(SQLException.class, () -> new Driver() + .connect("jdbc:postgresql://127.0.0.1:1/db?password=a%zz", new Properties())); + assertFalse(e.getMessage().contains("a%zz"), e.getMessage()); + } } From 3c322981753f66ebb9095622eb7ef2524bdc6c93 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:51:55 +0000 Subject: [PATCH 066/150] fix(core): require the postgresql ALPN protocol on direct TLS With sslnegotiation=direct the driver offered the postgresql ALPN protocol but never looked at what the server selected. Direct TLS skips the SSLRequest exchange, so the ALPN result is the only sign that the peer agreed to speak PostgreSQL on this connection rather than being some other TLS service on the same port, or a proxy that terminates TLS for one. libpq fails closed here; do the same. --- .../postgresql/client/core/TlsContexts.java | 2 +- .../postgresql/client/core/TlsNegotiator.java | 22 ++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/TlsContexts.java b/postgresql-client/src/main/java/org/postgresql/client/core/TlsContexts.java index 4d0eae0c..91a833b8 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/TlsContexts.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/TlsContexts.java @@ -30,7 +30,7 @@ final class TlsContexts { * a server accepting a direct connection that sees no {@code postgresql} ALPN protocol * drops the connection rather than speaking the protocol over an unconfirmed channel. */ - private static final String PG_ALPN_PROTOCOL = "postgresql"; + static final String PG_ALPN_PROTOCOL = "postgresql"; private TlsContexts() {} diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/TlsNegotiator.java b/postgresql-client/src/main/java/org/postgresql/client/core/TlsNegotiator.java index ea1c2edc..ca1c469d 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/TlsNegotiator.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/TlsNegotiator.java @@ -5,6 +5,7 @@ import javax.net.ssl.SSLSocketFactory; import org.jspecify.annotations.Nullable; import org.postgresql.client.core.transport.SocketTransport; +import org.postgresql.client.core.transport.TlsTransport; import org.postgresql.client.core.transport.Transport; import org.postgresql.client.protocol.ProtocolEncoder; import org.postgresql.client.protocol.message.SSLRequest; @@ -55,7 +56,26 @@ static Transport upgrade(SocketTransport plain, PgConnectionConfig config, Strin SSLSocketFactory factory = config.sslConfig().sslSocketFactory() != null ? config.sslConfig().sslSocketFactory() : context.getSocketFactory(); - return plain.upgradeToTls(factory, parameters, host, port); + TlsTransport tls = plain.upgradeToTls(factory, parameters, host, port); + if (config.sslNegotiation() == SslNegotiation.DIRECT) { + requirePostgresqlAlpn(tls, host, port); + } + return tls; + } + + /** + * Direct TLS has no SSLRequest exchange, so the ALPN result is the only sign that the peer + * agreed to speak the PostgreSQL protocol on this connection rather than some other TLS + * service on the same port. Offering the protocol is not enough; libpq also fails closed when + * the server did not select it. + */ + private static void requirePostgresqlAlpn(TlsTransport tls, String host, int port) { + String selected = tls.sslSocket().getApplicationProtocol(); + if (!TlsContexts.PG_ALPN_PROTOCOL.equals(selected)) { + tls.close(); + throw new PgTlsException("direct TLS connection to " + host + ":" + port + + " was established without the server selecting the postgresql ALPN protocol"); + } } private static byte readResponseByte(SocketTransport plain) { From 7e9a6b6c045c04449ed9cbd8dd4f4cdedfcb3f9a Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:51:55 +0000 Subject: [PATCH 067/150] test(core): pin the ALPN check on direct TLS --- .../client/core/DirectTlsAlpnTest.java | 100 ++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/DirectTlsAlpnTest.java diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/DirectTlsAlpnTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/DirectTlsAlpnTest.java new file mode 100644 index 00000000..4b86f619 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/DirectTlsAlpnTest.java @@ -0,0 +1,100 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLSocket; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +/** + * Direct TLS has no SSLRequest exchange, so the server selecting the {@code postgresql} ALPN + * protocol is the only confirmation that it speaks PostgreSQL on this connection. + */ +@Timeout(30) +class DirectTlsAlpnTest { + + @TempDir + Path dir; + + private SSLContext serverContext() throws Exception { + SslConfig material = SslConfig.builder() + .certFile(copy("/tls/test-client.crt")) + .keyFile(copy("/tls/test-client.key")) + .build(); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(SslMaterials.keyManagers(material), null, null); + return context; + } + + private Path copy(String resource) throws IOException { + try (InputStream in = DirectTlsAlpnTest.class.getResourceAsStream(resource)) { + assertNotNull(in, resource); + return Files.write(dir.resolve(Path.of(resource).getFileName().toString()), in.readAllBytes()); + } + } + + /** Accepts one connection, completes the handshake selecting {@code alpn} (none if null), then hangs up. */ + private static Thread serve(SSLServerSocket server, String alpn) { + return Thread.ofVirtual().start(() -> { + try (SSLSocket socket = (SSLSocket) server.accept()) { + if (alpn != null) { + SSLParameters parameters = socket.getSSLParameters(); + parameters.setApplicationProtocols(new String[] {alpn}); + socket.setSSLParameters(parameters); + } + socket.startHandshake(); + socket.getInputStream().read(); + } catch (IOException e) { + // the client gave up, which is what the refusing case expects + } + }); + } + + private static PgConnectionConfig config(int port) { + return PgConnectionConfig.builder() + .host("127.0.0.1", port) + .user("app") + .database("appdb") + .sslMode(SslMode.REQUIRE) + .sslNegotiation(SslNegotiation.DIRECT) + .loginTimeout(Duration.ofSeconds(5)) + .build(); + } + + @Test + void handshakeWithoutAlpnIsRefused() throws Exception { + try (SSLServerSocket server = (SSLServerSocket) + serverContext().getServerSocketFactory().createServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + Thread t = serve(server, null); + PgException e = assertThrows(PgException.class, () -> PgConnections.connect(config(server.getLocalPort()))); + assertTrue(e.getMessage().contains("ALPN"), e.getMessage()); + t.join(5000); + } + } + + @Test + void handshakeSelectingPostgresqlProceeds() throws Exception { + try (SSLServerSocket server = (SSLServerSocket) + serverContext().getServerSocketFactory().createServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + Thread t = serve(server, "postgresql"); + // The fake server hangs up after reading the startup message, so the connect still + // fails, but past the ALPN check. + PgException e = assertThrows(PgException.class, () -> PgConnections.connect(config(server.getLocalPort()))); + assertFalse(String.valueOf(e.getMessage()).contains("ALPN"), e.getMessage()); + t.join(5000); + } + } +} From 8a668935d4e6a88e5e6eb57680795ce3a4c5c9e3 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:52:57 +0000 Subject: [PATCH 068/150] fix(core): refuse a protocol negotiation that does not go down The minor version in NegotiateProtocolVersion was used as sent. A broken or hostile peer could name 3.99, or a negative minor, and the session would record a version it never offered, switching on protocol behaviour neither side agreed to. Refuse anything outside [0, requested), as libpq does; the driver sends no protocol options, so an answer naming the requested version itself carries no negotiation either. --- .../client/core/internal/StartupOrchestrator.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java index 06c4ff3a..43d80020 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java @@ -199,7 +199,16 @@ private int handleNegotiation(NegotiateProtocolVersion negotiate) { throw new PgConnectionException("server does not support the requested protocol version " + "and protocol-version fallback is not enabled"); } - return ProtocolConstants.protocolVersion(3, negotiate.newestMinorVersion()); + // A negotiation can only go down. Anything else is a broken or hostile peer claiming a + // version we never offered, which would switch on protocol features the session never + // agreed to; libpq refuses it the same way. + int offered = ProtocolConstants.protocolMinor(requestedVersionCode); + int minor = negotiate.newestMinorVersion(); + if (minor < 0 || minor >= offered) { + throw new PgConnectionException("invalid protocol negotiation: the server offered 3." + minor + + " in reply to a request for 3." + offered); + } + return ProtocolConstants.protocolVersion(3, minor); } /** Rejects an authentication method the {@code require_auth} policy does not permit. */ From f0f6f83a96c07718528784365e12b3770a851c2f Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:52:57 +0000 Subject: [PATCH 069/150] test(core): pin the refusal of an upward protocol negotiation --- .../client/core/StartupOrchestratorTest.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java index 02cba3eb..05fb93be 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java @@ -167,6 +167,25 @@ void negotiateProtocolVersionAcceptedWhenLatest() { assertEquals(ProtocolConstants.PROTOCOL_3_0, result.negotiatedProtocolVersion()); } + @Test + void negotiationCanOnlyGoDown() { + // The driver asks for 3.2 and sends no protocol options, so a reply naming 3.2 or above, or + // a negative minor, is not a negotiation the server could legitimately make. + PgConnectionConfig latest = PgConnectionConfig.builder() + .host("h") + .user("app") + .protocolVersionPolicy(ProtocolVersionPolicy.LATEST) + .build(); + for (int minor : new int[] {2, 3, 99, -1}) { + MockServer server = new MockServer() + .onStartup((s, frame) -> s.send( + BackendWire.negotiateProtocolVersion(minor), + BackendWire.authenticationOk(), + BackendWire.readyForQuery('I'))); + assertThrows(PgConnectionException.class, () -> run(server, latest), "3." + minor); + } + } + @Test void negotiateProtocolVersionRejectedWhenStrict() { MockServer server = new MockServer().onStartup((s, frame) -> s.send(BackendWire.negotiateProtocolVersion(0))); From 335dc0f9cb899723a8d546a4e1196aea9928f62b Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:54:03 +0000 Subject: [PATCH 070/150] fix(core): escape server text before it is logged The notification listener logged a server ErrorResponse message as is, and a failed connect attempt logged the exception message, which can be the server's FATAL text. A newline in either starts what reads as a separate, driver-written log entry, so a hostile server or MITM could forge log lines. Write CR, LF, tab and other control characters as escapes at both sites. --- .../client/core/BackgroundListener.java | 4 +- .../postgresql/client/core/PgConnections.java | 4 +- .../client/core/internal/LogText.java | 43 +++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 postgresql-client/src/main/java/org/postgresql/client/core/internal/LogText.java diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/BackgroundListener.java b/postgresql-client/src/main/java/org/postgresql/client/core/BackgroundListener.java index 9f598934..4b247877 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/BackgroundListener.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/BackgroundListener.java @@ -2,6 +2,7 @@ import java.time.Duration; import org.jspecify.annotations.Nullable; +import org.postgresql.client.core.internal.LogText; import org.postgresql.client.core.internal.ServerErrors; import org.postgresql.client.protocol.message.BackendMessage; import org.postgresql.client.protocol.message.ErrorResponse; @@ -99,7 +100,8 @@ private void loop() { // Unsolicited errors are terminal (e.g. FATAL 57P01 admin shutdown). LOG.warn( "notification listener received server error: {}", - ServerErrors.toServerMessage(error.fields()).message()); + LogText.escape(ServerErrors.toServerMessage(error.fields()) + .message())); connection.markBroken(); return; } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/PgConnections.java b/postgresql-client/src/main/java/org/postgresql/client/core/PgConnections.java index 4a4154f9..b9d8eb15 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/PgConnections.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/PgConnections.java @@ -6,6 +6,7 @@ import org.jspecify.annotations.Nullable; import org.postgresql.client.core.auth.Authenticator; import org.postgresql.client.core.auth.StandardAuthenticator; +import org.postgresql.client.core.internal.LogText; import org.postgresql.client.core.internal.ProtocolVersionUnsupportedException; import org.postgresql.client.core.internal.StartupOrchestrator; import org.postgresql.client.core.internal.StartupResult; @@ -63,7 +64,8 @@ public static PgConnection connect( connection.close(); // wrong server type for this pass; try the next host } catch (RuntimeException e) { lastFailure = e; - LOG.debug("connect attempt to {} failed: {}", host, e.getMessage()); + // The message can be a server's FATAL text. + LOG.debug("connect attempt to {} failed: {}", host, LogText.escape(e.getMessage())); if (connection != null) { connection.close(); } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/LogText.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/LogText.java new file mode 100644 index 00000000..f3fbf4a5 --- /dev/null +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/LogText.java @@ -0,0 +1,43 @@ +package org.postgresql.client.core.internal; + +import org.jspecify.annotations.Nullable; + +/** + * Makes text the server controls safe to put in a log line. A server error or notice can hold a + * newline, and logged as is it would start what looks like a separate, driver-written entry. + */ +public final class LogText { + + private LogText() {} + + /** {@code text} with CR, LF, tab and other control characters written as escapes. */ + public static @Nullable String escape(@Nullable String text) { + if (text == null) { + return null; + } + int i = 0; + while (i < text.length() && !Character.isISOControl(text.charAt(i))) { + i++; + } + if (i == text.length()) { + return text; + } + StringBuilder out = new StringBuilder(text.length() + 8).append(text, 0, i); + for (; i < text.length(); i++) { + char c = text.charAt(i); + switch (c) { + case '\r' -> out.append("\\r"); + case '\n' -> out.append("\\n"); + case '\t' -> out.append("\\t"); + default -> { + if (Character.isISOControl(c)) { + out.append(String.format("\\u%04x", (int) c)); + } else { + out.append(c); + } + } + } + } + return out.toString(); + } +} From 2500c60aeb73ec386167846553383345ef9c88a6 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:54:03 +0000 Subject: [PATCH 071/150] test(core): pin the escaping of server text for logs --- .../postgresql/client/core/LogTextTest.java | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/LogTextTest.java diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/LogTextTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/LogTextTest.java new file mode 100644 index 00000000..90bd9c51 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/LogTextTest.java @@ -0,0 +1,26 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.internal.LogText; + +/** Server text goes into log lines escaped, so a newline in it cannot start a forged entry. */ +class LogTextTest { + + @Test + void escapesLineBreaksAndControlCharacters() { + assertEquals( + "relation does not exist\\n12:00:00 WARN admin password reset\\r\\t\\u0007", + LogText.escape("relation does not exist\n12:00:00 WARN admin password reset\r\t\u0007")); + } + + @Test + void leavesOrdinaryTextAlone() { + String text = "duplicate key value violates unique constraint \"t_pkey\" (caf\u00e9)"; + assertSame(text, LogText.escape(text)); + assertNull(LogText.escape(null)); + } +} From 01456be4618a4a90595701fd1c20f69bece7f173 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:56:57 +0000 Subject: [PATCH 072/150] fix(core): keep the last value of a repeated connection-string key The core parser kept the first value of a key repeated in a URL query or a key-value string, while libpq, pgjdbc and the compat driver keep the last, so one URL configured a connection two ways depending on the driver it went through: sslmode=disable&...&sslmode=require was plaintext through the native driver and TLS through compat. Keep the last value within the query and within a key-value string. The userinfo and path still outrank the query as before. PgDriver appends the connection Properties to the query, so it now skips any property the URL already sets, keeping the URL's precedence. --- .../org/postgresql/client/jdbc/PgDriver.java | 28 ++++++++++++++++++- .../internal/jdbc/ConnectionStringParser.java | 8 ++++-- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java index e776412e..140f2539 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java @@ -22,6 +22,7 @@ import org.postgresql.client.core.auth.AuthenticationProvider; import org.postgresql.client.core.auth.StandardAuthenticator; import org.postgresql.client.core.internal.jdbc.ConnectionStringParser; +import org.postgresql.client.core.internal.jdbc.PercentDecoding; import org.postgresql.client.jdbc.batch.BatchArrayRewriter; import org.postgresql.client.jdbc.batch.BatchArrayRewriters; import org.postgresql.client.jdbc.batch.BatchRewriteSetting; @@ -403,9 +404,17 @@ private static String queryParam(String url, String name) { } /** Builds a core config by merging the URL (higher precedence) with the supplied properties. */ - private static PgConnectionConfig buildConfig(String url, Properties info) throws SQLException { + static PgConnectionConfig buildConfig(String url, Properties info) throws SQLException { StringBuilder uri = new StringBuilder(normalizeUri(url.substring("jdbc:".length()))); char separator = uri.indexOf("?") >= 0 ? '&' : '?'; + // The properties go on the end of the query, where a repeated key's last value wins; skip + // the ones the URL already sets, so the URL keeps its precedence. + java.util.Set urlKeys; + try { + urlKeys = queryKeys(uri.toString()); + } catch (PgException e) { + throw PgSqlExceptions.wrap(e); // a malformed %-escape in a key + } for (String name : info.stringPropertyNames()) { if (JDBC_ONLY_PROPERTIES.contains(name)) { continue; // JDBC-only: consumed by the driver, not a core connection-string key @@ -415,6 +424,9 @@ private static PgConnectionConfig buildConfig(String url, Properties info) throw continue; } String key = PROPERTY_RENAMES.getOrDefault(name, name); + if (urlKeys.contains(key)) { + continue; + } uri.append(separator).append(encode(key)).append('=').append(encode(value)); separator = '&'; } @@ -430,6 +442,20 @@ private static PgConnectionConfig buildConfig(String url, Properties info) throw } } + /** The decoded keys of {@code uri}'s query parameters. */ + private static java.util.Set queryKeys(String uri) { + java.util.Set keys = new java.util.HashSet<>(); + int q = uri.indexOf('?'); + if (q < 0) { + return keys; + } + for (String pair : uri.substring(q + 1).split("&")) { + int eq = pair.indexOf('='); + keys.add(PercentDecoding.decode(eq >= 0 ? pair.substring(0, eq) : pair)); + } + return keys; + } + /** Returns {@code uri} with every {@code key=...} query parameter removed. */ private static String stripQueryParam(String uri, String key) { int q = uri.indexOf('?'); diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java index 9ad55e32..985fdb3e 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java @@ -123,6 +123,9 @@ private static void parseUri(String rest, Map params, List queryParams = new LinkedHashMap<>(); for (String pair : query.split("&")) { if (pair.isEmpty()) { continue; @@ -130,8 +133,9 @@ private static void parseUri(String rest, Map params, List putIfAbsent(params, key, value)); } } @@ -211,7 +215,7 @@ private static void parseKeyValue(String input, Map params) { i++; } } - putIfAbsent(params, key, value.toString()); + params.put(key, value.toString()); // a repeated key keeps its last value, as in libpq } } From 9d5b43d23d0c16ecdcd00c6decc0cb4910cd2b86 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:56:57 +0000 Subject: [PATCH 073/150] test(core): pin last-wins for repeated connection-string keys Also pins that the URL still outranks Properties in PgDriver. --- .../postgresql/client/jdbc/PgDriverTest.java | 17 +++++++++++++++ .../core/ConnectionStringParserTest.java | 21 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java index ba0c6b42..ed959bbd 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java @@ -14,6 +14,8 @@ import java.util.Properties; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Isolated; +import org.postgresql.client.core.PgConnectionConfig; +import org.postgresql.client.core.SslMode; // Mutates process-global state (the DriverManager registry), so it must not run concurrently with // any other test (analysis-013 F14). @@ -150,6 +152,21 @@ void customRewriterClassIsStillAcceptedFromProperties() { assertTrue(e.getMessage().contains("does not implement"), e.getMessage()); } + @Test + void urlStillOutranksPropertiesOfTheSameName() throws SQLException { + // Properties are appended to the URL query, where a repeated key's last value now wins; + // the URL's own value must still be the one used. + Properties info = new Properties(); + info.setProperty("user", "app"); + info.setProperty("sslmode", "disable"); + info.setProperty("application_name", "from-properties"); + PgConnectionConfig config = + PgDriver.buildConfig("jdbc:postgresql://h/db?sslmode=require&application_name=from-url", info); + assertEquals(SslMode.REQUIRE, config.sslMode()); + assertEquals("from-url", config.applicationName()); + assertEquals("app", config.user()); + } + @Test void reportsVersionAndCompliance() { assertEquals(0, driver.getMajorVersion()); diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java index a3639e30..3c63a4d5 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java @@ -265,4 +265,25 @@ void nonAsciiCharactersSurviveAlongsideEscapes() { assertEquals("\u00fcser+1", c.user()); assertEquals("\u65e5A", c.applicationName()); } + + @Test + void repeatedQueryKeyKeepsItsLastValue() { + PgConnectionConfig c = parse("postgresql://h/db?user=app&sslmode=disable&application_name=a&sslmode=require"); + assertEquals(SslMode.REQUIRE, c.sslMode()); + assertEquals("a", c.applicationName()); + } + + @Test + void userinfoAndPathStillOutrankTheQuery() { + PgConnectionConfig c = parse("postgresql://alice@h/db?user=mallory&dbname=other&user=eve"); + assertEquals("alice", c.user()); + assertEquals("db", c.database()); + } + + @Test + void repeatedKeyValueKeyKeepsItsLastValue() { + PgConnectionConfig c = + ConnectionStringParser.parse("host=h user=app sslmode=disable sslmode=require", Map.of()); + assertEquals(SslMode.REQUIRE, c.sslMode()); + } } From 2c421f6902284f0b351b259ec11e52b5a8571569 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:58:18 +0000 Subject: [PATCH 074/150] fix(jdbc): match JDBC-only URL keys after percent-decoding them PgDriver stripped the JDBC-only keys from the URL query, and read the claim-scheme and rewriter keys from it, by comparing raw text, while the core parser decodes keys. %61uthenticationPluginClassName= was therefore not stripped and went to the server as a startup parameter, and an encoded rewriteBatchUsingArrays key escaped the check that refuses a custom class name from the URL. Both failed closed, since the driver then never acted on the key, but the two readings of one URL should agree. Decode keys and values before comparing, keeping the last of a repeated key as the core parser does. The compat driver's query reading decodes keys too now, as its parseURL already did. --- .../org/postgresql/client/jdbc/PgDriver.java | 23 +++++++++++++++---- .../src/main/java/org/postgresql/Driver.java | 5 ++-- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java index 140f2539..b673f72c 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java @@ -394,13 +394,28 @@ private static String queryParam(String url, String name) { if (q < 0) { return null; } + // Keys and values are compared decoded, and the last occurrence wins, exactly as the core + // parser reads the same query: %72ewriteBatchUsingArrays= is the same key to it. + String value = null; for (String pair : url.substring(q + 1).split("&")) { int eq = pair.indexOf('='); - if (eq >= 0 && pair.substring(0, eq).equals(name)) { - return pair.substring(eq + 1); + if (eq >= 0 && decodeOrRaw(pair.substring(0, eq)).equals(name)) { + value = decodeOrRaw(pair.substring(eq + 1)); } } - return null; + return value; + } + + /** + * Percent-decodes {@code s}, or returns it as is when an escape is malformed; the core parser + * rejects such a URL when it builds the config. + */ + private static String decodeOrRaw(String s) { + try { + return PercentDecoding.decode(s); + } catch (PgException e) { + return s; + } } /** Builds a core config by merging the URL (higher precedence) with the supplied properties. */ @@ -465,7 +480,7 @@ private static String stripQueryParam(String uri, String key) { StringBuilder kept = new StringBuilder(); for (String pair : uri.substring(q + 1).split("&")) { int eq = pair.indexOf('='); - String name = eq >= 0 ? pair.substring(0, eq) : pair; + String name = decodeOrRaw(eq >= 0 ? pair.substring(0, eq) : pair); if (name.equals(key)) { continue; } diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java index 4474b128..d6015aa7 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java @@ -360,7 +360,8 @@ private static void warnOnce(String name, String message) { } /** - * The URL's query parameters, values percent-decoded. A repeated key keeps its last value. Both + * The URL's query parameters, keys and values percent-decoded, as the core parser and + * {@link #parseURL} read them. A repeated key keeps its last value. Both * the translation and {@link #rawProperty} read this one map: they used to parse separately, one * first-wins and the other last-wins, so {@code readOnly=false&readOnly=true} meant one thing to * the connection and the opposite to the emulated read-only switch. @@ -376,7 +377,7 @@ private static LinkedHashMap queryParameters(String url) { continue; } int eq = pair.indexOf('='); - String name = eq < 0 ? pair : pair.substring(0, eq); + String name = decode(eq < 0 ? pair : pair.substring(0, eq)); String value = eq < 0 ? "" : decode(pair.substring(eq + 1)); pairs.put(name, value); } From 2a4d799b4c83b0daf90c0a09235a0d34f48314f6 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:58:18 +0000 Subject: [PATCH 075/150] test(jdbc): pin percent-encoded JDBC-only keys being recognized --- .../org/postgresql/client/jdbc/PgDriverTest.java | 15 +++++++++++++++ .../src/test/java/org/postgresql/DriverTest.java | 7 +++++++ 2 files changed, 22 insertions(+) diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java index ed959bbd..1fb77d69 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java @@ -167,6 +167,21 @@ void urlStillOutranksPropertiesOfTheSameName() throws SQLException { assertEquals("app", config.user()); } + @Test + void percentEncodedJdbcOnlyKeysAreRecognized() throws SQLException { + // Core decodes keys, so an encoded JDBC-only key must be stripped and checked like the plain one. + Properties info = new Properties(); + info.setProperty("user", "app"); + PgConnectionConfig config = PgDriver.buildConfig( + "jdbc:postgresql://h/db?%61uthenticationPluginClassName=x&%63laimPostgresqlScheme=always", info); + assertFalse(config.runtimeParameters().containsKey("authenticationPluginClassName")); + assertFalse(config.runtimeParameters().containsKey("claimPostgresqlScheme")); + + SQLException e = assertThrows(SQLException.class, () -> new PgDriver() + .connect("jdbc:postgresql://127.0.0.1:1/db?%72ewriteBatchUsingArrays=com.example.Rewriter", info)); + assertTrue(e.getMessage().contains("custom rewriter class"), e.getMessage()); + } + @Test void reportsVersionAndCompliance() { assertEquals(0, driver.getMajorVersion()); diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java index dace5c65..0dd1a71d 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java @@ -240,6 +240,13 @@ void dataSourceUrlValuesKeepTheirSpaces() throws Exception { assertEquals("a+b c", parsed.getProperty("application_name")); } + @Test + void percentEncodedKeysAreDecoded() throws Exception { + String url = "jdbc:postgresql://h/db?%73slmode=require&%72eadOnly=true"; + assertEquals("jdbc:postgresql://h/db?sslmode=require", Driver.translateUrl(url)); + assertEquals("true", Driver.rawProperty(url, null, "readOnly")); + } + @Test void urlWithoutQueryIsUnchanged() throws Exception { assertEquals("jdbc:postgresql://h/db", Driver.translateUrl("jdbc:postgresql://h/db")); From c2c032583f5f8de14f1011cbe12535a6a947a853 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:59:19 +0000 Subject: [PATCH 076/150] fix(compat): pass the whole host list to the pooling and XA sources The pooling and XA data sources configured their native counterpart through setServerName and setPortNumber, which take one host, so a multi-host configuration silently became its first host: no failover, no targetServerType across hosts, and a down first host failed the connection. Hand the native source a URL carrying every server and port instead. The server names are already validated against URL syntax. --- .../ds/PGConnectionPoolDataSource.java | 2 +- .../postgresql/ds/common/BaseDataSource.java | 28 +++++++++++-------- .../org/postgresql/xa/PGXADataSource.java | 2 +- 3 files changed, 19 insertions(+), 13 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java index 1f6d02b5..8eeb0714 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java @@ -60,7 +60,7 @@ public boolean isDefaultAutoCommit() { */ private PgConnectionPoolDataSource configureNative() throws SQLException { PgConnectionPoolDataSource ds = new PgConnectionPoolDataSource(); - copyIdentityTo(ds::setServerName, ds::setPortNumber, ds::setDatabaseName); + ds.setUrl(nativeIdentityUrl()); copyNativePropertiesTo(ds::setProperty); ds.setLoginTimeout(getLoginTimeout()); return ds; diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java index c23049b4..be853f35 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java @@ -598,19 +598,25 @@ private static String decode(String value) { } /** - * Copies this bean's connection identity onto a native DataSource via its setters: server - * name, the port only when explicitly set (non-zero, so the native default applies otherwise), - * and database name. Shared by the pooling and XA compat sources. + * The connection identity as a URL for a native DataSource: every server and its port (a zero + * port is left out, so the native default applies) and the database. Shared by the pooling and + * XA compat sources, which used to pass only the first server and port through the native + * setters and so silently dropped the rest of a multi-host configuration. The server names are + * validated by {@link #setServerNames}, so they cannot carry URL syntax. */ - protected void copyIdentityTo( - java.util.function.Consumer serverName, - java.util.function.IntConsumer portNumber, - java.util.function.Consumer databaseName) { - serverName.accept(getServerName()); - if (getPortNumber() != 0) { - portNumber.accept(getPortNumber()); + protected String nativeIdentityUrl() { + StringBuilder url = new StringBuilder("jdbc:postgresql://"); + for (int i = 0; i < serverNames.length; i++) { + if (i > 0) { + url.append(','); + } + url.append(serverNames[i]); + int port = i < portNumbers.length ? portNumbers[i] : 0; + if (port != 0) { + url.append(':').append(port); + } } - databaseName.accept(getDatabaseName()); + return url.append('/').append(encode(databaseName)).toString(); } /** diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java index 04c767b7..a2457c40 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java @@ -47,7 +47,7 @@ public XAConnection getXAConnection(String user, String password) throws SQLExce */ private PgXADataSource configureNative() throws SQLException { PgXADataSource ds = new PgXADataSource(); - copyIdentityTo(ds::setServerName, ds::setPortNumber, ds::setDatabaseName); + ds.setUrl(nativeIdentityUrl()); copyNativePropertiesTo(ds::setProperty); ds.setLoginTimeout(getLoginTimeout()); return ds; From d0e84844153cedc4b4e0e40639b60391174c25e6 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 15:59:19 +0000 Subject: [PATCH 077/150] test(compat): pin multi-host failover through the pooling and XA sources --- .../ds/DataSourceMultiHostTest.java | 88 +++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourceMultiHostTest.java diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourceMultiHostTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourceMultiHostTest.java new file mode 100644 index 00000000..3e64f684 --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourceMultiHostTest.java @@ -0,0 +1,88 @@ +package org.postgresql.ds; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.function.Executable; +import org.postgresql.ds.common.BaseDataSource; +import org.postgresql.xa.PGXADataSource; + +/** + * The pooling and XA sources pass the whole host list to the native driver: with the first host + * down, the connection must move on to the second instead of failing on the only host it was given. + */ +@Timeout(30) +class DataSourceMultiHostTest { + + private static final byte[] FATAL = fatal(); + + private static byte[] fatal() { + byte[] body = "SFATAL\0C28000\0Mstop\0\0".getBytes(StandardCharsets.US_ASCII); + return ByteBuffer.allocate(5 + body.length) + .put((byte) 'E') + .putInt(4 + body.length) + .put(body) + .array(); + } + + @Test + void connectionPoolDataSourceTriesTheSecondHost() throws Exception { + PGConnectionPoolDataSource ds = new PGConnectionPoolDataSource(); + assertReachesSecondHost(ds, ds::getPooledConnection); + } + + @Test + void xaDataSourceTriesTheSecondHost() throws Exception { + PGXADataSource ds = new PGXADataSource(); + assertReachesSecondHost(ds, ds::getXAConnection); + } + + private static void assertReachesSecondHost(BaseDataSource ds, Executable connect) throws Exception { + int deadPort; + try (ServerSocket probe = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + deadPort = probe.getLocalPort(); // closed again before the connect, so nothing listens + } + AtomicBoolean reached = new AtomicBoolean(); + try (ServerSocket second = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + Thread acceptor = Thread.ofVirtual().start(() -> answerWithFatal(second, reached)); + ds.setServerNames(new String[] {"127.0.0.1", "127.0.0.1"}); + ds.setPortNumbers(new int[] {deadPort, second.getLocalPort()}); + ds.setDatabaseName("db"); + ds.setUser("alice"); + ds.setSslMode("disable"); + ds.setLoginTimeout(5); + + assertThrows(SQLException.class, connect); + second.close(); + acceptor.join(5000); + } + assertTrue(reached.get(), "the second host never saw a startup message"); + } + + private static void answerWithFatal(ServerSocket server, AtomicBoolean reached) { + try (Socket socket = server.accept()) { + socket.setSoTimeout(5000); + DataInputStream in = new DataInputStream(socket.getInputStream()); + int length = in.readInt(); + in.readFully(new byte[length - 4]); + reached.set(true); + OutputStream out = socket.getOutputStream(); + out.write(FATAL); + out.flush(); + } catch (IOException e) { + // the listener was closed without a connection, which the assertion reports + } + } +} From 3db56f480fe7f89e467ee22bff7bd9919aaa8d85 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:01:59 +0000 Subject: [PATCH 078/150] fix(compat): give pooled and XA handles what Driver.connect gives The pooling and XA data sources returned the native PooledConnection and XAConnection as is, so their logical handles skipped everything the compat driver does after connecting: readOnly was never applied, the handles had no vendor-extension ring (unwrap(PGConnection.class) failed), and PGConnectionPoolDataSource accepted defaultAutoCommit and ignored it. Wrap them in compat pooled and XA connections whose handles go through the driver's own finishing step, with defaultAutoCommit applied to each pooled handle as pgjdbc does. Connection events are re-fired with the compat object as their source, since a pool matches events to what it was handed. The internal holder the driver installs into now carries that step as well as the property translation, and is renamed to fit. --- .../src/main/java/org/postgresql/Driver.java | 31 +++++-- .../compat/internal/CompatDriverHooks.java | 57 ++++++++++++ .../internal/CompatPooledConnection.java | 86 +++++++++++++++++++ .../internal/CompatPropertyTranslation.java | 42 --------- .../compat/internal/CompatXAConnection.java | 20 +++++ .../ds/PGConnectionPoolDataSource.java | 6 +- .../postgresql/ds/common/BaseDataSource.java | 11 ++- .../org/postgresql/xa/PGXADataSource.java | 3 +- 8 files changed, 202 insertions(+), 54 deletions(-) create mode 100644 postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatDriverHooks.java create mode 100644 postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPooledConnection.java delete mode 100644 postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPropertyTranslation.java create mode 100644 postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatXAConnection.java diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java index d6015aa7..d350f4c4 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java @@ -20,7 +20,7 @@ import java.util.logging.Logger; import org.postgresql.PgPropertyMappings.Mapping; import org.postgresql.PgPropertyMappings.Support; -import org.postgresql.client.compat.internal.CompatPropertyTranslation; +import org.postgresql.client.compat.internal.CompatDriverHooks; import org.postgresql.client.core.PgConfigurationException; import org.postgresql.client.core.auth.AuthenticationProvider; import org.postgresql.client.core.internal.jdbc.PercentDecoding; @@ -75,7 +75,18 @@ public Driver() {} private static volatile Driver registeredDriver; static { - CompatPropertyTranslation.install(Driver::translateProperties); + CompatDriverHooks.install(new CompatDriverHooks.Hooks() { + @Override + public Properties translate(Properties pgjdbcProperties) throws SQLException { + return translateProperties(pgjdbcProperties); + } + + @Override + public Connection finishConnection(Connection nativeConnection, Properties pgjdbcProperties) + throws SQLException { + return Driver.finishConnection(nativeConnection, null, pgjdbcProperties); + } + }); // Fail fast if the real pgjdbc is co-present (ADR-0015): two org.postgresql.Driver definitions // on one classpath have undefined resolution order, so no arbitration can make it safe. requireSinglePostgresqlDriver(driverClassResources()); @@ -215,17 +226,23 @@ private Connection connectAccepted(String url, Properties info) throws SQLExcept if (rawProperty(url, info, "allowUnencryptedPasswordAuth") == null) { nativeProps.setProperty("allowUnencryptedPasswordAuth", "true"); } - Connection connection = NATIVE.connect(translateUrl(url), nativeProps, provider); - // readOnly is emulated: applied to the connection after it is established. + return finishConnection(NATIVE.connect(translateUrl(url), nativeProps, provider), url, info); + } + + /** + * The steps every compat connection gets once the native driver has connected it: the emulated + * {@code readOnly}, then the pgjdbc vendor-extension ring (N4.3) so {@code unwrap(PGConnection.class)} + * and casts work. Also applied by the pooling and XA sources to each logical handle. + */ + static Connection finishConnection(Connection connection, String url, Properties info) throws SQLException { if (isTruthy(rawProperty(url, info, "readOnly"))) { connection.setReadOnly(true); } - // Install the pgjdbc vendor-extension ring (N4.3) so unwrap(PGConnection.class) and casts work. return CompatConnections.wrap(connection, vendorSettings(url, info)); } /** Seeds the connection's pgjdbc vendor state from the requested connection properties. */ - private VendorSettings vendorSettings(String url, Properties info) { + private static VendorSettings vendorSettings(String url, Properties info) { VendorSettings settings = VendorSettings.defaults(); String mode = rawProperty(url, info, "preferQueryMode"); if (mode != null) { @@ -242,7 +259,7 @@ private VendorSettings vendorSettings(String url, Properties info) { return settings; } - private int intProperty(String url, Properties info, String name, int fallback) { + private static int intProperty(String url, Properties info, String name, int fallback) { String value = rawProperty(url, info, name); if (value == null || value.isEmpty()) { return fallback; diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatDriverHooks.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatDriverHooks.java new file mode 100644 index 00000000..1de2cd49 --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatDriverHooks.java @@ -0,0 +1,57 @@ +package org.postgresql.client.compat.internal; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Reaches the compat {@link org.postgresql.Driver}'s package-private behavior from the data sources, + * which live in other packages: its pgjdbc-to-native property translation, and the steps it applies + * to every new connection (the emulated {@code readOnly} and the vendor-extension ring). The + * behavior stays package-private in {@code org.postgresql}, an exported pgjdbc-named package, and + * the driver installs it here when its class initializes; this package is not exported. + */ +public final class CompatDriverHooks { + + /** The driver's own implementations. */ + public interface Hooks { + /** Translates pgjdbc property names and values to the native driver's. */ + Properties translate(Properties pgjdbcProperties) throws SQLException; + + /** Applies what {@code Driver.connect} does to a native connection, given the pgjdbc bag. */ + Connection finishConnection(Connection nativeConnection, Properties pgjdbcProperties) throws SQLException; + } + + private static final AtomicReference HOOKS = new AtomicReference<>(); + + private CompatDriverHooks() {} + + /** Called once by the driver's static initializer; later calls are ignored. */ + public static void install(Hooks hooks) { + HOOKS.compareAndSet(null, hooks); + } + + /** Translates {@code pgjdbcProperties} the way {@code Driver.connect} translates its own. */ + public static Properties translate(Properties pgjdbcProperties) throws SQLException { + return hooks().translate(pgjdbcProperties); + } + + /** Finishes {@code nativeConnection} the way {@code Driver.connect} finishes its own. */ + public static Connection finishConnection(Connection nativeConnection, Properties pgjdbcProperties) + throws SQLException { + return hooks().finishConnection(nativeConnection, pgjdbcProperties); + } + + private static Hooks hooks() { + Hooks installed = HOOKS.get(); + if (installed == null) { + org.postgresql.Driver.isRegistered(); // initializes the driver class, which installs them + installed = HOOKS.get(); + } + if (installed == null) { + throw new IllegalStateException("the compat driver did not install its hooks"); + } + return installed; + } +} diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPooledConnection.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPooledConnection.java new file mode 100644 index 00000000..3940d9b2 --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPooledConnection.java @@ -0,0 +1,86 @@ +package org.postgresql.client.compat.internal; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.CopyOnWriteArrayList; +import javax.sql.ConnectionEvent; +import javax.sql.ConnectionEventListener; +import javax.sql.PooledConnection; +import javax.sql.StatementEventListener; +import org.jspecify.annotations.Nullable; + +/** + * The compat view of a native {@link PooledConnection}. Each logical handle gets what + * {@code Driver.connect} gives a plain connection -- the emulated {@code readOnly} and the pgjdbc + * vendor-extension ring -- plus pgjdbc's {@code defaultAutoCommit} when the pooling source sets one. + * Connection events are re-fired with this object as their source, since a pool matches events to + * the pooled connection it handed out. + */ +public class CompatPooledConnection implements PooledConnection { + + private final PooledConnection delegate; + private final Properties pgjdbcProperties; + private final @Nullable Boolean defaultAutoCommit; + private final List listeners = new CopyOnWriteArrayList<>(); + + public CompatPooledConnection( + PooledConnection delegate, Properties pgjdbcProperties, @Nullable Boolean defaultAutoCommit) { + this.delegate = delegate; + this.pgjdbcProperties = pgjdbcProperties; + this.defaultAutoCommit = defaultAutoCommit; + delegate.addConnectionEventListener(new ConnectionEventListener() { + @Override + public void connectionClosed(ConnectionEvent event) { + ConnectionEvent ours = new ConnectionEvent(CompatPooledConnection.this); + listeners.forEach(listener -> listener.connectionClosed(ours)); + } + + @Override + public void connectionErrorOccurred(ConnectionEvent event) { + ConnectionEvent ours = new ConnectionEvent(CompatPooledConnection.this, event.getSQLException()); + listeners.forEach(listener -> listener.connectionErrorOccurred(ours)); + } + }); + } + + /** The native pooled connection, for a subclass that exposes more of it. */ + protected final PooledConnection delegate() { + return delegate; + } + + @Override + public Connection getConnection() throws SQLException { + Connection handle = delegate.getConnection(); + if (defaultAutoCommit != null) { + handle.setAutoCommit(defaultAutoCommit); + } + return CompatDriverHooks.finishConnection(handle, pgjdbcProperties); + } + + @Override + public void close() throws SQLException { + delegate.close(); + } + + @Override + public void addConnectionEventListener(ConnectionEventListener listener) { + listeners.add(listener); + } + + @Override + public void removeConnectionEventListener(ConnectionEventListener listener) { + listeners.remove(listener); + } + + @Override + public void addStatementEventListener(StatementEventListener listener) { + delegate.addStatementEventListener(listener); + } + + @Override + public void removeStatementEventListener(StatementEventListener listener) { + delegate.removeStatementEventListener(listener); + } +} diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPropertyTranslation.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPropertyTranslation.java deleted file mode 100644 index bd5bf1aa..00000000 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPropertyTranslation.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.postgresql.client.compat.internal; - -import java.sql.SQLException; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicReference; - -/** - * Reaches the compat {@link org.postgresql.Driver}'s pgjdbc-to-native property translation from the - * data sources, which live in other packages. The translation stays package-private in - * {@code org.postgresql}, an exported pgjdbc-named package, and the driver installs it here when - * its class initializes; this package is not exported. - */ -public final class CompatPropertyTranslation { - - /** Translates pgjdbc property names and values to the native driver's. */ - @FunctionalInterface - public interface Translator { - Properties translate(Properties pgjdbcProperties) throws SQLException; - } - - private static final AtomicReference TRANSLATOR = new AtomicReference<>(); - - private CompatPropertyTranslation() {} - - /** Called once by the driver's static initializer; later calls are ignored. */ - public static void install(Translator translator) { - TRANSLATOR.compareAndSet(null, translator); - } - - /** Translates {@code pgjdbcProperties} the way {@code Driver.connect} translates its own. */ - public static Properties translate(Properties pgjdbcProperties) throws SQLException { - Translator translator = TRANSLATOR.get(); - if (translator == null) { - org.postgresql.Driver.isRegistered(); // initializes the driver class, which installs it - translator = TRANSLATOR.get(); - } - if (translator == null) { - throw new IllegalStateException("the compat driver did not install its property translation"); - } - return translator.translate(pgjdbcProperties); - } -} diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatXAConnection.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatXAConnection.java new file mode 100644 index 00000000..49597718 --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatXAConnection.java @@ -0,0 +1,20 @@ +package org.postgresql.client.compat.internal; + +import java.sql.SQLException; +import java.util.Properties; +import javax.sql.XAConnection; +import javax.transaction.xa.XAResource; + +/** The compat view of a native {@link XAConnection}; see {@link CompatPooledConnection}. */ +public final class CompatXAConnection extends CompatPooledConnection implements XAConnection { + + public CompatXAConnection(XAConnection delegate, Properties pgjdbcProperties) { + // Auto-commit on an XA connection is the transaction manager's business, not a default's. + super(delegate, pgjdbcProperties, null); + } + + @Override + public XAResource getXAResource() throws SQLException { + return ((XAConnection) delegate()).getXAResource(); + } +} diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java index 8eeb0714..a7b66d90 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java @@ -7,6 +7,7 @@ import java.sql.SQLException; import javax.sql.ConnectionPoolDataSource; import javax.sql.PooledConnection; +import org.postgresql.client.compat.internal.CompatPooledConnection; import org.postgresql.client.jdbc.PgConnectionPoolDataSource; import org.postgresql.ds.common.BaseDataSource; @@ -40,10 +41,11 @@ public PooledConnection getPooledConnection() throws SQLException { @Override public PooledConnection getPooledConnection(String user, String password) throws SQLException { - return configureNative().getPooledConnection(user, password); + return new CompatPooledConnection( + configureNative().getPooledConnection(user, password), pgjdbcProperties(), defaultAutoCommit); } - /** Whether logical connections start in auto-commit mode (accepted for pgjdbc compatibility). */ + /** Whether each logical connection starts in auto-commit mode, as in pgjdbc. */ public void setDefaultAutoCommit(boolean defaultAutoCommit) { this.defaultAutoCommit = defaultAutoCommit; } diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java index be853f35..d404313c 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java @@ -20,7 +20,7 @@ import javax.naming.StringRefAddr; import javax.sql.CommonDataSource; import org.postgresql.PGProperty; -import org.postgresql.client.compat.internal.CompatPropertyTranslation; +import org.postgresql.client.compat.internal.CompatDriverHooks; import org.postgresql.client.core.internal.jdbc.ConnectionStringRedaction; /** @@ -619,6 +619,13 @@ protected String nativeIdentityUrl() { return url.append('/').append(encode(databaseName)).toString(); } + /** A copy of the property bag, by pgjdbc name, for a subclass that finishes native connections. */ + protected Properties pgjdbcProperties() { + Properties copy = new Properties(); + copy.putAll(properties); + return copy; + } + /** * Hands the bag to {@code sink} as the native driver spells it, after the defaults the compat * {@link org.postgresql.Driver} gives every connection. A subclass that builds a native data @@ -628,7 +635,7 @@ protected String nativeIdentityUrl() { * server as startup parameters, unenforced. */ protected void copyNativePropertiesTo(java.util.function.BiConsumer sink) throws SQLException { - Properties translated = CompatPropertyTranslation.translate(properties); + Properties translated = CompatDriverHooks.translate(properties); // pgjdbc reads no environment and sends a password whenever the server asks; an explicit // bag entry still wins. if (!translated.containsKey("ignoreEnvironment")) { diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java index a2457c40..7e9711dc 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java @@ -3,6 +3,7 @@ import java.sql.SQLException; import javax.sql.XAConnection; import javax.sql.XADataSource; +import org.postgresql.client.compat.internal.CompatXAConnection; import org.postgresql.client.jdbc.PgXADataSource; import org.postgresql.ds.common.BaseDataSource; @@ -30,7 +31,7 @@ public XAConnection getXAConnection() throws SQLException { @Override public XAConnection getXAConnection(String user, String password) throws SQLException { - return configureNative().getXAConnection(user, password); + return new CompatXAConnection(configureNative().getXAConnection(user, password), pgjdbcProperties()); } /** From 6f5d305f7446f661f616394a61e73271f21ba246 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:01:59 +0000 Subject: [PATCH 079/150] test(compat): pin the finishing of pooled and XA logical handles --- .../internal/CompatPooledConnectionTest.java | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/client/compat/internal/CompatPooledConnectionTest.java diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/client/compat/internal/CompatPooledConnectionTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/client/compat/internal/CompatPooledConnectionTest.java new file mode 100644 index 00000000..54d452df --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/client/compat/internal/CompatPooledConnectionTest.java @@ -0,0 +1,98 @@ +package org.postgresql.client.compat.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertSame; + +import java.lang.reflect.Proxy; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import javax.sql.ConnectionEvent; +import javax.sql.ConnectionEventListener; +import javax.sql.PooledConnection; +import org.junit.jupiter.api.Test; +import org.postgresql.PGConnection; + +/** + * Logical handles from the compat pooling and XA sources get what {@code Driver.connect} gives a + * plain connection, plus pgjdbc's {@code defaultAutoCommit}, and events name the compat object. + */ +class CompatPooledConnectionTest { + + /** Records the calls made on the native logical handle. */ + private final List calls = new ArrayList<>(); + + private ConnectionEventListener nativeListener; + + private Connection nativeHandle() { + return (Connection) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] {Connection.class}, (proxy, method, args) -> { + if (method.getName().startsWith("set")) { + calls.add(method.getName() + "=" + args[0]); + } + return switch (method.getName()) { + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == args[0]; + default -> method.getReturnType() == boolean.class ? false : null; + }; + }); + } + + private PooledConnection nativePooled() { + return (PooledConnection) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] {PooledConnection.class}, (proxy, method, args) -> { + switch (method.getName()) { + case "getConnection" -> { + return nativeHandle(); + } + case "addConnectionEventListener" -> nativeListener = (ConnectionEventListener) args[0]; + default -> { + // nothing else is exercised + } + } + return null; + }); + } + + @Test + void handlesCarryTheVendorRingReadOnlyAndAutoCommit() throws Exception { + Properties bag = new Properties(); + bag.setProperty("readOnly", "true"); + CompatPooledConnection pooled = new CompatPooledConnection(nativePooled(), bag, false); + + Connection handle = pooled.getConnection(); + + assertInstanceOf(PGConnection.class, handle); + assertEquals(List.of("setAutoCommit=false", "setReadOnly=true"), calls); + } + + @Test + void noDefaultAutoCommitLeavesTheHandleAlone() throws Exception { + new CompatPooledConnection(nativePooled(), new Properties(), null).getConnection(); + assertEquals(List.of(), calls); + } + + @Test + void eventsNameTheCompatPooledConnection() { + CompatPooledConnection pooled = new CompatPooledConnection(nativePooled(), new Properties(), null); + List sources = new ArrayList<>(); + pooled.addConnectionEventListener(new ConnectionEventListener() { + @Override + public void connectionClosed(ConnectionEvent event) { + sources.add(event.getSource()); + } + + @Override + public void connectionErrorOccurred(ConnectionEvent event) { + sources.add(event.getSource()); + } + }); + + nativeListener.connectionClosed(new ConnectionEvent(nativePooled())); + + assertEquals(1, sources.size()); + assertSame(pooled, sources.get(0)); + } +} From bfde3ffd5201945a2c8a3508413def6e49634105 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:04:57 +0000 Subject: [PATCH 080/150] fix(core): answer a stray CopyInResponse with CopyFail When a later statement of a multi-statement simple query was COPY ... FROM STDIN, the result stream read past its CopyInResponse while draining, but the server was then waiting for copy data, so the drain blocked until socketTimeout (forever by default): execute("SELECT 1; COPY t FROM STDIN") hung. The synchronous drain had the same gap. Send CopyFail when the read-ahead or a drain meets a CopyInResponse. The server's resulting error surfaces like any other trailing statement's, and the connection stays usable. Checked on 17: the call fails in milliseconds with the CopyFail reason and the next query runs. --- .../client/core/CoreConnection.java | 8 +++++++- .../client/core/PullResultStream.java | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java b/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java index 6a5560d8..90b86e91 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java @@ -36,6 +36,8 @@ import org.postgresql.client.protocol.message.Close; import org.postgresql.client.protocol.message.CloseComplete; import org.postgresql.client.protocol.message.CommandComplete; +import org.postgresql.client.protocol.message.CopyFail; +import org.postgresql.client.protocol.message.CopyInResponse; import org.postgresql.client.protocol.message.DataRow; import org.postgresql.client.protocol.message.Describe; import org.postgresql.client.protocol.message.EmptyQueryResponse; @@ -1294,9 +1296,13 @@ BackendMessage pullNonAsync() { /** Reads to ReadyForQuery (discarding intervening messages) and returns the transaction status. */ private TransactionStatus drainSynchronous() { while (true) { - if (pullNonAsync() instanceof ReadyForQuery ready) { + BackendMessage message = pullNonAsync(); + if (message instanceof ReadyForQuery ready) { return ready.status(); } + if (message instanceof CopyInResponse) { + channel.send(new CopyFail(PullResultStream.UNEXPECTED_COPY_IN)); // see drainToReadyForQuery + } } } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/PullResultStream.java b/postgresql-client/src/main/java/org/postgresql/client/core/PullResultStream.java index 15af3304..b6e03315 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/PullResultStream.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/PullResultStream.java @@ -6,6 +6,8 @@ import org.postgresql.client.core.internal.WireChannel; import org.postgresql.client.protocol.message.BackendMessage; import org.postgresql.client.protocol.message.CommandComplete; +import org.postgresql.client.protocol.message.CopyFail; +import org.postgresql.client.protocol.message.CopyInResponse; import org.postgresql.client.protocol.message.DataRow; import org.postgresql.client.protocol.message.EmptyQueryResponse; import org.postgresql.client.protocol.message.ErrorResponse; @@ -215,6 +217,7 @@ private void finishResult() { // later statement of the string is the realistic case. Finish the cycle the way // it was always finished -- drain and release -- rather than call the connection // broken over a message that is legal here. + refuseCopyIn(message); completeAndRelease(); return; } @@ -222,6 +225,9 @@ private void finishResult() { } } + /** The CopyFail reason for a COPY FROM STDIN met where no copy stream was opened for it. */ + static final String UNEXPECTED_COPY_IN = "COPY FROM STDIN is not supported here; use the copy-in API"; + /** A result the stream has seen the head of but not yet moved onto. */ private record Pending(RowMetadata metadata, @Nullable ResultSummary summary) {} @@ -341,10 +347,23 @@ protected final void drainToReadyForQuery() { finalStatus = ready.status(); } else if (message instanceof ErrorResponse error && drainError == null) { drainError = PgExceptions.fromServerMessage(ServerErrors.toServerMessage(error.fields())); + } else { + refuseCopyIn(message); } } } + /** + * Answers a {@code CopyInResponse} from a later statement of the string with {@code CopyFail}. + * The server is then waiting for data, so reading on would hang until {@code socketTimeout}; + * its error arrives in the drain like any other trailing statement's. + */ + private void refuseCopyIn(BackendMessage message) { + if (message instanceof CopyInResponse) { + channel.send(new CopyFail(UNEXPECTED_COPY_IN)); + } + } + /** * Returns the next non-async message, routing notices, notifications, and parameter-status * reports through the connection so runtime GUC changes apply to live session state (ADR-0011). From 797fd8192717c88e0b1c57268519ab5b64740d32 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:04:57 +0000 Subject: [PATCH 081/150] test(core): pin CopyFail for a stray CopyInResponse --- .../client/core/UnexpectedCopyInTest.java | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/UnexpectedCopyInTest.java diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/UnexpectedCopyInTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/UnexpectedCopyInTest.java new file mode 100644 index 00000000..30c5a725 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/UnexpectedCopyInTest.java @@ -0,0 +1,79 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.postgresql.client.core.auth.TrustAuthenticator; +import org.postgresql.client.core.internal.StartupOrchestrator; +import org.postgresql.client.core.internal.StartupResult; +import org.postgresql.client.core.internal.WireChannel; +import org.postgresql.client.core.transport.BackendWire; +import org.postgresql.client.core.transport.MockServer; +import org.postgresql.client.protocol.MessageType; + +/** + * A COPY FROM STDIN later in a multi-statement string leaves the server waiting for data. The drain + * has to answer it with CopyFail rather than read on: the next message would never come. + */ +@Timeout(30) +class UnexpectedCopyInTest { + + private static CoreConnection connect(MockServer server) { + PgConnectionConfig config = PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .build(); + server.onStartup((s, f) -> s.send(BackendWire.authenticationOk(), BackendWire.readyForQuery('I'))); + WireChannel channel = new WireChannel(server, SizeLimits.unlimited()); + StartupResult startup = new StartupOrchestrator( + channel, config, HostAndPort.of("h"), TrustAuthenticator.INSTANCE, PgConnectionListener.NO_OP) + .run(); + return new CoreConnection(channel, config, startup, HostAndPort.of("h"), PgConnectionListener.NO_OP); + } + + @Test + void trailingCopyInIsRefusedWithCopyFail() { + List received = new ArrayList<>(); + MockServer server = new MockServer().onMessage((s, f) -> { + received.add((char) f.type()); + if (f.type() == MessageType.Frontend.QUERY && received.size() == 1) { + s.send( + BackendWire.rowDescription("?column?"), + BackendWire.dataRow("1"), + BackendWire.commandComplete("SELECT 1"), + BackendWire.copyInResponse(1)); + } else if (f.type() == MessageType.Frontend.COPY_FAIL) { + s.send( + BackendWire.errorResponse("ERROR", "57014", "COPY from stdin failed"), + BackendWire.readyForQuery('I')); + } else { + s.send( + BackendWire.rowDescription("?column?"), + BackendWire.dataRow("2"), + BackendWire.commandComplete("SELECT 1"), + BackendWire.readyForQuery('I')); + } + }); + CoreConnection connection = connect(server); + + PgException e = assertThrows(PgException.class, () -> { + try (PgResultStream rs = connection.execute("SELECT 1; COPY t FROM STDIN")) { + assertTrue(rs.next()); + assertFalse(rs.next()); + } + }); + assertTrue(e.getMessage().contains("COPY"), e.getMessage()); + assertEquals(List.of('Q', 'f'), received); + assertFalse(connection.isBroken()); + try (PgResultStream rs = connection.execute("SELECT 2")) { + assertTrue(rs.next(), "the connection is usable again"); + } + } +} From 0c63a70ed0f8e6c6d3c87d69cf99d4efc77504d3 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:07:43 +0000 Subject: [PATCH 082/150] fix(jdbc): scope Statement.setQueryTimeout to the statement's execute A statement applied its query timeout to the core connection before each execute and never cleared it. The setting is connection-wide in core, so after one statement with a timeout ran, every later core call that no statement drove -- commits, metadata queries, type lookups -- ran under that statement's timeout too, and could be cancelled by it. Clear the setting once the execute has armed its timer, at each of the statement, prepared, callable and batch execute paths. --- .../client/jdbc/PgCallableStatement.java | 1 + .../client/jdbc/PgPreparedStatement.java | 5 +++++ .../postgresql/client/jdbc/PgStatement.java | 19 +++++++++++++++++++ 3 files changed, 25 insertions(+) diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgCallableStatement.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgCallableStatement.java index c6ec8c81..d5e9865f 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgCallableStatement.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgCallableStatement.java @@ -168,6 +168,7 @@ public boolean execute() throws SQLException { throw PgSqlExceptions.wrap(e); } finally { setFetchSize(callerFetchSize); + clearQueryTimeout(); } } diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgPreparedStatement.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgPreparedStatement.java index 1ded4785..5ac63024 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgPreparedStatement.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgPreparedStatement.java @@ -144,6 +144,8 @@ public boolean execute() throws SQLException { : core.execute(nativeSql, values)); } catch (RuntimeException e) { throw PgSqlExceptions.wrap(e); + } finally { + clearQueryTimeout(); } } @@ -1212,6 +1214,7 @@ private long[] executePipelinedBatch() throws SQLException { throw PgSqlExceptions.wrap(e); } finally { parameterBatch.clear(); + clearQueryTimeout(); } } @@ -1279,6 +1282,7 @@ private long[] executeArrayBatch(BatchArrayExecution.Plan plan) throws SQLExcept // must not re-run the already-attempted batch. Clearing only on success left a failed // rewritten batch armed for an accidental re-execute (N1.12 F1). parameterBatch.clear(); + clearQueryTimeout(); } long[] counts = new long[elements]; long value = plan.countSemantics() == CountSemantics.ONE_PER_ELEMENT ? 1L : java.sql.Statement.SUCCESS_NO_INFO; @@ -1350,6 +1354,7 @@ private long[] executeMultiValuesBatch(ValuesTemplate template, BatchMultiValues wrapped); } finally { parameterBatch.clear(); + clearQueryTimeout(); } long[] counts = new long[plan.totalElements()]; Arrays.fill(counts, elementCount); diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgStatement.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgStatement.java index 081a76c3..bae6311d 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgStatement.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgStatement.java @@ -172,6 +172,8 @@ private boolean doExecute(String sql, boolean generatedKeysRequested, String[] k return consume(core.execute(native_)); } catch (RuntimeException e) { throw PgSqlExceptions.wrap(e); + } finally { + clearQueryTimeout(); } } @@ -180,6 +182,15 @@ protected void applyQueryTimeout() { core.setQueryTimeout(queryTimeout); } + /** + * Clears the timeout {@link #applyQueryTimeout} set, once the execute has armed its timer. The + * setting is connection-wide in core, so left in place it also timed out work no statement asked + * to bound: commits, metadata queries, type lookups and the like. + */ + protected void clearQueryTimeout() { + core.setQueryTimeout(null); + } + /** Inspects a freshly opened stream: a row result becomes the current ResultSet, else an update. */ protected boolean consume(PgResultStream stream) throws SQLException { if (keysCaptureActive && stream.metadata().columnCount() > 0) { @@ -572,6 +583,14 @@ public long[] executeLargeBatch() throws SQLException { */ private long[] pipelinedLargeBatch(List nativeSqls) throws SQLException { applyQueryTimeout(); + try { + return pipelinedLargeBatchWindows(nativeSqls); + } finally { + clearQueryTimeout(); + } + } + + private long[] pipelinedLargeBatchWindows(List nativeSqls) throws SQLException { long[] counts = new long[nativeSqls.size()]; try (PgPipeline pipeline = core.pipeline()) { int done = 0; From 23c923103746e2a5e1fcce98253e50a48c54091b Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:07:43 +0000 Subject: [PATCH 083/150] test(jdbc): pin the clearing of a statement's query timeout --- .../jdbc/StatementQueryTimeoutScopeTest.java | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/StatementQueryTimeoutScopeTest.java diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/StatementQueryTimeoutScopeTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/StatementQueryTimeoutScopeTest.java new file mode 100644 index 00000000..1409a703 --- /dev/null +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/StatementQueryTimeoutScopeTest.java @@ -0,0 +1,79 @@ +package org.postgresql.client.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.lang.reflect.Proxy; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.PgConnectionConfig; +import org.postgresql.client.core.PgResultStream; +import org.postgresql.client.core.RowMetadata; + +/** + * A statement's query timeout is set on the core connection just for its execute: left in place it + * also bounded work no statement asked to bound (commits, metadata queries, type lookups). + */ +class StatementQueryTimeoutScopeTest { + + private final List calls = new ArrayList<>(); + + private static Object proxy(Class type, java.lang.reflect.InvocationHandler handler) { + return Proxy.newProxyInstance( + StatementQueryTimeoutScopeTest.class.getClassLoader(), new Class[] {type}, handler); + } + + private static Object defaultFor(Class type) { + if (type == boolean.class) { + return false; + } + if (type == int.class) { + return 0; + } + if (type == long.class) { + return 0L; + } + return null; + } + + /** A command-only result: no columns, no further results. */ + private static PgResultStream commandResult() { + RowMetadata metadata = (RowMetadata) proxy(RowMetadata.class, (p, m, a) -> defaultFor(m.getReturnType())); + return (PgResultStream) proxy(PgResultStream.class, (p, m, a) -> switch (m.getName()) { + case "metadata" -> metadata; + default -> defaultFor(m.getReturnType()); + }); + } + + private org.postgresql.client.core.PgConnection core() { + return (org.postgresql.client.core.PgConnection) + proxy(org.postgresql.client.core.PgConnection.class, (p, m, a) -> { + switch (m.getName()) { + case "setQueryTimeout" -> calls.add("timeout=" + a[0]); + case "execute" -> { + calls.add("execute " + Arrays.asList(a).get(0)); + return commandResult(); + } + default -> { + // nothing else matters here + } + } + return defaultFor(m.getReturnType()); + }); + } + + @Test + void timeoutIsClearedOnceTheExecuteHasRun() throws Exception { + PgConnectionConfig config = + PgConnectionConfig.builder().host("h").user("app").build(); + PgConnection connection = new PgConnection(core(), config, null, null); + try (Statement statement = connection.createStatement()) { + statement.setQueryTimeout(5); + statement.execute("UPDATE t SET x = 1"); + } + assertEquals(List.of("timeout=" + Duration.ofSeconds(5), "execute UPDATE t SET x = 1", "timeout=null"), calls); + } +} From 3dd16f0e6e1f5d5a2d1fcabdbf4df34425cb6c89 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:11:17 +0000 Subject: [PATCH 084/150] fix(jdbc): keep literal arguments in a {call ...} escape PgCallableStatement rebuilt the routine call from the bound parameters alone, as name($1, ..., $n), so any argument written as a literal or an expression was dropped: {call f(?, 1)} ran f($1), which resolves to a different function or fails, and {call f(? + 1)} lost the "+ 1". Rebuild the call from the argument list as written instead. A bare ? is a parameter and may be OUT-only (omitted under SELECT, NULL under CALL, as before); any other argument is kept, with its placeholders renumbered as IN parameters, and quotes, comments and ?? are respected. The old selection helpers go; their tests now drive the new one. Checked on 17 with a function and a procedure taking literal arguments. --- .../postgresql/client/jdbc/CallArguments.java | 140 ++++++++++++++++++ .../client/jdbc/PgCallableStatement.java | 86 +++-------- .../client/jdbc/PgCallableStatementTest.java | 43 ++++-- 3 files changed, 188 insertions(+), 81 deletions(-) create mode 100644 postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java new file mode 100644 index 00000000..33821e88 --- /dev/null +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java @@ -0,0 +1,140 @@ +package org.postgresql.client.jdbc; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import org.postgresql.client.jdbc.sql.SqlLexing; + +/** + * Rebuilds the argument list of a {@code {call f(...)}} escape for the native call, keeping every + * argument as written. A bare {@code ?} is a parameter, which may be OUT-only; any other argument + * is an expression (a literal such as the {@code 1} in {@code f(?, 1)}, or {@code ? + 1}) whose + * {@code ?} placeholders are IN parameters. Placeholders are numbered left to right as JDBC + * numbers them, and renumbered {@code $1..$n} over the values actually sent. + */ +final class CallArguments { + + private CallArguments() {} + + /** + * The native argument list (without parentheses), appending the value for each {@code $n} to + * {@code values}. An unbound OUT-only parameter is dropped under {@code SELECT}, which does not + * take OUT arguments, and sent as NULL under {@code CALL}, which needs one per parameter. + */ + static String rebuild( + String argumentText, + boolean callMode, + Set outParameters, + boolean[] bound, + Object[] parameters, + List values) + throws SQLException { + List out = new ArrayList<>(); + int placeholder = 0; + for (String argument : split(argumentText)) { + String trimmed = argument.strip(); + if (trimmed.equals("?")) { + placeholder++; + if (!bound[placeholder - 1] && outParameters.contains(placeholder)) { + if (!callMode) { + continue; + } + values.add(null); + } else { + values.add(requireBound(placeholder, bound, parameters)); + } + out.add("$" + values.size()); + continue; + } + StringBuilder expression = new StringBuilder(); + int end = trimmed.length(); + int i = 0; + while (i < end) { + char c = trimmed.charAt(i); + int next = skipQuotedOrComment(trimmed, i, end); + if (next > i) { + expression.append(trimmed, i, next); + i = next; + } else if (c == '?' && i + 1 < end && trimmed.charAt(i + 1) == '?') { + expression.append('?'); // ?? is an escaped literal question mark, as in SqlParser + i += 2; + } else if (c == '?') { + placeholder++; + values.add(requireBound(placeholder, bound, parameters)); + expression.append('$').append(values.size()); + i++; + } else { + expression.append(c); + i++; + } + } + out.add(expression.toString()); + } + return String.join(", ", out); + } + + private static Object requireBound(int placeholder, boolean[] bound, Object[] parameters) throws SQLException { + if (placeholder > bound.length || !bound[placeholder - 1]) { + throw new SQLException("parameter " + placeholder + " is not set"); + } + return parameters[placeholder - 1]; + } + + /** Splits the argument list at commas outside quotes, comments, parentheses and brackets. */ + static List split(String text) { + List arguments = new ArrayList<>(); + if (text.isBlank()) { + return arguments; + } + int depth = 0; + int start = 0; + int end = text.length(); + int i = 0; + while (i < end) { + int next = skipQuotedOrComment(text, i, end); + if (next > i) { + i = next; + continue; + } + char c = text.charAt(i); + if (c == '(' || c == '[') { + depth++; + } else if (c == ')' || c == ']') { + depth--; + } else if (c == ',' && depth == 0) { + arguments.add(text.substring(start, i)); + start = i + 1; + } + i++; + } + arguments.add(text.substring(start)); + return arguments; + } + + /** + * The index past the quoted string, identifier, dollar quote or comment opening at {@code i}, or + * {@code i} itself when none opens there. An unterminated one runs to {@code end}. + */ + private static int skipQuotedOrComment(String s, int i, int end) { + char c = s.charAt(i); + int next; + if (c == '\'') { + next = SqlLexing.skipSingleQuoted(s, i, end, SqlLexing.isEscapeStringPrefix(s, i)); + } else if (c == '"') { + next = SqlLexing.skipDoubleQuoted(s, i, end); + } else if (c == '$') { + next = SqlLexing.skipDollarQuote(s, i, end); + if (next == i + 1) { + return i; // a lone '$', not a quote + } + } else if (c == '-' && i + 1 < end && s.charAt(i + 1) == '-') { + next = SqlLexing.skipLineComment(s, i, end); + } else if (c == '/' && i + 1 < end && s.charAt(i + 1) == '*') { + next = SqlLexing.skipBlockComment(s, i, end); + } else { + return i; + } + return next < 0 ? end : next; + } +} diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgCallableStatement.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgCallableStatement.java index d5e9865f..d37f1c52 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgCallableStatement.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgCallableStatement.java @@ -47,6 +47,9 @@ public final class PgCallableStatement extends PgPreparedStatement implements CallableStatement { private final String routineName; + /** The call's argument list as written, between its parentheses ({@code ""} when it has none). */ + private final String argumentText; + private final boolean returnForm; /** Whether this call is translated to {@code CALL} rather than {@code SELECT} (N3.9). */ private final boolean useCall; @@ -62,6 +65,7 @@ public final class PgCallableStatement extends PgPreparedStatement implements Ca throws SQLException { super(connection, sql, resultSetType, resultSetConcurrency, java.sql.Statement.NO_GENERATED_KEYS, null); this.routineName = parseRoutineName(sql); + this.argumentText = routineName != null ? parseArgumentText(sql) : ""; this.returnForm = routineName != null && isReturnForm(sql); this.useCall = routineName != null && connection.config().escapeSyntaxCallMode().usesCall(returnForm); @@ -117,6 +121,17 @@ private static String parseRoutineName(String jdbcSql) { return name.isEmpty() ? null : name; } + /** The text between the parentheses after the routine name, or {@code ""} when there are none. */ + private static String parseArgumentText(String jdbcSql) { + String s = jdbcSql.strip(); + if (s.startsWith("{") && s.endsWith("}")) { + s = s.substring(1, s.length() - 1).strip(); + } + int open = s.indexOf('('); + int close = s.lastIndexOf(')'); + return open >= 0 && close > open ? s.substring(open + 1, close) : ""; + } + /** * Executes a routine call for its effects. A call always comes back as a result row -- that is * how PostgreSQL returns OUT values -- so the inherited rule that a result set means the caller @@ -149,10 +164,10 @@ public boolean execute() throws SQLException { if (routineName == null) { return super.execute(); // passthrough: all placeholders are IN } - List args = useCall ? callProcedureArguments() : inArguments(); - String sql = useCall - ? "CALL " + routineName + "(" + placeholders(args.size()) + ")" - : "SELECT * FROM " + routineName + "(" + placeholders(args.size()) + ")"; + List args = new ArrayList<>(); + String argumentList = + CallArguments.rebuild(argumentText, useCall, placeholderOutParameters(), bound, parameters, args); + String sql = (useCall ? "CALL " : "SELECT * FROM ") + routineName + "(" + argumentList + ")"; applyQueryTimeout(); int callerFetchSize = getFetchSize(); try { @@ -191,38 +206,6 @@ private void captureRefCursors() throws SQLException { } } - /** The call argument values in order: IN and INOUT parameters; OUT-only parameters skipped. */ - private List inArguments() throws SQLException { - return callArguments(parameterCount, placeholderOutParameters(), bound, parameters); - } - - /** - * The {@code CALL} argument values: every parameter in order, an unbound OUT parameter as NULL. - * {@code CALL} requires an argument for each of the procedure's parameters, OUT ones included, - * but does not evaluate the OUT arguments -- so NULL is the conventional filler, and it is what - * lets the server resolve the procedure by arity. An OUT parameter that was also bound is INOUT - * and sends its input value. - */ - private List callProcedureArguments() throws SQLException { - return procedureArguments(parameterCount, placeholderOutParameters(), bound, parameters); - } - - /** @see #callProcedureArguments() */ - static List procedureArguments( - int parameterCount, Set outParameters, boolean[] bound, Object[] parameters) throws SQLException { - List args = new ArrayList<>(parameterCount); - for (int i = 1; i <= parameterCount; i++) { - if (bound[i - 1]) { - args.add(parameters[i - 1]); - } else if (outParameters.contains(i)) { - args.add(null); - } else { - throw new SQLException("parameter " + i + " is not set"); - } - } - return args; - } - /** * The registered OUT indices translated to placeholder space. Identity except in the return * form, where JDBC index 1 (the return) has no placeholder and later indices shift down by one. @@ -240,37 +223,6 @@ private Set placeholderOutParameters() { return shifted; } - /** - * Selects the argument values the routine call sends. A registered OUT parameter that was never - * bound is OUT-only and not part of PostgreSQL's call signature; a registered parameter that was - * also bound is INOUT, and its input value must be sent as an argument. - */ - static List callArguments( - int parameterCount, Set outParameters, boolean[] bound, Object[] parameters) throws SQLException { - List args = new ArrayList<>(); - for (int i = 1; i <= parameterCount; i++) { - if (outParameters.contains(i) && !bound[i - 1]) { - continue; - } - if (!bound[i - 1]) { - throw new SQLException("parameter " + i + " is not set"); - } - args.add(parameters[i - 1]); - } - return args; - } - - private static String placeholders(int count) { - StringBuilder out = new StringBuilder(); - for (int i = 1; i <= count; i++) { - if (i > 1) { - out.append(", "); - } - out.append('$').append(i); - } - return out.toString(); - } - /** Positions the result cursor at the single output row on first access. */ private PgResultSet outRow() throws SQLException { if (!outRowLoaded) { diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgCallableStatementTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgCallableStatementTest.java index f056c7ed..5aa74239 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgCallableStatementTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgCallableStatementTest.java @@ -6,6 +6,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; @@ -23,23 +25,21 @@ class PgCallableStatementTest { @Test void boundInoutParameterIsSentAsAnArgument() throws SQLException { // fn(IN a, INOUT b): both indices are bound, index 2 is also registered OUT. - List args = - PgCallableStatement.callArguments(2, Set.of(2), new boolean[] {true, true}, new Object[] {"a", "b"}); + List args = selectArguments(2, Set.of(2), new boolean[] {true, true}, new Object[] {"a", "b"}); assertEquals(List.of("a", "b"), args); } @Test void outOnlyParameterIsOmittedFromTheArguments() throws SQLException { // fn(IN a, OUT c): index 2 is registered and never bound. - List args = - PgCallableStatement.callArguments(2, Set.of(2), new boolean[] {true, false}, new Object[] {"a", null}); + List args = selectArguments(2, Set.of(2), new boolean[] {true, false}, new Object[] {"a", null}); assertEquals(List.of("a"), args); } @Test void mixedInInoutAndOutKeepDeclarationOrder() throws SQLException { // fn(IN a, INOUT b, OUT c, IN d): arguments are a, b, d in order. - List args = PgCallableStatement.callArguments( + List args = selectArguments( 4, Set.of(2, 3), new boolean[] {true, true, false, true}, new Object[] {"a", "b", null, "d"}); assertEquals(List.of("a", "b", "d"), args); } @@ -48,8 +48,7 @@ void mixedInInoutAndOutKeepDeclarationOrder() throws SQLException { void unboundInParameterIsRejected() { SQLException e = assertThrows( SQLException.class, - () -> PgCallableStatement.callArguments( - 2, Set.of(), new boolean[] {true, false}, new Object[] {"a", null})); + () -> selectArguments(2, Set.of(), new boolean[] {true, false}, new Object[] {"a", null})); assertEquals("parameter 2 is not set", e.getMessage()); } @@ -58,8 +57,7 @@ void unboundInParameterIsRejected() { @Test void callSendsAnOutOnlyParameterAsNull() throws SQLException { // p(IN a, OUT b): CALL takes an argument for b too, and does not evaluate it. - List args = PgCallableStatement.procedureArguments( - 2, Set.of(2), new boolean[] {true, false}, new Object[] {"a", null}); + List args = callArguments(2, Set.of(2), new boolean[] {true, false}, new Object[] {"a", null}); assertEquals(2, args.size()); assertEquals("a", args.get(0)); assertNull(args.get(1)); @@ -68,8 +66,7 @@ void callSendsAnOutOnlyParameterAsNull() throws SQLException { @Test void callSendsABoundInoutParameterAsItsInputValue() throws SQLException { // p(INOUT a, OUT b): a is registered and bound, so its input value goes on the wire. - List args = PgCallableStatement.procedureArguments( - 2, Set.of(1, 2), new boolean[] {true, false}, new Object[] {21, null}); + List args = callArguments(2, Set.of(1, 2), new boolean[] {true, false}, new Object[] {21, null}); assertEquals(2, args.size()); assertEquals(21, args.get(0)); assertNull(args.get(1)); @@ -78,7 +75,7 @@ void callSendsABoundInoutParameterAsItsInputValue() throws SQLException { @Test void callKeepsDeclarationOrderAcrossInInoutAndOut() throws SQLException { // p(IN a, INOUT b, OUT c, IN d): four arguments, the OUT one null, order preserved. - List args = PgCallableStatement.procedureArguments( + List args = callArguments( 4, Set.of(2, 3), new boolean[] {true, true, false, true}, new Object[] {"a", "b", null, "d"}); assertEquals(java.util.Arrays.asList("a", "b", null, "d"), args); } @@ -88,8 +85,26 @@ void callKeepsDeclarationOrderAcrossInInoutAndOut() throws SQLException { void callRejectsAnUnsetInParameter() { SQLException e = assertThrows( SQLException.class, - () -> PgCallableStatement.procedureArguments( - 2, Set.of(2), new boolean[] {false, false}, new Object[] {null, null})); + () -> callArguments(2, Set.of(2), new boolean[] {false, false}, new Object[] {null, null})); assertTrue(e.getMessage().contains("parameter 1"), e.getMessage()); } + + /** The values sent for {@code n} bare {@code ?} arguments under SELECT. */ + private static List selectArguments(int n, Set out, boolean[] bound, Object[] parameters) + throws SQLException { + return values(n, false, out, bound, parameters); + } + + /** The values sent for {@code n} bare {@code ?} arguments under CALL. */ + private static List callArguments(int n, Set out, boolean[] bound, Object[] parameters) + throws SQLException { + return values(n, true, out, bound, parameters); + } + + private static List values(int n, boolean call, Set out, boolean[] bound, Object[] parameters) + throws SQLException { + List values = new ArrayList<>(); + CallArguments.rebuild(String.join(", ", Collections.nCopies(n, "?")), call, out, bound, parameters, values); + return values; + } } From 0daaf1c968a5dae5f83156c0f22d70eaff497164 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:11:17 +0000 Subject: [PATCH 085/150] test(jdbc): pin literal and expression arguments in call escapes --- .../client/jdbc/CallArgumentsTest.java | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/CallArgumentsTest.java diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/CallArgumentsTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/CallArgumentsTest.java new file mode 100644 index 00000000..998ed72d --- /dev/null +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/CallArgumentsTest.java @@ -0,0 +1,65 @@ +package org.postgresql.client.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import org.junit.jupiter.api.Test; + +/** A {@code {call ...}} escape keeps the arguments as written, literals included. */ +class CallArgumentsTest { + + private final List values = new ArrayList<>(); + + private String rebuild(String text, boolean call, Set out, Object... bound) throws SQLException { + boolean[] isBound = new boolean[bound.length]; + for (int i = 0; i < bound.length; i++) { + isBound[i] = bound[i] != null; + } + return CallArguments.rebuild(text, call, out, isBound, bound, values); + } + + @Test + void literalArgumentsAreKept() throws SQLException { + assertEquals("$1, 1", rebuild("?, 1", false, Set.of(), "a")); + assertEquals(List.of("a"), values); + } + + @Test + void expressionsKeepTheirPlaceholdersAsInParameters() throws SQLException { + assertEquals( + "$1 + 1, 'x, y', lower($2), ARRAY[1, 2]", + rebuild("? + 1, 'x, y', lower(?), ARRAY[1, 2]", false, Set.of(), 5, "B")); + assertEquals(List.of(5, "B"), values); + } + + @Test + void outOnlyParametersAreDroppedUnderSelectAndNullUnderCall() throws SQLException { + // f(IN ?, 42, OUT ?): placeholder 2 is OUT-only. + assertEquals("$1, 42", rebuild("?, 42, ?", false, Set.of(2), "a", null)); + values.clear(); + assertEquals("$1, 42, $2", rebuild("?, 42, ?", true, Set.of(2), "a", null)); + assertEquals(Arrays.asList("a", null), values); + } + + @Test + void quotedQuestionMarksAndCommentsAreNotPlaceholders() throws SQLException { + assertEquals( + "'?', \"a?\", $$?,$$, $1 /* ?, */", rebuild("'?', \"a?\", $$?,$$, ? /* ?, */", false, Set.of(), "v")); + assertEquals(List.of("v"), values); + } + + @Test + void doubledQuestionMarkIsALiteral() throws SQLException { + assertEquals("$1 ? 'k'", rebuild("? ?? 'k'", false, Set.of(), "{}")); + } + + @Test + void emptyArgumentListStaysEmpty() throws SQLException { + assertEquals("", rebuild("", false, Set.of())); + assertEquals("", rebuild(" ", true, Set.of())); + } +} From ec05b94f9a2332c81e7eddc28b1b6ad853618863 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:13:04 +0000 Subject: [PATCH 086/150] fix(jdbc): step over all of PostgreSQL's quoting in {fn ...} arguments The {fn ...} translation split its arguments and matched parentheses knowing only '...' and "..." with doubled quotes, so a comma or parenthesis inside a dollar-quoted string, an E'' string with a backslash-escaped quote, or a comment was taken as syntax and the call was mistranslated. Separately, isEscapeStringPrefix took the quote in x$e'..' for an E'' string, although x$e is one identifier, which threw the main lexer's placeholder count off. Add a shared skipLexeme to SqlLexing, use it for the {fn} splitting (sharing the call-escape argument splitter), and count '$' as an identifier character before the e. --- .../postgresql/client/jdbc/CallArguments.java | 30 +--------- .../org/postgresql/client/jdbc/SqlParser.java | 55 ++++++------------- .../postgresql/client/jdbc/sql/SqlLexing.java | 31 ++++++++++- 3 files changed, 48 insertions(+), 68 deletions(-) diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java index 33821e88..483c8df7 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java @@ -52,7 +52,7 @@ static String rebuild( int i = 0; while (i < end) { char c = trimmed.charAt(i); - int next = skipQuotedOrComment(trimmed, i, end); + int next = SqlLexing.skipLexeme(trimmed, i, end); if (next > i) { expression.append(trimmed, i, next); i = next; @@ -92,7 +92,7 @@ static List split(String text) { int end = text.length(); int i = 0; while (i < end) { - int next = skipQuotedOrComment(text, i, end); + int next = SqlLexing.skipLexeme(text, i, end); if (next > i) { i = next; continue; @@ -111,30 +111,4 @@ static List split(String text) { arguments.add(text.substring(start)); return arguments; } - - /** - * The index past the quoted string, identifier, dollar quote or comment opening at {@code i}, or - * {@code i} itself when none opens there. An unterminated one runs to {@code end}. - */ - private static int skipQuotedOrComment(String s, int i, int end) { - char c = s.charAt(i); - int next; - if (c == '\'') { - next = SqlLexing.skipSingleQuoted(s, i, end, SqlLexing.isEscapeStringPrefix(s, i)); - } else if (c == '"') { - next = SqlLexing.skipDoubleQuoted(s, i, end); - } else if (c == '$') { - next = SqlLexing.skipDollarQuote(s, i, end); - if (next == i + 1) { - return i; // a lone '$', not a quote - } - } else if (c == '-' && i + 1 < end && s.charAt(i + 1) == '-') { - next = SqlLexing.skipLineComment(s, i, end); - } else if (c == '/' && i + 1 < end && s.charAt(i + 1) == '*') { - next = SqlLexing.skipBlockComment(s, i, end); - } else { - return i; - } - return next < 0 ? end : next; - } } diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java index ae6bd38d..02e08ac9 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java @@ -308,60 +308,37 @@ private static String translateLocate(List args) { /** Finds the index of the {@code ')'} matching the {@code '('} at {@code open}, or -1. */ private static int matchingParen(String s, int open) { int depth = 0; - for (int i = open; i < s.length(); i++) { + int i = open; + while (i < s.length()) { + int next = SqlLexing.skipLexeme(s, i, s.length()); + if (next > i) { + i = next; + continue; + } char c = s.charAt(i); - if (c == '\'' || c == '"') { - i = skipQuoted(s, i, c); - } else if (c == '(') { + if (c == '(') { depth++; } else if (c == ')' && --depth == 0) { return i; } + i++; } return -1; } - /** Splits a function argument list on top-level commas, respecting nested parens and quotes. */ + /** + * Splits a function argument list on top-level commas, respecting nested parens and brackets, + * and stepping over quoted strings (E'' and dollar-quoted ones too), quoted identifiers and + * comments, whose commas and parentheses are not syntax. + */ private static List splitArgs(String s) { List args = new ArrayList<>(); - if (s.isBlank()) { - return args; - } - int depth = 0; - int start = 0; - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c == '\'' || c == '"') { - i = skipQuoted(s, i, c); - } else if (c == '(') { - depth++; - } else if (c == ')') { - depth--; - } else if (c == ',' && depth == 0) { - args.add(s.substring(start, i).trim()); - start = i + 1; - } + for (String arg : CallArguments.split(s)) { + args.add(arg.trim()); } - args.add(s.substring(start).trim()); return args; } - /** Returns the index of the quote closing the one at {@code i}, treating {@code qq} as escaped. */ - private static int skipQuoted(String s, int i, char quote) { - int j = i + 1; - while (j < s.length()) { - if (s.charAt(j) == quote) { - if (j + 1 < s.length() && s.charAt(j + 1) == quote) { - j += 2; // doubled quote: an escaped quote, stay inside - continue; - } - return j; - } - j++; - } - return s.length() - 1; // unterminated; stop at the end (best effort) - } - /** * The first significant word in {@code sql} (lowercased) -- a run of identifier characters after * skipping leading whitespace and line/block comments; empty string if there is none. Used to diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/sql/SqlLexing.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/sql/SqlLexing.java index 3cc55623..a32973e8 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/sql/SqlLexing.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/sql/SqlLexing.java @@ -28,7 +28,36 @@ public static boolean isEscapeStringPrefix(String sql, int i) { return true; } char before = sql.charAt(i - 2); - return !(Character.isLetterOrDigit(before) || before == '_'); + // '$' too: PostgreSQL identifiers may contain it after the first character, so the 'e' of + // x$e'..' ends the identifier x$e and the quote opens a plain string. + return !(Character.isLetterOrDigit(before) || before == '_' || before == '$'); + } + + /** + * Skips the quoted string, quoted identifier, dollar-quoted string or comment opening at + * {@code i}: returns the index just past it, {@code end} if it never terminates, or {@code i} + * itself when none opens there. For scanners that only need to step over these constructs. + */ + public static int skipLexeme(String sql, int i, int end) { + char c = sql.charAt(i); + int next; + if (c == '\'') { + next = skipSingleQuoted(sql, i, end, isEscapeStringPrefix(sql, i)); + } else if (c == '"') { + next = skipDoubleQuoted(sql, i, end); + } else if (c == '$') { + next = skipDollarQuote(sql, i, end); + if (next == i + 1) { + return i; // a lone '$', not a quote + } + } else if (c == '-' && i + 1 < end && sql.charAt(i + 1) == '-') { + next = skipLineComment(sql, i, end); + } else if (c == '/' && i + 1 < end && sql.charAt(i + 1) == '*') { + next = skipBlockComment(sql, i, end); + } else { + return i; + } + return next < 0 ? end : next; } /** From 2c30119e02c27487dce83fceccd2ded8458d835a Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:13:04 +0000 Subject: [PATCH 087/150] test(jdbc): pin {fn} argument splitting and the x$e'' lexing case --- .../postgresql/client/jdbc/SqlParserTest.java | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java index e59426b1..37156ad8 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java @@ -202,4 +202,27 @@ void detectsMultipleStatements() { assertFalse(parse("select ';'").multiStatement()); assertFalse(parse("select 1; -- trailing comment\n").multiStatement()); } + + @Test + void fnArgumentsStepOverDollarQuotesEStringsAndComments() { + // Commas and parentheses inside these are not syntax; splitting there mistranslated the call. + assertEquals( + "coalesce($$a,b)$$,'x')", + SqlParser.parse("{fn ifnull($$a,b)$$,'x')}", true).nativeSql()); + assertEquals( + "coalesce(E'it\\'s, ok','x')", + SqlParser.parse("{fn ifnull(E'it\\'s, ok','x')}", true).nativeSql()); + assertEquals( + "position('a' in b /* , ) */)", + SqlParser.parse("{fn locate('a', b /* , ) */)}", true).nativeSql()); + } + + @Test + void dollarInsideAnIdentifierDoesNotMakeAnEString() { + // x$e is one identifier, so the quote after it opens a plain string, in which a backslash + // is an ordinary character and the next quote closes it. + ParsedSql p = SqlParser.parse("select x$e'\\', ?", false); + assertEquals("select x$e'\\', $1", p.nativeSql()); + assertEquals(1, p.parameterCount()); + } } From 4b4cd0d8e569f7387d415d042daf69b28237941d Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:14:26 +0000 Subject: [PATCH 088/150] fix(compat): key the base column name cache by the whole column pair getBaseColumnName cached its catalog answers under tableOid * 31 + attnum, which collides: in a join, table OID 1 column 32 and table OID 2 column 1 shared one entry, so the second column got the first one's name. Pack the OID and the attribute number into a long so distinct pairs never share a key. --- .../src/main/java/org/postgresql/PgResultSets.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgResultSets.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgResultSets.java index 8570db3c..706db12e 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgResultSets.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgResultSets.java @@ -209,7 +209,7 @@ private static final class MetaDataHandler implements InvocationHandler { private final HstoreSupport hstore; /** Lazy per-column base names, resolved together from one catalog round trip per table OID. */ - private Map baseColumnNames; + private Map baseColumnNames; MetaDataHandler(ResultSetMetaData delegate, Connection connection, HstoreSupport hstore) { this.delegate = delegate; @@ -318,7 +318,9 @@ private String baseColumnName(int column) throws SQLException { if (source.tableOid() == 0 || source.columnAttributeNumber() <= 0) { return ""; } - int key = source.tableOid() * 31 + source.columnAttributeNumber(); + // Both halves of the pair, packed without overlap: tableOid * 31 + attnum collided (OID 1, + // column 32 and OID 2, column 1), handing one column another's name. + long key = ((long) source.tableOid() << 32) | Integer.toUnsignedLong(source.columnAttributeNumber()); if (baseColumnNames == null) { baseColumnNames = new HashMap<>(); } else { From 8a181405be483d4b0849375932e8049f2a088bbe Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:14:26 +0000 Subject: [PATCH 089/150] test(compat): pin distinct base column names for formerly colliding pairs --- .../postgresql/BaseColumnNameCacheTest.java | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/BaseColumnNameCacheTest.java diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/BaseColumnNameCacheTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/BaseColumnNameCacheTest.java new file mode 100644 index 00000000..e7f9eb52 --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/BaseColumnNameCacheTest.java @@ -0,0 +1,76 @@ +package org.postgresql; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Proxy; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.ColumnMetadata; +import org.postgresql.client.core.RowMetadata; + +/** + * getBaseColumnName caches catalog answers by the (table OID, attnum) pair; two columns whose pairs + * differ must never share an entry, which tableOid * 31 + attnum did for OID 1/attnum 32 and OID 2/attnum 1. + */ +class BaseColumnNameCacheTest { + + @SuppressWarnings("unchecked") + private static T proxy(Class type, InvocationHandler handler) { + return (T) + Proxy.newProxyInstance(BaseColumnNameCacheTest.class.getClassLoader(), new Class[] {type}, handler); + } + + private static ColumnMetadata column(int tableOid, int attnum) { + return proxy(ColumnMetadata.class, (p, m, a) -> switch (m.getName()) { + case "tableOid" -> tableOid; + case "columnAttributeNumber" -> attnum; + default -> null; + }); + } + + /** Answers the pg_attribute lookup with a name naming the pair it was asked about. */ + private static Connection catalog() { + return proxy(Connection.class, (p, m, a) -> { + if (!m.getName().equals("prepareStatement")) { + return null; + } + int[] bound = new int[2]; + return proxy(PreparedStatement.class, (ps, pm, pa) -> switch (pm.getName()) { + case "setInt" -> { + bound[(Integer) pa[0] - 1] = (Integer) pa[1]; + yield null; + } + case "executeQuery" -> { + boolean[] read = {false}; + yield proxy(ResultSet.class, (r, rm, ra) -> switch (rm.getName()) { + case "next" -> !read[0] && (read[0] = true); + case "getString" -> "oid" + bound[0] + "_att" + bound[1]; + default -> null; + }); + } + default -> null; + }); + }); + } + + @Test + void pairsThatUsedToCollideGetTheirOwnNames() throws Exception { + RowMetadata row = proxy( + RowMetadata.class, + (p, m, a) -> + m.getName().equals("column") ? ((Integer) a[0] == 1 ? column(1, 32) : column(2, 1)) : null); + ResultSetMetaData delegate = proxy(ResultSetMetaData.class, (p, m, a) -> switch (m.getName()) { + case "isWrapperFor" -> a[0] == RowMetadata.class; + case "unwrap" -> row; + default -> null; + }); + PGResultSetMetaData md = (PGResultSetMetaData) PgResultSets.wrapMetaData(delegate, catalog(), null); + + assertEquals("oid1_att32", md.getBaseColumnName(1)); + assertEquals("oid2_att1", md.getBaseColumnName(2)); + } +} From af4d441f04f8465539d10c73971624f663a16cad Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:15:38 +0000 Subject: [PATCH 090/150] fix(jdbc): handle null and malformed catalog values in DatabaseMetaData tableType and foreignKeyRule switched on a catalog string with no null case, so a NULL relkind or foreign-key action threw NullPointerException, and the oidvector and oid[] parsers used Integer.parseInt, which threw NumberFormatException both on malformed text and on a legitimate OID above 2^31 - 1 (OIDs are unsigned). Fall back to the defaults on NULL, parse OIDs as unsigned, and report malformed ones as SQLException. --- .../client/jdbc/PgDatabaseMetaData.java | 29 ++++++++++++++----- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDatabaseMetaData.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDatabaseMetaData.java index b29967e3..28a5393b 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDatabaseMetaData.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDatabaseMetaData.java @@ -943,11 +943,12 @@ public ResultSet getTables(String catalog, String schemaPattern, String tableNam * the SYSTEM/TEMPORARY variants ({@code pg_catalog}/{@code information_schema} are system, * {@code pg_toast} is toast, {@code pg_temp_*} are temporary). */ - private static String tableType(String relkind, String schema) { + static String tableType(String relkind, String schema) { boolean system = "pg_catalog".equals(schema) || "information_schema".equals(schema); boolean toast = schema != null && schema.startsWith("pg_toast"); boolean temp = schema != null && schema.startsWith("pg_temp_"); return switch (relkind) { + case null -> "TABLE"; case "r" -> toast ? "SYSTEM TOAST TABLE" : system ? "SYSTEM TABLE" : temp ? "TEMPORARY TABLE" : "TABLE"; case "p" -> temp ? "TEMPORARY TABLE" : "PARTITIONED TABLE"; case "v" -> system ? "SYSTEM VIEW" : temp ? "TEMPORARY VIEW" : "VIEW"; @@ -1330,9 +1331,10 @@ private ResultSet foreignKeys(String where, List params, String orderBy) "DEFERRABILITY"); } - private static short foreignKeyRule(String pgType) { + static short foreignKeyRule(String pgType) { return (short) switch (pgType) { + case null -> importedKeyNoAction; case "c" -> importedKeyCascade; case "r" -> importedKeyRestrict; case "n" -> importedKeySetNull; @@ -1651,31 +1653,44 @@ private List compositeAttributes(int relid) throws SQLException { } /** Parses an {@code oidvector} rendered as text ({@code "23 1043"}) into its OIDs. */ - private static int[] parseOidVector(String text) { + static int[] parseOidVector(String text) throws SQLException { if (text == null || text.isBlank()) { return new int[0]; } String[] parts = text.trim().split("\\s+"); int[] oids = new int[parts.length]; for (int i = 0; i < parts.length; i++) { - oids[i] = Integer.parseInt(parts[i]); + oids[i] = parseCatalogOid(parts[i]); } return oids; } - /** Parses an {@code int[]} array literal ({@code "{23,1043}"}), or null when the source was null/empty. */ - private static int[] parseIntArrayLiteral(String text) { + /** Parses an {@code oid[]} array literal ({@code "{23,1043}"}), or null when the source was null/empty. */ + static int[] parseIntArrayLiteral(String text) throws SQLException { String[] parts = parseTextArrayLiteral(text); if (parts == null) { return null; } int[] out = new int[parts.length]; for (int i = 0; i < parts.length; i++) { - out[i] = Integer.parseInt(parts[i].trim()); + out[i] = parseCatalogOid(parts[i]); } return out; } + /** + * An OID from catalog text. OIDs are unsigned, so one above 2^31 - 1 is legitimate and wraps to a + * negative int as the driver stores OIDs everywhere; anything not a number is a server answering + * something impossible, reported as an SQLException rather than a NumberFormatException. + */ + private static int parseCatalogOid(String text) throws SQLException { + try { + return (int) Long.parseLong(text.trim()); + } catch (NumberFormatException e) { + throw new SQLException("malformed OID in the catalog: " + text, e); + } + } + /** * Parses a one-dimensional array literal ({@code "{a,b}"}) into its unquoted elements, or null when the * source was null. Sufficient for the identifier/mode/OID arrays here, which never contain commas. From 4399ce01fe09ac189c32eac6b72c8b87f3fc5956 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:15:38 +0000 Subject: [PATCH 091/150] test(jdbc): pin DatabaseMetaData handling of null and large catalog values --- .../DatabaseMetaDataCatalogValuesTest.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/DatabaseMetaDataCatalogValuesTest.java diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/DatabaseMetaDataCatalogValuesTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/DatabaseMetaDataCatalogValuesTest.java new file mode 100644 index 00000000..b2e68ed1 --- /dev/null +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/DatabaseMetaDataCatalogValuesTest.java @@ -0,0 +1,35 @@ +package org.postgresql.client.jdbc; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import org.junit.jupiter.api.Test; + +/** + * Catalog values the metadata methods decode come from the server; null or malformed ones must + * not escape as NullPointerException or NumberFormatException. + */ +class DatabaseMetaDataCatalogValuesTest { + + @Test + void nullRelkindAndRuleFallBackToTheDefaults() { + assertEquals("TABLE", PgDatabaseMetaData.tableType(null, "public")); + assertEquals(DatabaseMetaData.importedKeyNoAction, PgDatabaseMetaData.foreignKeyRule(null)); + } + + @Test + void oidsAboveTheSignedRangeParse() throws SQLException { + // OIDs are unsigned; 3000000000 is a real OID on a long-lived cluster. + assertArrayEquals(new int[] {23, (int) 3000000000L}, PgDatabaseMetaData.parseOidVector("23 3000000000")); + assertArrayEquals(new int[] {(int) 3000000000L}, PgDatabaseMetaData.parseIntArrayLiteral("{3000000000}")); + } + + @Test + void malformedOidsAreSqlExceptions() { + assertThrows(SQLException.class, () -> PgDatabaseMetaData.parseOidVector("23 x")); + assertThrows(SQLException.class, () -> PgDatabaseMetaData.parseIntArrayLiteral("{23,x}")); + } +} From a60a8a182015ab700b09f5280de467bce7b5b397 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:16:39 +0000 Subject: [PATCH 092/150] fix(compat): report malformed hstore and interval text as bad input HStoreConverter.fromString threw StringIndexOutOfBoundsException on truncated text, and PGInterval.setValue, which declares SQLException, let NumberFormatException and StringIndexOutOfBoundsException escape for a non-numeric quantity or a cut-off token. Report the first as an IllegalArgumentException (its signature allows no checked exception) and the second as the SQLException it already throws for other malformed input. --- .../org/postgresql/util/HStoreConverter.java | 16 +++++++++++++++- .../java/org/postgresql/util/PGInterval.java | 14 ++++++++++---- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/HStoreConverter.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/HStoreConverter.java index 0de7a259..25d89b4a 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/HStoreConverter.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/HStoreConverter.java @@ -16,8 +16,22 @@ public final class HStoreConverter { private HStoreConverter() {} - /** Parses the server's hstore text form into a map; a {@code NULL} value becomes Java null. */ + /** + * Parses the server's hstore text form into a map; a {@code NULL} value becomes Java null. + * + * @throws IllegalArgumentException if the text is truncated + */ public static Map fromString(String s) { + try { + return parse(s); + } catch (IndexOutOfBoundsException e) { + // Text cut off inside a token. The signature allows no checked exception, so report it + // as the bad argument it is rather than as an index error from deep in the parser. + throw new IllegalArgumentException("malformed hstore text: truncated", e); + } + } + + private static Map parse(String s) { Map result = new HashMap<>(); int length = s.length(); StringBuilder sb = new StringBuilder(); diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/PGInterval.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/PGInterval.java index 3468fedf..8fec93ca 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/PGInterval.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/PGInterval.java @@ -91,10 +91,16 @@ public void setValue(String value) throws SQLException { if (text.isEmpty()) { return; } - if (text.charAt(0) == 'P') { - parseIso8601(text); - } else { - parseTraditional(text); + try { + if (text.charAt(0) == 'P') { + parseIso8601(text); + } else { + parseTraditional(text); + } + } catch (NumberFormatException | IndexOutOfBoundsException e) { + // A quantity that is not a number, or text cut off mid-token: still bad input, which + // this method reports as an SQLException. + throw new SQLException("malformed interval: " + text, e); } } From a24212d002f216b6d359168300174d55013c7519 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:16:39 +0000 Subject: [PATCH 093/150] test(compat): pin errors for malformed hstore and interval text --- .../java/org/postgresql/util/HStoreConverterTest.java | 11 +++++++++++ .../test/java/org/postgresql/util/PGIntervalTest.java | 7 +++++++ 2 files changed, 18 insertions(+) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/HStoreConverterTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/HStoreConverterTest.java index df773d39..0513a85f 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/HStoreConverterTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/HStoreConverterTest.java @@ -1,6 +1,8 @@ package org.postgresql.util; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Collections; import java.util.HashMap; @@ -74,4 +76,13 @@ void roundTripsThroughBothDirections() { map.put("k3", null); assertEquals(map, HStoreConverter.fromString(HStoreConverter.toString(map))); } + + @Test + void truncatedTextIsAnIllegalArgument() { + for (String text : new String[] {"\"a\"=>", "\"a", "\"a\"=>\"b", "\"a\"=>\"b\\"}) { + IllegalArgumentException e = + assertThrows(IllegalArgumentException.class, () -> HStoreConverter.fromString(text), text); + assertTrue(e.getMessage().contains("hstore"), e.getMessage()); + } + } } diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/PGIntervalTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/PGIntervalTest.java index be49cc3a..67cb741e 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/PGIntervalTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/PGIntervalTest.java @@ -73,4 +73,11 @@ void wholeAndMicroSecondsSplit() { void rejectsUnknownUnit() { assertThrows(SQLException.class, () -> new PGInterval("3 fortnights")); } + + @Test + void malformedTextIsAnSqlException() { + for (String text : new String[] {"P1xY", "Pabc", "1 years 2 mon x days", "x years", "@ 1 days ago 2"}) { + assertThrows(SQLException.class, () -> new PGInterval().setValue(text), text); + } + } } From dc6b2975a23b9318aef1dcba47ae1684cd23c9ef Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:18:08 +0000 Subject: [PATCH 094/150] fix(compat): stop sharing the copy-in transfer buffer across calls CopyManager kept one transfer buffer per manager and reused it for every copyIn(sql, InputStream), handing it to the caller's InputStream each time. A stream that kept a reference saw its data overwritten by the next copy. Allocate the buffer per call; a COPY dwarfs the allocation. PGCopyInputStream.readFromCopy was also flagged for returning its internal chunk. It does so only after marking the chunk consumed, and reads the next chunk into a new array, so the caller owns it; say so in its Javadoc rather than copy every chunk. --- .../main/java/org/postgresql/copy/CopyManager.java | 13 +++---------- .../java/org/postgresql/copy/PGCopyInputStream.java | 6 +++++- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/CopyManager.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/CopyManager.java index b927d909..7acdb253 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/CopyManager.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/CopyManager.java @@ -26,11 +26,6 @@ public class CopyManager { private final PgConnection core; - // Reused across copyIn(sql, InputStream, ...) calls on this manager so a caller running many bulk - // copies does not allocate a fresh transfer buffer each time (task 16). COPY operations on a - // connection are serial (the connection is busy for the whole copy), so sharing the field is safe. - private byte[] transferBuffer; - /** Builds a manager over the pg-java core connection unwrapped from {@code connection}. */ public CopyManager(Connection connection) throws SQLException { this(connection.unwrap(PgConnection.class)); @@ -77,11 +72,9 @@ public long copyIn(String sql, InputStream from) throws SQLException, IOExceptio /** Copies {@code from} into a {@code COPY ... FROM STDIN} using {@code bufferSize} chunks. */ public long copyIn(String sql, InputStream from, int bufferSize) throws SQLException, IOException { CopyIn op = copyIn(sql); - byte[] buffer = transferBuffer; - if (buffer == null || buffer.length != bufferSize) { - buffer = new byte[bufferSize]; - transferBuffer = buffer; - } + // A fresh buffer per copy. It is handed to the caller's InputStream, so one shared across + // calls was visible to (and overwritten under) any stream that kept a reference to it. + byte[] buffer = new byte[bufferSize]; try { int read; while ((read = from.read(buffer)) >= 0) { diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/PGCopyInputStream.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/PGCopyInputStream.java index 22f9f263..ee9d781f 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/PGCopyInputStream.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/PGCopyInputStream.java @@ -77,7 +77,11 @@ public int read(byte[] b, int off, int siz) throws IOException { return got == 0 && !didReadSomething ? -1 : got; } - /** Returns the current buffered chunk remainder, or the next chunk; {@code null} at the end. */ + /** + * Returns the current buffered chunk remainder, or the next chunk; {@code null} at the end. The + * array belongs to the caller: a whole chunk is handed over as is, but only once it is marked + * consumed, and the stream reads the next chunk into a new array, never into this one. + */ @Override public byte[] readFromCopy() throws SQLException { byte[] result = null; From 59f7b1a7d41ac5af65118d9719da08ebc015efe3 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:18:08 +0000 Subject: [PATCH 095/150] test(compat): pin a fresh copy-in buffer per call --- .../copy/CopyBufferOwnershipTest.java | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/copy/CopyBufferOwnershipTest.java diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/copy/CopyBufferOwnershipTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/copy/CopyBufferOwnershipTest.java new file mode 100644 index 00000000..52e9db3f --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/copy/CopyBufferOwnershipTest.java @@ -0,0 +1,57 @@ +package org.postgresql.copy; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.PgConnection; +import org.postgresql.client.core.PgCopyInStream; + +/** Copy buffers handed to caller code are not reused behind its back. */ +class CopyBufferOwnershipTest { + + private static Object defaultFor(Class type) { + return type == long.class ? 0L : type == int.class ? 0 : type == boolean.class ? false : null; + } + + private static PgConnection core() { + PgCopyInStream in = (PgCopyInStream) Proxy.newProxyInstance( + CopyBufferOwnershipTest.class.getClassLoader(), + new Class[] {PgCopyInStream.class}, + (p, m, a) -> defaultFor(m.getReturnType())); + return (PgConnection) Proxy.newProxyInstance( + CopyBufferOwnershipTest.class.getClassLoader(), + new Class[] {PgConnection.class}, + (p, m, a) -> m.getName().equals("copyIn") ? in : defaultFor(m.getReturnType())); + } + + @Test + void copyInBufferIsNotSharedAcrossCalls() throws Exception { + List seen = new ArrayList<>(); + CopyManager manager = new CopyManager(core()); + manager.copyIn("COPY t FROM STDIN", retaining(new byte[] {1, 2, 3}, seen), 8); + manager.copyIn("COPY t FROM STDIN", retaining(new byte[] {9, 9, 9}, seen), 8); + + assertNotSame(seen.get(0), seen.get(1)); + assertArrayEquals(new byte[] {1, 2, 3}, Arrays.copyOf(seen.get(0), 3), "the first copy's buffer was reused"); + } + + /** An InputStream that keeps a reference to every buffer it is asked to fill. */ + private static InputStream retaining(byte[] data, List seen) { + return new ByteArrayInputStream(data) { + @Override + public int read(byte[] b, int off, int len) { + if (seen.isEmpty() || seen.get(seen.size() - 1) != b) { + seen.add(b); + } + return super.read(b, off, len); + } + }; + } +} From 52b25df67ee8ff3882070cb70661acf2f23d4be7 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:19:14 +0000 Subject: [PATCH 096/150] fix(compat): decode BaseDataSource URLs with the drivers' own decoder BaseDataSource.setUrl decoded components with URLDecoder, which turns '+' into a space, while the compat and core drivers keep a '+' as is. One URL therefore configured a data source differently from a direct connect: my+db became database "my db". Use the shared percent decoder, which also makes the userinfo special case unnecessary; a malformed escape is still an IllegalArgumentException from setUrl. --- .../postgresql/ds/common/BaseDataSource.java | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java index d404313c..f4aa13a3 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java @@ -4,7 +4,6 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; -import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.sql.Connection; @@ -21,7 +20,9 @@ import javax.sql.CommonDataSource; import org.postgresql.PGProperty; import org.postgresql.client.compat.internal.CompatDriverHooks; +import org.postgresql.client.core.PgConfigurationException; import org.postgresql.client.core.internal.jdbc.ConnectionStringRedaction; +import org.postgresql.client.core.internal.jdbc.PercentDecoding; /** * pgjdbc-compatible {@code org.postgresql.ds.common.BaseDataSource} (N4.3): the common JavaBean @@ -218,10 +219,10 @@ public void setUrl(String url) { hosts = hosts.substring(at + 1); int colon = userinfo.indexOf(':'); if (colon >= 0) { - setUser(decodeUserinfo(userinfo.substring(0, colon))); - setPassword(decodeUserinfo(userinfo.substring(colon + 1))); + setUser(decode(userinfo.substring(0, colon))); + setPassword(decode(userinfo.substring(colon + 1))); } else if (!userinfo.isEmpty()) { - setUser(decodeUserinfo(userinfo)); + setUser(decode(userinfo)); } } String[] parts = hosts.split(","); @@ -261,11 +262,6 @@ public void setUrl(String url) { } } - /** Percent-decodes as the core parser does, which leaves a {@code +} alone. */ - private static String decodeUserinfo(String value) { - return decode(value.replace("+", "%2B")); - } - private static int parsePort(String text) { try { return Integer.parseInt(text); @@ -593,8 +589,17 @@ private static String encode(String value) { .replace("+", "%20"); } + /** + * Decodes a URL component as the compat and core drivers do, so a URL means the same here as on + * a connect: only {@code %XX} is special, and a {@code +} stays a {@code +} (URLDecoder made it a + * space). + */ private static String decode(String value) { - return URLDecoder.decode(value, StandardCharsets.UTF_8); + try { + return PercentDecoding.decode(value); + } catch (PgConfigurationException e) { + throw new IllegalArgumentException(e.getMessage(), e); + } } /** From 881eedab922f193580f840a0b861b76b9eaa001c Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:19:14 +0000 Subject: [PATCH 097/150] test(compat): pin '+' handling in BaseDataSource.setUrl --- .../org/postgresql/ds/common/BaseDataSourceTest.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java index 2b9ff037..3d68f6fa 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java @@ -139,6 +139,16 @@ void objectFactoryDoesNotInitializeAClassOutsideTheFamily() throws Exception { assertFalse(STATIC_INIT_RAN.get(), "the named class's static initializer must not have run"); } + @Test + void setUrlKeepsALiteralPlusAsTheDriversDo() { + PGSimpleDataSource ds = new PGSimpleDataSource(); + ds.setUrl("jdbc:postgresql://h/my+db?ApplicationName=a+b%20c&options=-c%20x%3D1"); + assertEquals("my+db", ds.getDatabaseName()); + assertEquals("a+b c", ds.getApplicationName()); + assertEquals("-c x=1", ds.getOptions()); + assertThrows(IllegalArgumentException.class, () -> ds.setUrl("jdbc:postgresql://h/db?x=%zz")); + } + @Test void shortFormUrlTargetsLocalhost() { PGSimpleDataSource ds = new PGSimpleDataSource(); From d5e7cca44fc3fd9194f0b707c26ccbf885cece29 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:20:29 +0000 Subject: [PATCH 098/150] fix(core): send only parseable names to the composite type lookup TypeCache documented its to_regtype lookup as never throwing, so that it could not abort the caller's transaction. to_regtype returns NULL for a name that does not exist, but before PostgreSQL 16 it raises a syntax error for one that does not parse, and a bound PgComposite or Struct type name is caller input. Look up only names of the form a composite can have: one to three dot-separated identifiers, unquoted or double-quoted. Anything else cannot name a composite and falls back to the record literal without a round trip. The escaping test now uses a quoted identifier, which can still carry the quote and backslash it exercises. --- .../org/postgresql/client/core/TypeCache.java | 71 ++++++++++++++++++- .../client/core/TypeCacheLookupTest.java | 5 +- 2 files changed, 71 insertions(+), 5 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java b/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java index c3eaf003..c44dc3e4 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java @@ -75,9 +75,10 @@ Codec resolve(int oid) { * Resolves a composite (row) type by name to its codec for a bind parameter, querying the catalog * on first use and caching the name-to-OID mapping (C10.9). Returns {@code null} when the name does * not resolve to a composite type, so the encoder falls back to the record literal under the - * unspecified OID (server type inference). The lookup uses {@code to_regtype} (never throwing, so it - * cannot abort a caller's transaction); on servers without it (before 9.4) the fallback still binds - * a composite that has column or cast context. + * unspecified OID (server type inference). The lookup uses {@code to_regtype}, which returns NULL + * for an unknown name rather than raising (a name that does not parse is never sent; see + * {@link #lookupOid}), so it cannot abort a caller's transaction; on servers without it (before 9.4) + * the fallback still binds a composite that has column or cast context. */ @Nullable Codec resolveComposite(String typeName) { @@ -161,6 +162,13 @@ private int lookupArrayOid(int elementOid) { /** Resolves a (possibly schema-qualified) type name to its OID, or 0 when it does not exist. */ private int lookupOid(String typeName) { + // to_regtype returns NULL for a name that does not exist but, before PostgreSQL 16, raises a + // syntax error for one that does not parse, and that error aborts the caller's transaction. + // A composite type is always named by a plain (possibly qualified, possibly quoted) name, so + // anything else cannot resolve here and is not worth the round trip or the risk. + if (!isQualifiedName(typeName)) { + return 0; + } // An E'' literal escapes the same way whatever standard_conforming_strings says: a plain '' // literal with only the quotes doubled let a type name ending in a backslash break out // once the session turned the setting off. Not bound as a parameter because this also @@ -173,6 +181,63 @@ private int lookupOid(String typeName) { return parseOid(row[0]); } + /** + * Whether {@code name} is one to three dot-separated identifiers, each either unquoted (a letter, + * underscore or non-ASCII character, then those, digits or {@code $}) or double-quoted with + * {@code ""} as the escaped quote -- the forms {@code oid::regtype::text} produces for a composite. + */ + static boolean isQualifiedName(String name) { + int parts = 0; + int i = 0; + int n = name.length(); + while (true) { + if (i >= n) { + return false; + } + if (name.charAt(i) == '"') { + int j = i + 1; + while (true) { + if (j >= n) { + return false; + } + if (name.charAt(j) == '"') { + if (j + 1 < n && name.charAt(j + 1) == '"') { + j += 2; + continue; + } + break; + } + j++; + } + if (j == i + 1) { + return false; // "" is not an identifier + } + i = j + 1; + } else { + char first = name.charAt(i); + if (!(Character.isLetter(first) || first == '_' || first >= 0x80)) { + return false; + } + i++; + while (i < n) { + char c = name.charAt(i); + if (!(Character.isLetterOrDigit(c) || c == '_' || c == '$' || c >= 0x80)) { + break; + } + i++; + } + } + parts++; + if (i == n) { + return parts <= 3; + } + if (name.charAt(i) != '.') { + return false; + } + i++; + } + } + private void queryAndRegister(int oid) { // oid::regtype::text is the search_path-aware type name (qualified/quoted only when needed), // so a decoded composite's name round-trips through the to_regtype bind lookup. diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java index 8eeaf990..eddff9b4 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java @@ -53,8 +53,9 @@ void typeNameIsSentAsAnEscapeStringLiteral() { }); TypeCache cache = new TypeCache(connect(server), Codecs.defaultRegistry()); - assertNull(cache.resolveComposite("x\\' || NULL); DROP TABLE t; --")); - assertEquals(List.of("SELECT to_regtype(E'x\\\\'' || NULL); DROP TABLE t; --')::oid"), queries); + // A quoted identifier may hold anything but a lone double quote, so the escaping still matters. + assertNull(cache.resolveComposite("\"x\\' || NULL); DROP TABLE t; --\"")); + assertEquals(List.of("SELECT to_regtype(E'\"x\\\\'' || NULL); DROP TABLE t; --\"')::oid"), queries); } @Test From 1d5ea705f65758d94027aa431d331ea7666cc544 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:20:43 +0000 Subject: [PATCH 099/150] test(core): pin that unparseable composite names are never looked up --- .../client/core/TypeCacheLookupTest.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java index eddff9b4..6fb4407e 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java @@ -102,4 +102,25 @@ void endlessDomainChainIsCut() { assertEquals(TypeCache.MAX_DEPTH, lookups.get()); assertFalse(connection.isBroken()); } + + @Test + void unparseableNamesAreNotSentAtAll() { + // Before PostgreSQL 16 to_regtype raises a syntax error for these, aborting the transaction. + List queries = new ArrayList<>(); + MockServer server = new MockServer() + .onMessage((s, f) -> queries.add(f.payloadReader().readCString())); + TypeCache cache = new TypeCache(connect(server), Codecs.defaultRegistry()); + + for (String name : new String[] {"x' || 1", "a b", "a..b", "1abc", "a.b.c.d", "\"\"", "\"open", ""}) { + assertNull(cache.resolveComposite(name), name); + } + assertEquals(List.of(), queries); + } + + @Test + void qualifiedNameRecognizesWhatRegtypeTextProduces() { + for (String name : new String[] {"t", "public.t", "db.public.t", "\"My Type\"", "s.\"a\"\"b\"", "t$1", "_x"}) { + assertTrue(TypeCache.isQualifiedName(name), name); + } + } } From ac0da7d25efd5f9280afaf791a8b25575e2fd5f6 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:21:44 +0000 Subject: [PATCH 100/150] fix(core): refuse an embedded NUL in startup values at config build The startup values (user, database, application_name, options, runtime parameters) and the password go out as NUL-terminated strings. The wire encoder already refuses an embedded NUL rather than truncating, but as an IllegalArgumentException thrown in the middle of the connect, which PgConnections rethrows and PgDriver does not turn into an SQLException (ADR-0007). Check them when the configuration is built and report a PgConfigurationException naming the field, never quoting the password. --- .../client/core/PgConnectionConfig.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/PgConnectionConfig.java b/postgresql-client/src/main/java/org/postgresql/client/core/PgConnectionConfig.java index 79997edc..90325310 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/PgConnectionConfig.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/PgConnectionConfig.java @@ -539,7 +539,31 @@ public PgConnectionConfig build() { if (user == null || user.isBlank()) { throw new PgConfigurationException("user is required"); } + // These go out as NUL-terminated strings, so an embedded NUL cannot be sent. The wire + // encoder refuses one too, but as an IllegalArgumentException from the middle of the + // connect; refusing it here makes it a configuration error the JDBC layer reports. + requireNoNul("user", user); + requireNoNul("database", database); + requireNoNul("application_name", applicationName); + requireNoNul("options", options); + runtimeParameters.forEach((name, value) -> { + requireNoNul("a runtime parameter name", name); + requireNoNul("runtime parameter " + name, value); + }); + if (password != null) { + for (char c : password.chars()) { + if (c == '\0') { + throw new PgConfigurationException("password contains an embedded NUL"); + } + } + } return new PgConnectionConfig(this); } + + private static void requireNoNul(String what, @Nullable String value) { + if (value != null && value.indexOf('\0') >= 0) { + throw new PgConfigurationException(what + " contains an embedded NUL"); + } + } } } From 7614d44aae8511d1d698e97740d9cbc734f3792b Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:21:44 +0000 Subject: [PATCH 101/150] test(core): pin the refusal of embedded NUL in startup values --- .../client/core/EmbeddedNulConfigTest.java | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/EmbeddedNulConfigTest.java diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/EmbeddedNulConfigTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/EmbeddedNulConfigTest.java new file mode 100644 index 00000000..b6e516e2 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/EmbeddedNulConfigTest.java @@ -0,0 +1,42 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.function.UnaryOperator; +import org.junit.jupiter.api.Test; + +/** + * Startup values go out NUL-terminated, so an embedded NUL is refused when the configuration is + * built: as a PgConfigurationException, not an IllegalArgumentException from the wire encoder. + */ +class EmbeddedNulConfigTest { + + private static PgConfigurationException refuse(UnaryOperator setting) { + PgConnectionConfig.Builder builder = + PgConnectionConfig.builder().host("h").user("app").database("db"); + return assertThrows( + PgConfigurationException.class, () -> setting.apply(builder).build()); + } + + @Test + void everyStartupValueIsChecked() { + assertTrue(refuse(b -> b.user("ap\0p")).getMessage().contains("user")); + assertTrue(refuse(b -> b.database("d\0b")).getMessage().contains("database")); + assertTrue(refuse(b -> b.applicationName("a\0")).getMessage().contains("application_name")); + assertTrue(refuse(b -> b.options("-c a=\0")).getMessage().contains("options")); + assertTrue(refuse(b -> b.runtimeParameter("search_path", "a\0b")) + .getMessage() + .contains("search_path")); + assertTrue( + refuse(b -> b.runtimeParameter("bad\0name", "x")).getMessage().contains("name")); + } + + @Test + void passwordIsCheckedWithoutBeingQuoted() { + PgConfigurationException e = refuse(b -> b.password("s3c\0ret")); + assertTrue(e.getMessage().contains("password"), e.getMessage()); + assertFalse(e.getMessage().contains("s3c"), e.getMessage()); + } +} From 5934175f9560acc0734c2c929664bfe7bfc926bd Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:22:45 +0000 Subject: [PATCH 102/150] fix(core): take the channel-binding hash of a PSS certificate from its parameters tls-server-end-point hashes the server certificate with the hash of its signature algorithm. RSASSA-PSS names no hash in the algorithm name, so the mapping fell through to SHA-256, while the server hashes with the digest in the PSS parameters: against a PSS certificate signed with SHA-384 or SHA-512 the bindings never matched and SCRAM-SHA-256-PLUS failed (closed, but for every such connection). Read the digest from the signature parameters, with the usual SHA-1 upgrade. --- .../core/internal/TlsChannelBinding.java | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/TlsChannelBinding.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/TlsChannelBinding.java index a3650dfa..23dcac66 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/TlsChannelBinding.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/TlsChannelBinding.java @@ -1,10 +1,15 @@ package org.postgresql.client.core.internal; +import java.io.IOException; +import java.security.AlgorithmParameters; +import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; +import java.security.spec.PSSParameterSpec; import java.util.Locale; +import org.jspecify.annotations.Nullable; import org.postgresql.client.core.PgTlsException; /** @@ -21,7 +26,8 @@ private TlsChannelBinding() {} /** The {@code tls-server-end-point} value for {@code certificate}. */ static byte[] tlsServerEndPoint(X509Certificate certificate) { - String hashAlgorithm = hashAlgorithmFor(certificate.getSigAlgName()); + String hashAlgorithm = hashAlgorithmFor( + certificate.getSigAlgName(), certificate.getSigAlgOID(), certificate.getSigAlgParams()); try { MessageDigest digest = MessageDigest.getInstance(hashAlgorithm); return digest.digest(certificate.getEncoded()); @@ -32,9 +38,17 @@ static byte[] tlsServerEndPoint(X509Certificate certificate) { /** * Maps a certificate signature algorithm (for example {@code SHA256withRSA}) to the - * digest used for channel binding, upgrading MD5/SHA-1 to SHA-256. + * digest used for channel binding, upgrading MD5/SHA-1 to SHA-256. RSASSA-PSS names no hash in + * its algorithm name; the hash is in the signature parameters, and a PSS certificate signed with + * SHA-384 or SHA-512 must bind with that hash, as the server computes it. */ - private static String hashAlgorithmFor(String signatureAlgorithm) { + static String hashAlgorithmFor(String signatureAlgorithm, String oid, byte @Nullable [] parameters) { + if (RSASSA_PSS_OID.equals(oid) || "RSASSA-PSS".equalsIgnoreCase(signatureAlgorithm)) { + String pssHash = pssDigest(parameters); + if (pssHash != null) { + return hashAlgorithmFor(pssHash, "", null); + } + } String name = signatureAlgorithm.toUpperCase(Locale.ROOT); int with = name.indexOf("WITH"); String hash = with > 0 ? name.substring(0, with) : name; @@ -48,4 +62,20 @@ private static String hashAlgorithmFor(String signatureAlgorithm) { default -> "SHA-256"; }; } + + private static final String RSASSA_PSS_OID = "1.2.840.113549.1.1.10"; + + /** The digest named by DER-encoded RSASSA-PSS parameters, or {@code null} if they do not decode. */ + private static @Nullable String pssDigest(byte @Nullable [] parameters) { + if (parameters == null) { + return null; + } + try { + AlgorithmParameters decoded = AlgorithmParameters.getInstance("RSASSA-PSS"); + decoded.init(parameters); + return decoded.getParameterSpec(PSSParameterSpec.class).getDigestAlgorithm(); + } catch (GeneralSecurityException | IOException e) { + return null; // fall back to the name-based mapping, as before + } + } } From 02c160789d3b6f0f476eb7bf1cfd7ac13152b2a3 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:22:45 +0000 Subject: [PATCH 103/150] test(core): pin the channel-binding hash for PSS certificates --- .../internal/TlsChannelBindingHashTest.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/internal/TlsChannelBindingHashTest.java diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/internal/TlsChannelBindingHashTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/internal/TlsChannelBindingHashTest.java new file mode 100644 index 00000000..67561805 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/internal/TlsChannelBindingHashTest.java @@ -0,0 +1,45 @@ +package org.postgresql.client.core.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.security.AlgorithmParameters; +import java.security.spec.MGF1ParameterSpec; +import java.security.spec.PSSParameterSpec; +import org.junit.jupiter.api.Test; + +/** The tls-server-end-point hash follows the certificate's signature hash, PSS included. */ +class TlsChannelBindingHashTest { + + private static byte[] pss(String digest, MGF1ParameterSpec mgf, int saltLength) throws Exception { + AlgorithmParameters parameters = AlgorithmParameters.getInstance("RSASSA-PSS"); + parameters.init(new PSSParameterSpec(digest, "MGF1", mgf, saltLength, 1)); + return parameters.getEncoded(); + } + + @Test + void pssUsesTheHashFromItsParameters() throws Exception { + String oid = "1.2.840.113549.1.1.10"; + assertEquals( + "SHA-384", + TlsChannelBinding.hashAlgorithmFor("RSASSA-PSS", oid, pss("SHA-384", MGF1ParameterSpec.SHA384, 48))); + assertEquals( + "SHA-512", + TlsChannelBinding.hashAlgorithmFor("RSASSA-PSS", oid, pss("SHA-512", MGF1ParameterSpec.SHA512, 64))); + assertEquals( + "SHA-256", + TlsChannelBinding.hashAlgorithmFor("RSASSA-PSS", oid, pss("SHA-256", MGF1ParameterSpec.SHA256, 32))); + // PSS with SHA-1 is upgraded like any SHA-1 signature. + assertEquals( + "SHA-256", + TlsChannelBinding.hashAlgorithmFor("RSASSA-PSS", oid, pss("SHA-1", MGF1ParameterSpec.SHA1, 20))); + } + + @Test + void namedSignaturesAreUnchanged() { + assertEquals("SHA-384", TlsChannelBinding.hashAlgorithmFor("SHA384withRSA", "1.2.840.113549.1.1.12", null)); + assertEquals("SHA-256", TlsChannelBinding.hashAlgorithmFor("SHA1withRSA", "1.2.840.113549.1.1.5", null)); + assertEquals( + "SHA-256", + TlsChannelBinding.hashAlgorithmFor("RSASSA-PSS", "1.2.840.113549.1.1.10", new byte[] {1, 2})); + } +} From 6cebef72bf8c53bab2cf4ed8091122a2da4c9ccd Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:23:40 +0000 Subject: [PATCH 104/150] fix(compat): classify logServerErrorDetail as emulated The compat driver implements logServerErrorDetail (read into the vendor settings, applied by ServerErrorRedaction), but the property table still classed it UNSUPPORTED, so every use logged a "not supported" warning and getPropertyInfo left it out. Class it EMULATED: honored by the driver, never forwarded to core. --- .../src/main/java/org/postgresql/PgPropertyMappings.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgPropertyMappings.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgPropertyMappings.java index de11efe6..26a41f74 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgPropertyMappings.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgPropertyMappings.java @@ -209,6 +209,8 @@ private static String mapReWriteBatchedInserts(String v) { // -- Emulated (synthesized by the Driver, not forwarded verbatim) -- emulated("readOnly"); + // Read into the connection's vendor settings and applied by ServerErrorRedaction. + emulated("logServerErrorDetail"); // -- Recognized but not yet supported (warn + drop) -- unsupported("readOnlyMode"); @@ -288,7 +290,6 @@ private static String mapReWriteBatchedInserts(String v) { // state and the decode context with it (ADR-0011). So our behavior is this property's `true` // setting, unconditionally, and setting it false would not be honored. unsupported("allowEncodingChanges"); - unsupported("logServerErrorDetail"); unsupported("loggerLevel"); unsupported("loggerFile"); unsupported("logUnclosedConnections"); From 37618c01aa24f4b711f7deb912c01d3b69ce3f43 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:23:40 +0000 Subject: [PATCH 105/150] test(compat): pin logServerErrorDetail as an emulated property --- .../src/test/java/org/postgresql/DriverTest.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java index 0dd1a71d..83ee5f9e 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java @@ -11,6 +11,7 @@ import java.net.URI; import java.net.URL; import java.sql.DriverManager; +import java.util.Arrays; import java.util.List; import java.util.Properties; import org.junit.jupiter.api.Test; @@ -247,6 +248,20 @@ void percentEncodedKeysAreDecoded() throws Exception { assertEquals("true", Driver.rawProperty(url, null, "readOnly")); } + @Test + void logServerErrorDetailIsEmulatedNotDropped() throws Exception { + // The compat driver honors it (ServerErrorRedaction), so it must not be classed unsupported, + // which warned on every use, and must not be forwarded to core as a startup parameter. + assertEquals( + PgPropertyMappings.Support.EMULATED, + PgPropertyMappings.get("logServerErrorDetail").support()); + Properties info = new Properties(); + info.setProperty("logServerErrorDetail", "false"); + assertEquals(0, Driver.translateProperties(info).size()); + assertTrue(Arrays.stream(new Driver().getPropertyInfo("jdbc:postgresql://h/db", null)) + .anyMatch(p -> p.name.equals("logServerErrorDetail"))); + } + @Test void urlWithoutQueryIsUnchanged() throws Exception { assertEquals("jdbc:postgresql://h/db", Driver.translateUrl("jdbc:postgresql://h/db")); From 80d1cb62c9137c128ee327c6d51820e70a3e95b6 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:23:51 +0000 Subject: [PATCH 106/150] docs: mark the logServerErrorDetail classification follow-up resolved --- docs/follow-up.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/follow-up.md b/docs/follow-up.md index 0deca51b..868feed8 100644 --- a/docs/follow-up.md +++ b/docs/follow-up.md @@ -638,7 +638,9 @@ surfaced two mapping-table inconsistencies in - **`logServerErrorDetail` is implemented but classified `unsupported`.** The behavior ships (`ServerErrorRedaction`, wired via `Driver.vendorSettings()` and consulted in `CompatStatements`), yet the mapping entry still emits a - misleading "not supported" WARN on every use. Reclassify it as mapped. + misleading "not supported" WARN on every use. **RESOLVED (2026-10-23):** + reclassified as emulated (6cebef72) -- not mapped, since forwarding it would + send it to the server as a startup parameter. - **`sslcrl` is warn-dropped though core accepts it.** Core's `ConnectionStringParser` and `SslMaterials` handle a CRL file, but `PgPropertyMappings` has no entry, so the property falls into the From 10dfbe0a1c30c63524819a2c8fda64347574c80d Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:24:55 +0000 Subject: [PATCH 107/150] fix(compat): warn when the duplicate-pgjdbc check cannot run The compat driver refuses to load when the real pgjdbc is also on the classpath (ADR-0015), by counting the org.postgresql.Driver class resources. When enumerating them threw IOException it returned an empty list, which read as "no duplicate", so the check was skipped without a word. Report "could not enumerate" separately and log a warning; startup still is not blocked on it. --- .../src/main/java/org/postgresql/Driver.java | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java index d350f4c4..0ad01955 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java @@ -14,6 +14,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -89,7 +90,15 @@ public Connection finishConnection(Connection nativeConnection, Properties pgjdb }); // Fail fast if the real pgjdbc is co-present (ADR-0015): two org.postgresql.Driver definitions // on one classpath have undefined resolution order, so no arbitration can make it safe. - requireSinglePostgresqlDriver(driverClassResources()); + Optional> definitions = driverClassResources(Driver.class.getClassLoader()); + if (definitions.isPresent()) { + requireSinglePostgresqlDriver(definitions.get()); + } else { + // Do not block startup on the safety check, but do not skip it silently either: a + // duplicate pgjdbc jar would now go undetected. + LOG.warn("pgjdbc compat: could not enumerate org.postgresql.Driver definitions on the classpath;" + + " the check for a co-present pgjdbc jar (ADR-0015) was skipped"); + } try { // The PSQLException factory is installed lazily on the first compat connection, NOT here: // it is a JVM-global that flattens the native driver's java.sql SQLException subtypes, so @@ -102,17 +111,17 @@ public Connection finishConnection(Connection nativeConnection, Properties pgjdb } /** The classpath URLs defining {@code org.postgresql.Driver}; {@code >1} means a duplicate jar. */ - private static List driverClassResources() { + static Optional> driverClassResources(ClassLoader loader) { List urls = new ArrayList<>(); try { - Enumeration found = Driver.class.getClassLoader().getResources("org/postgresql/Driver.class"); + Enumeration found = loader.getResources("org/postgresql/Driver.class"); while (found.hasMoreElements()) { urls.add(found.nextElement()); } } catch (IOException e) { - return List.of(); // cannot enumerate: do not block startup on the safety check + return Optional.empty(); // cannot enumerate; the caller says so } - return urls; + return Optional.of(urls); } /** From 017c971e62375b1091b62e05bf645e59b4e7c919 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:24:55 +0000 Subject: [PATCH 108/150] test(compat): pin the unreadable-classpath case of the duplicate check --- .../test/java/org/postgresql/DriverTest.java | 18 ++++++++++++++++++ .../postgresql/NativeImageMetadataTest.java | 2 +- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java index 83ee5f9e..19adfe41 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java @@ -8,10 +8,12 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.IOException; import java.net.URI; import java.net.URL; import java.sql.DriverManager; import java.util.Arrays; +import java.util.Enumeration; import java.util.List; import java.util.Properties; import org.junit.jupiter.api.Test; @@ -262,6 +264,22 @@ void logServerErrorDetailIsEmulatedNotDropped() throws Exception { .anyMatch(p -> p.name.equals("logServerErrorDetail"))); } + @Test + void anUnreadableClasspathIsReportedNotTakenAsClean() { + // An IOException from getResources used to read as "no duplicate", skipping the check silently. + ClassLoader failing = new ClassLoader(null) { + @Override + public Enumeration getResources(String name) throws IOException { + throw new IOException("unreadable classpath entry"); + } + }; + assertTrue(Driver.driverClassResources(failing).isEmpty()); + assertTrue(Driver.driverClassResources(Driver.class.getClassLoader()) + .orElseThrow() + .size() + >= 1); + } + @Test void urlWithoutQueryIsUnchanged() throws Exception { assertEquals("jdbc:postgresql://h/db", Driver.translateUrl("jdbc:postgresql://h/db")); diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/NativeImageMetadataTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/NativeImageMetadataTest.java index d893d987..38f95237 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/NativeImageMetadataTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/NativeImageMetadataTest.java @@ -46,7 +46,7 @@ void reflectConfigNamesTheCompatDriver() throws Exception { @Test void resourceConfigCoversTheDriverClassLookup() throws Exception { - // Driver.driverClassResources() enumerates this resource for the duplicate-jar check; a + // Driver.driverClassResources(ClassLoader) enumerates this resource for the duplicate-jar check; a // native image only sees classpath resources that are explicitly registered. String json = readResource(BASE + "resource-config.json"); assertTrue( From 62394bf4ae4d414cc4d7da08bb9cbf2c7c6eb4df Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:28:53 +0000 Subject: [PATCH 109/150] fix(core): read NegotiateProtocolVersion's version as a whole code The protocol documentation calls the field the newest minor version, but servers send the whole version code (3 << 16 | minor), as libpq reads it. The negotiation check added in 8a668935 compared that raw value with the requested minor, so every legitimate downgrade, 3.0 from a PostgreSQL 17 server asked for 3.2, was refused as "3.196608", and protocolVersion=latest stopped connecting to anything older than 18. (The code before it happened to work: building the version masked the major half away.) Split the field into major and minor, require major 3 and a minor below the one requested, and keep the code as sent. Unit tests missed it because the mock server sent a bare minor; it now sends what servers do. Checked with ProtocolVersionNegotiationIT on 17 and 18. --- .../protocol/message/NegotiateProtocolVersion.java | 4 +++- .../client/core/internal/StartupOrchestrator.java | 12 ++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/message/NegotiateProtocolVersion.java b/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/message/NegotiateProtocolVersion.java index 8ea8fb31..755d148d 100644 --- a/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/message/NegotiateProtocolVersion.java +++ b/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/message/NegotiateProtocolVersion.java @@ -14,7 +14,9 @@ *

    The driver uses this to fall back when it requested protocol 3.2 via * {@code protocolVersion=latest} (ADR-0004). * - * @param newestMinorVersion the newest minor protocol version the server supports + * @param newestMinorVersion the newest protocol version the server supports for the requested major + * version. The protocol documentation calls this the minor version, but servers send the whole + * version code ({@code major << 16 | minor}), so read it with {@code ProtocolConstants}. * @param unsupportedOptions names of requested protocol options the server did not * recognize, in order */ diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java index 43d80020..1174cb20 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java @@ -202,13 +202,17 @@ private int handleNegotiation(NegotiateProtocolVersion negotiate) { // A negotiation can only go down. Anything else is a broken or hostile peer claiming a // version we never offered, which would switch on protocol features the session never // agreed to; libpq refuses it the same way. + // The field is documented as the newest minor version, but servers send a whole version + // code (3 << 16 | minor), and libpq reads it as one. int offered = ProtocolConstants.protocolMinor(requestedVersionCode); - int minor = negotiate.newestMinorVersion(); - if (minor < 0 || minor >= offered) { - throw new PgConnectionException("invalid protocol negotiation: the server offered 3." + minor + int version = negotiate.newestMinorVersion(); + int major = ProtocolConstants.protocolMajor(version); + int minor = ProtocolConstants.protocolMinor(version); + if (major != 3 || minor >= offered) { + throw new PgConnectionException("invalid protocol negotiation: the server offered " + major + "." + minor + " in reply to a request for 3." + offered); } - return ProtocolConstants.protocolVersion(3, minor); + return version; } /** Rejects an authentication method the {@code require_auth} policy does not permit. */ From 5971ab6125377ca0a852aac25f3bb7977186940f Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Fri, 23 Oct 2026 16:28:53 +0000 Subject: [PATCH 110/150] test(core): send whole version codes from the mock NegotiateProtocolVersion --- .../postgresql/client/core/StartupOrchestratorTest.java | 9 +++++---- .../postgresql/client/core/transport/BackendWire.java | 9 ++++++++- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java index 05fb93be..3e04cfd1 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java @@ -170,19 +170,20 @@ void negotiateProtocolVersionAcceptedWhenLatest() { @Test void negotiationCanOnlyGoDown() { // The driver asks for 3.2 and sends no protocol options, so a reply naming 3.2 or above, or - // a negative minor, is not a negotiation the server could legitimately make. + // anything but major version 3, is not a negotiation the server could legitimately make. PgConnectionConfig latest = PgConnectionConfig.builder() .host("h") .user("app") .protocolVersionPolicy(ProtocolVersionPolicy.LATEST) .build(); - for (int minor : new int[] {2, 3, 99, -1}) { + // Whole version codes, as servers send them: 3.2, 3.3, 3.99, 4.0, and a bare minor 1. + for (int code : new int[] {ProtocolConstants.PROTOCOL_3_2, 196611, 196707, 4 << 16, 1, -1}) { MockServer server = new MockServer() .onStartup((s, frame) -> s.send( - BackendWire.negotiateProtocolVersion(minor), + BackendWire.negotiateProtocolVersionCode(code), BackendWire.authenticationOk(), BackendWire.readyForQuery('I'))); - assertThrows(PgConnectionException.class, () -> run(server, latest), "3." + minor); + assertThrows(PgConnectionException.class, () -> run(server, latest), Integer.toString(code)); } } diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/transport/BackendWire.java b/postgresql-client/src/test/java/org/postgresql/client/core/transport/BackendWire.java index 500bd3a8..1b25f0ac 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/transport/BackendWire.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/transport/BackendWire.java @@ -160,9 +160,16 @@ public static byte[] dataRow(String... textColumns) { return framed(MessageType.Backend.DATA_ROW, buf.toByteArray()); } + /** As a server sends it: the version field carries the whole code, 3 in the major half. */ public static byte[] negotiateProtocolVersion(int newestMinorVersion, String... unsupportedOptions) { + return negotiateProtocolVersionCode( + ProtocolConstants.protocolVersion(3, newestMinorVersion), unsupportedOptions); + } + + /** A NegotiateProtocolVersion carrying {@code versionCode} as is. */ + public static byte[] negotiateProtocolVersionCode(int versionCode, String... unsupportedOptions) { PgWriteBuffer buf = new PgWriteBuffer(); - buf.writeInt(newestMinorVersion); + buf.writeInt(versionCode); buf.writeInt(unsupportedOptions.length); for (String option : unsupportedOptions) { buf.writeCString(option); From 8b28f7008193b3c4c0b2a543275d39a4a8556fff Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:34:35 +0000 Subject: [PATCH 111/150] fix(core): qualify operators and functions in internal catalog queries pg_catalog has no exact oid = int4 or set_config(text, varchar, bool), so an exact match in any search_path schema won over it. --- .../postgresql/client/core/CoreConnection.java | 3 ++- .../org/postgresql/client/core/TypeCache.java | 18 ++++++++++++------ .../client/core/TypeCacheLookupTest.java | 2 +- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java b/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java index 90b86e91..94485ce8 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java @@ -1443,7 +1443,8 @@ public void setApplicationName(String applicationName) { // The resource is opened to be closed -- running the statement is the point, the rows are not. @SuppressWarnings("try") private void setConfig(String name, String value) { - try (PgResultStream ignored = execute("SELECT set_config('" + name + "', $1, false)", List.of(value))) { + try (PgResultStream ignored = + execute("SELECT pg_catalog.set_config('" + name + "', $1, false)", List.of(value))) { // value applied for the session } } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java b/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java index c44dc3e4..cdeb9acf 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java @@ -153,7 +153,12 @@ void clear() { /** The OID of {@code pg_type.typarray} for an element OID, or 0 when it has no array type. */ private int lookupArrayOid(int elementOid) { - String[] row = queryRow("SELECT typarray FROM pg_type WHERE oid = " + Integer.toUnsignedString(elementOid), 1); + // These queries qualify operators and functions: pg_catalog has no exact oid = int4, and the + // backend takes an exact match from any search_path schema over a pg_catalog one that casts. + String[] row = queryRow( + "SELECT typarray FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) " + + Integer.toUnsignedString(elementOid), + 1); if (row == null || row[0] == null) { return 0; } @@ -174,7 +179,7 @@ private int lookupOid(String typeName) { // once the session turned the setting off. Not bound as a parameter because this also // runs in SIMPLE query mode, which has none. String literal = "E'" + typeName.replace("\\", "\\\\").replace("'", "''") + "'"; - String[] row = queryRow("SELECT to_regtype(" + literal + ")::oid", 1); + String[] row = queryRow("SELECT pg_catalog.to_regtype(" + literal + ")::oid", 1); if (row == null || row[0] == null) { return 0; } @@ -243,7 +248,7 @@ private void queryAndRegister(int oid) { // so a decoded composite's name round-trips through the to_regtype bind lookup. String[] type = queryRow( "SELECT typtype, typbasetype, typrelid, typelem, typcategory, oid::regtype::text" - + " FROM pg_type WHERE oid = " + Integer.toUnsignedString(oid), + + " FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) " + Integer.toUnsignedString(oid), 6); if (type == null) { return; // unknown OID: leave the text/raw fallback in place @@ -289,9 +294,10 @@ private void registerArray(int oid, int elementOid) { private void registerComposite(int oid, String typeName, int relationOid) { List names = new ArrayList<>(); List fieldOids = new ArrayList<>(); - try (PgResultStream rs = connection.execute("SELECT attname, atttypid FROM pg_attribute WHERE attrelid = " - + Integer.toUnsignedString(relationOid) - + " AND attnum > 0 AND NOT attisdropped ORDER BY attnum")) { + try (PgResultStream rs = connection.execute( + "SELECT attname, atttypid FROM pg_catalog.pg_attribute WHERE attrelid OPERATOR(pg_catalog.=) " + + Integer.toUnsignedString(relationOid) + + " AND attnum > 0 AND NOT attisdropped ORDER BY attnum")) { while (rs.next()) { Row row = rs.currentRow(); names.add(requireColumn(row.getString(1), "pg_attribute.attname")); diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java index 6fb4407e..b57f3b9c 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java @@ -55,7 +55,7 @@ void typeNameIsSentAsAnEscapeStringLiteral() { // A quoted identifier may hold anything but a lone double quote, so the escaping still matters. assertNull(cache.resolveComposite("\"x\\' || NULL); DROP TABLE t; --\"")); - assertEquals(List.of("SELECT to_regtype(E'\"x\\\\'' || NULL); DROP TABLE t; --\"')::oid"), queries); + assertEquals(List.of("SELECT pg_catalog.to_regtype(E'\"x\\\\'' || NULL); DROP TABLE t; --\"')::oid"), queries); } @Test From 12d5c18e8b50ed3363b7bf4e28fb2333ca954134 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:35:59 +0000 Subject: [PATCH 112/150] test(core): pin catalog queries against search_path shadowing --- .../client/core/it/SearchPathShadowingIT.java | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/it/SearchPathShadowingIT.java diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/it/SearchPathShadowingIT.java b/postgresql-client/src/test/java/org/postgresql/client/core/it/SearchPathShadowingIT.java new file mode 100644 index 00000000..cbfddf62 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/it/SearchPathShadowingIT.java @@ -0,0 +1,72 @@ +package org.postgresql.client.core.it; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.postgresql.client.core.PgComposite; +import org.postgresql.client.core.PgConnection; +import org.postgresql.client.core.PgConnections; +import org.postgresql.client.core.PgResultStream; + +/** + * The driver's own catalog queries must not run an operator or function that a search_path schema + * supplies with an exact signature match pg_catalog lacks. Each shadowing object raises, so a + * query that resolved to it fails the test. + */ +@Timeout(60) +class SearchPathShadowingIT extends AbstractPostgresIT { + + private static PgConnection shadowedConnection(String schema) { + PgConnection c = PgConnections.connect(connectionConfig().build()); + c.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE").close(); + c.execute("CREATE SCHEMA " + schema).close(); + c.execute("SET search_path = " + schema + ", public").close(); + c.execute("CREATE FUNCTION " + schema + ".shadow_eq(oid, int4) RETURNS bool LANGUAGE plpgsql" + + " AS $$BEGIN RAISE EXCEPTION 'shadowing operator ran'; END$$") + .close(); + c.execute("CREATE OPERATOR " + schema + ".= (LEFTARG = oid, RIGHTARG = int4, FUNCTION = " + schema + + ".shadow_eq)") + .close(); + c.execute("CREATE FUNCTION " + schema + ".set_config(text, varchar, bool) RETURNS text" + + " LANGUAGE plpgsql AS $$BEGIN RAISE EXCEPTION 'shadowing function ran'; END$$") + .close(); + return c; + } + + private static int typeOid(PgConnection c, String typeName) { + try (PgResultStream rs = c.execute("SELECT '" + typeName + "'::regtype::oid")) { + assertTrue(rs.next(), "expected one row"); + return rs.currentRow().getLong(1).intValue(); + } + } + + @Test + void typeLookupsUsePgCatalogOperators() { + try (PgConnection c = shadowedConnection("shadow_types")) { + c.execute("CREATE TYPE shadow_mood AS ENUM ('sad', 'ok')").close(); + c.execute("CREATE TYPE shadow_pt AS (x int4, y int4)").close(); + + c.resolveType(typeOid(c, "shadow_mood")); + c.resolveType(typeOid(c, "shadow_pt")); + List points = List.of(new PgComposite("shadow_pt", List.of(1, 2))); + try (PgResultStream rs = c.execute("SELECT cardinality($1::shadow_pt[])", List.of(points))) { + assertTrue(rs.next(), "expected one row"); + assertEquals(1, rs.currentRow().getInt(1)); + } + } + } + + @Test + void setApplicationNameUsesPgCatalogSetConfig() { + try (PgConnection c = shadowedConnection("shadow_config")) { + c.setApplicationName("shadow-test"); + try (PgResultStream rs = c.execute("SHOW application_name")) { + assertTrue(rs.next(), "expected one row"); + assertEquals("shadow-test", rs.currentRow().getString(1)); + } + } + } +} From 33cce6ebce1aefad3f3ad35f347aba9f0fce119e Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:39:30 +0000 Subject: [PATCH 113/150] fix(jdbc): qualify operators and functions in catalog queries Same search_path shadowing as the core fix: name LIKE varchar, name = varchar, oid = int4, oid = regclass and regproc <> regproc have no exact match in pg_catalog. --- .../client/jdbc/CatalogLookups.java | 6 +- .../postgresql/client/jdbc/PgConnection.java | 2 +- .../client/jdbc/PgDatabaseMetaData.java | 67 ++++++++++--------- .../postgresql/client/jdbc/PgXAResource.java | 4 +- .../jdbc/UpdatableResultSetSupport.java | 2 +- 5 files changed, 42 insertions(+), 39 deletions(-) diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CatalogLookups.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CatalogLookups.java index 8904fed6..9fc82fc6 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CatalogLookups.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CatalogLookups.java @@ -40,7 +40,7 @@ static SourceColumn sourceColumn(Connection connection, int tableOid, int attrib + " OR COALESCE(pg_catalog.pg_get_expr(d.adbin, d.adrelid), '') LIKE 'nextval(%'" + " FROM pg_catalog.pg_attribute a" + " LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum" - + " WHERE a.attrelid = ? AND a.attnum = ?"; + + " WHERE a.attrelid OPERATOR(pg_catalog.=) ? AND a.attnum = ?"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, tableOid); ps.setInt(2, attributeNumber); @@ -72,7 +72,7 @@ record CatalogType(String name, char typtype, boolean isArray, int elementOid, c static CatalogType catalogType(Connection connection, int typeOid) throws SQLException { String sql = "SELECT t.typname, t.typtype, t.typcategory, t.typelem," + " COALESCE(e.typdelim, ',') FROM pg_catalog.pg_type t" - + " LEFT JOIN pg_catalog.pg_type e ON e.oid = t.typelem WHERE t.oid = ?"; + + " LEFT JOIN pg_catalog.pg_type e ON e.oid = t.typelem WHERE t.oid OPERATOR(pg_catalog.=) ?"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, typeOid); try (ResultSet rs = ps.executeQuery()) { @@ -98,7 +98,7 @@ static CatalogType catalogType(Connection connection, int typeOid) throws SQLExc */ static String[] tableName(Connection connection, int tableOid) throws SQLException { String sql = "SELECT n.nspname, c.relname FROM pg_catalog.pg_class c" - + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.oid = ?"; + + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.oid OPERATOR(pg_catalog.=) ?"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, tableOid); try (ResultSet rs = ps.executeQuery()) { diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgConnection.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgConnection.java index 337c4208..d815b906 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgConnection.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgConnection.java @@ -534,7 +534,7 @@ public void setSchema(String schema) throws SQLException { @Override public String getSchema() throws SQLException { checkOpen(); - try (PgResultStream stream = core.execute("select current_schema()")) { + try (PgResultStream stream = core.execute("select pg_catalog.current_schema()")) { return stream.next() ? stream.currentRow().getString(1) : null; } catch (RuntimeException e) { throw PgSqlExceptions.wrap(e); diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDatabaseMetaData.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDatabaseMetaData.java index 28a5393b..d5515a70 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDatabaseMetaData.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDatabaseMetaData.java @@ -895,10 +895,13 @@ private String catalogName() { @Override public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException { + // Operators with no exact pg_catalog match for their argument types (name LIKE varchar, + // oid = int4, ...) are written OPERATOR(pg_catalog.op): otherwise an exact match from any + // search_path schema would win. String sql = "SELECT n.nspname AS schem, c.relname AS name, c.relkind AS kind, " + "pg_catalog.obj_description(c.oid, 'pg_class') AS remarks " + "FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " - + "WHERE c.relkind IN ('r','p','v','m','f','i','I','S','c') AND n.nspname LIKE ? AND c.relname LIKE ? " + + "WHERE c.relkind IN ('r','p','v','m','f','i','I','S','c') AND n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.~~) ? " + "ORDER BY c.relkind, n.nspname, c.relname"; List wanted = types == null ? null : List.of(types); List rows = new ArrayList<>(); @@ -972,7 +975,7 @@ public ResultSet getColumns(String catalog, String schemaPattern, String tableNa String identityExpr = major >= 10 ? "a.attidentity" : "''"; String generatedExpr = major >= 12 ? "a.attgenerated" : "''"; String sql = "SELECT n.nspname AS schem, c.relname AS tbl, a.attname AS col, a.atttypid AS typid, " - + "row_number() OVER (PARTITION BY c.oid ORDER BY a.attnum) AS ord, " + + "pg_catalog.row_number() OVER (PARTITION BY c.oid ORDER BY a.attnum) AS ord, " + "a.attnotnull AS notnull, a.atttypmod AS typmod, " + "t.typtype AS typtype, t.typbasetype AS basetype, t.typtypmod AS domtypmod, " + "t.typnotnull AS domnotnull, " @@ -985,13 +988,13 @@ public ResultSet getColumns(String catalog, String schemaPattern, String tableNa + "JOIN pg_catalog.pg_type t ON t.oid = a.atttypid " + "LEFT JOIN pg_catalog.pg_attrdef ad ON ad.adrelid = c.oid AND ad.adnum = a.attnum " + "WHERE a.attnum > 0 AND NOT a.attisdropped AND c.relkind IN ('r','p','v','m','f') " - + "AND n.nspname LIKE ? AND c.relname LIKE ? " + + "AND n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.~~) ? " + "ORDER BY n.nspname, c.relname, a.attnum"; // ORDINAL_POSITION renumbers over the table's live columns; the column-name filter must // not affect it, so it applies outside the window (getColumns(..., "quest") still reports // the column's real ordinal). sql = "SELECT * FROM (" + sql.replace(" ORDER BY n.nspname, c.relname, a.attnum", "") + ") cols " - + "WHERE cols.col LIKE ? ORDER BY cols.schem, cols.tbl, cols.ord"; + + "WHERE cols.col OPERATOR(pg_catalog.~~) ? ORDER BY cols.schem, cols.tbl, cols.ord"; List rows = !catalogSelects(catalog) ? List.of() : query( @@ -1124,7 +1127,7 @@ public ResultSet getSchemas() throws SQLException { @Override public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException { String sql = "SELECT nspname AS schem FROM pg_catalog.pg_namespace " - + "WHERE nspname LIKE ? AND nspname NOT LIKE 'pg\\_toast%' AND nspname NOT LIKE 'pg\\_temp%' " + + "WHERE nspname OPERATOR(pg_catalog.~~) ? AND nspname OPERATOR(pg_catalog.!~~) 'pg\\_toast%' AND nspname OPERATOR(pg_catalog.!~~) 'pg\\_temp%' " + "ORDER BY nspname"; List rows = !catalogSelects(catalog) ? List.of() @@ -1212,7 +1215,7 @@ public ResultSet getPrimaryKeys(String catalog, String schema, String table) thr + "JOIN pg_catalog.pg_class ci ON ci.oid = ix.indexrelid " + "JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " + "JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attnum = " + INDKEY_ATTNUM + " " - + "WHERE ix.indisprimary AND n.nspname LIKE ? AND c.relname = ? " + + "WHERE ix.indisprimary AND n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.=) ? " + keyOnly + "ORDER BY a.attname"; List rows = !catalogSelects(catalog) @@ -1231,7 +1234,7 @@ public ResultSet getPrimaryKeys(String catalog, String schema, String table) thr @Override public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { return foreignKeys( - "fc.relname = ? AND fn.nspname LIKE ?", + "fc.relname OPERATOR(pg_catalog.=) ? AND fn.nspname OPERATOR(pg_catalog.~~) ?", List.of(nullToEmpty(table), pattern(schema)), // The constraint name before the ordinal keeps multiple foreign keys to the same // parent contiguous (KEY_SEQ restarts per FK_NAME), as pgjdbc orders them. @@ -1241,7 +1244,7 @@ public ResultSet getImportedKeys(String catalog, String schema, String table) th @Override public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { return foreignKeys( - "pc.relname = ? AND pn.nspname LIKE ?", + "pc.relname OPERATOR(pg_catalog.=) ? AND pn.nspname OPERATOR(pg_catalog.~~) ?", List.of(nullToEmpty(table), pattern(schema)), "fn.nspname, fc.relname, con.conname, seq"); } @@ -1256,7 +1259,7 @@ public ResultSet getCrossReference( String foreignTable) throws SQLException { return foreignKeys( - "pc.relname = ? AND pn.nspname LIKE ? AND fc.relname = ? AND fn.nspname LIKE ?", + "pc.relname OPERATOR(pg_catalog.=) ? AND pn.nspname OPERATOR(pg_catalog.~~) ? AND fc.relname OPERATOR(pg_catalog.=) ? AND fn.nspname OPERATOR(pg_catalog.~~) ?", List.of( nullToEmpty(parentTable), pattern(parentSchema), @@ -1275,8 +1278,8 @@ private ResultSet foreignKeys(String where, List params, String orderBy) // subquery, not a LATERAL join, so this runs on pre-9.3 servers too. + "(SELECT ic.relname FROM pg_catalog.pg_depend dep " + "JOIN pg_catalog.pg_class ic ON ic.oid = dep.refobjid AND ic.relkind = 'i' " - + "WHERE dep.classid = 'pg_constraint'::regclass AND dep.objid = con.oid " - + "AND dep.refclassid = 'pg_class'::regclass AND dep.deptype = 'n' LIMIT 1) AS pkname, " + + "WHERE dep.classid OPERATOR(pg_catalog.=) 'pg_catalog.pg_constraint'::regclass AND dep.objid = con.oid " + + "AND dep.refclassid OPERATOR(pg_catalog.=) 'pg_catalog.pg_class'::regclass AND dep.deptype = 'n' LIMIT 1) AS pkname, " + "con.condeferrable AS deferrable, con.condeferred AS deferred " // Columns listed explicitly rather than `c.*`: before PostgreSQL 12 `oid` was a hidden // system column that a wildcard does not expand to, and the PK_NAME subquery needs it. @@ -1373,7 +1376,7 @@ public ResultSet getIndexInfo(String catalog, String schema, String table, boole + "JOIN pg_catalog.pg_class ci ON ci.oid = ix.indexrelid " + "JOIN pg_catalog.pg_namespace n ON n.oid = ct.relnamespace " + "LEFT JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.oid AND a.attnum = " + INDKEY_ATTNUM + " " - + "WHERE n.nspname LIKE ? AND ct.relname = ? AND (NOT ? OR ix.indisunique) " + + "WHERE n.nspname OPERATOR(pg_catalog.~~) ? AND ct.relname OPERATOR(pg_catalog.=) ? AND (NOT ? OR ix.indisunique) " + "ORDER BY nonuniq, ci.relname, " + INDKEY_ORD; List rows = query(sql, List.of(pattern(schema), nullToEmpty(table), unique), rs -> new Object[] { catalogName(), @@ -1417,8 +1420,8 @@ public ResultSet getTypeInfo() throws SQLException { // static tables know keep their JDBC type code; the rest report OTHER. String sql = "SELECT t.typname AS name, t.oid AS oid FROM pg_catalog.pg_type t " + "JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace " - + "WHERE t.typtype IN ('b','e') AND n.nspname NOT LIKE 'pg\\_toast%' " - + "AND t.typinput <> 'pg_catalog.array_in'::regproc " + + "WHERE t.typtype IN ('b','e') AND n.nspname OPERATOR(pg_catalog.!~~) 'pg\\_toast%' " + + "AND t.typinput OPERATOR(pg_catalog.<>) 'pg_catalog.array_in'::regproc " + "ORDER BY t.typname"; List rows = query(sql, List.of(), rs -> { int oid = rs.getInt("oid"); @@ -1476,9 +1479,9 @@ public ResultSet getProcedures(String catalog, String schemaPattern, String proc String sql = "SELECT n.nspname AS schem, p.proname AS name, p.oid AS oid, " + "pg_catalog.obj_description(p.oid, 'pg_proc') AS remarks " + "FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace " - + "WHERE p.prokind = 'p' AND n.nspname LIKE ? AND p.proname LIKE ? " + + "WHERE p.prokind = 'p' AND n.nspname OPERATOR(pg_catalog.~~) ? AND p.proname OPERATOR(pg_catalog.~~) ? " // SPECIFIC_NAME is proname_oid; JDBC orders by it as text, so sort the same way. - + "ORDER BY n.nspname, p.proname, p.proname || '_' || p.oid"; + + "ORDER BY n.nspname, p.proname, p.proname OPERATOR(pg_catalog.||) '_' OPERATOR(pg_catalog.||) p.oid"; List rows = !catalogSelects(catalog) ? List.of() : query(sql, List.of(pattern(schemaPattern), pattern(procedureNamePattern)), rs -> new Object[] { @@ -1519,7 +1522,7 @@ public ResultSet getProcedureColumns( + "p.proargnames::text AS argnames " + "FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace " + "JOIN pg_catalog.pg_type t ON t.oid = p.prorettype " - + "WHERE n.nspname LIKE ? AND p.proname LIKE ? " + + "WHERE n.nspname OPERATOR(pg_catalog.~~) ? AND p.proname OPERATOR(pg_catalog.~~) ? " + "ORDER BY n.nspname, p.proname, p.oid"; List rows = new ArrayList<>(); if (!catalogSelects(catalog)) { @@ -1647,7 +1650,7 @@ private Object[] procedureColumnRow( private List compositeAttributes(int relid) throws SQLException { return query( "SELECT a.attname AS nm, a.atttypid AS tid FROM pg_catalog.pg_attribute a " - + "WHERE a.attrelid = ? AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum", + + "WHERE a.attrelid OPERATOR(pg_catalog.=) ? AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum", List.of(relid), rs -> new Object[] {rs.getString("nm"), rs.getInt("tid")}); } @@ -1723,9 +1726,9 @@ public ResultSet getFunctions(String catalog, String schemaPattern, String funct String sql = "SELECT n.nspname AS schem, p.proname AS name, p.oid AS oid, p.proretset AS retset, " + "pg_catalog.obj_description(p.oid, 'pg_proc') AS remarks " + "FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace " - + "WHERE p.prokind IN ('f','a','w') AND n.nspname LIKE ? AND p.proname LIKE ? " + + "WHERE p.prokind IN ('f','a','w') AND n.nspname OPERATOR(pg_catalog.~~) ? AND p.proname OPERATOR(pg_catalog.~~) ? " // SPECIFIC_NAME is proname_oid; JDBC orders by it as text, so sort the same way. - + "ORDER BY n.nspname, p.proname, p.proname || '_' || p.oid"; + + "ORDER BY n.nspname, p.proname, p.proname OPERATOR(pg_catalog.||) '_' OPERATOR(pg_catalog.||) p.oid"; List rows = !catalogSelects(catalog) ? List.of() : query(sql, List.of(pattern(schemaPattern), pattern(functionNamePattern)), rs -> new Object[] { @@ -1753,7 +1756,7 @@ public ResultSet getFunctionColumns( + "p.proargnames::text AS argnames " + "FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace " + "JOIN pg_catalog.pg_type t ON t.oid = p.prorettype " - + "WHERE n.nspname LIKE ? AND p.proname LIKE ? " + + "WHERE n.nspname OPERATOR(pg_catalog.~~) ? AND p.proname OPERATOR(pg_catalog.~~) ? " + "ORDER BY n.nspname, p.proname, p.oid"; List rows = new ArrayList<>(); if (!catalogSelects(catalog)) { @@ -1871,14 +1874,14 @@ public ResultSet getColumnPrivileges(String catalog, String schema, String table // grants (acldefault). One row per (column, grantee, privilege); grantee 0 is PUBLIC. String sql = "SELECT n.nspname AS schem, c.relname AS tbl, a.attname AS col, " + "pg_catalog.pg_get_userbyid(g.grantor) AS grantor, " - + "CASE WHEN g.grantee = 0 THEN 'PUBLIC' ELSE pg_catalog.pg_get_userbyid(g.grantee) END AS grantee, " + + "CASE WHEN g.grantee OPERATOR(pg_catalog.=) 0 THEN 'PUBLIC' ELSE pg_catalog.pg_get_userbyid(g.grantee) END AS grantee, " + "g.privilege_type AS priv, " + "CASE WHEN g.is_grantable THEN 'YES' ELSE 'NO' END AS grantable " + "FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " + "JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped " + "CROSS JOIN LATERAL " - + "aclexplode(COALESCE(a.attacl, c.relacl, pg_catalog.acldefault('r'::\"char\", c.relowner))) g " - + "WHERE n.nspname LIKE ? AND c.relname = ? AND a.attname LIKE ? " + + "pg_catalog.aclexplode(COALESCE(a.attacl, c.relacl, pg_catalog.acldefault('r'::\"char\", c.relowner))) g " + + "WHERE n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.=) ? AND a.attname OPERATOR(pg_catalog.~~) ? " + "AND g.privilege_type IN ('SELECT','INSERT','UPDATE','REFERENCES') " + "ORDER BY a.attname, g.privilege_type"; List rows = !catalogSelects(catalog) @@ -1917,13 +1920,13 @@ public ResultSet getTablePrivileges(String catalog, String schemaPattern, String // privilege name; grantee 0 is PUBLIC. String sql = "SELECT n.nspname AS schem, c.relname AS tbl, " + "pg_catalog.pg_get_userbyid(g.grantor) AS grantor, " - + "CASE WHEN g.grantee = 0 THEN 'PUBLIC' ELSE pg_catalog.pg_get_userbyid(g.grantee) END AS grantee, " + + "CASE WHEN g.grantee OPERATOR(pg_catalog.=) 0 THEN 'PUBLIC' ELSE pg_catalog.pg_get_userbyid(g.grantee) END AS grantee, " + "g.privilege_type AS priv, " + "CASE WHEN g.is_grantable THEN 'YES' ELSE 'NO' END AS grantable " + "FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " + "CROSS JOIN LATERAL " - + "aclexplode(COALESCE(c.relacl, pg_catalog.acldefault('r'::\"char\", c.relowner))) g " - + "WHERE c.relkind IN ('r','p','v','m','f') AND n.nspname LIKE ? AND c.relname LIKE ? " + + "pg_catalog.aclexplode(COALESCE(c.relacl, pg_catalog.acldefault('r'::\"char\", c.relowner))) g " + + "WHERE c.relkind IN ('r','p','v','m','f') AND n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.~~) ? " + "ORDER BY n.nspname, c.relname, g.privilege_type"; List rows = query(sql, List.of(pattern(schemaPattern), pattern(tableNamePattern)), rs -> new Object[] { @@ -1954,7 +1957,7 @@ public ResultSet getBestRowIdentifier(String catalog, String schema, String tabl + "JOIN pg_catalog.pg_class c ON c.oid = ix.indrelid " + "JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " + "JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attnum = " + INDKEY_ATTNUM + " " - + "WHERE ix.indisprimary AND n.nspname LIKE ? AND c.relname = ? " + + "WHERE ix.indisprimary AND n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.=) ? " + "ORDER BY " + INDKEY_ORD; rows = query(sql, List.of(pattern(schema), table == null ? "" : table), rs -> { int oid = rs.getInt("tid"); @@ -2032,7 +2035,7 @@ public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePa String sql = "SELECT n.nspname AS schem, t.typname AS name, t.typtype AS kind, t.typbasetype AS basetype, " + "pg_catalog.obj_description(t.oid, 'pg_type') AS remarks " + "FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace " - + "WHERE t.typtype IN ('c','d','e') AND n.nspname LIKE ? AND t.typname LIKE ? " + + "WHERE t.typtype IN ('c','d','e') AND n.nspname OPERATOR(pg_catalog.~~) ? AND t.typname OPERATOR(pg_catalog.~~) ? " + "ORDER BY n.nspname, t.typname"; List rows = new ArrayList<>(); List found = !catalogSelects(catalog) @@ -2101,7 +2104,7 @@ public ResultSet getAttributes( // throwing and an empty result. String sql = "SELECT n.nspname AS schem, t.typname AS tname, a.attname AS aname, " + "a.atttypid AS typid, a.atttypmod AS typmod, a.attnotnull AS notnull, " - + "row_number() OVER (PARTITION BY c.oid ORDER BY a.attnum) AS ord, " + + "pg_catalog.row_number() OVER (PARTITION BY c.oid ORDER BY a.attnum) AS ord, " + "pg_catalog.pg_get_expr(ad.adbin, ad.adrelid) AS def, " + "pg_catalog.col_description(c.oid, a.attnum) AS remarks " + "FROM pg_catalog.pg_type t " @@ -2111,10 +2114,10 @@ public ResultSet getAttributes( + "AND NOT a.attisdropped " + "LEFT JOIN pg_catalog.pg_attrdef ad ON ad.adrelid = c.oid AND ad.adnum = a.attnum " + "WHERE t.typtype = 'c' AND c.relkind = 'c' " - + "AND n.nspname LIKE ? AND t.typname LIKE ?"; + + "AND n.nspname OPERATOR(pg_catalog.~~) ? AND t.typname OPERATOR(pg_catalog.~~) ?"; // The attribute-name filter applies outside the window so it cannot renumber // ORDINAL_POSITION, the same way getColumns keeps a column's real ordinal. - sql = "SELECT * FROM (" + sql + ") attrs WHERE attrs.aname LIKE ? " + sql = "SELECT * FROM (" + sql + ") attrs WHERE attrs.aname OPERATOR(pg_catalog.~~) ? " + "ORDER BY attrs.schem, attrs.tname, attrs.ord"; List rows = !catalogSelects(catalog) ? List.of() diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgXAResource.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgXAResource.java index 69e5246f..8bac0f13 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgXAResource.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgXAResource.java @@ -135,8 +135,8 @@ public Xid[] recover(int flag) throws XAException { } List xids = new ArrayList<>(); try (Statement st = connection.createStatement(); - ResultSet rs = - st.executeQuery("SELECT gid FROM pg_prepared_xacts WHERE database = current_database()")) { + ResultSet rs = st.executeQuery( + "SELECT gid FROM pg_catalog.pg_prepared_xacts WHERE database = pg_catalog.current_database()")) { while (rs.next()) { Xid xid = decode(rs.getString(1)); if (xid != null) { diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/UpdatableResultSetSupport.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/UpdatableResultSetSupport.java index 21097ea7..6788f7d8 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/UpdatableResultSetSupport.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/UpdatableResultSetSupport.java @@ -112,7 +112,7 @@ private static void lookupColumns( + " FROM pg_catalog.pg_attribute a" + " LEFT JOIN pg_catalog.pg_index i" + " ON i.indrelid = a.attrelid AND i.indisprimary AND a.attnum = ANY(i.indkey)" - + " WHERE a.attrelid = ? AND a.attnum > 0 AND NOT a.attisdropped" + + " WHERE a.attrelid OPERATOR(pg_catalog.=) ? AND a.attnum > 0 AND NOT a.attisdropped" + " ORDER BY a.attnum"; try (java.sql.PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, tableOid); From b7c54fda2a91e59c919c07e4008e9cee3ffcf329 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:40:48 +0000 Subject: [PATCH 114/150] test(jdbc): pin metadata queries against search_path shadowing --- .../client/jdbc/it/SearchPathShadowingIT.java | 126 ++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/SearchPathShadowingIT.java diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/SearchPathShadowingIT.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/SearchPathShadowingIT.java new file mode 100644 index 00000000..50d919a9 --- /dev/null +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/SearchPathShadowingIT.java @@ -0,0 +1,126 @@ +package org.postgresql.client.jdbc.it; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import org.junit.jupiter.api.Test; + +/** + * DatabaseMetaData, ResultSetMetaData and updatable result sets must not run an operator that a + * search_path schema supplies with an exact signature match pg_catalog lacks. Each shadowing + * operator raises, so a catalog query that resolved to one fails the test. + */ +class SearchPathShadowingIT extends AbstractJdbcPostgresIT { + + private static final String SCHEMA = "shadow_jdbc"; + + /** Left type, right type and operator of each shadowed signature. */ + private static final String[][] SHADOWED = { + {"name", "varchar", "~~"}, + {"name", "name", "!~~"}, + {"name", "varchar", "="}, + {"oid", "int4", "="}, + {"oid", "regclass", "="}, + {"regproc", "regproc", "<>"}, + {"name", "name", "||"}, + }; + + private static void exec(Connection con, String sql) throws SQLException { + try (Statement st = con.createStatement()) { + st.execute(sql); + } + } + + private static int drain(ResultSet rs) throws SQLException { + try (rs) { + int rows = 0; + while (rs.next()) { + rows++; + } + return rows; + } + } + + private static Connection shadowedConnection() throws SQLException { + Connection con = connect(); + exec(con, "DROP SCHEMA IF EXISTS " + SCHEMA + " CASCADE"); + exec(con, "CREATE SCHEMA " + SCHEMA); + exec(con, "SET search_path = " + SCHEMA + ", public"); + exec(con, "CREATE TABLE sh_parent (id int4 PRIMARY KEY, label text)"); + exec(con, "CREATE TABLE sh_child (id serial PRIMARY KEY, parent int4 REFERENCES sh_parent)"); + exec(con, "CREATE INDEX sh_child_parent ON sh_child (parent)"); + exec(con, "CREATE TYPE sh_pair AS (a int4, b text)"); + exec(con, "CREATE FUNCTION sh_fn(x int4) RETURNS sh_pair LANGUAGE sql AS $$SELECT x, 'v'::text$$"); + exec(con, "INSERT INTO sh_parent VALUES (1, 'one')"); + for (int i = 0; i < SHADOWED.length; i++) { + String[] s = SHADOWED[i]; + String fn = SCHEMA + ".shadow_" + i; + String returns = "||".equals(s[2]) ? "text" : "bool"; + exec( + con, + "CREATE FUNCTION " + fn + "(" + s[0] + ", " + s[1] + ") RETURNS " + returns + + " LANGUAGE plpgsql AS $$BEGIN RAISE EXCEPTION 'shadowing operator " + s[2] + + " ran'; END$$"); + exec( + con, + "CREATE OPERATOR " + SCHEMA + "." + s[2] + " (LEFTARG = " + s[0] + ", RIGHTARG = " + s[1] + + ", FUNCTION = " + fn + ")"); + } + return con; + } + + @Test + void databaseMetaDataUsesPgCatalogOperators() throws SQLException { + try (Connection con = shadowedConnection()) { + DatabaseMetaData md = con.getMetaData(); + assertTrue(drain(md.getTables(null, SCHEMA, "sh_%", null)) >= 2); + assertTrue(drain(md.getColumns(null, SCHEMA, "sh_parent", "%")) >= 2); + assertTrue(drain(md.getSchemas(null, SCHEMA)) >= 1); + assertEquals(1, drain(md.getPrimaryKeys(null, SCHEMA, "sh_parent"))); + assertEquals(1, drain(md.getImportedKeys(null, SCHEMA, "sh_child"))); + assertEquals(1, drain(md.getExportedKeys(null, SCHEMA, "sh_parent"))); + assertEquals(1, drain(md.getCrossReference(null, SCHEMA, "sh_parent", null, SCHEMA, "sh_child"))); + assertTrue(drain(md.getIndexInfo(null, SCHEMA, "sh_child", false, false)) >= 2); + assertTrue(drain(md.getBestRowIdentifier(null, SCHEMA, "sh_parent", 0, false)) >= 1); + assertTrue(drain(md.getTypeInfo()) > 0); + assertTrue(drain(md.getFunctions(null, SCHEMA, "sh_fn")) >= 1); + assertTrue(drain(md.getFunctionColumns(null, SCHEMA, "sh_fn", "%")) >= 1); + drain(md.getProcedures(null, SCHEMA, "%")); + assertTrue(drain(md.getProcedureColumns(null, SCHEMA, "sh_fn", "%")) >= 1); + drain(md.getColumnPrivileges(null, SCHEMA, "sh_parent", "%")); + drain(md.getTablePrivileges(null, SCHEMA, "sh_%")); + assertTrue(drain(md.getUDTs(null, SCHEMA, "sh_%", null)) >= 1); + assertEquals(2, drain(md.getAttributes(null, SCHEMA, "sh_pair", "%"))); + } + } + + @Test + void resultSetMetaDataUsesPgCatalogOperators() throws SQLException { + try (Connection con = shadowedConnection(); + Statement st = con.createStatement(); + ResultSet rs = st.executeQuery("SELECT id, label FROM sh_parent")) { + ResultSetMetaData md = rs.getMetaData(); + assertEquals("sh_parent", md.getTableName(1)); + assertEquals(SCHEMA, md.getSchemaName(1)); + md.isAutoIncrement(1); + md.isNullable(2); + } + } + + @Test + void updatableResultSetUsesPgCatalogOperators() throws SQLException { + try (Connection con = shadowedConnection(); + Statement st = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); + ResultSet rs = st.executeQuery("SELECT id, label FROM sh_parent")) { + assertTrue(rs.next()); + rs.updateString("label", "uno"); + rs.updateRow(); + } + } +} From df7a4ffff3f97b98863aa3ebe835c140ce12015f Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:42:25 +0000 Subject: [PATCH 115/150] fix(compat): qualify operators in catalog queries Same search_path shadowing of oid = int4 as the core and jdbc fixes. --- .../src/main/java/org/postgresql/PgResultSets.java | 3 ++- .../org/postgresql/client/compat/internal/CompatTypeInfo.java | 4 ++-- .../org/postgresql/client/compat/internal/HstoreSupport.java | 4 ++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgResultSets.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgResultSets.java index 706db12e..725ee278 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgResultSets.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgResultSets.java @@ -335,7 +335,8 @@ private String baseColumnName(int column) throws SQLException { } private String lookupBaseColumnName(int tableOid, int attributeNumber) { - String sql = "SELECT attname FROM pg_catalog.pg_attribute WHERE attrelid = ? AND attnum = ?"; + String sql = + "SELECT attname FROM pg_catalog.pg_attribute WHERE attrelid OPERATOR(pg_catalog.=) ? AND attnum = ?"; try (PreparedStatement statement = connection.prepareStatement(sql)) { statement.setInt(1, tableOid); statement.setInt(2, attributeNumber); diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatTypeInfo.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatTypeInfo.java index 42f12431..f7a7fe30 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatTypeInfo.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatTypeInfo.java @@ -193,8 +193,8 @@ private int lookupOid(String name) throws SQLException { } private String lookupName(int oid) throws SQLException { - try (PreparedStatement statement = - connection.prepareStatement("SELECT typname FROM pg_catalog.pg_type WHERE oid = ?")) { + try (PreparedStatement statement = connection.prepareStatement( + "SELECT typname FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) ?")) { statement.setInt(1, oid); try (ResultSet rows = statement.executeQuery()) { return rows.next() ? rows.getString(1) : null; diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/HstoreSupport.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/HstoreSupport.java index 146ee0c0..adcfedd8 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/HstoreSupport.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/HstoreSupport.java @@ -146,8 +146,8 @@ public DynamicType typeForOid(int oid) { if (types.containsKey(oid)) { return types.get(oid); } - try (java.sql.PreparedStatement ps = - connection.prepareStatement("SELECT typname, typtype FROM pg_type WHERE oid = ?")) { + try (java.sql.PreparedStatement ps = connection.prepareStatement( + "SELECT typname, typtype FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) ?")) { ps.setInt(1, oid); try (ResultSet rs = ps.executeQuery()) { DynamicType type = rs.next() From b74e1ab89e476c42a356d17be89679952051c2b8 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:43:17 +0000 Subject: [PATCH 116/150] test(compat): pin catalog lookups against search_path shadowing --- .../it/SearchPathShadowingCompatIT.java | 67 +++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/SearchPathShadowingCompatIT.java diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/SearchPathShadowingCompatIT.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/SearchPathShadowingCompatIT.java new file mode 100644 index 00000000..bfc2b2f5 --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/SearchPathShadowingCompatIT.java @@ -0,0 +1,67 @@ +package org.postgresql.it; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import org.junit.jupiter.api.Test; +import org.postgresql.PGResultSetMetaData; +import org.postgresql.core.BaseConnection; + +/** + * The compat layer's own catalog lookups must not run an {@code =(oid, int4)} operator that a + * search_path schema supplies. The shadowing operator raises, so a lookup that resolved to it fails + * the test. + */ +class SearchPathShadowingCompatIT extends AbstractCompatPostgresIT { + + private static final String SCHEMA = "shadow_compat"; + + private static void exec(Connection con, String sql) throws SQLException { + try (Statement st = con.createStatement()) { + st.execute(sql); + } + } + + private static int oid(Connection con, String typeName) throws SQLException { + try (Statement st = con.createStatement(); + ResultSet rs = st.executeQuery("SELECT '" + typeName + "'::regtype::oid::int4")) { + assertTrue(rs.next()); + return rs.getInt(1); + } + } + + @Test + void catalogLookupsUsePgCatalogOperators() throws SQLException { + try (Connection con = connect()) { + exec(con, "DROP SCHEMA IF EXISTS " + SCHEMA + " CASCADE"); + exec(con, "CREATE SCHEMA " + SCHEMA); + exec(con, "SET search_path = " + SCHEMA + ", public"); + exec(con, "CREATE TYPE sh_mood AS ENUM ('sad', 'ok')"); + exec(con, "CREATE TABLE sh_t (m sh_mood)"); + exec(con, "INSERT INTO sh_t VALUES ('ok')"); + exec( + con, + "CREATE FUNCTION " + SCHEMA + ".shadow_eq(oid, int4) RETURNS bool LANGUAGE plpgsql" + + " AS $$BEGIN RAISE EXCEPTION 'shadowing operator ran'; END$$"); + exec( + con, + "CREATE OPERATOR " + SCHEMA + ".= (LEFTARG = oid, RIGHTARG = int4, FUNCTION = " + SCHEMA + + ".shadow_eq)"); + + assertEquals( + "sh_mood", con.unwrap(BaseConnection.class).getTypeInfo().getPGType(oid(con, "sh_mood"))); + try (Statement st = con.createStatement(); + ResultSet rs = st.executeQuery("SELECT m FROM sh_t")) { + PGResultSetMetaData md = assertInstanceOf(PGResultSetMetaData.class, rs.getMetaData()); + assertEquals("m", md.getBaseColumnName(1)); + assertTrue(rs.next()); + assertEquals("ok", rs.getObject(1).toString()); + } + } + } +} From eabc6910f77a4587dceb4133ed97768b6acfebdf Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:46:12 +0000 Subject: [PATCH 117/150] fix(core): refuse an ssl value that is neither true nor false ssl=require or ssl=verify-full left the connection at sslmode=prefer. --- .../core/internal/jdbc/ConnectionStringParser.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java index 985fdb3e..f1a3662a 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java @@ -275,8 +275,13 @@ private static PgConnectionConfig toConfig( // environment does not defer it: a URL parameter outranks the environment, so a stray // PGSSLMODE=disable must not silently turn an explicit ssl=true into a cleartext session. String ssl = params.get("ssl"); - if (ssl != null && urlSslMode == null && isTruthy(ssl)) { - builder.sslMode(SslMode.VERIFY_FULL); + if (ssl != null && urlSslMode == null) { + if (isTruthy(ssl)) { + builder.sslMode(SslMode.VERIFY_FULL); + } else if (!isFalsy(ssl)) { + // ssl=require or ssl=verify-full must not quietly leave the connection at prefer. + throw new PgConfigurationException("invalid ssl: " + ssl + " (expected true or false)"); + } } String channelBinding = firstNonNull(params.get("channel_binding"), env.get("PGCHANNELBINDING")); if (channelBinding != null) { @@ -574,6 +579,11 @@ private static boolean isTruthy(String value) { return v.isEmpty() || v.equals("true") || v.equals("1") || v.equals("yes") || v.equals("on"); } + private static boolean isFalsy(String value) { + String v = value.trim().toLowerCase(java.util.Locale.ROOT); + return v.equals("false") || v.equals("0") || v.equals("no") || v.equals("off"); + } + private static @Nullable String firstNonNull(@Nullable String... values) { for (String value : values) { if (value != null) { From 1514732310b8c5acf868e0e80728c7d948052765 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:46:58 +0000 Subject: [PATCH 118/150] test(core): cover unrecognised and false ssl values --- .../core/ConnectionStringParserTest.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java index 3c63a4d5..2099bcde 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java @@ -158,6 +158,33 @@ void anSslModeParameterStillOutranksSslTrue() { assertEquals(SslMode.REQUIRE, c.sslMode()); } + @Test + void anUnrecognisedSslValueIsRefused() { + for (String value : new String[] {"require", "verify-full", "y", "enabled"}) { + assertThrows( + PgConfigurationException.class, + () -> parse("postgresql://h/db?user=app&ssl=" + value), + "ssl=" + value); + } + } + + @Test + void sslFalseKeepsTheDefaultMode() { + for (String value : new String[] {"false", "0", "no", "off", "FALSE"}) { + assertEquals( + SslMode.PREFER, + parse("postgresql://h/db?user=app&ssl=" + value).sslMode(), + value); + } + } + + @Test + void anSslModeParameterMakesTheSslValueIrrelevant() { + // As in pgjdbc, ssl is ignored when sslmode is set, so its value is not checked either. + PgConnectionConfig c = parse("postgresql://h/db?user=app&ssl=require&sslmode=verify-ca"); + assertEquals(SslMode.VERIFY_CA, c.sslMode()); + } + @Test void ignoreEnvironmentDropsEveryPgVariable() { // One switch rather than a list of variables to distrust: the set grows, and what the From e4a75b4d11297de3b29f9e121739c0c16889e439 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:50:16 +0000 Subject: [PATCH 119/150] fix(core): refuse a BigDecimal outside numeric's range The binary encoder wrapped weight and dscale to 16 bits, so 1e131072 was stored as 0. A huge exponent also cost quadratic time before the send. --- .../client/core/codec/ScalarCodecs.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/codec/ScalarCodecs.java b/postgresql-client/src/main/java/org/postgresql/client/core/codec/ScalarCodecs.java index 313d34b8..ee1ed6a4 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/codec/ScalarCodecs.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/codec/ScalarCodecs.java @@ -311,6 +311,25 @@ static final class NumericCodec extends AbstractCodec { private static final int NUMERIC_NINF = 0xF000; // -Infinity (PG14+) private static final int NBASE = 10000; // base-10000 digits, 4 decimal places each + /** PostgreSQL's NUMERIC_DSCALE_MAX: the most fractional digits a numeric can carry. */ + private static final int MAX_DSCALE = 0x3FFF; + + /** Integer digits a numeric can carry: 4 per base-10000 group, weight at most int16 max. */ + private static final long MAX_INTEGER_DIGITS = 4L * (Short.MAX_VALUE + 1); + + /** + * Refuses what the server could not store, before any work proportional to the exponent: + * the binary form would otherwise wrap weight or dscale to 16 bits and store another value. + */ + private static void checkRange(BigDecimal value) { + if (value.scale() > MAX_DSCALE) { + throw new PgException("numeric value has more than " + MAX_DSCALE + " fractional digits"); + } + if (value.signum() != 0 && (long) value.precision() - value.scale() > MAX_INTEGER_DIGITS) { + throw new PgException("numeric value has more than " + MAX_INTEGER_DIGITS + " integer digits"); + } + } + NumericCodec() { super(BigDecimal.class, Oids.NUMERIC); } @@ -391,6 +410,7 @@ protected BigDecimal decodeBinary(ByteSlice value, CodecContext context) { @Override protected String encodeAsText(BigDecimal value, CodecContext context) { + checkRange(value); return value.toPlainString(); } @@ -441,6 +461,7 @@ public boolean prefersBinaryParameter() { */ @Override public void encodeBinaryTo(PgWriteBuffer buf, BigDecimal value, CodecContext context) { + checkRange(value); int dscale = Math.max(0, value.scale()); if (value.signum() == 0) { buf.writeShort(0); // ndigits From 8918fe6e96808a8bc79de9226cd04864574e000e Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:50:46 +0000 Subject: [PATCH 120/150] test(core): cover BigDecimal values outside numeric's range --- .../client/core/codec/ScalarCodecsTest.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/codec/ScalarCodecsTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/codec/ScalarCodecsTest.java index 5e551449..45739620 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/codec/ScalarCodecsTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/codec/ScalarCodecsTest.java @@ -139,6 +139,23 @@ void binaryParameterEncodingRoundTripsThroughDecode() { // task 10 assertBinaryRoundTrip(Oids.BOOL, false); } + @Test + void numericOutsideTheServerRangeIsRefused() { + @SuppressWarnings("unchecked") + Codec numeric = (Codec) registry.forOid(Oids.NUMERIC); + // 1e131072 would wrap weight to -32768 and 999999.99e-262144 dscale to 2: both store another value. + for (String text : new String[] {"1e131072", "999999.99e-262144", "1e100000000", "-1e-16384"}) { + BigDecimal value = new BigDecimal(text); + assertThrows(PgException.class, () -> numeric.encodeBinary(value, context), text); + assertThrows(PgException.class, () -> numeric.encodeText(value, context), text); + } + } + + @Test + void numericAtTheServerLimitsRoundTrips() { + assertBinaryRoundTrip(Oids.NUMERIC, new BigDecimal("1e-16383")); + } + @Test void numericBinaryParameterRoundTripsThroughDecode() { // P4, N5.7: numeric now binds in binary Codec numeric = registry.forOid(Oids.NUMERIC); From 0900bd6ae3ecb9ce14fb94206c31269d90c0daeb Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:51:08 +0000 Subject: [PATCH 121/150] fix(core): refuse client encodings that embed ASCII in multibyte characters SQL text is sent as UTF-8; read as SJIS, BIG5, GBK, UHC, JOHAB or GB18030 a backslash can be swallowed, which breaks the E'' literal of the composite type lookup. A runtime SET now closes the connection. --- .../main/java/org/postgresql/client/core/PgEncodings.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/PgEncodings.java b/postgresql-client/src/main/java/org/postgresql/client/core/PgEncodings.java index db44ba6a..df627e3a 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/PgEncodings.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/PgEncodings.java @@ -33,6 +33,12 @@ static Charset toCharset(@Nullable String encoding) { case "LATIN1", "ISO88591" -> StandardCharsets.ISO_8859_1; case "LATIN9", "ISO885915" -> requireCharset(encoding, "ISO-8859-15"); case "WIN1252" -> requireCharset(encoding, "windows-1252"); + // SQL text always goes out as UTF-8. Read in one of these, a UTF-8 byte can become a + // lead byte that takes the next ASCII byte as its trail, so a backslash or quote in a + // literal disappears and the rest of the literal runs as SQL. + case "SJIS", "SHIFT_JIS_2004", "BIG5", "GBK", "UHC", "JOHAB", "GB18030" -> + throw new PgConfigurationException("client_encoding '" + encoding + "' is not supported: it can" + + " read an ASCII byte as part of a multibyte character. Use client_encoding=UTF8."); default -> requireCharset(encoding, encoding); }; } From 281cd4de0b5bcbfdf0762f552530123feeefe9b6 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:51:37 +0000 Subject: [PATCH 122/150] test(core): cover refusing ASCII-unsafe client encodings --- .../client/core/PgEncodingsTest.java | 7 +++++++ .../core/SessionParameterChangeTest.java | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/PgEncodingsTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/PgEncodingsTest.java index 022c3192..bfb768c7 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/PgEncodingsTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/PgEncodingsTest.java @@ -22,6 +22,13 @@ void utf8NamesMapToUtf8() { assertEquals(StandardCharsets.UTF_8, PgEncodings.toCharset("UNICODE")); } + @Test + void asciiUnsafeEncodingsAreRefused() { + for (String name : new String[] {"SJIS", "SHIFT_JIS_2004", "BIG5", "GBK", "UHC", "JOHAB", "GB18030", "sjis"}) { + assertThrows(PgConfigurationException.class, () -> PgEncodings.toCharset(name), name); + } + } + @Test void nullDefaultsToUtf8() { assertEquals(StandardCharsets.UTF_8, PgEncodings.toCharset(null)); diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/SessionParameterChangeTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/SessionParameterChangeTest.java index 2ba4c1fa..e2e60149 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/SessionParameterChangeTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/SessionParameterChangeTest.java @@ -93,4 +93,22 @@ void standardConformingStringsTurnedOffBreaksTheConnection() { assertTrue(e.getMessage().contains("standard_conforming_strings"), e.getMessage()); assertTrue(connection.isBroken()); } + + @Test + void anAsciiUnsafeClientEncodingBreaksTheConnection() { + MockServer server = new MockServer() + .onMessage((s, f) -> s.send( + BackendWire.commandComplete("SET"), + BackendWire.parameterStatus("client_encoding", "SJIS"), + BackendWire.readyForQuery('I'))); + CoreConnection connection = connect(server); + + PgException e = assertThrows(PgException.class, () -> { + try (PgResultStream rs = connection.execute("SET client_encoding TO 'SJIS'")) { + rs.next(); + } + }); + assertTrue(e.getMessage().contains("SJIS"), e.getMessage()); + assertTrue(connection.isBroken()); + } } From 7aa366774703d8eb6267c5fdf0a14d4866fc1c18 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:52:12 +0000 Subject: [PATCH 123/150] fix(jdbc): keep the newline after a comment in an escape argument Arguments are rejoined on one line, so a -- comment in one ran on over the rest of the line, turning a later literal into SQL. --- .../postgresql/client/jdbc/CallArguments.java | 21 ++++++++++++++++++- .../org/postgresql/client/jdbc/SqlParser.java | 2 +- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java index 483c8df7..e8320b00 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java @@ -33,7 +33,7 @@ static String rebuild( List out = new ArrayList<>(); int placeholder = 0; for (String argument : split(argumentText)) { - String trimmed = argument.strip(); + String trimmed = strip(argument); if (trimmed.equals("?")) { placeholder++; if (!bound[placeholder - 1] && outParameters.contains(placeholder)) { @@ -74,6 +74,25 @@ static String rebuild( return String.join(", ", out); } + /** + * The argument without surrounding whitespace, except that one ending in a {@code --} comment + * keeps a newline: the arguments are rejoined on one line, where the comment would otherwise run + * on over whatever follows. + */ + static String strip(String argument) { + String stripped = argument.strip(); + int end = stripped.length(); + int i = 0; + while (i < end) { + int next = SqlLexing.skipLexeme(stripped, i, end); + if (next == end && stripped.startsWith("--", i)) { + return stripped + "\n"; + } + i = next > i ? next : i + 1; + } + return stripped; + } + private static Object requireBound(int placeholder, boolean[] bound, Object[] parameters) throws SQLException { if (placeholder > bound.length || !bound[placeholder - 1]) { throw new SQLException("parameter " + placeholder + " is not set"); diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java index 02e08ac9..ff5ded93 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java @@ -334,7 +334,7 @@ private static int matchingParen(String s, int open) { private static List splitArgs(String s) { List args = new ArrayList<>(); for (String arg : CallArguments.split(s)) { - args.add(arg.trim()); + args.add(CallArguments.strip(arg)); } return args; } From db75c0acd191681cb2365d7bfce9c26680cbc9d3 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:52:34 +0000 Subject: [PATCH 124/150] test(jdbc): cover a comment in an escape argument --- .../org/postgresql/client/jdbc/CallArgumentsTest.java | 7 +++++++ .../java/org/postgresql/client/jdbc/SqlParserTest.java | 9 +++++++++ 2 files changed, 16 insertions(+) diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/CallArgumentsTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/CallArgumentsTest.java index 998ed72d..075ea83d 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/CallArgumentsTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/CallArgumentsTest.java @@ -22,6 +22,13 @@ private String rebuild(String text, boolean call, Set out, Object... bo return CallArguments.rebuild(text, call, out, isBound, bound, values); } + @Test + void aCommentInAnArgumentKeepsItsNewline() throws SQLException { + assertEquals("$1 -- c\n, 'l1\nl2'", rebuild("? -- c\n, 'l1\nl2'", false, Set.of(), "a")); + values.clear(); + assertEquals("1 -- c\n, $1", rebuild("1 -- c\n, ?", false, Set.of(), "a")); + } + @Test void literalArgumentsAreKept() throws SQLException { assertEquals("$1, 1", rebuild("?, 1", false, Set.of(), "a")); diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java index 37156ad8..e22c6af1 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java @@ -225,4 +225,13 @@ void dollarInsideAnIdentifierDoesNotMakeAnEString() { assertEquals("select x$e'\\', $1", p.nativeSql()); assertEquals(1, p.parameterCount()); } + + @Test + void aCommentInAnEscapeArgumentKeepsItsNewline() { + // Without the newline the comment would run over 'l1 and leave l2 outside a literal. + ParsedSql p = parse("SELECT {fn ifnull(a -- c\n, 'x')}, 'l1\nl2'"); + assertEquals("SELECT coalesce(a -- c\n,'x'), 'l1\nl2'", p.nativeSql()); + ParsedSql q = parse("SELECT {fn locate('a', b -- c\n)}"); + assertEquals("SELECT position('a' in b -- c\n)", q.nativeSql()); + } } From 9ffa4b8798c5c137d664afbb4f477e2175a9804f Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:52:50 +0000 Subject: [PATCH 125/150] fix(compat): resolve hstore to the extension's type A typname match could pick a domain named hstore in any schema, another session's temp schema included. --- .../postgresql/client/compat/internal/HstoreSupport.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/HstoreSupport.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/HstoreSupport.java index adcfedd8..d7754182 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/HstoreSupport.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/HstoreSupport.java @@ -68,8 +68,14 @@ public int resolve() { oid = ABSENT; // no core connection will ever appear; do not re-query return oid; } + // The hstore extension's own type: a bare typname match could pick a domain named hstore + // in any schema, another session's temp schema included, and bind Maps with its OID. try (Statement statement = connection.createStatement(); - ResultSet rs = statement.executeQuery("SELECT oid FROM pg_type WHERE typname = 'hstore' LIMIT 1")) { + ResultSet rs = statement.executeQuery("SELECT t.oid FROM pg_catalog.pg_type t" + + " JOIN pg_catalog.pg_depend d ON d.objid = t.oid AND d.deptype = 'e'" + + " AND d.classid OPERATOR(pg_catalog.=) 'pg_catalog.pg_type'::pg_catalog.regclass" + + " JOIN pg_catalog.pg_extension e ON e.oid = d.refobjid" + + " WHERE e.extname = 'hstore' AND t.typname = 'hstore'")) { if (rs.next()) { int resolved = rs.getInt(1); core.registerCodecOverriding(new HstoreCodec(resolved)); From 24ed75f5934661a1e507f3b97126a11eb145fdd7 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:53:16 +0000 Subject: [PATCH 126/150] test(compat): pin the hstore OID against a same-named domain --- .../org/postgresql/it/HstoreCompatIT.java | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/HstoreCompatIT.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/HstoreCompatIT.java index 370e4c55..d4402b5b 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/HstoreCompatIT.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/HstoreCompatIT.java @@ -85,6 +85,33 @@ void mapParameterBindsAsTypedHstore() throws SQLException { } } + @Test + void mapParameterUsesTheExtensionTypeNotAnotherTypeNamedHstore() throws SQLException { + try (Connection setup = connect()) { + assumeTrue(hstoreAvailable(setup), "server can install hstore"); + try (Statement stmt = setup.createStatement()) { + stmt.execute("DROP SCHEMA IF EXISTS hs_shadow CASCADE"); + stmt.execute("CREATE SCHEMA hs_shadow"); + stmt.execute("CREATE DOMAIN hs_shadow.hstore AS text CHECK (false)"); + } + try (Connection con = connect(); + PreparedStatement ps = con.prepareStatement("SELECT pg_typeof(?)::oid::int8, (" + + "SELECT t.oid::int8 FROM pg_type t JOIN pg_extension e ON e.oid = (" + + "SELECT refobjid FROM pg_depend WHERE objid = t.oid AND deptype = 'e')" + + " WHERE e.extname = 'hstore' AND t.typname = 'hstore')")) { + ps.setObject(1, Collections.singletonMap("a", 1)); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getLong(2), rs.getLong(1)); + } + } finally { + try (Statement stmt = setup.createStatement()) { + stmt.execute("DROP SCHEMA hs_shadow CASCADE"); + } + } + } + } + @Test void mapParameterRoundTripsBareSelectWithEscapes() throws SQLException { try (Connection con = connect()) { From e650d1a244e82a51f141a9226ba445242c200c0f Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:53:26 +0000 Subject: [PATCH 127/150] fix(compat): refuse service instead of ignoring it The entry's settings, sslmode included, were silently dropped. --- .../src/main/java/org/postgresql/Driver.java | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java index 0ad01955..1d465d86 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java @@ -365,10 +365,19 @@ static String translateUrl(String url) throws PSQLException { * Rejects an unsupported property whose value demands a security property rather than * expressing a preference. {@code gssEncMode=require} is the only such drop today: silently * ignoring it hands the caller a connection with no GSSAPI transport encryption at all, which - * is the failure direction a "require" must never take. Every other unsupported property - * degrades to a warning because dropping it cannot weaken the connection. + * is the failure direction a "require" must never take. {@code service} is refused too: the + * entry may carry sslmode or other settings the connection would otherwise run without. Every + * other unsupported property degrades to a warning because dropping it cannot weaken the + * connection. */ private static void rejectUnsupportedRequirement(String name, String value) throws PSQLException { + if ("service".equals(name) && value != null && !value.isBlank()) { + throw new PSQLException( + "service=" + value + " is not supported: pg-java does not read pg_service.conf, and" + + " connecting without the entry could drop settings such as sslmode. Put the" + + " entry's settings in the URL instead.", + PSQLState.CONNECTION_REJECTED); + } if ("gssEncMode".equals(name) && value != null && "require".equalsIgnoreCase(value.trim())) { throw new PSQLException( "gssEncMode=require demands GSSAPI transport encryption, which pg-java does not" From b28df765fb415c627824698c2f2f171d2508e796 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:53:40 +0000 Subject: [PATCH 128/150] test(compat): cover refusing service --- .../src/test/java/org/postgresql/DriverTest.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java index 19adfe41..72b79cf8 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java @@ -90,6 +90,19 @@ void gssEncModeRequireIsRefusedRatherThanDropped() throws Exception { assertThrows(PSQLException.class, () -> Driver.translateUrl("jdbc:postgresql://h/db?gssEncMode=require")); } + @Test + void serviceIsRefusedRatherThanDropped() throws Exception { + Properties info = new Properties(); + info.setProperty("user", "bob"); + info.setProperty("service", "prod"); + + PSQLException e = assertThrows(PSQLException.class, () -> Driver.translateProperties(info)); + assertTrue(e.getMessage().contains("service=prod"), e.getMessage()); + assertEquals(PSQLState.CONNECTION_REJECTED.getState(), e.getSQLState()); + + assertThrows(PSQLException.class, () -> Driver.translateUrl("jdbc:postgresql://h/db?service=prod")); + } + @Test void ignoreEnvironmentDefaultsOnForCompat() throws Exception { // pgjdbc reads no PG* environment, so its drop-in must not either: inheriting PGSSLMODE or From e6857bc55f83f9eae1f730f4854f795e9c61385f Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:54:19 +0000 Subject: [PATCH 129/150] fix(core): mark the connection broken on a malformed message ProtocolException is not a PgException, so it escaped the markBroken catches and left the connection busy but not broken. --- .../client/core/internal/WireChannel.java | 27 ++++++++++++------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/WireChannel.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/WireChannel.java index afeffb4d..a535e16c 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/WireChannel.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/WireChannel.java @@ -8,6 +8,7 @@ import org.postgresql.client.core.transport.Transport; import org.postgresql.client.protocol.ProtocolDecoder; import org.postgresql.client.protocol.ProtocolEncoder; +import org.postgresql.client.protocol.ProtocolException; import org.postgresql.client.protocol.message.BackendMessage; import org.postgresql.client.protocol.message.FrontendMessage; @@ -132,18 +133,24 @@ public void flush() { /** Blocks until the next backend message is available, or fails if the server closes. */ public BackendMessage next() { - BackendMessage message = decoder.next(); - while (message == null) { - // Read straight into the decoder's framing buffer (no staging array + copy): the - // transport fills the buffer's writable tail directly. Safe because a message is only - // returned once fully framed, and the caller consumes it before the next read here. - int n = decoder.fillFrom(transport::read); - if (n < 0) { - throw new PgConnectionException("server closed the connection"); + try { + BackendMessage message = decoder.next(); + while (message == null) { + // Read straight into the decoder's framing buffer (no staging array + copy): the + // transport fills the buffer's writable tail directly. Safe because a message is only + // returned once fully framed, and the caller consumes it before the next read here. + int n = decoder.fillFrom(transport::read); + if (n < 0) { + throw new PgConnectionException("server closed the connection"); + } + message = decoder.next(); } - message = decoder.next(); + return message; + } catch (ProtocolException e) { + // A PgConnectionException, so the callers that mark the connection broken on PgException + // do so for a malformed message too. + throw new PgConnectionException("protocol violation: " + e.getMessage(), e); } - return message; } public Transport transport() { From 5db39ec629bec3e3c7e31bea1c1b92bac96b38d1 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:54:42 +0000 Subject: [PATCH 130/150] test(core): pin that a malformed message breaks the connection --- .../client/core/MalformedMessageTest.java | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 postgresql-client/src/test/java/org/postgresql/client/core/MalformedMessageTest.java diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/MalformedMessageTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/MalformedMessageTest.java new file mode 100644 index 00000000..4c3d682f --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/MalformedMessageTest.java @@ -0,0 +1,73 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.auth.TrustAuthenticator; +import org.postgresql.client.core.internal.StartupOrchestrator; +import org.postgresql.client.core.internal.StartupResult; +import org.postgresql.client.core.internal.WireChannel; +import org.postgresql.client.core.transport.BackendWire; +import org.postgresql.client.core.transport.MockServer; + +/** A message the decoder refuses breaks the connection, on every read path. */ +class MalformedMessageTest { + + /** A RowDescription claiming one field but carrying none. */ + private static final byte[] TRUNCATED_ROW_DESCRIPTION = {'T', 0, 0, 0, 6, 0, 1}; + + private static CoreConnection connect(MockServer server) { + PgConnectionConfig config = PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .build(); + server.onStartup((s, f) -> s.send( + BackendWire.authenticationOk(), + BackendWire.parameterStatus("server_version", "17.0"), + BackendWire.parameterStatus("client_encoding", "UTF8"), + BackendWire.parameterStatus("DateStyle", "ISO, MDY"), + BackendWire.parameterStatus("IntervalStyle", "iso_8601"), + BackendWire.parameterStatus("standard_conforming_strings", "on"), + BackendWire.parameterStatus("TimeZone", "UTC"), + BackendWire.readyForQuery('I'))); + WireChannel channel = new WireChannel(server, SizeLimits.unlimited()); + StartupResult startup = new StartupOrchestrator( + channel, config, HostAndPort.of("h"), TrustAuthenticator.INSTANCE, PgConnectionListener.NO_OP) + .run(); + CoreConnection connection = + new CoreConnection(channel, config, startup, HostAndPort.of("h"), PgConnectionListener.NO_OP); + connection.bootstrapSession(); + return connection; + } + + @Test + void simpleQueryBreaksTheConnection() { + MockServer server = new MockServer().onMessage((s, f) -> s.send(TRUNCATED_ROW_DESCRIPTION)); + CoreConnection connection = connect(server); + + assertThrows(PgConnectionException.class, () -> { + try (PgResultStream rs = connection.execute("SELECT 1")) { + rs.next(); + } + }); + assertTrue(connection.isBroken()); + assertFalse(connection.isValid()); + } + + @Test + void extendedQueryBreaksTheConnection() { + MockServer server = new MockServer().onMessage((s, f) -> s.send(TRUNCATED_ROW_DESCRIPTION)); + CoreConnection connection = connect(server); + + assertThrows(PgConnectionException.class, () -> { + try (PgResultStream rs = connection.execute("SELECT $1::int4", List.of(1))) { + rs.next(); + } + }); + assertTrue(connection.isBroken()); + } +} From ffffa9289a9f5414fda74cbd8aad2474384d2851 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:55:19 +0000 Subject: [PATCH 131/150] fix(jdbc): treat a failed batch inside BEGIN as rolled back under autocommit The synced windows were reported as succeeded, and their keys kept, though the failed transaction block rolls them back. --- .../postgresql/client/jdbc/PgPreparedStatement.java | 2 +- .../java/org/postgresql/client/jdbc/PgStatement.java | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgPreparedStatement.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgPreparedStatement.java index 5ac63024..05ff701c 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgPreparedStatement.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgPreparedStatement.java @@ -1169,7 +1169,7 @@ public long[] executeLargeBatch() throws SQLException { // Inside an explicit transaction a failed batch commits nothing (the caller's later // commit rolls the aborted transaction back), so the keys captured before the failure are // not durable -- drop them to stay consistent with the all-failed update counts. - if (failed && !connection.getAutoCommit()) { + if (failed && !batchProgressIsDurable()) { keyMetadata = null; keyRows.clear(); } diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgStatement.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgStatement.java index bae6311d..d7c53aee 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgStatement.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgStatement.java @@ -704,13 +704,21 @@ static BatchUpdateException batchFailure(String message, String sqlState, long[] * {@code BatchResultHandler}, which advances its committed boundary only when autocommit is on. */ long[] failedBatchCounts(long[] counts, int committed, int totalSize) throws SQLException { - int boundary = connection.getAutoCommit() ? committed : 0; + int boundary = batchProgressIsDurable() ? committed : 0; long[] out = new long[totalSize]; Arrays.fill(out, Statement.EXECUTE_FAILED); System.arraycopy(counts, 0, out, 0, boundary); return out; } + /** + * Whether the windows of a failed batch that already synced stay committed: under autocommit, and + * not inside a transaction block the caller opened with BEGIN, whose failure rolls them back. + */ + boolean batchProgressIsDurable() throws SQLException { + return connection.getAutoCommit() && !core.inTransaction(); + } + /** * A full-length update-count array whose first {@code kept} entries carry their real counts (from * {@code counts}) and the rest are {@link Statement#EXECUTE_FAILED}. Used when a batch entry From 5a6a630d041dd18f441437479522cb9b57e87f9c Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:55:38 +0000 Subject: [PATCH 132/150] test(jdbc): cover a failed batch inside BEGIN under autocommit --- .../client/jdbc/it/JdbcBatchIT.java | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/JdbcBatchIT.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/JdbcBatchIT.java index c249fa38..fcb84081 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/JdbcBatchIT.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/JdbcBatchIT.java @@ -387,4 +387,44 @@ void generatedKeysOfSucceededEntriesSurviveAMidBatchFailure() throws Exception { } } } + + @Test + void pipelinedBatchFailureInsideBeginUnderAutocommitReportsEveryEntryFailed() throws Exception { + // Autocommit is on, but the caller opened a transaction block: the windows that synced before + // the failure are rolled back with it, so none of their counts or keys may be reported. + int n = 400; + try (Connection setup = connect(); + Statement st = setup.createStatement()) { + st.execute("drop table if exists bp3"); + st.execute("create table bp3 (id serial primary key, v int unique)"); + } + try (Connection conn = connect()) { + try (Statement st = conn.createStatement()) { + st.execute("begin"); + } + try (PreparedStatement ps = + conn.prepareStatement("insert into bp3 (v) values (?)", Statement.RETURN_GENERATED_KEYS)) { + for (int i = 0; i < n; i++) { + ps.setInt(1, i == 300 ? 0 : i); + ps.addBatch(); + } + BatchUpdateException e = assertThrows(BatchUpdateException.class, ps::executeBatch); + for (int c : e.getUpdateCounts()) { + assertEquals(Statement.EXECUTE_FAILED, c); + } + try (ResultSet keys = ps.getGeneratedKeys()) { + assertFalse(keys.next()); + } + } + } + // Closing the connection ends the failed transaction block; nothing it held is committed. + try (Connection check = connect(); + Statement st = check.createStatement()) { + try (ResultSet rs = st.executeQuery("select count(*) from bp3")) { + assertTrue(rs.next()); + assertEquals(0, rs.getInt(1)); + } + st.execute("drop table bp3"); + } + } } From f892a466fd42b6ba39a490f91516ca7eb6c6184e Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:56:48 +0000 Subject: [PATCH 133/150] fix(jdbc): lex string continuations, $ in identifiers and surrogates as the backend does Each put placeholders where the server saw a literal, or the reverse. --- .../postgresql/client/jdbc/sql/SqlLexing.java | 80 +++++++++++++++++-- 1 file changed, 75 insertions(+), 5 deletions(-) diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/sql/SqlLexing.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/sql/SqlLexing.java index a32973e8..0bd84c9c 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/sql/SqlLexing.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/sql/SqlLexing.java @@ -27,10 +27,50 @@ public static boolean isEscapeStringPrefix(String sql, int i) { if (i < 2) { return true; } - char before = sql.charAt(i - 2); // '$' too: PostgreSQL identifiers may contain it after the first character, so the 'e' of // x$e'..' ends the identifier x$e and the quote opens a plain string. - return !(Character.isLetterOrDigit(before) || before == '_' || before == '$'); + return !isIdentifierPart(sql, i - 2); + } + + /** + * Whether the character at {@code i} continues an identifier as the backend sees it: an ASCII + * letter, digit, {@code _} or {@code $}, or any non-ASCII character. An unpaired surrogate is + * not one, since it goes out as {@code ?}. + */ + private static boolean isIdentifierPart(String sql, int i) { + char c = sql.charAt(i); + if (c < 0x80) { + return Character.isLetterOrDigit(c) || c == '_' || c == '$'; + } + return !isUnpairedSurrogate(sql, i); + } + + private static boolean isUnpairedSurrogate(String sql, int i) { + char c = sql.charAt(i); + if (Character.isHighSurrogate(c)) { + return i + 1 >= sql.length() || !Character.isLowSurrogate(sql.charAt(i + 1)); + } + if (Character.isLowSurrogate(c)) { + return i == 0 || !Character.isHighSurrogate(sql.charAt(i - 1)); + } + return false; + } + + /** + * Whether the {@code $} at {@code i} continues an identifier ({@code x$b$} is one identifier to + * the backend, not {@code x} and a dollar quote): the run of identifier characters before it + * starts with a letter, {@code _} or non-ASCII character rather than a digit or {@code $}. + */ + private static boolean continuesIdentifier(String sql, int i) { + int j = i; + while (j > 0 && isIdentifierPart(sql, j - 1)) { + j--; + } + if (j == i) { + return false; + } + char first = sql.charAt(j); + return !(first == '$' || (first >= '0' && first <= '9')); } /** @@ -78,13 +118,40 @@ public static int skipSingleQuoted(String sql, int i, int end, boolean escapeStr i += 2; // doubled quote: an escaped quote, stay in the string continue; } - return i + 1; + int continued = continuationQuote(sql, i + 1, end); + if (continued < 0) { + return i + 1; + } + i = continued + 1; // 'a''b' is one string, keeping E'' rules if it had them + continue; } i++; } return -1; } + /** + * The index of the quote that continues a string closed just before {@code i}: whitespace + * holding at least one newline (line comments allowed), then a quote. -1 when none follows. + */ + private static int continuationQuote(String sql, int i, int end) { + boolean newline = false; + while (i < end) { + char c = sql.charAt(i); + if (c == '\n' || c == '\r') { + newline = true; + i++; + } else if (c == ' ' || c == '\t' || c == '\f' || c == '\u000B') { + i++; + } else if (c == '-' && i + 1 < end && sql.charAt(i + 1) == '-') { + i = skipLineComment(sql, i, end); + } else { + return newline && c == '\'' ? i : -1; + } + } + return -1; + } + /** * Skips the double-quoted identifier opening at {@code i} (with {@code ""} escapes); returns * the index past the closing quote, or -1 if unterminated. @@ -142,6 +209,9 @@ public static int skipBlockComment(String sql, int i, int end) { * closes; when it is a lone {@code $} (not an open tag), returns {@code i + 1}. */ public static int skipDollarQuote(String sql, int i, int end) { + if (continuesIdentifier(sql, i)) { + return i + 1; + } int tagEnd = dollarTagEnd(sql, i, end); if (tagEnd < 0) { return i + 1; // a lone '$', not a dollar-quote open @@ -157,9 +227,9 @@ private static int dollarTagEnd(String sql, int i, int end) { if (j < end && sql.charAt(j) == '$') { return j; // empty tag $$ } - if (j < end && isDollarTagStart(sql.charAt(j))) { + if (j < end && isDollarTagStart(sql.charAt(j)) && !isUnpairedSurrogate(sql, j)) { j++; - while (j < end && isDollarTagPart(sql.charAt(j))) { + while (j < end && isDollarTagPart(sql.charAt(j)) && !isUnpairedSurrogate(sql, j)) { j++; } if (j < end && sql.charAt(j) == '$') { From 7c72031c70dd40ff420099218aad2ae08703ece4 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:57:14 +0000 Subject: [PATCH 134/150] test(jdbc): cover continuations, $ in identifiers and surrogates in the lexer --- .../postgresql/client/jdbc/SqlParserTest.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java index e22c6af1..099bb547 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java @@ -234,4 +234,38 @@ void aCommentInAnEscapeArgumentKeepsItsNewline() { ParsedSql q = parse("SELECT {fn locate('a', b -- c\n)}"); assertEquals("SELECT position('a' in b -- c\n)", q.nativeSql()); } + + @Test + void aContinuedEscapeStringKeepsItsEscapes() { + // The backend reads a' , ? -- as one E'' string, so there is no placeholder. + ParsedSql p = parse("SELECT E'a'\n'\\' , ? -- '"); + assertEquals(0, p.parameterCount()); + ParsedSql q = parse("SELECT 'a' -- c\n'b', ?"); + assertEquals("SELECT 'a' -- c\n'b', $1", q.nativeSql()); + ParsedSql r = parse("SELECT 'a' 'b', ?"); + assertEquals(1, r.parameterCount()); + } + + @Test + void aDollarInsideAnIdentifierDoesNotOpenAQuote() { + ParsedSql p = parse("SELECT x$b$ , $b$ ? $b$"); + assertEquals("SELECT x$b$ , $b$ ? $b$", p.nativeSql()); + assertEquals(0, p.parameterCount()); + ParsedSql q = parse("SELECT ?, $1$a$ ? $a$"); + assertEquals(1, q.parameterCount()); + } + + @Test + void anEAfterANonAsciiCharacterIsPartOfAnIdentifier() { + ParsedSql p = parse("SELECT \u00A7e'\\' ? ' ? '"); + assertEquals("SELECT \u00A7e'\\' $1 ' ? '", p.nativeSql()); + } + + @Test + void anUnpairedSurrogateDoesNotFormADollarTag() { + ParsedSql p = parse("SELECT $a\uD800$ ? $a\uD800$, ?"); + assertEquals(2, p.parameterCount()); + ParsedSql q = parse("SELECT $a\uD83D\uDE00$ ? $a\uD83D\uDE00$, ?"); + assertEquals(1, q.parameterCount()); + } } From 6bf1eea33ba6b3620e286629133c006ad5c43613 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:57:36 +0000 Subject: [PATCH 135/150] fix(jdbc): count $ and non-ASCII characters as identifier characters in keyword search x$returning matched RETURNING, so generated keys were not requested. --- .../src/main/java/org/postgresql/client/jdbc/SqlParser.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java index ff5ded93..09f645c6 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java @@ -141,8 +141,9 @@ private static int skipThrough(int end, int skipEnd) { return skipEnd < 0 ? end : skipEnd; } + /** As the backend sees it, so {@code x$returning} is one identifier, not a RETURNING keyword. */ private static boolean isIdentifierPart(char c) { - return Character.isLetterOrDigit(c) || c == '_'; + return Character.isLetterOrDigit(c) || c == '_' || c == '$' || c >= 0x80; } /** From b512bf6dc1cdd0583d2e85dd6e5c6bd33db37290 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:57:44 +0000 Subject: [PATCH 136/150] test(jdbc): cover keyword search past identifiers ending in the keyword --- .../java/org/postgresql/client/jdbc/SqlParserTest.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java index 099bb547..b9d58bee 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java @@ -268,4 +268,11 @@ void anUnpairedSurrogateDoesNotFormADollarTag() { ParsedSql q = parse("SELECT $a\uD83D\uDE00$ ? $a\uD83D\uDE00$, ?"); assertEquals(1, q.parameterCount()); } + + @Test + void containsKeywordSkipsIdentifiersThatEndInTheKeyword() { + assertFalse(SqlParser.containsKeyword("insert into t (x$returning) values (1)", "returning")); + assertFalse(SqlParser.containsKeyword("insert into t (\u00e9returning) values (1)", "returning")); + assertTrue(SqlParser.containsKeyword("insert into t values (1) returning id", "returning")); + } } From caa2488775b5d4cc3fd7f52cf9a14e1fafacb2ee Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:58:35 +0000 Subject: [PATCH 137/150] fix(protocol): cap frame buffer growth below the JVM array limit Near the cap the buffer doubled to Integer.MAX_VALUE, which the JVM refuses with an OutOfMemoryError. The default cap now admits the largest message a server builds. --- .../client/protocol/framing/FrameReader.java | 31 ++++++++++++------- .../protocol/framing/FrameReaderTest.java | 2 +- .../postgresql/client/core/SizeLimits.java | 2 +- .../client/core/SizeLimitsTest.java | 2 +- 4 files changed, 22 insertions(+), 15 deletions(-) diff --git a/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/framing/FrameReader.java b/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/framing/FrameReader.java index a0d447a7..802aceab 100644 --- a/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/framing/FrameReader.java +++ b/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/framing/FrameReader.java @@ -28,11 +28,15 @@ public final class FrameReader { public static final long UNLIMITED = 0L; /** - * Default cap when none is specified: 1 GiB. Generous enough for a maximum-size PostgreSQL - * value (a single field maxes at {@code 0x3FFFFFFF}, just under 1 GiB) while bounding the - * accumulation-buffer memory-exhaustion vector so an unconfigured connection is not unlimited. + * Default cap when none is specified: the largest message a server builds. A message body lives + * in a StringInfo, whose data stays under MaxAllocSize ({@code 0x3FFFFFFF}), and the length + * prefix counts its own four bytes. This bounds the accumulation-buffer memory-exhaustion vector + * so an unconfigured connection is not unlimited. */ - public static final long DEFAULT_MAX_MESSAGE_LENGTH = 1L << 30; + public static final long DEFAULT_MAX_MESSAGE_LENGTH = 0x3FFFFFFEL + 4; + + /** The largest array length every JVM allocates; {@code Integer.MAX_VALUE} is refused by some. */ + private static final int MAX_ARRAY_LENGTH = Integer.MAX_VALUE - 8; private static final int DEFAULT_CAPACITY = 8192; @@ -227,16 +231,19 @@ private void ensureWritable(int additional) { if (additional <= buf.length - end) { return; } - long needed = (long) end + additional; - if (needed > Integer.MAX_VALUE) { - throw new IllegalStateException("frame buffer would exceed Integer.MAX_VALUE bytes"); + byte[] grown = new byte[grownCapacity(buf.length, (long) end + additional)]; + System.arraycopy(buf, 0, grown, 0, end); + buf = grown; + } + /** Doubles {@code capacity} until it holds {@code needed}, never past what the JVM allocates. */ + static int grownCapacity(int capacity, long needed) { + if (needed > MAX_ARRAY_LENGTH) { + throw new ProtocolException("frame buffer would exceed " + MAX_ARRAY_LENGTH + " bytes"); } - int newCapacity = buf.length; + long newCapacity = Math.max(capacity, 1); while (newCapacity < needed) { - newCapacity = (int) Math.min((long) newCapacity * 2, Integer.MAX_VALUE); + newCapacity = Math.min(newCapacity * 2, MAX_ARRAY_LENGTH); } - byte[] grown = new byte[newCapacity]; - System.arraycopy(buf, 0, grown, 0, end); - buf = grown; + return (int) newCapacity; } } diff --git a/postgresql-client-protocol/src/test/java/org/postgresql/client/protocol/framing/FrameReaderTest.java b/postgresql-client-protocol/src/test/java/org/postgresql/client/protocol/framing/FrameReaderTest.java index 80f87c9c..30560443 100644 --- a/postgresql-client-protocol/src/test/java/org/postgresql/client/protocol/framing/FrameReaderTest.java +++ b/postgresql-client-protocol/src/test/java/org/postgresql/client/protocol/framing/FrameReaderTest.java @@ -218,7 +218,7 @@ void defaultCapIsNonZero() { @Test void defaultRejectsOverCapDeclaredLengthBeforeAllocating() { FrameReader reader = new FrameReader(); // default cap - long over = FrameReader.DEFAULT_MAX_MESSAGE_LENGTH + 1; // 0x40000001, still a valid int32 prefix + long over = FrameReader.DEFAULT_MAX_MESSAGE_LENGTH + 1; // still a valid int32 prefix reader.feed(new byte[] {'Q', (byte) (over >>> 24), (byte) (over >>> 16), (byte) (over >>> 8), (byte) over}); assertThrows(ProtocolException.class, reader::nextTypedFrame); } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/SizeLimits.java b/postgresql-client/src/main/java/org/postgresql/client/core/SizeLimits.java index 0b4f0bc7..0d82bdac 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/SizeLimits.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/SizeLimits.java @@ -39,7 +39,7 @@ public static SizeLimits unlimited() { /** * The safe default: whole messages capped at {@link FrameReader#DEFAULT_MAX_MESSAGE_LENGTH} - * (1 GiB, closing the accumulation-buffer DoS, M2), single values unlimited. Applications that + * (about 1 GiB, closing the accumulation-buffer DoS, M2), single values unlimited. Applications that * must read even larger messages opt back to {@link #unlimited()} or set a custom cap. */ public static SizeLimits defaults() { diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/SizeLimitsTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/SizeLimitsTest.java index fdce94ec..eddb6760 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/SizeLimitsTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/SizeLimitsTest.java @@ -25,7 +25,7 @@ void defaultsBoundMessagesButNotValues() { SizeLimits limits = SizeLimits.defaults(); assertTrue(limits.limitsMessages(), "the default must cap whole messages (M2)"); assertFalse(limits.limitsValues()); - assertEquals(1L << 30, limits.maxMessageLength()); + assertEquals(0x3FFFFFFEL + 4, limits.maxMessageLength()); } @Test From 99dff3e0e3d00396010155bc13548e1686f4c9bd Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:58:52 +0000 Subject: [PATCH 138/150] test(protocol): cover frame buffer growth near the array limit --- .../client/protocol/framing/FrameReaderTest.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/postgresql-client-protocol/src/test/java/org/postgresql/client/protocol/framing/FrameReaderTest.java b/postgresql-client-protocol/src/test/java/org/postgresql/client/protocol/framing/FrameReaderTest.java index 30560443..49706767 100644 --- a/postgresql-client-protocol/src/test/java/org/postgresql/client/protocol/framing/FrameReaderTest.java +++ b/postgresql-client-protocol/src/test/java/org/postgresql/client/protocol/framing/FrameReaderTest.java @@ -223,6 +223,21 @@ void defaultRejectsOverCapDeclaredLengthBeforeAllocating() { assertThrows(ProtocolException.class, reader::nextTypedFrame); } + @Test + void defaultAcceptsTheLargestMessageAServerBuilds() { + // A body under MaxAllocSize (0x3FFFFFFF) plus the four length bytes. + assertEquals(0x3FFFFFFEL + 4, FrameReader.DEFAULT_MAX_MESSAGE_LENGTH); + } + + @Test + void growthStopsBelowTheJvmArrayLimit() { + int limit = Integer.MAX_VALUE - 8; + assertEquals(limit, FrameReader.grownCapacity(1 << 30, (1L << 30) + 32768)); + assertEquals(limit, FrameReader.grownCapacity(8192, limit)); + assertEquals(16384, FrameReader.grownCapacity(8192, 8193)); + assertThrows(ProtocolException.class, () -> FrameReader.grownCapacity(1 << 30, limit + 1L)); + } + @Test void defaultAcceptsANormalFrame() { FrameReader reader = new FrameReader(); From cb930de76006fcf5353de59aae56b7234d7423b5 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:59:11 +0000 Subject: [PATCH 139/150] fix(core): bound the number of messages read during startup A server repeating password requests or notices kept the handshake open forever; loginTimeout is off by default. --- .../client/core/internal/StartupOrchestrator.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java index 1174cb20..5e9c7175 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java @@ -50,6 +50,13 @@ public final class StartupOrchestrator implements AuthExchange { */ private static final int MAX_STARTUP_PARAMETERS = 2048; + /** + * Messages startup reads before giving up. Each read succeeds, so socketTimeout never fires, and + * loginTimeout is off by default: a peer repeating password requests or notices would otherwise + * hold the handshake open forever. Room for the parameter cap plus a long notice stream. + */ + private static final int MAX_STARTUP_MESSAGES = 2 * MAX_STARTUP_PARAMETERS + 1024; + private final WireChannel channel; private final PgConnectionConfig config; private final HostAndPort host; @@ -108,8 +115,13 @@ public StartupResult run() { // cleanup() zeroes any driver-owned secret the authenticator holds across calls (the SCRAM // exchange); the finally guarantees it runs on a failed login too, not only on success. + int messages = 0; try { while (true) { + if (++messages > MAX_STARTUP_MESSAGES) { + throw new PgConnectionException( + "the server sent more than " + MAX_STARTUP_MESSAGES + " messages during startup"); + } BackendMessage message = readNext(); switch (message) { case AuthenticationRequest.Ok ignored -> { From 2141f815cf367e409fd7a79c76974d8a74cc8a30 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 16:59:40 +0000 Subject: [PATCH 140/150] test(core): cover a server that never finishes startup --- .../postgresql/client/core/StartupOrchestratorTest.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java index 3e04cfd1..8736dd71 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java @@ -143,6 +143,15 @@ void channelBindingRequireRejectsTrustOk() { assertTrue(e.getMessage().contains("channelBinding=require"), e.getMessage()); } + @Test + void endlessStartupMessagesAreRefused() { + byte[][] notices = new byte[10_000][]; + java.util.Arrays.fill(notices, BackendWire.noticeResponse("still here")); + MockServer server = new MockServer().onStartup((s, frame) -> s.send(notices)); + PgConnectionException e = assertThrows(PgConnectionException.class, () -> run(server, config())); + assertTrue(e.getMessage().contains("messages during startup"), e.getMessage()); + } + @Test void serverCloseDuringStartupFails() { MockServer server = new MockServer(); // sends nothing From b7d15011d1cb10b6f285745a2610d4ae7dab0ae6 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 17:00:33 +0000 Subject: [PATCH 141/150] fix(core): cap messages at 30000 bytes before authentication Until AuthenticationOk any message could be as long as the 1 GiB cap, so an unauthenticated peer could make the driver buffer that much. --- .../client/protocol/ProtocolDecoder.java | 10 ++++++++++ .../client/protocol/framing/FrameReader.java | 17 +++++++++++++++-- .../core/internal/StartupOrchestrator.java | 10 ++++++++++ .../client/core/internal/WireChannel.java | 10 ++++++++++ 4 files changed, 45 insertions(+), 2 deletions(-) diff --git a/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/ProtocolDecoder.java b/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/ProtocolDecoder.java index 30abe82b..c2061591 100644 --- a/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/ProtocolDecoder.java +++ b/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/ProtocolDecoder.java @@ -96,6 +96,16 @@ public int fillFrom(FrameReader.Filler filler) { return decode(frame); } + /** See {@link FrameReader#limitMessageLength(long)}. */ + public void limitMessageLength(long limit) { + frameReader.limitMessageLength(limit); + } + + /** See {@link FrameReader#clearMessageLengthLimit()}. */ + public void clearMessageLengthLimit() { + frameReader.clearMessageLengthLimit(); + } + /** Releases an oversized framing buffer once idle; see {@link FrameReader#shrinkIfIdle()}. */ public void shrinkIfIdle() { frameReader.shrinkIfIdle(); diff --git a/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/framing/FrameReader.java b/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/framing/FrameReader.java index 802aceab..859be6da 100644 --- a/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/framing/FrameReader.java +++ b/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/framing/FrameReader.java @@ -54,6 +54,8 @@ public final class FrameReader { private static final int MIN_READ_CHUNK = 32 * 1024; private final long maxMessageLength; + // maxMessageLength, or a tighter limit set for a phase of the connection (see limitMessageLength). + private long messageLengthLimit; private byte[] buf; private int start; private int end; @@ -75,9 +77,20 @@ public FrameReader(long maxMessageLength) { throw new IllegalArgumentException("maxMessageLength must be >= 0: " + maxMessageLength); } this.maxMessageLength = maxMessageLength; + this.messageLengthLimit = maxMessageLength; this.buf = new byte[DEFAULT_CAPACITY]; } + /** Applies {@code limit} on top of the configured maximum until {@link #clearMessageLengthLimit()}. */ + public void limitMessageLength(long limit) { + messageLengthLimit = maxMessageLength == UNLIMITED ? limit : Math.min(maxMessageLength, limit); + } + + /** Restores the configured maximum message length. */ + public void clearMessageLengthLimit() { + messageLengthLimit = maxMessageLength; + } + public void feed(byte[] data) { feed(data, 0, data.length); } @@ -183,8 +196,8 @@ private boolean fill(boolean typed, Frame into) { if (length < 4) { throw new ProtocolException("invalid frame length prefix: " + length); } - if (maxMessageLength != UNLIMITED && length > maxMessageLength) { - throw new ProtocolException("frame length " + length + " exceeds max message length " + maxMessageLength); + if (messageLengthLimit != UNLIMITED && length > messageLengthLimit) { + throw new ProtocolException("frame length " + length + " exceeds max message length " + messageLengthLimit); } // Compute in long: a typed frame with length 0x7FFFFFFF would overflow (1 + MAX_VALUE) to a // negative int, bypassing the short-read guard below and allocating a ~2 GiB payload from a diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java index 5e9c7175..1b1f7e93 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java @@ -57,6 +57,13 @@ public final class StartupOrchestrator implements AuthExchange { */ private static final int MAX_STARTUP_MESSAGES = 2 * MAX_STARTUP_PARAMETERS + 1024; + /** + * Message length limit until AuthenticationOk, so a peer that has authenticated nothing cannot + * make the driver buffer up to the configured maximum. libpq refuses a message of a type outside + * VALID_LONG_MESSAGE_TYPE longer than 30000 bytes; none of the pre-authentication types is one. + */ + private static final int MAX_PRE_AUTH_MESSAGE_LENGTH = 30000; + private final WireChannel channel; private final PgConnectionConfig config; private final HostAndPort host; @@ -116,6 +123,7 @@ public StartupResult run() { // cleanup() zeroes any driver-owned secret the authenticator holds across calls (the SCRAM // exchange); the finally guarantees it runs on a failed login too, not only on success. int messages = 0; + channel.limitMessageLength(MAX_PRE_AUTH_MESSAGE_LENGTH); try { while (true) { if (++messages > MAX_STARTUP_MESSAGES) { @@ -125,6 +133,7 @@ public StartupResult run() { BackendMessage message = readNext(); switch (message) { case AuthenticationRequest.Ok ignored -> { + channel.clearMessageLengthLimit(); authenticator.authenticationOk(); // authentication succeeded; enforce require_auth for the trust (no-credential) case if (!credentialRequested) { @@ -169,6 +178,7 @@ public StartupResult run() { } } } finally { + channel.clearMessageLengthLimit(); authenticator.cleanup(); } } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/WireChannel.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/WireChannel.java index a535e16c..fc1542e5 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/WireChannel.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/WireChannel.java @@ -165,6 +165,16 @@ public void shrinkReadBuffer() { decoder.shrinkIfIdle(); } + /** Caps inbound messages at {@code limit} bytes, within the configured maximum, until cleared. */ + public void limitMessageLength(long limit) { + decoder.limitMessageLength(limit); + } + + /** Restores the configured maximum inbound message length. */ + public void clearMessageLengthLimit() { + decoder.clearMessageLengthLimit(); + } + /** Whether this connection is running over TLS. */ public boolean isTls() { return transport instanceof TlsTransport; From 01072a673e1dfddf6a95a9d5265fd2f8fea6630a Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 17:00:44 +0000 Subject: [PATCH 142/150] test(core): cover the message length limit before authentication --- .../client/core/StartupOrchestratorTest.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java index 8736dd71..1271ab98 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java @@ -143,6 +143,25 @@ void channelBindingRequireRejectsTrustOk() { assertTrue(e.getMessage().contains("channelBinding=require"), e.getMessage()); } + @Test + void aLongMessageBeforeAuthenticationIsRefused() { + String longText = "x".repeat(40_000); + MockServer server = new MockServer().onStartup((s, frame) -> s.send(BackendWire.noticeResponse(longText))); + PgConnectionException e = assertThrows(PgConnectionException.class, () -> run(server, config())); + assertTrue(e.getMessage().contains("exceeds max message length 30000"), e.getMessage()); + } + + @Test + void aLongMessageAfterAuthenticationIsAccepted() { + String longValue = "x".repeat(40_000); + MockServer server = new MockServer() + .onStartup((s, frame) -> s.send( + BackendWire.authenticationOk(), + BackendWire.parameterStatus("long_setting", longValue), + BackendWire.readyForQuery('I'))); + assertEquals(longValue, run(server, config()).parameters().get("long_setting")); + } + @Test void endlessStartupMessagesAreRefused() { byte[][] notices = new byte[10_000][]; From 801d1b5a5638c8141d27f69096b953cc2d7885eb Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 17:01:06 +0000 Subject: [PATCH 143/150] fix(jdbc): do not record a stack trace for each server warning --- .../client/jdbc/PgSqlExceptions.java | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSqlExceptions.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSqlExceptions.java index e5380ed0..189bceef 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSqlExceptions.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSqlExceptions.java @@ -105,7 +105,24 @@ private static String withDetailAndHint(String message, PgServerMessage server) /** Converts a core notice into a JDBC {@link SQLWarning}. */ static SQLWarning toWarning(PgNotice notice) { - return new SQLWarning(notice.message(), notice.sqlState()); + return new ServerWarning(notice.message(), notice.sqlState()); + } + + /** + * A warning the server sent, not one the driver raised, so the reading thread's stack means + * nothing; and getWarnings can build thousands of them per call. + */ + private static final class ServerWarning extends SQLWarning { + private static final long serialVersionUID = 1L; + + ServerWarning(String message, String sqlState) { + super(message, sqlState); + } + + @Override + public Throwable fillInStackTrace() { + return this; + } } /** Chains the notices from index {@code from} onward into a SQLWarning list (null when empty). */ From 2ad0dc17bbc618a788c3ba9c8e6d1eb1f63149a8 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 17:01:29 +0000 Subject: [PATCH 144/150] test(jdbc): pin that server warnings carry no stack trace --- .../postgresql/client/jdbc/PgSqlExceptionsTest.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSqlExceptionsTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSqlExceptionsTest.java index 57c17baa..a7927453 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSqlExceptionsTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSqlExceptionsTest.java @@ -19,6 +19,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.postgresql.client.core.PgException; +import org.postgresql.client.core.PgNotice; import org.postgresql.client.core.PgServerMessage; import org.postgresql.client.core.PgTimeoutException; @@ -189,4 +190,15 @@ void resetRestoresTheDefaultMapping() { SQLIntegrityConstraintViolationException.class, PgSqlExceptions.wrap(serverError("23505", "duplicate key"))); } + + @Test + void serverWarningsCarryNoStackTrace() { + PgNotice notice = new PgNotice(new PgServerMessage( + "WARNING", "WARNING", "01000", "careful", null, null, null, null, null, null, null, null, null, null, + null, null, null, null)); + java.sql.SQLWarning warning = PgSqlExceptions.toWarning(notice); + assertEquals("careful", warning.getMessage()); + assertEquals("01000", warning.getSQLState()); + assertEquals(0, warning.getStackTrace().length); + } } From f558009af627c5b8e4ec2794dd48ca19edde43e2 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 17:17:01 +0000 Subject: [PATCH 145/150] fix(core): let the server reject statements in an aborted transaction The driver refused every statement once the transaction failed, ROLLBACK included. Under autocommit, after the caller's own BEGIN, rollback() is refused too, so the session could not recover. The refusal also carried no SQLSTATE, so JDBC reported it as a connection failure; the server's 25P02 is an ordinary error. Autosave recovery is unchanged. --- .../client/core/CoreConnection.java | 47 +++++++++---------- 1 file changed, 21 insertions(+), 26 deletions(-) diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java b/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java index 94485ce8..1de03bf7 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java @@ -233,7 +233,7 @@ public void invalidateTypes() { public PgResultStream execute(String sql) { requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); invalidateCachesForSessionCommand(sql); ensureTransactionOpen(); return sendArmed(disarm -> { @@ -293,7 +293,7 @@ public PgResultStream execute(String sql, List parameters, int fetchSize) { } requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); invalidateCachesForSessionCommand(sql); ensureTransactionOpen(); return statementCache != null @@ -327,7 +327,7 @@ public PgPipeline pipeline() { } requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); ensureTransactionOpen(); claimWire(); try { @@ -691,7 +691,7 @@ public CorePreparedStatement prepare(String sql, int[] declaredParameterOids) { PgResultStream executePrepared(CorePreparedStatement statement, List parameters, int fetchSize) { requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); ensureTransactionOpen(); return executePreparedInternal(statement, parameters, fetchSize); } @@ -758,7 +758,7 @@ private static int[] columnTypeOids(RowMetadata metadata) { public long[] executeBatch(String sql, List parameterSets, int window) { requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); ensureTransactionOpen(); if (parameterSets.isEmpty()) { return new long[0]; @@ -962,7 +962,7 @@ private int fillWindow(String name, int[] profile) { public long[] executeMultiStatementBatch(List sqls, List> parameterSets) { requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); ensureTransactionOpen(); int chunks = sqls.size(); long[] counts = new long[chunks]; @@ -1514,7 +1514,7 @@ public void unlinkLargeObject(long oid) { byte @Nullable [] fastpathCall(int functionOid, byte[][] arguments) { requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); ensureTransactionOpen(); beginConversation(new FunctionCall( functionOid, new int[] {ProtocolConstants.FORMAT_BINARY}, arguments, ProtocolConstants.FORMAT_BINARY)); @@ -1542,7 +1542,7 @@ public void unlinkLargeObject(long oid) { public PgCopyOutStream copyOut(String sql) { requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); ensureTransactionOpen(); beginConversation(new Query(sql)); try { @@ -1560,7 +1560,7 @@ public PgCopyOutStream copyOut(String sql) { public PgCopyInStream copyIn(String sql) { requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); ensureTransactionOpen(); beginConversation(new Query(sql)); try { @@ -1633,7 +1633,7 @@ public boolean isValid(Duration timeout) { * nothing in the transaction to protect yet, and a preceding {@code SAVEPOINT} would both make * {@code SET TRANSACTION ISOLATION LEVEL} non-first and put it in a subtransaction, which the * server rejects (pgjdbc #3307; pgjdbc-suite AutoSaveTransactionSettingsTest). A first - * statement that fails aborts an empty transaction, which {@link #requireUsableTransaction} + * statement that fails aborts an empty transaction, which {@link #recoverAutosave} * recovers by rolling back outright. */ private void ensureTransactionOpen() { @@ -1654,27 +1654,22 @@ private void ensureTransactionOpen() { } /** - * Guards data statements in the aborted-transaction state (C13.2): rolls back to the internal - * autosave savepoint to recover when {@link Autosave#ALWAYS} is on, otherwise rejects the - * command until the caller rolls back. + * Under {@link Autosave#ALWAYS}, recovers an aborted transaction before the next statement by + * rolling back to the internal autosave savepoint (C13.2). Otherwise the statement goes to the + * server, which refuses it with 25P02 or, for ROLLBACK and the like, ends the block. */ - private void requireUsableTransaction() { - if (transactionStatus != TransactionStatus.FAILED) { + private void recoverAutosave() { + if (transactionStatus != TransactionStatus.FAILED || config.autosave() != Autosave.ALWAYS) { return; } - if (config.autosave() == Autosave.ALWAYS) { - if (autosaveActive) { - runCommand("ROLLBACK TO SAVEPOINT pg_java_autosave"); - return; - } - // The failed statement was the transaction's first (no savepoint is installed before - // it; see ensureTransactionOpen): the transaction is empty, so recover by rolling it - // back outright -- ensureTransactionOpen reopens it for the statement about to run. - runCommand("ROLLBACK"); + if (autosaveActive) { + runCommand("ROLLBACK TO SAVEPOINT pg_java_autosave"); return; } - throw new PgException( - "current transaction is aborted: roll back (or to a savepoint) before issuing further commands"); + // The failed statement was the transaction's first (no savepoint is installed before + // it; see ensureTransactionOpen): the transaction is empty, so recover by rolling it + // back outright -- ensureTransactionOpen reopens it for the statement about to run. + runCommand("ROLLBACK"); } /** Runs a transaction/session control command via the simple protocol and updates the status. */ From 576e8143d58a10f1278c798a7fe5606103139aa7 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 17:17:05 +0000 Subject: [PATCH 146/150] docs: rename requireUsableTransaction in life-of-a-query --- docs/life-of-a-query.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/life-of-a-query.md b/docs/life-of-a-query.md index d55a340c..690813d5 100644 --- a/docs/life-of-a-query.md +++ b/docs/life-of-a-query.md @@ -114,7 +114,8 @@ never buffers. The buffering is a JDBC-layer policy applied on top of it. `CoreConnection.execute(String)` is the native entry point: ```java -requireOpen(); requireIdle(); requireUsableTransaction(); // connection-busy contract (ADR-0005) +requireOpen(); requireIdle(); // connection-busy contract (ADR-0005) +recoverAutosave(); // autosave=always: undo a failed statement invalidateCachesForSessionCommand(sql); // SET search_path / DISCARD / DEALLOCATE ALL ensureTransactionOpen(); // lazy BEGIN when autocommit is off return sendArmed(disarm -> { // arms the query timeout, un-busies on a failed send From 29bb1ae0c1e5a1428bcc2de8c42192090a22e255 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 17:18:00 +0000 Subject: [PATCH 147/150] test(jdbc): cover ending a failed BEGIN block under autocommit --- .../ManualTransactionUnderAutocommitIT.java | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/ManualTransactionUnderAutocommitIT.java diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/ManualTransactionUnderAutocommitIT.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/ManualTransactionUnderAutocommitIT.java new file mode 100644 index 00000000..5d89378f --- /dev/null +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/ManualTransactionUnderAutocommitIT.java @@ -0,0 +1,78 @@ +package org.postgresql.client.jdbc.it; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLNonTransientConnectionException; +import java.sql.Statement; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Under autocommit a caller may still open a transaction block with BEGIN. Once a statement in it + * fails, rollback() is refused (autocommit is on), so a typed ROLLBACK, COMMIT or END must reach + * the server and end the block, and anything else gets the server's own 25P02. + */ +class ManualTransactionUnderAutocommitIT extends AbstractJdbcPostgresIT { + + private static void failInsideBegin(Statement st) { + assertThrows(SQLException.class, () -> { + st.execute("begin"); + st.execute("select 1 / 0"); + }); + } + + private static void assertUsable(Statement st) throws SQLException { + try (ResultSet rs = st.executeQuery("select 1")) { + assertTrue(rs.next()); + assertEquals(1, rs.getInt(1)); + } + } + + @ParameterizedTest + @ValueSource(strings = {"rollback", "abort", "commit", "end"}) + void aTypedCommandEndsTheFailedBlock(String command) throws SQLException { + try (Connection con = connect(); + Statement st = con.createStatement()) { + failInsideBegin(st); + st.execute(command); + assertUsable(st); + } + } + + @ParameterizedTest + @ValueSource(strings = {"rollback", "commit"}) + void aPreparedCommandEndsTheFailedBlock(String command) throws SQLException { + try (Connection con = connect(); + Statement st = con.createStatement()) { + failInsideBegin(st); + try (PreparedStatement ps = con.prepareStatement(command)) { + ps.execute(); + } + assertUsable(st); + } + } + + @ParameterizedTest + @ValueSource(strings = {"select 1", "savepoint s1"}) + void otherStatementsGetTheServerError(String sql) throws SQLException { + try (Connection con = connect(); + Statement st = con.createStatement()) { + failInsideBegin(st); + SQLException e = assertThrows(SQLException.class, () -> st.execute(sql)); + // An aborted transaction is not a broken connection: a pool must not evict it. + assertEquals("25P02", e.getSQLState()); + assertFalse( + e instanceof SQLNonTransientConnectionException, + e.getClass().getName()); + st.execute("rollback"); + assertUsable(st); + } + } +} From 534c1573aeb328edb817dc3e1ab2ce88f419509d Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 17:39:35 +0000 Subject: [PATCH 148/150] test(core): load the encrypted client key from an openssl-made fixture The test encrypted the key at runtime and re-wrapped the cipher's parameters as generic PBES2. On JDK 25 that drops the PRF, so the key decoded as PBEWithHmacSHA1AndAES_256 and would not decrypt. The driver reads openssl's output fine on both JDKs. --- .../core/SslMaterialsClientKeyTest.java | 66 ++----------------- .../test/resources/tls/test-client-enc.key | 37 +++++++++++ .../src/test/resources/tls/test-client.key | 4 +- 3 files changed, 43 insertions(+), 64 deletions(-) create mode 100644 postgresql-client/src/test/resources/tls/test-client-enc.key diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/SslMaterialsClientKeyTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/SslMaterialsClientKeyTest.java index a3fb16ba..4cb165b7 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/SslMaterialsClientKeyTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/SslMaterialsClientKeyTest.java @@ -1,6 +1,5 @@ package org.postgresql.client.core; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -12,13 +11,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.security.AlgorithmParameters; -import java.util.Base64; -import javax.crypto.Cipher; -import javax.crypto.EncryptedPrivateKeyInfo; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; import javax.net.ssl.KeyManager; import javax.net.ssl.X509KeyManager; import org.junit.jupiter.api.BeforeAll; @@ -35,8 +27,8 @@ *

    The certificate and matching plaintext key are small throwaway self-signed test-only * materials checked in under {@code src/test/resources/tls/} (generated offline with openssl, * expiring far in the future); an X.509 certificate cannot be minted with public JDK APIs. - * The encrypted-key variants are derived from the plaintext key at runtime with JDK crypto - * (PBES2), so the passphrase paths need no extra checked-in secrets. The end-to-end + * The encrypted variant ({@code test-client-enc.key}) is the same key encrypted by openssl with + * PBES2, the format users actually have; its header holds the passphrase and command. The end-to-end * counterpart against a {@code clientcert}-enforcing server is {@code TlsNegativeMatrixIT}. */ class SslMaterialsClientKeyTest { @@ -54,13 +46,13 @@ class SslMaterialsClientKeyTest { static void materializeTestMaterials() throws Exception { certFile = copyResource("/tls/test-client.crt", "client.crt"); keyFile = copyResource("/tls/test-client.key", "client.key"); - encryptedKeyFile = writeEncryptedCopy(keyFile, PASSPHRASE, "client-enc.key"); + encryptedKeyFile = copyResource("/tls/test-client-enc.key", "client-enc.key"); } /** * Copies a classpath PEM resource to a plain file, dropping the {@code #} comment header. * The driver tolerates the header ({@link #pemFilesWithLeadingCommentaryLoadDirectly} - * proves it); the stripped copy keeps this class's own {@link #decodePem} helper simple. + * proves it); the other tests use the stripped copy. */ private static Path copyResource(String resource, String name) throws IOException { try (InputStream in = SslMaterialsClientKeyTest.class.getResourceAsStream(resource)) { @@ -83,41 +75,6 @@ private static Path copyRawResource(String resource, String name) throws IOExcep } } - /** - * Encrypts the plaintext PKCS#8 key under {@code passphrase} with PBES2 - * (PBKDF2-HmacSHA256 + AES-256-CBC, what modern openssl emits) using only public JDK - * APIs, and writes it as a {@code BEGIN ENCRYPTED PRIVATE KEY} PEM file. - */ - private static Path writeEncryptedCopy(Path plainKey, String passphrase, String name) throws Exception { - byte[] plainDer = decodePem(Files.readString(plainKey, StandardCharsets.US_ASCII)); - String algorithm = "PBEWithHmacSHA256AndAES_256"; - SecretKey secret = - SecretKeyFactory.getInstance(algorithm).generateSecret(new PBEKeySpec(passphrase.toCharArray())); - Cipher cipher = Cipher.getInstance(algorithm); - cipher.init(Cipher.ENCRYPT_MODE, secret); - byte[] encrypted = cipher.doFinal(plainDer); - // Re-house the cipher's parameters under the generic PBES2 name so the JDK can map - // them to the PBES2 OID when encoding the EncryptedPrivateKeyInfo structure. - AlgorithmParameters params = AlgorithmParameters.getInstance("PBES2"); - params.init(cipher.getParameters().getEncoded()); - byte[] der = new EncryptedPrivateKeyInfo(params, encrypted).getEncoded(); - StringBuilder pem = new StringBuilder("-----BEGIN ENCRYPTED PRIVATE KEY-----\n"); - pem.append(Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(der)); - pem.append("\n-----END ENCRYPTED PRIVATE KEY-----\n"); - return Files.writeString(tempDir.resolve(name), pem.toString(), StandardCharsets.US_ASCII); - } - - private static byte[] decodePem(String text) { - StringBuilder base64 = new StringBuilder(); - for (String line : text.split("\\R")) { - String trimmed = line.trim(); - if (!trimmed.isEmpty() && !trimmed.startsWith("-----")) { - base64.append(trimmed); - } - } - return Base64.getDecoder().decode(base64.toString()); - } - /** Asserts the key managers actually expose the client key and its certificate chain. */ private static void assertHoldsClientCredentials(KeyManager[] keyManagers) { assertNotNull(keyManagers, "key managers must be built when client cert material is configured"); @@ -231,19 +188,4 @@ void missingKeyFileFailsClosed() { .build(); assertThrows(PgTlsException.class, () -> SslMaterials.keyManagers(ssl)); } - - @Test - void jdkEncryptedVariantRoundTripsSanityCheck() throws Exception { - // Guard for the helper itself: the runtime-encrypted PEM must decrypt back to the - // exact plaintext PKCS#8 bytes with plain JDK crypto, independent of SslMaterials. - byte[] plainDer = decodePem(Files.readString(keyFile, StandardCharsets.US_ASCII)); - byte[] encDer = decodePem(Files.readString(encryptedKeyFile, StandardCharsets.US_ASCII)); - EncryptedPrivateKeyInfo info = new EncryptedPrivateKeyInfo(encDer); - SecretKey secret = SecretKeyFactory.getInstance(info.getAlgName()) - .generateSecret(new PBEKeySpec(PASSPHRASE.toCharArray())); - Cipher cipher = Cipher.getInstance(info.getAlgName()); - cipher.init(Cipher.DECRYPT_MODE, secret, info.getAlgParameters()); - byte[] decrypted = info.getKeySpec(cipher).getEncoded(); - assertArrayEquals(plainDer, decrypted); - } } diff --git a/postgresql-client/src/test/resources/tls/test-client-enc.key b/postgresql-client/src/test/resources/tls/test-client-enc.key new file mode 100644 index 00000000..648183e4 --- /dev/null +++ b/postgresql-client/src/test/resources/tls/test-client-enc.key @@ -0,0 +1,37 @@ +# Throwaway TEST-ONLY encrypted PKCS#8 copy of test-client.key for +# SslMaterialsClientKeyTest. The passphrase is correct-horse-battery. Made with: +# openssl pkcs8 -topk8 -in test-client.key -out test-client-enc.key \ +# -v2 aes-256-cbc -v2prf hmacWithSHA256 -iter 2048 +# (PBES2: PBKDF2-HmacSHA256 + AES-256-CBC, what modern openssl emits). Checked in +# rather than encrypted at runtime: re-encoding PBES2 parameters through the JDK +# loses the PRF on JDK 25, which made the test key unreadable there. +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQUYD51sSBDnWou2QL +QNYpDAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEAdoWYtGg20zB1OR +q+hI5WoEggTQ/hrmbQEP/8j4NikPiBYLB/QAeDCBs871yECgmSOo5+nrXoJm2/ue +UMrKzAasJ6XjPN4mv8vO12vaotAEqwmJHrqM3Rxv1L4chykmIj+LV2O9Z8aAV2Nx +lILTOMhHrGnMjF1xNVViOvnHY8Ww3whXhRoeuLHP3DKsY06LZLazB7WcVYP8/Jyb +k/ncwg3uyLAILTMahTsp1FKQhLySl5rADVSkWhPcaoLj/XqLv7GAvH67fFgzHG0T +XCT9a6Pb8Bw+HR9OhnuzlIVQPe+mNw6y9LaNlAOhxxzIPDfzwmO+vDkoooDaWbdy +RduBIl+hEp1aQaVimvkoc84NsFreqjjlBLtJOfCKhqdWQUlEw7r/RWQCt63bUJGP +habDh1keWidtquh0y37SAfbpBcYuf3VMafReqZExA8jqC10AgosAQOeDyTls516c +d26OX5rE4slTZDurMJB+9EdIJ4KJRNVqrusf7YU8ZN1nxr7JbXRxuju8Rb9sQVN7 +ncL3sZ6FskSH+zi2uDh9QIYqz90CrVhTk8Lf3lbu710n/1bGmUY7whYF7CtmNNTk +3ML58NoNTx/75d32cUcpC4TG6rXvh55SiSE6C2mfwA2nGX7RvY6PB/VJAl2lWGzs +iVbl4Xc71b+FaROfZKkEC8MlIJGs0O3JmqZ/rl5M5QwHBo/vDAVWMbfHm/LZS3PM +gheNQ+GHh1rnTD5Pxk+JEUfH+7+sZh25jYNy7Jq63CM31LsH2xKEuUlOjql5a4mR +J8MkW/KZpmzFpTOcKV5I064AkjK/KyTkUpRrHt/n9/8E02x5IqytXCBuSU+DsJBr +dAB4M/LN/THxI0UVZz8lblPvK96qVJg/QNFdy0vmCd/qnRWJ8wn6BOAAzy6JvinQ +fFjS1xpuh2u6P5C62gR+UOx9ar5mJ4hURBmbqowAyuVhKDA3M6j+la/atnAn2doz +ajj102nTm2dL4lgSc26IlGzIuO9CHMqKUdiILGZLQlHUuLiby1d5skuKsh51cNJv +SQH/UO2is8ZpG4ErYjYT9nxI9nMppQTFSmEY/A614PX8hsBgaCteOKKWW/YGnrHg +s8cKq9vQR5H7uUr6WyskPlwa2uM4FWBQ/ym73q7E3ZznIKz7PE80csalpv3LxQTV +fESLLCacZ7KdAB2RXX5I7pkVFLNb0MBC7wFdFSqfFVLTL+3rnNEzgXdxory9B7QJ +GKRVQYtHZSZ5baUaHr7GWuWWkVDDEzBXyzjnXZuuNyeH5ioeMA4ar89Ew40+VqkR +NtMjWzHCge6TODl7k8/O+nTfa4NdMcHDyw6sLh4e0+aBFXeDqnfj1WfGSHF1CrBJ +X6IsywNbF+xjFrbPU7iluBfrudMJ7YNIJ9RMm6xw3MB74qSov1HKQG8KX7JpPVH/ +CAOsat6QAbUeARZAdcXf5HCgRESOBjq7sJ/PAnh3a6TwE7t539nlDes75q2NAqN1 +ri0MYYyvLFq9kWuuhatywNJRqBqY5tfcL9q/4mQtQv4JH4bJdEcugq8ByiTyo4Q1 +6xFWML8TxV7LUVuzaHFYj6Ydl7FZ+MBKWz3kjU1CzlCN0GBSPM2sVHKpLYZYu+W3 +99mN77xHp9cLtEVvhzWjpVtwcnn6ZvBFht4fRq+SIadVsVGyYPTHewg= +-----END ENCRYPTED PRIVATE KEY----- diff --git a/postgresql-client/src/test/resources/tls/test-client.key b/postgresql-client/src/test/resources/tls/test-client.key index 583f59a0..8131d9bb 100644 --- a/postgresql-client/src/test/resources/tls/test-client.key +++ b/postgresql-client/src/test/resources/tls/test-client.key @@ -1,7 +1,7 @@ # Throwaway TEST-ONLY plaintext PKCS#8 private key for SslMaterialsClientKeyTest. # It matches test-client.crt, protects nothing, and was generated offline with -# openssl (see the header of test-client.crt for the exact command). The tests -# derive the encrypted-key variants from this key at runtime with JDK crypto. +# openssl (see the header of test-client.crt for the exact command). +# test-client-enc.key is this key encrypted with a passphrase. # The driver tolerates this comment header (text outside the PEM envelope is # skipped, like libpq), and the tests feed this file both raw and stripped. -----BEGIN PRIVATE KEY----- From 9018c3998ddf41197c2d4b74b6ab96354a22cef9 Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 13:01:03 -0500 Subject: [PATCH 149/150] test(core): report full JFR detail when the pinning IT fails VirtualThreadPinningIT keeps failing on JDK 25 and its report cut each stack to eight frames with no event fields, which is not enough to tell where the pin comes from. On failure it now reports every field the running JDK records for jdk.VirtualThreadPinned (pinning reason, blocking operation, duration, threads where present, and says which are absent), the full stack with line, bci and frame type plus whether JFR truncated it, and the JVM version. The failsafe argLine raises the JFR stack depth to 128 frames. The recording is now dumped under target/jfr and kept when the test fails, and the integration jobs upload it as an artifact on failure. Diagnostics only: the workload, event filter and assertion are unchanged. --- .github/workflows/ci.yml | 22 ++++ pom.xml | 8 +- .../core/it/VirtualThreadPinningIT.java | 120 ++++++++++++++++-- 3 files changed, 139 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 82cbc6ed..42521eb4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -130,6 +130,14 @@ jobs: cache: maven - name: Integration tests (Testcontainers) run: ./mvnw -B -ntp verify -Pintegration-tests -Dpg.it.image=postgres:${{ matrix.pg }} + # VirtualThreadPinningIT keeps its JFR recording under target/jfr only when it fails. + - name: Upload pinning JFR recording + if: failure() + uses: actions/upload-artifact@v4 + with: + name: pinning-jfr-postgres-${{ matrix.pg }} + path: postgresql-client/target/jfr/*.jfr + if-no-files-found: ignore # One integration leg on the current LTS. The server matrix above sweeps PostgreSQL # versions on the JDK floor; this sweeps the other axis once, so JDK-dependent @@ -150,6 +158,13 @@ jobs: cache: maven - name: Integration tests (Testcontainers) run: ./mvnw -B -ntp verify -Pintegration-tests -Dpg.it.image=postgres:17 + - name: Upload pinning JFR recording + if: failure() + uses: actions/upload-artifact@v4 + with: + name: pinning-jfr-jdk25 + path: postgresql-client/target/jfr/*.jfr + if-no-files-found: ignore # Protocol 3.2 (PG18) is a distinct negotiation path -- StartupMessage requests 3.2, # the server may answer NegotiateProtocolVersion, and the cancellation key becomes @@ -172,3 +187,10 @@ jobs: ./mvnw -B -ntp verify -Pintegration-tests -Dpg.it.image=postgres:18 -Dpg.it.protocolVersion=latest + - name: Upload pinning JFR recording + if: failure() + uses: actions/upload-artifact@v4 + with: + name: pinning-jfr-protocol-3-2 + path: postgresql-client/target/jfr/*.jfr + if-no-files-found: ignore diff --git a/pom.xml b/pom.xml index e982d31e..c8acabeb 100644 --- a/pom.xml +++ b/pom.xml @@ -394,9 +394,13 @@ + @{argLine} preserves the JaCoCo integration agent's argLine. + The JFR stack depth (default 64) is a JVM-startup option the + Recording API cannot set; 128 frames keeps the pinning IT's + failure report from cutting off above the driver frames. --> @{argLine} --add-modules jdk.jfr - --add-reads org.postgresql.client.core=jdk.jfr + --add-reads org.postgresql.client.core=jdk.jfr + -XX:FlightRecorderOptions=stackdepth=128 diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/it/VirtualThreadPinningIT.java b/postgresql-client/src/test/java/org/postgresql/client/core/it/VirtualThreadPinningIT.java index 9d159752..df6697eb 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/it/VirtualThreadPinningIT.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/it/VirtualThreadPinningIT.java @@ -13,9 +13,16 @@ import java.util.concurrent.Future; import java.util.stream.Collectors; import jdk.jfr.Recording; +import jdk.jfr.ValueDescriptor; +import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordedFrame; +import jdk.jfr.consumer.RecordedMethod; +import jdk.jfr.consumer.RecordedObject; import jdk.jfr.consumer.RecordedStackTrace; +import jdk.jfr.consumer.RecordedThread; import jdk.jfr.consumer.RecordingFile; +import org.jspecify.annotations.Nullable; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.postgresql.client.core.PgConnection; @@ -60,13 +67,15 @@ class VirtualThreadPinningIT extends AbstractPostgresIT { * {@code max_connections=100} since each task holds its own connection for its lifetime. */ private static final int TASKS = 50; + private static final String PINNED_EVENT = "jdk.VirtualThreadPinned"; + private static final int ROUNDS = 3; private static final int SERIES = 5000; @Test void driverIoDoesNotPinCarriersUnderVirtualThreadLoad() throws Exception { Recording recording = new Recording(); - recording.enable("jdk.VirtualThreadPinned").withThreshold(Duration.ZERO); + recording.enable(PINNED_EVENT).withThreshold(Duration.ZERO); recording.start(); try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { @@ -80,21 +89,37 @@ void driverIoDoesNotPinCarriersUnderVirtualThreadLoad() throws Exception { } recording.stop(); - Path dump = Files.createTempFile("vthread-pinning", ".jfr"); + // Dumped under the module's target/ (failsafe's working directory) rather than the system + // temp dir, so a failing run leaves the recording where CI uploads it as an artifact. + Path dumpDir = Files.createDirectories(Path.of("target", "jfr")); + Path dump = Files.createTempFile(dumpDir, "virtual-thread-pinning-", ".jfr"); + boolean passed = false; try { recording.dump(dump); + List allPins = new ArrayList<>(); List driverPins = new ArrayList<>(); for (RecordedEvent event : RecordingFile.readAllEvents(dump)) { + if (PINNED_EVENT.equals(event.getEventType().getName())) { + allPins.add(event); + } if (pinnedInDriverTransport(event)) { driverPins.add(event); } } assertTrue( driverPins.isEmpty(), - () -> "the driver transport pinned a carrier thread " + driverPins.size() + " time(s):\n" + () -> "the driver transport pinned a carrier thread " + driverPins.size() + " time(s)" + + " (" + allPins.size() + " " + PINNED_EVENT + " event(s) recorded in total)\n" + + describeJvm() + "\n" + + " recording kept at: " + dump.toAbsolutePath() + "\n" + describe(driverPins)); + passed = true; } finally { - Files.deleteIfExists(dump); + if (passed) { + Files.deleteIfExists(dump); + } else { + System.err.println("VirtualThreadPinningIT: JFR recording kept at " + dump.toAbsolutePath()); + } recording.close(); } } @@ -130,11 +155,88 @@ private static String describe(List pins) { return pins.stream().map(VirtualThreadPinningIT::describeEvent).collect(Collectors.joining("\n --\n")); } + private static String describeJvm() { + return " jvm: " + System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version") + + " (" + System.getProperty("java.vm.vendor") + ", vm " + System.getProperty("java.vm.version") + + ", " + System.getProperty("os.name") + " " + System.getProperty("os.arch") + ")"; + } + + /** + * Reports every field the running JDK recorded for the event, not a fixed list: the field set of + * {@code jdk.VirtualThreadPinned} varies by release (newer JDKs record more, such as the pinning + * reason, blocking operation and carrier thread), so a fixed list would either miss data on a newer + * JDK or fail on an older one. The fields this test most wants are also named when absent, so a + * report from an older JDK says so rather than silently omitting them. + */ private static String describeEvent(RecordedEvent event) { - return event.getStackTrace().getFrames().stream() - .limit(8) - .map(frame -> " at " + frame.getMethod().getType().getName() + "." - + frame.getMethod().getName()) - .collect(Collectors.joining("\n")); + StringBuilder out = new StringBuilder(); + out.append(" event: ").append(event.getEventType().getName()); + if (event.getEventType().getLabel() != null) { + out.append(" (").append(event.getEventType().getLabel()).append(')'); + } + out.append('\n'); + for (ValueDescriptor field : event.getFields()) { + if (field.getName().equals("stackTrace")) { + continue; + } + out.append(" ").append(field.getName()); + if (field.getLabel() != null) { + out.append(" [").append(field.getLabel()).append(']'); + } + out.append(": ") + .append(describeValue(event.getValue(field.getName()))) + .append('\n'); + } + for (String expected : new String[] {"pinnedReason", "blockingOperation", "carrierThread"}) { + if (!event.hasField(expected)) { + out.append(" ").append(expected).append(": \n"); + } + } + RecordedStackTrace stack = event.getStackTrace(); + if (stack == null) { + out.append(" stackTrace: "); + return out.toString(); + } + out.append(" stackTrace (") + .append(stack.getFrames().size()) + .append(" frame(s)") + .append(stack.isTruncated() ? ", TRUNCATED by the JFR stack depth limit" : "") + .append("):\n"); + out.append(stack.getFrames().stream() + .map(VirtualThreadPinningIT::describeFrame) + .collect(Collectors.joining("\n"))); + return out.toString(); + } + + private static String describeValue(@Nullable Object value) { + if (value instanceof RecordedThread thread) { + return "javaName=" + thread.getJavaName() + + ", javaThreadId=" + thread.getJavaThreadId() + + ", virtual=" + thread.isVirtual() + + ", osName=" + thread.getOSName() + + ", osThreadId=" + thread.getOSThreadId(); + } + if (value instanceof RecordedClass type) { + return type.getName(); + } + if (value instanceof RecordedObject object) { + return object.toString().replace("\n", " ").replaceAll("\\s+", " ").trim(); + } + return String.valueOf(value); + } + + private static String describeFrame(RecordedFrame frame) { + RecordedMethod method = frame.getMethod(); + String where; + if (method == null) { + where = ""; + } else { + String type = method.getType() == null + ? "" + : method.getType().getName(); + where = type + "." + method.getName() + method.getDescriptor(); + } + return " at " + where + " (line " + frame.getLineNumber() + ", bci " + frame.getBytecodeIndex() + ", " + + frame.getType() + ")"; } } From 6a9b735600a567be71d81befa5a4d2424c8ecc5b Mon Sep 17 00:00:00 2001 From: Sehrope Sarkuni Date: Sun, 29 Nov 2026 13:16:15 -0500 Subject: [PATCH 150/150] test(core): warm up the JDK socket poller before the pinning IT records The recurring JDK 25 failures were all virtual threads waiting on the class initializer of sun.nio.ch.Poller, which the JDK sets up lazily on the first virtual-thread socket park. Fifty threads reaching it at once pin their carriers there (JDK-8369238), which is not a driver pin. Run the same blocking-read workload on one virtual thread before the recording starts so the poller is already initialized. The zero-pin assertion, the event filter and the diagnostics are unchanged. --- .../client/core/it/VirtualThreadPinningIT.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/it/VirtualThreadPinningIT.java b/postgresql-client/src/test/java/org/postgresql/client/core/it/VirtualThreadPinningIT.java index df6697eb..de015454 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/it/VirtualThreadPinningIT.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/it/VirtualThreadPinningIT.java @@ -74,6 +74,16 @@ class VirtualThreadPinningIT extends AbstractPostgresIT { @Test void driverIoDoesNotPinCarriersUnderVirtualThreadLoad() throws Exception { + // The JDK sets up sun.nio.ch.Poller lazily, the first time a virtual thread parks on socket + // I/O. If many virtual threads reach that point at once, all but one wait on the class + // initializer and pin their carriers ("Waited for initialization of sun.nio.ch.Poller by + // another thread"). That is a JDK limitation (JDK-8369238), not a driver pin, so one virtual + // thread runs the same blocking-read workload first to initialize the poller before + // recording starts. + try (ExecutorService warmup = Executors.newVirtualThreadPerTaskExecutor()) { + warmup.submit(VirtualThreadPinningIT::runQueries).get(); + } + Recording recording = new Recording(); recording.enable(PINNED_EVENT).withThreshold(Duration.ZERO); recording.start();