pg.ddx.io  GitHub: pgjdbc/pgjdbc (issues + PRs as email threads)  
help / color / mirror / Atom feed
[pgjdbc/pgjdbc] PR #4251: OAuth implementation
168+ messages / 9 participants
[nested] [flat]

* [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-06-24 16:56  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  0 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-06-24 16:56 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

### 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.yml index 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.mjs index 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.md index 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.md index 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.kts index 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-server index 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.md index 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.yml index 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: 60 diff --git a/docker/postgres-server/keycloak/realm.json b/docker/postgres-server/keycloak/realm.json new file mode 100644 index 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.sh index 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.sh index 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.md index 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.java new file mode 100644 index 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.java new file mode 100644 index 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.java index 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.java index 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.java index 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.java index 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.java index 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.java index 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.java new file mode 100644 index 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.java index 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.java index 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.java new file mode 100644 index 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.java new file mode 100644 index 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.java index 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.java index 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.java index 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.java new file mode 100644 index 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.java new file mode 100644 index 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.java new file mode 100644 index 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.java new file mode 100644 index 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.java new file mode 100644 index 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.java new file mode 100644 index 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.java index 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.java index 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.java index 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.java index 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.java index 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.java index 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.java index 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.java new file mode 100644 index 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.java index 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.java index 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.java index 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.java new file mode 100644 index 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.java index 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.java similarity index 100% rename from pgjdbc/src/test/java/org/postgresql/util/TestLogHandler.java rename to testkit/src/main/java/org/postgresql/util/TestLogHandler.java
^ permalink raw [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-06-24 17:04  "davecramer (@davecramer)" <noreply+davecramer@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: davecramer (@davecramer) @ 2026-06-24 17:04 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

see #4087 I see yours has better  TLS enforcement and integration testing. I may cherry pick from yours

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-06-24 17:49  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-06-24 17:49 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Thanks for this. The wire protocol is implemented correctly, edge cases are handled defensively, and the TLS/GSS enforcement plus the integration tests are a clear step up from #4087. Notes below, grouped by the review axes and sorted by impact. Nothing here is a blocker; most are doc or design refinements.

## Security

* **A bearer token is a plaintext-equivalent secret, and the encryption check accepts any TLS, not just `verify-full`.** Unlike SCRAM (challenge/response, the password never crosses the wire), the token is sent to the server in clear inside the SASL message, so its exposure model matches `password`. `OAuthAuthenticator.checkTransportEncryption` passes for `getSocket() instanceof SSLSocket || isGssEncrypted()`, which also accepts `sslmode=require` (encryption without certificate verification). An active MITM under `sslmode=require` therefore captures a valid token. RFC 7628 §4 asks for a confidential channel, but encryption is not server authentication. libpq takes the same stance (encryption required, verification left to the user), so this is not a blocker, but for bearer tokens it is worth calling out in the docs that `sslmode=verify-full` is strongly recommended and that `require` leaves the channel open to MITM.
* Good, please keep: `TOKEN_REGEX` (RFC 6750 §2.1) rejects `SOH`/`CR`/`LF`/space, which prevents injecting extra `kvpair`s into the SASL message. This is an important property.
* Good: the token is not logged. The `FINEST` line logs the literal `auth=Bearer <token>`, not the value.
* A static `oauthToken` passed in the URL lands in the `Connecting with URL: {0}` `FINE` log, exactly like `password`. Worth a doc note that the provider is preferable for that reason.

## Correctness and robustness

* **The discovery branch is currently dead code and the comment is misleading.** In the OAuth branch `resolveOAuthToken` always returns non-null or throws: `isOAuthConfigured` guarantees a token or a provider, a static token is checked for non-emptiness, and a provider returning an empty token throws. So `if (oauthToken != null)` in `ConnectionFactoryImpl` is always true, and the `handleAuthenticationSASL(null)` / `buildTokenMessage(null)` paths never run in production (they live only in the unit tests as scaffolding for discovery). The comment "If token was empty, then server will send discovery information" describes a path that cannot be reached yet. Until discovery lands, either simplify this or mark it explicitly as scaffolding, so the next reader does not have to reverse-engineer it.
* **The error message is misleading when `requireAuth` is the real cause.** When the server offers only OAUTHBEARER and `requireAuth=!oauth-bearer`, the user gets "the server requested SASL authentication with mechanisms [OAUTHBEARER], but non of them configured or supported by the driver", even though the actual reason is that `requireAuth` forbids the method. This is baked into the `requireAuthForbidsOAuth` test. The MD5 and password paths throw the specific "Authentication method is not allowed by requireAuth"; the OAuth/SCRAM routing should surface the same reason here.
* Verified the SASL exchange against the PG protocol for all three outcomes: success (`SASLInitialResponse` then `AuthenticationOk`), failure (`SASLContinue` with the error JSON, then the dummy `0x01`, then `ErrorResponse`), and the defensive `PROTOCOL_VIOLATION` on an unexpected `SASL_FINAL` for OAuth. `setFinishedAuthenticationRequests()` correctly stops the final `AuthenticationOk` from being treated as trust/NONE. `requireAuth` downgrade protection is preserved (OAuth routes via the non-throwing `isAllowed`, while the other branches still throw via `checkAuth`). Moving the mechanism read into `readMechanisms` and passing the list to `ScramAuthenticator` is clean and does not change SCRAM behavior.

## Performance

* **`OAuthTokenProvider.getToken()` runs on every connection, and the provider is re-instantiated each time.** `resolveOAuthToken` creates the provider via `ObjectFactory.instantiate` on each `doAuthentication`, so an implementation cannot cache a token in an instance field (only in a static). If the implementation fetches a token over the network, that is per-connect latency, which hurts most under a connection pool. The interface defines no caching or TTL contract. At minimum document the expectation to cache; ideally reuse the provider instance.
* Minor: `ScramMechanism.supportedMechanisms()` is recomputed for every element of the stream (it allocates a fresh `List` plus an `O(n)` `contains`). Hoist it into a local before the `anyMatch`.

## RFC compliance

All checked and correct: the RFC 7628 §3.1 message shape (`n,,` gs2-header, `\x01`, `auth=Bearer <token>`, `\x01\x01`), the RFC 6750 §2.1 `b64token` validation (covers base64url JWTs with dots), the §3.2.3 dummy `\x01` response on error (length 5, payload `0x01`), and omitting the optional `host`/`port` kvpairs as libpq does.

## libpq compliance

* The TLS-or-GSS requirement with an override (`oauthAllowUnencrypted`) matches libpq and the pgsql-hackers discussion you linked. GSS as a confidential channel is accepted too, which also matches.
* Please confirm the `requireAuth` keyword. pgjdbc uses `oauth-bearer`; it is worth checking how the method is named in libpq's `require_auth` (it may be `oauth`) so that users migrating from libpq are not surprised. Align or document the difference.

## Extensibility

* **`OAuthTokenProvider.getToken()` receives no context, which will force a breaking change when discovery lands.** libpq in PG 18 hands its custom hook a `PGoauthBearerRequest` with `issuer` / `scope` / `openid-configuration` (obtained during discovery). Here `getToken()` takes no arguments, so when you add discovery in a follow-up the interface will have to change incompatibly to pass issuer/scope/host/user. Designing it now as `getToken(OAuthBearerRequest ctx)` (host, user, requested scope/issuer, some fields empty for now) avoids breaking a public plugin API later. As written the provider also cannot see the `HostSpec` or user, so a single implementation cannot issue different tokens per host.
* No built-in Device Authorization Grant (RFC 8628). Understood as deliberately deferred.

## Test infrastructure and maintenance

* **`platform: linux/amd64` is pinned on the shared `pgdb` service, which every docker scenario uses (SSL, XA, SCRAM, replication), not just OAuth.** The only reason it is needed is that `pg_oidc_validator` ships an amd64-only `.deb`, installed by `entrypoint.sh` when `OAUTH=yes`. As written it forces amd64 emulation for all docker test runs on arm64 hosts (Apple Silicon) even when `OAUTH=no`, slowing everyone down for a dependency they never load. On CI it is a no-op, since `ubuntu-latest` runners are already amd64. Suggestion: keep the native platform by default and make the pin opt-in for the OAuth path, for example `platform: ${PG_PLATFORM:-}` (empty resolves to the daemon default, i.e. native) with `PG_PLATFORM=linux/amd64` exported by `docker/bin/oauth-server` and the CI oauth job. Longer term, an arm64 build of the validator (or building it in the entrypoint) removes the constraint entirely.
* Mutable, non-reproducible test dependencies will eventually flake CI: the `.deb` is fetched from the `latest` release tag (`Percona-Lab/pg_oidc_validator/releases/download/latest/...`) with no checksum, and `keycloak:latest` is unpinned. Pin both to concrete versions.
* The test-only relaxations (`sslRequired: "none"`, `issuer=http://...`, `KC_HOSTNAME_STRICT: "false"`) are fine for tests, but please make sure they do not get copied into production-facing docs as an example config.

## Wording nits

* `ConnectionFactoryImpl`: "but non of them configured or supported by the driver" should read "but none of them are configured or supported by the driver" (and update the `assertEquals` in `OAuthTest.requireAuthForbidsOAuth`, which pins the current text).
* Commit message: "OAuth berarer authentication" should be "bearer".


^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-06-25 10:24  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-06-25 10:24 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Hi @davecramer, at the time when I started to work on this, as discussed in https://github.com/pgjdbc/pgjdbc/pull/4251, there was no your PR yet. Yesterday, before sending this PR, I found yours but it looked stale and incomplete. Do you plan to finish it and what is the plan in general? Just for the context this PR is not just prompt feed to AI, I worked with RFCs, other libraries implementations, libpq internals and Postgres mailing lists. OAuth topic turned out not so simple and it has some nuances, especially regarding discovery phase. Also before sending this PR I passed internal review within my company by principal engineers. So I think it's already in a pretty good state, what is confirmed by @vlsi review.

I would appreciate clarity what to do next. Thanks!

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-06-25 10:38  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-06-25 10:38 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Just to let you know: we plan a patch release (it is long overdue), so this (or any other OAuth impl) could be merged only after the release.

PS. Regarding the tests: I would like to integrate oauth tests right into the test matrix, not as a separate ci job.
That would make it easier to maintain the job configuration and keep the number of jobs under control.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-06-25 10:46  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-06-25 10:46 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

@vlsi And what about tests infrastructure itself? This PR uses real validator extension on PG side + keycloak, which is heavy setup. Alternative option may be to have some dummy validator implementation just for test needs. For example pgx uses this approach: https://github.com/jackc/pgx/blob/master/testsetup/oauth_validator_module/dummy_validator.c



^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-06-25 11:20  "davecramer (@davecramer)" <noreply+davecramer@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: davecramer (@davecramer) @ 2026-06-25 11:20 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

> Hi @davecramer, at the time when I started to work on this, as discussed in #4251, there was no your PR yet. Yesterday, before sending this PR, I found yours but it looked stale and incomplete. Do you plan to finish it and what is the plan in general? Just for the context this PR is not just prompt feed to AI, I worked on RFCs, other libraries implementations, libpq internals and Postgres mailing lists. OAuth topic turned out not so simple and it has some nuances, especially regarding discovery phase. Also before sending this PR I passed internal review within my company by principal engineers. So I think it's already in a pretty good state, what is confirmed by @vlsi review.
> 
> I would appreciate clarity what to do next. Thanks!

Hi @artemgavrilov — thanks for putting together a solid implementation. The RFC 7628 message format is correct, the RFC 6750 token validation regex is a nice touch, and having real integrationtests with Keycloak is the right approach. This is a strong foundation. 

  A few recommendations before this can merge:

  1. OAuthTokenProvider.getToken() needs a context argument

  The current no-argument signature means a provider has no way to know which server it's acquiring a token for, what scope was requested, or what issuer the server advertises. In practice this forces implementors to either hardcode that configuration or read it from out-of-band sources — which defeats the purpose of a plugin interface. More importantly, discovery (when it lands) will need to pass the server-advertised issuer URL and scope to the provider, which means the signature will have to change after this is already a public API. Better to define it correctly once:

  public interface OAuthTokenProvider {
      String getToken(OAuthTokenRequest request) throws PSQLException;
  }

  Where OAuthTokenRequest carries host, port, user, database, discoveryUrl, scope, and clientId. Fields can be null when not yet known — providers can ignore what they don't need. This is the only change I'd call a blocker since it's a public API that would be painful to change post-merge.

  2. CI platform: linux/amd64 pin

  The pin affects all Docker test scenarios, not just OAuth — SSL, XA, SCRAM, and replication tests all run under emulation on ARM64 hosts. Scope it to the Keycloak container specifically, or remove it and accept that the OAuth test only runs on amd64 CI runners.

  3. Consider a lightweight validator alternative

  Keycloak is a significant dependency for CI. The pgx project uses a minimal dummy_validator.c PostgreSQL extension that validates tokens without a full IdP. That would make the test environment faster and less prone to keycloak:latest drift. Keycloak has the advantage of testing a realistic flow, so this is a trade-off worth discussing rather than a hard recommendation.

  4. Token zeroing

  resolveOAuthToken returns a String, which can't be zeroed after use. The driver already handles passwords as char[] for this reason — must be fixed for security reasons.

  The requireAuth=oauth-bearer naming is worth aligning with the rest of the project where methods use shorter names (scram-sha-256, password, gss). Minor, but consistency helps.

  Overall this is closer to ready than #4087. The provider interface change is the one thing I'd call a blocker since it's a public API that would be painful to change post-merge.

I'll close mine in favour of this.


^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-06-25 11:36  "davecramer (@davecramer)" <noreply+davecramer@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: davecramer (@davecramer) @ 2026-06-25 11:36 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

> @vlsi And what about tests infrastructure itself? This PR uses real validator extension on PG side + keycloak, which is heavy setup. Alternative option may be to have some dummy validator implementation just for test needs. For example pgx uses this approach: https://github.com/jackc/pgx/blob/master/testsetup/oauth_validator_module/dummy_validator.c

This would require compiling the validator for the tests. We just moved off of compiling postgres. Unless there is an extension that is publicly available. I wonder if we could create that in a separate project and pull it in?

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-06-25 11:40  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-06-25 11:40 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

> And what about tests infrastructure itself? This PR uses real validator extension on PG side + keycloak, which is heavy setup

As far as I understand Keycloak startup takes ~30 seconds, doesn't it? Extra 30 sec for oauth jobs is fine.
We have similar cases: gss tests (requires gss infra), replication tests (requires pg replica startup).

I guess pg+keycloack could be configured via docker compose. Am I missing something?

Check out the way I wire "domain socket" testing in https://github.com/pgjdbc/pgjdbc/pull/4188

> CI: two matrix axes drive socket testing...


^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-06-25 11:41  "codecov[bot] (bot) (@codecov[bot])" <noreply+codecov[bot]@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: codecov[bot] (bot) (@codecov[bot]) @ 2026-06-25 11:41 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

## [Codecov](https://app.codecov.io/gh/pgjdbc/pgjdbc/pull/4251?dropdown=coverage&src=pr&el=h1&utm_med...) Report
:x: Patch coverage is `76.78959%` with `107 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 72.34%. Comparing base ([`a3fad9d`](https://app.codecov.io/gh/pgjdbc/pgjdbc/commit/a3fad9d6bd7e3372be0c97035d13363db671355f?dropdown=cov...)) to head ([`bb861cb`](https://app.codecov.io/gh/pgjdbc/pgjdbc/commit/bb861cb7ba385dacba71d0d76f4aee2999aa4743?dropdown=cov...)).

<details><summary>Additional details and impacted files</summary>



```diff
@@             Coverage Diff              @@
##             master    #4251      +/-   ##
============================================
- Coverage     72.37%   72.34%   -0.04%     
- Complexity     5485     5601     +116     
============================================
  Files           244      248       +4     
  Lines         22193    22593     +400     
  Branches       3730     3787      +57     
============================================
+ Hits          16063    16344     +281     
- Misses         4464     4559      +95     
- Partials       1666     1690      +24     
```
</details>
<details><summary> :rocket: New features to boost your workflow: </summary>

- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
</details>

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-06-25 12:19  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-06-25 12:19 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Just to clarify, we collect code coverage from a single ci job only which executes everything possible (see https://github.com/pgjdbc/pgjdbc/blob/be96a9b52636559139ce7a2f7d2b72f0efcf8d87/.github/workflows/mat...), so I would suggest:
1) `oauth_frontend=smoke` mode to execute only some tests (a single test class or two trying OAuth). This would be configured in coverage job.
2) `oauth_frontend=all` mode to execute all tests through oauth to surface issues like "batchtest fails if the driver connects via oauth". This would be helpful as a generic bug catcher.

In theory, it should result in proper PR diff coverage.
See https://app.codecov.io/gh/pgjdbc/pgjdbc/pull/4251

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-05 23:11  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-05 23:11 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

PR Update:

1. Added context parameter to `getToken` method interface. Now it holds information needed to request token, but I skipped database name, user, host, etc. Please let me know if you want this, or any other data to be in the context.
2. Changed token variable type from String to char[] and added this variable zeroing right after usage.
3. Aligned `requireAuth` parameter name with libpq: `oauth_bearer` -> `oauth`
4. Integrated OAuth tests into test matrix
5. Added Oauth test profiles: `smoke` and `all`. From `all` test run I excluded tests that explicitly incompatible with OAuth (like password authentication tests) and suites that have their own infrastructure setup (GSS).
6. Fixed error messages for incompatible with `requireAuth` scenarios.
7. Fixed typos
8. `pg_oidc_validator` extension now moves to official PGDG package repos. RPMs already available, but I'm waithing for DEBs. For time being added todo commens to remove architecutre pin in docker compose and switch repos.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 09:05  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-14 09:05 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

@davecramer @vlsi JFYI I updated PR 

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 09:17  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-07-14 09:17 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on .github/workflows/matrix.mjs)

This should be 18+, not just 18

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 09:19  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-07-14 09:19 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on .github/workflows/matrix.mjs)

Is this significantly different from `...matrix.allAxisValues('oauth'),`?

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 09:20  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-07-14 09:20 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docker/bin/postgres-server)

```suggestion
#    OAUTH = "yes" | "no"                   - Whether to start Keycloak and enable OAuth (PG 18+)
```

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 09:31  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-07-14 09:31 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docker/postgres-server/docker-compose.yml)

This seem to impact all executions rather than oidc only.

PS. I've filed https://github.com/percona/pg_oidc_validator/issues/44

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 09:31  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-07-14 09:31 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docker/postgres-server/docker-compose.yml)

Let us use fixed versions rather than latest ones

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 09:40  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-07-14 09:40 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java:196)

Is it different from `msg.put(token)`?

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 09:47  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-07-14 09:47 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

Have you considered `!Collections.disjoint(saslMechanisms, ScramMechanism.supportedMechanisms())`?

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 09:49  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-07-14 09:49 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

Please add a hard limit on the number of algorithms. We should not have infinite loops in response processing code

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 09:50  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-07-14 09:50 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

Asserts may be disabled in production. Please use to regular exception flow.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 09:54  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-07-14 09:54 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/test/java/org/postgresql/test/jdbc4/OAuthTest.java)

Is `TestLogHandler` unused here? Should it be removed?

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 10:14  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-07-14 10:14 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Great update so far.

I'm not sure regarding pass-through only connection properties (oauthIssuer, oauthClientId, oauthClientSecret, oauthScope, oauthUsername). The driver does not use them, yet they become the public API.

---

Could you please clarify the reason you exclude oath+ssl?
It would be great to have the test coverage for successful oauth + ssl.

---

CI execution produces a lot of warnings:

```
UpdateableResultTest > testUpdateRowWithLocalDateTime() STANDARD_ERROR
    июл 06, 2026 1:07:44 AM org.postgresql.core.v3.OAuthAuthenticator checkTransportEncryption
    WARNING: OAUTHBEARER is being used over an unencrypted connection. This violates RFC 7628 §4. DO NOT USE THIS CONFIGURATION IN PRODUCTION!
```

Could you please make it so successful execution does not produce false warnings/stdout messages?

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 10:18  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-07-14 10:18 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docs/content/documentation/use.md)

The property configures "http vs https validation", yet the naming is broad.
At the same time, it looks like an escape hatch rather than a regular configuration option.

Have you considered renaming it to `oauthAllowInsecureIssuer` so a mere presence of the option signals that it is insecure?

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 10:18  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-07-14 10:18 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docs/content/documentation/use.md)

`oauthAllowUnencryptedConnection`?

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 13:03  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-14 13:03 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docker/postgres-server/docker-compose.yml)

pg_oidc_validator soon will be available in official PGDG repos. RPMs already [there](https://github.com/pgdg-packaging/pgdg-rpms/issues/216) and I'm waiting for DEBs: https://github.com/pgdg-packaging/apt.postgresql.org-issues/issues/2

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 13:06  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-14 13:06 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

This code was there [before](https://github.com/pgjdbc/pgjdbc/blob/6ee3a55f678efbba6ed9ffb7a22bfe690660c737/pgjdbc/src/main/java/...), I just extracted it from ScramAuthenticator to ConnectionFactoryImpl. Do you still want me to change that?

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-14 13:48  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-14 13:48 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java:196)

`msg.put` accepts `byte[]` while `token` is `char[]`. This code intends to avoid any token copies left in memory as was requested in previous review round. So this loop is easiest way to make conversion without leaving any copies.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-17 12:48  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-17 12:48 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docs/content/documentation/use.md)

Renamed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-17 12:48  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-17 12:48 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docs/content/documentation/use.md)

Renamed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-17 12:48  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-17 12:48 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/test/java/org/postgresql/test/jdbc4/OAuthTest.java)

Yep, leftover. Removed.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-17 12:49  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-17 12:49 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

Aha, changed!

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-17 12:50  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-17 12:50 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docker/postgres-server/docker-compose.yml)

Done, pinned to `26.7`. For some reason keycloak has no just `26` version tag.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-17 12:50  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-17 12:50 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docker/bin/postgres-server)

Done

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-17 12:53  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-17 12:53 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on .github/workflows/matrix.mjs)

Done

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-17 12:58  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-17 12:58 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

Same, this code was just moved. Should I change it?

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-17 13:05  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-17 13:05 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on .github/workflows/matrix.mjs)

That's just more specific. We definitely want `smoke + ssl` pair to be ran. 

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-17 13:22  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-17 13:22 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Hi @vlsi , thanks for the review! I pushed new update that address majority of the comments, but some of them need your input:

> I'm not sure regarding pass-through only connection properties (oauthIssuer, oauthClientId, oauthClientSecret, oauthScope, oauthUsername). The driver does not use them, yet they become the public API.

I've added them after @davecramer [review comment ](https://github.com/pgjdbc/pgjdbc/pull/4251#issuecomment-4798663272) about context argument, which sounds reasonable. Do you have any ideas how it can be done in different way? User has to have some way to configure plugin, but its class instantiated late in connection factory. 

---

> CI execution produces a lot of warnings:

I can make this log to be printed only once per instance, instead of once per connection. Will it work? Removing this warning at all seems not the best option as user really shouldn't use this in production.

---





^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-20 20:53  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-07-20 20:53 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

> I can make this log to be printed only once per instance, instead of once per connection

My target is that a successful test execution should print zero warnings/errors/other messages to the logs.


^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-28 15:16  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-28 15:16 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on .github/workflows/matrix.mjs)

Nevermind, changed to `matrix.allAxisValues('oauth')`

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-07-28 16:41  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-07-28 16:41 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Hi @vlsi , I updated PR. Now all OAuth test run with SSL + I added few test cases that explicitly check that warning if unencrypted connection used, but those tests intercept logs. So no more warnings regarding this in tests output.

There are still questions that requires your input, please take a look on unresolved comments above.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-08-08 11:14  "Abdel-Monaam-Aouini (@Abdel-Monaam-Aouini)" <noreply+Abdel-Monaam-Aouini@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: Abdel-Monaam-Aouini (@Abdel-Monaam-Aouini) @ 2026-08-08 11:14 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

We need this PR ASAP ;)

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-08-08 12:23  "davecramer (@davecramer)" <noreply+davecramer@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: davecramer (@davecramer) @ 2026-08-08 12:23 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Latest review from aI 
  ---
  Comment 1 (on the platform: linux/amd64 line in docker/postgres-server/docker-compose.yml):

  This pins the architecture unconditionally on the pgdb service, but the TODO right above it makes clear the constraint comes entirely from pg_oidc_validator's amd64-only
  nightly builds. As written, every containerized test run inherits the pin, so anyone using docker/bin/postgres-server for ordinary non-OAuth testing on arm64 (Apple Silicon,
  etc.) now gets full Postgres emulation, which is slow and can mask arch-specific behaviour. Since the amd64 requirement is purely an OAuth artifact, could this ride the same
  OAUTH/oauth profile condition as the rest of the OAuth infra rather than applying to all local runs? On the CI runners it's a no-op either way, so this only costs local arm64
  users.

  ---
  Comment 2 (general PR comment, nits):
  
  A few minor things, none blocking:

  1. testkit/.../TestUtil.java, addOAuthProperties: new Properties(props) installs props as the defaults map rather than copying its entries. It works here because the driver
  reads via propertyNames(), which walks defaults, but it's the classic Properties footgun (entrySet()/stringPropertyNames() treat defaults differently) and reads as if it were
  a shallow copy. new Properties(); putAll(props) would express the intent without the subtlety.

  2. pgjdbc/.../jdbc4/OAuthTest.java: the new String(provider.getToken(...)) calls create an immortal heap copy of the token, defeating the char[]-wipe guarantee the SPI and
  driver otherwise maintain. Test-only so the risk is nil, but a short comment noting it's acceptable only because this is test code would keep users from copying the pattern.

  3. pgjdbc/.../core/v3/ConnectionFactoryImpl.java, OAuth AUTH_REQ_SASL branch: since the branch requires isOAuthConfigured and resolveOAuthToken never returns null/empty, the
  if (oauthToken != null) guards, sendDummyResponse(), and the discovery path are inert until the follow-up discovery PR. Consistent with the staged plan; a one-line
  "scaffolding for discovery" note would save a future reader some hunting.

  ---


^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-08-12 20:34  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-08-12 20:34 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

@davecramer I pushed update that address your latest comments. One thing regarding 1, `putAll` didn't work because we still need resolved defaults. But I refactored this chunk to explicit loop to make everything clear.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-08-31 17:26  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-08-31 17:26 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Hi @vlsi and @davecramer ! How can we move this forward? Do you want me address something else?

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-08-31 18:54  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-08-31 18:54 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

@artemgavrilov , we still miss "patch release", see https://github.com/pgjdbc/pgjdbc/pull/4251#issuecomment-4798332267

I'm busy polishing the patches, so I don't have review capacity (that includes lack of Clade max 20x capacity 😂).
At the same time, I see no way we merge this before releasing patch release.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-01 14:19  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-01 14:19 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

> @artemgavrilov , we still miss "patch release", see [#4251 (comment)](https://github.com/pgjdbc/pgjdbc/pull/4251#issuecomment-4798332267)
> 
> I'm busy polishing the patches, so I don't have review capacity (that includes lack of Clade max 20x capacity 😂). At the same time, I see no way we merge this before releasing patch release.

Aha, got it! Thanks for reply!

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 14:35  "jamalfundatament (@jamalfundatament)" <noreply+jamalfundatament@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: jamalfundatament (@jamalfundatament) @ 2026-09-09 14:35 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Following up here since I saw PR #4251 great to see this has real momentum, thank you for the work on it. Wanted to flag a concrete use case for prioritization: we're standing up a self-managed PostgreSQL 18 instance (managed PG18 isn't available from our cloud provider yet) and already use Microsoft Entra ID (Azure AD) for SSO across the rest of our platform. Native OAUTHBEARER support is exactly what we'd want for database login too same identity provider, no separate DB credentials to manage or rotate. We're currently blocked purely because our GUI client (DBeaver) depends on pgjdbc for its PostgreSQL connections.

I saw the maintainers' note that this is waiting on a patch release before it can merge — is there a rough sense of when that's expected? Also happy to help test the token-provider flow against a real Entra ID tenant once it's mergeable, if that's useful for validation before release.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

I ran this branch against PostgreSQL 18.6 with `pg_oidc_validator` and Keycloak in Docker. All eight tests in `OAuthTest` pass, `./gradlew styleCheck` passes, and `-PenableCheckerframework classes` passes. The client message matches libpq byte for byte, including the discovery form `n,,\x01auth=\x01\x01`; `TOKEN_REGEX` matches the `b64token` grammar of RFC 6750 section 2.1; zeroing the token before `flush()` is safe, because `PgBufferedOutputStream` and `GSSOutputStream` both copy; and `OAuthAuthenticatorTest` covers the whole transport decision table with a negative control. The docker-compose work made all of this reproducible in a few minutes, so thank you for that.

Three findings below are blocking. I reproduced each one against a fake backend or the live server rather than reading it out of the code.

### A server that rejects the token still gets an authenticated connection

A fake backend sends `AuthenticationSASLContinue` carrying `{"status":"invalid_token"}`, reads the mandatory `0x01` response, and then sends `AuthenticationOk`:

```text
SERVER: sent AuthenticationSASLContinue(error json)
WARNING: Server rejected OAuth bearer token: {"status":"invalid_token","scope":"openid"}
SERVER: got 'p' dummy=[1]
SERVER: sent AuthenticationOk + ReadyForQuery AFTER the error
SERVER: post-auth client message Q:SET application_name = 'PostgreSQL JDBC Driver'
CLIENT: CONNECTION ESTABLISHED, autocommit=true
```

libpq refuses that sequence: `oauth_exchange` moves to `FE_OAUTH_SERVER_ERROR` and fails with `server sent additional OAuth data after error`. `requireAuth=oauth` does not change the outcome, so the setting that exists to establish which method authenticated the connection reports a guarantee that does not hold.

### The token goes to a peer whose certificate was never checked

`sslmode=require` encrypts without validating the certificate, and `checkTransportEncryption` tests only `instanceof SSLSocket`. Against a rogue endpoint holding a self-signed `CN=evil.example.com`, with `oauthAllowUnencryptedConnection` left at its default:

```text
ROGUE: TLS handshake completed, cipher=TLS_AES_256_GCM_SHA384
ROGUE: *** HARVESTED BEARER TOKEN: the-victims-real-bearer-token ***
```

There is a second half to this. Under `sslmode=prefer`, which is the default, a failed authentication over TLS makes the driver reconnect without encryption, and the same token goes out again in the clear:

```text
FE=> SASLInitialResponse(...)          first attempt, over TLS
WARNING Server rejected OAuth bearer token
FE=> SASLResponse(0x01)
WARNING OAUTHBEARER is being used over an unencrypted connection ...
FE=> SASLInitialResponse(...)          same token, plaintext
```

libpq guards this from the other side. `setup_oauth_parameters` requires `oauth_issuer` and `oauth_client_id` for every OAuth connection, including one whose token arrived through a hook, and it then compares the discovery URI the server advertises against the configured issuer, citing RFC 9207 mix-up attacks. Here `oauthIssuer` is optional, unused on the `oauthToken` path, and never compared with anything.

### The bearer token and the client secret reach the log

`BaseDataSource.getUrl()` appends every `PGProperty` that is set. `password` stays out of that URL on purpose, because it lives in its own field; `oauthToken` and `oauthClientSecret` do not. Both lines below come from a plain `PGSimpleDataSource.getConnection()` at `FINE`, carrying a real Keycloak token:

```text
org.postgresql.Driver.connect: Connecting with URL: jdbc:postgresql://127.0.0.1:15433/test?oauthAllowUnencryptedConnection=true&oauthToken=<<<THE-TOKEN>>>&sslmode=disable
org.postgresql.ds.common.BaseDataSource.getConnection: Created a Non-Pooling DataSource ... at ...&oauthToken=<<<THE-TOKEN>>>...
```

### RFC citations

`RFC 7628 §4` appears in the exception text, the log warning, the `PGProperty` javadoc, `use.md`, and two test patterns that match on it. Section 4 of RFC 7628 is "Examples". The TLS requirement is in section 3, "for the two mechanisms specified in this document, TLS MUST be used for OAUTHBEARER to protect the bearer token", and again in section 5. `matrix.mjs` cites `RFC 7632 Section 3`, and RFC 7632 is "Endpoint Security Posture Assessment: Enterprise Use Cases". The exception text is what a user pastes into a search engine, so this is worth one patch across all six places.

### Tests

The three unit test classes are well chosen, and in a default run they are the only OAuth tests that execute: every `OAuthTest` method needs `-Denable_oauth_tests=true`, so the protocol path runs nowhere except the `oauth` rows of the CI matrix. What I would ask for before merge, most of it as unit tests that need no server:

- The mechanism selection table in `AUTH_REQ_SASL`. Seven reachable columns, none covered. The one I would start with is `requireAuth=!oauth` with a server offering both mechanisms, where the driver is meant to fall through to SCRAM.
- The three new `PROTOCOL_VIOLATION` branches for SASL CONTINUE and FINAL out of order. `StrangeProxyServer` already gives you a socket-level fixture.
- `Arrays.fill` on the provider token, which `OAuthTokenProvider` documents as a contract. Delete the `finally` today and everything stays green.
- `oauthToken` taking precedence over `oauthTokenProviderClassName`. Swap the two blocks in `resolveOAuthToken` and nothing fails.
- `Unable to load OAuth token provider {0}` and `OAuth token provider returned no token`. Both are one short test each.
- The byte layout of `SASLInitialResponse` and of the `0x01` response. An off-by-one in either length is caught today only by the `oauth` CI rows.
- `AuthMethod.values()` against `fromString` and `REQUIRE_AUTH.getChoices()`, so the next constant added to the enum cannot skip either.

### Smaller things

`CHANGELOG.md` has no entry, and this adds nine connection properties plus a new public SPI. `TESTING.md` holds a copy of the `docker/bin/postgres-server` header that still lacks `OAUTH`, and it has sections for SSL, SCRAM, and authentication plugins but none for OAuth.

The commit messages need a pass. `ci: add job for OAuth tests run` adds a matrix axis rather than a job; `docs: document OAuth connection properties` names three properties out of nine and calls one of them `oauthAllowUnencrypted`, which does not exist; `feat:` has `berarer` in the body.

The description says discovery is deferred, and I read that as the right call. It is worth saying in the description that `OAuthTokenRequest` and the six discovery-shaped properties freeze the token-request API now, because that part is hard to change after a release.

The branch is behind `master` by more than twenty commits, so `git diff master..oauth` shows unrelated changes backwards. A rebase would make the next review round easier to read.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

`oauthOffered` means "offered by the server and configured by the client", while `scramOffered` next to it means only "offered by the server". The correctness of the `else` branch below rests on that asymmetry, and a reader who trusts the names reads the branch wrong. `oauthUsable` for the first one, or moving `isOAuthConfigured(info)` into the `if`, would make the pair readable.

This decision table is also the part of the change with the widest blast radius and no test at all. Seven columns are reachable, and the one I would most want pinned is `requireAuth=!oauth` against a server that offers both mechanisms: by the code the driver falls through to SCRAM, and a regression here breaks the user who disabled OAuth deliberately. `readMechanisms` and `validateOAuthIssuer` are already package-private for testing, so extracting the selection into a package-private static method fits what the change already does, and `pgjdbc-mockito-test` already mocks `PGStream` in this package.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:1273)

This is the first blocking finding from the review body. After the server has said the token is invalid, the driver sends the dummy response and calls `setFinishedAuthenticationRequests()` without recording that a rejection arrived, so the next `AuthenticationOk` is accepted and `getConnection()` returns a live connection.

libpq keeps a state for exactly this. `oauth_exchange` sets `FE_OAUTH_SERVER_ERROR` after `handle_oauth_sasl_error`, and any further server message then fails the connection with `server sent additional OAuth data after error`. RFC 4422 section 3.6, which RFC 7628 section 3.2.3 cites, is the rule behind it.

A boolean on the authenticator covers it: set it here, and throw from `AUTH_REQ_OK` and `AUTH_REQ_SASL_FINAL` when it is set. Worth a test with a fake backend, since no real server produces this sequence.

Two smaller points on the same lines. The comment restates the method name below it; what a reader cannot see is why no further request arrives, which is that the dummy response closes the error sequence and the server answers with `ErrorResponse`. And the JSON reaches the log at `WARNING` but never reaches the exception, so a user reading the stack trace loses the `status` and `scope` fields that libpq parses and uses.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docs/content/documentation/use.md)

"By default, a non-HTTPS issuer is rejected with an error at connection time" does not hold for the configuration this page calls the preferred one. `validateOAuthIssuer` runs only inside the provider branch of `resolveOAuthToken`, so `oauthToken` together with `oauthIssuer=http://...` connects with no error. I checked against the live server.

Four facts are missing from the eight new entries, and each one is something a reader has to decide before configuring this:

- `sslmode`. The default is `prefer`, under which the server may refuse TLS and the connection continues in plaintext. OAUTHBEARER then fails, and the fix is `sslmode=require` or higher, not `oauthAllowUnencryptedConnection`.
- `channelBinding=require` is rejected outright with `Channel binding is not supported for OAuth authentication.`, and the `channelBinding` entry above says nothing about it. Slot it into both entries, since a reader arrives at only one of them.
- Precedence over SCRAM. When the server offers both mechanisms and either OAuth property is set, the driver picks OAUTHBEARER and never uses `password`. `requireAuth=scram-sha-256` is the way back.
- PostgreSQL 18. `matrix.mjs`, `entrypoint.sh` and the docker script header all know the `oauth` method needs 18; this page does not say so, and it has a precedent for the phrasing in `is only available for server version 17 or higher`.

Two smaller ones. None of the five error messages a user will search for is quoted here, and this page usually does quote them. `RFC 7628 §4` in the `oauthAllowUnencryptedConnection` entry should be a link to section 5 or section 3; the page already links RFC 3986 that way, and `§` appears nowhere else under `docs/content/`.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

The comment and the code disagree in two ways, and the branch it describes cannot run.

`isOAuthConfigured(info)` guarded this branch, so `resolveOAuthToken` either returns a non-empty token or throws; `null` is unreachable. The comment says the following code "already has support" for the discovery case, and it does not: with `null` the `if` on line 1109 skips `handleAuthenticationSASL`, so nothing is written to the socket, `setFinishedAuthenticationRequests()` is skipped, and the loop blocks on a message the server will never send because it is waiting for the client. The second comment then says "if token was empty", while the code tests `!= null`, and an empty array is rejected earlier by `OAuth token provider returned no token`.

The support for the discovery message does exist, in `buildTokenMessage`, which builds `n,,\x01auth=\x01\x01` for a null token exactly as libpq does. It is this caller that turns it off.

I would drop all three `!= null` tests and both comments, and let the type say what holds:

```java
char[] oauthToken = castNonNull(resolveOAuthToken(info));
try {
  oauthAuthenticator.handleAuthenticationSASL(oauthToken);
} finally {
  Arrays.fill(oauthToken, (char) 0);
}
// The server answers a valid token with AuthenticationOk, so no further request arrives.
pgStream.setFinishedAuthenticationRequests();
```

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

`validateOAuthIssuer` runs only on the provider path, so a connection that sets `oauthToken` never reaches it. I confirmed that `oauthToken` together with `oauthIssuer=http://plain-http.example.com` connects with no error and no warning.

That may well be intended, since the issuer only matters to the provider. The problem is that `use.md` promises the opposite: the `oauthAllowInsecureIssuer` entry says a non-HTTPS issuer "is rejected with an error at connection time". Either move the call up so the check covers both paths, or say in the documentation that it applies only when a provider is called, and pin whichever you choose with a test.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java)

This is the second blocking finding. `instanceof SSLSocket` establishes that the connection is encrypted, not that the peer is the server the user meant to reach. Under `sslmode=require` and `sslmode=prefer` pgjdbc does not validate the certificate, so a rogue endpoint with a self-signed certificate passes this check and receives the token. I harvested one that way with `oauthAllowUnencryptedConnection` left at its default `false`.

RFC 7628 asks for TLS in order to keep the bearer token from a third party, and encryption without peer authentication does not deliver that.

The second half is `sslmode=prefer`, the driver default: when authentication over TLS fails, pgjdbc reconnects without encryption and this method sends the same token again in the clear, with only a `WARNING` between the two attempts. An expired token then leaks on every reconnect attempt.

I would require `SslMode.VERIFY_CA` or higher here, and at minimum warn under `require` and `prefer`. The retry path deserves its own decision: either the token is not resent after a downgrade, or the behavior is documented and pinned by a test.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java:116)

The summary says the method parses the payload, and it reads a string, logs it, and sends the dummy response. `Reads the AuthenticationSASLContinue payload, which RFC 7628 sends only to convey an OAuth error result, and answers with the dummy response required by section 3.2.3.` covers what the body does.

Two names for one exchange also appear in this file: this comment calls it "an OAuth error result", and `sendDummyResponse` below calls it "the failed discovery exchange", which the description says is out of scope for this PR. RFC 7628 calls it the error message sequence, and `sendDummyResponse` cites section 3.2 where the precise one is 3.2.3.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/ds/common/BaseDataSource.java:1610)

This is the third blocking finding. `getUrl()` builds its query string from every `PGProperty` that is set, so `oauthToken` and `oauthClientSecret` go into it. `password` is kept out of that URL by design, since it lives in a separate field rather than in `properties`, and these two secrets do not get the same treatment.

`getUrl()` is not only a bean getter. `getConnection()` logs it at `FINE` on every success and on every failure, and `Driver.connect` logs the same URL again. With a real Keycloak token on a plain `PGSimpleDataSource`:

```text
org.postgresql.Driver.connect: Connecting with URL: jdbc:postgresql://127.0.0.1:15433/test?...&oauthToken=<<<THE-TOKEN>>>&sslmode=disable
org.postgresql.ds.common.BaseDataSource.getConnection: Created a Non-Pooling DataSource ... at ...&oauthToken=<<<THE-TOKEN>>>...
```

The two properties need the treatment `password` gets: excluded from `getUrl()`, and redacted wherever a URL is logged.

This also puts the `char[]` handling in perspective. On the `oauthToken` path the secret is a `String` in `Properties` for the lifetime of the DataSource, and `toCharArray()` zeroes a copy, so the wiping helps only the provider path.

Smaller, on the same block: `setOAuthTokenProviderClassName` is the only one of the twelve new setters taking `@Nullable String`, and `getOAuthToken` yields the bean property `OAuthToken` rather than `oauthToken`, which `PGPropertyTest.dataSourceProperties` tolerates only because it indexes case-insensitively.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/plugin/OAuthTokenProvider.java:39)

`@return the token; must not be null` states half the contract. `resolveOAuthToken` rejects a zero-length array with the same `OAuth token provider returned no token`, so an implementer who returns `new char[0]` hits an exception this comment did not warn about. `@return the token; neither null nor empty` covers it.

`Individual fields may be null when not yet known` describes a staged handshake that does not happen. The rule is checkable: a field is null when the matching connection property is unset.

The wiping paragraph is the interesting one, and it is spread over two paragraphs with the second one entirely in `<b>`. One sentence carries both facts: `The driver zeroes the returned array once it has sent the token, so each call must return a fresh array.` Present tense fits, since this is what the code does rather than something it will do.

The type comment is worth more than it says now. An implementer needs to know that the driver instantiates the class named by `oauthTokenProviderClassName` through `ObjectFactory`, so a `Properties` constructor or a no-arg constructor is required; that `getToken` runs once per connection attempt, which makes it part of the connect path; and that a connection setting `oauthToken` never reaches the provider at all.

Separately, and this is an API question rather than a wording one: `AuthenticationPlugin` already covers `AuthenticationRequestType.SASL` and already does just-in-time `char[]` handling. It is worth a line in the description saying why OAuth gets its own SPI, since `requireAuth=oauth` will lead people with `authenticationPluginClassName` configured to expect their plugin to be called.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on build-logic/jvm/src/main/kotlin/build-logic.test-base.gradle.kts)

`authMode` is missing from this list, so `oauth=all` cannot be reproduced outside CI. I ran `./gradlew :postgresql:test --tests '*DriverTest' -DauthMode=oauth` and got one skipped test out of eighteen, where the eight `assumeNotOAuthMode()` calls this PR adds to `DriverTest` should have skipped eight; inside the test JVM `authMode` is null.

In CI it works by accident: `main.yml` passes `matrix.extraJvmArgs` through `_JAVA_OPTIONS`, which every JVM picks up, including the forked test JVM. That also makes the `enable_oauth_tests` entry you added here redundant for CI and load-bearing for local runs, so `authMode` needs the same treatment.

Together with the `OAUTH` value mismatch in `docker/bin/postgres-server`, `oauth=all` cannot be reproduced locally at all, which is the mode that justifies editing nine existing test classes.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on .github/workflows/matrix.mjs)

RFC 7632 is "Endpoint Security Posture Assessment: Enterprise Use Cases". The document you want is 7628, and its TLS requirement is in section 3.

```js
// OAUTHBEARER must run over TLS (RFC 7628, section 3), so OAuth rows need ssl=yes.
```

Two more in this block. The comment above line 357 says the Keycloak container exists only for PG 18 and up, and `quay.io/keycloak/keycloak:26.7` has no PostgreSQL version tied to it; the constraint belongs to `pg-oidc-validator-pgdg18.deb`. And near line 600, `// Route every connection through OAuth` overstates what `TestUtil.addOAuthProperties` does, which is to redirect connections of the default user that have no OAuth configured already.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/test/java/org/postgresql/test/jdbc4/OAuthTest.java:210)

`requireAuthForbidsOAuth` twenty lines up carries the rule for this file: "Assert only on the SQL state: the message is localized via GT.tr and varies by JVM locale." This assertion breaks it, and so does the one in `OAuthAuthenticatorTest` line 115. Both pass today only because the strings have not reached any `.po` file yet, and the matrix runs tests under `de_DE`, `fr_FR`, `ru_RU` and `tr_TR`. On my machine the neighbouring translated message already comes back as `Метод аутентификации запрещён настройкой requireAuth`.

`requireAuthForbidsOAuth` has the opposite problem: `CONNECTION_REJECTED` is returned by three other refusals on this path, including the transport check and `none of them configured or supported by the driver`, so on a host where `sslmode=prefer` gets no TLS it would stay green with the `AuthMethod.isAllowed` check deleted. A unit test over `AuthMethod.isAllowed` pins that behavior without a server and without depending on message text.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

The loop ignores `msgLen` and reads until it meets two NUL bytes, so an `AuthenticationSASL` whose body is a single terminator makes it read past the end of the message. I sent that from a fake backend, followed by an `ErrorResponse`:

```text
CLIENT-EXC: The server requested SASL authentication with mechanisms [, E],
            but none of them configured or supported by the driver.
```

The `E` is the type byte of the `ErrorResponse`, which the parser consumed as a mechanism name, and the server's real error never reaches the user. The `mechanisms.isEmpty()` check below cannot fire either, because `do/while` appends before it tests.

This came over unchanged from `ScramAuthenticator.advertisedMechanisms`, so it is not a regression. It is worth fixing here because the move is what makes it fixable: `msgLen` is in scope at the call site now and was not before. Passing the body length in and reading exactly that many bytes also lets the empty-list check become reachable.

One more on line 1257: `assert c == 0` is not an error handler, and the CI matrix has rows both with and without `-ea`, so a malformed packet behaves differently between them.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:427)

The `URISyntaxException` path lands in the same message, so a user whose issuer will not parse is told to set `oauthAllowInsecureIssuer=true`, which does not fix a malformed URL. `ValidateOAuthIssuerTest.malformedIssuerRejected` pins that behavior with `ht!tp://bad url`.

Splitting the two causes gives each its own remedy:

```java
} catch (URISyntaxException e) {
  throw new PSQLException(
      GT.tr("oauthIssuer is not a valid URL: {0}", issuer),
      PSQLState.INVALID_PARAMETER_VALUE, e);
}
```

A URI with no scheme at all, such as `issuer.example.com`, reaches the HTTPS message through `getScheme() == null` rather than through a scheme comparison, and is worth a case in the test either way.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java)

Four points on these two messages.

The section number is wrong: RFC 7628 section 4 is "Examples". The TLS requirement is in section 3 and section 5.

The remedy is the wrong one. A user who hits this under `sslmode=disable` needs `sslmode=verify-full`, and `oauthAllowUnencryptedConnection=true` only silences the check while leaving the token exposed.

The warning does not name the reason it fired, so an operator who finds it in a log cannot tell which property to remove. It also fires on every connection, which for a pool means one line per connection in every refill.

Suggestion for both:

```java
GT.tr("OAUTHBEARER authentication requires a TLS- or GSS-encrypted connection, "
    + "as RFC 7628, section 3 requires. Enable TLS with sslmode=verify-full, or set "
    + "oauthAllowUnencryptedConnection=true for development and testing.")
```

```java
LOGGER.log(Level.WARNING,
    "oauthAllowUnencryptedConnection=true: the bearer token is sent over a connection that is "
        + "neither TLS- nor GSS-encrypted. RFC 7628, section 3 requires TLS.");
```

The capitals and the exclamation mark do not add urgency that the level does not already carry, and this exact string is duplicated in `OAuthAuthenticatorTest` and `OAuthTest`, so rewording it today breaks two tests.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java)

`ScramAuthenticator` next door is a package-private `final class`, and this one is `public` only because `OAuthAuthenticatorTest` sits in `org.postgresql.test.core.v3` rather than in `org.postgresql.core.v3`, where its sibling `ScramAuthenticatorChannelBindingTest` sits in the same module. Moving the test into that package lets the class go back to package-private and keeps a new type out of the published surface of `org.postgresql.core.v3`.

The class comment is also the place to say what the constructor does, since it is the one that enforces the transport requirement and throws. Something like: `Writes the client side of the OAUTHBEARER SASL exchange (RFC 7628) onto a PGStream. One instance serves one authentication attempt, and the constructor enforces the encryption requirement, so a caller holding an instance may send the token.`

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/PGProperty.java)

Section 4 of RFC 7628 is "Examples"; the TLS requirement is in section 3 and section 5. "Confidential channel" is also a phrase the RFC does not use, where it says TLS.

The description string reaches users through `DriverPropertyInfo`, so it is worth more than the javadoc above it. `Default false per RFC 7628` repeats the default that is already the argument on the previous line and gives the reader nothing to act on.

```java
"Allow OAUTHBEARER authentication over a connection encrypted by neither TLS nor GSS. "
+ "RFC 7628, section 3 requires TLS, so enable this for development and testing only."
```

Four of the new descriptions say only what their name says: `OAuth client ID.`, `OAuth client secret.`, `OAuth token scope.`, `OAuth username.`. The fact a user needs is the one `use.md` already carries, that the driver does not contact the issuer and passes these to the `oauthTokenProviderClassName` implementation.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/test/java/org/postgresql/test/jdbc4/OAuthTest.java)

This asserts on a message the server produced, so it depends on the server's `lc_messages` and on how PostgreSQL 18 words this error in a given minor release. When a server upgrade changes the wording, the failure will point at the driver. `assertEquals("28000", ex.getSQLState())` is the stable form, with `ServerErrorMessage.getRoutine()` if you need to distinguish further.

This test is also the only coverage of the `AuthenticationSASLContinue` path, and it does not check that the path ran: `handleAuthenticationSASLContinue` could do nothing at all and the server would still send its `ErrorResponse`. `logHandler` is already wired up in this class, so asserting that the rejection record appeared would close that gap.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docker/bin/postgres-server)

The header of this script says it "respects all the same environment variables used by the CI matrix", and for `OAUTH` it does not. The matrix uses `no`, `smoke`, and `all` (`matrix.mjs` lines 197-201), `entrypoint.sh` tests `!= "no"` and separately `= "all"`, and this line tests `= "yes"`, a value the matrix never produces.

So `OAUTH=smoke docker/bin/postgres-server` and `OAUTH=all docker/bin/postgres-server` both install `pg_oidc_validator`, write an `oauth` rule into `pg_hba.conf` pointing at `issuer=http://keycloak:8080/...`, and start no Keycloak, because the compose profile is only exported here. On arm64 they also skip `PG_PLATFORM`, and the amd64-only package fails to install.

`if [ "${OAUTH:-no}" != "no" ]` fixes the profile. The header on line 14 and `docker/postgres-server/README.md` line 22 both need the three real values, plus the two effects a reader only discovers by running it: Keycloak takes `127.0.0.1:8080`, and on arm64 the server runs emulated under `linux/amd64`.

There is a missing space after `available:` in the TODO on line 66, and the same in `docker-compose.yml` line 7, which keeps the URL from linking.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/test/java/org/postgresql/core/v3/BuildTokenMessageTest.java)

Good set of invalid characters. Five cases are missing at the boundary of `[A-Za-z0-9._~+/-]+=*`, and this regex is the only thing standing between a caller and a malformed token on the wire:

- `"="` alone, padding with no leading character, which the `+` refuses
- `"abc=def"`, an `=` in the middle
- `"abc=="`, double padding, since only a single `=` is covered today
- `"a"`, one character
- a non-ASCII token. This one is not cosmetic: `buildTokenMessage` writes the token with `msg.put((byte) c)`, and that narrowing is safe only because the regex ran first. Nothing pins that ordering.

`@ValueSource` also prints the argument as the case name, so `"newline\nhere"` puts a real line break into the report and `"soh\u0001here"` puts a control byte into the XML. `@MethodSource` with `argumentSet("token containing a newline", "newline\nhere")` names them instead.

Minor: `validToken` asserts on the decoded `String` and reads well on failure, while `nullToken` and `emptyToken` assert on raw bytes and print `expected: <[110, 44, 44, 1, ...]>`. One style for both would help.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc-mockito-test/src/test/java/org/postgresql/test/core/v3/OAuthAuthenticatorTest.java)

`assertEquals(1, warnings.size())` prints `expected: <1> but was: <0>` and carries no message, so a failure says nothing about which records were there. The same shape appears at lines 79, 87, 96, 105 and 117 as `assertEquals(0, logHandler.records.size(), ...)`. Asserting on the list of messages instead prints what actually arrived.

This class is otherwise the best-tested part of the change: `{TLS, GSS, unencrypted} × {require, allow}` is complete and the negative control is there. Since the six methods differ only in their inputs, one `@ParameterizedTest` with `argumentSet("TLS socket, encryption required", ...)` would say so.

A class comment would help too, in the shape its sibling `ScramAuthenticatorChannelBindingTest` uses: the rule guarded rather than the subject. Something like `A TLS- or GSS-encrypted connection admits OAUTHBEARER silently, an unencrypted one is refused, and oauthAllowUnencryptedConnection turns that refusal into a single WARNING record.`

Two small ones: `"no log records expected over a GSS"` reads oddly, `over a GSS-encrypted connection` fits; and line 117 is missing a space after the comma.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc-mockito-test/src/test/java/org/postgresql/core/v3/ScramAuthenticatorChannelBindingTest.java:39)

Moving the `-PLUS` check into `initializeScramClient` gives `requireRejectsConnectionWithoutSsl` a second way to pass. That test asserts only `CONNECTION_REJECTED`, and the new check throws the same state, so dropping `SCRAM-SHA-256-PLUS` from this constant leaves the test green while it stops guarding the regression it was written for (GHSA-j92g-9f8w-j867). Its neighbour `requireRejectsCertificateWithoutChannelBindingHash` is safe, because it asserts on the message.

Asserting the message in that test, or a short comment here saying why `-PLUS` has to stay in this list, closes it.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on testkit/src/main/java/org/postgresql/test/OAuthTestTokenProvider.java)

Three things in this method, and they matter more than usual because this class is the only worked example of `OAuthTokenProvider` in the repository.

`oauthToken system property not set` on line 48 describes something the method does not do. This branch runs when Keycloak returned a response with an empty `access_token`.

Line 58 puts `request.getClientSecret()` into the resource owner's `password` field. `realm.json` declares `pgjdbc-test` as `publicClient: true`, so it has no client secret at all, and `testoidc-password` is the password of user `testoauth`. The example therefore teaches that `oauthClientSecret` carries a user password, and `getClientSecret()` is never exercised as what it is.

`readResponse` reads only `getInputStream()`. On a 4xx the JVM throws there and the Keycloak error body in `getErrorStream()` is lost, so a broken realm shows up as `Failed to get OAuth token: Server returned HTTP response code: 401` with nothing to act on.

One design note: `getToken` makes a full HTTP round trip per connection with no caching. Under `authMode=oauth` that is one request per connection for the whole suite, and a single network hiccup fails an unrelated test.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:45  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:45 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on testkit/src/main/java/org/postgresql/test/TestUtil.java)

Two constants name something other than what they hold.

`OAUTH_ISSUER` is the token endpoint. The issuer the server knows, from `entrypoint.sh`, is `http://keycloak:8080/realms/pgjdbc`, and `use.md` describes the property as "URL of the OAuth issuer (authorization server)". A test provider that treats the issuer as a URL to POST to will mislead the first person who copies it.

`OAUTH_CLIENT_SECRET` holds the password of user `testoauth` from `realm.json`, not a client secret.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-09 15:50  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-09 15:50 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docker/postgres-server/docker-compose.yml)

Fixed. `platform` is now `${PG_PLATFORM:-}`, and only `docker/bin/postgres-server` sets it, for OAuth runs. Checked on an arm64 host: with `PG_PLATFORM` unset, `docker compose config` emits no `platform` key at all, so a non-OAuth run stays on the host architecture and only OAuth runs pay for emulation. percona/pg_oidc_validator#44 and pgdg-packaging/apt.postgresql.org-issues#2 are both still open, so the TODO is still accurate.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251 (changes requested): OAuth implementation
@ 2026-09-12 16:22  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-12 16:22 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

See comments above. Adding a formal "request changes" so GitHub filters can do their thing (e.g. `review:changes_requested`)

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 18:50  "gitguardian[bot] (bot) (@gitguardian[bot])" <noreply+gitguardian[bot]@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: gitguardian[bot] (bot) (@gitguardian[bot]) @ 2026-09-22 18:50 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

#### ⚠️ GitGuardian has uncovered 1 secret following the scan of your pull request.

Please consider investigating the findings and remediating the incidents. Failure to do so may lead to compromising the associated services or software components.

Since your pull request originates from a forked repository, GitGuardian is not able to associate the secrets uncovered with secret incidents on your GitGuardian dashboard.
Skipping this check run and merging your pull request will create secret incidents on your GitGuardian dashboard.

<details>
<summary>🔎 Detected hardcoded secret in your pull request</summary>
<br>

| GitGuardian id | GitGuardian status | Secret                         | Commit           | Filename        |                      |
| -------------- | ------------------ | ------------------------------ | ---------------- | --------------- | -------------------- |
| [-](https://dashboard.gitguardian.com/workspace/59849/incidents/secrets) | - | Generic Password | 1c0cd665a11ae1f9330885550b76a0d4bb517204 | pgjdbc/src/test/java/org/postgresql/util/internal/JdbcUrlMaskerTest.java | [View secret](https://github.com/pgjdbc/pgjdbc/commit/1c0cd665a11ae1f9330885550b76a0d4bb517204#diff-bda439cd4223b2...) |



</details>

<details>
<summary>🛠 Guidelines to remediate hardcoded secrets</summary>
<br>

1. Understand the implications of revoking this secret by investigating where it is used in your code.
2. Replace and store your secret safely. [Learn here](https://blog.gitguardian.com/secrets-api-management?utm_source=product&amp;utm_medium=GitHub_che...) the best practices.
3. Revoke and [rotate this secret](https://docs.gitguardian.com/secrets-detection/secrets-detection-engine/detectors/generics/generic_p...).
4. If possible, [rewrite git history](https://blog.gitguardian.com/rewriting-git-history-cheatsheet?utm_source=product&amp;utm_medium=...). Rewriting git history is not a trivial act. You might completely break other contributing developers' workflow and you risk accidentally deleting legitimate data.

To avoid such incidents in the future consider

-   following these [best practices](https://blog.gitguardian.com/secrets-api-management/?utm_source=product&amp;utm_medium=GitHub_ch...) for managing and storing secrets including API keys and other credentials
-   install [secret detection on pre-commit](https://docs.gitguardian.com/ggshield-docs/integrations/git-hooks/pre-commit?utm_source=product&...) to catch secret before it leaves your machine and ease remediation.


</details>

---

<sup>🦉 [GitGuardian](https://dashboard.gitguardian.com/auth/login/?utm_medium=checkruns&amp;utm_source=github&amp...) detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.<br/></sup>

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 18:51  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 18:51 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

Done, this function was rewritten

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 18:53  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 18:53 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:1273)

Fixed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 18:55  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 18:55 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

Function was rewritten and now respects message len.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 18:56  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 18:56 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

Reworked that part and added tests

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 18:58  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 18:58 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

Fixed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:01  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:01 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java)

Added cert validation

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:01  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:01 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java)

Fixed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:01  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:01 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java)

Done

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:02  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:02 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/ds/common/BaseDataSource.java:1610)

Added fix for credentials masking in separate commit

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:03  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:03 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/PGProperty.java)

Fixed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:03  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:03 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/plugin/OAuthTokenProvider.java:39)

Done

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:04  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:04 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on build-logic/jvm/src/main/kotlin/build-logic.test-base.gradle.kts)

Fixed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:04  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:04 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docker/bin/postgres-server)

Done

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:05  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:05 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on .github/workflows/matrix.mjs)

Fixed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:05  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:05 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/test/java/org/postgresql/test/jdbc4/OAuthTest.java)

Fixed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:06  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:06 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/test/java/org/postgresql/test/jdbc4/OAuthTest.java:210)

Fixed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:08  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:08 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

Function was rewritten 

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:08  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:08 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:427)

Fixed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:09  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:09 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java:116)

Fixed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:10  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:10 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docs/content/documentation/use.md)

Updated

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:10  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:10 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on testkit/src/main/java/org/postgresql/test/OAuthTestTokenProvider.java)

Fixed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:11  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:11 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on testkit/src/main/java/org/postgresql/test/TestUtil.java)

Yep, this was a mess. Fixed.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:12  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:12 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/test/java/org/postgresql/core/v3/BuildTokenMessageTest.java)

Added

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:13  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:13 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc-mockito-test/src/test/java/org/postgresql/test/core/v3/OAuthAuthenticatorTest.java)

Changed 

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:15  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:15 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc-mockito-test/src/test/java/org/postgresql/core/v3/ScramAuthenticatorChannelBindingTest.java:39)

Added assertion

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:15  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:15 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

Fixed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:17  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:17 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Pushed huge update that fixes a lot of corner cases and resolves all existing comments.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-22 19:18  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-09-22 19:18 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

@artemgavrilov requested a review.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java:66)

This trusts the value of `sslmode`, not what happened on the socket:

- `sslmode=verify-full&sslfactory=org.postgresql.ssl.NonValidatingFactory` connects with no root certificate, and the token goes to an unverified server without any warning. The docs describe this, but a user who copies a `NonValidatingFactory` URL from a Stack Overflow answer won't read that paragraph.
- The Cloud SQL and AlloyDB Java connectors require `sslmode=disable`, and their `socketFactory` returns an `SSLSocket` they have already verified. This check refuses them with `sslmode=disable does not verify it`, which is wrong for them.
- `verify-ca` passes although it skips the host name check.

libpq has no transport check for OAUTHBEARER at all. Being stricter is defensible for a bearer token, but these cases need to be either handled or documented as known limits.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:1380)

This loop keeps reading after the empty name that ends the list. A fake backend sending `\0OAUTHBEARER\0\0` gets `["", "OAUTHBEARER"]` back, and the driver sends the token. `A\0\0B\0\0` gives `[A, "", B]`, so a mechanism after the terminator is accepted. libpq stops at the first empty name (`pg_SASL_init` in `fe-auth.c`).

Stop at the first empty name, and throw `PROTOCOL_VIOLATION` when bytes follow it. `\0` alone should also be `08P01`, like its siblings; right now it reports `0 mechanisms!` with `08004`.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:411)

`oauthAllowInsecureIssuer=true` returns before the URI is parsed, so it also accepts `not a uri`. The property's description promises only to allow `http`. Parse first, then check the scheme.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:372)

libpq picks the first of SCRAM-SHA-256 and OAUTHBEARER in the order the server sends them (`fe-auth.c`). This code picks OAUTHBEARER in either order. No PostgreSQL server offers both in one message, since the `pg_hba.conf` entry selects one method (`oauth_get_mechanisms` advertises only OAUTHBEARER), so the preference is hypothetical. It's the docs and the changelog that turn it into advice to add `requireAuth=scram-sha-256` (see the comment on `use.md`).

Also, nothing logs this decision, including the two fallbacks to SCRAM (channel binding, OAUTHBEARER not offered). A user who configured OAuth then sees only a SCRAM error. One FINE record with the offered list, the choice, and the reason would help.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:468)

The sibling messages name the provider class, and this one doesn't: `GT.tr("OAuth token provider {0} returned a null or empty token", providerClassName)`.

Also: a provider that returns the same array twice gets it back zeroed on the second connection, and then fails with `Invalid OAuth bearer token format`, which gives no hint of the cause. That follows the documented contract, but the Javadoc could say what the failure looks like.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:1273)

The flag was already set at line 1222, so this call has no effect: removing it changes nothing. Drop it, or explain why it's needed.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:1337)

The behavior is right and matches libpq's `check_expected_areq`, but this and the GSS changes above fix a defect from 42.7.11 (#3895) that affects SCRAM users without OAuth. Please move them to a separate PR so they can ship without the feature.

The call sites have no test. Putting `setFinishedAuthenticationRequests()` back into `enableGSSEncrypted`, or removing it from the JGSS branch, passes every test. `CheckAuthenticationCompletedTest` covers the predicate only.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java:73)

RFC 7628 §3 says only "TLS MUST be used for OAUTHBEARER to protect the bearer token". It says nothing about verifying the certificate or about GSS. Certificate validation is RFC 6750 §5.3 ("Validate TLS certificate chains"), whose "or equivalent transport security" also covers GSS. The same citation appears in `PGProperty`, `use.md`, and `CHANGELOG.md`.

Suggested text:

```
OAUTHBEARER sends the bearer token only to a verified server, and sslmode={0} does not verify the server certificate. Set sslmode=verify-full or verify-ca (RFC 6750 section 5.3).
```

For the unencrypted case, include the `sslmode` in effect (the usual cause is `prefer` falling back to plaintext) and leave `oauthAllowInsecureConnection` to the docs. Offering the escape hatch in the error contradicts `use.md`, which says the remedy is to raise `sslmode`. I'd also write "section" instead of `§` in `GT.tr` strings, since they end up in `.po` msgids and on consoles.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java:116)

The caller never sees this JSON. The connection fails with `FATAL: OAuth bearer authentication failed for user "..."` (28000), and the `status`/`scope`/`openid-configuration` that tell the caller why exist only in this WARNING. A retrying HikariCP pool logged six of these in one second. The text is server-controlled, possibly from an unverified server when `oauthAllowInsecureConnection=true`, and it is logged verbatim, newlines included.

Keep the JSON in the authenticator, attach it to the exception built from the ErrorResponse (as a cause, so 28000 stays), and log it at FINEST as ` <=BE AuthenticationSASLContinue( {0} )`, like `ScramAuthenticator`. libpq also parses the JSON and fails on a malformed one; here an empty body is logged without complaint.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:431)

This runs before the `oauthToken` check, so an `oauthIssuer` the driver never uses blocks the connection: `oauthToken=good-token&oauthIssuer=http://idp` fails with `OAuth issuer URL must use HTTPS`, and a malformed URI fails with `OAuth issuer is not a valid URL`. The same issuer against a SCRAM server connects, because this runs only on the OAuth path.

The driver doesn't compare `oauthIssuer` with the issuer the server advertises either (libpq does, during discovery). So I'd drop the validation, or apply it only to the value handed to the provider, and document which it is.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:337)

An empty `oauthToken=` or `oauthTokenProviderClassName=` counts as "not configured" here, and mutation testing shows no test pins that down: removing both `isEmpty()` checks passes every test. That matters, because with both mechanisms offered an empty token would make OAUTHBEARER win and then fail. Please add the two empty-string rows to `SelectSaslMechanismTest`.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:442)

The driver creates a new provider instance on every connection attempt, including each failover retry. Please document this in the `OAuthTokenProvider` Javadoc and in `use.md`, and say that an implementation should be a lightweight bridge to a layer that caches the token (a cloud SDK credential, a token file), or keep its cache in a static field keyed by everything that affects the token, the client secret and the user included.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:1222)

Removing this call passes every DB-free test, yet it breaks `requireAuth=oauth` for every successful login (AuthenticationOk then looks like trust). The live server run shows the current code is right. Please add a loopback test of a successful OAUTHBEARER exchange with `requireAuth=oauth`: SASL(OAUTHBEARER), then AuthenticationOk, then ReadyForQuery, and the connection opens.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java:1213)

The constructor enforces the transport check before `resolveOAuthToken`, which is the right order: the provider isn't called for a connection that would be refused.

Mutation testing found that forcing `allowInsecure` to `true` here, or changing the default of `oauthAllowInsecureConnection` to `"true"`, passes every test. See the comment on `OAuthHandshakeTest`.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java:84)

pgjdbc logs through `java.util.logging`, whose default console handler prints WARNING to stderr, so this fires once per connection in any host that never configured logging. A pool of 50 prints 50 two-line blocks, and so does every pool refill. The user opted in by name, so the record carries no news after the first one.

Log WARNING once per JVM, then FINE. Add the host (`pgStream.getHostSpec()`), so the reader can tell which DataSource logged it. Drop the RFC citation and "Do not use this configuration in production", for example:

```
Sending the OAuth bearer token to {0} over TLS without verifying the server certificate (sslmode={1}), because oauthAllowInsecureConnection=true
```

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docs/content/documentation/use.md:563)

Please add what a user needs before relying on this property:

- The token is a fixed value. A pool that opens a connection after it expires gets `FATAL: OAuth bearer authentication failed for user "..."` on every new connection and never recovers (reproduced with HikariCP), while open sessions stay up. Use `oauthTokenProviderClassName` for pools.
- The token must match the RFC 6750 `b64token` syntax, or the connection fails with `Invalid OAuth bearer token format...`. In a JDBC URL, write `+` as `%2B`.
- The value is omitted from `getUrl()` and masked in logged URLs, but `DatabaseMetaData.getURL()` returns it, and HikariCP logs `dataSourceProperties` unmasked at DEBUG.
- Cloud IAM and Entra tokens (RDS, Aurora, Azure, Cloud SQL) are passwords, not OAUTHBEARER tokens. Setting one here fails with `The server requested password-based authentication, but no password was provided.` Point users to `password` or `authenticationPluginClassName` instead.
- `Since: 42.7.14` on this and every other new entry, and on the `oauth` value of `requireAuth`.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docs/content/documentation/use.md:559)

No PostgreSQL server offers OAUTHBEARER and SCRAM-SHA-256 in one message: the `pg_hba.conf` entry selects one method, and `oauth_get_mechanisms` advertises only OAUTHBEARER. A reader of this paragraph will conclude that setting `oauthToken` makes `password` unusable, or that `requireAuth=scram-sha-256` is needed to keep passwords working. Neither is true: against a SCRAM rule, the driver uses the password even with `oauthToken` set.

Suggested: "The server's `pg_hba.conf` entry selects the method. When it selects `oauth`, the driver sends the token from `oauthToken` or `oauthTokenProviderClassName`; for any other method these properties are ignored." The same claim is in the changelog.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java:136)

On the `handleAuthenticationOk` path, the server sent AuthenticationOk after an error result, not "additional OAuth data". Suggested: `The server continued the OAUTHBEARER exchange after it reported an error.`

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java:165)

Removing this `Arrays.fill` passes every test, since only the `char[]` wipe in `ConnectionFactoryImpl` is tested. A mockito test that captures the array passed to `pgStream.send(byte[])` and checks it's all zeros afterwards, including when `send` throws, would pin it down.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java:189)

The message gives no action and doesn't say where the token came from. A token passed in the JDBC URL with a `+` fails here, because `Driver.parseURL` decodes `+` to a space. Suggested: `The OAuth bearer token contains a character that RFC 6750 section 2.1 does not allow. Check oauthToken, where a + in a URL must be written as %2B, or the value the OAuthTokenProvider returned.`

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/plugin/OAuthTokenProvider.java:18)

"once per connection attempt" is ambiguous. The driver creates a new instance and calls `getToken` each time a server requests OAUTHBEARER over a connection that passes the transport check. With several hosts that happens more than once per `getConnection`, and it never happens when the server picks SCRAM. The call counts toward `loginTimeout` and must return within the server's `authentication_timeout`.

Please add one more sentence: the message and cause of an exception thrown here reach the caller and the FINE `Connection error:` log record, so they must not contain the token or `clientSecret`.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on TESTING.md:372)

Renumbering changes the anchor from `#11---credits-and-feedback` to `#12---credits-and-feedback`. Nothing in the repository links to it, but outside links may. Placing the OAuth section after Credits keeps the old number. Also: the section should say that `authMode=oauth` sets `oauthAllowInsecureConnection=true` and `oauthAllowInsecureIssuer=true` for the whole suite, so the secure transport path is not what CI tests.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/test/java/org/postgresql/core/v3/SelectSaslMechanismTest.java:73)

Several tests here make two or more calls with different inputs and assert after each (for example lines 74-79, 100-105, 108-114, 160-167, 170-177), so one failure hides the rest, and the name has to cover several cases. The function is a pure decision over offered mechanisms × `requireAuth` × configured × `channelBinding`, which reads best as one `@ParameterizedTest` table with a named row per case.

Missing rows: empty `oauthToken=` and `oauthTokenProviderClassName=` (a surviving mutant), a server offering only `SCRAM-SHA-256-PLUS`, and one offering `PLAIN` with `OAUTHBEARER`.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on CHANGELOG.md)

"`password` was never affected" isn't true for a `password` in the JDBC URL. On master, `Driver` logs the URL verbatim at WARNING (`JDBC URL contains too many / characters: {0}`, `JDBC URL must contain a / at the end of the host or port: {0}`), at FINE (`Connecting with URL: {0}`), and in the `Unable to parse URL {0}` exception. That is the leak released users have, and this entry doesn't mention it.

`oauthToken` and `oauthClientSecret` were never released, so no upgrading user was affected by them. The `getUrl()` change needs a `**Breaking:**` marker and its own entry, or better, see the comment on `BaseDataSource.getUrl()`.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/test/java/org/postgresql/core/v3/OAuthHandshakeTest.java:93)

Every handshake here runs with `oauthAllowInsecureConnection=true`, and so does every OAuth success path in CI (`TestUtil.addOAuthProperties`). Mutation testing shows the consequence: forcing the flag to `true` in `ConnectionFactoryImpl`, or making `true` its default in `PGProperty`, passes every test.

Please add a handshake without the flag over plaintext that is refused with `CONNECTION_REJECTED` and whose backend receives no SASLInitialResponse. Please also add an integration test of the production configuration: `sslmode=verify-full` with the test certificates.

Other gaps in this class, each a surviving mutant or an untested sequence: a successful OAUTHBEARER exchange with `requireAuth=oauth`; a second AuthenticationSASLContinue after the error; a second AuthenticationSASL during SCRAM. In `refusesASecondSaslExchange`, `&password=secret` and the extra `authenticationSaslContinue()` do nothing, because the check fires before anything is read. `refusesSaslFinalAfterTheServerRejectedTheToken` hit its 30-second timeout once when run under load.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docs/content/documentation/use.md:593)

RFC 7628 §3 says only that TLS must be used. It gives no reason, and says nothing about impostor servers or certificate verification. That part is RFC 6750 §5.3. Suggested: "RFC 7628 §3 requires TLS for OAUTHBEARER, and RFC 6750 §5.3 requires the client to validate the server certificate, so an unverified server could collect the token." One more sentence would save bug reports: libpq applies no such check, so a connection string copied from `psql` with `sslmode=prefer` fails here.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on CHANGELOG.md:8)

This entry is about 330 words, which is documentation rather than a change note. It cites RFC 7628 §3 for certificate verification (that's RFC 6750 §5.3). It also includes the OAUTHBEARER-over-SCRAM precedence, which no PostgreSQL server can trigger. Suggested:

```markdown
* feat: OAUTHBEARER authentication for PostgreSQL 18, set by `oauthToken` or by an `org.postgresql.plugin.OAuthTokenProvider` named in `oauthTokenProviderClassName`. The provider receives `oauthIssuer`, `oauthClientId`, `oauthClientSecret` and `oauthScope`, and the driver does not contact the issuer. `requireAuth` accepts `oauth`. The token is sent only with `sslmode=verify-ca` or `verify-full`, or over GSS encryption, so the default `sslmode=prefer` fails with `OAUTHBEARER authentication requires ...`; `oauthAllowInsecureConnection=true` is for testing [Issue #3816](https://github.com/pgjdbc/pgjdbc/issues/3816) [PR #4251](https://github.com/pgjdbc/pgjdbc/pull/4251)
```

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/PGProperty.java:492)

The Javadoc and description cite RFC 7628 §3 for certificate verification, which is RFC 6750 §5.3. "DO NOT ENABLE IN PRODUCTION ENVIRONMENTS" doesn't need the capitals. Suggested description: `Allow OAUTHBEARER when the connection is neither GSS-encrypted nor TLS-encrypted with sslmode=verify-ca or verify-full. For testing only.`

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/ds/common/BaseDataSource.java:122)

This method has 0% coverage, and dropping every credential it copies passes every test: `setOAuthToken`, `setSslPassword`, and `setOAuthClientSecret` would stop working silently. A test that connects a `PGSimpleDataSource` with `setOAuthToken(...)` to the `OAuthHandshakeTest` fake backend and checks the token in the SASLInitialResponse would pin it down.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docs/content/documentation/use.md:552)

This paragraph leaves out the case every reader hits first. With the default `sslmode=prefer`, OAuth always fails, over TLS too: the check refuses any `sslmode` that doesn't verify the certificate. As written, the text says `prefer` fails only when the server refuses TLS.

I'd move this introduction out of the property list into an `### OAuth authentication` section after it (as with `### Unix sockets`), and open with: "OAuth authentication needs a verified server. Set `sslmode=verify-full` (or `verify-ca`), or use a GSS-encrypted connection. With the default `sslmode=prefer`, and with `require`, the driver refuses to send the token even when the connection uses TLS." The section would also hold the server prerequisites (PostgreSQL 18, an `oauth` rule in `pg_hba.conf`, a validator in `oauth_validator_libraries`), a URL example, a provider skeleton, a pooled setup, and the error texts, since none of the messages appears on the page.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docs/content/documentation/use.md:541)

"`requireAuth=gss` is met by `gssEncMode=require` alone" holds only when the server asks for nothing after GSS encryption. If `pg_hba.conf` then asks for a password, `requireAuth=gss` refuses the connection. It also holds for `gssEncMode=prefer`. The next sentence denies the pre-fix behavior, which belongs in the changelog. Suggested: "The connection fails if the server completes authentication without requesting any, as with a `trust` rule, unless `requireAuth` allows `none`. On a GSS-encrypted connection, `gss` is accepted in that case as well." 

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docs/content/documentation/use.md:567)

This entry needs the provider's contract:

- a public constructor taking `java.util.Properties`, or a no-argument one;
- the driver creates a new instance and calls `getToken` on every connection attempt, including once per host of a multi-host URL, so any cache must be static;
- the call happens only after the server asks for OAuth and the transport check passes, and it counts against `loginTimeout` and the server's `authentication_timeout`;
- it must return a new array every time, because the driver wipes it;
- a `PSQLException` reaches the caller unchanged, and anything else is wrapped as `OAuth token provider {0} failed to return a token`.

Please also link to the Javadoc.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on docs/content/documentation/use.md:598)

Three of these four sentences explain the mechanism and defend it. The consequence the reader needs is missing: with `sslmode=verify-ca` or `verify-full` and a factory that doesn't validate, the token goes to an unverified server, and nothing is logged. Suggested: "With a custom `sslfactory`, the driver trusts `sslmode` and does not inspect the factory. A factory that skips validation, such as `org.postgresql.ssl.NonValidatingFactory`, sends the token to an unverified server without a warning." The `sslfactory` entry needs a matching sentence.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on CHANGELOG.md:11)

Please say "defect since 42.7.11, where `requireAuth` was added", note that only connections with `requireAuth` set are affected, and quote the new error text, which replaces `Authentication method is not allowed by requireAuth` when a server lets the connection in without a request. This entry would travel with the separate PR.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/OAuthAuthenticator.java:103)

Minor: the password path traces ` FE=> Password(password=<not shown>)`. `<token>` looks like a placeholder that failed to substitute; `<not shown>` would match.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/plugin/OAuthTokenRequest.java:22)

This class becomes public API, and a public four-argument constructor fixes its field set: adding a field later means another constructor or a break. A builder, or a constructor that isn't public (the driver is the only one that creates requests), keeps it open.

The fields are also too few for anything beyond a client-credentials flow against a fixed issuer. There is no host, port, user, or database, and with a multi-host URL a provider can't tell which host is being tried. Tokens from cloud identity providers are bound to exactly those values. Since discovery is planned for later, the issuer and scope the server advertises will need a place too.

The getters have only `@return` tags and no `@since`.

Please also rename the class to `OauthTokenRequest`, and `OAuthTokenProvider` to `OauthTokenProvider`, following the same camel-case rule as the setters ([Google Java Style §5.3](https://google.github.io/styleguide/javaguide.html#s5.3-camel-case)).

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/PGProperty.java:1075)

Masking matches parameter names exactly, as `parseURL` does, so it covers what the driver reads. Two things it doesn't cover: `PgConnection.getURL()` and `DatabaseMetaData.getURL()` still return the raw URL with `oauthToken=...`, and `Driver`'s FINE `JDBC URL database name [{0}] could not be decoded` prints a token-like value that sits in the path. The first is the same as `password` today, but tools often log `DatabaseMetaData.getURL()`, so it's worth a docs note that recommends the provider over a token in the URL.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/ds/common/BaseDataSource.java:1519)

This is a compatibility break. I reproduced it with an encrypted client key: `copy.setURL(ds.getURL()); copy.setUser(ds.getUser())` connects on master and fails here with `Could not read password for SSL key file, console is not available.` Meanwhile `getReference()` and serialization still carry `sslpassword` and `oauthToken`, so the secret doesn't leave the DataSource anyway.

I'd keep `getUrl()` as it was and mask the URL where it is logged (`getConnection` logs it twice at FINE). If you keep the change, it needs a `**Breaking:**` changelog entry and its own commit.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/ds/common/BaseDataSource.java:1608)

HikariCP's `PropertyElf` derives `setOauthToken` from `dataSource.oauthToken`, so with `dataSourceClassName=org.postgresql.ds.PGSimpleDataSource` the pool fails at start:

```
java.lang.RuntimeException: Property oauthToken does not exist on target class org.postgresql.ds.PGSimpleDataSource
```

The same happens with `hikari.properties`. Only `dataSource.OAuthToken` works. This affects all eight new setters. Since none of them has been released, please rename them rather than add aliases: `get/setOauthToken`, `get/setOauthTokenProviderClassName`, `get/setOauthIssuer`, `get/setOauthClientId`, `get/setOauthClientSecret`, `get/setOauthScope`, `get/setOauthAllowInsecureConnection`, `get/setOauthAllowInsecureIssuer`. That is what `java.beans.Introspector` derives from `oauthToken`, and it follows [Google Java Style §5.3](https://google.github.io/styleguide/javaguide.html#s5.3-camel-case), as `setSslMode` and `setGssResponseTimeout` do. `PGPropertyTest.dataSourceProperties` didn't catch it because it compares names with `CASE_INSENSITIVE_ORDER`; it should also check the exact setter name HikariCP looks up.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/test/java/org/postgresql/test/jdbc4/OAuthTest.java:214)

This test and `unverifiedTlsConnectionRejected` and `requireAuthForbidsOAuth` assert only `CONNECTION_REJECTED`, which five other failures share (for example "no password was provided"), so they can pass for the wrong reason. Please assert something specific to the cause as well. `staticToken`, `tokenProvider`, and `invalidToken` are names without an outcome, for example `connectsWithAStaticToken` and `refusesATokenTheValidatorRejects`.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 06:43  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:43 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc-mockito-test/src/test/java/org/postgresql/core/v3/ReadMechanismsTest.java:68)

The stub ignores the read position, so `verify(stream).receive(n)` can't show where the stream ended up. Use a real `PGStream` over `CannedSocketFactory` (already in `pgjdbc/src/test/.../core/`), put an `'E'` after the message, and assert that the next `receiveChar()` returns it. That also removes the mock of a class the test doesn't own.

Please add the cases from the comment on `readMechanisms`: bytes after the terminating empty name, and an empty first name. `rejectsUnterminatedMechanismName` (line 99) is misnamed: the name is terminated, and what is missing is the list terminator.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251 (changes requested): OAuth implementation
@ 2026-09-23 06:47  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-09-23 06:47 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Thanks for the big update. The OAUTHBEARER message format matches RFC 7628, `requireAuth=oauth` behaves correctly end to end, and the loopback `OAuthHandshakeTest` is a good way to test the handshake without Keycloak. I ran the PR (head 0b6a1442e) against PostgreSQL 18.6 with a dummy validator, against a scripted fake backend, under 131 hand-made mutants, and with HikariCP 7.1 and Spring Boot 4.1. I compared behavior with libpq and pgbouncer at their current `master`. The results are below, and the line-specific ones are in inline comments.

I'm requesting changes. The main reasons: a parser bug in `readMechanisms`, a backward-incompatible change to `BaseDataSource.getUrl()`, HikariCP's `dataSource.oauthToken` failing at pool start, a public SPI that can't grow, and RFC citations that don't say what the messages claim.

## Bugs

1. `readMechanisms` keeps reading after the terminator of the mechanism list. `\0OAUTHBEARER\0\0` is parsed as `["", "OAUTHBEARER"]` and the token is sent. `A\0\0B\0\0` becomes `[A, "", B]`. libpq stops at the first empty name (`fe-auth.c`, `pg_SASL_init`). See the inline comment.
2. `oauthIssuer` blocks a connection that never uses it. `resolveOAuthToken` validates the issuer before it looks at `oauthToken`, so `oauthToken=good-token&oauthIssuer=http://idp` fails with `OAuth issuer URL must use HTTPS` (22023), and a malformed URI fails with `OAuth issuer is not a valid URL`. The same issuer against a SCRAM server connects, because the check runs only on the OAuth path. The driver also never compares `oauthIssuer` with the issuer the server advertises: `oauthIssuer=https://other.example` connects to a server configured with `issuer=https://issuer.example`. `oauthAllowInsecureIssuer=true` skips the URI syntax check too.
3. HikariCP's JavaBean route fails. `dataSourceClassName=org.postgresql.ds.PGSimpleDataSource` with `dataSource.oauthToken=...` (or the same key in `hikari.properties`) fails at pool start with `Property oauthToken does not exist on target class org.postgresql.ds.PGSimpleDataSource`. HikariCP's `PropertyElf` looks for `setOauthToken`, and all eight new setters are spelled `setOAuth...`. Only `dataSource.OAuthToken` works, and nobody will guess that key. The API is not released yet, so please rename the setters and getters to `setOauthToken`, `getOauthToken`, and so on, rather than add aliases. That is what `java.beans.Introspector` derives from the property name `oauthToken`, and it matches [Google Java Style §5.3](https://google.github.io/styleguide/javaguide.html#s5.3-camel-case) and the rest of `BaseDataSource` (`setSslMode`, `setGssResponseTimeout`, `setTcpKeepAlive`). `PGPropertyTest.dataSourceProperties` misses it because it compares names with `CASE_INSENSITIVE_ORDER`.
4. The reason for a rejected token never reaches the caller. The server's RFC 7628 error result (`status`, `scope`, `openid-configuration`) goes only to a WARNING log. The exception says only `FATAL: OAuth bearer authentication failed for user "..."`. A Hikari pool that retries produced 6 of these WARNINGs in one second. The JSON is server-controlled and is logged verbatim, newlines included.

## Backward compatibility

- `BaseDataSource.getUrl()` and `getURL()` no longer include `sslpassword`. I reproduced the break with an encrypted client key: `copy.setURL(ds.getURL())` connects on master and fails on this PR with `Could not read password for SSL key file, console is not available.` The changelog mentions this at the end of a Security entry and does not mark it as breaking. `getReference()` and serialization still carry the token and `sslpassword`, so the change does not remove the secret from the DataSource either. I suggest masking the URLs that are logged and leaving `getUrl()` as it was.
- Commit 0b6a1442e changes `requireAuth` for connections that have nothing to do with OAuth. It fixes a defect present since `requireAuth` shipped in 42.7.11 (#3895): on a GSS-encrypted connection, `requireAuth=scram-sha-256` refused a connection that had authenticated with SCRAM. The fix matches libpq's `check_expected_areq`, and I agree with it, but it deserves its own PR so it can be released without OAuth. It also has no test at the call sites: moving `setFinishedAuthenticationRequests()` back into `enableGSSEncrypted`, or removing it from the JGSS branch, passes every test.
- The SASL rework changes SCRAM parsing: `ScramAuthenticator` no longer reads the mechanism list, the list is now bounded by the message length, and there are three new `08P01` errors. That is an improvement, but it is hidden inside the `feat:` commit, and the commit message doesn't mention it.

## Surprising behavior

- The transport check is stricter than libpq, which has no transport check for OAUTHBEARER at all (`fe-auth-oauth.c` on current master). With the default `sslmode=prefer`, and with `require`, every OAuth connection fails, including over TLS. That may be the right default for a bearer token, but the docs bury it. As written, `use.md` says `prefer` fails only when the server refuses TLS.
- The check trusts the value of `sslmode`, not what happened on the socket:
  - `sslmode=verify-full&sslfactory=org.postgresql.ssl.NonValidatingFactory` sends the token to an unverified server with no warning at all. The docs mention this, but the WARNING fires only for `oauthAllowInsecureConnection=true`.
  - The Cloud SQL and AlloyDB Java connectors require `sslmode=disable` and do TLS in their `socketFactory`. The check would refuse them with `sslmode=disable does not verify it`, which is wrong for that setup.
  - Over a Unix domain socket, OAuth works only with `oauthAllowInsecureConnection=true`, and then logs a WARNING on every connection.
- RFC 7628 §3 says only `TLS MUST be used for OAUTHBEARER to protect the bearer token`. It says nothing about verifying the certificate or about GSS. Certificate validation is RFC 6750 §5.3 ("Validate TLS certificate chains"). The citation is wrong in the two error messages, in `PGProperty`, in `use.md`, and in the changelog.
- When the server offers both SCRAM-SHA-256 and OAUTHBEARER, the driver picks OAUTHBEARER in either order. libpq picks the first of the two in server order (`fe-auth.c`). No PostgreSQL server offers both in one message, because the `pg_hba.conf` rule selects one method, and `oauth_get_mechanisms` advertises only OAUTHBEARER. `use.md` and the changelog nonetheless tell users that setting `oauthToken` makes `password` unusable unless they add `requireAuth=scram-sha-256`. Please drop that paragraph or describe the real rule: the `pg_hba.conf` entry decides.
- A `+` in a token passed through the JDBC URL is decoded to a space and then refused by the format check. The token has to be written as `%2B`.
- `PgConnection.getURL()` and `DatabaseMetaData.getURL()` return the URL with `oauthToken=...` in it, and HikariCP logs `oauthToken` and `oauthClientSecret` at DEBUG, because it masks only keys that contain "password". The driver can't fix HikariCP, but the docs should steer users towards the provider instead of a token in the URL.
- Pools:
  - The driver creates a new provider instance on every connection attempt. Please document that, and say that an implementation should be a lightweight bridge to a layer that caches the token, such as a cloud SDK credential or a token file, or keep its cache in a static field keyed by everything that affects the token.
  - A static `oauthToken` works until it expires. After that, the pool can't open any new connection and never recovers. Open sessions stay up, because the server checks the token only at connect.
  
  None of this is documented.
- Setting an IAM or Entra token as `oauthToken` against RDS, Aurora, Azure, or Cloud SQL fails with `The server requested password-based authentication, but no password was provided.`, because those services take the token as a password, not through OAUTHBEARER. None of the major managed services documents server-side OAUTHBEARER today. A hint in that error, when `oauthToken` or `oauthTokenProviderClassName` is set, would save users a support ticket. Please don't fall back to sending the token as a cleartext password.

## Public API

`OAuthTokenProvider` and `OAuthTokenRequest` become public API with this PR, so please settle them before merge:
- The public four-argument `OAuthTokenRequest` constructor fixes the field set. Adding a field later means another constructor, or a breaking change. A builder, or a package-private constructor, would keep it open.
- The request has no host, port, user, or database. The provider can read `PGHOST` from its `Properties` constructor, but with a multi-host URL that is the whole list, and it can't tell which host is being tried. Tokens from cloud identity providers are usually bound to exactly those values.
- Please rename the classes to `OauthTokenProvider` and `OauthTokenRequest` as well. The code is new, so it should follow the same camel-case rule as the setters.
- `oauthToken` is a convenience that neither libpq nor pgx has: libpq takes a process-global hook (`PQsetAuthDataHook`) or runs its built-in device flow, and pgx takes only a provider function. It works for a one-off connection, such as a desktop tool where the user pastes a token, and it breaks a pool once the token expires. The PR ships no provider implementation of its own. Have you considered a small built-in provider that rereads the token from a file on each connection instead? That is how Kubernetes projected service-account tokens and cloud workload-identity agents deliver rotated tokens, and it would serve both the paste-a-token case and pools without any cache.
- `oauthIssuer`, `oauthClientId`, `oauthClientSecret`, and `oauthScope` are pass-through properties the driver never reads, yet they become public connection properties, with validation on one of them. I asked about this earlier. If they stay, the driver should at least not reject a connection over an issuer it doesn't use (bug 2).
- `AuthenticationPlugin` is not connected to OAUTHBEARER, so a plugin such as Azure's `AzurePostgresqlAuthenticationPlugin` could not serve a bearer token. If you want that bridge, it has to be opt-in (a new `AuthenticationRequestType` value the plugin declares support for), because existing plugins ignore the request type and would return a password.

## Tests

The unit tests of the static helpers are solid: branch coverage of `selectSaslMechanism`, `validateOAuthIssuer`, `checkAuthenticationCompleted`, and `OAuthAuthenticator` is 100% from the DB-free tests. Mutation testing shows what the tests don't pin down: 131 mutants, 27 survived, of which about 17 are real gaps. The ones that matter for security:

- `oauthAllowInsecureConnection` forced to `true`, or its default changed to `"true"`, passes every test, because `OAuthHandshakeTest` always sets the flag (inline comment).
- Removing `Arrays.fill(clientMessage, (byte) 0)` passes every test. Only the `char[]` wipe is tested.
- Removing `setFinishedAuthenticationRequests()` after the OAuth initial response passes every DB-free test, yet it breaks `requireAuth=oauth` for every successful login. No test runs a successful OAUTHBEARER exchange with `requireAuth` set.
- `BaseDataSource.getConnectionProperties` has 0% coverage. Dropping every credential it passes (`setOAuthToken`, `setSslPassword`, `setOAuthClientSecret`) passes every test.
- The masking in `Driver` (`Unable to parse URL`, `Connecting with URL`, the two WARNINGs about a malformed URL) and in `BaseDataSource.setUrl` can be removed without a failing test. Only the FINE record for an undecodable parameter is pinned.

Other gaps: an empty `oauthToken=` counts as configured (it makes OAuth win over SCRAM and then fail), a `PSQLException` from the provider is passed through unwrapped but untested, a second AuthenticationSASL during SCRAM is not detected by any test, and a second AuthenticationSASLContinue after the OAuth error is not tested. `OAuthHandshakeTest.refusesSaslFinalAfterTheServerRejectedTheToken` also hit its 30-second timeout once under load.

Tests to rewrite are in inline comments: `SelectSaslMechanismTest` (act after assert, better as one parameterized decision table), `ReadMechanismsTest.stopsAtTheEndOfTheMessage` (verifies a stub that can't show the stream position), and `OAuthTest` (rejections asserted only by `CONNECTION_REJECTED`, which five other failures share). Every OAuth success path in CI runs with `oauthAllowInsecureConnection=true`, so the production configuration, `sslmode=verify-full`, is never tested end to end.

Coverage reporting: `pgjdbc-mockito-test` runs against the shaded `-all.jar`, so JaCoCo gives `ConnectionFactoryImpl` and `ScramAuthenticator` different class IDs there, and the root report drops that coverage. The Codecov diff coverage for this PR is understated because of that.

## Logging

- The two `oauthAllowInsecureConnection` WARNINGs fire on every connection. A pool of 50 prints 50 two-line blocks to stderr, because pgjdbc logs through `java.util.logging`, whose default console handler prints WARNING. Log once per JVM at WARNING and at FINE afterwards, include the host, and drop the RFC citation and "Do not use this configuration in production".
- Move the server's error result into the exception and log the JSON at FINEST, like the other `<=BE` trace lines (bug 4).
- `selectSaslMechanism` makes silent decisions. It prefers OAUTHBEARER, falls back to SCRAM under `channelBinding=require`, and falls back to SCRAM when the server doesn't offer OAUTHBEARER. A user who configured OAuth then sees only a SCRAM error. One FINE record naming the offered list, the choice, and the reason would help.
- A provider exception is chained as the cause and ends up in `Connection error:` at FINE. Please add a sentence to the `getToken` Javadoc saying the exception message must not contain the token or `clientSecret`.

## Documentation

- The OAuth introduction sits between `scramMaxIterations` and `oauthToken`, without a heading. Please move it to an `### OAuth authentication` section after the property list, as with `### Unix sockets`.
- The first thing a reader needs is missing: with the default `sslmode=prefer`, OAuth fails. Set `sslmode=verify-full`, or `verify-ca`, or use GSS encryption.
- No error text a user will search for appears on the page. Quote `OAUTHBEARER authentication requires ...`, `OAuth issuer URL must use HTTPS: {0}`, `The server requested OAuth authentication, but neither oauthToken nor oauthTokenProviderClassName is configured.`, `Invalid OAuth bearer token format...`, and the server's `OAuth bearer authentication failed for user "..."`.
- `oauthTokenProviderClassName` needs its contract on the page:
  - the class needs a `Properties` constructor or a no-argument constructor;
  - the driver creates a new instance for each attempt, including each host of a multi-host URL;
  - `getToken` runs only after the server asks for OAuth and the transport check passes;
  - the call counts against `loginTimeout` and the server's `authentication_timeout`;
  - it must return a new array every time.
- `oauthToken` needs its limits: the token expires, which breaks a pool (use a provider there), the `b64token` syntax, and the `%2B` for `+` in a URL.
- A short how-to with a URL example, a provider skeleton, and a pooled setup; "Since: 42.7.14" on every new entry and on the `oauth` value of `requireAuth`; and one sentence each in `sslmode`, `gssEncMode`, `sslfactory`, and `loginTimeout`, linking to the OAuth section.
- `TESTING.md` renumbers `## 11 - Credits and Feedback` to `## 12`, which changes its anchor. Placing the new section after it keeps the old number.
- The PR description no longer matches the code. It says "Two options were added" and "TLS or GSSAPI", while the code adds eight properties, a public SPI, and the verify-ca/verify-full requirement. It also doesn't mention the `getUrl()` change, the URL masking, or the `requireAuth` fix. The link text says RFC 7632 and links to RFC 7628, and `Solves #3816` does not close the issue (use `Fixes #3816`).

## Changelog

- The Added entry is about 330 words, and cites RFC 7628 §3 for certificate verification. Please cut it to what an upgrading user needs: the two token sources, `requireAuth=oauth`, the `sslmode` requirement with the error text, and the escape hatch.
- The Security entry says "`password` was never affected". That is not true for a `password` in the JDBC URL. On master, `Driver` logs the URL verbatim at WARNING when it has too many `/` or no `/` after the host, at FINE in `Connecting with URL: {0}`, and in the `Unable to parse URL {0}` exception. `oauthToken` and `oauthClientSecret` were never released, so listing them as fixed leaks overstates the entry. The `getUrl()` change needs a `**Breaking:**` marker, or better, no break at all.
- The Fixed entry for `requireAuth` should say the defect has been present since 42.7.11, and quote the new error text, which replaces `Authentication method is not allowed by requireAuth` for a trust server.

## Commit structure

The project merges by rebase, so each commit lands in `master` as it is. The seven commits are split by artifact type (feat, test, ci, docs, changelog), not by behavior:
- the feat commit has no docs or changelog, and they arrive four commits later;
- the changelog of `aa239e0f9` sits in a separate `docs:` commit;
- the two fixes of released code come last and depend on OAuth identifiers (`OAUTH_TOKEN`, `AuthMethod.OAUTH`), so neither can ship without the feature.

I suggest:

1. A separate PR for the `requireAuth` and GSS fix, based on `master`, with `CheckAuthenticationCompletedTest` minus the `OAUTH` row.
2. A separate PR for masking credentials in logged URLs and in the `Unable to parse URL` message, with `password` and `sslpassword` as the sensitive set, and without the `getUrl()` change.
3. This PR, rebased on both, as four commits:
   - `refactor(core): read the SASL mechanism list by the message's declared length`;
   - `feat(core): add OAUTHBEARER authentication for PostgreSQL 18`, with its unit tests, docs, changelog entry, and `Fixes #3816`;
   - `test: run OAuth integration tests against PostgreSQL 18 and Keycloak`, with the `smoke` CI axis;
   - `test: add a CI mode that authenticates the whole suite through OAUTHBEARER`, with the `all` axis and the `assumeNotOAuthMode` changes.

Each commit body should name the problem and carry `Caller sees:` lines for the new error texts.

I'm happy to help split the fixes out if you'd like.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-09-23 09:17  "ImTheKai (@ImTheKai)" <noreply+ImTheKai@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: ImTheKai (@ImTheKai) @ 2026-09-23 09:17 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

@vlsi Just out of curiosity and being able to address things better and quicker, which LLM are you using and how, can you share more about it? It feels like LLM constantly finds new things, based on whatever was done, which is a little bit frustrating. Is there a way you think we can do better?

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-13 10:07  "ImTheKai (@ImTheKai)" <noreply+ImTheKai@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: ImTheKai (@ImTheKai) @ 2026-10-13 10:07 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

@vlsi Any feedback on my previous ask? I would be great to know how we can move forward in the best way possible, without each new LLM model finding more and more. I'm really serious here, as we would love to help and work on it, but how exactly are you testing and what is needed to finally move this across the finish line?

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-14 23:27  "mlbiam (@mlbiam)" <noreply+mlbiam@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: mlbiam (@mlbiam) @ 2026-10-14 23:27 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

So using this PR i've got a Java app running in Kubernetes that is talking to a remote PostgreSQL with a token exchange sidecar.  Writing up a blog post but this works really well with no client secrets or passwords.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-22 19:55  "mlbiam (@mlbiam)" <noreply+mlbiam@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: mlbiam (@mlbiam) @ 2026-10-22 19:55 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

here's the blog post - https://www.tremolo.io/post/postgresql-as-a-service-without-passwords i'll promote next week.  great PR! 

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-23 04:48  "davecramer (@davecramer)" <noreply+davecramer@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: davecramer (@davecramer) @ 2026-10-23 04:48 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

 @artemgavrilov @ImTheKai sorry for the slow answer. I want to get this merged, and I agree that it needs a list that stops growing. Here is what I think has to change before
  merge. Everything else in vlsi's review can be a follow-up issue.

  Before merge:

  1. Rebase on master. It conflicts with the requireAuth change in AuthMethod.java.
  2. Fix readMechanisms so the list ends at the first empty name, as libpq does.
  3. Leave BaseDataSource.getUrl() as it is. Mask the URL where it is logged, but don't drop sslpassword from getUrl().
  4. Rename the setters and getters to setOauthToken, getOauthToken, and so on, and the classes to OauthTokenProvider and OauthTokenRequest, so HikariCP's dataSource.oauthToken
     works. This is public API, so it has to be right before the release.
  5. Settle OauthTokenRequest before it ships: no public constructor that fixes the fields, and add host, port, user and database so a provider can tell which server it is
     connecting to.
  6. Drop oauthIssuer, oauthClientId, oauthClientSecret and oauthScope for now. The driver doesn't use them, and the issuer check blocks connections that don't use OAuth. They
     can come back with the discovery PR.
  7. Put the server's error result in the exception instead of logging it at WARNING.
  8. Move the requireAuth and GSS fix to its own PR, so we can release it without OAuth.
  9. Add tests that the default oauthAllowInsecureConnection=false refuses an insecure connection, and that a successful OAuth login works with requireAuth=oauth.
  10. Fix the RFC citation: RFC 7628 §3 requires TLS but says nothing about verifying the certificate.

  Follow-ups, after merge: the logging volume, the doc restructure, the remaining test rewrites, a file-based token provider, the AuthenticationPlugin bridge, and the hint for
  managed services that take the token as a password.

  On the LLM question: we do use models to help review, and they keep finding new things. That is why I'm fixing the list here instead of asking for another round.


^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-23 05:06  "davecramer (@davecramer)" <noreply+davecramer@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: davecramer (@davecramer) @ 2026-10-23 05:06 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

@davecramer closed this.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-23 05:06  "davecramer (@davecramer)" <noreply+davecramer@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: davecramer (@davecramer) @ 2026-10-23 05:06 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

closing to kick off CI

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-23 05:06  "davecramer (@davecramer)" <noreply+davecramer@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: davecramer (@davecramer) @ 2026-10-23 05:06 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

@davecramer reopened this.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-23 06:03  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-10-23 06:03 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

> Everything else in vlsi's review can be a follow-up issue.

Dave, OAuth relates to security, and merging code that violates RFCs and so on can easily result in CVEs.

>That is why I'm fixing the list here instead of asking for another round.

As you might know, PostgreSQL team decided to postpone PostgreSQL release after LLMs surfaced issues in human-merged changes.

LLM finding new stuff does not mean it will always new stuff. It will converge as defects get fixed.

If you do not want fixing the issues, I can help with that.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-23 08:53  "davecramer (@davecramer)" <noreply+davecramer@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: davecramer (@davecramer) @ 2026-10-23 08:53 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

@vlsi what I meant is that deal with this first and we will discuss the rest of the issues next
Not a new PR

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-23 08:55  "vlsi (@vlsi)" <noreply+vlsi@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: vlsi (@vlsi) @ 2026-10-23 08:55 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Could you rephrase?
I fully agree that side quests like `requireAuth and GSS fix` should better be in their separate PRs.
However, I think we should merge OAuth only if we are sure the implementation is secure.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-23 08:58  "davecramer (@davecramer)" <noreply+davecramer@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: davecramer (@davecramer) @ 2026-10-23 08:58 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

I agree we need to make sure this is secure before merging.
My statement was that the author has to rebase before we can continue reviewing

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-23 10:49  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-10-23 10:49 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Thanks for response @davecramer ! I hope to continue with this PR next week.

@vlsi I agree that LLMs help to find issues and build better software, on other hand every PR update touches more existing code and that causes more and more LLM feedback. I'm afraid that I'll stuck with evergrowing scope. Can we somehow limit or split review comments in way what is must-have right in this PR and what can be done in the following ones? Also I would appreciate if you'll share your review prompts/LLMs that you're using. Because my last iteration I checked with Fable and it was fine.

Thank you!

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-23 17:25  "davecramer (@davecramer)" <noreply+davecramer@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: davecramer (@davecramer) @ 2026-10-23 17:25 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Hi @artemgavrilov hopefully you can rebase it and I will kick off CI, then we can look at the review again

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-23 19:17  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-10-23 19:17 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Sure @davecramer , done!

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-29 16:04  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-10-29 16:04 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Hey @davecramer @vlsi , I started to split this PR. Here is first fix that can be merged independently from OAuth implementation: https://github.com/pgjdbc/pgjdbc/pull/4512

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-10-31 14:42  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-10-31 14:42 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

And here is `requireAuth` fix: https://github.com/pgjdbc/pgjdbc/pull/4513

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-11-09 16:32  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-11-09 16:32 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

Pushed update, it sits on top of https://github.com/pgjdbc/pgjdbc/pull/4512 and https://github.com/pgjdbc/pgjdbc/pull/4513

I haven't pined pg_oidc_validator version because it's nightly builds, I'm still waiting for https://github.com/pgdg-packaging/apt.postgresql.org-issues/issues/2 . Will appreciate upvote there. 

Also I haven't put `since <version>` comments anywhere, because target version for this PR is unknown.

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-11-09 16:32  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-11-09 16:32 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

Fixed

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-11-09 16:33  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-11-09 16:33 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

(on pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java)

Done

^ permalink  raw  [nested|flat] 168+ messages in thread

* Re: [pgjdbc/pgjdbc] PR #4251: OAuth implementation
@ 2026-11-09 16:36  "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
  166 siblings, 0 replies; 168+ messages in thread

From: artemgavrilov (@artemgavrilov) @ 2026-11-09 16:36 UTC (permalink / raw)
  To: pgjdbc/pgjdbc <noreply+pgjdbc-pgjdbc@github.com>

@artemgavrilov requested a review.

^ permalink  raw  [nested|flat] 168+ messages in thread


end of thread, other threads:[~2026-11-09 16:36 UTC | newest]

Thread overview: 168+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-06-24 16:56 [pgjdbc/pgjdbc] PR #4251: OAuth implementation "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-06-24 17:04 ` "davecramer (@davecramer)" <noreply+davecramer@github.com>
2026-06-24 17:49 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-06-25 10:24 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-06-25 10:38 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-06-25 10:46 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-06-25 11:20 ` "davecramer (@davecramer)" <noreply+davecramer@github.com>
2026-06-25 11:36 ` "davecramer (@davecramer)" <noreply+davecramer@github.com>
2026-06-25 11:40 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-06-25 11:41 ` "codecov[bot] (bot) (@codecov[bot])" <noreply+codecov[bot]@github.com>
2026-06-25 12:19 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-05 23:11 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-14 09:05 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-14 09:17 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-14 09:19 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-14 09:20 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-14 09:31 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-14 09:31 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-14 09:40 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-14 09:47 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-14 09:49 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-14 09:50 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-14 09:54 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-14 10:14 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-14 10:18 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-14 10:18 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-14 13:03 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-14 13:06 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-14 13:48 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-17 12:48 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-17 12:48 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-17 12:48 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-17 12:49 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-17 12:50 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-17 12:50 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-17 12:53 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-17 12:58 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-17 13:05 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-17 13:22 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-20 20:53 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-07-28 15:16 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-07-28 16:41 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-08-08 11:14 ` "Abdel-Monaam-Aouini (@Abdel-Monaam-Aouini)" <noreply+Abdel-Monaam-Aouini@github.com>
2026-08-08 12:23 ` "davecramer (@davecramer)" <noreply+davecramer@github.com>
2026-08-12 20:34 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-08-31 17:26 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-08-31 18:54 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-01 14:19 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-09 14:35 ` "jamalfundatament (@jamalfundatament)" <noreply+jamalfundatament@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:45 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-09 15:50 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-12 16:22 ` Re: [pgjdbc/pgjdbc] PR #4251 (changes requested): OAuth implementation "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-22 18:50 ` "gitguardian[bot] (bot) (@gitguardian[bot])" <noreply+gitguardian[bot]@github.com>
2026-09-22 18:51 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 18:53 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 18:55 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 18:56 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 18:58 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:01 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:01 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:01 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:02 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:03 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:03 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:04 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:04 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:05 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:05 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:06 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:08 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:08 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:09 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:10 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:10 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:11 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:12 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:13 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:15 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:15 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:17 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-22 19:18 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:43 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 06:47 ` Re: [pgjdbc/pgjdbc] PR #4251 (changes requested): OAuth implementation "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-09-23 09:17 ` "ImTheKai (@ImTheKai)" <noreply+ImTheKai@github.com>
2026-10-13 10:07 ` "ImTheKai (@ImTheKai)" <noreply+ImTheKai@github.com>
2026-10-14 23:27 ` "mlbiam (@mlbiam)" <noreply+mlbiam@github.com>
2026-10-22 19:55 ` "mlbiam (@mlbiam)" <noreply+mlbiam@github.com>
2026-10-23 04:48 ` "davecramer (@davecramer)" <noreply+davecramer@github.com>
2026-10-23 05:06 ` "davecramer (@davecramer)" <noreply+davecramer@github.com>
2026-10-23 05:06 ` "davecramer (@davecramer)" <noreply+davecramer@github.com>
2026-10-23 05:06 ` "davecramer (@davecramer)" <noreply+davecramer@github.com>
2026-10-23 06:03 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-10-23 08:53 ` "davecramer (@davecramer)" <noreply+davecramer@github.com>
2026-10-23 08:55 ` "vlsi (@vlsi)" <noreply+vlsi@github.com>
2026-10-23 08:58 ` "davecramer (@davecramer)" <noreply+davecramer@github.com>
2026-10-23 10:49 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-10-23 17:25 ` "davecramer (@davecramer)" <noreply+davecramer@github.com>
2026-10-23 19:17 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-10-29 16:04 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-10-31 14:42 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-11-09 16:32 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-11-09 16:32 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-11-09 16:33 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>
2026-11-09 16:36 ` "artemgavrilov (@artemgavrilov)" <noreply+artemgavrilov@github.com>

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