From: artemgavrilov (@artemgavrilov) <noreply+artemgavrilov@github.com>
To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>
Subject: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
Date: Wed, 24 Jun 2026 16:56:05 +0000
Message-ID: <gh-pgjdbc-pgjdbc-4251@github.com> (raw)
### All Submissions:
* [x] Have you followed the guidelines in our [Contributing](https://github.com/pgjdbc/pgjdbc/blob/master/CONTRIBUTING.md) document?
* [x] Have you checked to ensure there aren't other open [Pull Requests](../../pulls) for the same update/change?
<!-- You can erase any parts of this template not applicable to your Pull Request. -->
### New Feature Submissions:
1. [x] Does your submission pass tests?
2. [x] Does `./gradlew styleCheck` pass ?
3. [ ] Have you added your new test classes to an existing test suite in alphabetical order?
### Changes to Existing Features:
* [ ] Does this break existing behaviour? If so please explain.
* [x] Have you added an explanation of what your changes do and why you'd like us to include them?
* [x] Have you written new tests for your core changes, as applicable?
* [x] Have you successfully run tests with your changes locally?
Solves https://github.com/pgjdbc/pgjdbc/issues/3816
This PR adds OAuth bearer authentication support ([RFC 7628](https://datatracker.ietf.org/doc/html/rfc7628)). Two options were added:
1. Static token
2. Token provider class
Authentication via discovery phase skipped as the PR already too big + there are complex topics to discuss regarding discovery info handling. So I'll address discovery in following PRs.
The RFC explicitly requires TLS for token exchange with a sever (see [RFC 7632 §3](https://datatracker.ietf.org/doc/html/rfc7628#section-3)). However PostgreSQL supports also GSSAPI as a transport encryption, so this PR adds these two options as a requirement for OAuth with the option to disable the requirement for testing/development needs. Same topic discussed for [libpq here](https://www.postgresql.org/message-id/CAN4CZFOa0iA3PV=oE0+O=jdZyu_KtS9vGLA+4a7hjAhfzVLAJg@mail.gmail...).
For integration tests I used [real oauth validator](https://github.com/percona/pg_oidc_validator) + keycloak as token provider. But it seems like overkill and I'm pretty sure that you don't want that. Alternative option may be dummy validator implementation just for test needs, but it will require C compiler as dependency, so what do you think?
inline patch 1: .github/workflows/main.yml, .github/workflows/matrix.mjs, CHANGELOG.md and 45 more (+3608/-116 lines) download inline-1.patchdiff --git a/.github/workflows/main.yml b/.github/workflows/main.ymlindex 44ef7bcdf2..e81f46e82c 100644--- a/.github/workflows/main.yml+++ b/.github/workflows/main.yml@@ -150,6 +150,8 @@ jobs:
ACTIONS_STEP_DEBUG: true
ACTIONS_RUNNER_DEBUG: true
TZ: ${{ matrix.tz }}
+ # Enable the docker-compose 'oauth' profile whenever OAuth tests enabled+ COMPOSE_PROFILES: ${{ matrix.oauth != 'no' && 'oauth' || '' }}
steps:
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
with:
@@ -163,6 +165,7 @@ jobs:
XA: ${{ matrix.xa }}
SSL: ${{ matrix.ssl }}
SCRAM: ${{ matrix.scram }}
+ OAUTH: ${{ matrix.oauth }}
CREATE_REPLICAS: ${{ matrix.replication }}
PG_IMAGE: ${{ matrix.pg_version == 'HEAD' && 'pgjdbc/postgres-devel:ci-head' || '' }}
PG_PULL_POLICY: ${{ matrix.pg_version == 'HEAD' && 'build' || 'missing' }}
diff --git a/.github/workflows/matrix.mjs b/.github/workflows/matrix.mjsindex 041e7ffffe..7a2232eec4 100644--- a/.github/workflows/matrix.mjs+++ b/.github/workflows/matrix.mjs@@ -194,6 +194,20 @@ matrix.addAxis({
]
});
+// Available options for oauth:+// no - no infrastructure is started and the OAuth integration tests are skipped+// smoke - start the required infrastructure and run OAuth tests+// all - start the required infrastructure and route all tests through OAuth authentication+matrix.addAxis({+ name: 'oauth',+ title: x => x.value === 'no' ? '' : 'oauth_' + x.value,+ values: [+ {value: 'no', weight: 10},+ {value: 'smoke', weight: 2},+ {value: 'all', weight: 1},+ ]+});+
matrix.addAxis({
name: 'xa',
title: x => (x.value === 'yes' ? '' : 'no_') + 'xa',
@@ -319,10 +333,14 @@ function lessThan(minVersion) {
return value => value === 'HEAD' ? false : Number(value) < Number(minVersion);
}
+function greaterThanOrEqual(version) {+ return value => Number(value) >= Number(version);+}+
matrix.setNamePattern([
'java_version', 'java_distribution', 'pg_version', 'query_mode', 'scram', 'ssl', 'hash', 'os',
'server_tz', 'tz', 'locale',
- 'gss', 'replication', 'slow_tests',+ 'gss', 'oauth', 'replication', 'slow_tests',
'adaptive_fetch', 'rewrite_batch_inserts', 'query_timeout', 'socket_timeout',
'login_timeout', 'connect_timeout',
'autosave', 'cleanupSavepoints', 'cpu_count', 'assertions', 'standard_conforming_strings'
@@ -344,6 +362,21 @@ matrix.imply({java_distribution: {value: 'oracle'}}, {java_version: v => v === e
// TODO: Semeru does not ship Java 21 builds yet
matrix.exclude({java_distribution: {value: 'semeru'}, java_version: '21'})
matrix.imply({gss: {value: 'yes'}}, {os: {value: 'ubuntu-latest'}})
+// The oauth auth method was added in PostgreSQL 18, and the validator the test setup installs+// is built for it as well (pg-oidc-validator-pgdg18.deb, see+// docker/postgres-server/scripts/entrypoint.sh).+matrix.imply({oauth: {value: ['smoke', 'all']}}, {pg_version: greaterThanOrEqual('18')})+// The Keycloak and PostgreSQL containers the test needs are only started on the Docker-based+// (Linux) setup.+matrix.imply({oauth: {value: ['smoke', 'all']}}, {os: {value: 'ubuntu-latest'}})+// OAUTHBEARER must run over TLS (RFC 7628, section 3), so OAuth rows need ssl=yes.+matrix.imply({oauth: {value: ['smoke', 'all']}}, {ssl: {value: 'yes'}})+// "all" oauth mode replaces the test role's authentication with oauth (scoped to the "test"+// database only, see docker/postgres-server/scripts/entrypoint.sh), so it is incompatible with+// tests that authenticate the test user a different way or assume TCP host semantics: GSS+// negotiates its own encryption, and replication tests use the privileged role and compare hosts.+matrix.exclude({oauth: {value: 'all'}, gss: {value: 'yes'}})+matrix.exclude({oauth: {value: 'all'}, replication: {value: 'yes'}})
// ikalnytskyi/action-setup-postgres supports PostgreSQL 14+ only
matrix.exclude({os: {value: ['windows-latest', 'macos-latest']}, pg_version: lessThan('14')});
// HEAD is built from pgdg-snapshot inside Docker, which only runs on Linux.
@@ -383,6 +416,8 @@ const include = matrix.generateRows(Number(process.env.MATRIX_JOBS || 6), {
// slow tests add ~0 coverage but cost runtime; GSS exercises the driver's encryption
// paths and the krb5 setup runs anyway on this Linux job, so keep it on.
slow_tests: {value: 'no'}, gss: {value: 'yes'},
+ // Run the OAuth smoke tests on the coverage job so OAuth code earns PR diff coverage.+ oauth: {value: 'smoke'},
},
tag: row => { row.collectCoverage = true; },
},
@@ -415,6 +450,7 @@ const include = matrix.generateRows(Number(process.env.MATRIX_JOBS || 6), {
...matrix.allAxisValues('os'),
...matrix.allAxisValues('cpu_count'),
...matrix.allAxisValues('assertions'),
+ ...matrix.allAxisValues('oauth'),
],
});
if (include.length === 0) {
@@ -471,6 +507,7 @@ include.forEach(v => {
v.slow_tests = v.slow_tests.value;
v.xa = v.xa.value;
v.gss = v.gss.value;
+ v.oauth = v.oauth.value;
v.ssl = v.ssl.value;
v.scram = v.scram.value;
v.query_mode = v.query_mode.value;
@@ -573,6 +610,14 @@ include.forEach(v => {
testJvmArgs.push('-ea');
}
delete v.assertions;
+ if (v.oauth !== 'no') {+ // Start required infrastructure and run OAuth integration tests+ jvmArgs.push('-Denable_oauth_tests=true');+ }+ if (v.oauth === 'all') {+ // Redirect connections of the default user to OAuth, see TestUtil.addOAuthProperties+ jvmArgs.push('-DauthMode=oauth');+ }
v.extraJvmArgs = jvmArgs.join(' ');
v.testExtraJvmArgs = testJvmArgs.join(' ::: ');
delete v.hash;
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 121da767b5..59d258d162 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,7 +4,11 @@ Notable changes since version 42.0.0, read the complete [History of Changes](htt
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
## [Unreleased]
+### Added+* feat: add OAuth Bearer authentication (OAUTHBEARER SASL, [RFC 7628](https://www.rfc-editor.org/rfc/rfc7628)) for PostgreSQL 18 and later, where the server side `oauth` authentication method was introduced. The application supplies the token, either directly through the new `oauthToken` connection property or through the new `org.postgresql.plugin.OAuthTokenProvider` SPI, whose implementation is named by `oauthTokenProviderClassName` and called once per connection attempt with an `OAuthTokenRequest` carrying `oauthIssuer`, `oauthClientId`, `oauthClientSecret` and `oauthScope`. The driver does not contact the issuer itself, so the OAuth discovery exchange is left for a later release. `requireAuth` accepts `oauth`, and when a server offers OAUTHBEARER alongside SCRAM-SHA-256, setting either token property selects OAUTHBEARER and `password` goes unused; `requireAuth=scram-sha-256` keeps the password path. `channelBinding=require` rules OAUTHBEARER out, since the driver has no channel binding to offer for it. The token is sent only over a connection to a verified server, as RFC 7628, section 3 requires: TLS with `sslmode=verify-ca` or `verify-full`, or GSS encryption, and `sslmode=require` is not enough because it encrypts without checking the server certificate. The new `oauthAllowInsecureConnection=true` lifts that requirement for development and testing and logs a warning instead, and a non-HTTPS `oauthIssuer` is rejected for the same reason unless `oauthAllowInsecureIssuer=true` [Issue #3816](https://github.com/pgjdbc/pgjdbc/issues/3816) [PR #4251](https://github.com/pgjdbc/pgjdbc/pull/4251)+
### Fixed
+* fix: `requireAuth` no longer demands `gss` on every GSS-encrypted connection. Establishing GSS encryption was taken as the authentication that happened, so `requireAuth=oauth` or `requireAuth=scram-sha-256` with `gssEncMode=require` was refused even though the client had authenticated with that method, and `requireAuth=gss` was refused when the server asked for a Kerberos handshake without GSS encryption. As in libpq, an authentication exchange the client completed meets `requireAuth` on its own, and GSS encryption stands in for an AuthenticationGSS request only where the server sends none. A server that authenticates the connection without asking the client for anything is still refused unless `none` is allowed, GSS-encrypted or not [PR #4251](https://github.com/pgjdbc/pgjdbc/pull/4251)
* fix: `PGStream.skip` no longer loops forever when the connection ends while the driver is discarding bytes, and no longer mistakes a stream that skips nothing for one that has ended. `InputStream.skip` may return zero with more data still coming, which a stream supplied through the `socketFactory` property is free to do; the driver now reads a byte in that case and treats only `-1` as the end [PR #4358](https://github.com/pgjdbc/pgjdbc/pull/4358)
* fix: `LargeObjectManager` operations now work inside an active XA transaction. Since 42.7.13 an XA branch keeps the caller's `autoCommit=true`, and the guard rejected large objects as if the connection were idle. It now checks the server transaction state (`getTransactionState()`) instead of `autoCommit`, so a genuine auto-commit connection with no open transaction is still refused [Issue #4309](https://github.com/pgjdbc/pgjdbc/issues/4309) [PR #4310](https://github.com/pgjdbc/pgjdbc/pull/4310)
* fix: batch update counts are no longer secured as committed inside an XA transaction. `BatchResultHandler` treated per-statement progress as durable whenever `autoCommit=true`, but an XA branch keeps `autoCommit=true` while the transaction is open, so a batch that flushed mid-way and then failed could report rolled-back statements as succeeded. Progress is now secured only when no server transaction is open [Issue #4309](https://github.com/pgjdbc/pgjdbc/issues/4309) [PR #4311](https://github.com/pgjdbc/pgjdbc/pull/4311)
@@ -24,6 +28,9 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/).
* fix: the read buffer returns to its initial size once the message that grew it is drained, so a connection no longer retains 32 MiB after one large error [Issue #4015](https://github.com/pgjdbc/pgjdbc/issues/4015)
* fix: exceeding `maxResultBuffer` closes the connection. The row is not read past the limit, so the connection cannot continue, and it is now dropped where the limit is exceeded rather than refused as a protocol violation at the next message. The error reported is the limit alone, with SQLState `08S01` as before [Issue #4015](https://github.com/pgjdbc/pgjdbc/issues/4015)
+### Security+* fix: `oauthToken`, `oauthClientSecret` and `sslpassword` no longer reach the log. `BaseDataSource.getUrl()` built its query string from every connection property that was set, and `Driver.connect` and `BaseDataSource.getConnection` log a URL at `FINE` on both success and failure, so a credential held in a property was written to the log. `getUrl()` now omits every property that `PGProperty.isSensitive()` reports, `getConnection` passes those values to the driver directly, and the URLs the driver logs have the same values replaced with `***`. `password` was never affected, since `BaseDataSource` holds it in its own field rather than among the properties. Callers that passed `getUrl()` to `DriverManager.getConnection` and relied on it carrying `sslpassword` must now supply that credential themselves [PR #4251](https://github.com/pgjdbc/pgjdbc/pull/4251)+
## [42.7.14] (2026-10-07)
### Security
diff --git a/TESTING.md b/TESTING.mdindex f6bc2aae22..9a5347dd9c 100644--- a/TESTING.md+++ b/TESTING.md@@ -57,6 +57,8 @@ If you have Docker, you can use `docker compose` to launch test database (see [d
SSL = "yes" | "no" - Whether to enable SSL
XA = "yes" | "no" - Whether to enable XA for prepared transactions
SCRAM = "yes" | "no" - Whether to enable SCRAM authentication
+ OAUTH = "no" | "smoke" | "all" - OAuth mode: off, OAuth tests only, or route every+ connection through OAuth (PG 18+)
TZ = "Etc/UTC" | ... - Override server timezone (default Etc/UTC)
CREATE_REPLICAS = "yes" | "no" - Whether to create two streaming replicas (defaults to off)
@@ -87,6 +89,17 @@ If you have Docker, you can use `docker compose` to launch test database (see [d
CREATE_REPLICAS=on docker/bin/postgres-server
+ To start a PostgreSQL 18 server with Keycloak for OAuth testing:++ PGV=18 OAUTH=smoke docker/bin/postgres-server++ To additionally authenticate the whole test suite via OAuth:++ PGV=18 OAUTH=all docker/bin/postgres-server++ Any OAuth mode other than "no" starts a Keycloak container that binds+ 127.0.0.1:8080 on the host.+
An alternative way is to use a Vagrant script: [jackdb/pgjdbc-test-vm](https://github.com/jackdb/pgjdbc-test-vm).
Follow the instructions on that project's [README](https://github.com/jackdb/pgjdbc-test-vm) page.
@@ -273,7 +286,90 @@ host test all all md5
The test user must also have a password set so the server can verify it (`ALTER USER test WITH PASSWORD 'test';`).
-## 11 - Credits and Feedback+## 11 - OAuth authentication tests++`OAuthTest` exercises OAUTHBEARER authentication ([RFC 7628](https://www.rfc-editor.org/rfc/rfc7628)) against a real server and a real authorization server. Every test in it skips unless `-Denable_oauth_tests=true` is given, so a plain `./gradlew test` never runs them.++There is a second mode. Under `-DauthMode=oauth` the default `test` role authenticates through OAuth for the whole suite, so every test that opens a connection takes the OAuth path (see `TestUtil.addOAuthProperties`). Tests that cannot work that way call `TestUtil.assumeNotOAuthMode()` and skip.++### Requirements++- PostgreSQL 18 or later (the server side `oauth` authentication method was introduced in 18)+- A validator module named by `oauth_validator_libraries`. The Docker setup installs [pg_oidc_validator](https://github.com/percona/pg_oidc_validator)+- An authorization server to issue the tokens. The Docker setup runs Keycloak with the realm in `docker/postgres-server/keycloak/realm.json`+- A `testoauth` role, an `oauth` rule for it in `pg_hba.conf`, and an ident map from the `preferred_username` claim of the token to that role++### Using Docker++Start the server together with Keycloak:++```sh+PGV=18 OAUTH=smoke docker/bin/postgres-server+```++Keycloak binds `127.0.0.1:8080` on the host. `pg_oidc_validator` is published for amd64 only, so on an arm64 host `docker/bin/postgres-server` runs the server under `linux/amd64` emulation, which is noticeably slower.++Then run the tests:++```sh+./gradlew :postgresql:test --tests '*OAuthTest' -Denable_oauth_tests=true+```++`OAUTH=all` switches the `test` role to OAuth as well, which is what `authMode=oauth` expects:++```sh+PGV=18 OAUTH=all docker/bin/postgres-server+./gradlew test -Denable_oauth_tests=true -DauthMode=oauth+```++### Manual setup++If you are not using Docker, load a validator and point an `oauth` rule at your issuer. With `pg_oidc_validator` and a Keycloak realm named `pgjdbc`:++```+# postgresql.conf+oauth_validator_libraries = 'pg_oidc_validator'+pg_oidc_validator.authn_field = 'preferred_username'+ident_file = '/path/to/pg_ident.conf'+```++```+# pg_hba.conf, above the other host rules so it takes precedence+host all testoauth all oauth scope=pgjdbc,issuer=http://keycloak:8080/realms/pgjdbc,map=oauthmap+```++```+# pg_ident.conf+# map-name system-username database-username+oauthmap service-account-pgjdbc-test testoauth+```++```sql+CREATE ROLE testoauth WITH LOGIN;+GRANT CONNECT ON DATABASE test TO testoauth;+GRANT USAGE ON SCHEMA public TO testoauth;+```++The `issuer` in the rule is matched against the issuer inside the token, so it is the URL the authorization server knows itself by. That is not necessarily the URL the tests reach it at, which is `oauthIssuer` below.++### Test properties++The tests obtain their own tokens through `org.postgresql.test.OAuthTestTokenProvider`, which sends a `client_credentials` request to the issuer. These system properties configure the tests, and the defaults match the Docker setup:++| Property | Default | Meaning |+| --- | --- | --- |+| `enable_oauth_tests` | `false` | Runs the tests in `OAuthTest` rather than skipping them |+| `authMode` | `default` | `oauth` routes the whole suite through OAuth |+| `oauthIssuer` | `http://localhost:8080/realms/pgjdbc` | Realm the token is requested from |+| `oauthClientId` | `pgjdbc-test` | Client the token is requested as |+| `oauthClientSecret` | `pgjdbc-test-client-secret` | Secret of that client |+| `oauthScope` | `pgjdbc` | Scope requested, and the one the `pg_hba.conf` rule requires |+| `oauthTokenProviderClassName` | `org.postgresql.test.OAuthTestTokenProvider` | Provider the tests configure the driver with |+| `oauthRole` | `testoauth` | Role the tests connect as |++The build forwards `enable_oauth_tests` and `authMode` to the forked test JVM; see the `passProperty` list in `build-logic/jvm/src/main/kotlin/build-logic.test-base.gradle.kts`. The remaining properties are not on that list, so `-D` on the Gradle command line does not reach the tests. Add them to that list, or export `_JAVA_OPTIONS`, which every JVM picks up and which is how CI passes its test properties.++## 12 - Credits and Feedback
The parts of this document describing the PostgreSQL test suite
were originally written by Rene Pijlman. Liam Stewart contributed
diff --git a/build-logic/jvm/src/main/kotlin/build-logic.test-base.gradle.kts b/build-logic/jvm/src/main/kotlin/build-logic.test-base.gradle.ktsindex a09e2dab7b..3cfb5ad454 100644--- a/build-logic/jvm/src/main/kotlin/build-logic.test-base.gradle.kts+++ b/build-logic/jvm/src/main/kotlin/build-logic.test-base.gradle.kts@@ -49,7 +49,8 @@ tasks.configureEach<Test> {
for (p in listOf("test.url.PGHOST", "test.url.PGPORT", "test.url.PGDBNAME", "user", "password",
"privilegedUser", "privilegedPassword",
"simpleProtocolOnly", "enable_ssl_tests",
- "autosave", "cleanupSavepoints")) {+ "autosave", "cleanupSavepoints",+ "enable_oauth_tests", "authMode")) {
passProperty(p)
}
}
diff --git a/docker/bin/postgres-server b/docker/bin/postgres-serverindex d9fb4dd137..6d6aff8e96 100755--- a/docker/bin/postgres-server+++ b/docker/bin/postgres-server@@ -11,6 +11,8 @@ set -euo pipefail
# SSL = "yes" | "no" - Whether to enable SSL
# XA = "yes" | "no" - Whether to enable XA for prepared transactions
# SCRAM = "yes" | "no" - Whether to enable SCRAM authentication
+# OAUTH = "no" | "smoke" | "all" - OAuth mode: off, OAuth tests only, or route every+# connection through OAuth (PG 18+)
# TZ = "Etc/UTC" | ... - Override server timezone (default Etc/UTC)
# CREATE_REPLICAS = "yes" | "no" - Whether to create two streaming replicas (defaults to off)
#
@@ -40,6 +42,17 @@ set -euo pipefail
# To start the default (latest) version with read only replicas:
#
# CREATE_REPLICAS=on docker/bin/postgres-server
+#+# To start a PostgreSQL 18 server with Keycloak for OAuth testing:+#+# PGV=18 OAUTH=smoke docker/bin/postgres-server+#+# To additionally authenticate the whole test suite via OAuth:+#+# PGV=18 OAUTH=all docker/bin/postgres-server+#+# Any OAuth mode other than "no" starts a Keycloak container that binds+# 127.0.0.1:8080 on the host.
log () {
echo "$@" 1>&2
@@ -54,6 +67,15 @@ main () {
local script_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
cd "${script_dir}/../postgres-server"
+ if [ "${OAUTH:-no}" != "no" ]; then+ export COMPOSE_PROFILES=oauth+ # pg_oidc_validator nightly builds are amd64-only, so OAuth runs need an amd64 server even+ # on arm64 hosts. Only OAuth runs pay the emulation cost.+ # TODO: Drop this parameter as soon as arm64 builds are available: https://github.com/pgdg-packaging/apt.postgresql.org-issues/issues/2+ export PG_PLATFORM="linux/amd64"+ log "Using oauth compose profile"+ fi+
log "Starting Postgres server and mapping to local port ${publish_port}"
exec docker compose run \
--rm \
diff --git a/docker/postgres-server/README.md b/docker/postgres-server/README.mdindex 0bb59cdec6..7aa6f395cd 100644--- a/docker/postgres-server/README.md+++ b/docker/postgres-server/README.md@@ -19,6 +19,16 @@ Environment variables
See the [list of available tags](https://github.com/docker-library/docs/blob/master/postgres/README.md#supported-tags-and-respective-...) at the official page.
* `SCRAM=yes|no` (default: `yes`). Configures `password_encryption=scram-sha-256`
* `SSL=yes|no` (default: `yes`). Configures SSL
+* `OAUTH=no|smoke|all` (default: `no`). Configures the server to support OAuth authentication.+ `smoke` enables it for the `testoauth` role only; `all` also switches the `test` role to OAuth,+ so the whole test suite authenticates via OAuth.+ Keycloak sits behind the `oauth` compose profile, and the `pg_oidc_validator` package the+ server needs is published for amd64 only, so both modes also require:++ COMPOSE_PROFILES=oauth PG_PLATFORM=linux/amd64 OAUTH=smoke docker compose up++ Keycloak then binds `127.0.0.1:8080` on the host, and on an arm64 host the server is+ emulated and noticeably slower. `docker/bin/postgres-server` sets both variables for you
Example usages
==============
diff --git a/docker/postgres-server/docker-compose.yml b/docker/postgres-server/docker-compose.ymlindex 9866a6454d..cd8beb170e 100644--- a/docker/postgres-server/docker-compose.yml+++ b/docker/postgres-server/docker-compose.yml@@ -1,6 +1,11 @@
services:
pgdb:
image: ${PG_IMAGE:-postgres:${PGV:-latest}}
+ # Empty by default, so non-OAuth runs use the host architecture. OAuth runs set it to+ # linux/amd64 (see docker/bin/postgres-server), because pg_oidc_validator is only published as+ # amd64 nightly builds;+ # TODO: Drop this parameter as soon as arm64 builds are available: https://github.com/pgdg-packaging/apt.postgresql.org-issues/issues/2+ platform: ${PG_PLATFORM:-}
# With the default pull_policy (missing) this section is ignored and the
# official postgres:<PGV> is pulled; force a build with PG_PULL_POLICY=build.
build:
@@ -24,6 +29,7 @@ services:
- SSL=${SSL:-yes}
- XA=${XA:-yes}
- SCRAM=${SCRAM:-yes}
+ - OAUTH=${OAUTH:-no}
- TZ=${TZ:-Etc/UTC}
- FSYNC=${FSYNC:-no}
- SYNC_COMMIT=${SYNC_COMMIT:-yes}
@@ -50,3 +56,31 @@ services:
timeout: 5s
retries: 30
start_period: 30s
+ depends_on:+ keycloak:+ condition: service_healthy+ required: false++ keycloak:+ profiles: [oauth]+ image: quay.io/keycloak/keycloak:26.7+ hostname: keycloak+ environment:+ KC_BOOTSTRAP_ADMIN_USERNAME: admin+ KC_BOOTSTRAP_ADMIN_PASSWORD: admin+ KC_HEALTH_ENABLED: "true"+ KC_HOSTNAME: keycloak+ KC_HOSTNAME_PORT: 8080+ # Allow requests via localhost (host port mapping) in addition to keycloak hostname.+ KC_HOSTNAME_STRICT: "false"+ KC_HOSTNAME_STRICT_BACKCHANNEL: "true"+ volumes:+ - ./keycloak:/opt/keycloak/data/import:ro+ ports:+ - "127.0.0.1:8080:8080"+ command: start-dev --import-realm+ healthcheck:+ test: ["CMD-SHELL", "exec 3<>/dev/tcp/localhost/8080"]+ interval: 5s+ timeout: 3s+ retries: 60diff --git a/docker/postgres-server/keycloak/realm.json b/docker/postgres-server/keycloak/realm.jsonnew file mode 100644index 0000000000..46a20afcc4--- /dev/null+++ b/docker/postgres-server/keycloak/realm.json@@ -0,0 +1,63 @@+{+ "realm": "pgjdbc",+ "enabled": true,+ "sslRequired": "none",+ "registrationAllowed": false,+ "loginWithEmailAllowed": false,+ "duplicateEmailsAllowed": false,+ "clientScopes": [+ {+ "name": "pgjdbc",+ "description": "pgjdbc JDBC driver OAuth test scope",+ "protocol": "openid-connect",+ "attributes": {+ "include.in.token.scope": "true",+ "display.on.consent.screen": "false",+ "consent.screen.text": ""+ },+ "protocolMappers": [+ {+ "name": "preferred_username",+ "protocol": "openid-connect",+ "protocolMapper": "oidc-usermodel-property-mapper",+ "consentRequired": false,+ "config": {+ "userinfo.token.claim": "true",+ "user.attribute": "username",+ "id.token.claim": "true",+ "access.token.claim": "true",+ "claim.name": "preferred_username",+ "jsonType.label": "String"+ }+ }+ ]+ }+ ],+ "clients": [+ {+ "clientId": "pgjdbc-test",+ "name": "pgjdbc Integration Tests",+ "enabled": true,+ "publicClient": false,+ "clientAuthenticatorType": "client-secret",+ "secret": "pgjdbc-test-client-secret",+ "directAccessGrantsEnabled": false,+ "serviceAccountsEnabled": true,+ "protocol": "openid-connect",+ "defaultClientScopes": [+ "web-origins",+ "acr",+ "profile",+ "roles",+ "email",+ "pgjdbc"+ ],+ "optionalClientScopes": [+ "address",+ "phone",+ "offline_access",+ "microprofile-jwt"+ ]+ }+ ]+}diff --git a/docker/postgres-server/scripts/entrypoint.sh b/docker/postgres-server/scripts/entrypoint.shindex ef28e3cea8..f3e2201baa 100755--- a/docker/postgres-server/scripts/entrypoint.sh+++ b/docker/postgres-server/scripts/entrypoint.sh@@ -58,6 +58,42 @@ main () {
sed -i -e "s/^hostssl\b/#hostssl/" "${pg_hba}"
fi
+ if [[ "${OAUTH:-no}" != "no" ]] && is_pg_version_at_least "18"; then+ echo "Installing pg_oidc_validator for OAuth testing..."+ apt-get update -qq+ apt-get install -y -qq wget libcurl4+ # TODO: Use official PGDG repo once pg_oidc_validator is available there+ # See https://github.com/pgdg-packaging/apt.postgresql.org-issues/issues/2+ local deb_url="https://github.com/percona/pg_oidc_validator/releases/download/latest/pg-oidc-validator-pgdg18.deb...;+ wget -q -O /tmp/pg_oidc_validator.deb "${deb_url}"+ apt-get install -y /tmp/pg_oidc_validator.deb+ rm /tmp/pg_oidc_validator.deb++ # Username mapping: JWT preferred_username "service-account-pgjdbc-test" → DB role "testoauth"+ cat > /tmp/pg_ident.conf <<'IDENT'+# map-name system-username database-username+oauthmap service-account-pgjdbc-test testoauth+IDENT++ # The oauth auth method only exists on PG 18+.+ # Insert the OAuth rule above all host rules so it takes precedence.+ sed -i '/^# TYPE\b/a\+host all testoauth all oauth scope=pgjdbc,issuer=http://keycloak:8080/realms/pgjdbc,map=oauthmap'; "${pg_hba}"++ if [ "$OAUTH" = "all" ]; then+ # in "all" mode the whole test suite authenticates via OAuth.+ # Map the same service account onto the default "test" role and switch that role's auth to oauth.+ # Scoped to the "test" database only (the one the general suite connects to).+ echo 'oauthmap service-account-pgjdbc-test test' >> /tmp/pg_ident.conf+ sed -i '/^# TYPE\b/a\+host test test all oauth scope=pgjdbc,issuer=http://keycloak:8080/realms/pgjdbc,map=oauthmap'; "${pg_hba}"+ fi++ add_pg_opt "-c oauth_validator_libraries=pg_oidc_validator"+ add_pg_opt "-c pg_oidc_validator.authn_field=preferred_username"+ add_pg_opt "-c ident_file=/tmp/pg_ident.conf"+ fi+
if is_option_enabled "${XA}"; then
pg_opts="${pg_opts} -c max_prepared_transactions=64"
fi
diff --git a/docker/postgres-server/scripts/post-startup.sh b/docker/postgres-server/scripts/post-startup.shindex d2ada9895a..ed9a6f9335 100755--- a/docker/postgres-server/scripts/post-startup.sh+++ b/docker/postgres-server/scripts/post-startup.sh@@ -54,6 +54,17 @@ hba_file = '/home/certdir/pg_hba.conf'
log_line_prefix = 'REPLICA<${name}>: %m [%p]'
EOF
+ if [[ "${OAUTH:-no}" != "no" ]] && is_pg_version_at_least "18"; then+ # The replica shares the primary's pg_hba.conf, which contains an oauth+ # rule. These settings are passed to the primary as command-line options+ # (see entrypoint.sh), so the replica must set them explicitly.+ cat <<EOF >>"${replica_data_dir}/postgresql.conf"+oauth_validator_libraries = 'pg_oidc_validator'+pg_oidc_validator.authn_field = 'preferred_username'+ident_file = '/tmp/pg_ident.conf'+EOF+ fi+
log "Starting replica ${name} that will listen on port ${port}"
pg_ctl start -D "${replica_data_dir}"
}
@@ -112,6 +123,15 @@ main () {
create_replica one 5433
create_replica two 5434
fi
++ if [[ "${OAUTH:-no}" != "no" ]] && is_pg_version_at_least "18"; then+ # Role used by OAuth integration tests. The preferred_username claim in+ # the Keycloak JWT equals "service-account-pgjdbc-test" which+ # pg_oidc_validator maps to this role via the oauthmap ident mapping.+ psql_super "${POSTGRES_DB}" "CREATE ROLE testoauth WITH LOGIN;"+ psql_super "${POSTGRES_DB}" "GRANT CONNECT ON DATABASE test TO testoauth;"+ psql_super "test" "GRANT USAGE ON SCHEMA public TO testoauth;"+ fi
}
main "$@"
diff --git a/docs/content/documentation/use.md b/docs/content/documentation/use.mdindex dd4d097d82..5b5a506e36 100644--- a/docs/content/documentation/use.md+++ b/docs/content/documentation/use.md@@ -247,6 +247,8 @@ This option controls the client's use of channel binding. A setting of `require`
Channel binding is a method for the server to authenticate itself to the client. It is only supported over SSL connections with PostgreSQL 11 or later servers using the SCRAM authentication method.
+`require` rules out OAUTHBEARER, since the driver has no channel binding to offer for that mechanism. When the server offers OAUTHBEARER alongside SCRAM, the driver answers with SCRAM so the channel binding still happens; when OAUTHBEARER is all the server offers, the connection is rejected rather than proceeding without a channel binding.+
* **`binaryTransfer (`*boolean*`)`** *Default `true`*\
Enable binary transfer for supported built-in types if possible.
Setting this to false disables any binary transfer unless it's individually activated for each type with `binaryTransferEnable`.
@@ -532,8 +534,13 @@ value in the connection properties will be used.
* **`requireAuth (`*String*`)`** *Default `null`*\
Comma-separated list of acceptable authentication methods. Use '!' prefix to reject methods (e.g., '!password' to reject cleartext).
-Supported methods: `password`, `md5`, `gss`, `sspi`, `scram-sha-256`, `none`. Cannot mix positive and negative options.+Supported methods: `password`, `md5`, `gss`, `sspi`, `scram-sha-256`, `oauth`, `none`. Cannot mix positive and negative options.
Examples: `requireAuth=md5,scram-sha-256` (allow only MD5 or SCRAM-SHA-256), `requireAuth=!password,!none` (reject cleartext and trust authentication).
+Whatever is allowed, the server has to authenticate the connection: one that is let through without the driver being+asked for anything is refused unless `none` is allowed. `gss` is the exception, because establishing GSS encryption+authenticates the client and leaves the server no reason to ask again, so `requireAuth=gss` is met by `gssEncMode=require`+alone. GSS encryption is not required to be named for any other method: a connection encrypted by GSS and then+authenticated with, say, OAUTHBEARER meets `requireAuth=oauth`.
* **`scramMaxIterations (`*int*`)`** *Default `100000`*\
Maximum PBKDF2 iteration count that pgjdbc will accept from the server during SCRAM authentication.
@@ -541,6 +548,58 @@ During SCRAM-SHA-256 authentication, the server sends the iteration count used t
This limits client CPU exposure if a malicious or compromised server sends an excessively large iteration count.
A value of zero disables this check.
+The `oauth*` properties below configure OAUTHBEARER ([RFC 7628](https://www.rfc-editor.org/rfc/rfc7628)) authentication.+Three things hold for all of them. The server side `oauth` authentication method is only available for PostgreSQL version+18 or higher. Unless `oauthAllowInsecureConnection` is enabled, the driver sends the token only over a secure connection to a+verified server, so `sslmode` must be `verify-ca` or `verify-full`, or the connection must be encrypted by GSS; the+default `sslmode=prefer` lets the server refuse TLS and continue in plaintext, which OAUTHBEARER then rejects, and+`sslmode=require` is not enough either because it does not verify the server certificate. And `channelBinding=require`+rules OAUTHBEARER out, since the driver has no channel binding to offer for it.++Setting either `oauthToken` or `oauthTokenProviderClassName` also decides the mechanism: when the server offers both+OAUTHBEARER and SCRAM-SHA-256, the driver answers with OAUTHBEARER and `password` is never used. Set+`requireAuth=scram-sha-256` to authenticate with a password instead.++* **`oauthToken (`*String*`)`** *Default `null`*\+OAuth 2.0 bearer token used for OAUTHBEARER (RFC 7628) authentication.+Takes precedence over `oauthTokenProviderClassName`.++* **`oauthTokenProviderClassName (`*String*`)`** *Default `null`*\+Fully qualified name of a class implementing the `org.postgresql.plugin.OAuthTokenProvider` interface, used to+obtain an OAuth bearer token at connection time. Ignored when `oauthToken` is set.++* **`oauthIssuer (`*String*`)`** *Default `null`*\+URL of the OAuth issuer (authorization server) to obtain a token from. The driver does not contact the issuer+itself; the value is passed to the `oauthTokenProviderClassName` implementation. Unless `oauthAllowInsecureIssuer`+is enabled, this URL must use HTTPS.++* **`oauthAllowInsecureIssuer (`*boolean*`)`** *Default `false`*\+Allow the `oauthIssuer` URL to use a plaintext `http` scheme instead of HTTPS. By default, a non-HTTPS issuer is+rejected. Enabling this is intended for development and testing only;+do not enable it in production.++* **`oauthClientId (`*String*`)`** *Default `null`*\+OAuth client id, passed to the `oauthTokenProviderClassName` implementation.++* **`oauthClientSecret (`*String*`)`** *Default `null`*\+OAuth client secret, passed to the `oauthTokenProviderClassName` implementation.++* **`oauthScope (`*String*`)`** *Default `null`*\+OAuth scope to request, passed to the `oauthTokenProviderClassName` implementation.++* **`oauthAllowInsecureConnection (`*boolean*`)`** *Default `false`*\+Allow OAUTHBEARER authentication over a connection that is neither encrypted by TLS with a verified server+certificate (`sslmode=verify-ca` or `verify-full`) nor by GSS.+[RFC 7628, section 3](https://www.rfc-editor.org/rfc/rfc7628#section-3) requires TLS, because the bearer+token is otherwise exposed to the network or to an impostor server.+The remedy for a connection the driver refuses on these grounds is to raise `sslmode` to `verify-ca` or higher, not to+enable this property. Enabling it is intended for development and testing only and logs a warning; do not enable it in+production.\+Whether the server certificate was verified is read from `sslmode`, which is exact for the driver's own SSL factory.+A custom `sslfactory` replaces the driver's certificate validation, and the driver cannot inspect what that factory+does, so using `sslfactory=org.postgresql.ssl.NonValidatingFactory` bypasses the driver's certificate validation.+Selecting a non-validating factory is as explicit a choice as enabling this property, and the driver treats it as one.+
### Unix sockets
By adding junixsocket you can obtain a socket factory that works with the driver.
diff --git a/pgjdbc-mockito-test/src/test/java/org/postgresql/core/v3/OAuthAuthenticatorTest.java b/pgjdbc-mockito-test/src/test/java/org/postgresql/core/v3/OAuthAuthenticatorTest.javanew file mode 100644index 0000000000..2874c295ac--- /dev/null+++ b/pgjdbc-mockito-test/src/test/java/org/postgresql/core/v3/OAuthAuthenticatorTest.java@@ -0,0 +1,189 @@+/*+ * Copyright (c) 2026, PostgreSQL Global Development Group+ * See the LICENSE file in the project root for more information.+ */++package org.postgresql.core.v3;++import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.params.provider.Arguments.argumentSet;+import static org.mockito.Mockito.when;++import org.postgresql.core.PGStream;+import org.postgresql.jdbc.SslMode;+import org.postgresql.util.GT;+import org.postgresql.util.PSQLException;+import org.postgresql.util.PSQLState;+import org.postgresql.util.TestLogHandler;++import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.extension.ExtendWith;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.Arguments;+import org.junit.jupiter.params.provider.MethodSource;+import org.mockito.Mock;+import org.mockito.junit.jupiter.MockitoExtension;++import java.net.Socket;+import java.text.MessageFormat;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.logging.Level;+import java.util.logging.LogRecord;+import java.util.logging.Logger;+import java.util.stream.Stream;++import javax.net.ssl.SSLSocket;++@ExtendWith(MockitoExtension.class)+class OAuthAuthenticatorTest {++ /** How the connection under test is encrypted, if at all. */+ private enum Transport {+ TLS,+ GSS,+ PLAINTEXT+ }++ private static final String UNENCRYPTED_WARNING =+ "WARNING: oauthAllowInsecureConnection=true: OAUTHBEARER is being used over an unencrypted "+ + "connection, so the bearer token is sent in the clear. RFC 7628 §3 requires a "+ + "secure channel. Do not use this configuration in production.";++ private static String unverifiedTlsWarning(SslMode sslMode) {+ return "WARNING: oauthAllowInsecureConnection=true: OAUTHBEARER is being used over a TLS "+ + "connection whose server certificate is not verified (sslmode=" + sslMode.value+ + "), so the bearer token may be disclosed to an impostor. RFC 7628 §3 requires a "+ + "secure channel. Do not use this configuration in production.";+ }++ private static String unverifiedTlsRefusal(SslMode sslMode) {+ return GT.tr("OAUTHBEARER authentication requires the server certificate to be verified "+ + "(RFC 7628 §3), and sslmode={0} does not verify it. Use sslmode=verify-ca or "+ + "sslmode=verify-full, or set oauthAllowInsecureConnection=true to override "+ + "(testing only).", sslMode.value);+ }++ @Mock+ private SSLSocket sslSocket;++ @Mock+ private Socket socket;++ @Mock+ private PGStream pgStream;++ private TestLogHandler logHandler;+ private Logger oauthLogger;+ private Level previousLevel;+ private boolean previousUseParentHandlers;++ @BeforeEach+ void setUp() {+ logHandler = new TestLogHandler();+ oauthLogger = Logger.getLogger(OAuthAuthenticator.class.getName());+ previousLevel = oauthLogger.getLevel();+ previousUseParentHandlers = oauthLogger.getUseParentHandlers();+ oauthLogger.addHandler(logHandler);+ oauthLogger.setLevel(Level.ALL);+ // Record the messages here without also emitting them to the console.+ oauthLogger.setUseParentHandlers(false);+ }++ @AfterEach+ void tearDown() {+ oauthLogger.removeHandler(logHandler);+ oauthLogger.setLevel(previousLevel);+ oauthLogger.setUseParentHandlers(previousUseParentHandlers);+ }++ static Stream<Arguments> accepts() {+ return Stream.of(+ argumentSet("TLS, sslmode=verify-ca, secure connection required",+ Transport.TLS, SslMode.VERIFY_CA, false, Collections.emptyList()),+ argumentSet("TLS, sslmode=verify-full, secure connection required",+ Transport.TLS, SslMode.VERIFY_FULL, false, Collections.emptyList()),+ argumentSet("TLS, sslmode=verify-ca, insecure connection allowed",+ Transport.TLS, SslMode.VERIFY_CA, true, Collections.emptyList()),+ argumentSet("TLS, sslmode=verify-full, insecure connection allowed",+ Transport.TLS, SslMode.VERIFY_FULL, true, Collections.emptyList()),+ argumentSet("GSS encryption, secure connection required",+ Transport.GSS, SslMode.DISABLE, false, Collections.emptyList()),+ argumentSet("GSS encryption, insecure connection allowed",+ Transport.GSS, SslMode.DISABLE, true, Collections.emptyList()),+ argumentSet("TLS, sslmode=prefer, insecure connection allowed",+ Transport.TLS, SslMode.PREFER, true,+ Collections.singletonList(unverifiedTlsWarning(SslMode.PREFER))),+ argumentSet("TLS, sslmode=require, insecure connection allowed",+ Transport.TLS, SslMode.REQUIRE, true,+ Collections.singletonList(unverifiedTlsWarning(SslMode.REQUIRE))),+ argumentSet("no encryption, insecure connection allowed",+ Transport.PLAINTEXT, SslMode.DISABLE, true,+ Collections.singletonList(UNENCRYPTED_WARNING)));+ }++ @ParameterizedTest+ @MethodSource+ void accepts(Transport transport, SslMode sslMode, boolean allowInsecure,+ List<String> expectedLog) {+ stubTransport(transport);++ assertDoesNotThrow(() -> new OAuthAuthenticator(pgStream, sslMode, allowInsecure));+ assertEquals(expectedLog, loggedMessages());+ }++ static Stream<Arguments> refuses() {+ return Stream.of(+ argumentSet("TLS, sslmode=prefer", Transport.TLS, SslMode.PREFER,+ unverifiedTlsRefusal(SslMode.PREFER)),+ argumentSet("TLS, sslmode=require", Transport.TLS, SslMode.REQUIRE,+ unverifiedTlsRefusal(SslMode.REQUIRE)),+ argumentSet("no encryption", Transport.PLAINTEXT, SslMode.DISABLE,+ GT.tr("OAUTHBEARER authentication requires a connection to a verified server "+ + "(TLS with sslmode=verify-ca or higher, or GSS encryption) (RFC 7628 §3). "+ + "Set oauthAllowInsecureConnection=true to override (testing only).")));+ }++ @ParameterizedTest+ @MethodSource+ void refuses(Transport transport, SslMode sslMode, String expectedMessage) {+ stubTransport(transport);++ PSQLException ex = assertThrows(PSQLException.class,+ () -> new OAuthAuthenticator(pgStream, sslMode, false));+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ assertEquals(expectedMessage, ex.getMessage());+ assertEquals(Collections.emptyList(), loggedMessages());+ }++ private void stubTransport(Transport transport) {+ switch (transport) {+ case TLS:+ when(pgStream.getSocket()).thenReturn(sslSocket);+ break;+ case GSS:+ when(pgStream.isGssEncrypted()).thenReturn(true);+ break;+ default:+ when(pgStream.getSocket()).thenReturn(socket);+ break;+ }+ }++ private List<String> loggedMessages() {+ List<String> messages = new ArrayList<>();+ for (LogRecord record : logHandler.records) {+ String message = record.getMessage();+ Object[] parameters = record.getParameters();+ if (message != null && parameters != null && parameters.length > 0) {+ message = MessageFormat.format(message, parameters);+ }+ messages.add(record.getLevel() + ": " + message);+ }+ return messages;+ }+}diff --git a/pgjdbc-mockito-test/src/test/java/org/postgresql/core/v3/ReadMechanismsTest.java b/pgjdbc-mockito-test/src/test/java/org/postgresql/core/v3/ReadMechanismsTest.javanew file mode 100644index 0000000000..9d424b7ac7--- /dev/null+++ b/pgjdbc-mockito-test/src/test/java/org/postgresql/core/v3/ReadMechanismsTest.java@@ -0,0 +1,122 @@+/*+ * Copyright (c) 2026, PostgreSQL Global Development Group+ * See the LICENSE file in the project root for more information.+ */++package org.postgresql.core.v3;++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 static org.mockito.ArgumentMatchers.anyInt;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++import org.postgresql.core.Encoding;+import org.postgresql.core.PGStream;+import org.postgresql.util.GT;+import org.postgresql.util.PSQLException;+import org.postgresql.util.PSQLState;++import org.junit.jupiter.api.Test;++import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.nio.charset.StandardCharsets;+import java.util.Arrays;++class ReadMechanismsTest {++ private static PGStream stream(byte[] wire) throws IOException {+ PGStream stream = mock(PGStream.class);+ when(stream.getEncoding()).thenReturn(Encoding.getJVMEncoding("UTF-8"));+ when(stream.receive(anyInt())).thenAnswer(invocation -> {+ int size = invocation.getArgument(0);+ assertTrue(size <= wire.length, "read " + size + " bytes past the end of the message");+ return Arrays.copyOfRange(wire, 0, size);+ });+ return stream;+ }++ private static byte[] body(String... mechanisms) {+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ for (String mechanism : mechanisms) {+ byte[] name = mechanism.getBytes(StandardCharsets.UTF_8);+ out.write(name, 0, name.length);+ out.write(0);+ }+ out.write(0);+ return out.toByteArray();+ }++ @Test+ void readsSingleMechanism() throws Exception {+ byte[] payload = body("SCRAM-SHA-256");+ assertEquals(Arrays.asList("SCRAM-SHA-256"),+ ConnectionFactoryImpl.readMechanisms(stream(payload), payload.length));+ }++ @Test+ void readsMultipleMechanisms() throws Exception {+ byte[] payload = body("OAUTHBEARER", "SCRAM-SHA-256", "SCRAM-SHA-256-PLUS");+ assertEquals(Arrays.asList("OAUTHBEARER", "SCRAM-SHA-256", "SCRAM-SHA-256-PLUS"),+ ConnectionFactoryImpl.readMechanisms(stream(payload), payload.length));+ }++ @Test+ void stopsAtTheEndOfTheMessage() throws Exception {+ byte[] payload = body("SCRAM-SHA-256");+ byte[] wire = Arrays.copyOf(payload, payload.length + 1);+ wire[payload.length] = 'E'; // Next message++ PGStream stream = stream(wire);+ assertEquals(Arrays.asList("SCRAM-SHA-256"),+ ConnectionFactoryImpl.readMechanisms(stream, payload.length));+ // Exactly the body was consumed, so the next message type byte is left for the caller+ verify(stream).receive(payload.length);+ }++ @Test+ void rejectsEmptyMechanismList() throws Exception {+ PSQLException e = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.readMechanisms(stream(new byte[]{0}), 1));+ assertEquals(GT.tr("Received AuthenticationSASL message with 0 mechanisms!"),+ e.getMessage());+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), e.getSQLState());+ }++ @Test+ void rejectsBodyWithoutTerminator() throws Exception {+ byte[] payload = "SCRAM-SHA-256".getBytes(StandardCharsets.UTF_8);+ PSQLException e = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.readMechanisms(stream(payload), payload.length));+ assertEquals(GT.tr("Received invalid AuthenticationSASL message."), e.getMessage());+ assertEquals(PSQLState.PROTOCOL_VIOLATION.getState(), e.getSQLState());+ }++ @Test+ void rejectsUnterminatedMechanismName() throws Exception {+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ byte[] name = "SCRAM-SHA-256".getBytes(StandardCharsets.UTF_8);+ out.write(name, 0, name.length);+ out.write(0);+ byte[] payload = out.toByteArray();++ PSQLException e = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.readMechanisms(stream(payload), payload.length));+ assertEquals(+ GT.tr("Received AuthenticationSASL message with invalid authentication mechanism list."),+ e.getMessage());+ assertEquals(PSQLState.PROTOCOL_VIOLATION.getState(), e.getSQLState());+ }++ @Test+ void rejectsNonPositiveLength() throws Exception {+ PSQLException e = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.readMechanisms(stream(new byte[]{0}), 0));+ assertEquals(GT.tr("Received AuthenticationSASL message with an invalid length: {0}.", 0),+ e.getMessage());+ assertEquals(PSQLState.PROTOCOL_VIOLATION.getState(), e.getSQLState());+ }+}diff --git a/pgjdbc-mockito-test/src/test/java/org/postgresql/core/v3/ScramAuthenticatorChannelBindingTest.java b/pgjdbc-mockito-test/src/test/java/org/postgresql/core/v3/ScramAuthenticatorChannelBindingTest.javaindex 914ceb0438..6943fcb39b 100644--- a/pgjdbc-mockito-test/src/test/java/org/postgresql/core/v3/ScramAuthenticatorChannelBindingTest.java+++ b/pgjdbc-mockito-test/src/test/java/org/postgresql/core/v3/ScramAuthenticatorChannelBindingTest.java@@ -12,6 +12,7 @@
import static org.mockito.Mockito.when;
import org.postgresql.core.PGStream;
+import org.postgresql.util.GT;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
@@ -20,6 +21,8 @@
import java.net.Socket;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
+import java.util.Arrays;+import java.util.List;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
@@ -32,6 +35,9 @@
*/
class ScramAuthenticatorChannelBindingTest {
+ private static final List<String> MECHANISMS =+ Arrays.asList("SCRAM-SHA-256", "SCRAM-SHA-256-PLUS");+
@Test
void requireRejectsCertificateWithoutChannelBindingHash() throws Exception {
// A certificate whose signature algorithm yields no channel binding hash, such as Ed25519.
@@ -48,7 +54,8 @@ void requireRejectsCertificateWithoutChannelBindingHash() throws Exception {
when(stream.getSocket()).thenReturn(socket);
PSQLException ex = assertThrows(PSQLException.class,
- () -> new ScramAuthenticator("secret".toCharArray(), stream, ChannelBinding.REQUIRE, 0));+ () -> new ScramAuthenticator("secret".toCharArray(), stream, ChannelBinding.REQUIRE, 0,+ MECHANISMS));
assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());
// The message names the offending signature algorithm so an operator can act.
@@ -61,8 +68,10 @@ void requireRejectsConnectionWithoutSsl() throws Exception {
when(stream.getSocket()).thenReturn(mock(Socket.class));
PSQLException ex = assertThrows(PSQLException.class,
- () -> new ScramAuthenticator("secret".toCharArray(), stream, ChannelBinding.REQUIRE, 0));+ () -> new ScramAuthenticator("secret".toCharArray(), stream, ChannelBinding.REQUIRE, 0,+ MECHANISMS));
assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());
+ assertEquals(GT.tr("Channel Binding is required, but SSL is not in use"), ex.getMessage());
}
}
diff --git a/pgjdbc-osgi-test/src/test/java/org/postgresql/test/osgi/DataSourceFactoryTest.java b/pgjdbc-osgi-test/src/test/java/org/postgresql/test/osgi/DataSourceFactoryTest.javaindex 6776acd6bd..a61864b600 100644--- a/pgjdbc-osgi-test/src/test/java/org/postgresql/test/osgi/DataSourceFactoryTest.java+++ b/pgjdbc-osgi-test/src/test/java/org/postgresql/test/osgi/DataSourceFactoryTest.java@@ -13,6 +13,7 @@
import org.postgresql.util.internal.FileUtils;
import org.junit.Assert;
+import org.junit.Assume;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.Configuration;
@@ -84,6 +85,7 @@ public void dataSourceFactoryIsRegistered() throws Exception {
@Test
public void createDataSource() throws SQLException {
+ assumeNotOAuthAllMode();
Properties props = getProperties();
DataSource dataSource = dataSourceFactory.createDataSource(props);
Connection con = dataSource.getConnection();
@@ -92,6 +94,7 @@ public void createDataSource() throws SQLException {
@Test
public void createXADataSource() throws SQLException {
+ assumeNotOAuthAllMode();
Properties props = getProperties();
XADataSource dataSource = dataSourceFactory.createXADataSource(props);
XAConnection con = dataSource.getXAConnection();
@@ -100,12 +103,22 @@ public void createXADataSource() throws SQLException {
@Test
public void createDriver() throws SQLException {
+ assumeNotOAuthAllMode();
Properties props = getProperties();
Driver driver = dataSourceFactory.createDriver(new Properties());
Connection con = driver.connect(getUrl(), props);
testConnection(con);
}
+ /**+ * Skip these tests in OAuth "all" mode as this bundle cannot import the testkit bundle.+ */+ private static void assumeNotOAuthAllMode() {+ Assume.assumeFalse(+ "OAuth all-mode routes the test role through OAUTHBEARER, which the OSGi bundle cannot satisfy",+ "oauth".equals(System.getProperty("authMode")));+ }+
private static void testConnection(Connection con) throws SQLException {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select 2+2*2");
diff --git a/pgjdbc/src/main/java/org/postgresql/Driver.java b/pgjdbc/src/main/java/org/postgresql/Driver.javaindex 89872d6854..6e17d2e883 100644--- a/pgjdbc/src/main/java/org/postgresql/Driver.java+++ b/pgjdbc/src/main/java/org/postgresql/Driver.java@@ -286,12 +286,14 @@ private Properties loadDefaultProperties() throws IOException {
// parse URL and add more properties
if ((props = parseURL(url, props)) == null) {
throw new PSQLException(
- GT.tr("Unable to parse URL {0}", url),+ GT.tr("Unable to parse URL {0}", PGPropertyUtil.maskSensitiveValues(url)),
PSQLState.UNEXPECTED_ERROR);
}
try {
- LOGGER.log(Level.FINE, "Connecting with URL: {0}", url);+ if (LOGGER.isLoggable(Level.FINE)) {+ LOGGER.log(Level.FINE, "Connecting with URL: {0}", PGPropertyUtil.maskSensitiveValues(url));+ }
// Enforce login timeout, if specified, by handing the connection
// attempt to an Executor, which must run it on a thread other than
@@ -543,7 +545,10 @@ public boolean jdbcCompliant() {
}
if (!urlServer.startsWith("jdbc:postgresql:")) {
- LOGGER.log(Level.FINE, "JDBC URL must start with \"jdbc:postgresql:\" but was: {0}", url);+ if (LOGGER.isLoggable(Level.FINE)) {+ LOGGER.log(Level.FINE, "JDBC URL must start with \"jdbc:postgresql:\" but was: {0}",+ PGPropertyUtil.maskSensitiveValues(url));+ }
return null;
}
urlServer = urlServer.substring("jdbc:postgresql:".length());
@@ -554,20 +559,25 @@ public boolean jdbcCompliant() {
urlServer = urlServer.substring(2);
long slashCount = urlServer.chars().filter(ch -> ch == '/').count();
if (slashCount > 1) {
- LOGGER.log(Level.WARNING, "JDBC URL contains too many / characters: {0}", url);+ LOGGER.log(Level.WARNING, "JDBC URL contains too many / characters: {0}",+ PGPropertyUtil.maskSensitiveValues(url));
return null;
}
int slash = urlServer.indexOf('/');
if (slash == -1) {
- LOGGER.log(Level.WARNING, "JDBC URL must contain a / at the end of the host or port: {0}", url);+ LOGGER.log(Level.WARNING, "JDBC URL must contain a / at the end of the host or port: {0}",+ PGPropertyUtil.maskSensitiveValues(url));
return null;
}
if (!urlServer.endsWith("/")) {
- String value = urlDecode(urlServer.substring(slash + 1));- if (value == null) {+ String dbName = urlServer.substring(slash + 1);+ try {+ PGProperty.PG_DBNAME.set(priority1Url, URLCoder.decode(dbName));+ } catch (IllegalArgumentException e) {+ LOGGER.log(Level.FINE, "JDBC URL database name [{0}] could not be decoded: {1}",+ new Object[]{dbName, e.getMessage()});
return null;
}
- PGProperty.PG_DBNAME.set(priority1Url, value);
}
urlServer = urlServer.substring(0, slash);
@@ -599,11 +609,13 @@ public boolean jdbcCompliant() {
} else if (urlServer.startsWith("/")) {
return null;
} else {
- String value = urlDecode(urlServer);- if (value == null) {+ try {+ priority1Url.setProperty(PGProperty.PG_DBNAME.getName(), URLCoder.decode(urlServer));+ } catch (IllegalArgumentException e) {+ LOGGER.log(Level.FINE, "JDBC URL database name [{0}] could not be decoded: {1}",+ new Object[]{urlServer, e.getMessage()});
return null;
}
- priority1Url.setProperty(PGProperty.PG_DBNAME.getName(), value);
}
// parse the args part of the url
@@ -618,8 +630,12 @@ public boolean jdbcCompliant() {
priority1Url.setProperty(token, "");
} else {
String pName = PGPropertyUtil.translatePGServiceToPGProperty(token.substring(0, pos));
- String pValue = urlDecode(token.substring(pos + 1));- if (pValue == null) {+ String pValue;+ try {+ pValue = URLCoder.decode(token.substring(pos + 1));+ } catch (IllegalArgumentException e) {+ // The value may be a credential, so only the parameter name is logged+ LOGGER.log(Level.FINE, "URL parameter [{0}] could not be decoded", pName);
return null;
}
if (PGProperty.SERVICE.getName().equals(pName)) {
@@ -678,16 +694,6 @@ public boolean jdbcCompliant() {
return result;
}
- // decode url, on failure log and return null- private static @Nullable String urlDecode(String url) {- try {- return URLCoder.decode(url);- } catch (IllegalArgumentException e) {- LOGGER.log(Level.FINE, "Url [{0}] parsing failed with error [{1}]", new Object[]{url, e.getMessage()});- }- return null;- }-
/**
* @return the address portion of the URL
*/
diff --git a/pgjdbc/src/main/java/org/postgresql/PGProperty.java b/pgjdbc/src/main/java/org/postgresql/PGProperty.javaindex 650b33e536..204dc27537 100644--- a/pgjdbc/src/main/java/org/postgresql/PGProperty.java+++ b/pgjdbc/src/main/java/org/postgresql/PGProperty.java@@ -14,9 +14,12 @@
import java.sql.Connection;
import java.sql.DriverPropertyInfo;
+import java.util.Collections;+import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
+import java.util.Set;
/**
* All connection parameters that can be either set in JDBC URL, in Driver properties or in
@@ -481,6 +484,82 @@ public enum PGProperty {
"8192",
"Maximum amount of bytes buffered before sending to the backend"),
+ /**+ * Allow OAUTHBEARER authentication over a connection that is not encrypted, or whose server+ * certificate is not verified. RFC 7628 §3 requires TLS, so enabling this is intended for+ * development and testing only; DO NOT ENABLE IN PRODUCTION ENVIRONMENTS.+ */+ OAUTH_ALLOW_INSECURE_CONNECTION(+ "oauthAllowInsecureConnection",+ "false",+ "Allow OAUTHBEARER authentication over a connection that is neither encrypted by TLS with a "+ + "verified server certificate nor by GSS. RFC 7628, section 3 requires TLS, so enable "+ + "this for development and testing only."),++ /**+ * Whether to allow a non-HTTPS OAuth issuer URL. Disabled by default;+ * enable only for development/testing.+ */+ OAUTH_ALLOW_INSECURE_ISSUER(+ "oauthAllowInsecureIssuer",+ "false",+ "Allow the oauthIssuer URL to use a plaintext http scheme instead of HTTPS. Enable this for "+ + "development and testing only."),++ /**+ * The OAuth client ID to use for the token request.+ */+ OAUTH_CLIENT_ID(+ "oauthClientId",+ null,+ "OAuth client id. The driver does not contact the issuer itself; the value is passed to the "+ + "oauthTokenProviderClassName implementation."),++ /**+ * The OAuth client secret to use for the token request.+ */+ OAUTH_CLIENT_SECRET(+ "oauthClientSecret",+ null,+ "OAuth client secret. The driver does not contact the issuer itself; the value is passed to "+ + "the oauthTokenProviderClassName implementation."),++ /**+ * The HTTPS URL of the OAuth issuer.+ */+ OAUTH_ISSUER(+ "oauthIssuer",+ null,+ "URL of the OAuth issuer to obtain a token from. The driver does not contact the issuer "+ + "itself; the value is passed to the oauthTokenProviderClassName implementation."),++ /**+ * The OAuth scope to request for the token.+ */+ OAUTH_SCOPE(+ "oauthScope",+ null,+ "OAuth scope to request. The driver does not contact the issuer itself; the value is passed "+ + "to the oauthTokenProviderClassName implementation."),++ /**+ * OAuth bearer token for OAUTHBEARER SASL authentication.+ * Takes priority over token provider.+ */+ OAUTH_TOKEN(+ "oauthToken",+ null,+ "OAuth bearer token for OAuth authentication."),++ /**+ * Fully-qualified class name of an OAuthTokenProvider implementation.+ * The provider is called to obtain a bearer token.+ */+ OAUTH_TOKEN_PROVIDER_CLASS_NAME(+ "oauthTokenProviderClassName",+ null,+ "Name of the class implementing OAuthTokenProvider for OAuth bearer token authentication."),+
/**
* Specify 'options' connection initialization parameter.
* The value of this parameter may contain spaces and other special characters or their URL representation.
@@ -666,10 +745,10 @@ public enum PGProperty {
null,
"Comma-separated list of acceptable authentication methods. "
+ "Use '!' prefix to reject methods (e.g., '!password' to reject cleartext). "
- + "Supported: password, md5, gss, sspi, scram-sha-256, none",+ + "Supported: password, md5, gss, sspi, scram-sha-256, oauth, none",
false,
- new String[]{"password", "md5", "gss", "sspi", "scram-sha-256", "none",- "!password", "!md5", "!gss", "!sspi", "!scram-sha-256", "!none"}+ new String[]{"password", "md5", "gss", "sspi", "scram-sha-256", "oauth", "none",+ "!password", "!md5", "!gss", "!sspi", "!scram-sha-256", "!oauth", "!none"}
),
/**
@@ -990,6 +1069,12 @@ public enum PGProperty {
}
}
+ /**+ * These parameters should not be disclosed.+ */+ private static final Set<PGProperty> SENSITIVE_PROPERTIES = Collections.unmodifiableSet(+ EnumSet.of(PASSWORD, SSL_PASSWORD, OAUTH_TOKEN, OAUTH_CLIENT_SECRET));+
/**
* Returns the name of the connection parameter. The name is the key that must be used in JDBC URL
* or in Driver properties
@@ -1018,6 +1103,15 @@ public boolean isRequired() {
return required;
}
+ /**+ * Returns whether the value of this parameter is sensitive.+ *+ * @return whether the value of this parameter is sensitive+ */+ public boolean isSensitive() {+ return SENSITIVE_PROPERTIES.contains(this);+ }+
/**
* Returns the description for this connection parameter.
*
diff --git a/pgjdbc/src/main/java/org/postgresql/core/AuthMethod.java b/pgjdbc/src/main/java/org/postgresql/core/AuthMethod.javaindex 66de4f6dce..434401ce07 100644--- a/pgjdbc/src/main/java/org/postgresql/core/AuthMethod.java+++ b/pgjdbc/src/main/java/org/postgresql/core/AuthMethod.java@@ -17,7 +17,7 @@
* Enumeration of PostgreSQL authentication methods.
*/
public enum AuthMethod {
- NONE, PASSWORD, MD5, GSS, SSPI, SCRAM_SHA_256;+ NONE, PASSWORD, MD5, GSS, SSPI, SCRAM_SHA_256, OAUTH;
public static AuthMethod fromString(String method) throws PSQLException {
switch (method) {
@@ -27,6 +27,7 @@ public static AuthMethod fromString(String method) throws PSQLException {
case "gss": return GSS;
case "sspi": return SSPI;
case "scram-sha-256": return SCRAM_SHA_256;
+ case "oauth": return OAUTH;
default: throw new PSQLException(GT.tr("Invalid authentication method: {0}", method), PSQLState.INVALID_PARAMETER_VALUE);
}
}
@@ -90,6 +91,10 @@ public static AuthMethod fromString(String method) throws PSQLException {
return allowedMethods;
}
+ public static boolean isAllowed(@Nullable EnumSet<AuthMethod> allowedMethods, AuthMethod authMethod) {+ return allowedMethods == null || allowedMethods.contains(authMethod);+ }+
/**
* Refuses an authentication method that {@code requireAuth} does not allow.
*
@@ -100,10 +105,7 @@ public static AuthMethod fromString(String method) throws PSQLException {
* method is not allowed
*/
public static void checkAuth(@Nullable EnumSet<AuthMethod> allowedMethods, AuthMethod authMethod) throws PSQLException {
- if (allowedMethods == null) {- return;- }- if (!allowedMethods.contains(authMethod)) {+ if (!isAllowed(allowedMethods, authMethod)) {
throw new PSQLException(GT.tr("Authentication method is not allowed by requireAuth"), PSQLState.CONNECTION_REJECTED);
}
}
diff --git a/pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java b/pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.javaindex 0ed56e576e..5643bac098 100644--- a/pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java+++ b/pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java@@ -11,6 +11,7 @@
import org.postgresql.PGProperty;
import org.postgresql.core.AuthMethod;
import org.postgresql.core.ConnectionFactory;
+import org.postgresql.core.Encoding;
import org.postgresql.core.PGStream;
import org.postgresql.core.PgMessageType;
import org.postgresql.core.ProtocolVersion;
@@ -32,6 +33,8 @@
import org.postgresql.jdbc.SslMode;
import org.postgresql.jdbc.SslNegotiation;
import org.postgresql.plugin.AuthenticationRequestType;
+import org.postgresql.plugin.OAuthTokenProvider;+import org.postgresql.plugin.OAuthTokenRequest;
import org.postgresql.ssl.MakeSSL;
import org.postgresql.sspi.ISSPIClient;
import org.postgresql.util.ClassLoaderStrategy;
@@ -39,20 +42,25 @@
import org.postgresql.util.GT;
import org.postgresql.util.HostSpec;
import org.postgresql.util.MD5Digest;
+import org.postgresql.util.ObjectFactory;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.ServerErrorMessage;
import org.postgresql.util.internal.Nullness;
+import com.ongres.scram.common.ScramMechanism;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
+import java.net.URI;+import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
@@ -306,7 +314,7 @@ private PGStream tryConnect(Properties info, SocketFactory socketFactory, HostSp
sendStartupPacket(newStream, ProtocolVersion.fromMajorMinor(protocolMajor,protocolMinor), paramList);
// Do authentication (until AuthenticationOk).
- doAuthentication(newStream, hostSpec.getHost(), user, info);+ doAuthentication(newStream, hostSpec.getHost(), user, sslMode, info);
return newStream;
} catch (IOException e) {
@@ -326,6 +334,150 @@ private PGStream tryConnect(Properties info, SocketFactory socketFactory, HostSp
}
}
+ private static boolean isOAuthConfigured(Properties info) {+ String staticToken = PGProperty.OAUTH_TOKEN.getOrDefault(info);+ if (staticToken != null && !staticToken.isEmpty()) {+ return true;+ }+ String providerClass = PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.getOrDefault(info);+ if (providerClass != null && !providerClass.isEmpty()) {+ return true;+ }+ return false;+ }++ /**+ * Picks the mechanism to answer an {@code AuthenticationSASL} request with. OAUTHBEARER is+ * preferred over SCRAM when the server offers both and the driver can use it.+ *+ * @param saslMechanisms mechanisms offered by the server+ * @param info connection properties+ * @param authMethods methods allowed by {@code requireAuth}, or {@code null} if unrestricted+ * @param channelBinding the {@code channelBinding} setting+ * @return {@link AuthMethod#OAUTH} or {@link AuthMethod#SCRAM_SHA_256}+ * @throws PSQLException if no offered mechanism is both usable by the driver and allowed+ */+ static AuthMethod selectSaslMechanism(List<String> saslMechanisms, Properties info,+ @Nullable EnumSet<AuthMethod> authMethods, ChannelBinding channelBinding)+ throws PSQLException {+ // "offered" is what the server sent, "allowed" is that narrowed down by requireAuth.+ boolean oauthOffered = saslMechanisms.contains(OAuthAuthenticator.SASL_MECHANISM);+ boolean scramOffered = !Collections.disjoint(saslMechanisms,+ ScramMechanism.supportedMechanisms());+ boolean oauthAllowed = oauthOffered && AuthMethod.isAllowed(authMethods, AuthMethod.OAUTH);+ boolean scramAllowed = scramOffered+ && AuthMethod.isAllowed(authMethods, AuthMethod.SCRAM_SHA_256);++ // Everything needed for OAuth is available, so we can select it immediately.+ if (oauthAllowed && isOAuthConfigured(info) && channelBinding != ChannelBinding.REQUIRE) {+ return AuthMethod.OAUTH;+ }++ // Otherwise if SCRAM is allowed, select it next.+ if (scramAllowed) {+ return AuthMethod.SCRAM_SHA_256;+ }+ if (oauthAllowed) {+ // If OAuth configured the only thing preventing its use is channel binding.+ if (isOAuthConfigured(info)) {+ throw new PSQLException(+ GT.tr("Channel binding is not supported for OAuth authentication."),+ PSQLState.CONNECTION_REJECTED);+ }+ // Otherwise, the driver lacks the necessary OAuth configuration.+ throw new PSQLException(+ GT.tr("The server requested OAuth authentication, but neither {0} nor {1} is configured.",+ PGProperty.OAUTH_TOKEN.getName(),+ PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.getName()),+ PSQLState.CONNECTION_REJECTED);+ }+ if (oauthOffered || scramOffered) {+ // If we reach this point, the server offered OAuth or SCRAM, but neither is allowed by requireAuth.+ throw new PSQLException(GT.tr("Authentication method is not allowed by requireAuth"),+ PSQLState.CONNECTION_REJECTED);+ }+ throw new PSQLException(+ GT.tr("The server requested SASL authentication with mechanisms {0}, "+ + "but the driver supports none of them.",+ saslMechanisms),+ PSQLState.CONNECTION_REJECTED);+ }++ static void validateOAuthIssuer(Properties info) throws PSQLException {+ String issuer = PGProperty.OAUTH_ISSUER.getOrDefault(info);+ if (issuer == null || issuer.isEmpty()) {+ return;+ }+ if (PGProperty.OAUTH_ALLOW_INSECURE_ISSUER.getBoolean(info)) {+ return;+ }+ URI issuerUri;+ try {+ issuerUri = new URI(issuer);+ } catch (URISyntaxException e) {+ throw new PSQLException(+ GT.tr("OAuth issuer is not a valid URL: {0}", issuer),+ PSQLState.INVALID_PARAMETER_VALUE, e);+ }+ if (!"https".equalsIgnoreCase(issuerUri.getScheme())) {+ throw new PSQLException(+ GT.tr("OAuth issuer URL must use HTTPS: {0}. "+ + "Set oauthAllowInsecureIssuer=true to disable this check for development.", issuer),+ PSQLState.INVALID_PARAMETER_VALUE);+ }+ }++ static char [] resolveOAuthToken(Properties info) throws PSQLException {+ validateOAuthIssuer(info);++ String tokenText = PGProperty.OAUTH_TOKEN.getOrDefault(info);+ if (tokenText != null && !tokenText.isEmpty()) {+ return tokenText.toCharArray();+ }++ String providerClassName = PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.getOrDefault(info);+ if (providerClassName != null && !providerClassName.isEmpty()) {+ OAuthTokenProvider provider;+ try {+ provider = ObjectFactory.instantiate(OAuthTokenProvider.class, providerClassName, info, false,+ null);+ } catch (Exception ex) {+ throw new PSQLException(+ GT.tr("Unable to load OAuth token provider {0}", providerClassName),+ PSQLState.INVALID_PARAMETER_VALUE, ex);+ }++ OAuthTokenRequest request = new OAuthTokenRequest(+ PGProperty.OAUTH_ISSUER.getOrDefault(info),+ PGProperty.OAUTH_CLIENT_ID.getOrDefault(info),+ PGProperty.OAUTH_CLIENT_SECRET.getOrDefault(info),+ PGProperty.OAUTH_SCOPE.getOrDefault(info));++ char [] token;+ try {+ token = provider.getToken(request);+ } catch (PSQLException ex) {+ throw ex;+ } catch (Exception ex) {+ throw new PSQLException(+ GT.tr("OAuth token provider {0} failed to return a token", providerClassName),+ PSQLState.CONNECTION_REJECTED, ex);+ }+ if (token == null || token.length == 0) {+ throw new PSQLException(+ GT.tr("OAuth token provider returned no token"),+ PSQLState.CONNECTION_REJECTED);+ }+ return token;+ }++ throw new PSQLException(+ GT.tr("The server requested OAuth authentication, but neither {0} nor {1} is configured.",+ PGProperty.OAUTH_TOKEN.getName(),+ PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.getName()),+ PSQLState.CONNECTION_REJECTED);+ }+
@Override
public QueryExecutor openConnectionImpl(HostSpec[] hostSpecs, Properties info) throws SQLException {
SslMode sslMode = SslMode.of(info);
@@ -637,7 +789,6 @@ private static PGStream enableGSSEncrypted(PGStream pgStream, GSSEncMode gssEncM
PGProperty.LOG_SERVER_ERROR_DETAIL.getBoolean(info));
return void.class;
});
- pgStream.setFinishedAuthenticationRequests();
return pgStream;
} catch (PSQLException ex) {
// allow the connection to proceed
@@ -791,7 +942,8 @@ private static String getAuthenticationMethodName(int authReq) {
}
}
- private static void doAuthentication(PGStream pgStream, String host, String user, Properties info) throws IOException, SQLException {+ private static void doAuthentication(PGStream pgStream, String host, String user,+ SslMode sslMode, Properties info) throws IOException, SQLException {
// Now get the response from the backend, either an error message
// or an authentication request
@@ -800,6 +952,10 @@ private static void doAuthentication(PGStream pgStream, String host, String user
/* SCRAM authentication state, if used */
ScramAuthenticator scramAuthenticator = null;
++ /* OAuth authentication state, if used */+ OAuthAuthenticator oauthAuthenticator = null;+
// TODO: figure out how to deal with new protocols
int protocol = 3 << 16;
@@ -807,8 +963,8 @@ private static void doAuthentication(PGStream pgStream, String host, String user
ChannelBinding channelBinding = ChannelBinding.of(info);
// Parse requireAuth property for authentication method validation
- String requireAuth = PGProperty.REQUIRE_AUTH.getOrDefault(info);- @Nullable EnumSet<AuthMethod> authMethods = AuthMethod.parseRequireAuth(requireAuth);+ @Nullable EnumSet<AuthMethod> authMethods =+ AuthMethod.parseRequireAuth(PGProperty.REQUIRE_AUTH.getOrDefault(info));
try {
int messages = 0;
@@ -1027,6 +1183,7 @@ private static void doAuthentication(PGStream pgStream, String host, String user
PGProperty.LOG_SERVER_ERROR_DETAIL.getBoolean(info));
return void.class;
});
+ pgStream.setFinishedAuthenticationRequests();
}
break;
@@ -1038,53 +1195,109 @@ private static void doAuthentication(PGStream pgStream, String host, String user
pgStream.setFinishedAuthenticationRequests();
break;
- case AUTH_REQ_SASL:- AuthMethod.checkAuth(authMethods, AuthMethod.SCRAM_SHA_256);- int scramMaxIterations = PGProperty.SCRAM_MAX_ITERATIONS.getInt(info);- if (scramMaxIterations < 0) {+ case AUTH_REQ_SASL: {+ // Check if no SASL exchange has been started yet.+ if (oauthAuthenticator != null || scramAuthenticator != null) {
throw new PSQLException(
- GT.tr("{0} must be a non-negative integer, but was: {1}",- PGProperty.SCRAM_MAX_ITERATIONS.getName(), scramMaxIterations),- PSQLState.INVALID_PARAMETER_VALUE);+ GT.tr("Server started a second SASL exchange."),+ PSQLState.PROTOCOL_VIOLATION);
}
- scramAuthenticator = AuthenticationPluginManager.<ScramAuthenticator>withPassword(AuthenticationRequestType.SASL, info, password -> {- if (password == null) {- throw new PSQLException(- GT.tr(- "The server requested SCRAM-based authentication, but no password was provided."),- PSQLState.CONNECTION_REJECTED);+ List<String> saslMechanisms = readMechanisms(pgStream, msgLen - 8);+ AuthMethod selectedMechanism =+ selectSaslMechanism(saslMechanisms, info, authMethods, channelBinding);++ switch (selectedMechanism) {+ case OAUTH: {+ boolean allowInsecure =+ PGProperty.OAUTH_ALLOW_INSECURE_CONNECTION.getBoolean(info);+ oauthAuthenticator = new OAuthAuthenticator(pgStream, sslMode, allowInsecure);+ char [] oauthToken = resolveOAuthToken(info);+ try {+ oauthAuthenticator.handleAuthenticationSASL(oauthToken);+ } finally {+ /* Cleanup token */+ Arrays.fill(oauthToken, (char) 0);+ }++ pgStream.setFinishedAuthenticationRequests();++ break;
}
- if (password.length == 0) {- throw new PSQLException(- GT.tr(- "The server requested SCRAM-based authentication, but the password is an empty string."),- PSQLState.CONNECTION_REJECTED);++ case SCRAM_SHA_256: {+ int scramMaxIterations = PGProperty.SCRAM_MAX_ITERATIONS.getInt(info);+ if (scramMaxIterations < 0) {+ throw new PSQLException(+ GT.tr("{0} must be a non-negative integer, but was: {1}",+ PGProperty.SCRAM_MAX_ITERATIONS.getName(), scramMaxIterations),+ PSQLState.INVALID_PARAMETER_VALUE);+ }+ scramAuthenticator =+ AuthenticationPluginManager.<ScramAuthenticator>withPassword(+ AuthenticationRequestType.SASL, info, password -> {+ if (password == null) {+ throw new PSQLException(+ GT.tr("The server requested SCRAM-based authentication,"+ + " but no password was provided."),+ PSQLState.CONNECTION_REJECTED);+ }+ if (password.length == 0) {+ throw new PSQLException(+ GT.tr("The server requested SCRAM-based authentication,"+ + " but the password is an empty string."),+ PSQLState.CONNECTION_REJECTED);+ }+ return new ScramAuthenticator(password, pgStream, channelBinding,+ scramMaxIterations, saslMechanisms);+ });+ scramAuthenticator.handleAuthenticationSASL();+ break;
}
- return new ScramAuthenticator(password, pgStream, channelBinding, scramMaxIterations);- });- scramAuthenticator.handleAuthenticationSASL();++ default:+ throw new PSQLException(+ GT.tr("Unexpected SASL mechanism selected: {0}", selectedMechanism),+ PSQLState.UNEXPECTED_ERROR);+ }
break;
+ }
case AUTH_REQ_SASL_CONTINUE:
- castNonNull(scramAuthenticator).handleAuthenticationSASLContinue(msgLen - 4 - 4);+ if (oauthAuthenticator != null) {+ // For OAUTHBEARER this message conveys the server's error result, and the dummy+ // response the authenticator sends back closes the client's side of the exchange+ // (RFC 7628 section 3.2.3). The server answers that with an ErrorResponse rather+ // than another authentication request, so the client is done sending; anything+ // else that arrives is rejected by the authenticator.+ oauthAuthenticator.handleAuthenticationSASLContinue(msgLen - 4 - 4);+ pgStream.setFinishedAuthenticationRequests();+ } else if (scramAuthenticator != null) {+ scramAuthenticator.handleAuthenticationSASLContinue(msgLen - 4 - 4);+ } else {+ throw new PSQLException(+ GT.tr("SASL CONTINUE message received out of order."),+ PSQLState.PROTOCOL_VIOLATION);+ }
break;
case AUTH_REQ_SASL_FINAL:
- castNonNull(scramAuthenticator).handleAuthenticationSASLFinal(msgLen - 4 - 4);- saslHandshakeCompleted = true;- pgStream.setFinishedAuthenticationRequests();+ if (scramAuthenticator != null) {+ scramAuthenticator.handleAuthenticationSASLFinal(msgLen - 4 - 4);+ saslHandshakeCompleted = true;+ pgStream.setFinishedAuthenticationRequests();+ } else {+ throw new PSQLException(+ GT.tr("SASL FINAL message received out of order."),+ PSQLState.PROTOCOL_VIOLATION);+ }
break;
case AUTH_REQ_OK:
- if (requireAuth != null) {- // this will happen if the authentication method is trust- if (!pgStream.isFinishedAuthenticationRequests()) {- AuthMethod.checkAuth(authMethods, AuthMethod.NONE);- }- if (pgStream.isGssEncrypted()) {- AuthMethod.checkAuth(authMethods, AuthMethod.GSS);- }+ if (oauthAuthenticator != null) {+ oauthAuthenticator.handleAuthenticationOk();
}
+ checkAuthenticationCompleted(authMethods,+ pgStream.isFinishedAuthenticationRequests(), pgStream.isGssEncrypted());
/* Cleanup after successful authentication */
LOGGER.log(Level.FINEST, " <=BE AuthenticationOk");
break authloop; // We're done.
@@ -1116,6 +1329,75 @@ private static void doAuthentication(PGStream pgStream, String host, String user
}
}
+ /**+ * Checks {@code requireAuth} on AuthenticationOk, where the handshake ends. Every request the+ * server sent was checked by {@link AuthMethod#checkAuth} as it arrived, so all that is left+ * here is the server that authenticates the connection without asking the client for anything.+ */+ static void checkAuthenticationCompleted(@Nullable EnumSet<AuthMethod> allowedMethods,+ boolean finishedAuthenticationRequests, boolean gssEncrypted) throws PSQLException {+ // Nothing to check: requireAuth is unset, or the client answered a request checkAuth allowed.+ if (allowedMethods == null || finishedAuthenticationRequests) {+ return;+ }+ // The server asked for nothing. Only none accepts that outright. gss accepts it when the+ // connection is GSS-encrypted, because that handshake authenticated the client and leaves+ // the server no reason to send an AuthenticationGSS request.+ if (allowedMethods.contains(AuthMethod.NONE)+ || (gssEncrypted && allowedMethods.contains(AuthMethod.GSS))) {+ return;+ }+ throw new PSQLException(+ GT.tr("The server accepted the connection without requesting authentication, which "+ + "requireAuth does not allow. Check the pg_hba.conf entry the server matched, or "+ + "add ''none'' to requireAuth to accept an unauthenticated connection."),+ PSQLState.CONNECTION_REJECTED);+ }++ /*+ * Reads the null-terminated mechanism list from an AuthenticationSASL message body.+ * For the format see https://www.postgresql.org/docs/current/protocol-message-formats.html#PROTOCOL-MESSAGE-FORMATS-AUTHE...+ */+ static List<String> readMechanisms(PGStream stream, int length)+ throws PSQLException, IOException {+ if (length < 1) {+ throw new PSQLException(+ GT.tr("Received AuthenticationSASL message with an invalid length: {0}.", length),+ PSQLState.PROTOCOL_VIOLATION);+ }++ byte[] body = stream.receive(length);+ if (body[length - 1] != 0) {+ throw new PSQLException(+ GT.tr("Received invalid AuthenticationSASL message."),+ PSQLState.PROTOCOL_VIOLATION);+ }++ List<String> mechanisms = new ArrayList<>();+ Encoding encoding = stream.getEncoding();+ int start = 0;+ for (int i = 0; i < length - 1; i++) {+ if (body[i] == 0) {+ mechanisms.add(encoding.decode(body, start, i - start));+ start = i + 1;+ }+ }++ if (start != length - 1) {+ throw new PSQLException(+ GT.tr("Received AuthenticationSASL message with invalid authentication mechanism list."),+ PSQLState.PROTOCOL_VIOLATION);+ }++ if (mechanisms.isEmpty()) {+ throw new PSQLException(+ GT.tr("Received AuthenticationSASL message with 0 mechanisms!"),+ PSQLState.CONNECTION_REJECTED);+ }+ LOGGER.log(Level.FINEST, " <=BE AuthenticationSASL( {0} )", mechanisms);+ return mechanisms;+ }+
private static void runInitialQueries(QueryExecutor queryExecutor, Properties info)
throws SQLException {
diff --git a/pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java b/pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.javanew file mode 100644index 0000000000..75a1a59183--- /dev/null+++ b/pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java@@ -0,0 +1,202 @@+/*+ * Copyright (c) 2026, PostgreSQL Global Development Group+ * See the LICENSE file in the project root for more information.+ */++package org.postgresql.core.v3;++import org.postgresql.core.PGStream;+import org.postgresql.core.PgMessageType;+import org.postgresql.jdbc.SslMode;+import org.postgresql.util.GT;+import org.postgresql.util.PSQLException;+import org.postgresql.util.PSQLState;++import org.checkerframework.checker.nullness.qual.Nullable;++import java.io.IOException;+import java.nio.ByteBuffer;+import java.nio.CharBuffer;+import java.nio.charset.StandardCharsets;+import java.util.Arrays;+import java.util.logging.Level;+import java.util.logging.Logger;+import java.util.regex.Pattern;++import javax.net.ssl.SSLSocket;++/**+ * Writes the client side of the OAUTHBEARER SASL exchange (RFC 7628) onto a {@link PGStream}.+ * One instance serves one authentication attempt, and the constructor enforces the encryption+ * requirement, so a caller holding an instance may send the token.+ */+final class OAuthAuthenticator {+ private static final Logger LOGGER = Logger.getLogger(OAuthAuthenticator.class.getName());+ static final String SASL_MECHANISM = "OAUTHBEARER";++ /** SOH byte (0x01) used as field separator in RFC 7628 SASL messages. */+ private static final byte SOH = 0x01;++ /**+ * OAuth bearer token characters per the grammar of RFC 6750 §2.1.+ */+ private static final Pattern TOKEN_REGEX = Pattern.compile("[A-Za-z0-9._~+/-]+=*");++ private final PGStream pgStream;+ private boolean serverError;++ OAuthAuthenticator(PGStream pgStream, SslMode sslMode, boolean allowInsecure)+ throws PSQLException {+ checkTransportSecurity(pgStream, sslMode, allowInsecure);+ this.pgStream = pgStream;+ }++ /**+ * Checks that connection to the server is secure, or that the user has+ * opted out of that requirement.+ */+ private static void checkTransportSecurity(PGStream pgStream, SslMode sslMode,+ boolean allowInsecure) throws PSQLException {++ if (pgStream.isGssEncrypted()) {+ return;+ }++ boolean encrypted = pgStream.getSocket() instanceof SSLSocket;+ if (encrypted && sslMode.verifyCertificate()) {+ return;+ }++ if (!allowInsecure) {+ throw new PSQLException(+ encrypted+ ? GT.tr("OAUTHBEARER authentication requires the server certificate to be verified "+ + "(RFC 7628 §3), and sslmode={0} does not verify it. Use sslmode=verify-ca or "+ + "sslmode=verify-full, or set oauthAllowInsecureConnection=true to override "+ + "(testing only).", sslMode.value)+ : GT.tr("OAUTHBEARER authentication requires a connection to a verified server "+ + "(TLS with sslmode=verify-ca or higher, or GSS encryption) (RFC 7628 §3). "+ + "Set oauthAllowInsecureConnection=true to override (testing only)."),+ PSQLState.CONNECTION_REJECTED);+ }++ if (encrypted) {+ LOGGER.log(Level.WARNING,+ "oauthAllowInsecureConnection=true: OAUTHBEARER is being used over a TLS connection "+ + "whose server certificate is not verified (sslmode={0}), so the bearer token may "+ + "be disclosed to an impostor. RFC 7628 §3 requires a secure channel. "+ + "Do not use this configuration in production.", sslMode.value);+ } else {+ LOGGER.log(Level.WARNING,+ "oauthAllowInsecureConnection=true: OAUTHBEARER is being used over an unencrypted "+ + "connection, so the bearer token is sent in the clear. RFC 7628 §3 requires a "+ + "secure channel. Do not use this configuration in production.");+ }+ }++ /**+ * Sends SASLInitialResponse with the bearer token.+ */+ void handleAuthenticationSASL(char @Nullable [] token) throws IOException, PSQLException {+ checkServerError();++ LOGGER.log(Level.FINEST, " FE=> SASLInitialResponse(OAUTHBEARER, auth=Bearer <token>)");+ sendSaslInitialResponse(buildTokenMessage(token));+ }++ /**+ * Reads the AuthenticationSASLContinue payload, which RFC 7628 §3.2.2 sends only to convey an+ * OAuth error result, and answers with the dummy response that completes the error message+ * sequence (§3.2.3).+ */+ void handleAuthenticationSASLContinue(int length) throws IOException, PSQLException {+ checkServerError();++ String json = pgStream.receiveString(length);+ LOGGER.log(Level.WARNING, "Server rejected OAuth bearer token: {0}", json);+ serverError = true;++ sendDummyResponse();+ }++ /**+ * Handles successful authentication.+ * Just checks that the authentication has not failed on previous steps.+ */+ void handleAuthenticationOk() throws PSQLException {+ checkServerError();+ }++ /**+ * Checks authentication state.+ */+ private void checkServerError() throws PSQLException {+ if (serverError) {+ throw new PSQLException(+ GT.tr("Server sent additional OAuth data after error."),+ PSQLState.PROTOCOL_VIOLATION);+ }+ }++ /**+ * Sends a SASLResponse with a single 0x01 byte, required by RFC 7628 §3.2.3 to complete the+ * error message sequence so the server can finish the exchange.+ */+ void sendDummyResponse() throws IOException {+ LOGGER.log(Level.FINEST, " FE=> SASLResponse(0x01)");+ pgStream.sendChar(PgMessageType.SASL_RESPONSE);+ pgStream.sendInteger4(Integer.BYTES + 1);+ pgStream.sendChar(1);+ pgStream.flush();+ }++ private void sendSaslInitialResponse(byte[] clientMessage) throws IOException {+ byte[] mechanismBytes = SASL_MECHANISM.getBytes(StandardCharsets.UTF_8);+ int bodyLength = mechanismBytes.length + 1 + Integer.BYTES + clientMessage.length;+ try {+ pgStream.sendChar(PgMessageType.SASL_INITIAL_RESPONSE);+ pgStream.sendInteger4(Integer.BYTES + bodyLength);+ pgStream.send(mechanismBytes);+ pgStream.sendChar(0);+ pgStream.sendInteger4(clientMessage.length);+ pgStream.send(clientMessage);+ } finally {+ /* Cleanup client message as it contains token, even when a send fails. */+ Arrays.fill(clientMessage, (byte) 0);+ }++ pgStream.flush();+ }++ /**+ * Builds the RFC 7628 SASL client message.+ */+ static byte[] buildTokenMessage(char @Nullable [] token) throws PSQLException {+ int tokenLen = token != null ? token.length : 0;+ // "n,,\x01auth=" = 9 bytes;+ // "Bearer " + token = 7 + tokenLen;+ // "\x01\x01" = 2 bytes+ int msgLen = 9 + (tokenLen > 0 ? 7 + tokenLen : 0) + 2;++ ByteBuffer msg = ByteBuffer.allocate(msgLen);+ msg.put("n,,".getBytes(StandardCharsets.UTF_8));+ msg.put(SOH);+ msg.put("auth=".getBytes(StandardCharsets.UTF_8));++ if (token != null && tokenLen > 0) {+ if (!TOKEN_REGEX.matcher(CharBuffer.wrap(token)).matches()) {+ throw new PSQLException(+ GT.tr("Invalid OAuth bearer token format. See RFC 6750 §2.1 for details."),+ PSQLState.CONNECTION_REJECTED);+ }++ msg.put("Bearer ".getBytes(StandardCharsets.UTF_8));+ for (char c : token) {+ msg.put((byte) c);+ }+ }+ msg.put(SOH).put(SOH);++ return msg.array();+ }+}diff --git a/pgjdbc/src/main/java/org/postgresql/core/v3/ScramAuthenticator.java b/pgjdbc/src/main/java/org/postgresql/core/v3/ScramAuthenticator.javaindex 227c5382cc..ef52b0b34a 100644--- a/pgjdbc/src/main/java/org/postgresql/core/v3/ScramAuthenticator.java+++ b/pgjdbc/src/main/java/org/postgresql/core/v3/ScramAuthenticator.java@@ -26,7 +26,6 @@
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
-import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -43,19 +42,26 @@ final class ScramAuthenticator {
private final int maxIterations;
ScramAuthenticator(char[] password, PGStream pgStream, ChannelBinding channelBinding,
- int maxIterations) throws PSQLException {+ int maxIterations, List<String> saslMechanisms) throws PSQLException {
this.pgStream = pgStream;
this.maxIterations = maxIterations;
- this.scramClient = initializeScramClient(password, pgStream, channelBinding);+ this.scramClient = initializeScramClient(password, pgStream, channelBinding, saslMechanisms);
}
- private static ScramClient initializeScramClient(char[] password, PGStream stream, ChannelBinding channelBinding) throws PSQLException {+ private static ScramClient initializeScramClient(char[] password, PGStream stream,+ ChannelBinding channelBinding, List<String> mechanisms) throws PSQLException {
try {
LOGGER.log(Level.FINEST, "channelBinding( {0} )", channelBinding);
+ if (channelBinding == ChannelBinding.REQUIRE+ && !mechanisms.stream().anyMatch(m -> m.endsWith("-PLUS"))) {+ throw new PSQLException(+ GT.tr("Channel Binding is required, but server did not offer an "+ + "authentication method that supports channel binding"),+ PSQLState.CONNECTION_REJECTED);+ }
final byte[] cbindData = getChannelBindingData(stream, channelBinding);
- final List<String> advertisedMechanisms = advertisedMechanisms(stream, channelBinding);
ScramClient client = ScramClient.builder()
- .advertisedMechanisms(advertisedMechanisms)+ .advertisedMechanisms(mechanisms)
.username("*") // username is ignored by server, startup message is used instead
.password(password)
.channelBinding(TlsServerEndpoint.TLS_SERVER_END_POINT, cbindData)
@@ -74,37 +80,13 @@ private static ScramClient initializeScramClient(char[] password, PGStream strea
LOGGER.log(Level.FINEST, () -> " Using SCRAM mechanism: "
+ client.getScramMechanism().getName());
return client;
- } catch (IllegalArgumentException | IOException e) {+ } catch (IllegalArgumentException e) {
throw new PSQLException(
GT.tr("Invalid SCRAM client initialization", e),
PSQLState.CONNECTION_REJECTED);
}
}
- private static List<String> advertisedMechanisms(PGStream stream, ChannelBinding channelBinding)- throws PSQLException, IOException {- List<String> mechanisms = new ArrayList<>();- do {- mechanisms.add(stream.receiveString());- } while (stream.peekChar() != 0);- int c = stream.receiveChar();- assert c == 0;- if (mechanisms.isEmpty()) {- throw new PSQLException(- GT.tr("Received AuthenticationSASL message with 0 mechanisms!"),- PSQLState.CONNECTION_REJECTED);- }- LOGGER.log(Level.FINEST, " <=BE AuthenticationSASL( {0} )", mechanisms);- if (channelBinding == ChannelBinding.REQUIRE- && !mechanisms.stream().anyMatch(m -> m.endsWith("-PLUS"))) {- throw new PSQLException(- GT.tr("Channel Binding is required, but server did not offer an "- + "authentication method that supports channel binding"),- PSQLState.CONNECTION_REJECTED);- }- return mechanisms;- }-
private static byte[] getChannelBindingData(PGStream stream, ChannelBinding channelBinding)
throws PSQLException {
if (channelBinding == ChannelBinding.DISABLE) {
diff --git a/pgjdbc/src/main/java/org/postgresql/ds/common/BaseDataSource.java b/pgjdbc/src/main/java/org/postgresql/ds/common/BaseDataSource.javaindex 204bb0355d..c84d0bb47f 100644--- a/pgjdbc/src/main/java/org/postgresql/ds/common/BaseDataSource.java+++ b/pgjdbc/src/main/java/org/postgresql/ds/common/BaseDataSource.java@@ -13,6 +13,7 @@
import org.postgresql.jdbc.PreferQueryMode;
import org.postgresql.util.ExpressionProperties;
import org.postgresql.util.GT;
+import org.postgresql.util.PGPropertyUtil;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.URLCoder;
@@ -95,20 +96,48 @@ public Connection getConnection() throws SQLException {
*/
public Connection getConnection(@Nullable String user, @Nullable String password)
throws SQLException {
+ // getUrl() carries no credentials, so it is also what gets logged below+ String url = getUrl();
try {
- Connection con = DriverManager.getConnection(getUrl(), user, password);+ Connection con = DriverManager.getConnection(url, getConnectionProperties(user, password));
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Created a {0} for {1} at {2}",
- new Object[]{getDescription(), user, getUrl()});+ new Object[]{getDescription(), user, url});
}
return con;
} catch (SQLException e) {
LOGGER.log(Level.FINE, "Failed to create a {0} for {1} at {2}: {3}",
- new Object[]{getDescription(), user, getUrl(), e});+ new Object[]{getDescription(), user, url, e});
throw e;
}
}
+ /**+ * Builds the connection properties.+ *+ * @param user user name to connect with, or null to connect without one+ * @param password password to connect with, or null to connect without one+ * @return properties holding the user name and every credential configured on this DataSource+ */+ private Properties getConnectionProperties(@Nullable String user, @Nullable String password) {+ Properties connectionProperties = new Properties();+ for (PGProperty property : PGProperty.values()) {+ if (property.isSensitive()) {+ String value = property.getSetString(properties);+ if (value != null) {+ property.set(connectionProperties, value);+ }+ }+ }+ if (user != null) {+ PGProperty.USER.set(connectionProperties, user);+ }+ if (password != null) {+ PGProperty.PASSWORD.set(connectionProperties, password);+ }+ return connectionProperties;+ }+
/**
* This implementation don't use a LogWriter.
*/
@@ -1455,6 +1484,7 @@ public void setScramMaxIterations(int scramMaxIterations) {
/**
* Generates a {@link DriverManager} URL from the other properties supplied.
+ * The URL carries no credentials, so it can be logged or shown in a message.
*
* @return {@link DriverManager} URL from the other properties supplied
*/
@@ -1485,7 +1515,8 @@ public String getUrl() {
StringBuilder query = new StringBuilder(100);
for (PGProperty property : PGProperty.values()) {
- if (property.isPresent(properties)) {+ // Credentials are skipped here and passed directly to the driver later.+ if (!property.isSensitive() && property.isPresent(properties)) {
if (query.length() != 0) {
query.append("&");
}
@@ -1505,9 +1536,11 @@ public String getUrl() {
}
/**
- * Generates a {@link DriverManager} URL from the other properties supplied.+ * Generates a {@link DriverManager} URL from the other properties supplied. Same as+ * {@link #getUrl()}, including the credentials it leaves out.
*
* @return {@link DriverManager} URL from the other properties supplied
+ * @see #getUrl()
*/
public String getURL() {
return getUrl();
@@ -1523,7 +1556,7 @@ public void setUrl(String url) {
Properties p = Driver.parseURL(url, null);
if (p == null) {
- throw new IllegalArgumentException("URL invalid " + url);+ throw new IllegalArgumentException("URL invalid " + PGPropertyUtil.maskSensitiveValues(url));
}
for (PGProperty property : PGProperty.values()) {
if (!this.properties.containsKey(property.getName())) {
@@ -1562,6 +1595,121 @@ public void setAuthenticationPluginClassName(String className) {
PGProperty.AUTHENTICATION_PLUGIN_CLASS_NAME.set(properties, className);
}
+ /**+ * @return OAuth 2.0 bearer token, or null if unset+ */+ public @Nullable String getOAuthToken() {+ return PGProperty.OAUTH_TOKEN.getOrDefault(properties);+ }++ /**+ * @param token OAuth 2.0 bearer token for authentication+ */+ public void setOAuthToken(String token) {+ PGProperty.OAUTH_TOKEN.set(properties, token);+ }++ /**+ * @return the class name to use for token provider, can be null+ */+ public @Nullable String getOAuthTokenProviderClassName() {+ return PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.getOrDefault(properties);+ }++ /**+ * @param className fully-qualified class implementing {@link org.postgresql.plugin.OAuthTokenProvider}+ * This class will be used to obtain the OAuth 2.0 bearer token.+ */+ public void setOAuthTokenProviderClassName(@Nullable String className) {+ PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.set(properties, className);+ }++ /**+ * @return OAuth issuer URL+ */+ public @Nullable String getOAuthIssuer() {+ return PGProperty.OAUTH_ISSUER.getOrDefault(properties);+ }++ /**+ * @param issuer OAuth issuer URL+ */+ public void setOAuthIssuer(String issuer) {+ PGProperty.OAUTH_ISSUER.set(properties, issuer);+ }++ /**+ * @return whether a non-HTTPS OAuth issuer URL is allowed+ */+ public boolean getOAuthAllowInsecureIssuer() {+ return PGProperty.OAUTH_ALLOW_INSECURE_ISSUER.getBoolean(properties);+ }++ /**+ * @param allowInsecure whether to allow a non-HTTPS OAuth issuer URL;+ * set to {@code true} only for development/testing+ */+ public void setOAuthAllowInsecureIssuer(boolean allowInsecure) {+ PGProperty.OAUTH_ALLOW_INSECURE_ISSUER.set(properties, allowInsecure);+ }++ /**+ * @return OAuth client ID+ */+ public @Nullable String getOAuthClientId() {+ return PGProperty.OAUTH_CLIENT_ID.getOrDefault(properties);+ }++ /**+ * @param clientId OAuth client ID+ */+ public void setOAuthClientId(String clientId) {+ PGProperty.OAUTH_CLIENT_ID.set(properties, clientId);+ }++ /**+ * @return OAuth client secret+ */+ public @Nullable String getOAuthClientSecret() {+ return PGProperty.OAUTH_CLIENT_SECRET.getOrDefault(properties);+ }++ /**+ * @param clientSecret OAuth client secret+ */+ public void setOAuthClientSecret(String clientSecret) {+ PGProperty.OAUTH_CLIENT_SECRET.set(properties, clientSecret);+ }++ /**+ * @return OAuth scope+ */+ public @Nullable String getOAuthScope() {+ return PGProperty.OAUTH_SCOPE.getOrDefault(properties);+ }++ /**+ * @param scope OAuth scope+ */+ public void setOAuthScope(String scope) {+ PGProperty.OAUTH_SCOPE.set(properties, scope);+ }++ /**+ * @return true if OAUTHBEARER is permitted over an insecure connection.+ */+ public boolean getOAuthAllowInsecureConnection() {+ return PGProperty.OAUTH_ALLOW_INSECURE_CONNECTION.getBoolean(properties);+ }++ /**+ * @param allow permits OAUTHBEARER authentication over an insecure connection or to+ * an unverified server. Intended for development only.+ */+ public void setOAuthAllowInsecureConnection(boolean allow) {+ PGProperty.OAUTH_ALLOW_INSECURE_CONNECTION.set(properties, allow);+ }+
public @Nullable String getProperty(String name) throws SQLException {
PGProperty pgProperty = PGProperty.forName(name);
if (pgProperty != null) {
diff --git a/pgjdbc/src/main/java/org/postgresql/plugin/OAuthTokenProvider.java b/pgjdbc/src/main/java/org/postgresql/plugin/OAuthTokenProvider.javanew file mode 100644index 0000000000..368952e159--- /dev/null+++ b/pgjdbc/src/main/java/org/postgresql/plugin/OAuthTokenProvider.java@@ -0,0 +1,41 @@+/*+ * Copyright (c) 2026, PostgreSQL Global Development Group+ * See the LICENSE file in the project root for more information.+ */++package org.postgresql.plugin;++import org.postgresql.util.PSQLException;++/**+ * Provides an OAuth 2.0 token for OAuth bearer authentication.+ *+ * <p>The driver instantiates the class named by the {@code oauthTokenProviderClassName}+ * connection property, so an implementation must declare either a constructor taking a single+ * {@link java.util.Properties} argument, which receives the connection properties, or a+ * no-argument constructor.</p>+ *+ * <p>{@link #getToken(OAuthTokenRequest)} is invoked once per connection attempt and therefore+ * runs on the connect path. It is not invoked at all when the {@code oauthToken} connection+ * property is set, as that token is used directly.</p>+ */+public interface OAuthTokenProvider {++ /**+ * Returns a token for OAuth authentication.+ *+ * <p>For security reasons, the driver will wipe the contents of the array returned+ * by this method after it has been used for authentication.</p>+ *+ * <p><b>Implementers must provide a new array each time this method is invoked as+ * the previous contents will have been wiped.</b></p>+ *+ * @param request holds the information that may be needed to obtain a token. A field is null+ * when the matching connection property is not set; implementers should ignore+ * fields they do not need.+ * @return the token; neither null nor empty+ * @throws PSQLException if the token cannot be obtained+ */+ char [] getToken(OAuthTokenRequest request) throws PSQLException;++}diff --git a/pgjdbc/src/main/java/org/postgresql/plugin/OAuthTokenRequest.java b/pgjdbc/src/main/java/org/postgresql/plugin/OAuthTokenRequest.javanew file mode 100644index 0000000000..f566e2d672--- /dev/null+++ b/pgjdbc/src/main/java/org/postgresql/plugin/OAuthTokenRequest.java@@ -0,0 +1,60 @@+/*+ * Copyright (c) 2026, PostgreSQL Global Development Group+ * See the LICENSE file in the project root for more information.+ */++package org.postgresql.plugin;++import org.checkerframework.checker.nullness.qual.Nullable;++/**+ * Context passed to {@link OAuthTokenProvider#getToken(OAuthTokenRequest)}.+ *+ * <p>A field is null when the matching connection property is not set.+ */+public final class OAuthTokenRequest {++ private final @Nullable String issuer;+ private final @Nullable String scope;+ private final @Nullable String clientId;+ private final @Nullable String clientSecret;++ public OAuthTokenRequest(+ @Nullable String issuer,+ @Nullable String clientId,+ @Nullable String clientSecret,+ @Nullable String scope) {+ this.issuer = issuer;+ this.clientId = clientId;+ this.clientSecret = clientSecret;+ this.scope = scope;+ }++ /**+ * @return the OAuth issuer URL.+ */+ public @Nullable String getIssuer() {+ return issuer;+ }++ /**+ * @return the OAuth client id.+ */+ public @Nullable String getClientId() {+ return clientId;+ }++ /**+ * @return the OAuth client secret.+ */+ public @Nullable String getClientSecret() {+ return clientSecret;+ }++ /**+ * @return the OAuth token scope.+ */+ public @Nullable String getScope() {+ return scope;+ }+}diff --git a/pgjdbc/src/main/java/org/postgresql/util/PGPropertyUtil.java b/pgjdbc/src/main/java/org/postgresql/util/PGPropertyUtil.javaindex 7505a4a06a..a7c1be0bcd 100644--- a/pgjdbc/src/main/java/org/postgresql/util/PGPropertyUtil.java+++ b/pgjdbc/src/main/java/org/postgresql/util/PGPropertyUtil.java@@ -21,6 +21,45 @@ public class PGPropertyUtil {
private static final Logger LOGGER = Logger.getLogger(PGPropertyUtil.class.getName());
+ private static final String MASKED_VALUE = "***";++ /**+ * Masks the value of every {@link PGProperty#isSensitive() sensitive} parameter in a JDBC URL, so+ * that the URL can be logged or put into an error message without disclosing credentials.+ *+ * @param url JDBC URL, possibly carrying credentials in its query string+ * @return the URL with the value of every sensitive parameter masked+ */+ public static String maskSensitiveValues(String url) {+ int qPos = url.indexOf('?');+ if (qPos == -1) {+ return url;+ }+ StringBuilder result = new StringBuilder(url.length());+ result.append(url, 0, qPos + 1);+ // Split the query string the same way Driver.parseURL does+ String[] args = url.substring(qPos + 1).split("&", -1);+ for (int i = 0; i < args.length; i++) {+ if (i > 0) {+ result.append('&');+ }+ String arg = args[i];+ int eqPos = arg.indexOf('=');+ if (eqPos == -1) {+ result.append(arg);+ continue;+ }+ String name = arg.substring(0, eqPos);+ PGProperty property = PGProperty.forName(name);+ if (property != null && property.isSensitive()) {+ result.append(name).append('=').append(MASKED_VALUE);+ } else {+ result.append(arg);+ }+ }+ return result.toString();+ }+
/**
* converts PGPORT String to Integer
*
diff --git a/pgjdbc/src/test/java/org/postgresql/core/AuthMethodTest.java b/pgjdbc/src/test/java/org/postgresql/core/AuthMethodTest.javaindex 6dfb1eef03..de05b69a2d 100644--- a/pgjdbc/src/test/java/org/postgresql/core/AuthMethodTest.java+++ b/pgjdbc/src/test/java/org/postgresql/core/AuthMethodTest.java@@ -9,7 +9,9 @@
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 static org.junit.jupiter.api.Assertions.assertTrue;+import org.postgresql.PGProperty;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
@@ -18,7 +20,10 @@
import org.junit.jupiter.params.provider.EnumSource;
import org.junit.jupiter.params.provider.ValueSource;
+import java.util.Arrays;
import java.util.EnumSet;
+import java.util.List;+import java.util.Locale;
/**
* An unset {@code requireAuth} allows every authentication method, and a
@@ -164,4 +169,41 @@ private static void assertParseError(String requireAuth) {
assertEquals(PSQLState.INVALID_PARAMETER_VALUE.getState(), e.getSQLState(),
"SQLState of the parse error");
}
++ /** The name {@code requireAuth} uses for a method, as {@code SCRAM_SHA_256} is scram-sha-256. */+ private static String requireAuthName(AuthMethod method) {+ return method.name().toLowerCase(Locale.ROOT).replace('_', '-');+ }++ @ParameterizedTest+ @EnumSource(AuthMethod.class)+ void everyMethodIsParsedFromItsRequireAuthName(AuthMethod method) throws Exception {+ assertEquals(method, AuthMethod.fromString(requireAuthName(method)));+ }++ @ParameterizedTest+ @EnumSource(AuthMethod.class)+ void everyMethodIsOfferedByRequireAuthInBothForms(AuthMethod method) {+ List<String> choices = Arrays.asList(PGProperty.REQUIRE_AUTH.getChoices());+ String name = requireAuthName(method);++ assertTrue(choices.contains(name), name + " is missing from the requireAuth choices " + choices);+ assertTrue(choices.contains("!" + name),+ "!" + name + " is missing from the requireAuth choices " + choices);+ }++ @Test+ void requireAuthOffersNothingBeyondTheMethods() {+ List<String> choices = Arrays.asList(PGProperty.REQUIRE_AUTH.getChoices());++ assertEquals(2 * AuthMethod.values().length, choices.size(),+ "requireAuth should offer each method and its negation, and nothing else: " + choices);+ }++ @Test+ void anUnknownMethodIsRejected() {+ PSQLException ex = assertThrows(PSQLException.class, () -> AuthMethod.fromString("oauth2"));++ assertEquals(PSQLState.INVALID_PARAMETER_VALUE.getState(), ex.getSQLState());+ }
}
diff --git a/pgjdbc/src/test/java/org/postgresql/core/MaliciousBackendTest.java b/pgjdbc/src/test/java/org/postgresql/core/MaliciousBackendTest.javaindex 4b0e01d181..24ef354154 100644--- a/pgjdbc/src/test/java/org/postgresql/core/MaliciousBackendTest.java+++ b/pgjdbc/src/test/java/org/postgresql/core/MaliciousBackendTest.java@@ -12,6 +12,7 @@
import org.postgresql.PGProperty;
import org.postgresql.core.v3.ConnectionFactoryImpl;
+import org.postgresql.jdbc.SslMode;
import org.postgresql.util.HostSpec;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
@@ -385,10 +386,10 @@ private static int countPasswordMessages(byte[] written) {
/** doAuthentication is private. */
private static void authenticate(PGStream stream, Properties info) throws Exception {
Method method = ConnectionFactoryImpl.class.getDeclaredMethod("doAuthentication",
- PGStream.class, String.class, String.class, Properties.class);+ PGStream.class, String.class, String.class, SslMode.class, Properties.class);
method.setAccessible(true);
try {
- method.invoke(null, stream, "localhost", "test", info);+ method.invoke(null, stream, "localhost", "test", SslMode.DISABLE, info);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof Exception) {
throw (Exception) e.getCause();
diff --git a/pgjdbc/src/test/java/org/postgresql/core/v3/BuildTokenMessageTest.java b/pgjdbc/src/test/java/org/postgresql/core/v3/BuildTokenMessageTest.javanew file mode 100644index 0000000000..5ac919d77e--- /dev/null+++ b/pgjdbc/src/test/java/org/postgresql/core/v3/BuildTokenMessageTest.java@@ -0,0 +1,76 @@+/*+ * Copyright (c) 2026, PostgreSQL Global Development Group+ * See the LICENSE file in the project root for more information.+ */++package org.postgresql.core.v3;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.params.provider.Arguments.argumentSet;++import org.postgresql.util.PSQLException;+import org.postgresql.util.PSQLState;++import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.Arguments;+import org.junit.jupiter.params.provider.MethodSource;++import java.nio.charset.StandardCharsets;+import java.util.stream.Stream;++class BuildTokenMessageTest {+ static Stream<Arguments> validTokens() {+ return Stream.of(+ argumentSet("token using every permitted character",+ "abc123-._~+/=", "n,,\u0001auth=Bearer abc123-._~+/=\u0001\u0001"),+ argumentSet("token of a single character",+ "a", "n,,\u0001auth=Bearer a\u0001\u0001"),+ argumentSet("token with two padding characters",+ "abc==", "n,,\u0001auth=Bearer abc==\u0001\u0001"));+ }++ @ParameterizedTest+ @MethodSource("validTokens")+ void validToken(String token, String expected) throws PSQLException {+ byte[] message = OAuthAuthenticator.buildTokenMessage(token.toCharArray());+ assertEquals(expected, new String(message, StandardCharsets.UTF_8));+ }++ @Test+ void nullToken() throws PSQLException {+ byte[] message = OAuthAuthenticator.buildTokenMessage(null);+ assertEquals("n,,\u0001auth=\u0001\u0001", new String(message, StandardCharsets.UTF_8));+ }++ @Test+ void emptyToken() throws PSQLException {+ byte[] message = OAuthAuthenticator.buildTokenMessage("".toCharArray());+ assertEquals("n,,\u0001auth=\u0001\u0001", new String(message, StandardCharsets.UTF_8));+ }++ static Stream<Arguments> invalidTokens() {+ return Stream.of(+ argumentSet("token containing a space", "has space"),+ argumentSet("token containing a tab", "tab\there"),+ argumentSet("token containing a newline", "newline\nhere"),+ argumentSet("token containing SOH", "soh\u0001here"),+ argumentSet("token containing a comma", "comma,here"),+ argumentSet("token containing an at sign", "at@sign"),+ argumentSet("token containing a double quote", "quote\"here"),+ argumentSet("token containing a backslash", "back\\slash"),+ argumentSet("padding with no preceding character", "="),+ argumentSet("padding character in the middle", "abc=def"),+ argumentSet("token containing a Latin-1 character", "töken"),+ argumentSet("token containing a character above U+00FF", "Ābc"));+ }++ @ParameterizedTest+ @MethodSource("invalidTokens")+ void invalidToken(String token) {+ PSQLException ex = assertThrows(PSQLException.class,+ () -> OAuthAuthenticator.buildTokenMessage(token.toCharArray()));+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ }+}diff --git a/pgjdbc/src/test/java/org/postgresql/core/v3/CheckAuthenticationCompletedTest.java b/pgjdbc/src/test/java/org/postgresql/core/v3/CheckAuthenticationCompletedTest.javanew file mode 100644index 0000000000..2c86204865--- /dev/null+++ b/pgjdbc/src/test/java/org/postgresql/core/v3/CheckAuthenticationCompletedTest.java@@ -0,0 +1,109 @@+/*+ * Copyright (c) 2026, PostgreSQL Global Development Group+ * See the LICENSE file in the project root for more information.+ */++package org.postgresql.core.v3;++import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+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 org.postgresql.core.AuthMethod;+import org.postgresql.util.PSQLException;+import org.postgresql.util.PSQLState;++import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.EnumSource;++import java.util.EnumSet;++/**+ * Covers the {@code requireAuth} check the driver makes on AuthenticationOk, where what is left+ * to rule out is a server that authenticated the connection without asking the client for+ * anything.+ */+class CheckAuthenticationCompletedTest {++ /** requireAuth is met by an authentication exchange the client completed, whatever it was. */+ @ParameterizedTest+ @EnumSource(AuthMethod.class)+ void aCompletedExchangeMeetsRequireAuth(AuthMethod method) throws Exception {+ EnumSet<AuthMethod> allowed = EnumSet.of(method);++ ConnectionFactoryImpl.checkAuthenticationCompleted(allowed, true, false);+ ConnectionFactoryImpl.checkAuthenticationCompleted(allowed, true, true);+ }++ /**+ * The server authenticating the connection without asking the client for anything is what+ * requireAuth is there to rule out, unless none is among the methods it allows.+ */+ @ParameterizedTest+ @EnumSource(AuthMethod.class)+ void onlyNoneMeetsRequireAuthWithoutAnExchange(AuthMethod method) {+ EnumSet<AuthMethod> allowed = EnumSet.of(method);++ if (method == AuthMethod.NONE) {+ assertDoesNotThrow(+ () -> ConnectionFactoryImpl.checkAuthenticationCompleted(allowed, false, false));+ return;+ }++ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.checkAuthenticationCompleted(allowed, false, false));+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ }++ /**+ * Establishing GSS encryption authenticates the client, so the server has no reason to send an+ * AuthenticationGSS request, and requireAuth=gss holds all the same.+ */+ @Test+ void gssEncryptionMeetsRequireAuthGssWithoutAnExchange() throws Exception {+ ConnectionFactoryImpl.checkAuthenticationCompleted(EnumSet.of(AuthMethod.GSS), false, true);+ }++ /** GSS encryption stands in for a GSS request only, not for whatever else was required. */+ @Test+ void gssEncryptionDoesNotMeetRequireAuthForAnotherMethod() {+ EnumSet<AuthMethod> allowed = EnumSet.of(AuthMethod.SCRAM_SHA_256, AuthMethod.OAUTH);++ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.checkAuthenticationCompleted(allowed, false, true));+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ }++ /**+ * A GSS-encrypted connection that then authenticated with OAUTHBEARER or SCRAM meets a+ * requireAuth naming that method: the encryption does not have to be named as well.+ */+ @ParameterizedTest+ @EnumSource(value = AuthMethod.class, names = {"OAUTH", "SCRAM_SHA_256", "PASSWORD", "MD5"})+ void anExchangeOverGssEncryptionDoesNotAlsoRequireGss(AuthMethod method) throws Exception {+ ConnectionFactoryImpl.checkAuthenticationCompleted(EnumSet.of(method), true, true);+ }++ /**+ * The refusal names {@code none} as what would allow the connection. Its quotes reach the user+ * only if they are doubled in the source, since GT.tr runs every message through MessageFormat.+ */+ @Test+ void theRefusalNamesNoneAsWhatWouldAllowTheConnection() {+ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.checkAuthenticationCompleted(+ EnumSet.of(AuthMethod.SCRAM_SHA_256), false, false));++ assertTrue(ex.getMessage().contains("'none'"), ex.getMessage());+ }++ /** With requireAuth unset there is nothing to check, however the connection was authenticated. */+ @Test+ void anUnsetRequireAuthAllowsEveryOutcome() throws Exception {+ ConnectionFactoryImpl.checkAuthenticationCompleted(null, false, false);+ ConnectionFactoryImpl.checkAuthenticationCompleted(null, false, true);+ ConnectionFactoryImpl.checkAuthenticationCompleted(null, true, false);+ }+}diff --git a/pgjdbc/src/test/java/org/postgresql/core/v3/OAuthHandshakeTest.java b/pgjdbc/src/test/java/org/postgresql/core/v3/OAuthHandshakeTest.javanew file mode 100644index 0000000000..2dd0d69743--- /dev/null+++ b/pgjdbc/src/test/java/org/postgresql/core/v3/OAuthHandshakeTest.java@@ -0,0 +1,469 @@+/*+ * Copyright (c) 2026, PostgreSQL Global Development Group+ * See the LICENSE file in the project root for more information.+ */++package org.postgresql.core.v3;++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.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++import org.postgresql.plugin.OAuthTokenProvider;+import org.postgresql.plugin.OAuthTokenRequest;+import org.postgresql.util.GT;+import org.postgresql.util.PSQLException;+import org.postgresql.util.PSQLState;++import org.checkerframework.checker.nullness.qual.Nullable;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.Timeout;++import java.io.ByteArrayOutputStream;+import java.io.Closeable;+import java.io.IOException;+import java.io.InputStream;+import java.io.OutputStream;+import java.net.InetAddress;+import java.net.ServerSocket;+import java.net.Socket;+import java.nio.charset.StandardCharsets;+import java.sql.DriverManager;+import java.sql.SQLException;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;+import java.util.concurrent.TimeUnit;++/**+ * Drives the OAUTHBEARER exchange against a backend that speaks a scripted conversation over+ * loopback, so the sequences no real server produces can be sent: a rejection followed by+ * {@code AuthenticationOk}, SASL CONTINUE or FINAL arriving before a mechanism was selected, and a+ * second mechanism offered once the exchange is under way.+ * The backend also records what the driver wrote, which pins the bytes of the two client+ * messages RFC 7628 specifies.+ */+class OAuthHandshakeTest {++ private static final String TOKEN = "test-token";++ /** The client message of RFC 7628 section 3.1, as the driver should build it for {@link #TOKEN}. */+ private static final byte[] CLIENT_MESSAGE =+ ("n,,\u0001auth=Bearer " + TOKEN + "\u0001\u0001").getBytes(StandardCharsets.UTF_8);++ private static final String ERROR_JSON = "{\"status\":\"invalid_token\",\"scope\":\"openid\"}";++ private static final int SSL_REQUEST = 80877103;+ private static final int GSS_ENC_REQUEST = 80877104;++ private static final int AUTH_REQ_OK = 0;+ private static final int AUTH_REQ_SASL = 10;+ private static final int AUTH_REQ_SASL_CONTINUE = 11;+ private static final int AUTH_REQ_SASL_FINAL = 12;++ /** The part of a conversation that follows the startup packet. */+ @FunctionalInterface+ private interface Conversation {+ void run(Backend backend, InputStream in, OutputStream out) throws IOException;+ }++ /**+ * Answers the startup packet with a scripted conversation and records every message the driver+ * writes in reply.+ */+ private static class Backend implements Closeable, Runnable {+ private final ServerSocket serverSocket;+ private final Conversation conversation;+ private final List<byte[]> clientMessages = Collections.synchronizedList(new ArrayList<>());+ private volatile boolean closed;++ Backend(Conversation conversation) throws IOException {+ this.conversation = conversation;+ this.serverSocket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"));+ this.serverSocket.setSoTimeout(30000);+ Thread thread = new Thread(this, "oauth-backend");+ thread.setDaemon(true);+ thread.start();+ }++ String getUrl(String oauthProperties) {+ return "jdbc:postgresql://127.0.0.1:" + serverSocket.getLocalPort() + "/test"+ + "?user=test&sslmode=disable&oauthAllowInsecureConnection=true&" + oauthProperties+ + "&connectTimeout=10&socketTimeout=10&loginTimeout=10";+ }++ /** The messages the driver wrote after the startup packet, each with its type and length. */+ List<byte[]> getClientMessages() {+ synchronized (clientMessages) {+ return new ArrayList<>(clientMessages);+ }+ }++ @Override+ public void run() {+ while (!closed) {+ Socket socket = null;+ try {+ socket = serverSocket.accept();+ socket.setSoTimeout(30000);+ InputStream in = socket.getInputStream();+ OutputStream out = socket.getOutputStream();+ consumeStartup(in, out);+ conversation.run(this, in, out);+ while (in.read() >= 0) {+ // Wait for the driver to close from its end.+ }+ } catch (Exception e) {+ // The driver hanging up mid-conversation is the expected outcome.+ } finally {+ closeQuietly(socket);+ }+ }+ }++ /** Reads one frontend message and records it whole, type byte and length included. */+ byte[] readClientMessage(InputStream in) throws IOException {+ int type = in.read();+ if (type < 0) {+ throw new IOException("end of stream before a frontend message");+ }+ int length = readInt4(in);+ byte[] message = new byte[1 + length];+ message[0] = (byte) type;+ writeInt4(message, 1, length);+ for (int i = 5; i < message.length; i++) {+ int b = in.read();+ if (b < 0) {+ throw new IOException("end of stream inside a frontend message");+ }+ message[i] = (byte) b;+ }+ clientMessages.add(message);+ return message;+ }++ private static void consumeStartup(InputStream in, OutputStream out) throws IOException {+ while (true) {+ int length = readInt4(in);+ byte[] body = new byte[length - 4];+ for (int i = 0; i < body.length; i++) {+ int b = in.read();+ if (b < 0) {+ throw new IOException("end of stream in startup packet");+ }+ body[i] = (byte) b;+ }+ int code = length == 8 ? ((body[0] & 0xFF) << 24) | ((body[1] & 0xFF) << 16)+ | ((body[2] & 0xFF) << 8) | (body[3] & 0xFF) : 0;+ if (code != SSL_REQUEST && code != GSS_ENC_REQUEST) {+ return;+ }+ out.write('N');+ out.flush();+ }+ }++ private static int readInt4(InputStream in) throws IOException {+ int value = 0;+ for (int i = 0; i < 4; i++) {+ int b = in.read();+ if (b < 0) {+ throw new IOException("end of stream");+ }+ value = (value << 8) | b;+ }+ return value;+ }++ private static void closeQuietly(@Nullable Socket socket) {+ if (socket != null) {+ try {+ socket.close();+ } catch (IOException ignore) {+ // nothing to do+ }+ }+ }++ @Override+ public void close() {+ closed = true;+ try {+ serverSocket.close();+ } catch (IOException ignore) {+ // nothing to do+ }+ }+ }++ private static void writeInt4(byte[] target, int offset, int value) {+ target[offset] = (byte) (value >>> 24);+ target[offset + 1] = (byte) (value >>> 16);+ target[offset + 2] = (byte) (value >>> 8);+ target[offset + 3] = (byte) value;+ }++ private static byte[] message(char type, byte[] body) {+ byte[] out = new byte[5 + body.length];+ out[0] = (byte) type;+ writeInt4(out, 1, body.length + 4);+ System.arraycopy(body, 0, out, 5, body.length);+ return out;+ }++ private static byte[] bytes(byte[]... parts) {+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ for (byte[] part : parts) {+ out.write(part, 0, part.length);+ }+ return out.toByteArray();+ }++ private static byte[] int4(int value) {+ byte[] out = new byte[4];+ writeInt4(out, 0, value);+ return out;+ }++ private static byte[] cstring(String value) {+ return bytes(value.getBytes(StandardCharsets.UTF_8), new byte[]{0});+ }++ /** {@code AuthenticationSASL} offering the given mechanisms, in order. */+ private static byte[] authenticationSasl(String... mechanisms) {+ ByteArrayOutputStream body = new ByteArrayOutputStream();+ byte[] request = int4(AUTH_REQ_SASL);+ body.write(request, 0, request.length);+ for (String mechanism : mechanisms) {+ byte[] name = cstring(mechanism);+ body.write(name, 0, name.length);+ }+ body.write(0);+ return message('R', body.toByteArray());+ }++ /** {@code AuthenticationSASLContinue}, which RFC 7628 uses to convey the OAuth error result. */+ private static byte[] authenticationSaslContinue() {+ return message('R', bytes(int4(AUTH_REQ_SASL_CONTINUE),+ ERROR_JSON.getBytes(StandardCharsets.UTF_8)));+ }++ private static byte[] authenticationSaslFinal() {+ return message('R', bytes(int4(AUTH_REQ_SASL_FINAL),+ "v=irrelevant".getBytes(StandardCharsets.UTF_8)));+ }++ private static byte[] authenticationOk() {+ return message('R', int4(AUTH_REQ_OK));+ }++ private static byte[] readyForQuery() {+ return message('Z', new byte[]{'I'});+ }++ private static byte[] errorResponse() {+ return message('E', bytes(+ cstring("SFATAL"),+ cstring("C28000"),+ cstring("MOAUTHBEARER authentication failed for user \"test\""),+ new byte[]{0}));+ }++ private static void send(OutputStream out, byte[]... messages) throws IOException {+ for (byte[] m : messages) {+ out.write(m);+ }+ out.flush();+ }++ /** Every exception in the chain with its SQLSTATE, so a failure says what actually arrived. */+ private static String describe(Throwable t) {+ StringBuilder sb = new StringBuilder();+ for (Throwable c = t; c != null && c != c.getCause(); c = c.getCause()) {+ if (sb.length() > 0) {+ sb.append(", caused by ");+ }+ sb.append(c);+ if (c instanceof SQLException) {+ sb.append(" [").append(((SQLException) c).getSQLState()).append(']');+ }+ }+ return sb.toString();+ }++ private static PSQLException findViolation(Throwable t) {+ for (Throwable c = t; c != null && c != c.getCause(); c = c.getCause()) {+ if (c instanceof PSQLException+ && PSQLState.PROTOCOL_VIOLATION.getState().equals(((PSQLException) c).getSQLState())) {+ return (PSQLException) c;+ }+ }+ throw new AssertionError("expected a PROTOCOL_VIOLATION in the chain, got: " + describe(t));+ }++ private static SQLException connectExpectingFailure(Backend backend) {+ return assertThrows(SQLException.class,+ () -> DriverManager.getConnection(backend.getUrl("oauthToken=" + TOKEN)).close());+ }++ private static void assertProtocolViolation(Conversation conversation, String expectedMessage)+ throws IOException {+ try (Backend backend = new Backend(conversation)) {+ PSQLException violation = findViolation(connectExpectingFailure(backend));+ assertEquals(expectedMessage, violation.getMessage());+ }+ }++ /**+ * RFC 4422 section 3.6, which RFC 7628 section 3.2.3 follows, ends the exchange at the error.+ * The driver must not accept the connection the server offers after it rejected the token.+ */+ @Test+ @Timeout(value = 30, unit = TimeUnit.SECONDS)+ void refusesAuthenticationOkAfterTheServerRejectedTheToken() throws IOException {+ assertProtocolViolation((backend, in, out) -> {+ send(out, authenticationSasl("OAUTHBEARER"));+ backend.readClientMessage(in);+ send(out, authenticationSaslContinue());+ backend.readClientMessage(in);+ send(out, authenticationOk(), readyForQuery());+ }, GT.tr("Server sent additional OAuth data after error."));+ }++ /** The same sequence, with {@code AuthenticationSASLFinal} in place of {@code AuthenticationOk}. */+ @Test+ @Timeout(value = 30, unit = TimeUnit.SECONDS)+ void refusesSaslFinalAfterTheServerRejectedTheToken() throws IOException {+ assertProtocolViolation((backend, in, out) -> {+ send(out, authenticationSasl("OAUTHBEARER"));+ backend.readClientMessage(in);+ send(out, authenticationSaslContinue());+ backend.readClientMessage(in);+ send(out, authenticationSaslFinal());+ }, GT.tr("SASL FINAL message received out of order."));+ }++ /**+ * A server that starts an OAUTHBEARER exchange and then offers SCRAM violates the protocol,+ * which only allows one SASL exchange per connection.+ */+ @Test+ @Timeout(value = 30, unit = TimeUnit.SECONDS)+ void refusesASecondSaslExchange() throws IOException {+ try (Backend backend = new Backend((b, in, out) -> {+ send(out, authenticationSasl("OAUTHBEARER"));+ b.readClientMessage(in);+ send(out, authenticationSasl("SCRAM-SHA-256"), authenticationSaslContinue());+ })) {+ SQLException failure = assertThrows(SQLException.class,+ () -> DriverManager.getConnection(+ backend.getUrl("oauthToken=" + TOKEN + "&password=secret")).close());+ assertEquals(GT.tr("Server started a second SASL exchange."),+ findViolation(failure).getMessage());+ }+ }++ @Test+ @Timeout(value = 30, unit = TimeUnit.SECONDS)+ void refusesSaslContinueBeforeAMechanismWasSelected() throws IOException {+ assertProtocolViolation((backend, in, out) -> send(out, authenticationSaslContinue()),+ GT.tr("SASL CONTINUE message received out of order."));+ }++ @Test+ @Timeout(value = 30, unit = TimeUnit.SECONDS)+ void refusesSaslFinalBeforeAMechanismWasSelected() throws IOException {+ assertProtocolViolation((backend, in, out) -> send(out, authenticationSaslFinal()),+ GT.tr("SASL FINAL message received out of order."));+ }++ /**+ * The whole {@code SASLInitialResponse}, so an off-by-one in either of its two lengths fails+ * here rather than only against a live server.+ */+ @Test+ @Timeout(value = 30, unit = TimeUnit.SECONDS)+ void sendsTheTokenInASaslInitialResponse() throws IOException {+ try (Backend backend = new Backend((b, in, out) -> {+ send(out, authenticationSasl("OAUTHBEARER"));+ b.readClientMessage(in);+ send(out, errorResponse());+ })) {+ connectExpectingFailure(backend);++ List<byte[]> written = backend.getClientMessages();+ assertEquals(1, written.size(), "expected the SASLInitialResponse alone");+ assertArrayEquals(+ bytes(+ new byte[]{'p'},+ int4(4 + "OAUTHBEARER".length() + 1 + 4 + CLIENT_MESSAGE.length),+ cstring("OAUTHBEARER"),+ int4(CLIENT_MESSAGE.length),+ CLIENT_MESSAGE),+ written.get(0));+ }+ }++ /** The response RFC 7628 section 3.2.3 requires: one message carrying a single 0x01 byte. */+ @Test+ @Timeout(value = 30, unit = TimeUnit.SECONDS)+ void answersTheRejectionWithASingleSohByte() throws IOException {+ try (Backend backend = new Backend((b, in, out) -> {+ send(out, authenticationSasl("OAUTHBEARER"));+ b.readClientMessage(in);+ send(out, authenticationSaslContinue());+ b.readClientMessage(in);+ send(out, errorResponse());+ })) {+ connectExpectingFailure(backend);++ List<byte[]> written = backend.getClientMessages();+ assertEquals(2, written.size(), "expected the SASLInitialResponse and the dummy response");+ assertArrayEquals(new byte[]{'p', 0, 0, 0, 5, 1}, written.get(1));+ }+ }++ /**+ * Records the array it handed the driver, so the test can read it back after the connection+ * attempt. {@link OAuthTokenProvider} promises the driver zeroes it.+ */+ public static class RecordingProvider implements OAuthTokenProvider {+ static char @Nullable [] lastToken;++ @Override+ public char[] getToken(OAuthTokenRequest request) {+ char[] token = "provider-token".toCharArray();+ lastToken = token;+ return token;+ }+ }++ @Test+ @Timeout(value = 30, unit = TimeUnit.SECONDS)+ void wipesTheTokenTheProviderReturned() throws IOException {+ RecordingProvider.lastToken = null;+ try (Backend backend = new Backend((b, in, out) -> {+ send(out, authenticationSasl("OAUTHBEARER"));+ b.readClientMessage(in);+ send(out, errorResponse());+ })) {+ String url = backend.getUrl(+ "oauthTokenProviderClassName=" + RecordingProvider.class.getName());+ assertThrows(SQLException.class, () -> DriverManager.getConnection(url).close());++ char[] token = RecordingProvider.lastToken;+ assertNotNull(token, "the provider should have been called");+ char[] wiped = new char[token.length];+ assertArrayEquals(wiped, token,+ "the driver should zero the array the provider returned, but it held: "+ + new String(token));+ // The token still has to have reached the wire, or zeroing it proves nothing.+ List<byte[]> written = backend.getClientMessages();+ assertEquals(1, written.size());+ assertTrue(new String(written.get(0), StandardCharsets.UTF_8).contains("Bearer provider-token"),+ "the SASLInitialResponse should carry the token the provider returned");+ }+ }+}diff --git a/pgjdbc/src/test/java/org/postgresql/core/v3/ResolveOAuthTokenTest.java b/pgjdbc/src/test/java/org/postgresql/core/v3/ResolveOAuthTokenTest.javanew file mode 100644index 0000000000..4600cfd11e--- /dev/null+++ b/pgjdbc/src/test/java/org/postgresql/core/v3/ResolveOAuthTokenTest.java@@ -0,0 +1,147 @@+/*+ * Copyright (c) 2026, PostgreSQL Global Development Group+ * See the LICENSE file in the project root for more information.+ */++package org.postgresql.core.v3;++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.assertThrows;++import org.postgresql.PGProperty;+import org.postgresql.plugin.OAuthTokenProvider;+import org.postgresql.plugin.OAuthTokenRequest;+import org.postgresql.util.GT;+import org.postgresql.util.PSQLException;+import org.postgresql.util.PSQLState;++import org.checkerframework.checker.nullness.qual.Nullable;+import org.junit.jupiter.api.Test;++import java.util.Properties;++class ResolveOAuthTokenTest {++ /**+ * Records the request the driver builds, so the test can assert every connection property+ * reaches the provider.+ */+ public static class RecordingProvider implements OAuthTokenProvider {+ static @Nullable OAuthTokenRequest lastRequest;++ @Override+ public char[] getToken(OAuthTokenRequest request) {+ lastRequest = request;+ return "recorded-token".toCharArray();+ }+ }++ /** Returns an array of length zero, which the driver must refuse. */+ public static class EmptyTokenProvider implements OAuthTokenProvider {+ @Override+ public char[] getToken(OAuthTokenRequest request) {+ return new char[0];+ }+ }++ /** Returns no token at all, which the driver must refuse just as it refuses an empty one. */+ public static class NullTokenProvider implements OAuthTokenProvider {+ @SuppressWarnings("return")+ @Override+ public char @Nullable [] getToken(OAuthTokenRequest request) {+ return null;+ }+ }++ private static Properties providerProps() {+ Properties info = new Properties();+ PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.set(info, RecordingProvider.class.getName());+ PGProperty.OAUTH_ISSUER.set(info, "https://issuer.example.com";);+ PGProperty.OAUTH_CLIENT_ID.set(info, "client-id");+ PGProperty.OAUTH_CLIENT_SECRET.set(info, "client-secret");+ PGProperty.OAUTH_SCOPE.set(info, "scope");+ return info;+ }++ @Test+ void requestCarriesEveryOAuthProperty() throws Exception {+ RecordingProvider.lastRequest = null;++ assertArrayEquals("recorded-token".toCharArray(),+ ConnectionFactoryImpl.resolveOAuthToken(providerProps()));++ OAuthTokenRequest request = RecordingProvider.lastRequest;+ assertNotNull(request, "The provider should have been called");+ assertEquals("https://issuer.example.com";, request.getIssuer());+ assertEquals("client-id", request.getClientId());+ assertEquals("client-secret", request.getClientSecret());+ assertEquals("scope", request.getScope());+ }++ @Test+ void unsetPropertiesArriveAsNull() throws Exception {+ RecordingProvider.lastRequest = null;++ Properties info = new Properties();+ PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.set(info, RecordingProvider.class.getName());+ ConnectionFactoryImpl.resolveOAuthToken(info);++ OAuthTokenRequest request = RecordingProvider.lastRequest;+ assertNotNull(request, "The provider should have been called");+ assertEquals(null, request.getIssuer());+ assertEquals(null, request.getClientId());+ assertEquals(null, request.getClientSecret());+ assertEquals(null, request.getScope());+ }++ @Test+ void staticTokenWinsOverProvider() throws Exception {+ RecordingProvider.lastRequest = null;++ Properties info = providerProps();+ PGProperty.OAUTH_TOKEN.set(info, "static-token");++ assertArrayEquals("static-token".toCharArray(),+ ConnectionFactoryImpl.resolveOAuthToken(info));+ assertEquals(null, RecordingProvider.lastRequest, "The provider must not be called");+ }++ @Test+ void providerThatCannotBeLoadedIsReported() {+ Properties info = new Properties();+ PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.set(info, "com.example.NoSuchTokenProvider");++ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.resolveOAuthToken(info));++ assertEquals(PSQLState.INVALID_PARAMETER_VALUE.getState(), ex.getSQLState());+ assertEquals(GT.tr("Unable to load OAuth token provider {0}", "com.example.NoSuchTokenProvider"),+ ex.getMessage());+ }++ @Test+ void providerReturningAnEmptyTokenIsReported() {+ Properties info = new Properties();+ PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.set(info, EmptyTokenProvider.class.getName());++ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.resolveOAuthToken(info));++ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ assertEquals(GT.tr("OAuth token provider returned no token"), ex.getMessage());+ }++ @Test+ void providerReturningNoTokenIsReported() {+ Properties info = new Properties();+ PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.set(info, NullTokenProvider.class.getName());++ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.resolveOAuthToken(info));++ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ assertEquals(GT.tr("OAuth token provider returned no token"), ex.getMessage());+ }+}diff --git a/pgjdbc/src/test/java/org/postgresql/core/v3/SelectSaslMechanismTest.java b/pgjdbc/src/test/java/org/postgresql/core/v3/SelectSaslMechanismTest.javanew file mode 100644index 0000000000..5bae751091--- /dev/null+++ b/pgjdbc/src/test/java/org/postgresql/core/v3/SelectSaslMechanismTest.java@@ -0,0 +1,214 @@+/*+ * Copyright (c) 2026, PostgreSQL Global Development Group+ * See the LICENSE file in the project root for more information.+ */++package org.postgresql.core.v3;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertThrows;++import org.postgresql.PGProperty;+import org.postgresql.core.AuthMethod;+import org.postgresql.util.GT;+import org.postgresql.util.PSQLException;+import org.postgresql.util.PSQLState;++import org.junit.jupiter.api.Test;++import java.util.Arrays;+import java.util.Collections;+import java.util.EnumSet;+import java.util.List;+import java.util.Properties;++class SelectSaslMechanismTest {++ private static final List<String> SCRAM_ONLY =+ Arrays.asList("SCRAM-SHA-256", "SCRAM-SHA-256-PLUS");+ private static final List<String> OAUTH_ONLY =+ Collections.singletonList(OAuthAuthenticator.SASL_MECHANISM);+ private static final List<String> BOTH =+ Arrays.asList(OAuthAuthenticator.SASL_MECHANISM, "SCRAM-SHA-256", "SCRAM-SHA-256-PLUS");++ private static final String REQUIRE_AUTH_MESSAGE =+ GT.tr("Authentication method is not allowed by requireAuth");++ private static final String OAUTH_CHANNEL_BINDING_MESSAGE =+ GT.tr("Channel binding is not supported for OAuth authentication.");++ private static final String OAUTH_NOT_CONFIGURED_MESSAGE =+ GT.tr("The server requested OAuth authentication, but neither {0} nor {1} is configured.",+ PGProperty.OAUTH_TOKEN.getName(),+ PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.getName());++ private static String unsupportedMessage(List<String> mechanisms) {+ return GT.tr("The server requested SASL authentication with mechanisms {0}, "+ + "but the driver supports none of them.", mechanisms);+ }++ private static Properties withToken() {+ Properties info = new Properties();+ PGProperty.OAUTH_TOKEN.set(info, "token");+ return info;+ }++ private static Properties withTokenProvider() {+ Properties info = new Properties();+ PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.set(info, "com.example.Provider");+ return info;+ }++ private static Properties noOAuth() {+ return new Properties();+ }++ private static EnumSet<AuthMethod> requireAuth(String value) throws PSQLException {+ EnumSet<AuthMethod> methods = AuthMethod.parseRequireAuth(value);+ assertNotNull(methods, "requireAuth=" + value + " parsed to no restriction");+ return methods;+ }++ @Test+ void oauthWinsWhenOfferedAndConfigured() throws Exception {+ assertEquals(AuthMethod.OAUTH,+ ConnectionFactoryImpl.selectSaslMechanism(BOTH, withToken(), null, ChannelBinding.PREFER));+ assertEquals(AuthMethod.OAUTH,+ ConnectionFactoryImpl.selectSaslMechanism(OAUTH_ONLY, withToken(), null, ChannelBinding.PREFER));+ }++ @Test+ void tokenProviderCountsAsConfiguredOAuth() throws Exception {+ assertEquals(AuthMethod.OAUTH,+ ConnectionFactoryImpl.selectSaslMechanism(BOTH, withTokenProvider(), null, ChannelBinding.PREFER));+ }++ @Test+ void unconfiguredOAuthFallsBackToScram() throws Exception {+ assertEquals(AuthMethod.SCRAM_SHA_256,+ ConnectionFactoryImpl.selectSaslMechanism(BOTH, noOAuth(), null, ChannelBinding.PREFER));+ }++ @Test+ void scramChosenWhenOnlyScramOffered() throws Exception {+ assertEquals(AuthMethod.SCRAM_SHA_256,+ ConnectionFactoryImpl.selectSaslMechanism(SCRAM_ONLY, withToken(), null, ChannelBinding.PREFER));+ }++ @Test+ void requireAuthExcludingOAuthFallsBackToScram() throws Exception {+ assertEquals(AuthMethod.SCRAM_SHA_256,+ ConnectionFactoryImpl.selectSaslMechanism(BOTH, withToken(), requireAuth("!oauth"), ChannelBinding.PREFER));+ assertEquals(AuthMethod.SCRAM_SHA_256,+ ConnectionFactoryImpl.selectSaslMechanism(BOTH, withToken(), requireAuth("scram-sha-256"), ChannelBinding.PREFER));+ }++ @Test+ void requireAuthExcludingScramStillAllowsOAuth() throws Exception {+ assertEquals(AuthMethod.OAUTH,+ ConnectionFactoryImpl.selectSaslMechanism(BOTH, withToken(),+ requireAuth("!scram-sha-256"), ChannelBinding.PREFER));+ assertEquals(AuthMethod.OAUTH,+ ConnectionFactoryImpl.selectSaslMechanism(BOTH, withToken(), requireAuth("oauth"), ChannelBinding.PREFER));+ }++ @Test+ void oauthOnlyServerRejectedWhenRequireAuthForbidsOAuth() {+ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.selectSaslMechanism(OAUTH_ONLY, withToken(),+ requireAuth("!oauth"), ChannelBinding.PREFER));+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ assertEquals(REQUIRE_AUTH_MESSAGE, ex.getMessage());+ }++ @Test+ void scramOnlyServerRejectedWhenRequireAuthForbidsScram() {+ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.selectSaslMechanism(SCRAM_ONLY, withToken(),+ requireAuth("oauth"), ChannelBinding.PREFER));+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ assertEquals(REQUIRE_AUTH_MESSAGE, ex.getMessage());+ }++ @Test+ void bothForbiddenByRequireAuthReportsRequireAuth() {+ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.selectSaslMechanism(BOTH, withToken(), requireAuth("md5"), ChannelBinding.PREFER));+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ assertEquals(REQUIRE_AUTH_MESSAGE, ex.getMessage());+ }++ @Test+ void oauthOnlyServerWithoutOAuthConfigurationReportsMissingConfiguration() {+ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.selectSaslMechanism(OAUTH_ONLY, noOAuth(), null, ChannelBinding.PREFER));+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ assertEquals(OAUTH_NOT_CONFIGURED_MESSAGE, ex.getMessage());+ }++ @Test+ void requireAuthOnlyAllowingOAuthWithoutOAuthConfigurationReportsMissingConfiguration()+ throws Exception {+ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.selectSaslMechanism(BOTH, noOAuth(), requireAuth("oauth"), ChannelBinding.PREFER));+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ assertEquals(OAUTH_NOT_CONFIGURED_MESSAGE, ex.getMessage());+ }++ @Test+ void channelBindingRequireFallsBackToScram() throws Exception {+ assertEquals(AuthMethod.SCRAM_SHA_256,+ ConnectionFactoryImpl.selectSaslMechanism(BOTH, withToken(), null,+ ChannelBinding.REQUIRE));+ assertEquals(AuthMethod.SCRAM_SHA_256,+ ConnectionFactoryImpl.selectSaslMechanism(BOTH, withToken(), requireAuth("!md5"),+ ChannelBinding.REQUIRE));+ }++ @Test+ void channelBindingDisableAndPreferStillChooseOAuth() throws Exception {+ assertEquals(AuthMethod.OAUTH,+ ConnectionFactoryImpl.selectSaslMechanism(BOTH, withToken(), null,+ ChannelBinding.DISABLE));+ assertEquals(AuthMethod.OAUTH,+ ConnectionFactoryImpl.selectSaslMechanism(BOTH, withToken(), null,+ ChannelBinding.PREFER));+ }++ @Test+ void oauthOnlyServerRejectedWhenChannelBindingRequired() {+ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.selectSaslMechanism(OAUTH_ONLY, withToken(), null,+ ChannelBinding.REQUIRE));+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ assertEquals(OAUTH_CHANNEL_BINDING_MESSAGE, ex.getMessage());+ }++ @Test+ void channelBindingRequiredWithScramForbiddenReportsChannelBinding() throws Exception {+ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.selectSaslMechanism(BOTH, withToken(), requireAuth("oauth"),+ ChannelBinding.REQUIRE));+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ assertEquals(OAUTH_CHANNEL_BINDING_MESSAGE, ex.getMessage());+ }++ @Test+ void unconfiguredOAuthUnderChannelBindingRequireReportsMissingConfiguration() {+ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.selectSaslMechanism(OAUTH_ONLY, noOAuth(), null,+ ChannelBinding.REQUIRE));+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ assertEquals(OAUTH_NOT_CONFIGURED_MESSAGE, ex.getMessage());+ }++ @Test+ void unknownMechanismReportsUnsupportedMechanism() {+ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.selectSaslMechanism(Collections.singletonList("PLAIN"),+ withToken(), null, ChannelBinding.PREFER));+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ assertEquals(unsupportedMessage(Collections.singletonList("PLAIN")), ex.getMessage());+ }+}diff --git a/pgjdbc/src/test/java/org/postgresql/core/v3/ValidateOAuthIssuerTest.java b/pgjdbc/src/test/java/org/postgresql/core/v3/ValidateOAuthIssuerTest.javanew file mode 100644index 0000000000..513910c2f4--- /dev/null+++ b/pgjdbc/src/test/java/org/postgresql/core/v3/ValidateOAuthIssuerTest.java@@ -0,0 +1,118 @@+/*+ * Copyright (c) 2026, PostgreSQL Global Development Group+ * See the LICENSE file in the project root for more information.+ */++package org.postgresql.core.v3;++import static org.junit.jupiter.api.Assertions.assertArrayEquals;+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;++import org.postgresql.PGProperty;+import org.postgresql.util.PSQLException;+import org.postgresql.util.PSQLState;++import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++import java.util.Properties;++class ValidateOAuthIssuerTest {++ private static String httpsRequiredMessage(String issuer) {+ return "OAuth issuer URL must use HTTPS: " + issuer+ + ". Set oauthAllowInsecureIssuer=true to disable this check for development.";+ }++ private static Properties propsWithIssuer(String issuer) {+ Properties info = new Properties();+ if (issuer != null) {+ PGProperty.OAUTH_ISSUER.set(info, issuer);+ }+ return info;+ }++ @Test+ void httpsIssuerPasses() {+ assertDoesNotThrow(+ () -> ConnectionFactoryImpl.validateOAuthIssuer(+ propsWithIssuer("https://issuer.example.com";)));+ }++ @Test+ void httpsSchemeIsCaseInsensitive() {+ assertDoesNotThrow(+ () -> ConnectionFactoryImpl.validateOAuthIssuer(+ propsWithIssuer("HTTPS://issuer.example.com")));+ }++ @Test+ void emptyIssuerIsNoOp() {+ assertDoesNotThrow(+ () -> ConnectionFactoryImpl.validateOAuthIssuer(propsWithIssuer("")));+ }++ @Test+ void unsetIssuerIsNoOp() {+ assertDoesNotThrow(+ () -> ConnectionFactoryImpl.validateOAuthIssuer(propsWithIssuer(null)));+ }++ @ParameterizedTest+ @ValueSource(strings = {+ "http://issuer.example.com";,+ "http://localhost:8080";,+ "http://127.0.0.1/realms/test";,+ })+ void httpIssuerRejected(String issuer) {+ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.validateOAuthIssuer(propsWithIssuer(issuer)));+ assertEquals(PSQLState.INVALID_PARAMETER_VALUE.getState(), ex.getSQLState());+ assertEquals(httpsRequiredMessage(issuer), ex.getMessage());+ }++ @Test+ void malformedIssuerRejected() {+ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.validateOAuthIssuer(propsWithIssuer("ht!tp://bad url")));+ assertEquals(PSQLState.INVALID_PARAMETER_VALUE.getState(), ex.getSQLState());+ // A malformed URL is not fixed by oauthAllowInsecureIssuer, so it must not be suggested.+ assertEquals("OAuth issuer is not a valid URL: ht!tp://bad url", ex.getMessage());+ }++ @Test+ void issuerWithoutSchemeRejectedAsNonHttps() {+ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.validateOAuthIssuer(propsWithIssuer("issuer.example.com")));+ assertEquals(PSQLState.INVALID_PARAMETER_VALUE.getState(), ex.getSQLState());+ assertEquals(httpsRequiredMessage("issuer.example.com"), ex.getMessage());+ }++ @Test+ void httpAcceptedWhenInsecureIssuerAllowed() {+ Properties info = propsWithIssuer("http://issuer.example.com";);+ PGProperty.OAUTH_ALLOW_INSECURE_ISSUER.set(info, true);+ assertDoesNotThrow(() -> ConnectionFactoryImpl.validateOAuthIssuer(info));+ }++ @Test+ void staticTokenWithHttpIssuerRejected() {+ Properties info = propsWithIssuer("http://issuer.example.com";);+ PGProperty.OAUTH_TOKEN.set(info, "static-token");+ PSQLException ex = assertThrows(PSQLException.class,+ () -> ConnectionFactoryImpl.resolveOAuthToken(info));+ assertEquals(PSQLState.INVALID_PARAMETER_VALUE.getState(), ex.getSQLState());+ assertEquals(httpsRequiredMessage("http://issuer.example.com";), ex.getMessage());+ }++ @Test+ void staticTokenWithHttpsIssuerAccepted() throws Exception {+ Properties info = propsWithIssuer("https://issuer.example.com";);+ PGProperty.OAUTH_TOKEN.set(info, "static-token");+ assertArrayEquals("static-token".toCharArray(),+ ConnectionFactoryImpl.resolveOAuthToken(info));+ }+}diff --git a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/DriverTest.java b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/DriverTest.javaindex 897d76bf1d..fd85c0302c 100644--- a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/DriverTest.java+++ b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/DriverTest.java@@ -199,6 +199,7 @@ private static void verifyUrl(Driver drv, String url, String hosts, String ports
*/
@Test
void connect() throws Exception {
+ TestUtil.assumeNotOAuthMode();
// Test with the url, username & password
String url = TestUtil.getURL();
String user = TestUtil.getUser();
@@ -373,6 +374,7 @@ void connectService() throws Exception {
*/
@Test
void connectPassword01() throws Exception {
+ TestUtil.assumeNotOAuthMode();
TestUtil.initDriver(); // Set up log levels, etc.
// Create temporary .pgpass file
@@ -406,6 +408,7 @@ void connectPassword01() throws Exception {
*/
@Test
void connectPassword02() throws Exception {
+ TestUtil.assumeNotOAuthMode();
TestUtil.initDriver(); // Set up log levels, etc.
String wrongPassword = "random wrong";
@@ -444,6 +447,7 @@ void connectPassword02() throws Exception {
*/
@Test
void connectPassword03() throws Exception {
+ TestUtil.assumeNotOAuthMode();
TestUtil.initDriver(); // Set up log levels, etc.
String wrongPassword = "random wrong";
@@ -484,6 +488,7 @@ void connectPassword03() throws Exception {
*/
@Test
void connectPassword04() throws Exception {
+ TestUtil.assumeNotOAuthMode();
TestUtil.initDriver(); // Set up log levels, etc.
String wrongPassword = "random wrong";
@@ -526,6 +531,7 @@ void connectPassword04() throws Exception {
*/
@Test
void connectFailover() throws Exception {
+ TestUtil.assumeNotOAuthMode();
String url = "jdbc:postgresql://invalidhost.not.here," + TestUtil.getServer() + ":"
+ TestUtil.getPort() + "/" + TestUtil.getDatabase() + "?connectTimeout=5";
Connection con = DriverManager.getConnection(url, TestUtil.getUser(), TestUtil.getPassword());
@@ -538,6 +544,7 @@ void connectFailover() throws Exception {
*/
@Test
void readOnly() throws Exception {
+ TestUtil.assumeNotOAuthMode();
TestUtil.initDriver(); // Set up log levels, etc.
Connection con = DriverManager.getConnection(TestUtil.getURL() + "&readOnly=true",
@@ -603,6 +610,7 @@ void registration() throws Exception {
@Test
void systemErrIsNotClosedWhenCreatedMultipleConnections() throws Exception {
+ TestUtil.assumeNotOAuthMode();
TestUtil.initDriver();
PrintStream err = System.err;
PrintStream buffer = new PrintStream(new ByteArrayOutputStream());
diff --git a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/LoginTimeoutInterruptTest.java b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/LoginTimeoutInterruptTest.javaindex d36556cfeb..ead831846f 100644--- a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/LoginTimeoutInterruptTest.java+++ b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/LoginTimeoutInterruptTest.java@@ -40,6 +40,8 @@ public class LoginTimeoutInterruptTest {
@Test
void loginTimeoutInterruptsAuthPluginSleep() throws Exception {
+ // This test drives a password/auth-plugin flow, which is incompatible with OAuth.+ TestUtil.assumeNotOAuthMode();
SleepThenThrowAuthPlugin.PLUGIN_INVOKED.set(false);
SleepThenThrowAuthPlugin.INTERRUPTED_DURING_SLEEP.set(false);
SleepThenThrowAuthPlugin.POST_SLEEP_REACHED.set(false);
diff --git a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/PGPropertyTest.java b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/PGPropertyTest.javaindex 491fa87950..47b815b163 100644--- a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/PGPropertyTest.java+++ b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/PGPropertyTest.java@@ -8,6 +8,7 @@
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -17,6 +18,7 @@
import org.postgresql.ds.common.BaseDataSource;
import org.postgresql.jdbc.AutoSave;
import org.postgresql.test.TestUtil;
+import org.postgresql.util.TestLogHandler;
import org.postgresql.util.URLCoder;
import org.junit.jupiter.api.AfterEach;
@@ -28,10 +30,15 @@
import java.beans.PropertyDescriptor;
import java.sql.DriverPropertyInfo;
import java.util.ArrayList;
+import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
+import java.util.logging.Level;+import java.util.logging.LogRecord;+import java.util.logging.Logger;+import java.util.logging.SimpleFormatter;
class PGPropertyTest {
@@ -295,4 +302,61 @@ void encodedUrlValuesFromDataSource() {
assertFalse(PGProperty.PASSWORD.isPresent(parsed), "password");
assertEquals(applicationName, PGProperty.APPLICATION_NAME.getOrDefault(parsed), "APPLICATION_NAME");
}
++ @Test+ void credentialsAreNotPassedAsUrlParameters() {+ PGSimpleDataSource dataSource = new PGSimpleDataSource();+ dataSource.setPassword("p4ssword");+ dataSource.setSslPassword("sslp4ssword");+ dataSource.setOAuthToken("t0ken");+ dataSource.setOAuthClientSecret("s3cret");+ // A non-secret OAuth property to show that only the credentials are held back+ dataSource.setOAuthClientId("pgjdbc");++ String url = dataSource.getURL();+ Properties parsed = Driver.parseURL(url, new Properties());+ assertNotNull(parsed, url);+ for (PGProperty property : PGProperty.values()) {+ if (property.isSensitive()) {+ assertFalse(property.isPresent(parsed), () -> property.getName() + " in " + url);+ }+ }+ assertEquals("pgjdbc", PGProperty.OAUTH_CLIENT_ID.getOrDefault(parsed), "oauthClientId");+ }++ /**+ * A parameter value that fails to URL-decode may be a credential, so only its name is logged.+ */+ @Test+ void malformedCredentialValueIsNotLogged() {+ Logger driverLogger = Logger.getLogger(Driver.class.getName());+ TestLogHandler logHandler = new TestLogHandler();+ Level previousLevel = driverLogger.getLevel();+ boolean previousUseParentHandlers = driverLogger.getUseParentHandlers();+ driverLogger.addHandler(logHandler);+ driverLogger.setLevel(Level.FINE);+ // Route the records to our handler only, so they do not pollute standard output+ driverLogger.setUseParentHandlers(false);+ try {+ // "%zz" is not a valid percent-escape, so decoding the value fails+ assertNull(Driver.parseURL(+ "jdbc:postgresql://localhost:5432/test?oauthToken=s3cr3t%zz", null));+ } finally {+ driverLogger.removeHandler(logHandler);+ driverLogger.setLevel(previousLevel);+ driverLogger.setUseParentHandlers(previousUseParentHandlers);+ }++ SimpleFormatter formatter = new SimpleFormatter();+ List<String> messages = new ArrayList<>();+ for (LogRecord record : logHandler.records) {+ messages.add(formatter.formatMessage(record));+ }+ assertFalse(messages.isEmpty(), "Expected the driver to log the decoding failure");+ for (String message : messages) {+ assertFalse(message.contains("s3cr3t"), () -> "The credential was logged: " + message);+ }+ assertTrue(messages.stream().anyMatch(message -> message.contains("oauthToken")),+ () -> "Expected the parameter name in the log, but got " + messages);+ }
}
diff --git a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/BaseDataSourceTest.java b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/BaseDataSourceTest.javaindex 5635c13181..99eb4548ea 100644--- a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/BaseDataSourceTest.java+++ b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/BaseDataSourceTest.java@@ -103,6 +103,7 @@ public static void setupDataSource(BaseDataSource bds) throws PSQLException {
bds.setPassword(TestUtil.getPassword());
bds.setPrepareThreshold(TestUtil.getPrepareThreshold());
bds.setProtocolVersion(TestUtil.getProtocolVersion());
+ TestUtil.configureOAuthIfNeeded(bds);
}
/**
diff --git a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/CaseOptimiserDataSourceTest.java b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/CaseOptimiserDataSourceTest.javaindex 013c3dc3ca..eda1bd7a76 100644--- a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/CaseOptimiserDataSourceTest.java+++ b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/CaseOptimiserDataSourceTest.java@@ -109,5 +109,6 @@ public static void setupDataSource(BaseDataSource bds) throws PSQLException {
bds.setPassword(TestUtil.getPassword());
bds.setPrepareThreshold(TestUtil.getPrepareThreshold());
bds.setProtocolVersion(TestUtil.getProtocolVersion());
+ TestUtil.configureOAuthIfNeeded(bds);
}
}
diff --git a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/SimpleDataSourceWithSetURLTest.java b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/SimpleDataSourceWithSetURLTest.javaindex f636cadd64..1d9e638ba4 100644--- a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/SimpleDataSourceWithSetURLTest.java+++ b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/SimpleDataSourceWithSetURLTest.java@@ -32,6 +32,7 @@ protected void initializeDataSource() throws PSQLException {
bds.setUser(TestUtil.getUser());
bds.setPassword(TestUtil.getPassword());
bds.setProtocolVersion(TestUtil.getProtocolVersion());
+ TestUtil.configureOAuthIfNeeded(bds);
}
}
diff --git a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/SimpleDataSourceWithUrlTest.java b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/SimpleDataSourceWithUrlTest.javaindex 2945dff8e2..2aab69eb67 100644--- a/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/SimpleDataSourceWithUrlTest.java+++ b/pgjdbc/src/test/java/org/postgresql/test/jdbc2/optional/SimpleDataSourceWithUrlTest.java@@ -27,6 +27,7 @@ protected void initializeDataSource() throws PSQLException {
bds.setUser(TestUtil.getUser());
bds.setPassword(TestUtil.getPassword());
bds.setProtocolVersion(TestUtil.getProtocolVersion());
+ TestUtil.configureOAuthIfNeeded(bds);
}
}
}
diff --git a/pgjdbc/src/test/java/org/postgresql/test/jdbc4/OAuthTest.java b/pgjdbc/src/test/java/org/postgresql/test/jdbc4/OAuthTest.javanew file mode 100644index 0000000000..87194b3ac4--- /dev/null+++ b/pgjdbc/src/test/java/org/postgresql/test/jdbc4/OAuthTest.java@@ -0,0 +1,304 @@+/*+ * Copyright (c) 2026, PostgreSQL Global Development Group+ * See the LICENSE file in the project root for more information.+ */++package org.postgresql.test.jdbc4;++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 static org.junit.jupiter.api.Assumptions.assumeTrue;++import org.postgresql.PGProperty;+import org.postgresql.core.ServerVersion;+import org.postgresql.plugin.OAuthTokenProvider;+import org.postgresql.plugin.OAuthTokenRequest;+import org.postgresql.test.OAuthTestTokenProvider;+import org.postgresql.test.TestUtil;+import org.postgresql.util.GT;+import org.postgresql.util.PSQLException;+import org.postgresql.util.PSQLState;+import org.postgresql.util.TestLogHandler;++import org.checkerframework.checker.nullness.qual.Nullable;+import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;++import java.sql.Connection;+import java.sql.ResultSet;+import java.sql.SQLException;+import java.sql.Statement;+import java.util.Properties;+import java.util.logging.Level;+import java.util.logging.Logger;+import java.util.regex.Pattern;++/**+ * Integration tests for OAuth Bearer (OAUTHBEARER SASL) authentication.+ * These tests require PostgreSQL 18+ with OAuth configured.+ */+public class OAuthTest {++ private static @Nullable Connection con;++ private static final OAuthTokenRequest tokenRequest = new OAuthTokenRequest(+ TestUtil.getOAuthIssuer(),+ TestUtil.getOAuthClientId(),+ TestUtil.getOAuthClientSecret(),+ TestUtil.getOAuthScope());++ private static final OAuthTestTokenProvider provider = new OAuthTestTokenProvider();++ private static final Pattern unencryptedConnectionWarning = Pattern.compile(+ "oauthAllowInsecureConnection=true: OAUTHBEARER is being used over an unencrypted "+ + "connection, so the bearer token is sent in the clear. RFC 7628 §3 requires a "+ + "secure channel. Do not use this configuration in production.");++ private static final Pattern unverifiedConnectionWarning = Pattern.compile(+ "OAUTHBEARER is being used over a TLS connection whose server certificate is not verified");++ private static final Pattern tokenRejectedWarning =+ Pattern.compile("Server rejected OAuth bearer token");++ private static final Logger oauthLogger =+ Logger.getLogger("org.postgresql.core.v3.OAuthAuthenticator");+ private static final TestLogHandler logHandler = new TestLogHandler();+ private static @Nullable Level previousLevel;+ private static boolean previousUseParentHandlers;+ private static boolean loggerConfigured;++ @BeforeAll+ static void setUp() throws Exception {+ TestUtil.assumeOAuthTestsEnabled();++ con = TestUtil.openPrivilegedDB();++ assumeTrue(+ TestUtil.haveMinimumServerVersion(con, ServerVersion.v18),+ "PostgreSQL 18+ required for OAuth tests");++ previousLevel = oauthLogger.getLevel();+ previousUseParentHandlers = oauthLogger.getUseParentHandlers();+ oauthLogger.addHandler(logHandler);+ oauthLogger.setLevel(Level.ALL);+ // Route logs to our handler only, so they do not pollute standard output.+ oauthLogger.setUseParentHandlers(false);+ loggerConfigured = true;+ }++ @AfterAll+ static void tearDown() throws Exception {+ if (loggerConfigured) {+ oauthLogger.removeHandler(logHandler);+ oauthLogger.setLevel(previousLevel);+ oauthLogger.setUseParentHandlers(previousUseParentHandlers);+ loggerConfigured = false;+ }+ TestUtil.closeDB(con);+ }++ /**+ * Static token authentication.+ */+ @Test+ void staticToken() throws Exception {+ String username = TestUtil.getOAuthRole();+ Properties props = new Properties();+ PGProperty.USER.set(props, username);+ PGProperty.OAUTH_ALLOW_INSECURE_CONNECTION.set(props, "true");+ PGProperty.OAUTH_TOKEN.set(props, fetchTokenAsString());++ try (Connection c = TestUtil.openDB(props)) {+ assertCurrentUser(c, username);+ }+ }++ /**+ * Token provided by {@link OAuthTokenProvider} plugin class.+ */+ @Test+ void tokenProvider() throws SQLException {+ String username = TestUtil.getOAuthRole();+ Properties props = new Properties();+ PGProperty.USER.set(props, username);+ PGProperty.OAUTH_ALLOW_INSECURE_CONNECTION.set(props, "true");+ PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.set(props, TestUtil.getTokenProviderClassName());+ PGProperty.OAUTH_ISSUER.set(props, TestUtil.getOAuthIssuer());+ PGProperty.OAUTH_ALLOW_INSECURE_ISSUER.set(props, "true");+ PGProperty.OAUTH_CLIENT_ID.set(props, TestUtil.getOAuthClientId());+ PGProperty.OAUTH_CLIENT_SECRET.set(props, TestUtil.getOAuthClientSecret());+ PGProperty.OAUTH_SCOPE.set(props, TestUtil.getOAuthScope());+ try (Connection c = TestUtil.openDB(props)) {+ assertCurrentUser(c, username);+ }+ }++ /**+ * An invalid bearer token causes the server to reject the connection.+ */+ @Test+ void invalidToken() throws Exception {+ String username = TestUtil.getOAuthRole();+ Properties props = new Properties();+ PGProperty.USER.set(props, username);+ PGProperty.OAUTH_ALLOW_INSECURE_CONNECTION.set(props, "true");+ PGProperty.OAUTH_TOKEN.set(props, "invalid-bearer-token");++ logHandler.records.clear();+ PSQLException ex = assertThrows(+ PSQLException.class,+ () -> TestUtil.openDB(props),+ "Server should reject an invalid bearer token");+ assertEquals(PSQLState.INVALID_AUTHORIZATION_SPECIFICATION.getState(), ex.getSQLState());+ assertFalse(+ logHandler.getRecordsMatching(tokenRejectedWarning).isEmpty(),+ "The rejection sent in AuthenticationSASLContinue should be logged");+ }++ @Test+ void requireAuthAllowsOAuth() throws Exception {+ String username = TestUtil.getOAuthRole();+ Properties props = new Properties();+ PGProperty.USER.set(props, username);+ PGProperty.OAUTH_ALLOW_INSECURE_CONNECTION.set(props, "true");+ PGProperty.OAUTH_TOKEN.set(props, fetchTokenAsString());+ PGProperty.REQUIRE_AUTH.set(props, "oauth");++ try (Connection c = TestUtil.openDB(props)) {+ assertCurrentUser(c, username);+ }+ }++ @Test+ void requireAuthForbidsOAuth() throws Exception {+ Properties props = new Properties();+ PGProperty.USER.set(props, TestUtil.getOAuthRole());+ PGProperty.OAUTH_ALLOW_INSECURE_CONNECTION.set(props, "true");+ PGProperty.OAUTH_TOKEN.set(props, fetchTokenAsString());+ PGProperty.REQUIRE_AUTH.set(props, "!oauth");++ PSQLException ex = assertThrows(+ PSQLException.class,+ () -> TestUtil.openDB(props),+ "Driver should reject the connection when requireAuth disallows OAuth Bearer");+ // Assert only on the SQL state: the message is localized via GT.tr and varies by JVM locale.+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ }++ @Test+ void channelBindingIncompatibleWithOAuth() throws Exception {+ // channelBinding requires a TLS connection, so this scenario only applies when SSL is enabled.+ TestUtil.assumeSslTestsEnabled();++ Properties props = new Properties();+ PGProperty.USER.set(props, TestUtil.getOAuthRole());+ PGProperty.SSL_MODE.set(props, "require");+ PGProperty.OAUTH_ALLOW_INSECURE_CONNECTION.set(props, "true");+ PGProperty.OAUTH_TOKEN.set(props, fetchTokenAsString());+ PGProperty.CHANNEL_BINDING.set(props, "require");++ PSQLException ex = assertThrows(+ PSQLException.class,+ () -> TestUtil.openDB(props),+ "Driver should reject OAuth when channelBinding=require");+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ assertEquals(+ GT.tr("Channel binding is not supported for OAuth authentication."),+ ex.getMessage());+ }++ @Test+ void unencryptedConnectionRejected() throws Exception {+ Properties props = new Properties();+ PGProperty.USER.set(props, TestUtil.getOAuthRole());+ PGProperty.SSL_MODE.set(props, "disable");+ PGProperty.OAUTH_TOKEN.set(props, fetchTokenAsString());++ PSQLException ex = assertThrows(+ PSQLException.class,+ () -> TestUtil.openDB(props),+ "Driver should reject OAUTHBEARER over an unencrypted connection unless explicitly allowed");+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ }++ @Test+ void unverifiedTlsConnectionRejected() throws Exception {+ TestUtil.assumeSslTestsEnabled();++ Properties props = new Properties();+ PGProperty.USER.set(props, TestUtil.getOAuthRole());+ PGProperty.SSL_MODE.set(props, "require");+ PGProperty.OAUTH_TOKEN.set(props, fetchTokenAsString());++ PSQLException ex = assertThrows(+ PSQLException.class,+ () -> TestUtil.openDB(props),+ "Driver should reject OAUTHBEARER over TLS that does not verify the server certificate");+ assertEquals(PSQLState.CONNECTION_REJECTED.getState(), ex.getSQLState());+ }++ @Test+ void unverifiedTlsConnectionAllowed() throws Exception {+ TestUtil.assumeSslTestsEnabled();++ String username = TestUtil.getOAuthRole();+ Properties props = new Properties();+ PGProperty.USER.set(props, username);+ PGProperty.SSL_MODE.set(props, "require");+ PGProperty.OAUTH_ALLOW_INSECURE_CONNECTION.set(props, "true");+ PGProperty.OAUTH_TOKEN.set(props, fetchTokenAsString());++ logHandler.records.clear();+ try (Connection c = TestUtil.openDB(props)) {+ assertCurrentUser(c, username);+ }++ assertFalse(+ logHandler.getRecordsMatching(unverifiedConnectionWarning).isEmpty(),+ "Expected a warning about using OAUTHBEARER against an unverified server");+ assertTrue(+ logHandler.getRecordsMatching(unencryptedConnectionWarning).isEmpty(),+ "The connection is encrypted, so the unencrypted warning must not be logged");+ }++ @Test+ void unencryptedConnectionAllowed() throws Exception {+ String username = TestUtil.getOAuthRole();+ Properties props = new Properties();+ PGProperty.USER.set(props, username);+ PGProperty.SSL_MODE.set(props, "disable");+ PGProperty.OAUTH_ALLOW_INSECURE_CONNECTION.set(props, "true");+ PGProperty.OAUTH_TOKEN.set(props, fetchTokenAsString());++ logHandler.records.clear();+ try (Connection c = TestUtil.openDB(props)) {+ assertCurrentUser(c, username);+ }++ assertFalse(+ logHandler.getRecordsMatching(unencryptedConnectionWarning).isEmpty(),+ "Expected a warning about using OAUTHBEARER over an unencrypted connection");+ }++ /**+ * Gets the token and converts it to a string. Avoid doing this in real code,+ * as token will be stored in memory until garbage collection. In tests, it's fine.+ */+ private static String fetchTokenAsString() throws PSQLException {+ return new String(provider.getToken(tokenRequest));+ }++ /**+ * Verifies that the given connection is authenticated as the expected user.+ */+ private static void assertCurrentUser(Connection c, String expectedUser) throws SQLException {+ try (Statement stmt = c.createStatement();+ ResultSet rs = stmt.executeQuery("SELECT current_user")) {+ assertTrue(rs.next(), "Expected at least one row from SELECT current_user");+ assertEquals(expectedUser, rs.getString(1), "current_user should match the expected user");+ }+ }+}diff --git a/pgjdbc/src/test/java/org/postgresql/test/jdbc4/WrapperTest.java b/pgjdbc/src/test/java/org/postgresql/test/jdbc4/WrapperTest.javaindex 25f6f46d22..e2824eb086 100644--- a/pgjdbc/src/test/java/org/postgresql/test/jdbc4/WrapperTest.java+++ b/pgjdbc/src/test/java/org/postgresql/test/jdbc4/WrapperTest.java@@ -93,7 +93,10 @@ void connectionUnwrapPGDataSource() throws SQLException {
dataSource.setDatabaseName(TestUtil.getDatabase());
dataSource.setServerName(TestUtil.getServer());
dataSource.setPortNumber(TestUtil.getPort());
- Connection connection = dataSource.getConnection(TestUtil.getUser(), TestUtil.getPassword());+ dataSource.setUser(TestUtil.getUser());+ dataSource.setPassword(TestUtil.getPassword());+ TestUtil.configureOAuthIfNeeded(dataSource);+ Connection connection = dataSource.getConnection();
assertNotNull(connection, "Unable to obtain a connection from PGSimpleDataSource");
Object v = connection.unwrap(PGConnection.class);
assertTrue(v instanceof PGConnection,
diff --git a/pgjdbc/src/test/java/org/postgresql/test/jre8/core/SocksProxyTest.java b/pgjdbc/src/test/java/org/postgresql/test/jre8/core/SocksProxyTest.javaindex ec8e368442..74091f4c95 100644--- a/pgjdbc/src/test/java/org/postgresql/test/jre8/core/SocksProxyTest.java+++ b/pgjdbc/src/test/java/org/postgresql/test/jre8/core/SocksProxyTest.java@@ -33,6 +33,7 @@ void cleanup() {
*/
@Test
void connectWithSocksNonProxyHost() throws Exception {
+ TestUtil.assumeNotOAuthMode();
System.setProperty("socksProxyHost", "fake-socks-proxy");
System.setProperty("socksProxyPort", "9999");
System.setProperty("socksNonProxyHosts", TestUtil.getServer());
diff --git a/pgjdbc/src/test/java/org/postgresql/util/PGPropertyUtilTest.java b/pgjdbc/src/test/java/org/postgresql/util/PGPropertyUtilTest.javaindex db0af3610f..1e60767a24 100644--- a/pgjdbc/src/test/java/org/postgresql/util/PGPropertyUtilTest.java+++ b/pgjdbc/src/test/java/org/postgresql/util/PGPropertyUtilTest.java@@ -7,12 +7,15 @@
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 org.postgresql.PGProperty;
import org.postgresql.test.annotations.DisableLogger;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;
import java.util.Properties;
@@ -68,4 +71,49 @@ void translatePGPropertyToPGService() {
assertEquals(row[0], PGPropertyUtil.translatePGPropertyToPGService(row[1]));
}
}
++ @ParameterizedTest+ @ValueSource(strings = {"password", "sslpassword", "oauthToken", "oauthClientSecret"})+ void masksCredentialValue(String propertyName) {+ PGProperty property = PGProperty.forName(propertyName);+ assertNotNull(property, propertyName);+ assertTrue(property.isSensitive(), () -> propertyName + " should be sensitive");+ assertEquals(+ "jdbc:postgresql://localhost:5432/test?" + propertyName + "=***",+ PGPropertyUtil.maskSensitiveValues(+ "jdbc:postgresql://localhost:5432/test?" + propertyName + "=s3cr3t"));+ }++ @Test+ void keepsNonSensitiveValues() {+ assertEquals(+ "jdbc:postgresql://localhost:5432/test?user=alice&oauthToken=***"+ + "&oauthClientId=pgjdbc&sslmode=disable",+ PGPropertyUtil.maskSensitiveValues(+ "jdbc:postgresql://localhost:5432/test?user=alice&oauthToken=eyJhbGciOi"+ + "&oauthClientId=pgjdbc&sslmode=disable"));+ }++ @Test+ void urlWithoutQueryStringIsUnchanged() {+ assertEquals("jdbc:postgresql://localhost:5432/test",+ PGPropertyUtil.maskSensitiveValues("jdbc:postgresql://localhost:5432/test"));+ }++ @Test+ void masksUnusualQueryString() {+ // An empty value still gets masked, so that the absence of a value is not disclosed either+ assertEquals("jdbc:postgresql:///?password=***",+ PGPropertyUtil.maskSensitiveValues("jdbc:postgresql:///?password="));+ // Parameters without a value, unknown parameters and empty parameters are passed through+ assertEquals("jdbc:postgresql:///?password&unknownParam=x&&ssl=true",+ PGPropertyUtil.maskSensitiveValues(+ "jdbc:postgresql:///?password&unknownParam=x&&ssl=true"));+ // Only the first "=" separates name from value, and non-sensitive values are left alone+ assertEquals("jdbc:postgresql:///?oauthToken=***&options=-c%20a%3Db",+ PGPropertyUtil.maskSensitiveValues(+ "jdbc:postgresql:///?oauthToken=ey=JhbGciOi&options=-c%20a%3Db"));+ // Not a URL at all+ assertEquals("", PGPropertyUtil.maskSensitiveValues(""));+ }
}
diff --git a/testkit/src/main/java/org/postgresql/test/OAuthTestTokenProvider.java b/testkit/src/main/java/org/postgresql/test/OAuthTestTokenProvider.javanew file mode 100644index 0000000000..70d63d2537--- /dev/null+++ b/testkit/src/main/java/org/postgresql/test/OAuthTestTokenProvider.java@@ -0,0 +1,177 @@+/*+ * Copyright (c) 2026, PostgreSQL Global Development Group+ * See the LICENSE file in the project root for more information.+ */++package org.postgresql.test;++import static org.postgresql.util.internal.Nullness.castNonNull;++import org.postgresql.plugin.OAuthTokenProvider;+import org.postgresql.plugin.OAuthTokenRequest;+import org.postgresql.util.PSQLException;+import org.postgresql.util.PSQLState;+import org.postgresql.util.URLCoder;++import org.checkerframework.checker.nullness.qual.Nullable;++import java.io.BufferedReader;+import java.io.DataOutputStream;+import java.io.InputStream;+import java.io.InputStreamReader;+import java.net.HttpURLConnection;+import java.net.URI;+import java.nio.charset.StandardCharsets;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.ConcurrentMap;+import java.util.regex.Matcher;+import java.util.regex.Pattern;+import java.util.stream.Collectors;++/**+ * OAuth token provider for the test suite.+ */+public class OAuthTestTokenProvider implements OAuthTokenProvider {++ private static final Pattern ACCESS_TOKEN_PATTERN =+ Pattern.compile("\"access_token\"\\s*:\\s*\"([^\"]+)\"");++ private static final Pattern EXPIRES_IN_PATTERN =+ Pattern.compile("\"expires_in\"\\s*:\\s*(\\d+)");++ /**+ * Stop using a token this long before it expires.+ */+ private static final long EXPIRY_MARGIN_MILLIS = 30_000;++ private static final ConcurrentMap<String, CachedToken> TOKEN_CACHE = new ConcurrentHashMap<>();++ @Override+ public char[] getToken(OAuthTokenRequest request) throws PSQLException {+ String key = cacheKey(request);+ CachedToken cached = TOKEN_CACHE.get(key);+ if (cached != null && cached.isUsable()) {+ return cached.token.clone();+ }++ CachedToken fresh;+ try {+ fresh = fetchToken(request);+ } catch (PSQLException ex) {+ throw ex;+ } catch (Exception ex) {+ throw new PSQLException(+ "Failed to get OAuth token: " + ex.getMessage(),+ PSQLState.CONNECTION_REJECTED, ex);+ }++ if (fresh.isUsable()) {+ TOKEN_CACHE.put(key, fresh);+ }+ return fresh.token.clone();+ }++ private static String cacheKey(OAuthTokenRequest request) {+ return request.getIssuer() + "\n" + request.getClientId() + "\n" + request.getScope();+ }++ private static CachedToken fetchToken(OAuthTokenRequest request) throws Exception {+ String issuer = require(request.getIssuer(), "oauthIssuer");+ String body = "grant_type=client_credentials"+ + "&client_id=" + URLCoder.encode(require(request.getClientId(), "oauthClientId"))+ + "&client_secret="+ + URLCoder.encode(require(request.getClientSecret(), "oauthClientSecret"))+ + "&scope=" + URLCoder.encode(require(request.getScope(), "oauthScope"));++ // A real provider reads token_endpoint from {issuer}/.well-known/openid-configuration. This+ // one appends Keycloak's well-known path instead, because the discovery document advertises+ // the container-internal keycloak:8080 URLs, which the tests cannot reach from the host.+ String response = httpPost(issuer + "/protocol/openid-connect/token", body);+ Matcher matcher = ACCESS_TOKEN_PATTERN.matcher(response);+ if (!matcher.find()) {+ throw new PSQLException(+ "access_token not found in Keycloak response: " + response,+ PSQLState.CONNECTION_REJECTED);+ }+ return new CachedToken(castNonNull(matcher.group(1)).toCharArray(), expiresAt(response));+ }++ /**+ * Returns when the token in the given response stops being usable, or 0 if the response carries+ * no {@code expires_in} and the token therefore must not be cached.+ */+ private static long expiresAt(String response) {+ Matcher matcher = EXPIRES_IN_PATTERN.matcher(response);+ if (!matcher.find()) {+ return 0;+ }+ long seconds = Long.parseLong(castNonNull(matcher.group(1)));+ return System.currentTimeMillis() + seconds * 1000 - EXPIRY_MARGIN_MILLIS;+ }++ private static String require(@Nullable String value, String name) throws PSQLException {+ if (value == null) {+ throw new PSQLException(+ "OAuth token request is missing required field: " + name,+ PSQLState.INVALID_PARAMETER_VALUE);+ }+ return value;+ }++ private static String httpPost(String url, String body) throws Exception {+ HttpURLConnection conn = open(url);+ conn.setRequestMethod("POST");+ conn.setDoOutput(true);+ conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");+ byte[] bodyBytes = body.getBytes(StandardCharsets.UTF_8);+ conn.setRequestProperty("Content-Length", String.valueOf(bodyBytes.length));+ try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {+ out.write(bodyBytes);+ }+ return readResponse(conn);+ }++ private static HttpURLConnection open(String urlStr) throws Exception {+ HttpURLConnection conn = (HttpURLConnection) URI.create(urlStr).toURL().openConnection();+ conn.setConnectTimeout(5000);+ conn.setReadTimeout(10000);+ return conn;+ }++ private static String readResponse(HttpURLConnection conn) throws Exception {+ int status = conn.getResponseCode();+ // On an error status getInputStream() throws and the body describing the error is only+ // available from getErrorStream(), so read that instead and report what the server said.+ InputStream stream = status >= HttpURLConnection.HTTP_BAD_REQUEST+ ? conn.getErrorStream()+ : conn.getInputStream();+ String payload = stream == null ? "" : readAll(stream);+ if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {+ throw new PSQLException(+ "Token endpoint " + conn.getURL() + " returned HTTP " + status + ": " + payload,+ PSQLState.CONNECTION_REJECTED);+ }+ return payload;+ }++ private static String readAll(InputStream stream) throws Exception {+ try (BufferedReader reader = new BufferedReader(+ new InputStreamReader(stream, StandardCharsets.UTF_8))) {+ return reader.lines().collect(Collectors.joining("\n"));+ }+ }++ private static final class CachedToken {+ private final char[] token;+ private final long usableUntilMillis;++ CachedToken(char[] token, long usableUntilMillis) {+ this.token = token;+ this.usableUntilMillis = usableUntilMillis;+ }++ boolean isUsable() {+ return System.currentTimeMillis() < usableUntilMillis;+ }+ }+}diff --git a/testkit/src/main/java/org/postgresql/test/TestUtil.java b/testkit/src/main/java/org/postgresql/test/TestUtil.javaindex 4e35b95187..9ff0e13ebf 100644--- a/testkit/src/main/java/org/postgresql/test/TestUtil.java+++ b/testkit/src/main/java/org/postgresql/test/TestUtil.java@@ -8,6 +8,7 @@
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.postgresql.util.internal.Nullness.castNonNull;
@@ -17,6 +18,7 @@
import org.postgresql.core.ServerVersion;
import org.postgresql.core.TransactionState;
import org.postgresql.core.Version;
+import org.postgresql.ds.common.BaseDataSource;
import org.postgresql.jdbc.PgConnection;
import org.postgresql.jdbc.ResourceLock;
import org.postgresql.util.PSQLException;
@@ -53,6 +55,19 @@ public class TestUtil {
*/
public static final String TEST_URL_PROPERTY_PREFIX = "test.url.";
+ public static final String TOKEN_PROVIDER_CLASS = "org.postgresql.test.OAuthTestTokenProvider";+ /**+ * OIDC issuer of the test realm. It differs from the {@code issuer=} the server is configured+ * with in {@code pg_hba.conf} only by hostname: the tests reach Keycloak through the port mapped+ * onto the host, the server reaches it through the compose network.+ */+ public static final String OAUTH_ISSUER = "http://localhost:8080/realms/pgjdbc";;+ public static final String OAUTH_CLIENT_ID = "pgjdbc-test";+ public static final String OAUTH_CLIENT_SECRET = "pgjdbc-test-client-secret";+ public static final String OAUTH_SCOPE = "pgjdbc";+ /** Database role the OAuth integration tests connect as. */+ public static final String OAUTH_ROLE = "testoauth";+
private static final ResourceLock lock = new ResourceLock();
static {
@@ -211,6 +226,31 @@ public static String getDatabase() {
return System.getProperty("privilegedPassword");
}
+ public static String getTokenProviderClassName() {+ return System.getProperty(+ PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.getName(), TOKEN_PROVIDER_CLASS);+ }++ public static String getOAuthIssuer() {+ return System.getProperty(PGProperty.OAUTH_ISSUER.getName(), OAUTH_ISSUER);+ }++ public static String getOAuthClientId() {+ return System.getProperty(PGProperty.OAUTH_CLIENT_ID.getName(), OAUTH_CLIENT_ID);+ }++ public static String getOAuthClientSecret() {+ return System.getProperty(PGProperty.OAUTH_CLIENT_SECRET.getName(), OAUTH_CLIENT_SECRET);+ }++ public static String getOAuthScope() {+ return System.getProperty(PGProperty.OAUTH_SCOPE.getName(), OAUTH_SCOPE);+ }++ public static String getOAuthRole() {+ return System.getProperty("oauthRole", OAUTH_ROLE);+ }+
static {
try {
initDriver();
@@ -275,6 +315,18 @@ public static String getSslTestCertPath(String name) {
return new File(certdir, name).getAbsolutePath();
}
+ public static void assumeOAuthTestsEnabled() {+ assumeTrue(Boolean.parseBoolean(System.getProperty("enable_oauth_tests")));+ }++ public static boolean isOAuthMode() {+ return System.getProperty("authMode", "default").equals("oauth");+ }++ public static void assumeNotOAuthMode() {+ assumeFalse(isOAuthMode(), "Test is incompatible with OAuth");+ }+
public static void initDriver() {
try (ResourceLock ignore = lock.obtain()) {
if (initialized) {
@@ -355,7 +407,75 @@ public static Connection openDB() throws SQLException {
*/
public static Connection openDB(Properties props) throws SQLException {
Properties propsWithDefaults = mergeDefaultProperties(props);
- return DriverManager.getConnection(getURL(propsWithDefaults), propsWithDefaults);+ // Build the URL before any OAuth redirection so getURL() still matches PgConnection.getURL():+ // the token provider is passed as a connection property, not appended to the URL.+ String url = getURL(propsWithDefaults);++ if (isOAuthMode()) {+ propsWithDefaults = addOAuthProperties(propsWithDefaults);+ }+ return DriverManager.getConnection(url, propsWithDefaults);+ }++ /**+ * Helper - configures a DataSource to use OAuth authentication.+ */+ public static void configureOAuthIfNeeded(BaseDataSource bds) {+ if (!isOAuthMode()) {+ return;+ }+ // If datasource already has OAuth configured leave it as is.+ if (bds.getOAuthToken() != null || bds.getOAuthTokenProviderClassName() != null) {+ return;+ }+ // If datasource uses a non-default user leave it as is.+ String defaultUser = getUser();+ if (defaultUser == null || !defaultUser.equals(bds.getUser())) {+ return;+ }+ bds.setOAuthTokenProviderClassName(getTokenProviderClassName());+ bds.setOAuthIssuer(getOAuthIssuer());+ bds.setOAuthClientId(getOAuthClientId());+ bds.setOAuthClientSecret(getOAuthClientSecret());+ bds.setOAuthScope(getOAuthScope());+ // Most tests connect without TLS, so allow OAuth over an insecure connection.+ bds.setOAuthAllowInsecureConnection(true);+ bds.setOAuthAllowInsecureIssuer(true);+ }++ /**+ * Helper - adds OAuth properties.+ */+ private static Properties addOAuthProperties(Properties props) {+ // If the caller already has configured OAuth leave it as is.+ if (PGProperty.OAUTH_TOKEN.getOrDefault(props) != null+ || PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.getOrDefault(props) != null) {+ return props;+ }+ // If the caller uses a non-default user leave it as is.+ String defaultUser = getUser();+ String user = PGProperty.USER.getOrDefault(props);+ if (defaultUser == null || !defaultUser.equals(user)) {+ return props;+ }+ Properties resultProps = new Properties();+ for (String name : props.stringPropertyNames()) {+ resultProps.setProperty(name, castNonNull(props.getProperty(name)));+ }+ resultProps.setProperty(+ PGProperty.OAUTH_TOKEN_PROVIDER_CLASS_NAME.getName(), getTokenProviderClassName());+ resultProps.setProperty(PGProperty.OAUTH_ISSUER.getName(), getOAuthIssuer());+ resultProps.setProperty(PGProperty.OAUTH_ALLOW_INSECURE_ISSUER.getName(), "true");+ resultProps.setProperty(PGProperty.OAUTH_CLIENT_ID.getName(), getOAuthClientId());+ resultProps.setProperty(PGProperty.OAUTH_CLIENT_SECRET.getName(), getOAuthClientSecret());+ resultProps.setProperty(PGProperty.OAUTH_SCOPE.getName(), getOAuthScope());+ // Most tests connect without TLS, and those that do use TLS do not verify the server+ // certificate, so let OAuth work without a verified server.+ // Some tests use their own props and are excluded with TLS.+ if (resultProps.getProperty(PGProperty.OAUTH_ALLOW_INSECURE_CONNECTION.getName()) == null) {+ resultProps.setProperty(PGProperty.OAUTH_ALLOW_INSECURE_CONNECTION.getName(), "true");+ }+ return resultProps;
}
/**
diff --git a/pgjdbc/src/test/java/org/postgresql/util/TestLogHandler.java b/testkit/src/main/java/org/postgresql/util/TestLogHandler.javasimilarity index 100%rename from pgjdbc/src/test/java/org/postgresql/util/TestLogHandler.javarename to testkit/src/main/java/org/postgresql/util/TestLogHandler.java