diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 82cbc6ed..42521eb4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -130,6 +130,14 @@ jobs: cache: maven - name: Integration tests (Testcontainers) run: ./mvnw -B -ntp verify -Pintegration-tests -Dpg.it.image=postgres:${{ matrix.pg }} + # VirtualThreadPinningIT keeps its JFR recording under target/jfr only when it fails. + - name: Upload pinning JFR recording + if: failure() + uses: actions/upload-artifact@v4 + with: + name: pinning-jfr-postgres-${{ matrix.pg }} + path: postgresql-client/target/jfr/*.jfr + if-no-files-found: ignore # One integration leg on the current LTS. The server matrix above sweeps PostgreSQL # versions on the JDK floor; this sweeps the other axis once, so JDK-dependent @@ -150,6 +158,13 @@ jobs: cache: maven - name: Integration tests (Testcontainers) run: ./mvnw -B -ntp verify -Pintegration-tests -Dpg.it.image=postgres:17 + - name: Upload pinning JFR recording + if: failure() + uses: actions/upload-artifact@v4 + with: + name: pinning-jfr-jdk25 + path: postgresql-client/target/jfr/*.jfr + if-no-files-found: ignore # Protocol 3.2 (PG18) is a distinct negotiation path -- StartupMessage requests 3.2, # the server may answer NegotiateProtocolVersion, and the cancellation key becomes @@ -172,3 +187,10 @@ jobs: ./mvnw -B -ntp verify -Pintegration-tests -Dpg.it.image=postgres:18 -Dpg.it.protocolVersion=latest + - name: Upload pinning JFR recording + if: failure() + uses: actions/upload-artifact@v4 + with: + name: pinning-jfr-protocol-3-2 + path: postgresql-client/target/jfr/*.jfr + if-no-files-found: ignore diff --git a/docs/adr/ADR-0014-batch-array-rewrite.md b/docs/adr/ADR-0014-batch-array-rewrite.md index 0aff7802..afe68768 100644 --- a/docs/adr/ADR-0014-batch-array-rewrite.md +++ b/docs/adr/ADR-0014-batch-array-rewrite.md @@ -89,7 +89,9 @@ lookup), unless rewriters pin element types via casts. - unset / `off` / `false` / `no` / `0` -- disabled (**default**); - `on` / `yes` / `true` / `1` / `latest` / `default` -- the latest built-in rewriter; - any other token -- a pinned built-in version/id, or a fully-qualified class name of - a custom `BatchArrayRewriter`. + a custom `BatchArrayRewriter`. A class name is accepted only from the connection + `Properties`; one in the URL query fails the connection, as for + `authenticationPluginClassName` (N2.9), because a class name is code to run. The default binding for "on" pins to a **fixed** built-in version, not "whatever is latest at runtime": a driver upgrade must never silently start rewriting a statement diff --git a/docs/adr/ADR-0016-batch-multi-values-rewrite.md b/docs/adr/ADR-0016-batch-multi-values-rewrite.md index 66e5fd89..49a38be4 100644 --- a/docs/adr/ADR-0016-batch-multi-values-rewrite.md +++ b/docs/adr/ADR-0016-batch-multi-values-rewrite.md @@ -57,6 +57,8 @@ compat layer's `reWriteBatchedInserts` translation onto it. rewriter, pinned to a **fixed** version so a driver upgrade never silently changes which statements are rewritten; - any other token -- a pinned built-in version/id, or a fully-qualified custom class name. + As for `rewriteBatchUsingArrays`, a class name is accepted only from the connection + `Properties`, never from the URL query. Like `rewriteBatchUsingArrays`, it is a JDBC-only knob: `PgDriver` reads and strips it before building the core config, so the core parser never sees it as a bogus server diff --git a/docs/follow-up.md b/docs/follow-up.md index 0deca51b..868feed8 100644 --- a/docs/follow-up.md +++ b/docs/follow-up.md @@ -638,7 +638,9 @@ surfaced two mapping-table inconsistencies in - **`logServerErrorDetail` is implemented but classified `unsupported`.** The behavior ships (`ServerErrorRedaction`, wired via `Driver.vendorSettings()` and consulted in `CompatStatements`), yet the mapping entry still emits a - misleading "not supported" WARN on every use. Reclassify it as mapped. + misleading "not supported" WARN on every use. **RESOLVED (2026-10-23):** + reclassified as emulated (6cebef72) -- not mapped, since forwarding it would + send it to the server as a startup parameter. - **`sslcrl` is warn-dropped though core accepts it.** Core's `ConnectionStringParser` and `SslMaterials` handle a CRL file, but `PgPropertyMappings` has no entry, so the property falls into the diff --git a/docs/life-of-a-query.md b/docs/life-of-a-query.md index d55a340c..690813d5 100644 --- a/docs/life-of-a-query.md +++ b/docs/life-of-a-query.md @@ -114,7 +114,8 @@ never buffers. The buffering is a JDBC-layer policy applied on top of it. `CoreConnection.execute(String)` is the native entry point: ```java -requireOpen(); requireIdle(); requireUsableTransaction(); // connection-busy contract (ADR-0005) +requireOpen(); requireIdle(); // connection-busy contract (ADR-0005) +recoverAutosave(); // autosave=always: undo a failed statement invalidateCachesForSessionCommand(sql); // SET search_path / DISCARD / DEALLOCATE ALL ensureTransactionOpen(); // lazy BEGIN when autocommit is off return sendArmed(disarm -> { // arms the query timeout, un-busies on a failed send diff --git a/docs/plans/pgjdbc-wrapper.md b/docs/plans/pgjdbc-wrapper.md index 979823ad..a7031647 100644 --- a/docs/plans/pgjdbc-wrapper.md +++ b/docs/plans/pgjdbc-wrapper.md @@ -99,9 +99,10 @@ Three sinks for a translated property, in order of preference: `PgConnectionConfig.Builder` programmatically. **Decision:** add the missing parser keys to core (one commit, W-A0) so both drivers gain them and the shim stays string-based. -3. **Shim-side emulation** (`currentSchema` -> `options=-c search_path=...`, - `readOnly` -> post-connect `SET`/`Connection.setReadOnly`, `tcpKeepAlive` -> - core socket option): handled in the compat layer or a small core knob. +3. **Shim-side emulation** (`readOnly` -> post-connect `SET`/`Connection.setReadOnly`, + `tcpKeepAlive` -> core socket option): handled in the compat layer or a small + core knob. `currentSchema` started here too, folded into `options`; it is now a + plain mapping to a `search_path` startup parameter (see 3.3). ### 3.3 Unknown / unsupported property policy (replaces silent drop) @@ -187,9 +188,10 @@ The 80% of real-world configs. Land these first after A0/A1. - [x] `sslnegotiation` -> `sslnegotiation` (MAP): `postgres|direct`, identical. - [x] `sslrootcert`/`sslcert`/`sslkey`/`sslpassword`/`sslcrl` already (MAP); add `sslmode` aliasing of pgjdbc-only nuance where `ssl=true` implies verify-full. *(2026-07-28: partial -- sslcrl absent from PgPropertyMappings, warn-dropped though core accepts it)* -- [x] `currentSchema` -> EMULATE: fold into `options=-c search_path=` (merge - with any existing options) (SHIM). Consider a first-class `search_path` core - knob later. +- [x] `currentSchema` -> MAP to a `search_path` startup parameter, as pgjdbc sends + it. It was first folded into `options=-c search_path=`, which the server + splits on whitespace, so the value could carry further `-c` settings and + `app, public` was rejected. - [x] `readOnly` + `readOnlyMode` -> EMULATE: set JDBC read-only / issue `SET default_transaction_read_only`; map `readOnlyMode=always|ignore|transaction` semantics (SHIM/CORE). *(2026-07-28: partial -- readOnlyMode unsupported, no always/ignore/transaction semantics)* diff --git a/pom.xml b/pom.xml index e982d31e..c8acabeb 100644 --- a/pom.xml +++ b/pom.xml @@ -394,9 +394,13 @@ + @{argLine} preserves the JaCoCo integration agent's argLine. + The JFR stack depth (default 64) is a JVM-startup option the + Recording API cannot set; 128 frames keeps the pinning IT's + failure report from cutting off above the driver frames. --> @{argLine} --add-modules jdk.jfr - --add-reads org.postgresql.client.core=jdk.jfr + --add-reads org.postgresql.client.core=jdk.jfr + -XX:FlightRecorderOptions=stackdepth=128 diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java new file mode 100644 index 00000000..e8320b00 --- /dev/null +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CallArguments.java @@ -0,0 +1,133 @@ +package org.postgresql.client.jdbc; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import org.postgresql.client.jdbc.sql.SqlLexing; + +/** + * Rebuilds the argument list of a {@code {call f(...)}} escape for the native call, keeping every + * argument as written. A bare {@code ?} is a parameter, which may be OUT-only; any other argument + * is an expression (a literal such as the {@code 1} in {@code f(?, 1)}, or {@code ? + 1}) whose + * {@code ?} placeholders are IN parameters. Placeholders are numbered left to right as JDBC + * numbers them, and renumbered {@code $1..$n} over the values actually sent. + */ +final class CallArguments { + + private CallArguments() {} + + /** + * The native argument list (without parentheses), appending the value for each {@code $n} to + * {@code values}. An unbound OUT-only parameter is dropped under {@code SELECT}, which does not + * take OUT arguments, and sent as NULL under {@code CALL}, which needs one per parameter. + */ + static String rebuild( + String argumentText, + boolean callMode, + Set outParameters, + boolean[] bound, + Object[] parameters, + List values) + throws SQLException { + List out = new ArrayList<>(); + int placeholder = 0; + for (String argument : split(argumentText)) { + String trimmed = strip(argument); + if (trimmed.equals("?")) { + placeholder++; + if (!bound[placeholder - 1] && outParameters.contains(placeholder)) { + if (!callMode) { + continue; + } + values.add(null); + } else { + values.add(requireBound(placeholder, bound, parameters)); + } + out.add("$" + values.size()); + continue; + } + StringBuilder expression = new StringBuilder(); + int end = trimmed.length(); + int i = 0; + while (i < end) { + char c = trimmed.charAt(i); + int next = SqlLexing.skipLexeme(trimmed, i, end); + if (next > i) { + expression.append(trimmed, i, next); + i = next; + } else if (c == '?' && i + 1 < end && trimmed.charAt(i + 1) == '?') { + expression.append('?'); // ?? is an escaped literal question mark, as in SqlParser + i += 2; + } else if (c == '?') { + placeholder++; + values.add(requireBound(placeholder, bound, parameters)); + expression.append('$').append(values.size()); + i++; + } else { + expression.append(c); + i++; + } + } + out.add(expression.toString()); + } + return String.join(", ", out); + } + + /** + * The argument without surrounding whitespace, except that one ending in a {@code --} comment + * keeps a newline: the arguments are rejoined on one line, where the comment would otherwise run + * on over whatever follows. + */ + static String strip(String argument) { + String stripped = argument.strip(); + int end = stripped.length(); + int i = 0; + while (i < end) { + int next = SqlLexing.skipLexeme(stripped, i, end); + if (next == end && stripped.startsWith("--", i)) { + return stripped + "\n"; + } + i = next > i ? next : i + 1; + } + return stripped; + } + + private static Object requireBound(int placeholder, boolean[] bound, Object[] parameters) throws SQLException { + if (placeholder > bound.length || !bound[placeholder - 1]) { + throw new SQLException("parameter " + placeholder + " is not set"); + } + return parameters[placeholder - 1]; + } + + /** Splits the argument list at commas outside quotes, comments, parentheses and brackets. */ + static List split(String text) { + List arguments = new ArrayList<>(); + if (text.isBlank()) { + return arguments; + } + int depth = 0; + int start = 0; + int end = text.length(); + int i = 0; + while (i < end) { + int next = SqlLexing.skipLexeme(text, i, end); + if (next > i) { + i = next; + continue; + } + char c = text.charAt(i); + if (c == '(' || c == '[') { + depth++; + } else if (c == ')' || c == ']') { + depth--; + } else if (c == ',' && depth == 0) { + arguments.add(text.substring(start, i)); + start = i + 1; + } + i++; + } + arguments.add(text.substring(start)); + return arguments; + } +} diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CatalogLookups.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CatalogLookups.java index 8904fed6..9fc82fc6 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CatalogLookups.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/CatalogLookups.java @@ -40,7 +40,7 @@ static SourceColumn sourceColumn(Connection connection, int tableOid, int attrib + " OR COALESCE(pg_catalog.pg_get_expr(d.adbin, d.adrelid), '') LIKE 'nextval(%'" + " FROM pg_catalog.pg_attribute a" + " LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum" - + " WHERE a.attrelid = ? AND a.attnum = ?"; + + " WHERE a.attrelid OPERATOR(pg_catalog.=) ? AND a.attnum = ?"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, tableOid); ps.setInt(2, attributeNumber); @@ -72,7 +72,7 @@ record CatalogType(String name, char typtype, boolean isArray, int elementOid, c static CatalogType catalogType(Connection connection, int typeOid) throws SQLException { String sql = "SELECT t.typname, t.typtype, t.typcategory, t.typelem," + " COALESCE(e.typdelim, ',') FROM pg_catalog.pg_type t" - + " LEFT JOIN pg_catalog.pg_type e ON e.oid = t.typelem WHERE t.oid = ?"; + + " LEFT JOIN pg_catalog.pg_type e ON e.oid = t.typelem WHERE t.oid OPERATOR(pg_catalog.=) ?"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, typeOid); try (ResultSet rs = ps.executeQuery()) { @@ -98,7 +98,7 @@ static CatalogType catalogType(Connection connection, int typeOid) throws SQLExc */ static String[] tableName(Connection connection, int tableOid) throws SQLException { String sql = "SELECT n.nspname, c.relname FROM pg_catalog.pg_class c" - + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.oid = ?"; + + " JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.oid OPERATOR(pg_catalog.=) ?"; try (PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, tableOid); try (ResultSet rs = ps.executeQuery()) { diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgCallableStatement.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgCallableStatement.java index c6ec8c81..d37f1c52 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgCallableStatement.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgCallableStatement.java @@ -47,6 +47,9 @@ public final class PgCallableStatement extends PgPreparedStatement implements CallableStatement { private final String routineName; + /** The call's argument list as written, between its parentheses ({@code ""} when it has none). */ + private final String argumentText; + private final boolean returnForm; /** Whether this call is translated to {@code CALL} rather than {@code SELECT} (N3.9). */ private final boolean useCall; @@ -62,6 +65,7 @@ public final class PgCallableStatement extends PgPreparedStatement implements Ca throws SQLException { super(connection, sql, resultSetType, resultSetConcurrency, java.sql.Statement.NO_GENERATED_KEYS, null); this.routineName = parseRoutineName(sql); + this.argumentText = routineName != null ? parseArgumentText(sql) : ""; this.returnForm = routineName != null && isReturnForm(sql); this.useCall = routineName != null && connection.config().escapeSyntaxCallMode().usesCall(returnForm); @@ -117,6 +121,17 @@ private static String parseRoutineName(String jdbcSql) { return name.isEmpty() ? null : name; } + /** The text between the parentheses after the routine name, or {@code ""} when there are none. */ + private static String parseArgumentText(String jdbcSql) { + String s = jdbcSql.strip(); + if (s.startsWith("{") && s.endsWith("}")) { + s = s.substring(1, s.length() - 1).strip(); + } + int open = s.indexOf('('); + int close = s.lastIndexOf(')'); + return open >= 0 && close > open ? s.substring(open + 1, close) : ""; + } + /** * Executes a routine call for its effects. A call always comes back as a result row -- that is * how PostgreSQL returns OUT values -- so the inherited rule that a result set means the caller @@ -149,10 +164,10 @@ public boolean execute() throws SQLException { if (routineName == null) { return super.execute(); // passthrough: all placeholders are IN } - List args = useCall ? callProcedureArguments() : inArguments(); - String sql = useCall - ? "CALL " + routineName + "(" + placeholders(args.size()) + ")" - : "SELECT * FROM " + routineName + "(" + placeholders(args.size()) + ")"; + List args = new ArrayList<>(); + String argumentList = + CallArguments.rebuild(argumentText, useCall, placeholderOutParameters(), bound, parameters, args); + String sql = (useCall ? "CALL " : "SELECT * FROM ") + routineName + "(" + argumentList + ")"; applyQueryTimeout(); int callerFetchSize = getFetchSize(); try { @@ -168,6 +183,7 @@ public boolean execute() throws SQLException { throw PgSqlExceptions.wrap(e); } finally { setFetchSize(callerFetchSize); + clearQueryTimeout(); } } @@ -190,38 +206,6 @@ private void captureRefCursors() throws SQLException { } } - /** The call argument values in order: IN and INOUT parameters; OUT-only parameters skipped. */ - private List inArguments() throws SQLException { - return callArguments(parameterCount, placeholderOutParameters(), bound, parameters); - } - - /** - * The {@code CALL} argument values: every parameter in order, an unbound OUT parameter as NULL. - * {@code CALL} requires an argument for each of the procedure's parameters, OUT ones included, - * but does not evaluate the OUT arguments -- so NULL is the conventional filler, and it is what - * lets the server resolve the procedure by arity. An OUT parameter that was also bound is INOUT - * and sends its input value. - */ - private List callProcedureArguments() throws SQLException { - return procedureArguments(parameterCount, placeholderOutParameters(), bound, parameters); - } - - /** @see #callProcedureArguments() */ - static List procedureArguments( - int parameterCount, Set outParameters, boolean[] bound, Object[] parameters) throws SQLException { - List args = new ArrayList<>(parameterCount); - for (int i = 1; i <= parameterCount; i++) { - if (bound[i - 1]) { - args.add(parameters[i - 1]); - } else if (outParameters.contains(i)) { - args.add(null); - } else { - throw new SQLException("parameter " + i + " is not set"); - } - } - return args; - } - /** * The registered OUT indices translated to placeholder space. Identity except in the return * form, where JDBC index 1 (the return) has no placeholder and later indices shift down by one. @@ -239,37 +223,6 @@ private Set placeholderOutParameters() { return shifted; } - /** - * Selects the argument values the routine call sends. A registered OUT parameter that was never - * bound is OUT-only and not part of PostgreSQL's call signature; a registered parameter that was - * also bound is INOUT, and its input value must be sent as an argument. - */ - static List callArguments( - int parameterCount, Set outParameters, boolean[] bound, Object[] parameters) throws SQLException { - List args = new ArrayList<>(); - for (int i = 1; i <= parameterCount; i++) { - if (outParameters.contains(i) && !bound[i - 1]) { - continue; - } - if (!bound[i - 1]) { - throw new SQLException("parameter " + i + " is not set"); - } - args.add(parameters[i - 1]); - } - return args; - } - - private static String placeholders(int count) { - StringBuilder out = new StringBuilder(); - for (int i = 1; i <= count; i++) { - if (i > 1) { - out.append(", "); - } - out.append('$').append(i); - } - return out.toString(); - } - /** Positions the result cursor at the single output row on first access. */ private PgResultSet outRow() throws SQLException { if (!outRowLoaded) { diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgConnection.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgConnection.java index 337c4208..d815b906 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgConnection.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgConnection.java @@ -534,7 +534,7 @@ public void setSchema(String schema) throws SQLException { @Override public String getSchema() throws SQLException { checkOpen(); - try (PgResultStream stream = core.execute("select current_schema()")) { + try (PgResultStream stream = core.execute("select pg_catalog.current_schema()")) { return stream.next() ? stream.currentRow().getString(1) : null; } catch (RuntimeException e) { throw PgSqlExceptions.wrap(e); diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDatabaseMetaData.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDatabaseMetaData.java index b29967e3..d5515a70 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDatabaseMetaData.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDatabaseMetaData.java @@ -895,10 +895,13 @@ private String catalogName() { @Override public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException { + // Operators with no exact pg_catalog match for their argument types (name LIKE varchar, + // oid = int4, ...) are written OPERATOR(pg_catalog.op): otherwise an exact match from any + // search_path schema would win. String sql = "SELECT n.nspname AS schem, c.relname AS name, c.relkind AS kind, " + "pg_catalog.obj_description(c.oid, 'pg_class') AS remarks " + "FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " - + "WHERE c.relkind IN ('r','p','v','m','f','i','I','S','c') AND n.nspname LIKE ? AND c.relname LIKE ? " + + "WHERE c.relkind IN ('r','p','v','m','f','i','I','S','c') AND n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.~~) ? " + "ORDER BY c.relkind, n.nspname, c.relname"; List wanted = types == null ? null : List.of(types); List rows = new ArrayList<>(); @@ -943,11 +946,12 @@ public ResultSet getTables(String catalog, String schemaPattern, String tableNam * the SYSTEM/TEMPORARY variants ({@code pg_catalog}/{@code information_schema} are system, * {@code pg_toast} is toast, {@code pg_temp_*} are temporary). */ - private static String tableType(String relkind, String schema) { + static String tableType(String relkind, String schema) { boolean system = "pg_catalog".equals(schema) || "information_schema".equals(schema); boolean toast = schema != null && schema.startsWith("pg_toast"); boolean temp = schema != null && schema.startsWith("pg_temp_"); return switch (relkind) { + case null -> "TABLE"; case "r" -> toast ? "SYSTEM TOAST TABLE" : system ? "SYSTEM TABLE" : temp ? "TEMPORARY TABLE" : "TABLE"; case "p" -> temp ? "TEMPORARY TABLE" : "PARTITIONED TABLE"; case "v" -> system ? "SYSTEM VIEW" : temp ? "TEMPORARY VIEW" : "VIEW"; @@ -971,7 +975,7 @@ public ResultSet getColumns(String catalog, String schemaPattern, String tableNa String identityExpr = major >= 10 ? "a.attidentity" : "''"; String generatedExpr = major >= 12 ? "a.attgenerated" : "''"; String sql = "SELECT n.nspname AS schem, c.relname AS tbl, a.attname AS col, a.atttypid AS typid, " - + "row_number() OVER (PARTITION BY c.oid ORDER BY a.attnum) AS ord, " + + "pg_catalog.row_number() OVER (PARTITION BY c.oid ORDER BY a.attnum) AS ord, " + "a.attnotnull AS notnull, a.atttypmod AS typmod, " + "t.typtype AS typtype, t.typbasetype AS basetype, t.typtypmod AS domtypmod, " + "t.typnotnull AS domnotnull, " @@ -984,13 +988,13 @@ public ResultSet getColumns(String catalog, String schemaPattern, String tableNa + "JOIN pg_catalog.pg_type t ON t.oid = a.atttypid " + "LEFT JOIN pg_catalog.pg_attrdef ad ON ad.adrelid = c.oid AND ad.adnum = a.attnum " + "WHERE a.attnum > 0 AND NOT a.attisdropped AND c.relkind IN ('r','p','v','m','f') " - + "AND n.nspname LIKE ? AND c.relname LIKE ? " + + "AND n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.~~) ? " + "ORDER BY n.nspname, c.relname, a.attnum"; // ORDINAL_POSITION renumbers over the table's live columns; the column-name filter must // not affect it, so it applies outside the window (getColumns(..., "quest") still reports // the column's real ordinal). sql = "SELECT * FROM (" + sql.replace(" ORDER BY n.nspname, c.relname, a.attnum", "") + ") cols " - + "WHERE cols.col LIKE ? ORDER BY cols.schem, cols.tbl, cols.ord"; + + "WHERE cols.col OPERATOR(pg_catalog.~~) ? ORDER BY cols.schem, cols.tbl, cols.ord"; List rows = !catalogSelects(catalog) ? List.of() : query( @@ -1123,7 +1127,7 @@ public ResultSet getSchemas() throws SQLException { @Override public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException { String sql = "SELECT nspname AS schem FROM pg_catalog.pg_namespace " - + "WHERE nspname LIKE ? AND nspname NOT LIKE 'pg\\_toast%' AND nspname NOT LIKE 'pg\\_temp%' " + + "WHERE nspname OPERATOR(pg_catalog.~~) ? AND nspname OPERATOR(pg_catalog.!~~) 'pg\\_toast%' AND nspname OPERATOR(pg_catalog.!~~) 'pg\\_temp%' " + "ORDER BY nspname"; List rows = !catalogSelects(catalog) ? List.of() @@ -1211,7 +1215,7 @@ public ResultSet getPrimaryKeys(String catalog, String schema, String table) thr + "JOIN pg_catalog.pg_class ci ON ci.oid = ix.indexrelid " + "JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " + "JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attnum = " + INDKEY_ATTNUM + " " - + "WHERE ix.indisprimary AND n.nspname LIKE ? AND c.relname = ? " + + "WHERE ix.indisprimary AND n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.=) ? " + keyOnly + "ORDER BY a.attname"; List rows = !catalogSelects(catalog) @@ -1230,7 +1234,7 @@ public ResultSet getPrimaryKeys(String catalog, String schema, String table) thr @Override public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { return foreignKeys( - "fc.relname = ? AND fn.nspname LIKE ?", + "fc.relname OPERATOR(pg_catalog.=) ? AND fn.nspname OPERATOR(pg_catalog.~~) ?", List.of(nullToEmpty(table), pattern(schema)), // The constraint name before the ordinal keeps multiple foreign keys to the same // parent contiguous (KEY_SEQ restarts per FK_NAME), as pgjdbc orders them. @@ -1240,7 +1244,7 @@ public ResultSet getImportedKeys(String catalog, String schema, String table) th @Override public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { return foreignKeys( - "pc.relname = ? AND pn.nspname LIKE ?", + "pc.relname OPERATOR(pg_catalog.=) ? AND pn.nspname OPERATOR(pg_catalog.~~) ?", List.of(nullToEmpty(table), pattern(schema)), "fn.nspname, fc.relname, con.conname, seq"); } @@ -1255,7 +1259,7 @@ public ResultSet getCrossReference( String foreignTable) throws SQLException { return foreignKeys( - "pc.relname = ? AND pn.nspname LIKE ? AND fc.relname = ? AND fn.nspname LIKE ?", + "pc.relname OPERATOR(pg_catalog.=) ? AND pn.nspname OPERATOR(pg_catalog.~~) ? AND fc.relname OPERATOR(pg_catalog.=) ? AND fn.nspname OPERATOR(pg_catalog.~~) ?", List.of( nullToEmpty(parentTable), pattern(parentSchema), @@ -1274,8 +1278,8 @@ private ResultSet foreignKeys(String where, List params, String orderBy) // subquery, not a LATERAL join, so this runs on pre-9.3 servers too. + "(SELECT ic.relname FROM pg_catalog.pg_depend dep " + "JOIN pg_catalog.pg_class ic ON ic.oid = dep.refobjid AND ic.relkind = 'i' " - + "WHERE dep.classid = 'pg_constraint'::regclass AND dep.objid = con.oid " - + "AND dep.refclassid = 'pg_class'::regclass AND dep.deptype = 'n' LIMIT 1) AS pkname, " + + "WHERE dep.classid OPERATOR(pg_catalog.=) 'pg_catalog.pg_constraint'::regclass AND dep.objid = con.oid " + + "AND dep.refclassid OPERATOR(pg_catalog.=) 'pg_catalog.pg_class'::regclass AND dep.deptype = 'n' LIMIT 1) AS pkname, " + "con.condeferrable AS deferrable, con.condeferred AS deferred " // Columns listed explicitly rather than `c.*`: before PostgreSQL 12 `oid` was a hidden // system column that a wildcard does not expand to, and the PK_NAME subquery needs it. @@ -1330,9 +1334,10 @@ private ResultSet foreignKeys(String where, List params, String orderBy) "DEFERRABILITY"); } - private static short foreignKeyRule(String pgType) { + static short foreignKeyRule(String pgType) { return (short) switch (pgType) { + case null -> importedKeyNoAction; case "c" -> importedKeyCascade; case "r" -> importedKeyRestrict; case "n" -> importedKeySetNull; @@ -1371,7 +1376,7 @@ public ResultSet getIndexInfo(String catalog, String schema, String table, boole + "JOIN pg_catalog.pg_class ci ON ci.oid = ix.indexrelid " + "JOIN pg_catalog.pg_namespace n ON n.oid = ct.relnamespace " + "LEFT JOIN pg_catalog.pg_attribute a ON a.attrelid = ct.oid AND a.attnum = " + INDKEY_ATTNUM + " " - + "WHERE n.nspname LIKE ? AND ct.relname = ? AND (NOT ? OR ix.indisunique) " + + "WHERE n.nspname OPERATOR(pg_catalog.~~) ? AND ct.relname OPERATOR(pg_catalog.=) ? AND (NOT ? OR ix.indisunique) " + "ORDER BY nonuniq, ci.relname, " + INDKEY_ORD; List rows = query(sql, List.of(pattern(schema), nullToEmpty(table), unique), rs -> new Object[] { catalogName(), @@ -1415,8 +1420,8 @@ public ResultSet getTypeInfo() throws SQLException { // static tables know keep their JDBC type code; the rest report OTHER. String sql = "SELECT t.typname AS name, t.oid AS oid FROM pg_catalog.pg_type t " + "JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace " - + "WHERE t.typtype IN ('b','e') AND n.nspname NOT LIKE 'pg\\_toast%' " - + "AND t.typinput <> 'pg_catalog.array_in'::regproc " + + "WHERE t.typtype IN ('b','e') AND n.nspname OPERATOR(pg_catalog.!~~) 'pg\\_toast%' " + + "AND t.typinput OPERATOR(pg_catalog.<>) 'pg_catalog.array_in'::regproc " + "ORDER BY t.typname"; List rows = query(sql, List.of(), rs -> { int oid = rs.getInt("oid"); @@ -1474,9 +1479,9 @@ public ResultSet getProcedures(String catalog, String schemaPattern, String proc String sql = "SELECT n.nspname AS schem, p.proname AS name, p.oid AS oid, " + "pg_catalog.obj_description(p.oid, 'pg_proc') AS remarks " + "FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace " - + "WHERE p.prokind = 'p' AND n.nspname LIKE ? AND p.proname LIKE ? " + + "WHERE p.prokind = 'p' AND n.nspname OPERATOR(pg_catalog.~~) ? AND p.proname OPERATOR(pg_catalog.~~) ? " // SPECIFIC_NAME is proname_oid; JDBC orders by it as text, so sort the same way. - + "ORDER BY n.nspname, p.proname, p.proname || '_' || p.oid"; + + "ORDER BY n.nspname, p.proname, p.proname OPERATOR(pg_catalog.||) '_' OPERATOR(pg_catalog.||) p.oid"; List rows = !catalogSelects(catalog) ? List.of() : query(sql, List.of(pattern(schemaPattern), pattern(procedureNamePattern)), rs -> new Object[] { @@ -1517,7 +1522,7 @@ public ResultSet getProcedureColumns( + "p.proargnames::text AS argnames " + "FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace " + "JOIN pg_catalog.pg_type t ON t.oid = p.prorettype " - + "WHERE n.nspname LIKE ? AND p.proname LIKE ? " + + "WHERE n.nspname OPERATOR(pg_catalog.~~) ? AND p.proname OPERATOR(pg_catalog.~~) ? " + "ORDER BY n.nspname, p.proname, p.oid"; List rows = new ArrayList<>(); if (!catalogSelects(catalog)) { @@ -1645,37 +1650,50 @@ private Object[] procedureColumnRow( private List compositeAttributes(int relid) throws SQLException { return query( "SELECT a.attname AS nm, a.atttypid AS tid FROM pg_catalog.pg_attribute a " - + "WHERE a.attrelid = ? AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum", + + "WHERE a.attrelid OPERATOR(pg_catalog.=) ? AND a.attnum > 0 AND NOT a.attisdropped ORDER BY a.attnum", List.of(relid), rs -> new Object[] {rs.getString("nm"), rs.getInt("tid")}); } /** Parses an {@code oidvector} rendered as text ({@code "23 1043"}) into its OIDs. */ - private static int[] parseOidVector(String text) { + static int[] parseOidVector(String text) throws SQLException { if (text == null || text.isBlank()) { return new int[0]; } String[] parts = text.trim().split("\\s+"); int[] oids = new int[parts.length]; for (int i = 0; i < parts.length; i++) { - oids[i] = Integer.parseInt(parts[i]); + oids[i] = parseCatalogOid(parts[i]); } return oids; } - /** Parses an {@code int[]} array literal ({@code "{23,1043}"}), or null when the source was null/empty. */ - private static int[] parseIntArrayLiteral(String text) { + /** Parses an {@code oid[]} array literal ({@code "{23,1043}"}), or null when the source was null/empty. */ + static int[] parseIntArrayLiteral(String text) throws SQLException { String[] parts = parseTextArrayLiteral(text); if (parts == null) { return null; } int[] out = new int[parts.length]; for (int i = 0; i < parts.length; i++) { - out[i] = Integer.parseInt(parts[i].trim()); + out[i] = parseCatalogOid(parts[i]); } return out; } + /** + * An OID from catalog text. OIDs are unsigned, so one above 2^31 - 1 is legitimate and wraps to a + * negative int as the driver stores OIDs everywhere; anything not a number is a server answering + * something impossible, reported as an SQLException rather than a NumberFormatException. + */ + private static int parseCatalogOid(String text) throws SQLException { + try { + return (int) Long.parseLong(text.trim()); + } catch (NumberFormatException e) { + throw new SQLException("malformed OID in the catalog: " + text, e); + } + } + /** * Parses a one-dimensional array literal ({@code "{a,b}"}) into its unquoted elements, or null when the * source was null. Sufficient for the identifier/mode/OID arrays here, which never contain commas. @@ -1708,9 +1726,9 @@ public ResultSet getFunctions(String catalog, String schemaPattern, String funct String sql = "SELECT n.nspname AS schem, p.proname AS name, p.oid AS oid, p.proretset AS retset, " + "pg_catalog.obj_description(p.oid, 'pg_proc') AS remarks " + "FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace " - + "WHERE p.prokind IN ('f','a','w') AND n.nspname LIKE ? AND p.proname LIKE ? " + + "WHERE p.prokind IN ('f','a','w') AND n.nspname OPERATOR(pg_catalog.~~) ? AND p.proname OPERATOR(pg_catalog.~~) ? " // SPECIFIC_NAME is proname_oid; JDBC orders by it as text, so sort the same way. - + "ORDER BY n.nspname, p.proname, p.proname || '_' || p.oid"; + + "ORDER BY n.nspname, p.proname, p.proname OPERATOR(pg_catalog.||) '_' OPERATOR(pg_catalog.||) p.oid"; List rows = !catalogSelects(catalog) ? List.of() : query(sql, List.of(pattern(schemaPattern), pattern(functionNamePattern)), rs -> new Object[] { @@ -1738,7 +1756,7 @@ public ResultSet getFunctionColumns( + "p.proargnames::text AS argnames " + "FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace " + "JOIN pg_catalog.pg_type t ON t.oid = p.prorettype " - + "WHERE n.nspname LIKE ? AND p.proname LIKE ? " + + "WHERE n.nspname OPERATOR(pg_catalog.~~) ? AND p.proname OPERATOR(pg_catalog.~~) ? " + "ORDER BY n.nspname, p.proname, p.oid"; List rows = new ArrayList<>(); if (!catalogSelects(catalog)) { @@ -1856,14 +1874,14 @@ public ResultSet getColumnPrivileges(String catalog, String schema, String table // grants (acldefault). One row per (column, grantee, privilege); grantee 0 is PUBLIC. String sql = "SELECT n.nspname AS schem, c.relname AS tbl, a.attname AS col, " + "pg_catalog.pg_get_userbyid(g.grantor) AS grantor, " - + "CASE WHEN g.grantee = 0 THEN 'PUBLIC' ELSE pg_catalog.pg_get_userbyid(g.grantee) END AS grantee, " + + "CASE WHEN g.grantee OPERATOR(pg_catalog.=) 0 THEN 'PUBLIC' ELSE pg_catalog.pg_get_userbyid(g.grantee) END AS grantee, " + "g.privilege_type AS priv, " + "CASE WHEN g.is_grantable THEN 'YES' ELSE 'NO' END AS grantable " + "FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " + "JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped " + "CROSS JOIN LATERAL " - + "aclexplode(COALESCE(a.attacl, c.relacl, pg_catalog.acldefault('r'::\"char\", c.relowner))) g " - + "WHERE n.nspname LIKE ? AND c.relname = ? AND a.attname LIKE ? " + + "pg_catalog.aclexplode(COALESCE(a.attacl, c.relacl, pg_catalog.acldefault('r'::\"char\", c.relowner))) g " + + "WHERE n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.=) ? AND a.attname OPERATOR(pg_catalog.~~) ? " + "AND g.privilege_type IN ('SELECT','INSERT','UPDATE','REFERENCES') " + "ORDER BY a.attname, g.privilege_type"; List rows = !catalogSelects(catalog) @@ -1902,13 +1920,13 @@ public ResultSet getTablePrivileges(String catalog, String schemaPattern, String // privilege name; grantee 0 is PUBLIC. String sql = "SELECT n.nspname AS schem, c.relname AS tbl, " + "pg_catalog.pg_get_userbyid(g.grantor) AS grantor, " - + "CASE WHEN g.grantee = 0 THEN 'PUBLIC' ELSE pg_catalog.pg_get_userbyid(g.grantee) END AS grantee, " + + "CASE WHEN g.grantee OPERATOR(pg_catalog.=) 0 THEN 'PUBLIC' ELSE pg_catalog.pg_get_userbyid(g.grantee) END AS grantee, " + "g.privilege_type AS priv, " + "CASE WHEN g.is_grantable THEN 'YES' ELSE 'NO' END AS grantable " + "FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " + "CROSS JOIN LATERAL " - + "aclexplode(COALESCE(c.relacl, pg_catalog.acldefault('r'::\"char\", c.relowner))) g " - + "WHERE c.relkind IN ('r','p','v','m','f') AND n.nspname LIKE ? AND c.relname LIKE ? " + + "pg_catalog.aclexplode(COALESCE(c.relacl, pg_catalog.acldefault('r'::\"char\", c.relowner))) g " + + "WHERE c.relkind IN ('r','p','v','m','f') AND n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.~~) ? " + "ORDER BY n.nspname, c.relname, g.privilege_type"; List rows = query(sql, List.of(pattern(schemaPattern), pattern(tableNamePattern)), rs -> new Object[] { @@ -1939,7 +1957,7 @@ public ResultSet getBestRowIdentifier(String catalog, String schema, String tabl + "JOIN pg_catalog.pg_class c ON c.oid = ix.indrelid " + "JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace " + "JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attnum = " + INDKEY_ATTNUM + " " - + "WHERE ix.indisprimary AND n.nspname LIKE ? AND c.relname = ? " + + "WHERE ix.indisprimary AND n.nspname OPERATOR(pg_catalog.~~) ? AND c.relname OPERATOR(pg_catalog.=) ? " + "ORDER BY " + INDKEY_ORD; rows = query(sql, List.of(pattern(schema), table == null ? "" : table), rs -> { int oid = rs.getInt("tid"); @@ -2017,7 +2035,7 @@ public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePa String sql = "SELECT n.nspname AS schem, t.typname AS name, t.typtype AS kind, t.typbasetype AS basetype, " + "pg_catalog.obj_description(t.oid, 'pg_type') AS remarks " + "FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace " - + "WHERE t.typtype IN ('c','d','e') AND n.nspname LIKE ? AND t.typname LIKE ? " + + "WHERE t.typtype IN ('c','d','e') AND n.nspname OPERATOR(pg_catalog.~~) ? AND t.typname OPERATOR(pg_catalog.~~) ? " + "ORDER BY n.nspname, t.typname"; List rows = new ArrayList<>(); List found = !catalogSelects(catalog) @@ -2086,7 +2104,7 @@ public ResultSet getAttributes( // throwing and an empty result. String sql = "SELECT n.nspname AS schem, t.typname AS tname, a.attname AS aname, " + "a.atttypid AS typid, a.atttypmod AS typmod, a.attnotnull AS notnull, " - + "row_number() OVER (PARTITION BY c.oid ORDER BY a.attnum) AS ord, " + + "pg_catalog.row_number() OVER (PARTITION BY c.oid ORDER BY a.attnum) AS ord, " + "pg_catalog.pg_get_expr(ad.adbin, ad.adrelid) AS def, " + "pg_catalog.col_description(c.oid, a.attnum) AS remarks " + "FROM pg_catalog.pg_type t " @@ -2096,10 +2114,10 @@ public ResultSet getAttributes( + "AND NOT a.attisdropped " + "LEFT JOIN pg_catalog.pg_attrdef ad ON ad.adrelid = c.oid AND ad.adnum = a.attnum " + "WHERE t.typtype = 'c' AND c.relkind = 'c' " - + "AND n.nspname LIKE ? AND t.typname LIKE ?"; + + "AND n.nspname OPERATOR(pg_catalog.~~) ? AND t.typname OPERATOR(pg_catalog.~~) ?"; // The attribute-name filter applies outside the window so it cannot renumber // ORDINAL_POSITION, the same way getColumns keeps a column's real ordinal. - sql = "SELECT * FROM (" + sql + ") attrs WHERE attrs.aname LIKE ? " + sql = "SELECT * FROM (" + sql + ") attrs WHERE attrs.aname OPERATOR(pg_catalog.~~) ? " + "ORDER BY attrs.schem, attrs.tname, attrs.ord"; List rows = !catalogSelects(catalog) ? List.of() diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java index 08158c22..b673f72c 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgDriver.java @@ -22,11 +22,14 @@ import org.postgresql.client.core.auth.AuthenticationProvider; import org.postgresql.client.core.auth.StandardAuthenticator; import org.postgresql.client.core.internal.jdbc.ConnectionStringParser; +import org.postgresql.client.core.internal.jdbc.PercentDecoding; import org.postgresql.client.jdbc.batch.BatchArrayRewriter; import org.postgresql.client.jdbc.batch.BatchArrayRewriters; import org.postgresql.client.jdbc.batch.BatchRewriteSetting; import org.postgresql.client.jdbc.batch.BatchValuesRewriter; import org.postgresql.client.jdbc.batch.BatchValuesRewriters; +import org.postgresql.client.jdbc.batch.InsertArrayRewriter; +import org.postgresql.client.jdbc.batch.InsertMultiValuesRewriter; import org.slf4j.LoggerFactory; /** @@ -335,13 +338,11 @@ private static AuthenticationProvider loadAuthenticationProvider(String classNam /** * Resolves the {@code rewriteBatchUsingArrays} property (ADR-0014) to a rewriter, or {@code null} * when disabled or unset. A URL-query value takes precedence over the {@link Properties} of the - * same name (matching the rest of the driver's precedence). + * same name (matching the rest of the driver's precedence), except that a custom class name is + * accepted only from {@link Properties}; see {@link #rewriterSetting}. */ private static BatchArrayRewriter resolveBatchRewriter(String url, Properties info) throws SQLException { - String value = queryParam(url, REWRITE_BATCH_PROPERTY); - if (value == null) { - value = info.getProperty(REWRITE_BATCH_PROPERTY); - } + String value = rewriterSetting(url, info, REWRITE_BATCH_PROPERTY, InsertArrayRewriter.ID); try { return BatchArrayRewriters.resolve(BatchRewriteSetting.fromProperty(value)) .orElse(null); @@ -353,13 +354,11 @@ private static BatchArrayRewriter resolveBatchRewriter(String url, Properties in /** * Resolves the {@code rewriteBatchUsingMultipleValues} property (ADR-0016) to a rewriter, or * {@code null} when disabled or unset. A URL-query value takes precedence over the {@link Properties} - * of the same name (matching the rest of the driver's precedence). + * of the same name (matching the rest of the driver's precedence), except that a custom class name + * is accepted only from {@link Properties}; see {@link #rewriterSetting}. */ private static BatchValuesRewriter resolveMultiValuesRewriter(String url, Properties info) throws SQLException { - String value = queryParam(url, REWRITE_BATCH_MULTIVALUES_PROPERTY); - if (value == null) { - value = info.getProperty(REWRITE_BATCH_MULTIVALUES_PROPERTY); - } + String value = rewriterSetting(url, info, REWRITE_BATCH_MULTIVALUES_PROPERTY, InsertMultiValuesRewriter.ID); try { return BatchValuesRewriters.resolve(BatchRewriteSetting.fromProperty(value)) .orElse(null); @@ -368,25 +367,69 @@ private static BatchValuesRewriter resolveMultiValuesRewriter(String url, Proper } } + /** + * The value of a rewriter property, from the URL query if present, else from {@link Properties}. + * A custom rewriter class named in the URL is refused: a class name is code to run, and the URL is + * the part of the configuration most often assembled from less trusted input, which is why + * {@code authenticationPluginClassName} is read only from {@link Properties} too (N2.9). The + * on/off spellings and the built-in id stay accepted from either. + */ + private static String rewriterSetting(String url, Properties info, String property, String builtInId) + throws SQLException { + String fromUrl = queryParam(url, property); + if (fromUrl == null) { + return info.getProperty(property); + } + BatchRewriteSetting setting = BatchRewriteSetting.fromProperty(fromUrl); + if (setting.mode() == BatchRewriteSetting.Mode.PINNED && !builtInId.equals(setting.selector())) { + throw new SQLException(property + " in the connection URL names a custom rewriter class; a class" + + " name is accepted only from the connection Properties"); + } + return fromUrl; + } + /** The raw value of the {@code name} query parameter in {@code url}, or {@code null} if absent. */ private static String queryParam(String url, String name) { int q = url.indexOf('?'); if (q < 0) { return null; } + // Keys and values are compared decoded, and the last occurrence wins, exactly as the core + // parser reads the same query: %72ewriteBatchUsingArrays= is the same key to it. + String value = null; for (String pair : url.substring(q + 1).split("&")) { int eq = pair.indexOf('='); - if (eq >= 0 && pair.substring(0, eq).equals(name)) { - return pair.substring(eq + 1); + if (eq >= 0 && decodeOrRaw(pair.substring(0, eq)).equals(name)) { + value = decodeOrRaw(pair.substring(eq + 1)); } } - return null; + return value; + } + + /** + * Percent-decodes {@code s}, or returns it as is when an escape is malformed; the core parser + * rejects such a URL when it builds the config. + */ + private static String decodeOrRaw(String s) { + try { + return PercentDecoding.decode(s); + } catch (PgException e) { + return s; + } } /** Builds a core config by merging the URL (higher precedence) with the supplied properties. */ - private static PgConnectionConfig buildConfig(String url, Properties info) throws SQLException { + static PgConnectionConfig buildConfig(String url, Properties info) throws SQLException { StringBuilder uri = new StringBuilder(normalizeUri(url.substring("jdbc:".length()))); char separator = uri.indexOf("?") >= 0 ? '&' : '?'; + // The properties go on the end of the query, where a repeated key's last value wins; skip + // the ones the URL already sets, so the URL keeps its precedence. + java.util.Set urlKeys; + try { + urlKeys = queryKeys(uri.toString()); + } catch (PgException e) { + throw PgSqlExceptions.wrap(e); // a malformed %-escape in a key + } for (String name : info.stringPropertyNames()) { if (JDBC_ONLY_PROPERTIES.contains(name)) { continue; // JDBC-only: consumed by the driver, not a core connection-string key @@ -396,6 +439,9 @@ private static PgConnectionConfig buildConfig(String url, Properties info) throw continue; } String key = PROPERTY_RENAMES.getOrDefault(name, name); + if (urlKeys.contains(key)) { + continue; + } uri.append(separator).append(encode(key)).append('=').append(encode(value)); separator = '&'; } @@ -411,6 +457,20 @@ private static PgConnectionConfig buildConfig(String url, Properties info) throw } } + /** The decoded keys of {@code uri}'s query parameters. */ + private static java.util.Set queryKeys(String uri) { + java.util.Set keys = new java.util.HashSet<>(); + int q = uri.indexOf('?'); + if (q < 0) { + return keys; + } + for (String pair : uri.substring(q + 1).split("&")) { + int eq = pair.indexOf('='); + keys.add(PercentDecoding.decode(eq >= 0 ? pair.substring(0, eq) : pair)); + } + return keys; + } + /** Returns {@code uri} with every {@code key=...} query parameter removed. */ private static String stripQueryParam(String uri, String key) { int q = uri.indexOf('?'); @@ -420,7 +480,7 @@ private static String stripQueryParam(String uri, String key) { StringBuilder kept = new StringBuilder(); for (String pair : uri.substring(q + 1).split("&")) { int eq = pair.indexOf('='); - String name = eq >= 0 ? pair.substring(0, eq) : pair; + String name = decodeOrRaw(eq >= 0 ? pair.substring(0, eq) : pair); if (name.equals(key)) { continue; } @@ -520,7 +580,7 @@ private static String matchingPrefix(String url) { } /** Percent-encodes a value so it survives the core parser's {@code %XX}-only decoding. */ - private static String encode(String value) { + static String encode(String value) { StringBuilder out = new StringBuilder(value.length()); for (byte b : value.getBytes(StandardCharsets.UTF_8)) { int c = b & 0xFF; diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgPreparedStatement.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgPreparedStatement.java index 1ded4785..05ff701c 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgPreparedStatement.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgPreparedStatement.java @@ -144,6 +144,8 @@ public boolean execute() throws SQLException { : core.execute(nativeSql, values)); } catch (RuntimeException e) { throw PgSqlExceptions.wrap(e); + } finally { + clearQueryTimeout(); } } @@ -1167,7 +1169,7 @@ public long[] executeLargeBatch() throws SQLException { // Inside an explicit transaction a failed batch commits nothing (the caller's later // commit rolls the aborted transaction back), so the keys captured before the failure are // not durable -- drop them to stay consistent with the all-failed update counts. - if (failed && !connection.getAutoCommit()) { + if (failed && !batchProgressIsDurable()) { keyMetadata = null; keyRows.clear(); } @@ -1212,6 +1214,7 @@ private long[] executePipelinedBatch() throws SQLException { throw PgSqlExceptions.wrap(e); } finally { parameterBatch.clear(); + clearQueryTimeout(); } } @@ -1279,6 +1282,7 @@ private long[] executeArrayBatch(BatchArrayExecution.Plan plan) throws SQLExcept // must not re-run the already-attempted batch. Clearing only on success left a failed // rewritten batch armed for an accidental re-execute (N1.12 F1). parameterBatch.clear(); + clearQueryTimeout(); } long[] counts = new long[elements]; long value = plan.countSemantics() == CountSemantics.ONE_PER_ELEMENT ? 1L : java.sql.Statement.SUCCESS_NO_INFO; @@ -1350,6 +1354,7 @@ private long[] executeMultiValuesBatch(ValuesTemplate template, BatchMultiValues wrapped); } finally { parameterBatch.clear(); + clearQueryTimeout(); } long[] counts = new long[plan.totalElements()]; Arrays.fill(counts, elementCount); diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSimpleDataSource.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSimpleDataSource.java index 26179f2e..e4829e7f 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSimpleDataSource.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSimpleDataSource.java @@ -7,6 +7,7 @@ import java.util.Properties; import java.util.logging.Logger; import javax.sql.DataSource; +import org.postgresql.client.core.internal.jdbc.ConnectionStringRedaction; /** * A minimal {@link DataSource} that hands out plain connections with no pooling (C23.5). @@ -45,7 +46,20 @@ public String getUrl() { return url; } + /** + * Sets the host. The value is spliced into a connection URL, so a character that would end the + * host part there is refused: {@code db?sslmode=disable&x=} would otherwise turn off the TLS + * policy configured on this data source, or name another host and user. + */ public void setServerName(String serverName) { + if (serverName != null) { + for (int i = 0; i < serverName.length(); i++) { + char c = serverName.charAt(i); + if (c <= ' ' || "/?#@&,=%\\".indexOf(c) >= 0) { + throw new IllegalArgumentException("invalid character in serverName: '" + c + "'"); + } + } + } this.serverName = serverName; } @@ -138,16 +152,18 @@ public Connection getConnection(String username, String password) throws SQLExce } Connection connection = driver.connect(effectiveUrl(), info); if (connection == null) { - throw new SQLException("invalid data source URL: " + effectiveUrl()); + // A URL that missed the scheme check can still carry a password (ADR-0010). + throw new SQLException("invalid data source URL: " + ConnectionStringRedaction.redactUrl(effectiveUrl())); } return connection; } - private String effectiveUrl() { + String effectiveUrl() { if (url != null) { return url; } - return "jdbc:postgresql://" + serverName + ':' + portNumber + '/' + (databaseName == null ? "" : databaseName); + return "jdbc:postgresql://" + serverName + ':' + portNumber + '/' + + (databaseName == null ? "" : PgDriver.encode(databaseName)); } // -- CommonDataSource. -- diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSqlExceptions.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSqlExceptions.java index e5380ed0..189bceef 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSqlExceptions.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgSqlExceptions.java @@ -105,7 +105,24 @@ private static String withDetailAndHint(String message, PgServerMessage server) /** Converts a core notice into a JDBC {@link SQLWarning}. */ static SQLWarning toWarning(PgNotice notice) { - return new SQLWarning(notice.message(), notice.sqlState()); + return new ServerWarning(notice.message(), notice.sqlState()); + } + + /** + * A warning the server sent, not one the driver raised, so the reading thread's stack means + * nothing; and getWarnings can build thousands of them per call. + */ + private static final class ServerWarning extends SQLWarning { + private static final long serialVersionUID = 1L; + + ServerWarning(String message, String sqlState) { + super(message, sqlState); + } + + @Override + public Throwable fillInStackTrace() { + return this; + } } /** Chains the notices from index {@code from} onward into a SQLWarning list (null when empty). */ diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgStatement.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgStatement.java index 081a76c3..d7c53aee 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgStatement.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgStatement.java @@ -172,6 +172,8 @@ private boolean doExecute(String sql, boolean generatedKeysRequested, String[] k return consume(core.execute(native_)); } catch (RuntimeException e) { throw PgSqlExceptions.wrap(e); + } finally { + clearQueryTimeout(); } } @@ -180,6 +182,15 @@ protected void applyQueryTimeout() { core.setQueryTimeout(queryTimeout); } + /** + * Clears the timeout {@link #applyQueryTimeout} set, once the execute has armed its timer. The + * setting is connection-wide in core, so left in place it also timed out work no statement asked + * to bound: commits, metadata queries, type lookups and the like. + */ + protected void clearQueryTimeout() { + core.setQueryTimeout(null); + } + /** Inspects a freshly opened stream: a row result becomes the current ResultSet, else an update. */ protected boolean consume(PgResultStream stream) throws SQLException { if (keysCaptureActive && stream.metadata().columnCount() > 0) { @@ -572,6 +583,14 @@ public long[] executeLargeBatch() throws SQLException { */ private long[] pipelinedLargeBatch(List nativeSqls) throws SQLException { applyQueryTimeout(); + try { + return pipelinedLargeBatchWindows(nativeSqls); + } finally { + clearQueryTimeout(); + } + } + + private long[] pipelinedLargeBatchWindows(List nativeSqls) throws SQLException { long[] counts = new long[nativeSqls.size()]; try (PgPipeline pipeline = core.pipeline()) { int done = 0; @@ -685,13 +704,21 @@ static BatchUpdateException batchFailure(String message, String sqlState, long[] * {@code BatchResultHandler}, which advances its committed boundary only when autocommit is on. */ long[] failedBatchCounts(long[] counts, int committed, int totalSize) throws SQLException { - int boundary = connection.getAutoCommit() ? committed : 0; + int boundary = batchProgressIsDurable() ? committed : 0; long[] out = new long[totalSize]; Arrays.fill(out, Statement.EXECUTE_FAILED); System.arraycopy(counts, 0, out, 0, boundary); return out; } + /** + * Whether the windows of a failed batch that already synced stay committed: under autocommit, and + * not inside a transaction block the caller opened with BEGIN, whose failure rolls them back. + */ + boolean batchProgressIsDurable() throws SQLException { + return connection.getAutoCommit() && !core.inTransaction(); + } + /** * A full-length update-count array whose first {@code kept} entries carry their real counts (from * {@code counts}) and the rest are {@link Statement#EXECUTE_FAILED}. Used when a batch entry diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgXAResource.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgXAResource.java index 69e5246f..8bac0f13 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgXAResource.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/PgXAResource.java @@ -135,8 +135,8 @@ public Xid[] recover(int flag) throws XAException { } List xids = new ArrayList<>(); try (Statement st = connection.createStatement(); - ResultSet rs = - st.executeQuery("SELECT gid FROM pg_prepared_xacts WHERE database = current_database()")) { + ResultSet rs = st.executeQuery( + "SELECT gid FROM pg_catalog.pg_prepared_xacts WHERE database = pg_catalog.current_database()")) { while (rs.next()) { Xid xid = decode(rs.getString(1)); if (xid != null) { diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java index ae6bd38d..09f645c6 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/SqlParser.java @@ -141,8 +141,9 @@ private static int skipThrough(int end, int skipEnd) { return skipEnd < 0 ? end : skipEnd; } + /** As the backend sees it, so {@code x$returning} is one identifier, not a RETURNING keyword. */ private static boolean isIdentifierPart(char c) { - return Character.isLetterOrDigit(c) || c == '_'; + return Character.isLetterOrDigit(c) || c == '_' || c == '$' || c >= 0x80; } /** @@ -308,60 +309,37 @@ private static String translateLocate(List args) { /** Finds the index of the {@code ')'} matching the {@code '('} at {@code open}, or -1. */ private static int matchingParen(String s, int open) { int depth = 0; - for (int i = open; i < s.length(); i++) { + int i = open; + while (i < s.length()) { + int next = SqlLexing.skipLexeme(s, i, s.length()); + if (next > i) { + i = next; + continue; + } char c = s.charAt(i); - if (c == '\'' || c == '"') { - i = skipQuoted(s, i, c); - } else if (c == '(') { + if (c == '(') { depth++; } else if (c == ')' && --depth == 0) { return i; } + i++; } return -1; } - /** Splits a function argument list on top-level commas, respecting nested parens and quotes. */ + /** + * Splits a function argument list on top-level commas, respecting nested parens and brackets, + * and stepping over quoted strings (E'' and dollar-quoted ones too), quoted identifiers and + * comments, whose commas and parentheses are not syntax. + */ private static List splitArgs(String s) { List args = new ArrayList<>(); - if (s.isBlank()) { - return args; - } - int depth = 0; - int start = 0; - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c == '\'' || c == '"') { - i = skipQuoted(s, i, c); - } else if (c == '(') { - depth++; - } else if (c == ')') { - depth--; - } else if (c == ',' && depth == 0) { - args.add(s.substring(start, i).trim()); - start = i + 1; - } + for (String arg : CallArguments.split(s)) { + args.add(CallArguments.strip(arg)); } - args.add(s.substring(start).trim()); return args; } - /** Returns the index of the quote closing the one at {@code i}, treating {@code qq} as escaped. */ - private static int skipQuoted(String s, int i, char quote) { - int j = i + 1; - while (j < s.length()) { - if (s.charAt(j) == quote) { - if (j + 1 < s.length() && s.charAt(j + 1) == quote) { - j += 2; // doubled quote: an escaped quote, stay inside - continue; - } - return j; - } - j++; - } - return s.length() - 1; // unterminated; stop at the end (best effort) - } - /** * The first significant word in {@code sql} (lowercased) -- a run of identifier characters after * skipping leading whitespace and line/block comments; empty string if there is none. Used to diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/UpdatableResultSetSupport.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/UpdatableResultSetSupport.java index 21097ea7..6788f7d8 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/UpdatableResultSetSupport.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/UpdatableResultSetSupport.java @@ -112,7 +112,7 @@ private static void lookupColumns( + " FROM pg_catalog.pg_attribute a" + " LEFT JOIN pg_catalog.pg_index i" + " ON i.indrelid = a.attrelid AND i.indisprimary AND a.attnum = ANY(i.indkey)" - + " WHERE a.attrelid = ? AND a.attnum > 0 AND NOT a.attisdropped" + + " WHERE a.attrelid OPERATOR(pg_catalog.=) ? AND a.attnum > 0 AND NOT a.attisdropped" + " ORDER BY a.attnum"; try (java.sql.PreparedStatement ps = connection.prepareStatement(sql)) { ps.setInt(1, tableOid); diff --git a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/sql/SqlLexing.java b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/sql/SqlLexing.java index 3cc55623..0bd84c9c 100644 --- a/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/sql/SqlLexing.java +++ b/postgresql-client-jdbc/src/main/java/org/postgresql/client/jdbc/sql/SqlLexing.java @@ -27,8 +27,77 @@ public static boolean isEscapeStringPrefix(String sql, int i) { if (i < 2) { return true; } - char before = sql.charAt(i - 2); - return !(Character.isLetterOrDigit(before) || before == '_'); + // '$' too: PostgreSQL identifiers may contain it after the first character, so the 'e' of + // x$e'..' ends the identifier x$e and the quote opens a plain string. + return !isIdentifierPart(sql, i - 2); + } + + /** + * Whether the character at {@code i} continues an identifier as the backend sees it: an ASCII + * letter, digit, {@code _} or {@code $}, or any non-ASCII character. An unpaired surrogate is + * not one, since it goes out as {@code ?}. + */ + private static boolean isIdentifierPart(String sql, int i) { + char c = sql.charAt(i); + if (c < 0x80) { + return Character.isLetterOrDigit(c) || c == '_' || c == '$'; + } + return !isUnpairedSurrogate(sql, i); + } + + private static boolean isUnpairedSurrogate(String sql, int i) { + char c = sql.charAt(i); + if (Character.isHighSurrogate(c)) { + return i + 1 >= sql.length() || !Character.isLowSurrogate(sql.charAt(i + 1)); + } + if (Character.isLowSurrogate(c)) { + return i == 0 || !Character.isHighSurrogate(sql.charAt(i - 1)); + } + return false; + } + + /** + * Whether the {@code $} at {@code i} continues an identifier ({@code x$b$} is one identifier to + * the backend, not {@code x} and a dollar quote): the run of identifier characters before it + * starts with a letter, {@code _} or non-ASCII character rather than a digit or {@code $}. + */ + private static boolean continuesIdentifier(String sql, int i) { + int j = i; + while (j > 0 && isIdentifierPart(sql, j - 1)) { + j--; + } + if (j == i) { + return false; + } + char first = sql.charAt(j); + return !(first == '$' || (first >= '0' && first <= '9')); + } + + /** + * Skips the quoted string, quoted identifier, dollar-quoted string or comment opening at + * {@code i}: returns the index just past it, {@code end} if it never terminates, or {@code i} + * itself when none opens there. For scanners that only need to step over these constructs. + */ + public static int skipLexeme(String sql, int i, int end) { + char c = sql.charAt(i); + int next; + if (c == '\'') { + next = skipSingleQuoted(sql, i, end, isEscapeStringPrefix(sql, i)); + } else if (c == '"') { + next = skipDoubleQuoted(sql, i, end); + } else if (c == '$') { + next = skipDollarQuote(sql, i, end); + if (next == i + 1) { + return i; // a lone '$', not a quote + } + } else if (c == '-' && i + 1 < end && sql.charAt(i + 1) == '-') { + next = skipLineComment(sql, i, end); + } else if (c == '/' && i + 1 < end && sql.charAt(i + 1) == '*') { + next = skipBlockComment(sql, i, end); + } else { + return i; + } + return next < 0 ? end : next; } /** @@ -49,13 +118,40 @@ public static int skipSingleQuoted(String sql, int i, int end, boolean escapeStr i += 2; // doubled quote: an escaped quote, stay in the string continue; } - return i + 1; + int continued = continuationQuote(sql, i + 1, end); + if (continued < 0) { + return i + 1; + } + i = continued + 1; // 'a''b' is one string, keeping E'' rules if it had them + continue; } i++; } return -1; } + /** + * The index of the quote that continues a string closed just before {@code i}: whitespace + * holding at least one newline (line comments allowed), then a quote. -1 when none follows. + */ + private static int continuationQuote(String sql, int i, int end) { + boolean newline = false; + while (i < end) { + char c = sql.charAt(i); + if (c == '\n' || c == '\r') { + newline = true; + i++; + } else if (c == ' ' || c == '\t' || c == '\f' || c == '\u000B') { + i++; + } else if (c == '-' && i + 1 < end && sql.charAt(i + 1) == '-') { + i = skipLineComment(sql, i, end); + } else { + return newline && c == '\'' ? i : -1; + } + } + return -1; + } + /** * Skips the double-quoted identifier opening at {@code i} (with {@code ""} escapes); returns * the index past the closing quote, or -1 if unterminated. @@ -113,6 +209,9 @@ public static int skipBlockComment(String sql, int i, int end) { * closes; when it is a lone {@code $} (not an open tag), returns {@code i + 1}. */ public static int skipDollarQuote(String sql, int i, int end) { + if (continuesIdentifier(sql, i)) { + return i + 1; + } int tagEnd = dollarTagEnd(sql, i, end); if (tagEnd < 0) { return i + 1; // a lone '$', not a dollar-quote open @@ -128,9 +227,9 @@ private static int dollarTagEnd(String sql, int i, int end) { if (j < end && sql.charAt(j) == '$') { return j; // empty tag $$ } - if (j < end && isDollarTagStart(sql.charAt(j))) { + if (j < end && isDollarTagStart(sql.charAt(j)) && !isUnpairedSurrogate(sql, j)) { j++; - while (j < end && isDollarTagPart(sql.charAt(j))) { + while (j < end && isDollarTagPart(sql.charAt(j)) && !isUnpairedSurrogate(sql, j)) { j++; } if (j < end && sql.charAt(j) == '$') { diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/CallArgumentsTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/CallArgumentsTest.java new file mode 100644 index 00000000..075ea83d --- /dev/null +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/CallArgumentsTest.java @@ -0,0 +1,72 @@ +package org.postgresql.client.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import org.junit.jupiter.api.Test; + +/** A {@code {call ...}} escape keeps the arguments as written, literals included. */ +class CallArgumentsTest { + + private final List values = new ArrayList<>(); + + private String rebuild(String text, boolean call, Set out, Object... bound) throws SQLException { + boolean[] isBound = new boolean[bound.length]; + for (int i = 0; i < bound.length; i++) { + isBound[i] = bound[i] != null; + } + return CallArguments.rebuild(text, call, out, isBound, bound, values); + } + + @Test + void aCommentInAnArgumentKeepsItsNewline() throws SQLException { + assertEquals("$1 -- c\n, 'l1\nl2'", rebuild("? -- c\n, 'l1\nl2'", false, Set.of(), "a")); + values.clear(); + assertEquals("1 -- c\n, $1", rebuild("1 -- c\n, ?", false, Set.of(), "a")); + } + + @Test + void literalArgumentsAreKept() throws SQLException { + assertEquals("$1, 1", rebuild("?, 1", false, Set.of(), "a")); + assertEquals(List.of("a"), values); + } + + @Test + void expressionsKeepTheirPlaceholdersAsInParameters() throws SQLException { + assertEquals( + "$1 + 1, 'x, y', lower($2), ARRAY[1, 2]", + rebuild("? + 1, 'x, y', lower(?), ARRAY[1, 2]", false, Set.of(), 5, "B")); + assertEquals(List.of(5, "B"), values); + } + + @Test + void outOnlyParametersAreDroppedUnderSelectAndNullUnderCall() throws SQLException { + // f(IN ?, 42, OUT ?): placeholder 2 is OUT-only. + assertEquals("$1, 42", rebuild("?, 42, ?", false, Set.of(2), "a", null)); + values.clear(); + assertEquals("$1, 42, $2", rebuild("?, 42, ?", true, Set.of(2), "a", null)); + assertEquals(Arrays.asList("a", null), values); + } + + @Test + void quotedQuestionMarksAndCommentsAreNotPlaceholders() throws SQLException { + assertEquals( + "'?', \"a?\", $$?,$$, $1 /* ?, */", rebuild("'?', \"a?\", $$?,$$, ? /* ?, */", false, Set.of(), "v")); + assertEquals(List.of("v"), values); + } + + @Test + void doubledQuestionMarkIsALiteral() throws SQLException { + assertEquals("$1 ? 'k'", rebuild("? ?? 'k'", false, Set.of(), "{}")); + } + + @Test + void emptyArgumentListStaysEmpty() throws SQLException { + assertEquals("", rebuild("", false, Set.of())); + assertEquals("", rebuild(" ", true, Set.of())); + } +} diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/DatabaseMetaDataCatalogValuesTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/DatabaseMetaDataCatalogValuesTest.java new file mode 100644 index 00000000..b2e68ed1 --- /dev/null +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/DatabaseMetaDataCatalogValuesTest.java @@ -0,0 +1,35 @@ +package org.postgresql.client.jdbc; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import org.junit.jupiter.api.Test; + +/** + * Catalog values the metadata methods decode come from the server; null or malformed ones must + * not escape as NullPointerException or NumberFormatException. + */ +class DatabaseMetaDataCatalogValuesTest { + + @Test + void nullRelkindAndRuleFallBackToTheDefaults() { + assertEquals("TABLE", PgDatabaseMetaData.tableType(null, "public")); + assertEquals(DatabaseMetaData.importedKeyNoAction, PgDatabaseMetaData.foreignKeyRule(null)); + } + + @Test + void oidsAboveTheSignedRangeParse() throws SQLException { + // OIDs are unsigned; 3000000000 is a real OID on a long-lived cluster. + assertArrayEquals(new int[] {23, (int) 3000000000L}, PgDatabaseMetaData.parseOidVector("23 3000000000")); + assertArrayEquals(new int[] {(int) 3000000000L}, PgDatabaseMetaData.parseIntArrayLiteral("{3000000000}")); + } + + @Test + void malformedOidsAreSqlExceptions() { + assertThrows(SQLException.class, () -> PgDatabaseMetaData.parseOidVector("23 x")); + assertThrows(SQLException.class, () -> PgDatabaseMetaData.parseIntArrayLiteral("{23,x}")); + } +} diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgCallableStatementTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgCallableStatementTest.java index f056c7ed..5aa74239 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgCallableStatementTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgCallableStatementTest.java @@ -6,6 +6,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.Set; import org.junit.jupiter.api.Test; @@ -23,23 +25,21 @@ class PgCallableStatementTest { @Test void boundInoutParameterIsSentAsAnArgument() throws SQLException { // fn(IN a, INOUT b): both indices are bound, index 2 is also registered OUT. - List args = - PgCallableStatement.callArguments(2, Set.of(2), new boolean[] {true, true}, new Object[] {"a", "b"}); + List args = selectArguments(2, Set.of(2), new boolean[] {true, true}, new Object[] {"a", "b"}); assertEquals(List.of("a", "b"), args); } @Test void outOnlyParameterIsOmittedFromTheArguments() throws SQLException { // fn(IN a, OUT c): index 2 is registered and never bound. - List args = - PgCallableStatement.callArguments(2, Set.of(2), new boolean[] {true, false}, new Object[] {"a", null}); + List args = selectArguments(2, Set.of(2), new boolean[] {true, false}, new Object[] {"a", null}); assertEquals(List.of("a"), args); } @Test void mixedInInoutAndOutKeepDeclarationOrder() throws SQLException { // fn(IN a, INOUT b, OUT c, IN d): arguments are a, b, d in order. - List args = PgCallableStatement.callArguments( + List args = selectArguments( 4, Set.of(2, 3), new boolean[] {true, true, false, true}, new Object[] {"a", "b", null, "d"}); assertEquals(List.of("a", "b", "d"), args); } @@ -48,8 +48,7 @@ void mixedInInoutAndOutKeepDeclarationOrder() throws SQLException { void unboundInParameterIsRejected() { SQLException e = assertThrows( SQLException.class, - () -> PgCallableStatement.callArguments( - 2, Set.of(), new boolean[] {true, false}, new Object[] {"a", null})); + () -> selectArguments(2, Set.of(), new boolean[] {true, false}, new Object[] {"a", null})); assertEquals("parameter 2 is not set", e.getMessage()); } @@ -58,8 +57,7 @@ void unboundInParameterIsRejected() { @Test void callSendsAnOutOnlyParameterAsNull() throws SQLException { // p(IN a, OUT b): CALL takes an argument for b too, and does not evaluate it. - List args = PgCallableStatement.procedureArguments( - 2, Set.of(2), new boolean[] {true, false}, new Object[] {"a", null}); + List args = callArguments(2, Set.of(2), new boolean[] {true, false}, new Object[] {"a", null}); assertEquals(2, args.size()); assertEquals("a", args.get(0)); assertNull(args.get(1)); @@ -68,8 +66,7 @@ void callSendsAnOutOnlyParameterAsNull() throws SQLException { @Test void callSendsABoundInoutParameterAsItsInputValue() throws SQLException { // p(INOUT a, OUT b): a is registered and bound, so its input value goes on the wire. - List args = PgCallableStatement.procedureArguments( - 2, Set.of(1, 2), new boolean[] {true, false}, new Object[] {21, null}); + List args = callArguments(2, Set.of(1, 2), new boolean[] {true, false}, new Object[] {21, null}); assertEquals(2, args.size()); assertEquals(21, args.get(0)); assertNull(args.get(1)); @@ -78,7 +75,7 @@ void callSendsABoundInoutParameterAsItsInputValue() throws SQLException { @Test void callKeepsDeclarationOrderAcrossInInoutAndOut() throws SQLException { // p(IN a, INOUT b, OUT c, IN d): four arguments, the OUT one null, order preserved. - List args = PgCallableStatement.procedureArguments( + List args = callArguments( 4, Set.of(2, 3), new boolean[] {true, true, false, true}, new Object[] {"a", "b", null, "d"}); assertEquals(java.util.Arrays.asList("a", "b", null, "d"), args); } @@ -88,8 +85,26 @@ void callKeepsDeclarationOrderAcrossInInoutAndOut() throws SQLException { void callRejectsAnUnsetInParameter() { SQLException e = assertThrows( SQLException.class, - () -> PgCallableStatement.procedureArguments( - 2, Set.of(2), new boolean[] {false, false}, new Object[] {null, null})); + () -> callArguments(2, Set.of(2), new boolean[] {false, false}, new Object[] {null, null})); assertTrue(e.getMessage().contains("parameter 1"), e.getMessage()); } + + /** The values sent for {@code n} bare {@code ?} arguments under SELECT. */ + private static List selectArguments(int n, Set out, boolean[] bound, Object[] parameters) + throws SQLException { + return values(n, false, out, bound, parameters); + } + + /** The values sent for {@code n} bare {@code ?} arguments under CALL. */ + private static List callArguments(int n, Set out, boolean[] bound, Object[] parameters) + throws SQLException { + return values(n, true, out, bound, parameters); + } + + private static List values(int n, boolean call, Set out, boolean[] bound, Object[] parameters) + throws SQLException { + List values = new ArrayList<>(); + CallArguments.rebuild(String.join(", ", Collections.nCopies(n, "?")), call, out, bound, parameters, values); + return values; + } } diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java index 6e8861e5..1fb77d69 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgDriverTest.java @@ -10,9 +10,12 @@ import java.sql.Driver; import java.sql.DriverManager; import java.sql.DriverPropertyInfo; +import java.sql.SQLException; import java.util.Properties; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Isolated; +import org.postgresql.client.core.PgConnectionConfig; +import org.postgresql.client.core.SslMode; // Mutates process-global state (the DriverManager registry), so it must not run concurrently with // any other test (analysis-013 F14). @@ -126,6 +129,59 @@ void autoRegisterCanBeDisabled() { } } + @Test + void customRewriterClassIsRefusedFromTheUrl() { + // A class name is code to run; like authenticationPluginClassName it is taken only from + // Properties. Both checks happen before any connection attempt. + Properties info = new Properties(); + info.setProperty("user", "app"); + for (String property : new String[] {"rewriteBatchUsingArrays", "rewriteBatchUsingMultipleValues"}) { + SQLException e = assertThrows(SQLException.class, () -> new PgDriver() + .connect("jdbc:postgresql://127.0.0.1:1/db?" + property + "=com.example.Rewriter", info)); + assertTrue(e.getMessage().contains("custom rewriter class"), e.getMessage()); + } + } + + @Test + void customRewriterClassIsStillAcceptedFromProperties() { + Properties info = new Properties(); + info.setProperty("user", "app"); + info.setProperty("rewriteBatchUsingArrays", "java.lang.String"); + SQLException e = assertThrows( + SQLException.class, () -> new PgDriver().connect("jdbc:postgresql://127.0.0.1:1/db", info)); + assertTrue(e.getMessage().contains("does not implement"), e.getMessage()); + } + + @Test + void urlStillOutranksPropertiesOfTheSameName() throws SQLException { + // Properties are appended to the URL query, where a repeated key's last value now wins; + // the URL's own value must still be the one used. + Properties info = new Properties(); + info.setProperty("user", "app"); + info.setProperty("sslmode", "disable"); + info.setProperty("application_name", "from-properties"); + PgConnectionConfig config = + PgDriver.buildConfig("jdbc:postgresql://h/db?sslmode=require&application_name=from-url", info); + assertEquals(SslMode.REQUIRE, config.sslMode()); + assertEquals("from-url", config.applicationName()); + assertEquals("app", config.user()); + } + + @Test + void percentEncodedJdbcOnlyKeysAreRecognized() throws SQLException { + // Core decodes keys, so an encoded JDBC-only key must be stripped and checked like the plain one. + Properties info = new Properties(); + info.setProperty("user", "app"); + PgConnectionConfig config = PgDriver.buildConfig( + "jdbc:postgresql://h/db?%61uthenticationPluginClassName=x&%63laimPostgresqlScheme=always", info); + assertFalse(config.runtimeParameters().containsKey("authenticationPluginClassName")); + assertFalse(config.runtimeParameters().containsKey("claimPostgresqlScheme")); + + SQLException e = assertThrows(SQLException.class, () -> new PgDriver() + .connect("jdbc:postgresql://127.0.0.1:1/db?%72ewriteBatchUsingArrays=com.example.Rewriter", info)); + assertTrue(e.getMessage().contains("custom rewriter class"), e.getMessage()); + } + @Test void reportsVersionAndCompliance() { assertEquals(0, driver.getMajorVersion()); diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSimpleDataSourceTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSimpleDataSourceTest.java index 56a1d38d..164d68d4 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSimpleDataSourceTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSimpleDataSourceTest.java @@ -11,9 +11,12 @@ import java.io.StringWriter; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; +import java.util.Map; import javax.sql.ConnectionPoolDataSource; import javax.sql.DataSource; import org.junit.jupiter.api.Test; +import org.postgresql.client.core.PgConnectionConfig; +import org.postgresql.client.core.internal.jdbc.ConnectionStringParser; /** * Unit tests for {@link PgSimpleDataSource} (N1.18): the JavaBeans property surface and its mapping @@ -83,6 +86,63 @@ void explicitUrlTakesPrecedenceOverDiscreteFields() { "the failure should name the explicit URL, not one built from the discrete fields"); } + /** The config the core parser builds from the data source's URL; the user travels separately. */ + private static PgConnectionConfig parseEffectiveUrl(PgSimpleDataSource ds) { + String url = ds.effectiveUrl().substring("jdbc:".length()); + return ConnectionStringParser.parse(url + (url.contains("?") ? "&" : "?") + "user=app", Map.of()); + } + + @Test + void databaseNameCannotInjectUrlParameters() { + // The bean fields are spliced into a URL whose query values outrank the bean's own + // properties; an unencoded database name could turn off sslmode or replace the user. + PgSimpleDataSource ds = new PgSimpleDataSource(); + ds.setServerName("db.example.com"); + ds.setDatabaseName("app?sslmode=disable&user=mallory&application_name="); + + PgConnectionConfig config = parseEffectiveUrl(ds); + assertEquals("app?sslmode=disable&user=mallory&application_name=", config.database()); + assertEquals("db.example.com", config.hosts().get(0).host()); + assertFalse(ds.effectiveUrl().contains("?"), ds.effectiveUrl()); + } + + @Test + void databaseNameWithNonAsciiRoundTrips() { + PgSimpleDataSource ds = new PgSimpleDataSource(); + ds.setDatabaseName("caf\u00e9 db"); + assertEquals("caf\u00e9 db", parseEffectiveUrl(ds).database()); + } + + @Test + void serverNameThatWouldEndTheHostIsRefused() { + PgSimpleDataSource ds = new PgSimpleDataSource(); + for (String bad : new String[] { + "evil?sslmode=disable&x=", "evil/db", "user@evil", "a,b", "evil#x", "evil x", "evil%2f", "evil&x=1" + }) { + assertThrows(IllegalArgumentException.class, () -> ds.setServerName(bad), bad); + } + assertEquals("localhost", ds.getServerName()); + ds.setServerName("[::1]"); + ds.setServerName("db-1.example.com"); + assertEquals("db-1.example.com", ds.getServerName()); + } + + @Test + void rejectedUrlIsRedactedInTheMessage() { + PgSimpleDataSource ds = new PgSimpleDataSource(); + for (String url : new String[] { + "postgresql://app:s3cret@db.example.com/app", + "jdbc:postgresq://app:s3cret@db.example.com/app", + "postgresql://db.example.com/app?password=s3cret", + "jdbc:mysql://db.example.com/app?user=app&password=s3cret" + }) { + ds.setUrl(url); + SQLException e = assertThrows(SQLException.class, ds::getConnection, url); + assertFalse(e.getMessage().contains("s3cret"), e.getMessage()); + assertTrue(e.getMessage().contains("db.example.com"), e.getMessage()); + } + } + @Test void loginTimeoutRoundTripsAndRejectsNegative() throws SQLException { PgSimpleDataSource ds = new PgSimpleDataSource(); diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSqlExceptionsTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSqlExceptionsTest.java index 57c17baa..a7927453 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSqlExceptionsTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/PgSqlExceptionsTest.java @@ -19,6 +19,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.postgresql.client.core.PgException; +import org.postgresql.client.core.PgNotice; import org.postgresql.client.core.PgServerMessage; import org.postgresql.client.core.PgTimeoutException; @@ -189,4 +190,15 @@ void resetRestoresTheDefaultMapping() { SQLIntegrityConstraintViolationException.class, PgSqlExceptions.wrap(serverError("23505", "duplicate key"))); } + + @Test + void serverWarningsCarryNoStackTrace() { + PgNotice notice = new PgNotice(new PgServerMessage( + "WARNING", "WARNING", "01000", "careful", null, null, null, null, null, null, null, null, null, null, + null, null, null, null)); + java.sql.SQLWarning warning = PgSqlExceptions.toWarning(notice); + assertEquals("careful", warning.getMessage()); + assertEquals("01000", warning.getSQLState()); + assertEquals(0, warning.getStackTrace().length); + } } diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java index e59426b1..b9d58bee 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/SqlParserTest.java @@ -202,4 +202,77 @@ void detectsMultipleStatements() { assertFalse(parse("select ';'").multiStatement()); assertFalse(parse("select 1; -- trailing comment\n").multiStatement()); } + + @Test + void fnArgumentsStepOverDollarQuotesEStringsAndComments() { + // Commas and parentheses inside these are not syntax; splitting there mistranslated the call. + assertEquals( + "coalesce($$a,b)$$,'x')", + SqlParser.parse("{fn ifnull($$a,b)$$,'x')}", true).nativeSql()); + assertEquals( + "coalesce(E'it\\'s, ok','x')", + SqlParser.parse("{fn ifnull(E'it\\'s, ok','x')}", true).nativeSql()); + assertEquals( + "position('a' in b /* , ) */)", + SqlParser.parse("{fn locate('a', b /* , ) */)}", true).nativeSql()); + } + + @Test + void dollarInsideAnIdentifierDoesNotMakeAnEString() { + // x$e is one identifier, so the quote after it opens a plain string, in which a backslash + // is an ordinary character and the next quote closes it. + ParsedSql p = SqlParser.parse("select x$e'\\', ?", false); + assertEquals("select x$e'\\', $1", p.nativeSql()); + assertEquals(1, p.parameterCount()); + } + + @Test + void aCommentInAnEscapeArgumentKeepsItsNewline() { + // Without the newline the comment would run over 'l1 and leave l2 outside a literal. + ParsedSql p = parse("SELECT {fn ifnull(a -- c\n, 'x')}, 'l1\nl2'"); + assertEquals("SELECT coalesce(a -- c\n,'x'), 'l1\nl2'", p.nativeSql()); + ParsedSql q = parse("SELECT {fn locate('a', b -- c\n)}"); + assertEquals("SELECT position('a' in b -- c\n)", q.nativeSql()); + } + + @Test + void aContinuedEscapeStringKeepsItsEscapes() { + // The backend reads a' , ? -- as one E'' string, so there is no placeholder. + ParsedSql p = parse("SELECT E'a'\n'\\' , ? -- '"); + assertEquals(0, p.parameterCount()); + ParsedSql q = parse("SELECT 'a' -- c\n'b', ?"); + assertEquals("SELECT 'a' -- c\n'b', $1", q.nativeSql()); + ParsedSql r = parse("SELECT 'a' 'b', ?"); + assertEquals(1, r.parameterCount()); + } + + @Test + void aDollarInsideAnIdentifierDoesNotOpenAQuote() { + ParsedSql p = parse("SELECT x$b$ , $b$ ? $b$"); + assertEquals("SELECT x$b$ , $b$ ? $b$", p.nativeSql()); + assertEquals(0, p.parameterCount()); + ParsedSql q = parse("SELECT ?, $1$a$ ? $a$"); + assertEquals(1, q.parameterCount()); + } + + @Test + void anEAfterANonAsciiCharacterIsPartOfAnIdentifier() { + ParsedSql p = parse("SELECT \u00A7e'\\' ? ' ? '"); + assertEquals("SELECT \u00A7e'\\' $1 ' ? '", p.nativeSql()); + } + + @Test + void anUnpairedSurrogateDoesNotFormADollarTag() { + ParsedSql p = parse("SELECT $a\uD800$ ? $a\uD800$, ?"); + assertEquals(2, p.parameterCount()); + ParsedSql q = parse("SELECT $a\uD83D\uDE00$ ? $a\uD83D\uDE00$, ?"); + assertEquals(1, q.parameterCount()); + } + + @Test + void containsKeywordSkipsIdentifiersThatEndInTheKeyword() { + assertFalse(SqlParser.containsKeyword("insert into t (x$returning) values (1)", "returning")); + assertFalse(SqlParser.containsKeyword("insert into t (\u00e9returning) values (1)", "returning")); + assertTrue(SqlParser.containsKeyword("insert into t values (1) returning id", "returning")); + } } diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/StatementQueryTimeoutScopeTest.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/StatementQueryTimeoutScopeTest.java new file mode 100644 index 00000000..1409a703 --- /dev/null +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/StatementQueryTimeoutScopeTest.java @@ -0,0 +1,79 @@ +package org.postgresql.client.jdbc; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.lang.reflect.Proxy; +import java.sql.Statement; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.PgConnectionConfig; +import org.postgresql.client.core.PgResultStream; +import org.postgresql.client.core.RowMetadata; + +/** + * A statement's query timeout is set on the core connection just for its execute: left in place it + * also bounded work no statement asked to bound (commits, metadata queries, type lookups). + */ +class StatementQueryTimeoutScopeTest { + + private final List calls = new ArrayList<>(); + + private static Object proxy(Class type, java.lang.reflect.InvocationHandler handler) { + return Proxy.newProxyInstance( + StatementQueryTimeoutScopeTest.class.getClassLoader(), new Class[] {type}, handler); + } + + private static Object defaultFor(Class type) { + if (type == boolean.class) { + return false; + } + if (type == int.class) { + return 0; + } + if (type == long.class) { + return 0L; + } + return null; + } + + /** A command-only result: no columns, no further results. */ + private static PgResultStream commandResult() { + RowMetadata metadata = (RowMetadata) proxy(RowMetadata.class, (p, m, a) -> defaultFor(m.getReturnType())); + return (PgResultStream) proxy(PgResultStream.class, (p, m, a) -> switch (m.getName()) { + case "metadata" -> metadata; + default -> defaultFor(m.getReturnType()); + }); + } + + private org.postgresql.client.core.PgConnection core() { + return (org.postgresql.client.core.PgConnection) + proxy(org.postgresql.client.core.PgConnection.class, (p, m, a) -> { + switch (m.getName()) { + case "setQueryTimeout" -> calls.add("timeout=" + a[0]); + case "execute" -> { + calls.add("execute " + Arrays.asList(a).get(0)); + return commandResult(); + } + default -> { + // nothing else matters here + } + } + return defaultFor(m.getReturnType()); + }); + } + + @Test + void timeoutIsClearedOnceTheExecuteHasRun() throws Exception { + PgConnectionConfig config = + PgConnectionConfig.builder().host("h").user("app").build(); + PgConnection connection = new PgConnection(core(), config, null, null); + try (Statement statement = connection.createStatement()) { + statement.setQueryTimeout(5); + statement.execute("UPDATE t SET x = 1"); + } + assertEquals(List.of("timeout=" + Duration.ofSeconds(5), "execute UPDATE t SET x = 1", "timeout=null"), calls); + } +} diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/JdbcBatchIT.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/JdbcBatchIT.java index c249fa38..fcb84081 100644 --- a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/JdbcBatchIT.java +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/JdbcBatchIT.java @@ -387,4 +387,44 @@ void generatedKeysOfSucceededEntriesSurviveAMidBatchFailure() throws Exception { } } } + + @Test + void pipelinedBatchFailureInsideBeginUnderAutocommitReportsEveryEntryFailed() throws Exception { + // Autocommit is on, but the caller opened a transaction block: the windows that synced before + // the failure are rolled back with it, so none of their counts or keys may be reported. + int n = 400; + try (Connection setup = connect(); + Statement st = setup.createStatement()) { + st.execute("drop table if exists bp3"); + st.execute("create table bp3 (id serial primary key, v int unique)"); + } + try (Connection conn = connect()) { + try (Statement st = conn.createStatement()) { + st.execute("begin"); + } + try (PreparedStatement ps = + conn.prepareStatement("insert into bp3 (v) values (?)", Statement.RETURN_GENERATED_KEYS)) { + for (int i = 0; i < n; i++) { + ps.setInt(1, i == 300 ? 0 : i); + ps.addBatch(); + } + BatchUpdateException e = assertThrows(BatchUpdateException.class, ps::executeBatch); + for (int c : e.getUpdateCounts()) { + assertEquals(Statement.EXECUTE_FAILED, c); + } + try (ResultSet keys = ps.getGeneratedKeys()) { + assertFalse(keys.next()); + } + } + } + // Closing the connection ends the failed transaction block; nothing it held is committed. + try (Connection check = connect(); + Statement st = check.createStatement()) { + try (ResultSet rs = st.executeQuery("select count(*) from bp3")) { + assertTrue(rs.next()); + assertEquals(0, rs.getInt(1)); + } + st.execute("drop table bp3"); + } + } } diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/ManualTransactionUnderAutocommitIT.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/ManualTransactionUnderAutocommitIT.java new file mode 100644 index 00000000..5d89378f --- /dev/null +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/ManualTransactionUnderAutocommitIT.java @@ -0,0 +1,78 @@ +package org.postgresql.client.jdbc.it; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.SQLNonTransientConnectionException; +import java.sql.Statement; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Under autocommit a caller may still open a transaction block with BEGIN. Once a statement in it + * fails, rollback() is refused (autocommit is on), so a typed ROLLBACK, COMMIT or END must reach + * the server and end the block, and anything else gets the server's own 25P02. + */ +class ManualTransactionUnderAutocommitIT extends AbstractJdbcPostgresIT { + + private static void failInsideBegin(Statement st) { + assertThrows(SQLException.class, () -> { + st.execute("begin"); + st.execute("select 1 / 0"); + }); + } + + private static void assertUsable(Statement st) throws SQLException { + try (ResultSet rs = st.executeQuery("select 1")) { + assertTrue(rs.next()); + assertEquals(1, rs.getInt(1)); + } + } + + @ParameterizedTest + @ValueSource(strings = {"rollback", "abort", "commit", "end"}) + void aTypedCommandEndsTheFailedBlock(String command) throws SQLException { + try (Connection con = connect(); + Statement st = con.createStatement()) { + failInsideBegin(st); + st.execute(command); + assertUsable(st); + } + } + + @ParameterizedTest + @ValueSource(strings = {"rollback", "commit"}) + void aPreparedCommandEndsTheFailedBlock(String command) throws SQLException { + try (Connection con = connect(); + Statement st = con.createStatement()) { + failInsideBegin(st); + try (PreparedStatement ps = con.prepareStatement(command)) { + ps.execute(); + } + assertUsable(st); + } + } + + @ParameterizedTest + @ValueSource(strings = {"select 1", "savepoint s1"}) + void otherStatementsGetTheServerError(String sql) throws SQLException { + try (Connection con = connect(); + Statement st = con.createStatement()) { + failInsideBegin(st); + SQLException e = assertThrows(SQLException.class, () -> st.execute(sql)); + // An aborted transaction is not a broken connection: a pool must not evict it. + assertEquals("25P02", e.getSQLState()); + assertFalse( + e instanceof SQLNonTransientConnectionException, + e.getClass().getName()); + st.execute("rollback"); + assertUsable(st); + } + } +} diff --git a/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/SearchPathShadowingIT.java b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/SearchPathShadowingIT.java new file mode 100644 index 00000000..50d919a9 --- /dev/null +++ b/postgresql-client-jdbc/src/test/java/org/postgresql/client/jdbc/it/SearchPathShadowingIT.java @@ -0,0 +1,126 @@ +package org.postgresql.client.jdbc.it; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; +import org.junit.jupiter.api.Test; + +/** + * DatabaseMetaData, ResultSetMetaData and updatable result sets must not run an operator that a + * search_path schema supplies with an exact signature match pg_catalog lacks. Each shadowing + * operator raises, so a catalog query that resolved to one fails the test. + */ +class SearchPathShadowingIT extends AbstractJdbcPostgresIT { + + private static final String SCHEMA = "shadow_jdbc"; + + /** Left type, right type and operator of each shadowed signature. */ + private static final String[][] SHADOWED = { + {"name", "varchar", "~~"}, + {"name", "name", "!~~"}, + {"name", "varchar", "="}, + {"oid", "int4", "="}, + {"oid", "regclass", "="}, + {"regproc", "regproc", "<>"}, + {"name", "name", "||"}, + }; + + private static void exec(Connection con, String sql) throws SQLException { + try (Statement st = con.createStatement()) { + st.execute(sql); + } + } + + private static int drain(ResultSet rs) throws SQLException { + try (rs) { + int rows = 0; + while (rs.next()) { + rows++; + } + return rows; + } + } + + private static Connection shadowedConnection() throws SQLException { + Connection con = connect(); + exec(con, "DROP SCHEMA IF EXISTS " + SCHEMA + " CASCADE"); + exec(con, "CREATE SCHEMA " + SCHEMA); + exec(con, "SET search_path = " + SCHEMA + ", public"); + exec(con, "CREATE TABLE sh_parent (id int4 PRIMARY KEY, label text)"); + exec(con, "CREATE TABLE sh_child (id serial PRIMARY KEY, parent int4 REFERENCES sh_parent)"); + exec(con, "CREATE INDEX sh_child_parent ON sh_child (parent)"); + exec(con, "CREATE TYPE sh_pair AS (a int4, b text)"); + exec(con, "CREATE FUNCTION sh_fn(x int4) RETURNS sh_pair LANGUAGE sql AS $$SELECT x, 'v'::text$$"); + exec(con, "INSERT INTO sh_parent VALUES (1, 'one')"); + for (int i = 0; i < SHADOWED.length; i++) { + String[] s = SHADOWED[i]; + String fn = SCHEMA + ".shadow_" + i; + String returns = "||".equals(s[2]) ? "text" : "bool"; + exec( + con, + "CREATE FUNCTION " + fn + "(" + s[0] + ", " + s[1] + ") RETURNS " + returns + + " LANGUAGE plpgsql AS $$BEGIN RAISE EXCEPTION 'shadowing operator " + s[2] + + " ran'; END$$"); + exec( + con, + "CREATE OPERATOR " + SCHEMA + "." + s[2] + " (LEFTARG = " + s[0] + ", RIGHTARG = " + s[1] + + ", FUNCTION = " + fn + ")"); + } + return con; + } + + @Test + void databaseMetaDataUsesPgCatalogOperators() throws SQLException { + try (Connection con = shadowedConnection()) { + DatabaseMetaData md = con.getMetaData(); + assertTrue(drain(md.getTables(null, SCHEMA, "sh_%", null)) >= 2); + assertTrue(drain(md.getColumns(null, SCHEMA, "sh_parent", "%")) >= 2); + assertTrue(drain(md.getSchemas(null, SCHEMA)) >= 1); + assertEquals(1, drain(md.getPrimaryKeys(null, SCHEMA, "sh_parent"))); + assertEquals(1, drain(md.getImportedKeys(null, SCHEMA, "sh_child"))); + assertEquals(1, drain(md.getExportedKeys(null, SCHEMA, "sh_parent"))); + assertEquals(1, drain(md.getCrossReference(null, SCHEMA, "sh_parent", null, SCHEMA, "sh_child"))); + assertTrue(drain(md.getIndexInfo(null, SCHEMA, "sh_child", false, false)) >= 2); + assertTrue(drain(md.getBestRowIdentifier(null, SCHEMA, "sh_parent", 0, false)) >= 1); + assertTrue(drain(md.getTypeInfo()) > 0); + assertTrue(drain(md.getFunctions(null, SCHEMA, "sh_fn")) >= 1); + assertTrue(drain(md.getFunctionColumns(null, SCHEMA, "sh_fn", "%")) >= 1); + drain(md.getProcedures(null, SCHEMA, "%")); + assertTrue(drain(md.getProcedureColumns(null, SCHEMA, "sh_fn", "%")) >= 1); + drain(md.getColumnPrivileges(null, SCHEMA, "sh_parent", "%")); + drain(md.getTablePrivileges(null, SCHEMA, "sh_%")); + assertTrue(drain(md.getUDTs(null, SCHEMA, "sh_%", null)) >= 1); + assertEquals(2, drain(md.getAttributes(null, SCHEMA, "sh_pair", "%"))); + } + } + + @Test + void resultSetMetaDataUsesPgCatalogOperators() throws SQLException { + try (Connection con = shadowedConnection(); + Statement st = con.createStatement(); + ResultSet rs = st.executeQuery("SELECT id, label FROM sh_parent")) { + ResultSetMetaData md = rs.getMetaData(); + assertEquals("sh_parent", md.getTableName(1)); + assertEquals(SCHEMA, md.getSchemaName(1)); + md.isAutoIncrement(1); + md.isNullable(2); + } + } + + @Test + void updatableResultSetUsesPgCatalogOperators() throws SQLException { + try (Connection con = shadowedConnection(); + Statement st = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); + ResultSet rs = st.executeQuery("SELECT id, label FROM sh_parent")) { + assertTrue(rs.next()); + rs.updateString("label", "uno"); + rs.updateRow(); + } + } +} diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/CompatConnectionView.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/CompatConnectionView.java index f46f0e6d..2524efeb 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/CompatConnectionView.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/CompatConnectionView.java @@ -280,10 +280,12 @@ public String escapeIdentifier(String identifier) throws SQLException { @Override public String escapeLiteral(String literal) throws SQLException { - // Mirrors pgjdbc org.postgresql.core.Utils.escapeLiteral: double any single quote; a NUL byte - // cannot appear. This driver requires standard_conforming_strings=on (SessionBootstrap refuses - // to connect otherwise), so backslashes are never special and are not doubled. Note pgjdbc - // does NOT add surrounding quotes here -- the caller supplies them. + // Mirrors pgjdbc org.postgresql.core.Utils.escapeLiteral: double any single quote, and any + // backslash while standard_conforming_strings is off; a NUL byte cannot appear. The setting + // is read per call: SessionBootstrap refuses "off" only at connect time, and a later SET, a + // function or a role default can still turn it off. Note pgjdbc does NOT add surrounding + // quotes here -- the caller supplies them. + boolean doubleBackslashes = !standardConformingStrings(); StringBuilder out = new StringBuilder(literal.length() + literal.length() / 8); for (int i = 0; i < literal.length(); i++) { char ch = literal.charAt(i); @@ -291,14 +293,22 @@ public String escapeLiteral(String literal) throws SQLException { throw new PSQLException( "Zero bytes may not occur in string parameters.", PSQLState.INVALID_PARAMETER_VALUE); } - if (ch == '\'') { - out.append('\''); + if (ch == '\'' || (ch == '\\' && doubleBackslashes)) { + out.append(ch); } out.append(ch); } return out.toString(); } + private boolean standardConformingStrings() { + try { + return core().sessionState().standardConformingStrings(); + } catch (SQLException e) { + return true; // no core: the bootstrap's guarantee is all there is to go on + } + } + @Override public void cancelQuery() throws SQLException { // Out-of-band cancel on a fresh side connection; safe to call from another thread while this diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java index 3f9cbc9d..1d465d86 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/Driver.java @@ -14,13 +14,17 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Logger; import org.postgresql.PgPropertyMappings.Mapping; import org.postgresql.PgPropertyMappings.Support; +import org.postgresql.client.compat.internal.CompatDriverHooks; +import org.postgresql.client.core.PgConfigurationException; import org.postgresql.client.core.auth.AuthenticationProvider; +import org.postgresql.client.core.internal.jdbc.PercentDecoding; import org.postgresql.client.jdbc.PgDriver; import org.postgresql.client.jdbc.SqlExceptionFactoryRegistry; import org.postgresql.jdbc.PreferQueryMode; @@ -40,9 +44,8 @@ * *

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

Loading this class deregisters the native {@link PgDriver} (which auto-registers itself for * {@code jdbc:postgresql:}) from the {@link DriverManager}, so this compatibility driver is the @@ -73,9 +76,29 @@ public Driver() {} private static volatile Driver registeredDriver; static { + CompatDriverHooks.install(new CompatDriverHooks.Hooks() { + @Override + public Properties translate(Properties pgjdbcProperties) throws SQLException { + return translateProperties(pgjdbcProperties); + } + + @Override + public Connection finishConnection(Connection nativeConnection, Properties pgjdbcProperties) + throws SQLException { + return Driver.finishConnection(nativeConnection, null, pgjdbcProperties); + } + }); // Fail fast if the real pgjdbc is co-present (ADR-0015): two org.postgresql.Driver definitions // on one classpath have undefined resolution order, so no arbitration can make it safe. - requireSinglePostgresqlDriver(driverClassResources()); + Optional> definitions = driverClassResources(Driver.class.getClassLoader()); + if (definitions.isPresent()) { + requireSinglePostgresqlDriver(definitions.get()); + } else { + // Do not block startup on the safety check, but do not skip it silently either: a + // duplicate pgjdbc jar would now go undetected. + LOG.warn("pgjdbc compat: could not enumerate org.postgresql.Driver definitions on the classpath;" + + " the check for a co-present pgjdbc jar (ADR-0015) was skipped"); + } try { // The PSQLException factory is installed lazily on the first compat connection, NOT here: // it is a JVM-global that flattens the native driver's java.sql SQLException subtypes, so @@ -88,17 +111,17 @@ public Driver() {} } /** The classpath URLs defining {@code org.postgresql.Driver}; {@code >1} means a duplicate jar. */ - private static List driverClassResources() { + static Optional> driverClassResources(ClassLoader loader) { List urls = new ArrayList<>(); try { - Enumeration found = Driver.class.getClassLoader().getResources("org/postgresql/Driver.class"); + Enumeration found = loader.getResources("org/postgresql/Driver.class"); while (found.hasMoreElements()) { urls.add(found.nextElement()); } } catch (IOException e) { - return List.of(); // cannot enumerate: do not block startup on the safety check + return Optional.empty(); // cannot enumerate; the caller says so } - return urls; + return Optional.of(urls); } /** @@ -177,6 +200,15 @@ public Connection connect(String url, Properties info) throws SQLException { // first actual compat connection, rather than at class-load: the app is now genuinely using // the compat layer, so taking over the process-wide mapping is expected (A12-M13). installExceptionFactory(); + try { + return connectAccepted(url, info); + } catch (PgConfigurationException e) { + // A malformed %-escape in the URL, found before the native driver (which wraps its own). + throw new PSQLException(e.getMessage(), PSQLState.INVALID_PARAMETER_VALUE, e); + } + } + + private Connection connectAccepted(String url, Properties info) throws SQLException { // authenticationPluginClassName is handled here (emulated): instantiate it, adapt a pgjdbc // AuthenticationPlugin to the core seam, and pass it to the native driver programmatically // rather than forwarding the name as a connection-string key. @@ -203,17 +235,23 @@ public Connection connect(String url, Properties info) throws SQLException { if (rawProperty(url, info, "allowUnencryptedPasswordAuth") == null) { nativeProps.setProperty("allowUnencryptedPasswordAuth", "true"); } - Connection connection = NATIVE.connect(translateUrl(url), nativeProps, provider); - // readOnly is emulated: applied to the connection after it is established. + return finishConnection(NATIVE.connect(translateUrl(url), nativeProps, provider), url, info); + } + + /** + * The steps every compat connection gets once the native driver has connected it: the emulated + * {@code readOnly}, then the pgjdbc vendor-extension ring (N4.3) so {@code unwrap(PGConnection.class)} + * and casts work. Also applied by the pooling and XA sources to each logical handle. + */ + static Connection finishConnection(Connection connection, String url, Properties info) throws SQLException { if (isTruthy(rawProperty(url, info, "readOnly"))) { connection.setReadOnly(true); } - // Install the pgjdbc vendor-extension ring (N4.3) so unwrap(PGConnection.class) and casts work. return CompatConnections.wrap(connection, vendorSettings(url, info)); } /** Seeds the connection's pgjdbc vendor state from the requested connection properties. */ - private VendorSettings vendorSettings(String url, Properties info) { + private static VendorSettings vendorSettings(String url, Properties info) { VendorSettings settings = VendorSettings.defaults(); String mode = rawProperty(url, info, "preferQueryMode"); if (mode != null) { @@ -230,7 +268,7 @@ private VendorSettings vendorSettings(String url, Properties info) { return settings; } - private int intProperty(String url, Properties info, String name, int fallback) { + private static int intProperty(String url, Properties info, String name, int fallback) { String value = rawProperty(url, info, name); if (value == null || value.isEmpty()) { return fallback; @@ -256,8 +294,6 @@ private int intProperty(String url, Properties info, String name, int fallback) */ private static LinkedHashMap translate(LinkedHashMap pgPairs) throws PSQLException { LinkedHashMap coreParams = new LinkedHashMap<>(); - String explicitOptions = null; - String searchPath = null; for (Map.Entry entry : pgPairs.entrySet()) { String name = entry.getKey(); String value = entry.getValue(); @@ -272,39 +308,15 @@ private static LinkedHashMap translate(LinkedHashMap pairs = new LinkedHashMap<>(); - for (String pair : query.split("&")) { - if (pair.isEmpty()) { - continue; - } - int eq = pair.indexOf('='); - String name = eq < 0 ? pair : pair.substring(0, eq); - String value = eq < 0 ? "" : decode(pair.substring(eq + 1)); - pairs.put(name, value); - } StringBuilder out = new StringBuilder(base); char separator = '?'; - for (Map.Entry e : translate(pairs).entrySet()) { + for (Map.Entry e : translate(queryParameters(url)).entrySet()) { out.append(separator).append(e.getKey()).append('=').append(encode(e.getValue())); separator = '&'; } @@ -364,10 +365,19 @@ static String translateUrl(String url) throws PSQLException { * Rejects an unsupported property whose value demands a security property rather than * expressing a preference. {@code gssEncMode=require} is the only such drop today: silently * ignoring it hands the caller a connection with no GSSAPI transport encryption at all, which - * is the failure direction a "require" must never take. Every other unsupported property - * degrades to a warning because dropping it cannot weaken the connection. + * is the failure direction a "require" must never take. {@code service} is refused too: the + * entry may carry sslmode or other settings the connection would otherwise run without. Every + * other unsupported property degrades to a warning because dropping it cannot weaken the + * connection. */ private static void rejectUnsupportedRequirement(String name, String value) throws PSQLException { + if ("service".equals(name) && value != null && !value.isBlank()) { + throw new PSQLException( + "service=" + value + " is not supported: pg-java does not read pg_service.conf, and" + + " connecting without the entry could drop settings such as sslmode. Put the" + + " entry's settings in the URL instead.", + PSQLState.CONNECTION_REJECTED); + } if ("gssEncMode".equals(name) && value != null && "require".equalsIgnoreCase(value.trim())) { throw new PSQLException( "gssEncMode=require demands GSSAPI transport encryption, which pg-java does not" @@ -384,18 +394,37 @@ private static void warnOnce(String name, String message) { } } + /** + * The URL's query parameters, keys and values percent-decoded, as the core parser and + * {@link #parseURL} read them. A repeated key keeps its last value. Both + * the translation and {@link #rawProperty} read this one map: they used to parse separately, one + * first-wins and the other last-wins, so {@code readOnly=false&readOnly=true} meant one thing to + * the connection and the opposite to the emulated read-only switch. + */ + private static LinkedHashMap queryParameters(String url) { + LinkedHashMap pairs = new LinkedHashMap<>(); + int question = url.indexOf('?'); + if (question < 0) { + return pairs; + } + for (String pair : url.substring(question + 1).split("&")) { + if (pair.isEmpty()) { + continue; + } + int eq = pair.indexOf('='); + String name = decode(eq < 0 ? pair : pair.substring(0, eq)); + String value = eq < 0 ? "" : decode(pair.substring(eq + 1)); + pairs.put(name, value); + } + return pairs; + } + /** Reads a raw (untranslated) property value from the URL query or {@code Properties}. */ - private static String rawProperty(String url, Properties info, String name) { + static String rawProperty(String url, Properties info, String name) { if (url != null) { - int question = url.indexOf('?'); - if (question >= 0) { - for (String pair : url.substring(question + 1).split("&")) { - int eq = pair.indexOf('='); - String key = eq < 0 ? pair : pair.substring(0, eq); - if (key.equals(name)) { - return eq < 0 ? "" : decode(pair.substring(eq + 1)); - } - } + Map query = queryParameters(url); + if (query.containsKey(name)) { + return query.get(name); } } return info == null ? null : info.getProperty(name); @@ -410,24 +439,10 @@ private static boolean isTruthy(String value) { return v.isEmpty() || v.equals("true") || v.equals("1") || v.equals("yes") || v.equals("on"); } - // -- Percent-coding (RFC 3986 unreserved set), matching core's decoder. -- + // -- Percent-coding (RFC 3986 unreserved set), decoding shared with core. -- private static String decode(String s) { - if (s.indexOf('%') < 0) { - return s; - } - byte[] bytes = new byte[s.length()]; - int len = 0; - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c == '%' && i + 2 < s.length()) { - bytes[len++] = (byte) Integer.parseInt(s.substring(i + 1, i + 3), 16); - i += 2; - } else { - bytes[len++] = (byte) c; - } - } - return new String(bytes, 0, len, StandardCharsets.UTF_8); + return PercentDecoding.decode(s); } private static String encode(String s) { @@ -512,13 +527,18 @@ public static Properties parseURL(String url, Properties defaults) { } int eq = pair.indexOf('='); String name = eq < 0 ? pair : pair.substring(0, eq); - parsed.setProperty(decode(name), eq < 0 ? "" : decode(pair.substring(eq + 1))); + try { + parsed.setProperty(decode(name), eq < 0 ? "" : decode(pair.substring(eq + 1))); + } catch (PgConfigurationException e) { + return null; // a malformed %-escape makes the URL unacceptable, like a bad port + } } } - if (!parseAuthority(authorityAndPath, parsed)) { + try { + return parseAuthority(authorityAndPath, parsed) ? parsed : null; + } catch (PgConfigurationException e) { return null; } - return parsed; } /** diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgPropertyMappings.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgPropertyMappings.java index 1f81dd0b..26a41f74 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgPropertyMappings.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgPropertyMappings.java @@ -24,9 +24,8 @@ * translator for enum spellings that differ (for example pgjdbc {@code extendedForPrepared} * vs core {@code extended-for-prepared}). *

  • {@link Support#EMULATED} -- not a simple rename; {@link Driver} synthesizes the behavior - * (for example {@code currentSchema} folds into {@code options=-c search_path=...} and - * {@code readOnly} is applied to the connection after connect). Emulated properties are not - * forwarded verbatim. + * (for example {@code readOnly} is applied to the connection after connect). Emulated + * properties are not forwarded verbatim. *
  • {@link Support#UNSUPPORTED} -- recognized as a real pgjdbc property but not yet honored by * pg-java; dropped with a one-time warning rather than forwarded as a bogus server runtime * parameter. @@ -203,9 +202,15 @@ private static String mapReWriteBatchedInserts(String v) { mapped("targetServerType", "targetServerType"); mapped("loadBalanceHosts", "loadBalanceHosts"); + // Sent as its own startup parameter, as pgjdbc does. Folded into options as + // "-c search_path=..." it was split on whitespace by the server, so a value such as + // "public -c work_mem=1GB" set further GUCs. + mapped("currentSchema", "search_path"); + // -- Emulated (synthesized by the Driver, not forwarded verbatim) -- - emulated("currentSchema"); emulated("readOnly"); + // Read into the connection's vendor settings and applied by ServerErrorRedaction. + emulated("logServerErrorDetail"); // -- Recognized but not yet supported (warn + drop) -- unsupported("readOnlyMode"); @@ -285,7 +290,6 @@ private static String mapReWriteBatchedInserts(String v) { // state and the decode context with it (ADR-0011). So our behavior is this property's `true` // setting, unconditionally, and setting it false would not be honored. unsupported("allowEncodingChanges"); - unsupported("logServerErrorDetail"); unsupported("loggerLevel"); unsupported("loggerFile"); unsupported("logUnclosedConnections"); diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgResultSets.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgResultSets.java index 8570db3c..725ee278 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgResultSets.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/PgResultSets.java @@ -209,7 +209,7 @@ private static final class MetaDataHandler implements InvocationHandler { private final HstoreSupport hstore; /** Lazy per-column base names, resolved together from one catalog round trip per table OID. */ - private Map baseColumnNames; + private Map baseColumnNames; MetaDataHandler(ResultSetMetaData delegate, Connection connection, HstoreSupport hstore) { this.delegate = delegate; @@ -318,7 +318,9 @@ private String baseColumnName(int column) throws SQLException { if (source.tableOid() == 0 || source.columnAttributeNumber() <= 0) { return ""; } - int key = source.tableOid() * 31 + source.columnAttributeNumber(); + // Both halves of the pair, packed without overlap: tableOid * 31 + attnum collided (OID 1, + // column 32 and OID 2, column 1), handing one column another's name. + long key = ((long) source.tableOid() << 32) | Integer.toUnsignedLong(source.columnAttributeNumber()); if (baseColumnNames == null) { baseColumnNames = new HashMap<>(); } else { @@ -333,7 +335,8 @@ private String baseColumnName(int column) throws SQLException { } private String lookupBaseColumnName(int tableOid, int attributeNumber) { - String sql = "SELECT attname FROM pg_catalog.pg_attribute WHERE attrelid = ? AND attnum = ?"; + String sql = + "SELECT attname FROM pg_catalog.pg_attribute WHERE attrelid OPERATOR(pg_catalog.=) ? AND attnum = ?"; try (PreparedStatement statement = connection.prepareStatement(sql)) { statement.setInt(1, tableOid); statement.setInt(2, attributeNumber); diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatDriverHooks.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatDriverHooks.java new file mode 100644 index 00000000..1de2cd49 --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatDriverHooks.java @@ -0,0 +1,57 @@ +package org.postgresql.client.compat.internal; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Reaches the compat {@link org.postgresql.Driver}'s package-private behavior from the data sources, + * which live in other packages: its pgjdbc-to-native property translation, and the steps it applies + * to every new connection (the emulated {@code readOnly} and the vendor-extension ring). The + * behavior stays package-private in {@code org.postgresql}, an exported pgjdbc-named package, and + * the driver installs it here when its class initializes; this package is not exported. + */ +public final class CompatDriverHooks { + + /** The driver's own implementations. */ + public interface Hooks { + /** Translates pgjdbc property names and values to the native driver's. */ + Properties translate(Properties pgjdbcProperties) throws SQLException; + + /** Applies what {@code Driver.connect} does to a native connection, given the pgjdbc bag. */ + Connection finishConnection(Connection nativeConnection, Properties pgjdbcProperties) throws SQLException; + } + + private static final AtomicReference HOOKS = new AtomicReference<>(); + + private CompatDriverHooks() {} + + /** Called once by the driver's static initializer; later calls are ignored. */ + public static void install(Hooks hooks) { + HOOKS.compareAndSet(null, hooks); + } + + /** Translates {@code pgjdbcProperties} the way {@code Driver.connect} translates its own. */ + public static Properties translate(Properties pgjdbcProperties) throws SQLException { + return hooks().translate(pgjdbcProperties); + } + + /** Finishes {@code nativeConnection} the way {@code Driver.connect} finishes its own. */ + public static Connection finishConnection(Connection nativeConnection, Properties pgjdbcProperties) + throws SQLException { + return hooks().finishConnection(nativeConnection, pgjdbcProperties); + } + + private static Hooks hooks() { + Hooks installed = HOOKS.get(); + if (installed == null) { + org.postgresql.Driver.isRegistered(); // initializes the driver class, which installs them + installed = HOOKS.get(); + } + if (installed == null) { + throw new IllegalStateException("the compat driver did not install its hooks"); + } + return installed; + } +} diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPooledConnection.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPooledConnection.java new file mode 100644 index 00000000..3940d9b2 --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatPooledConnection.java @@ -0,0 +1,86 @@ +package org.postgresql.client.compat.internal; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.CopyOnWriteArrayList; +import javax.sql.ConnectionEvent; +import javax.sql.ConnectionEventListener; +import javax.sql.PooledConnection; +import javax.sql.StatementEventListener; +import org.jspecify.annotations.Nullable; + +/** + * The compat view of a native {@link PooledConnection}. Each logical handle gets what + * {@code Driver.connect} gives a plain connection -- the emulated {@code readOnly} and the pgjdbc + * vendor-extension ring -- plus pgjdbc's {@code defaultAutoCommit} when the pooling source sets one. + * Connection events are re-fired with this object as their source, since a pool matches events to + * the pooled connection it handed out. + */ +public class CompatPooledConnection implements PooledConnection { + + private final PooledConnection delegate; + private final Properties pgjdbcProperties; + private final @Nullable Boolean defaultAutoCommit; + private final List listeners = new CopyOnWriteArrayList<>(); + + public CompatPooledConnection( + PooledConnection delegate, Properties pgjdbcProperties, @Nullable Boolean defaultAutoCommit) { + this.delegate = delegate; + this.pgjdbcProperties = pgjdbcProperties; + this.defaultAutoCommit = defaultAutoCommit; + delegate.addConnectionEventListener(new ConnectionEventListener() { + @Override + public void connectionClosed(ConnectionEvent event) { + ConnectionEvent ours = new ConnectionEvent(CompatPooledConnection.this); + listeners.forEach(listener -> listener.connectionClosed(ours)); + } + + @Override + public void connectionErrorOccurred(ConnectionEvent event) { + ConnectionEvent ours = new ConnectionEvent(CompatPooledConnection.this, event.getSQLException()); + listeners.forEach(listener -> listener.connectionErrorOccurred(ours)); + } + }); + } + + /** The native pooled connection, for a subclass that exposes more of it. */ + protected final PooledConnection delegate() { + return delegate; + } + + @Override + public Connection getConnection() throws SQLException { + Connection handle = delegate.getConnection(); + if (defaultAutoCommit != null) { + handle.setAutoCommit(defaultAutoCommit); + } + return CompatDriverHooks.finishConnection(handle, pgjdbcProperties); + } + + @Override + public void close() throws SQLException { + delegate.close(); + } + + @Override + public void addConnectionEventListener(ConnectionEventListener listener) { + listeners.add(listener); + } + + @Override + public void removeConnectionEventListener(ConnectionEventListener listener) { + listeners.remove(listener); + } + + @Override + public void addStatementEventListener(StatementEventListener listener) { + delegate.addStatementEventListener(listener); + } + + @Override + public void removeStatementEventListener(StatementEventListener listener) { + delegate.removeStatementEventListener(listener); + } +} diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatTypeInfo.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatTypeInfo.java index 42f12431..f7a7fe30 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatTypeInfo.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatTypeInfo.java @@ -193,8 +193,8 @@ private int lookupOid(String name) throws SQLException { } private String lookupName(int oid) throws SQLException { - try (PreparedStatement statement = - connection.prepareStatement("SELECT typname FROM pg_catalog.pg_type WHERE oid = ?")) { + try (PreparedStatement statement = connection.prepareStatement( + "SELECT typname FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) ?")) { statement.setInt(1, oid); try (ResultSet rows = statement.executeQuery()) { return rows.next() ? rows.getString(1) : null; diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatXAConnection.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatXAConnection.java new file mode 100644 index 00000000..49597718 --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/CompatXAConnection.java @@ -0,0 +1,20 @@ +package org.postgresql.client.compat.internal; + +import java.sql.SQLException; +import java.util.Properties; +import javax.sql.XAConnection; +import javax.transaction.xa.XAResource; + +/** The compat view of a native {@link XAConnection}; see {@link CompatPooledConnection}. */ +public final class CompatXAConnection extends CompatPooledConnection implements XAConnection { + + public CompatXAConnection(XAConnection delegate, Properties pgjdbcProperties) { + // Auto-commit on an XA connection is the transaction manager's business, not a default's. + super(delegate, pgjdbcProperties, null); + } + + @Override + public XAResource getXAResource() throws SQLException { + return ((XAConnection) delegate()).getXAResource(); + } +} diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/HstoreSupport.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/HstoreSupport.java index 146ee0c0..d7754182 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/HstoreSupport.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/client/compat/internal/HstoreSupport.java @@ -68,8 +68,14 @@ public int resolve() { oid = ABSENT; // no core connection will ever appear; do not re-query return oid; } + // The hstore extension's own type: a bare typname match could pick a domain named hstore + // in any schema, another session's temp schema included, and bind Maps with its OID. try (Statement statement = connection.createStatement(); - ResultSet rs = statement.executeQuery("SELECT oid FROM pg_type WHERE typname = 'hstore' LIMIT 1")) { + ResultSet rs = statement.executeQuery("SELECT t.oid FROM pg_catalog.pg_type t" + + " JOIN pg_catalog.pg_depend d ON d.objid = t.oid AND d.deptype = 'e'" + + " AND d.classid OPERATOR(pg_catalog.=) 'pg_catalog.pg_type'::pg_catalog.regclass" + + " JOIN pg_catalog.pg_extension e ON e.oid = d.refobjid" + + " WHERE e.extname = 'hstore' AND t.typname = 'hstore'")) { if (rs.next()) { int resolved = rs.getInt(1); core.registerCodecOverriding(new HstoreCodec(resolved)); @@ -146,8 +152,8 @@ public DynamicType typeForOid(int oid) { if (types.containsKey(oid)) { return types.get(oid); } - try (java.sql.PreparedStatement ps = - connection.prepareStatement("SELECT typname, typtype FROM pg_type WHERE oid = ?")) { + try (java.sql.PreparedStatement ps = connection.prepareStatement( + "SELECT typname, typtype FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) ?")) { ps.setInt(1, oid); try (ResultSet rs = ps.executeQuery()) { DynamicType type = rs.next() diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/CopyManager.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/CopyManager.java index b927d909..7acdb253 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/CopyManager.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/CopyManager.java @@ -26,11 +26,6 @@ public class CopyManager { private final PgConnection core; - // Reused across copyIn(sql, InputStream, ...) calls on this manager so a caller running many bulk - // copies does not allocate a fresh transfer buffer each time (task 16). COPY operations on a - // connection are serial (the connection is busy for the whole copy), so sharing the field is safe. - private byte[] transferBuffer; - /** Builds a manager over the pg-java core connection unwrapped from {@code connection}. */ public CopyManager(Connection connection) throws SQLException { this(connection.unwrap(PgConnection.class)); @@ -77,11 +72,9 @@ public long copyIn(String sql, InputStream from) throws SQLException, IOExceptio /** Copies {@code from} into a {@code COPY ... FROM STDIN} using {@code bufferSize} chunks. */ public long copyIn(String sql, InputStream from, int bufferSize) throws SQLException, IOException { CopyIn op = copyIn(sql); - byte[] buffer = transferBuffer; - if (buffer == null || buffer.length != bufferSize) { - buffer = new byte[bufferSize]; - transferBuffer = buffer; - } + // A fresh buffer per copy. It is handed to the caller's InputStream, so one shared across + // calls was visible to (and overwritten under) any stream that kept a reference to it. + byte[] buffer = new byte[bufferSize]; try { int read; while ((read = from.read(buffer)) >= 0) { diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/PGCopyInputStream.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/PGCopyInputStream.java index 22f9f263..ee9d781f 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/PGCopyInputStream.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/copy/PGCopyInputStream.java @@ -77,7 +77,11 @@ public int read(byte[] b, int off, int siz) throws IOException { return got == 0 && !didReadSomething ? -1 : got; } - /** Returns the current buffered chunk remainder, or the next chunk; {@code null} at the end. */ + /** + * Returns the current buffered chunk remainder, or the next chunk; {@code null} at the end. The + * array belongs to the caller: a whole chunk is handed over as is, but only once it is marked + * consumed, and the stream reads the next chunk into a new array, never into this one. + */ @Override public byte[] readFromCopy() throws SQLException { byte[] result = null; diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java index 9eb4a028..a7b66d90 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/PGConnectionPoolDataSource.java @@ -7,6 +7,7 @@ import java.sql.SQLException; import javax.sql.ConnectionPoolDataSource; import javax.sql.PooledConnection; +import org.postgresql.client.compat.internal.CompatPooledConnection; import org.postgresql.client.jdbc.PgConnectionPoolDataSource; import org.postgresql.ds.common.BaseDataSource; @@ -40,10 +41,11 @@ public PooledConnection getPooledConnection() throws SQLException { @Override public PooledConnection getPooledConnection(String user, String password) throws SQLException { - return configureNative().getPooledConnection(user, password); + return new CompatPooledConnection( + configureNative().getPooledConnection(user, password), pgjdbcProperties(), defaultAutoCommit); } - /** Whether logical connections start in auto-commit mode (accepted for pgjdbc compatibility). */ + /** Whether each logical connection starts in auto-commit mode, as in pgjdbc. */ public void setDefaultAutoCommit(boolean defaultAutoCommit) { this.defaultAutoCommit = defaultAutoCommit; } @@ -52,10 +54,17 @@ public boolean isDefaultAutoCommit() { return defaultAutoCommit; } - /** Builds a native pool source from the current JavaBean state. */ - private PgConnectionPoolDataSource configureNative() { + /** + * Builds a native pool source from the current JavaBean state, the same way + * {@link org.postgresql.xa.PGXADataSource} does. This used to copy only the server, port and + * database, so a pool configured with {@code sslmode=verify-full} fell back to plaintext + * against a server that declined TLS. + */ + private PgConnectionPoolDataSource configureNative() throws SQLException { PgConnectionPoolDataSource ds = new PgConnectionPoolDataSource(); - copyIdentityTo(ds::setServerName, ds::setPortNumber, ds::setDatabaseName); + ds.setUrl(nativeIdentityUrl()); + copyNativePropertiesTo(ds::setProperty); + ds.setLoginTimeout(getLoginTimeout()); return ds; } diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java index 4c85bf79..f4aa13a3 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/BaseDataSource.java @@ -4,7 +4,6 @@ import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; -import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.sql.Connection; @@ -20,7 +19,10 @@ import javax.naming.StringRefAddr; import javax.sql.CommonDataSource; import org.postgresql.PGProperty; +import org.postgresql.client.compat.internal.CompatDriverHooks; +import org.postgresql.client.core.PgConfigurationException; import org.postgresql.client.core.internal.jdbc.ConnectionStringRedaction; +import org.postgresql.client.core.internal.jdbc.PercentDecoding; /** * pgjdbc-compatible {@code org.postgresql.ds.common.BaseDataSource} (N4.3): the common JavaBean @@ -94,11 +96,27 @@ public void setServerNames(String[] serverNames) { String[] sanitized = new String[serverNames.length]; for (int i = 0; i < serverNames.length; i++) { String name = serverNames[i]; - sanitized[i] = name == null || name.isEmpty() ? "localhost" : name.trim(); + sanitized[i] = name == null || name.isEmpty() ? "localhost" : requireHostSyntax(name.trim()); } this.serverNames = sanitized; } + /** + * Refuses a server name that would end the host part of the URL {@link #getUrl()} renders. The + * name is spliced in raw, and {@code h/db?sslmode=disable&x=} would otherwise replace the + * database and swallow the first configured bag property, which can be {@code sslmode}. + * Brackets and colons stay legal for IPv6 literals. + */ + private static String requireHostSyntax(String name) { + for (int i = 0; i < name.length(); i++) { + char c = name.charAt(i); + if (c <= ' ' || "/?#@&=,%\\".indexOf(c) >= 0) { + throw new IllegalArgumentException("invalid character in server name: '" + c + "'"); + } + } + return name; + } + public int getPortNumber() { return portNumbers[0]; } @@ -162,7 +180,7 @@ public String getUrl() { for (String name : properties.stringPropertyNames()) { url.append(first ? '?' : '&'); first = false; - url.append(name).append('=').append(encode(properties.getProperty(name))); + url.append(encode(name)).append('=').append(encode(properties.getProperty(name))); } return url.toString(); } @@ -193,6 +211,20 @@ public void setUrl(String url) { int slash = rest.indexOf('/'); String hosts = slash < 0 ? rest : rest.substring(0, slash); setDatabaseName(slash < 0 ? "" : decode(rest.substring(slash + 1))); + // Userinfo, as the core parser accepts it: left in place, user:password@host became + // part of the server name, or a NumberFormatException quoting the password. + int at = hosts.indexOf('@'); + if (at >= 0) { + String userinfo = hosts.substring(0, at); + hosts = hosts.substring(at + 1); + int colon = userinfo.indexOf(':'); + if (colon >= 0) { + setUser(decode(userinfo.substring(0, colon))); + setPassword(decode(userinfo.substring(colon + 1))); + } else if (!userinfo.isEmpty()) { + setUser(decode(userinfo)); + } + } String[] parts = hosts.split(","); String[] names = new String[parts.length]; int[] ports = new int[parts.length]; @@ -203,7 +235,7 @@ public void setUrl(String url) { int bracket = part.lastIndexOf(']'); if (colon > bracket) { names[i] = part.substring(0, colon); - ports[i] = Integer.parseInt(part.substring(colon + 1)); + ports[i] = parsePort(part.substring(colon + 1)); } else { names[i] = part; ports[i] = 0; @@ -223,13 +255,21 @@ public void setUrl(String url) { continue; } int eq = pair.indexOf('='); - String name = eq < 0 ? pair : pair.substring(0, eq); + String name = decode(eq < 0 ? pair : pair.substring(0, eq)); String value = eq < 0 ? "" : decode(pair.substring(eq + 1)); setProperty(name, value); } } } + private static int parsePort(String text) { + try { + return Integer.parseInt(text); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("invalid port number in URL: '" + text + "'"); + } + } + /** pgjdbc alias for {@link #setUrl(String)}. */ public void setURL(String url) { setUrl(url); @@ -542,38 +582,75 @@ protected Map bagProperties() { } private static String encode(String value) { - return URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8); + // URLEncoder writes a space as '+', which the compat driver's %XX-only decoder (like the + // core parser's) keeps as a literal '+': options=-c a=b reached the server as "-c+a=b". A + // literal '+' is already %2B, so every '+' left is a space. + return URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8) + .replace("+", "%20"); } + /** + * Decodes a URL component as the compat and core drivers do, so a URL means the same here as on + * a connect: only {@code %XX} is special, and a {@code +} stays a {@code +} (URLDecoder made it a + * space). + */ private static String decode(String value) { - return URLDecoder.decode(value, StandardCharsets.UTF_8); + try { + return PercentDecoding.decode(value); + } catch (PgConfigurationException e) { + throw new IllegalArgumentException(e.getMessage(), e); + } } /** - * Copies this bean's connection identity onto a native DataSource via its setters: server - * name, the port only when explicitly set (non-zero, so the native default applies otherwise), - * and database name. Shared by the pooling and XA compat sources. + * The connection identity as a URL for a native DataSource: every server and its port (a zero + * port is left out, so the native default applies) and the database. Shared by the pooling and + * XA compat sources, which used to pass only the first server and port through the native + * setters and so silently dropped the rest of a multi-host configuration. The server names are + * validated by {@link #setServerNames}, so they cannot carry URL syntax. */ - protected void copyIdentityTo( - java.util.function.Consumer serverName, - java.util.function.IntConsumer portNumber, - java.util.function.Consumer databaseName) { - serverName.accept(getServerName()); - if (getPortNumber() != 0) { - portNumber.accept(getPortNumber()); + protected String nativeIdentityUrl() { + StringBuilder url = new StringBuilder("jdbc:postgresql://"); + for (int i = 0; i < serverNames.length; i++) { + if (i > 0) { + url.append(','); + } + url.append(serverNames[i]); + int port = i < portNumbers.length ? portNumbers[i] : 0; + if (port != 0) { + url.append(':').append(port); + } } - databaseName.accept(getDatabaseName()); + return url.append('/').append(encode(databaseName)).toString(); + } + + /** A copy of the property bag, by pgjdbc name, for a subclass that finishes native connections. */ + protected Properties pgjdbcProperties() { + Properties copy = new Properties(); + copy.putAll(properties); + return copy; } /** - * Hands every property in the bag to {@code sink}. A subclass that configures something other - * than a plain {@code Connection} -- the XA source builds a native data source instead of going - * through {@link #getConnection()} -- needs these as well as the identity: dropping them means - * silently ignoring what the caller configured, including {@code sslmode}. + * Hands the bag to {@code sink} as the native driver spells it, after the defaults the compat + * {@link org.postgresql.Driver} gives every connection. A subclass that builds a native data + * source instead of going through {@link #getConnection()} -- the pooling and XA sources -- needs + * this rather than the raw bag: pgjdbc spellings such as {@code requireAuth} and + * {@code channelBinding} would otherwise reach the native driver as unknown keys and go to the + * server as startup parameters, unenforced. */ - protected void copyPropertiesTo(java.util.function.BiConsumer sink) { - for (String name : properties.stringPropertyNames()) { - sink.accept(name, properties.getProperty(name)); + protected void copyNativePropertiesTo(java.util.function.BiConsumer sink) throws SQLException { + Properties translated = CompatDriverHooks.translate(properties); + // pgjdbc reads no environment and sends a password whenever the server asks; an explicit + // bag entry still wins. + if (!translated.containsKey("ignoreEnvironment")) { + sink.accept("ignoreEnvironment", "true"); + } + if (!translated.containsKey("allowUnencryptedPasswordAuth")) { + sink.accept("allowUnencryptedPasswordAuth", "true"); + } + for (String name : translated.stringPropertyNames()) { + sink.accept(name, translated.getProperty(name)); } } } diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/PGObjectFactory.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/PGObjectFactory.java index 899edfc1..273972c1 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/PGObjectFactory.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/ds/common/PGObjectFactory.java @@ -25,9 +25,11 @@ public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtabl // The Reference names the concrete DataSource class (including the legacy // jdbc2.optional aliases and the xa flavor); anything in the BaseDataSource // family restores the same way. Unknown classes yield null per the JNDI contract. + // initialize=false: a class outside the family must not run its static initializer just + // by being named in a Reference. Class klass; try { - klass = Class.forName(ref.getClassName()); + klass = Class.forName(ref.getClassName(), false, PGObjectFactory.class.getClassLoader()); } catch (ClassNotFoundException e) { return null; } diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/HStoreConverter.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/HStoreConverter.java index 0de7a259..25d89b4a 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/HStoreConverter.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/HStoreConverter.java @@ -16,8 +16,22 @@ public final class HStoreConverter { private HStoreConverter() {} - /** Parses the server's hstore text form into a map; a {@code NULL} value becomes Java null. */ + /** + * Parses the server's hstore text form into a map; a {@code NULL} value becomes Java null. + * + * @throws IllegalArgumentException if the text is truncated + */ public static Map fromString(String s) { + try { + return parse(s); + } catch (IndexOutOfBoundsException e) { + // Text cut off inside a token. The signature allows no checked exception, so report it + // as the bad argument it is rather than as an index error from deep in the parser. + throw new IllegalArgumentException("malformed hstore text: truncated", e); + } + } + + private static Map parse(String s) { Map result = new HashMap<>(); int length = s.length(); StringBuilder sb = new StringBuilder(); diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/ObjectFactory.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/ObjectFactory.java index f9efe57a..5cb81c1d 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/ObjectFactory.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/ObjectFactory.java @@ -29,7 +29,8 @@ public static T instantiate( Class expectedClass, String classname, Properties info, boolean tryString, String stringarg) throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { - Class loaded = Class.forName(classname, true, resolveClassLoader(expectedClass)); + // initialize=false: the static initializer must not run either, until the type check passes. + Class loaded = Class.forName(classname, false, resolveClassLoader(expectedClass)); if (!expectedClass.isAssignableFrom(loaded)) { throw new ClassCastException( "the class " + classname + " is not a " + expectedClass.getName() + ", so it was not instantiated"); diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/PGInterval.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/PGInterval.java index 3468fedf..8fec93ca 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/PGInterval.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/util/PGInterval.java @@ -91,10 +91,16 @@ public void setValue(String value) throws SQLException { if (text.isEmpty()) { return; } - if (text.charAt(0) == 'P') { - parseIso8601(text); - } else { - parseTraditional(text); + try { + if (text.charAt(0) == 'P') { + parseIso8601(text); + } else { + parseTraditional(text); + } + } catch (NumberFormatException | IndexOutOfBoundsException e) { + // A quantity that is not a number, or text cut off mid-token: still bad input, which + // this method reports as an SQLException. + throw new SQLException("malformed interval: " + text, e); } } diff --git a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java index 53e43748..7e9711dc 100644 --- a/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java +++ b/postgresql-client-pgjdbc-compat/src/main/java/org/postgresql/xa/PGXADataSource.java @@ -3,6 +3,7 @@ import java.sql.SQLException; import javax.sql.XAConnection; import javax.sql.XADataSource; +import org.postgresql.client.compat.internal.CompatXAConnection; import org.postgresql.client.jdbc.PgXADataSource; import org.postgresql.ds.common.BaseDataSource; @@ -30,13 +31,13 @@ public XAConnection getXAConnection() throws SQLException { @Override public XAConnection getXAConnection(String user, String password) throws SQLException { - return configureNative().getXAConnection(user, password); + return new CompatXAConnection(configureNative().getXAConnection(user, password), pgjdbcProperties()); } /** - * Builds a native XA source from the current JavaBean state: the identity, everything in the - * property bag, and the defaults the compat {@link org.postgresql.Driver} applies to an - * ordinary connection. + * Builds a native XA source from the current JavaBean state: the identity, the property bag + * translated to native spellings, and the defaults the compat {@link org.postgresql.Driver} + * applies to an ordinary connection. * *

    The bag matters. This used to copy the server, port and database and nothing else, so an * XA source configured with {@code sslmode=verify-full} connected on the default policy @@ -45,14 +46,11 @@ public XAConnection getXAConnection(String user, String password) throws SQLExce * rather than going through {@code Driver.connect}, and a drop-in that behaves one way for * {@code getConnection} and another for {@code getXAConnection} is not a drop-in. */ - private PgXADataSource configureNative() { + private PgXADataSource configureNative() throws SQLException { PgXADataSource ds = new PgXADataSource(); - copyIdentityTo(ds::setServerName, ds::setPortNumber, ds::setDatabaseName); - // pgjdbc reads no environment and sends a password whenever the server asks; the compat - // driver matches both, and so must this path. Set first, so an explicit bag entry wins. - ds.setProperty("ignoreEnvironment", "true"); - ds.setProperty("allowUnencryptedPasswordAuth", "true"); - copyPropertiesTo(ds::setProperty); + ds.setUrl(nativeIdentityUrl()); + copyNativePropertiesTo(ds::setProperty); + ds.setLoginTimeout(getLoginTimeout()); return ds; } } diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/BaseColumnNameCacheTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/BaseColumnNameCacheTest.java new file mode 100644 index 00000000..e7f9eb52 --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/BaseColumnNameCacheTest.java @@ -0,0 +1,76 @@ +package org.postgresql; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Proxy; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.ColumnMetadata; +import org.postgresql.client.core.RowMetadata; + +/** + * getBaseColumnName caches catalog answers by the (table OID, attnum) pair; two columns whose pairs + * differ must never share an entry, which tableOid * 31 + attnum did for OID 1/attnum 32 and OID 2/attnum 1. + */ +class BaseColumnNameCacheTest { + + @SuppressWarnings("unchecked") + private static T proxy(Class type, InvocationHandler handler) { + return (T) + Proxy.newProxyInstance(BaseColumnNameCacheTest.class.getClassLoader(), new Class[] {type}, handler); + } + + private static ColumnMetadata column(int tableOid, int attnum) { + return proxy(ColumnMetadata.class, (p, m, a) -> switch (m.getName()) { + case "tableOid" -> tableOid; + case "columnAttributeNumber" -> attnum; + default -> null; + }); + } + + /** Answers the pg_attribute lookup with a name naming the pair it was asked about. */ + private static Connection catalog() { + return proxy(Connection.class, (p, m, a) -> { + if (!m.getName().equals("prepareStatement")) { + return null; + } + int[] bound = new int[2]; + return proxy(PreparedStatement.class, (ps, pm, pa) -> switch (pm.getName()) { + case "setInt" -> { + bound[(Integer) pa[0] - 1] = (Integer) pa[1]; + yield null; + } + case "executeQuery" -> { + boolean[] read = {false}; + yield proxy(ResultSet.class, (r, rm, ra) -> switch (rm.getName()) { + case "next" -> !read[0] && (read[0] = true); + case "getString" -> "oid" + bound[0] + "_att" + bound[1]; + default -> null; + }); + } + default -> null; + }); + }); + } + + @Test + void pairsThatUsedToCollideGetTheirOwnNames() throws Exception { + RowMetadata row = proxy( + RowMetadata.class, + (p, m, a) -> + m.getName().equals("column") ? ((Integer) a[0] == 1 ? column(1, 32) : column(2, 1)) : null); + ResultSetMetaData delegate = proxy(ResultSetMetaData.class, (p, m, a) -> switch (m.getName()) { + case "isWrapperFor" -> a[0] == RowMetadata.class; + case "unwrap" -> row; + default -> null; + }); + PGResultSetMetaData md = (PGResultSetMetaData) PgResultSets.wrapMetaData(delegate, catalog(), null); + + assertEquals("oid1_att32", md.getBaseColumnName(1)); + assertEquals("oid2_att1", md.getBaseColumnName(2)); + } +} diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverParseUrlTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverParseUrlTest.java index 73d9cfe5..cb8df924 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverParseUrlTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverParseUrlTest.java @@ -1,8 +1,11 @@ package org.postgresql; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import java.sql.SQLException; import java.util.Properties; import org.junit.jupiter.api.Test; @@ -86,4 +89,24 @@ void reportsNullForAUrlItDoesNotAccept() { assertNull(Driver.parseURL("jdbc:postgresql://localhost:not-a-port/test", null)); assertNull(Driver.parseURL("jdbc:postgresql://localhost:99999/test", null)); } + + @Test + void decodesEscapesWithoutMangling() { + Properties p = Driver.parseURL("jdbc:postgresql://h/caf\u00e9%20db?ApplicationName=\u00fc%2Bx", null); + assertEquals("caf\u00e9 db", database(p)); + assertEquals("\u00fc+x", p.getProperty("ApplicationName")); + } + + @Test + void reportsNullForAMalformedEscape() { + assertNull(Driver.parseURL("jdbc:postgresql://h/db?password=a%zz", null)); + assertNull(Driver.parseURL("jdbc:postgresql://h/d%4", null)); + } + + @Test + void connectRefusesAMalformedEscapeAsSqlException() { + SQLException e = assertThrows(SQLException.class, () -> new Driver() + .connect("jdbc:postgresql://127.0.0.1:1/db?password=a%zz", new Properties())); + assertFalse(e.getMessage().contains("a%zz"), e.getMessage()); + } } diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java index 16845646..72b79cf8 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/DriverTest.java @@ -8,13 +8,17 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.IOException; import java.net.URI; import java.net.URL; import java.sql.DriverManager; +import java.util.Arrays; +import java.util.Enumeration; import java.util.List; import java.util.Properties; import org.junit.jupiter.api.Test; import org.postgresql.client.jdbc.PgDriver; +import org.postgresql.ds.PGSimpleDataSource; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; @@ -86,6 +90,19 @@ void gssEncModeRequireIsRefusedRatherThanDropped() throws Exception { assertThrows(PSQLException.class, () -> Driver.translateUrl("jdbc:postgresql://h/db?gssEncMode=require")); } + @Test + void serviceIsRefusedRatherThanDropped() throws Exception { + Properties info = new Properties(); + info.setProperty("user", "bob"); + info.setProperty("service", "prod"); + + PSQLException e = assertThrows(PSQLException.class, () -> Driver.translateProperties(info)); + assertTrue(e.getMessage().contains("service=prod"), e.getMessage()); + assertEquals(PSQLState.CONNECTION_REJECTED.getState(), e.getSQLState()); + + assertThrows(PSQLException.class, () -> Driver.translateUrl("jdbc:postgresql://h/db?service=prod")); + } + @Test void ignoreEnvironmentDefaultsOnForCompat() throws Exception { // pgjdbc reads no PG* environment, so its drop-in must not either: inheriting PGSSLMODE or @@ -166,25 +183,28 @@ void rewriteBatchUsingArraysPassesThroughUnderItsNativeName() throws Exception { } @Test - void currentSchemaFoldsIntoOptions() throws Exception { + void currentSchemaIsSentAsSearchPath() throws Exception { Properties info = new Properties(); info.setProperty("currentSchema", "myschema"); Properties core = Driver.translateProperties(info); - assertEquals("-c search_path=myschema", core.getProperty("options")); + assertEquals("myschema", core.getProperty("search_path")); assertNull(core.getProperty("currentSchema")); + assertNull(core.getProperty("options")); } @Test - void currentSchemaMergesWithExplicitOptions() throws Exception { + void currentSchemaCannotSmuggleOptions() throws Exception { + // Folded into options, the server split the value on whitespace and applied each -c. Properties info = new Properties(); info.setProperty("options", "-c statement_timeout=1000"); - info.setProperty("currentSchema", "app"); + info.setProperty("currentSchema", "public -c work_mem=1GB"); Properties core = Driver.translateProperties(info); - assertEquals("-c statement_timeout=1000 -c search_path=app", core.getProperty("options")); + assertEquals("-c statement_timeout=1000", core.getProperty("options")); + assertEquals("public -c work_mem=1GB", core.getProperty("search_path")); } @Test @@ -209,11 +229,70 @@ void translatesUrlQueryNamesAndPreservesBase() throws Exception { } @Test - void translatesUrlValuesAndFoldsCurrentSchema() throws Exception { + void translatesUrlValues() throws Exception { String translated = Driver.translateUrl("jdbc:postgresql://h/db?preferQueryMode=extendedForPrepared"); assertEquals("jdbc:postgresql://h/db?preferQueryMode=extended-for-prepared", translated); } + @Test + void repeatedUrlKeysResolveTheSameWayForTranslationAndEmulation() throws Exception { + // readOnly is emulated from the raw URL while sslmode goes through the translation; a + // repeated key has to mean the same thing to both, and that is the last value. + String url = "jdbc:postgresql://h/db?readOnly=false&sslmode=disable&readOnly=true&sslmode=require"; + assertEquals("true", Driver.rawProperty(url, null, "readOnly")); + assertEquals("require", Driver.rawProperty(url, null, "sslmode")); + assertEquals("jdbc:postgresql://h/db?sslmode=require", Driver.translateUrl(url)); + } + + @Test + void dataSourceUrlValuesKeepTheirSpaces() throws Exception { + PGSimpleDataSource ds = new PGSimpleDataSource(); + ds.setOptions("-c statement_timeout=5s"); + ds.setApplicationName("a+b c"); + + Properties parsed = Driver.parseURL(Driver.translateUrl(ds.getUrl()), null); + + assertEquals("-c statement_timeout=5s", parsed.getProperty("options")); + assertEquals("a+b c", parsed.getProperty("application_name")); + } + + @Test + void percentEncodedKeysAreDecoded() throws Exception { + String url = "jdbc:postgresql://h/db?%73slmode=require&%72eadOnly=true"; + assertEquals("jdbc:postgresql://h/db?sslmode=require", Driver.translateUrl(url)); + assertEquals("true", Driver.rawProperty(url, null, "readOnly")); + } + + @Test + void logServerErrorDetailIsEmulatedNotDropped() throws Exception { + // The compat driver honors it (ServerErrorRedaction), so it must not be classed unsupported, + // which warned on every use, and must not be forwarded to core as a startup parameter. + assertEquals( + PgPropertyMappings.Support.EMULATED, + PgPropertyMappings.get("logServerErrorDetail").support()); + Properties info = new Properties(); + info.setProperty("logServerErrorDetail", "false"); + assertEquals(0, Driver.translateProperties(info).size()); + assertTrue(Arrays.stream(new Driver().getPropertyInfo("jdbc:postgresql://h/db", null)) + .anyMatch(p -> p.name.equals("logServerErrorDetail"))); + } + + @Test + void anUnreadableClasspathIsReportedNotTakenAsClean() { + // An IOException from getResources used to read as "no duplicate", skipping the check silently. + ClassLoader failing = new ClassLoader(null) { + @Override + public Enumeration getResources(String name) throws IOException { + throw new IOException("unreadable classpath entry"); + } + }; + assertTrue(Driver.driverClassResources(failing).isEmpty()); + assertTrue(Driver.driverClassResources(Driver.class.getClassLoader()) + .orElseThrow() + .size() + >= 1); + } + @Test void urlWithoutQueryIsUnchanged() throws Exception { assertEquals("jdbc:postgresql://h/db", Driver.translateUrl("jdbc:postgresql://h/db")); diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/NativeImageMetadataTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/NativeImageMetadataTest.java index d893d987..38f95237 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/NativeImageMetadataTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/NativeImageMetadataTest.java @@ -46,7 +46,7 @@ void reflectConfigNamesTheCompatDriver() throws Exception { @Test void resourceConfigCoversTheDriverClassLookup() throws Exception { - // Driver.driverClassResources() enumerates this resource for the duplicate-jar check; a + // Driver.driverClassResources(ClassLoader) enumerates this resource for the duplicate-jar check; a // native image only sees classpath resources that are explicitly registered. String json = readResource(BASE + "resource-config.json"); assertTrue( diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/PgConnectionCompatTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/PgConnectionCompatTest.java index 211df436..816866f3 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/PgConnectionCompatTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/PgConnectionCompatTest.java @@ -12,11 +12,13 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; import java.sql.Array; import java.sql.Connection; import java.sql.SQLException; import org.junit.jupiter.api.Test; import org.postgresql.client.core.PgConnection; +import org.postgresql.client.core.SessionState; /** * Unit coverage for the pgjdbc {@link PGConnection} vendor ring (N4.3): proxy wiring, {@code unwrap}, @@ -106,6 +108,33 @@ void escapeLiteralDoublesQuotesWithoutSurroundingQuotes() throws SQLException { assertThrows(SQLException.class, () -> pg.escapeLiteral("bad\0value")); } + @Test + void escapeLiteralDoublesBackslashesWhenStandardConformingStringsIsOff() throws SQLException { + // SessionBootstrap refuses "off" only at connect time; a later SET can still turn it off, + // and an undoubled backslash would then escape the caller's closing quote. + FakeConnection fake = new FakeConnection(); + fake.core = coreWithStandardConformingStrings(false); + PGConnection pg = (PGConnection) CompatConnections.wrap(fakeConnection(fake)); + + assertEquals("\\\\'' || 1; --", pg.escapeLiteral("\\' || 1; --")); + assertEquals("O''Brien", pg.escapeLiteral("O'Brien")); + + fake.core = coreWithStandardConformingStrings(true); + PGConnection on = (PGConnection) CompatConnections.wrap(fakeConnection(fake)); + assertEquals("\\'' || 1; --", on.escapeLiteral("\\' || 1; --")); + } + + private static PgConnection coreWithStandardConformingStrings(boolean on) { + SessionState state = new SessionState(null, StandardCharsets.UTF_8, true, "UTC", "ISO, MDY", on); + return (PgConnection) Proxy.newProxyInstance( + PgConnectionCompatTest.class.getClassLoader(), new Class[] {PgConnection.class}, (p, m, a) -> { + if (m.getName().equals("sessionState")) { + return state; + } + throw new UnsupportedOperationException(m.getName()); + }); + } + @Test void vendorSettingsRoundTripAndSeedFromDefaults() throws SQLException { PGConnection pg = (PGConnection) CompatConnections.wrap(fakeConnection(new FakeConnection())); @@ -180,9 +209,13 @@ private static Connection fakeConnection(FakeConnection handler) { PgConnectionCompatTest.class.getClassLoader(), new Class[] {Connection.class}, handler); } - /** A minimal {@link Connection} stand-in that records calls and refuses every {@code unwrap}. */ + /** + * A minimal {@link Connection} stand-in that records calls and refuses every {@code unwrap}, + * except to {@link PgConnection} when a {@link #core} is set. + */ private static final class FakeConnection implements InvocationHandler { + PgConnection core; String lastMethod; Object[] lastArgs; String lastArrayType; @@ -198,7 +231,12 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl lastArrayElements = (Object[]) args[1]; return (Array) null; } - case "unwrap" -> throw new SQLException("not a wrapper for " + args[0]); + case "unwrap" -> { + if (core != null && args[0] == PgConnection.class) { + return core; + } + throw new SQLException("not a wrapper for " + args[0]); + } case "isWrapperFor" -> { return false; } diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/client/compat/internal/CompatPooledConnectionTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/client/compat/internal/CompatPooledConnectionTest.java new file mode 100644 index 00000000..54d452df --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/client/compat/internal/CompatPooledConnectionTest.java @@ -0,0 +1,98 @@ +package org.postgresql.client.compat.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertSame; + +import java.lang.reflect.Proxy; +import java.sql.Connection; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import javax.sql.ConnectionEvent; +import javax.sql.ConnectionEventListener; +import javax.sql.PooledConnection; +import org.junit.jupiter.api.Test; +import org.postgresql.PGConnection; + +/** + * Logical handles from the compat pooling and XA sources get what {@code Driver.connect} gives a + * plain connection, plus pgjdbc's {@code defaultAutoCommit}, and events name the compat object. + */ +class CompatPooledConnectionTest { + + /** Records the calls made on the native logical handle. */ + private final List calls = new ArrayList<>(); + + private ConnectionEventListener nativeListener; + + private Connection nativeHandle() { + return (Connection) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] {Connection.class}, (proxy, method, args) -> { + if (method.getName().startsWith("set")) { + calls.add(method.getName() + "=" + args[0]); + } + return switch (method.getName()) { + case "hashCode" -> System.identityHashCode(proxy); + case "equals" -> proxy == args[0]; + default -> method.getReturnType() == boolean.class ? false : null; + }; + }); + } + + private PooledConnection nativePooled() { + return (PooledConnection) Proxy.newProxyInstance( + getClass().getClassLoader(), new Class[] {PooledConnection.class}, (proxy, method, args) -> { + switch (method.getName()) { + case "getConnection" -> { + return nativeHandle(); + } + case "addConnectionEventListener" -> nativeListener = (ConnectionEventListener) args[0]; + default -> { + // nothing else is exercised + } + } + return null; + }); + } + + @Test + void handlesCarryTheVendorRingReadOnlyAndAutoCommit() throws Exception { + Properties bag = new Properties(); + bag.setProperty("readOnly", "true"); + CompatPooledConnection pooled = new CompatPooledConnection(nativePooled(), bag, false); + + Connection handle = pooled.getConnection(); + + assertInstanceOf(PGConnection.class, handle); + assertEquals(List.of("setAutoCommit=false", "setReadOnly=true"), calls); + } + + @Test + void noDefaultAutoCommitLeavesTheHandleAlone() throws Exception { + new CompatPooledConnection(nativePooled(), new Properties(), null).getConnection(); + assertEquals(List.of(), calls); + } + + @Test + void eventsNameTheCompatPooledConnection() { + CompatPooledConnection pooled = new CompatPooledConnection(nativePooled(), new Properties(), null); + List sources = new ArrayList<>(); + pooled.addConnectionEventListener(new ConnectionEventListener() { + @Override + public void connectionClosed(ConnectionEvent event) { + sources.add(event.getSource()); + } + + @Override + public void connectionErrorOccurred(ConnectionEvent event) { + sources.add(event.getSource()); + } + }); + + nativeListener.connectionClosed(new ConnectionEvent(nativePooled())); + + assertEquals(1, sources.size()); + assertSame(pooled, sources.get(0)); + } +} diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/copy/CopyBufferOwnershipTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/copy/CopyBufferOwnershipTest.java new file mode 100644 index 00000000..52e9db3f --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/copy/CopyBufferOwnershipTest.java @@ -0,0 +1,57 @@ +package org.postgresql.copy; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.PgConnection; +import org.postgresql.client.core.PgCopyInStream; + +/** Copy buffers handed to caller code are not reused behind its back. */ +class CopyBufferOwnershipTest { + + private static Object defaultFor(Class type) { + return type == long.class ? 0L : type == int.class ? 0 : type == boolean.class ? false : null; + } + + private static PgConnection core() { + PgCopyInStream in = (PgCopyInStream) Proxy.newProxyInstance( + CopyBufferOwnershipTest.class.getClassLoader(), + new Class[] {PgCopyInStream.class}, + (p, m, a) -> defaultFor(m.getReturnType())); + return (PgConnection) Proxy.newProxyInstance( + CopyBufferOwnershipTest.class.getClassLoader(), + new Class[] {PgConnection.class}, + (p, m, a) -> m.getName().equals("copyIn") ? in : defaultFor(m.getReturnType())); + } + + @Test + void copyInBufferIsNotSharedAcrossCalls() throws Exception { + List seen = new ArrayList<>(); + CopyManager manager = new CopyManager(core()); + manager.copyIn("COPY t FROM STDIN", retaining(new byte[] {1, 2, 3}, seen), 8); + manager.copyIn("COPY t FROM STDIN", retaining(new byte[] {9, 9, 9}, seen), 8); + + assertNotSame(seen.get(0), seen.get(1)); + assertArrayEquals(new byte[] {1, 2, 3}, Arrays.copyOf(seen.get(0), 3), "the first copy's buffer was reused"); + } + + /** An InputStream that keeps a reference to every buffer it is asked to fill. */ + private static InputStream retaining(byte[] data, List seen) { + return new ByteArrayInputStream(data) { + @Override + public int read(byte[] b, int off, int len) { + if (seen.isEmpty() || seen.get(seen.size() - 1) != b) { + seen.add(b); + } + return super.read(b, off, len); + } + }; + } +} diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourceMultiHostTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourceMultiHostTest.java new file mode 100644 index 00000000..3e64f684 --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourceMultiHostTest.java @@ -0,0 +1,88 @@ +package org.postgresql.ds; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.function.Executable; +import org.postgresql.ds.common.BaseDataSource; +import org.postgresql.xa.PGXADataSource; + +/** + * The pooling and XA sources pass the whole host list to the native driver: with the first host + * down, the connection must move on to the second instead of failing on the only host it was given. + */ +@Timeout(30) +class DataSourceMultiHostTest { + + private static final byte[] FATAL = fatal(); + + private static byte[] fatal() { + byte[] body = "SFATAL\0C28000\0Mstop\0\0".getBytes(StandardCharsets.US_ASCII); + return ByteBuffer.allocate(5 + body.length) + .put((byte) 'E') + .putInt(4 + body.length) + .put(body) + .array(); + } + + @Test + void connectionPoolDataSourceTriesTheSecondHost() throws Exception { + PGConnectionPoolDataSource ds = new PGConnectionPoolDataSource(); + assertReachesSecondHost(ds, ds::getPooledConnection); + } + + @Test + void xaDataSourceTriesTheSecondHost() throws Exception { + PGXADataSource ds = new PGXADataSource(); + assertReachesSecondHost(ds, ds::getXAConnection); + } + + private static void assertReachesSecondHost(BaseDataSource ds, Executable connect) throws Exception { + int deadPort; + try (ServerSocket probe = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + deadPort = probe.getLocalPort(); // closed again before the connect, so nothing listens + } + AtomicBoolean reached = new AtomicBoolean(); + try (ServerSocket second = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + Thread acceptor = Thread.ofVirtual().start(() -> answerWithFatal(second, reached)); + ds.setServerNames(new String[] {"127.0.0.1", "127.0.0.1"}); + ds.setPortNumbers(new int[] {deadPort, second.getLocalPort()}); + ds.setDatabaseName("db"); + ds.setUser("alice"); + ds.setSslMode("disable"); + ds.setLoginTimeout(5); + + assertThrows(SQLException.class, connect); + second.close(); + acceptor.join(5000); + } + assertTrue(reached.get(), "the second host never saw a startup message"); + } + + private static void answerWithFatal(ServerSocket server, AtomicBoolean reached) { + try (Socket socket = server.accept()) { + socket.setSoTimeout(5000); + DataInputStream in = new DataInputStream(socket.getInputStream()); + int length = in.readInt(); + in.readFully(new byte[length - 4]); + reached.set(true); + OutputStream out = socket.getOutputStream(); + out.write(FATAL); + out.flush(); + } catch (IOException e) { + // the listener was closed without a connection, which the assertion reports + } + } +} diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourcePropertyTranslationTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourcePropertyTranslationTest.java new file mode 100644 index 00000000..eb967f88 --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourcePropertyTranslationTest.java @@ -0,0 +1,98 @@ +package org.postgresql.ds; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.sql.SQLException; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.function.Executable; +import org.postgresql.ds.common.BaseDataSource; +import org.postgresql.xa.PGXADataSource; + +/** + * The pooling and XA sources build a native data source directly, so they must translate the + * pgjdbc property spellings as the compat driver does: an untranslated {@code requireAuth} reached + * the native driver as an unknown key and was sent to the server instead of being enforced. + */ +@Timeout(30) +class DataSourcePropertyTranslationTest { + + private static final int SSL_REQUEST_CODE = 80877103; + + @Test + void connectionPoolDataSourceEnforcesRequireAuth() throws Exception { + PGConnectionPoolDataSource ds = new PGConnectionPoolDataSource(); + assertRefusesCleartext(ds, ds::getPooledConnection); + } + + @Test + void xaDataSourceEnforcesRequireAuth() throws Exception { + PGXADataSource ds = new PGXADataSource(); + assertRefusesCleartext(ds, ds::getXAConnection); + } + + @Test + void simpleDataSourceEnforcesRequireAuth() throws Exception { + PGSimpleDataSource ds = new PGSimpleDataSource(); + assertRefusesCleartext(ds, ds::getConnection); + } + + private static void assertRefusesCleartext(BaseDataSource ds, Executable connect) throws Exception { + AtomicBoolean passwordSent = new AtomicBoolean(); + try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + Thread acceptor = Thread.ofVirtual().start(() -> askForCleartext(server, passwordSent)); + ds.setServerName("127.0.0.1"); + ds.setPortNumber(server.getLocalPort()); + ds.setDatabaseName("db"); + ds.setUser("alice"); + ds.setPassword("secret"); + ds.setSslMode("disable"); + ds.setProperty("requireAuth", "scram-sha-256"); + ds.setLoginTimeout(5); + + SQLException e = assertThrows(SQLException.class, connect); + server.close(); + assertFalse(passwordSent.get(), "the password reached the server"); + assertTrue(String.valueOf(e.getMessage()).contains("require_auth"), String.valueOf(e.getMessage())); + acceptor.join(5000); + } + } + + /** Answers the startup message with AuthenticationCleartextPassword and records a reply. */ + private static void askForCleartext(ServerSocket server, AtomicBoolean passwordSent) { + while (!server.isClosed()) { + try (Socket socket = server.accept()) { + socket.setSoTimeout(5000); + DataInputStream in = new DataInputStream(socket.getInputStream()); + OutputStream out = socket.getOutputStream(); + int length = in.readInt(); + int code = in.readInt(); + in.readFully(new byte[length - 8]); + if (code == SSL_REQUEST_CODE) { + continue; // sslmode=disable sends none; anything else is not this test's concern + } + out.write(ByteBuffer.allocate(9) + .put((byte) 'R') + .putInt(8) + .putInt(3) + .array()); + out.flush(); + if (in.read() == 'p') { + passwordSent.set(true); + } + } catch (IOException e) { + // The client hung up, or the test closed the listener. + } + } + } +} diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourceTlsPolicyTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourceTlsPolicyTest.java new file mode 100644 index 00000000..000b1b6d --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/DataSourceTlsPolicyTest.java @@ -0,0 +1,108 @@ +package org.postgresql.ds; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.DataInputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.sql.SQLException; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.function.Executable; +import org.postgresql.ds.common.BaseDataSource; +import org.postgresql.xa.PGXADataSource; + +/** + * Every compat data source honors the configured {@code sslmode}: against a server that declines + * TLS, {@code sslmode=require} must refuse before a plaintext startup message is sent. + */ +@Timeout(30) +class DataSourceTlsPolicyTest { + + private static final int SSL_REQUEST_CODE = 80877103; + private static final byte[] FATAL = fatal(); + + private static byte[] fatal() { + byte[] body = "SFATAL\0C28000\0Mstop\0\0".getBytes(StandardCharsets.US_ASCII); + return ByteBuffer.allocate(5 + body.length) + .put((byte) 'E') + .putInt(4 + body.length) + .put(body) + .array(); + } + + @Test + void simpleDataSourceRefusesPlaintext() throws Exception { + PGSimpleDataSource ds = new PGSimpleDataSource(); + assertRefusesPlaintext(ds, ds::getConnection); + } + + @Test + void connectionPoolDataSourceRefusesPlaintext() throws Exception { + PGConnectionPoolDataSource ds = new PGConnectionPoolDataSource(); + assertRefusesPlaintext(ds, ds::getPooledConnection); + } + + @Test + void xaDataSourceRefusesPlaintext() throws Exception { + PGXADataSource ds = new PGXADataSource(); + assertRefusesPlaintext(ds, ds::getXAConnection); + } + + private static void assertRefusesPlaintext(BaseDataSource ds, Executable connect) throws Exception { + AtomicBoolean startupSent = new AtomicBoolean(); + try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + Thread acceptor = Thread.ofVirtual().start(() -> declineTls(server, startupSent)); + ds.setServerName("127.0.0.1"); + ds.setPortNumber(server.getLocalPort()); + ds.setDatabaseName("db"); + ds.setUser("alice"); + ds.setPassword("secret"); + ds.setSslMode("require"); + ds.setLoginTimeout(5); + + SQLException e = assertThrows(SQLException.class, connect); + server.close(); + assertFalse(startupSent.get(), "a plaintext startup message reached the server"); + assertTrue(String.valueOf(e.getMessage()).contains("TLS"), String.valueOf(e.getMessage())); + acceptor.join(5000); + } + } + + /** + * Answers 'N' to SSLRequest and records whether a startup message follows, failing that login + * with a FATAL so a client that does fall back to plaintext errors out instead of waiting. + */ + private static void declineTls(ServerSocket server, AtomicBoolean startupSent) { + while (!server.isClosed()) { + try (Socket socket = server.accept()) { + socket.setSoTimeout(5000); + DataInputStream in = new DataInputStream(socket.getInputStream()); + OutputStream out = socket.getOutputStream(); + while (true) { + int length = in.readInt(); + int code = in.readInt(); + in.readFully(new byte[length - 8]); + if (code != SSL_REQUEST_CODE) { + startupSent.set(true); + out.write(FATAL); + out.flush(); + break; + } + out.write('N'); + out.flush(); + } + } catch (IOException e) { + // The client hung up, or the test closed the listener. + } + } + } +} diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java index 2bd14746..3d68f6fa 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/ds/common/BaseDataSourceTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -11,6 +12,7 @@ import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.util.concurrent.atomic.AtomicBoolean; import javax.naming.Reference; import org.junit.jupiter.api.Test; import org.postgresql.ds.PGSimpleDataSource; @@ -53,6 +55,100 @@ void rejectedUrlIsRedactedInTheMessage() { assertTrue(e.getMessage().contains("db.example.com"), e.getMessage()); } + @Test + void serverNameThatWouldEndTheHostIsRefused() { + PGSimpleDataSource ds = new PGSimpleDataSource(); + for (String bad : new String[] { + "h/realdb?sslmode=disable&x=", "h?sslmode=disable", "user@h", "a,b", "h#x", "h x", "h%2f", "h=x" + }) { + assertThrows(IllegalArgumentException.class, () -> ds.setServerName(bad), bad); + assertThrows(IllegalArgumentException.class, () -> ds.setServerNames(new String[] {"ok", bad}), bad); + } + assertEquals("localhost", ds.getServerName()); + ds.setServerNames(new String[] {"[::1]", "db-1.example.com"}); + assertArrayEquals(new String[] {"[::1]", "db-1.example.com"}, ds.getServerNames()); + } + + @Test + void bagKeysAreEncodedInTheUrl() { + PGSimpleDataSource ds = new PGSimpleDataSource(); + ds.setDatabaseName("app"); + ds.setSslMode("verify-full"); + ds.setProperty("x&sslmode", "disable"); + String url = ds.getUrl(); + assertFalse(url.contains("x&sslmode"), url); + assertEquals("verify-full", copyViaSetUrl(ds).getSslMode()); + assertEquals("disable", copyViaSetUrl(ds).getProperty("x&sslmode")); + } + + @Test + void urlUserinfoSetsTheCredentialsNotTheServerName() { + PGSimpleDataSource ds = new PGSimpleDataSource(); + ds.setUrl("jdbc:postgresql://alice:s3cret%40p+w@db.example.com:5433/app"); + assertEquals("db.example.com", ds.getServerName()); + assertEquals(5433, ds.getPortNumber()); + assertEquals("alice", ds.getUser()); + assertEquals("s3cret@p+w", ds.getPassword()); + assertFalse(ds.getUrl().contains("s3cret"), ds.getUrl()); + + PGSimpleDataSource noPort = new PGSimpleDataSource(); + noPort.setUrl("jdbc:postgresql://bob:pw@db.example.com/app"); + assertEquals("db.example.com", noPort.getServerName()); + assertEquals("bob", noPort.getUser()); + } + + @Test + void badPortIsReportedWithoutTheRestOfTheUrl() { + PGSimpleDataSource ds = new PGSimpleDataSource(); + IllegalArgumentException e = assertThrows( + IllegalArgumentException.class, () -> ds.setUrl("jdbc:postgresql://db:54x2/app?password=s3cret")); + assertTrue(e.getMessage().contains("54x2"), e.getMessage()); + assertFalse(e.getMessage().contains("s3cret"), e.getMessage()); + } + + @Test + void spacesRoundTripWithoutPlusSigns() { + PGSimpleDataSource ds = new PGSimpleDataSource(); + ds.setDatabaseName("my db"); + ds.setOptions("-c statement_timeout=5s"); + ds.setApplicationName("a+b c"); + String url = ds.getUrl(); + // The compat driver decodes %XX only, so a '+' for a space would arrive as a '+'. + assertFalse(url.contains("+"), url); + PGSimpleDataSource copy = copyViaSetUrl(ds); + assertEquals("my db", copy.getDatabaseName()); + assertEquals("-c statement_timeout=5s", copy.getOptions()); + assertEquals("a+b c", copy.getApplicationName()); + } + + static final AtomicBoolean STATIC_INIT_RAN = new AtomicBoolean(); + + /** Not a BaseDataSource, with a static initializer; named only by string so nothing else loads it. */ + public static class StaticInitProbe { + static { + STATIC_INIT_RAN.set(true); + } + } + + @Test + void objectFactoryDoesNotInitializeAClassOutsideTheFamily() throws Exception { + Reference ref = new Reference( + BaseDataSourceTest.class.getName() + "$StaticInitProbe", PGObjectFactory.class.getName(), null); + + assertNull(new PGObjectFactory().getObjectInstance(ref, null, null, null)); + assertFalse(STATIC_INIT_RAN.get(), "the named class's static initializer must not have run"); + } + + @Test + void setUrlKeepsALiteralPlusAsTheDriversDo() { + PGSimpleDataSource ds = new PGSimpleDataSource(); + ds.setUrl("jdbc:postgresql://h/my+db?ApplicationName=a+b%20c&options=-c%20x%3D1"); + assertEquals("my+db", ds.getDatabaseName()); + assertEquals("a+b c", ds.getApplicationName()); + assertEquals("-c x=1", ds.getOptions()); + assertThrows(IllegalArgumentException.class, () -> ds.setUrl("jdbc:postgresql://h/db?x=%zz")); + } + @Test void shortFormUrlTargetsLocalhost() { PGSimpleDataSource ds = new PGSimpleDataSource(); diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/HstoreCompatIT.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/HstoreCompatIT.java index 370e4c55..d4402b5b 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/HstoreCompatIT.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/HstoreCompatIT.java @@ -85,6 +85,33 @@ void mapParameterBindsAsTypedHstore() throws SQLException { } } + @Test + void mapParameterUsesTheExtensionTypeNotAnotherTypeNamedHstore() throws SQLException { + try (Connection setup = connect()) { + assumeTrue(hstoreAvailable(setup), "server can install hstore"); + try (Statement stmt = setup.createStatement()) { + stmt.execute("DROP SCHEMA IF EXISTS hs_shadow CASCADE"); + stmt.execute("CREATE SCHEMA hs_shadow"); + stmt.execute("CREATE DOMAIN hs_shadow.hstore AS text CHECK (false)"); + } + try (Connection con = connect(); + PreparedStatement ps = con.prepareStatement("SELECT pg_typeof(?)::oid::int8, (" + + "SELECT t.oid::int8 FROM pg_type t JOIN pg_extension e ON e.oid = (" + + "SELECT refobjid FROM pg_depend WHERE objid = t.oid AND deptype = 'e')" + + " WHERE e.extname = 'hstore' AND t.typname = 'hstore')")) { + ps.setObject(1, Collections.singletonMap("a", 1)); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(rs.getLong(2), rs.getLong(1)); + } + } finally { + try (Statement stmt = setup.createStatement()) { + stmt.execute("DROP SCHEMA hs_shadow CASCADE"); + } + } + } + } + @Test void mapParameterRoundTripsBareSelectWithEscapes() throws SQLException { try (Connection con = connect()) { diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/SearchPathShadowingCompatIT.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/SearchPathShadowingCompatIT.java new file mode 100644 index 00000000..bfc2b2f5 --- /dev/null +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/it/SearchPathShadowingCompatIT.java @@ -0,0 +1,67 @@ +package org.postgresql.it; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import org.junit.jupiter.api.Test; +import org.postgresql.PGResultSetMetaData; +import org.postgresql.core.BaseConnection; + +/** + * The compat layer's own catalog lookups must not run an {@code =(oid, int4)} operator that a + * search_path schema supplies. The shadowing operator raises, so a lookup that resolved to it fails + * the test. + */ +class SearchPathShadowingCompatIT extends AbstractCompatPostgresIT { + + private static final String SCHEMA = "shadow_compat"; + + private static void exec(Connection con, String sql) throws SQLException { + try (Statement st = con.createStatement()) { + st.execute(sql); + } + } + + private static int oid(Connection con, String typeName) throws SQLException { + try (Statement st = con.createStatement(); + ResultSet rs = st.executeQuery("SELECT '" + typeName + "'::regtype::oid::int4")) { + assertTrue(rs.next()); + return rs.getInt(1); + } + } + + @Test + void catalogLookupsUsePgCatalogOperators() throws SQLException { + try (Connection con = connect()) { + exec(con, "DROP SCHEMA IF EXISTS " + SCHEMA + " CASCADE"); + exec(con, "CREATE SCHEMA " + SCHEMA); + exec(con, "SET search_path = " + SCHEMA + ", public"); + exec(con, "CREATE TYPE sh_mood AS ENUM ('sad', 'ok')"); + exec(con, "CREATE TABLE sh_t (m sh_mood)"); + exec(con, "INSERT INTO sh_t VALUES ('ok')"); + exec( + con, + "CREATE FUNCTION " + SCHEMA + ".shadow_eq(oid, int4) RETURNS bool LANGUAGE plpgsql" + + " AS $$BEGIN RAISE EXCEPTION 'shadowing operator ran'; END$$"); + exec( + con, + "CREATE OPERATOR " + SCHEMA + ".= (LEFTARG = oid, RIGHTARG = int4, FUNCTION = " + SCHEMA + + ".shadow_eq)"); + + assertEquals( + "sh_mood", con.unwrap(BaseConnection.class).getTypeInfo().getPGType(oid(con, "sh_mood"))); + try (Statement st = con.createStatement(); + ResultSet rs = st.executeQuery("SELECT m FROM sh_t")) { + PGResultSetMetaData md = assertInstanceOf(PGResultSetMetaData.class, rs.getMetaData()); + assertEquals("m", md.getBaseColumnName(1)); + assertTrue(rs.next()); + assertEquals("ok", rs.getObject(1).toString()); + } + } + } +} diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/HStoreConverterTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/HStoreConverterTest.java index df773d39..0513a85f 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/HStoreConverterTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/HStoreConverterTest.java @@ -1,6 +1,8 @@ package org.postgresql.util; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Collections; import java.util.HashMap; @@ -74,4 +76,13 @@ void roundTripsThroughBothDirections() { map.put("k3", null); assertEquals(map, HStoreConverter.fromString(HStoreConverter.toString(map))); } + + @Test + void truncatedTextIsAnIllegalArgument() { + for (String text : new String[] {"\"a\"=>", "\"a", "\"a\"=>\"b", "\"a\"=>\"b\\"}) { + IllegalArgumentException e = + assertThrows(IllegalArgumentException.class, () -> HStoreConverter.fromString(text), text); + assertTrue(e.getMessage().contains("hstore"), e.getMessage()); + } + } } diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/ObjectFactoryTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/ObjectFactoryTest.java index 852692a7..4e76e4bd 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/ObjectFactoryTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/ObjectFactoryTest.java @@ -10,6 +10,7 @@ import java.net.InetAddress; import java.net.Socket; import java.util.Properties; +import java.util.concurrent.atomic.AtomicBoolean; import javax.net.SocketFactory; import org.junit.jupiter.api.Test; import org.postgresql.PGProperty; @@ -33,6 +34,15 @@ public NotASocketFactory() { } } + static final AtomicBoolean STATIC_INIT_RAN = new AtomicBoolean(); + + /** Not a SocketFactory, with a static initializer; named only by string so nothing else loads it. */ + public static class StaticInitProbe { + static { + STATIC_INIT_RAN.set(true); + } + } + /** Takes the Properties constructor, which is the one ObjectFactory prefers. */ public static class CapturingSocketFactory extends SocketFactory { final Properties properties; @@ -85,6 +95,19 @@ void rejectsAWrongTypedClassWithoutConstructingIt() { assertFalse(NotASocketFactory.instantiated, "the wrong-typed class must not have been constructed"); } + @Test + void rejectsAWrongTypedClassWithoutInitializingIt() { + assertThrows( + ClassCastException.class, + () -> ObjectFactory.instantiate( + SocketFactory.class, + ObjectFactoryTest.class.getName() + "$StaticInitProbe", + new Properties(), + false, + null)); + assertFalse(STATIC_INIT_RAN.get(), "the wrong-typed class's static initializer must not have run"); + } + @Test void prefersThePropertiesConstructor() throws Exception { Properties props = new Properties(); diff --git a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/PGIntervalTest.java b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/PGIntervalTest.java index be49cc3a..67cb741e 100644 --- a/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/PGIntervalTest.java +++ b/postgresql-client-pgjdbc-compat/src/test/java/org/postgresql/util/PGIntervalTest.java @@ -73,4 +73,11 @@ void wholeAndMicroSecondsSplit() { void rejectsUnknownUnit() { assertThrows(SQLException.class, () -> new PGInterval("3 fortnights")); } + + @Test + void malformedTextIsAnSqlException() { + for (String text : new String[] {"P1xY", "Pabc", "1 years 2 mon x days", "x years", "@ 1 days ago 2"}) { + assertThrows(SQLException.class, () -> new PGInterval().setValue(text), text); + } + } } diff --git a/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/ProtocolDecoder.java b/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/ProtocolDecoder.java index 30abe82b..c2061591 100644 --- a/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/ProtocolDecoder.java +++ b/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/ProtocolDecoder.java @@ -96,6 +96,16 @@ public int fillFrom(FrameReader.Filler filler) { return decode(frame); } + /** See {@link FrameReader#limitMessageLength(long)}. */ + public void limitMessageLength(long limit) { + frameReader.limitMessageLength(limit); + } + + /** See {@link FrameReader#clearMessageLengthLimit()}. */ + public void clearMessageLengthLimit() { + frameReader.clearMessageLengthLimit(); + } + /** Releases an oversized framing buffer once idle; see {@link FrameReader#shrinkIfIdle()}. */ public void shrinkIfIdle() { frameReader.shrinkIfIdle(); diff --git a/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/framing/FrameReader.java b/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/framing/FrameReader.java index a0d447a7..859be6da 100644 --- a/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/framing/FrameReader.java +++ b/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/framing/FrameReader.java @@ -28,11 +28,15 @@ public final class FrameReader { public static final long UNLIMITED = 0L; /** - * Default cap when none is specified: 1 GiB. Generous enough for a maximum-size PostgreSQL - * value (a single field maxes at {@code 0x3FFFFFFF}, just under 1 GiB) while bounding the - * accumulation-buffer memory-exhaustion vector so an unconfigured connection is not unlimited. + * Default cap when none is specified: the largest message a server builds. A message body lives + * in a StringInfo, whose data stays under MaxAllocSize ({@code 0x3FFFFFFF}), and the length + * prefix counts its own four bytes. This bounds the accumulation-buffer memory-exhaustion vector + * so an unconfigured connection is not unlimited. */ - public static final long DEFAULT_MAX_MESSAGE_LENGTH = 1L << 30; + public static final long DEFAULT_MAX_MESSAGE_LENGTH = 0x3FFFFFFEL + 4; + + /** The largest array length every JVM allocates; {@code Integer.MAX_VALUE} is refused by some. */ + private static final int MAX_ARRAY_LENGTH = Integer.MAX_VALUE - 8; private static final int DEFAULT_CAPACITY = 8192; @@ -50,6 +54,8 @@ public final class FrameReader { private static final int MIN_READ_CHUNK = 32 * 1024; private final long maxMessageLength; + // maxMessageLength, or a tighter limit set for a phase of the connection (see limitMessageLength). + private long messageLengthLimit; private byte[] buf; private int start; private int end; @@ -71,9 +77,20 @@ public FrameReader(long maxMessageLength) { throw new IllegalArgumentException("maxMessageLength must be >= 0: " + maxMessageLength); } this.maxMessageLength = maxMessageLength; + this.messageLengthLimit = maxMessageLength; this.buf = new byte[DEFAULT_CAPACITY]; } + /** Applies {@code limit} on top of the configured maximum until {@link #clearMessageLengthLimit()}. */ + public void limitMessageLength(long limit) { + messageLengthLimit = maxMessageLength == UNLIMITED ? limit : Math.min(maxMessageLength, limit); + } + + /** Restores the configured maximum message length. */ + public void clearMessageLengthLimit() { + messageLengthLimit = maxMessageLength; + } + public void feed(byte[] data) { feed(data, 0, data.length); } @@ -179,8 +196,8 @@ private boolean fill(boolean typed, Frame into) { if (length < 4) { throw new ProtocolException("invalid frame length prefix: " + length); } - if (maxMessageLength != UNLIMITED && length > maxMessageLength) { - throw new ProtocolException("frame length " + length + " exceeds max message length " + maxMessageLength); + if (messageLengthLimit != UNLIMITED && length > messageLengthLimit) { + throw new ProtocolException("frame length " + length + " exceeds max message length " + messageLengthLimit); } // Compute in long: a typed frame with length 0x7FFFFFFF would overflow (1 + MAX_VALUE) to a // negative int, bypassing the short-read guard below and allocating a ~2 GiB payload from a @@ -227,16 +244,19 @@ private void ensureWritable(int additional) { if (additional <= buf.length - end) { return; } - long needed = (long) end + additional; - if (needed > Integer.MAX_VALUE) { - throw new IllegalStateException("frame buffer would exceed Integer.MAX_VALUE bytes"); + byte[] grown = new byte[grownCapacity(buf.length, (long) end + additional)]; + System.arraycopy(buf, 0, grown, 0, end); + buf = grown; + } + /** Doubles {@code capacity} until it holds {@code needed}, never past what the JVM allocates. */ + static int grownCapacity(int capacity, long needed) { + if (needed > MAX_ARRAY_LENGTH) { + throw new ProtocolException("frame buffer would exceed " + MAX_ARRAY_LENGTH + " bytes"); } - int newCapacity = buf.length; + long newCapacity = Math.max(capacity, 1); while (newCapacity < needed) { - newCapacity = (int) Math.min((long) newCapacity * 2, Integer.MAX_VALUE); + newCapacity = Math.min(newCapacity * 2, MAX_ARRAY_LENGTH); } - byte[] grown = new byte[newCapacity]; - System.arraycopy(buf, 0, grown, 0, end); - buf = grown; + return (int) newCapacity; } } diff --git a/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/message/NegotiateProtocolVersion.java b/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/message/NegotiateProtocolVersion.java index 8ea8fb31..755d148d 100644 --- a/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/message/NegotiateProtocolVersion.java +++ b/postgresql-client-protocol/src/main/java/org/postgresql/client/protocol/message/NegotiateProtocolVersion.java @@ -14,7 +14,9 @@ *

    The driver uses this to fall back when it requested protocol 3.2 via * {@code protocolVersion=latest} (ADR-0004). * - * @param newestMinorVersion the newest minor protocol version the server supports + * @param newestMinorVersion the newest protocol version the server supports for the requested major + * version. The protocol documentation calls this the minor version, but servers send the whole + * version code ({@code major << 16 | minor}), so read it with {@code ProtocolConstants}. * @param unsupportedOptions names of requested protocol options the server did not * recognize, in order */ diff --git a/postgresql-client-protocol/src/test/java/org/postgresql/client/protocol/framing/FrameReaderTest.java b/postgresql-client-protocol/src/test/java/org/postgresql/client/protocol/framing/FrameReaderTest.java index 80f87c9c..49706767 100644 --- a/postgresql-client-protocol/src/test/java/org/postgresql/client/protocol/framing/FrameReaderTest.java +++ b/postgresql-client-protocol/src/test/java/org/postgresql/client/protocol/framing/FrameReaderTest.java @@ -218,11 +218,26 @@ void defaultCapIsNonZero() { @Test void defaultRejectsOverCapDeclaredLengthBeforeAllocating() { FrameReader reader = new FrameReader(); // default cap - long over = FrameReader.DEFAULT_MAX_MESSAGE_LENGTH + 1; // 0x40000001, still a valid int32 prefix + long over = FrameReader.DEFAULT_MAX_MESSAGE_LENGTH + 1; // still a valid int32 prefix reader.feed(new byte[] {'Q', (byte) (over >>> 24), (byte) (over >>> 16), (byte) (over >>> 8), (byte) over}); assertThrows(ProtocolException.class, reader::nextTypedFrame); } + @Test + void defaultAcceptsTheLargestMessageAServerBuilds() { + // A body under MaxAllocSize (0x3FFFFFFF) plus the four length bytes. + assertEquals(0x3FFFFFFEL + 4, FrameReader.DEFAULT_MAX_MESSAGE_LENGTH); + } + + @Test + void growthStopsBelowTheJvmArrayLimit() { + int limit = Integer.MAX_VALUE - 8; + assertEquals(limit, FrameReader.grownCapacity(1 << 30, (1L << 30) + 32768)); + assertEquals(limit, FrameReader.grownCapacity(8192, limit)); + assertEquals(16384, FrameReader.grownCapacity(8192, 8193)); + assertThrows(ProtocolException.class, () -> FrameReader.grownCapacity(1 << 30, limit + 1L)); + } + @Test void defaultAcceptsANormalFrame() { FrameReader reader = new FrameReader(); diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/BackgroundListener.java b/postgresql-client/src/main/java/org/postgresql/client/core/BackgroundListener.java index 9f598934..4b247877 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/BackgroundListener.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/BackgroundListener.java @@ -2,6 +2,7 @@ import java.time.Duration; import org.jspecify.annotations.Nullable; +import org.postgresql.client.core.internal.LogText; import org.postgresql.client.core.internal.ServerErrors; import org.postgresql.client.protocol.message.BackendMessage; import org.postgresql.client.protocol.message.ErrorResponse; @@ -99,7 +100,8 @@ private void loop() { // Unsolicited errors are terminal (e.g. FATAL 57P01 admin shutdown). LOG.warn( "notification listener received server error: {}", - ServerErrors.toServerMessage(error.fields()).message()); + LogText.escape(ServerErrors.toServerMessage(error.fields()) + .message())); connection.markBroken(); return; } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java b/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java index 072463d6..1de03bf7 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/CoreConnection.java @@ -36,6 +36,8 @@ import org.postgresql.client.protocol.message.Close; import org.postgresql.client.protocol.message.CloseComplete; import org.postgresql.client.protocol.message.CommandComplete; +import org.postgresql.client.protocol.message.CopyFail; +import org.postgresql.client.protocol.message.CopyInResponse; import org.postgresql.client.protocol.message.DataRow; import org.postgresql.client.protocol.message.Describe; import org.postgresql.client.protocol.message.EmptyQueryResponse; @@ -231,7 +233,7 @@ public void invalidateTypes() { public PgResultStream execute(String sql) { requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); invalidateCachesForSessionCommand(sql); ensureTransactionOpen(); return sendArmed(disarm -> { @@ -291,7 +293,7 @@ public PgResultStream execute(String sql, List parameters, int fetchSize) { } requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); invalidateCachesForSessionCommand(sql); ensureTransactionOpen(); return statementCache != null @@ -325,7 +327,7 @@ public PgPipeline pipeline() { } requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); ensureTransactionOpen(); claimWire(); try { @@ -657,6 +659,7 @@ public CorePreparedStatement prepare(String sql, int[] declaredParameterOids) { } int[] parameterOids = new int[0]; RowMetadata resultMetadata = SimpleRowMetadata.EMPTY; + boolean returnsRows = false; while (true) { BackendMessage message = pullNonAsync(); switch (message) { @@ -664,7 +667,10 @@ public CorePreparedStatement prepare(String sql, int[] declaredParameterOids) { /* parsed */ } case ParameterDescription description -> parameterOids = description.parameterTypeOids(); - case RowDescription description -> resultMetadata = SimpleRowMetadata.of(description); + case RowDescription description -> { + resultMetadata = SimpleRowMetadata.of(description); + returnsRows = true; + } case NoData ignored -> resultMetadata = SimpleRowMetadata.EMPTY; case ErrorResponse error -> throw failSynchronousExchange(error); case ReadyForQuery ready -> { @@ -673,7 +679,8 @@ public CorePreparedStatement prepare(String sql, int[] declaredParameterOids) { // (now fixed) result column type OIDs and the connection's codec policy, so every // execute of this statement reuses it instead of recomputing two int[] per op. int[] resultFormats = resultFormatPolicy.forColumns(columnTypeOids(resultMetadata), codecs); - return new CorePreparedStatement(this, name, sql, parameterOids, resultMetadata, resultFormats); + return new CorePreparedStatement( + this, name, sql, parameterOids, resultMetadata, returnsRows, resultFormats); } default -> throw unexpectedSynchronous(message); } @@ -684,7 +691,7 @@ public CorePreparedStatement prepare(String sql, int[] declaredParameterOids) { PgResultStream executePrepared(CorePreparedStatement statement, List parameters, int fetchSize) { requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); ensureTransactionOpen(); return executePreparedInternal(statement, parameters, fetchSize); } @@ -707,7 +714,8 @@ private PgResultStream executePreparedInternal( } else { channel.send(bind, Execute.UNNAMED_UNLIMITED, Sync.instance()); } - return new ExtendedQueryResultStream(this, fetchSize, disarm, statement.executeMetadata()); + return new ExtendedQueryResultStream( + this, fetchSize, disarm, statement.executeMetadata(), statement.returnsRows()); }); } @@ -750,7 +758,7 @@ private static int[] columnTypeOids(RowMetadata metadata) { public long[] executeBatch(String sql, List parameterSets, int window) { requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); ensureTransactionOpen(); if (parameterSets.isEmpty()) { return new long[0]; @@ -954,7 +962,7 @@ private int fillWindow(String name, int[] profile) { public long[] executeMultiStatementBatch(List sqls, List> parameterSets) { requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); ensureTransactionOpen(); int chunks = sqls.size(); long[] counts = new long[chunks]; @@ -1288,9 +1296,13 @@ BackendMessage pullNonAsync() { /** Reads to ReadyForQuery (discarding intervening messages) and returns the transaction status. */ private TransactionStatus drainSynchronous() { while (true) { - if (pullNonAsync() instanceof ReadyForQuery ready) { + BackendMessage message = pullNonAsync(); + if (message instanceof ReadyForQuery ready) { return ready.status(); } + if (message instanceof CopyInResponse) { + channel.send(new CopyFail(PullResultStream.UNEXPECTED_COPY_IN)); // see drainToReadyForQuery + } } } @@ -1431,7 +1443,8 @@ public void setApplicationName(String applicationName) { // The resource is opened to be closed -- running the statement is the point, the rows are not. @SuppressWarnings("try") private void setConfig(String name, String value) { - try (PgResultStream ignored = execute("SELECT set_config('" + name + "', $1, false)", List.of(value))) { + try (PgResultStream ignored = + execute("SELECT pg_catalog.set_config('" + name + "', $1, false)", List.of(value))) { // value applied for the session } } @@ -1501,7 +1514,7 @@ public void unlinkLargeObject(long oid) { byte @Nullable [] fastpathCall(int functionOid, byte[][] arguments) { requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); ensureTransactionOpen(); beginConversation(new FunctionCall( functionOid, new int[] {ProtocolConstants.FORMAT_BINARY}, arguments, ProtocolConstants.FORMAT_BINARY)); @@ -1529,7 +1542,7 @@ public void unlinkLargeObject(long oid) { public PgCopyOutStream copyOut(String sql) { requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); ensureTransactionOpen(); beginConversation(new Query(sql)); try { @@ -1547,7 +1560,7 @@ public PgCopyOutStream copyOut(String sql) { public PgCopyInStream copyIn(String sql) { requireOpen(); requireIdle(); - requireUsableTransaction(); + recoverAutosave(); ensureTransactionOpen(); beginConversation(new Query(sql)); try { @@ -1620,7 +1633,7 @@ public boolean isValid(Duration timeout) { * nothing in the transaction to protect yet, and a preceding {@code SAVEPOINT} would both make * {@code SET TRANSACTION ISOLATION LEVEL} non-first and put it in a subtransaction, which the * server rejects (pgjdbc #3307; pgjdbc-suite AutoSaveTransactionSettingsTest). A first - * statement that fails aborts an empty transaction, which {@link #requireUsableTransaction} + * statement that fails aborts an empty transaction, which {@link #recoverAutosave} * recovers by rolling back outright. */ private void ensureTransactionOpen() { @@ -1641,27 +1654,22 @@ private void ensureTransactionOpen() { } /** - * Guards data statements in the aborted-transaction state (C13.2): rolls back to the internal - * autosave savepoint to recover when {@link Autosave#ALWAYS} is on, otherwise rejects the - * command until the caller rolls back. + * Under {@link Autosave#ALWAYS}, recovers an aborted transaction before the next statement by + * rolling back to the internal autosave savepoint (C13.2). Otherwise the statement goes to the + * server, which refuses it with 25P02 or, for ROLLBACK and the like, ends the block. */ - private void requireUsableTransaction() { - if (transactionStatus != TransactionStatus.FAILED) { + private void recoverAutosave() { + if (transactionStatus != TransactionStatus.FAILED || config.autosave() != Autosave.ALWAYS) { return; } - if (config.autosave() == Autosave.ALWAYS) { - if (autosaveActive) { - runCommand("ROLLBACK TO SAVEPOINT pg_java_autosave"); - return; - } - // The failed statement was the transaction's first (no savepoint is installed before - // it; see ensureTransactionOpen): the transaction is empty, so recover by rolling it - // back outright -- ensureTransactionOpen reopens it for the statement about to run. - runCommand("ROLLBACK"); + if (autosaveActive) { + runCommand("ROLLBACK TO SAVEPOINT pg_java_autosave"); return; } - throw new PgException( - "current transaction is aborted: roll back (or to a savepoint) before issuing further commands"); + // The failed statement was the transaction's first (no savepoint is installed before + // it; see ensureTransactionOpen): the transaction is empty, so recover by rolling it + // back outright -- ensureTransactionOpen reopens it for the statement about to run. + runCommand("ROLLBACK"); } /** Runs a transaction/session control command via the simple protocol and updates the status. */ @@ -1971,7 +1979,15 @@ void restoreConfiguredReadTimeout() { */ void applyParameterStatus(String name, String value) { runtimeParameters.put(name, value); - refreshSessionState(name, value); + try { + refreshSessionState(name, value); + } catch (RuntimeException e) { + // An unmappable client_encoding, or standard_conforming_strings turned off, throws out of + // the middle of a response, leaving the rest of it on the wire; reusing the connection + // would hand this statement's messages to the next one. + markBroken(); + throw e; + } guardedCallback("PgConnectionListener.onParameterStatus", () -> listener.onParameterStatus(name, value)); } @@ -2005,14 +2021,20 @@ private void refreshSessionState(String name, String value) { s.timeZone(), value, s.standardConformingStrings()); - case "standard_conforming_strings" -> - new SessionState( - s.capabilities(), - s.clientEncoding(), - s.integerDatetimes(), - s.timeZone(), - s.dateStyle(), - !"off".equalsIgnoreCase(value)); + case "standard_conforming_strings" -> { + boolean on = !"off".equalsIgnoreCase(value); + if (!on && config.forceSessionDefaults()) { + // SessionBootstrap refuses "off" at connect time because the SQL lexers assume + // standard string literals; a later SET, function or role default reaching the + // same state is no safer. The caller's handler marks the connection broken. + throw new PgConnectionException("standard_conforming_strings was turned off on this connection;" + + " this driver requires it on (the SQL lexer assumes standard string literals), so" + + " the connection is closed. Leave it on, or set forceSessionDefaults(false) to" + + " relax this."); + } + yield new SessionState( + s.capabilities(), s.clientEncoding(), s.integerDatetimes(), s.timeZone(), s.dateStyle(), on); + } case "integer_datetimes" -> new SessionState( s.capabilities(), diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/CoreLargeObject.java b/postgresql-client/src/main/java/org/postgresql/client/core/CoreLargeObject.java index ee0fc705..b6a7c1ab 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/CoreLargeObject.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/CoreLargeObject.java @@ -20,7 +20,15 @@ public byte[] read(int length) { requireOpen(); byte[] result = connection.fastpathCall( LargeObjects.LO_READ, new byte[][] {LargeObjects.int4(fd), LargeObjects.int4(length)}); - return result != null ? result : new byte[0]; + if (result == null) { + return new byte[0]; + } + // Callers size their destination by what they asked for; a longer reply would overrun it. + if (result.length > length) { + throw new PgException( + "lo_read returned " + result.length + " bytes, more than the " + length + " requested"); + } + return result; } @Override diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/CorePreparedStatement.java b/postgresql-client/src/main/java/org/postgresql/client/core/CorePreparedStatement.java index 461e1455..8a16e618 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/CorePreparedStatement.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/CorePreparedStatement.java @@ -23,6 +23,7 @@ final class CorePreparedStatement implements PgPreparedStatement { private final int[] parameterTypeOids; private final RowMetadata resultMetadata; private final RowMetadata executeMetadata; + private final boolean returnsRows; private final int[] resultFormatCodes; private boolean closed; @@ -32,12 +33,14 @@ final class CorePreparedStatement implements PgPreparedStatement { String sql, int[] parameterTypeOids, RowMetadata resultMetadata, + boolean returnsRows, int[] resultFormatCodes) { this.connection = connection; this.name = name; this.sql = sql; this.parameterTypeOids = parameterTypeOids; this.resultMetadata = resultMetadata; + this.returnsRows = returnsRows; this.resultFormatCodes = resultFormatCodes; // The execute path skips the portal Describe (task 1), so precompute the metadata a Bind with // these result formats would yield: the prepare-time (statement Describe) columns adjusted to @@ -72,6 +75,15 @@ RowMetadata executeMetadata() { return executeMetadata; } + /** + * Whether the statement Describe answered with a RowDescription rather than NoData: the execute + * then has a row phase even when it declares no columns ({@code SELECT FROM t}), which the column + * count alone cannot tell apart from a command. + */ + boolean returnsRows() { + return returnsRows; + } + /** * The {@code Bind} result-format codes for this statement, computed once at prepare time from the * (fixed) result column type OIDs and codec policy. Returned by reference for the execute hot diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/ExtendedQueryResultStream.java b/postgresql-client/src/main/java/org/postgresql/client/core/ExtendedQueryResultStream.java index 1d78d344..be1e1863 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/ExtendedQueryResultStream.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/ExtendedQueryResultStream.java @@ -32,11 +32,12 @@ final class ExtendedQueryResultStream extends PullResultStream { private final int fetchSize; private final boolean describeSkipped; + private final boolean preparedReturnsRows; private boolean syncSent; /** The unnamed fast path: a portal Describe was sent, so the metadata comes from a RowDescription. */ ExtendedQueryResultStream(CoreConnection connection, int fetchSize, @Nullable Runnable onCloseHook) { - this(connection, fetchSize, onCloseHook, null); + this(connection, fetchSize, onCloseHook, null, false); } /** @@ -47,11 +48,13 @@ final class ExtendedQueryResultStream extends PullResultStream { CoreConnection connection, int fetchSize, @Nullable Runnable onCloseHook, - @Nullable RowMetadata preparedMetadata) { + @Nullable RowMetadata preparedMetadata, + boolean preparedReturnsRows) { super(connection, onCloseHook); this.fetchSize = fetchSize; this.syncSent = fetchSize <= 0; // the unbounded path sent Sync with the request this.describeSkipped = preparedMetadata != null; + this.preparedReturnsRows = preparedReturnsRows; if (preparedMetadata != null) { this.metadata = preparedMetadata; } @@ -130,8 +133,8 @@ private void primeWithoutDescribe() { BackendMessage message = pull(); switch (message) { case BindComplete ignored -> { - if (metadata.columnCount() > 0) { - return; // rows follow; the cursor's next() reads them + if (preparedReturnsRows) { + return; // rows follow, possibly with no columns; the cursor's next() reads them } // no result columns: the Execute reports CommandComplete next; keep reading to it } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/PgConnectionConfig.java b/postgresql-client/src/main/java/org/postgresql/client/core/PgConnectionConfig.java index 2e7e6625..90325310 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/PgConnectionConfig.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/PgConnectionConfig.java @@ -228,6 +228,12 @@ public boolean loadBalanceHosts() { * Class name of a {@link javax.net.SocketFactory} used to create the plain TCP socket (unix * sockets, proxies, test fault injection), or {@code null} for a plain {@code new Socket()}. * Instantiated per connection attempt with {@link #socketFactoryArg()} when that is set. + * + *

    This trusts the classpath: whoever sets the property picks which {@code SocketFactory} + * subclass on it runs, and with what argument. Only a class that is such a subclass is ever + * initialized, so naming any other class does nothing, but the property belongs with the rest + * of the deployer's configuration and should not be taken from a less trusted source, such as + * a URL an end user can edit. */ public @Nullable String socketFactory() { return socketFactory; @@ -533,7 +539,31 @@ public PgConnectionConfig build() { if (user == null || user.isBlank()) { throw new PgConfigurationException("user is required"); } + // These go out as NUL-terminated strings, so an embedded NUL cannot be sent. The wire + // encoder refuses one too, but as an IllegalArgumentException from the middle of the + // connect; refusing it here makes it a configuration error the JDBC layer reports. + requireNoNul("user", user); + requireNoNul("database", database); + requireNoNul("application_name", applicationName); + requireNoNul("options", options); + runtimeParameters.forEach((name, value) -> { + requireNoNul("a runtime parameter name", name); + requireNoNul("runtime parameter " + name, value); + }); + if (password != null) { + for (char c : password.chars()) { + if (c == '\0') { + throw new PgConfigurationException("password contains an embedded NUL"); + } + } + } return new PgConnectionConfig(this); } + + private static void requireNoNul(String what, @Nullable String value) { + if (value != null && value.indexOf('\0') >= 0) { + throw new PgConfigurationException(what + " contains an embedded NUL"); + } + } } } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/PgConnections.java b/postgresql-client/src/main/java/org/postgresql/client/core/PgConnections.java index 4a4154f9..b9d8eb15 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/PgConnections.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/PgConnections.java @@ -6,6 +6,7 @@ import org.jspecify.annotations.Nullable; import org.postgresql.client.core.auth.Authenticator; import org.postgresql.client.core.auth.StandardAuthenticator; +import org.postgresql.client.core.internal.LogText; import org.postgresql.client.core.internal.ProtocolVersionUnsupportedException; import org.postgresql.client.core.internal.StartupOrchestrator; import org.postgresql.client.core.internal.StartupResult; @@ -63,7 +64,8 @@ public static PgConnection connect( connection.close(); // wrong server type for this pass; try the next host } catch (RuntimeException e) { lastFailure = e; - LOG.debug("connect attempt to {} failed: {}", host, e.getMessage()); + // The message can be a server's FATAL text. + LOG.debug("connect attempt to {} failed: {}", host, LogText.escape(e.getMessage())); if (connection != null) { connection.close(); } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/PgEncodings.java b/postgresql-client/src/main/java/org/postgresql/client/core/PgEncodings.java index db44ba6a..df627e3a 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/PgEncodings.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/PgEncodings.java @@ -33,6 +33,12 @@ static Charset toCharset(@Nullable String encoding) { case "LATIN1", "ISO88591" -> StandardCharsets.ISO_8859_1; case "LATIN9", "ISO885915" -> requireCharset(encoding, "ISO-8859-15"); case "WIN1252" -> requireCharset(encoding, "windows-1252"); + // SQL text always goes out as UTF-8. Read in one of these, a UTF-8 byte can become a + // lead byte that takes the next ASCII byte as its trail, so a backslash or quote in a + // literal disappears and the rest of the literal runs as SQL. + case "SJIS", "SHIFT_JIS_2004", "BIG5", "GBK", "UHC", "JOHAB", "GB18030" -> + throw new PgConfigurationException("client_encoding '" + encoding + "' is not supported: it can" + + " read an ASCII byte as part of a multibyte character. Use client_encoding=UTF8."); default -> requireCharset(encoding, encoding); }; } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/PullResultStream.java b/postgresql-client/src/main/java/org/postgresql/client/core/PullResultStream.java index c2702f4b..b6e03315 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/PullResultStream.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/PullResultStream.java @@ -6,6 +6,8 @@ import org.postgresql.client.core.internal.WireChannel; import org.postgresql.client.protocol.message.BackendMessage; import org.postgresql.client.protocol.message.CommandComplete; +import org.postgresql.client.protocol.message.CopyFail; +import org.postgresql.client.protocol.message.CopyInResponse; import org.postgresql.client.protocol.message.DataRow; import org.postgresql.client.protocol.message.EmptyQueryResponse; import org.postgresql.client.protocol.message.ErrorResponse; @@ -61,11 +63,11 @@ protected PullResultStream(CoreConnection connection, @Nullable Runnable onClose /** Subclasses call this once, after the request has been sent, to read up to the first row. */ protected final void start() { prime(); - // A command-only result (no columns) or one that already ended during priming (a zero-row or - // empty query) never yields a DataRow, so it never needs the transient row: only allocate it - // when the result has columns and is still open (task 13a). next() dereferences row solely - // after a DataRow, which cannot arrive in either skipped case, so leaving it null is safe. - if (metadata.columnCount() > 0 && !resultEnded) { + // A result that already ended during priming (a command, a zero-row result or an empty + // query) never yields a DataRow, so it never needs the transient row (task 13a). One that is + // still open does, whatever its column count: SELECT FROM t declares no columns and still + // sends a DataRow per row. + if (!resultEnded) { this.row = new SimpleRow(metadata, connection); } if (resultEnded) { @@ -215,6 +217,7 @@ private void finishResult() { // later statement of the string is the realistic case. Finish the cycle the way // it was always finished -- drain and release -- rather than call the connection // broken over a message that is legal here. + refuseCopyIn(message); completeAndRelease(); return; } @@ -222,6 +225,9 @@ private void finishResult() { } } + /** The CopyFail reason for a COPY FROM STDIN met where no copy stream was opened for it. */ + static final String UNEXPECTED_COPY_IN = "COPY FROM STDIN is not supported here; use the copy-in API"; + /** A result the stream has seen the head of but not yet moved onto. */ private record Pending(RowMetadata metadata, @Nullable ResultSummary summary) {} @@ -256,7 +262,7 @@ public final boolean nextResult() { summary = next.summary(); resultEnded = next.summary() != null; rowAvailable = false; - row = metadata.columnCount() > 0 && !resultEnded ? new SimpleRow(metadata, connection) : null; + row = !resultEnded ? new SimpleRow(metadata, connection) : null; if (resultEnded) { finishResult(); // a row-less result: look ahead again so a third result is not missed } @@ -341,10 +347,23 @@ protected final void drainToReadyForQuery() { finalStatus = ready.status(); } else if (message instanceof ErrorResponse error && drainError == null) { drainError = PgExceptions.fromServerMessage(ServerErrors.toServerMessage(error.fields())); + } else { + refuseCopyIn(message); } } } + /** + * Answers a {@code CopyInResponse} from a later statement of the string with {@code CopyFail}. + * The server is then waiting for data, so reading on would hang until {@code socketTimeout}; + * its error arrives in the drain like any other trailing statement's. + */ + private void refuseCopyIn(BackendMessage message) { + if (message instanceof CopyInResponse) { + channel.send(new CopyFail(UNEXPECTED_COPY_IN)); + } + } + /** * Returns the next non-async message, routing notices, notifications, and parameter-status * reports through the connection so runtime GUC changes apply to live session state (ADR-0011). diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/SimpleRow.java b/postgresql-client/src/main/java/org/postgresql/client/core/SimpleRow.java index 119ec552..07363146 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/SimpleRow.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/SimpleRow.java @@ -173,6 +173,7 @@ public boolean getBooleanPrimitive(int columnIndex) { if (metadata.columnFormat(columnIndex) != ProtocolConstants.FORMAT_TEXT) { // Binary bool is a single 0/1 byte; read it directly, no codec or stringify (task 14). if (metadata.columnTypeOid(columnIndex) == Oids.BOOL) { + requireBinaryWidth(idx, 1); return row().payload()[row().columnOffset(idx)] != 0; } } else if (row().columnLength(idx) == 1) { diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/SizeLimits.java b/postgresql-client/src/main/java/org/postgresql/client/core/SizeLimits.java index 0b4f0bc7..0d82bdac 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/SizeLimits.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/SizeLimits.java @@ -39,7 +39,7 @@ public static SizeLimits unlimited() { /** * The safe default: whole messages capped at {@link FrameReader#DEFAULT_MAX_MESSAGE_LENGTH} - * (1 GiB, closing the accumulation-buffer DoS, M2), single values unlimited. Applications that + * (about 1 GiB, closing the accumulation-buffer DoS, M2), single values unlimited. Applications that * must read even larger messages opt back to {@link #unlimited()} or set a custom cap. */ public static SizeLimits defaults() { diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/SslMaterials.java b/postgresql-client/src/main/java/org/postgresql/client/core/SslMaterials.java index bd52d12c..6b28c11b 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/SslMaterials.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/SslMaterials.java @@ -1,9 +1,9 @@ package org.postgresql.client.core; +import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; -import java.nio.file.Files; import java.nio.file.Path; import java.security.GeneralSecurityException; import java.security.KeyFactory; @@ -38,6 +38,7 @@ import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import org.jspecify.annotations.Nullable; +import org.postgresql.client.core.internal.LocalFiles; /** * Loads TLS trust material and client key material from the files named by an @@ -81,8 +82,9 @@ static TrustManager[] verifyingTrustManagers(SslConfig ssl) { tmf.init(trustStoreFrom(requireRootCert(ssl))); return tmf.getTrustManagers(); } - PKIXBuilderParameters pkix = ssl.rootCertFile() != null - ? new PKIXBuilderParameters(trustStoreFrom(ssl.rootCertFile()), new X509CertSelector()) + Path rootCert = ssl.rootCertFile(); + PKIXBuilderParameters pkix = rootCert != null + ? new PKIXBuilderParameters(trustStoreFrom(rootCert), new X509CertSelector()) : new PKIXBuilderParameters(platformTrustAnchors(), new X509CertSelector()); pkix.setRevocationEnabled(true); pkix.addCertStore( @@ -179,12 +181,12 @@ private static int versionIndex(String version) { return idx; } - private static KeyStore trustStoreFrom(@Nullable Path rootCertFile) throws GeneralSecurityException, IOException { + private static KeyStore trustStoreFrom(Path rootCertFile) throws GeneralSecurityException, IOException { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); CertificateFactory factory = CertificateFactory.getInstance("X.509"); int i = 0; - try (InputStream in = Files.newInputStream(rootCertFile)) { + try (InputStream in = new ByteArrayInputStream(LocalFiles.readRegularFile(rootCertFile))) { for (Certificate cert : factory.generateCertificates(in)) { trustStore.setCertificateEntry("ca-" + (i++), cert); } @@ -194,7 +196,7 @@ private static KeyStore trustStoreFrom(@Nullable Path rootCertFile) throws Gener private static Certificate[] loadCertificateChain(Path certFile) throws GeneralSecurityException, IOException { CertificateFactory factory = CertificateFactory.getInstance("X.509"); - try (InputStream in = Files.newInputStream(certFile)) { + try (InputStream in = new ByteArrayInputStream(LocalFiles.readRegularFile(certFile))) { Collection certs = factory.generateCertificates(in); return certs.toArray(new Certificate[0]); } @@ -202,14 +204,14 @@ private static Certificate[] loadCertificateChain(Path certFile) throws GeneralS private static Collection loadCrls(Path crlFile) throws GeneralSecurityException, IOException { CertificateFactory factory = CertificateFactory.getInstance("X.509"); - try (InputStream in = Files.newInputStream(crlFile)) { + try (InputStream in = new ByteArrayInputStream(LocalFiles.readRegularFile(crlFile))) { return factory.generateCRLs(in); } } private static PrivateKey loadPrivateKey(Path keyFile, @Nullable Secret password) throws GeneralSecurityException, IOException { - byte[] raw = Files.readAllBytes(keyFile); + byte[] raw = LocalFiles.readRegularFile(keyFile); String text = new String(raw, StandardCharsets.US_ASCII); byte[] der; boolean encrypted; diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/TlsContexts.java b/postgresql-client/src/main/java/org/postgresql/client/core/TlsContexts.java index 4d0eae0c..91a833b8 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/TlsContexts.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/TlsContexts.java @@ -30,7 +30,7 @@ final class TlsContexts { * a server accepting a direct connection that sees no {@code postgresql} ALPN protocol * drops the connection rather than speaking the protocol over an unconfirmed channel. */ - private static final String PG_ALPN_PROTOCOL = "postgresql"; + static final String PG_ALPN_PROTOCOL = "postgresql"; private TlsContexts() {} diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/TlsNegotiator.java b/postgresql-client/src/main/java/org/postgresql/client/core/TlsNegotiator.java index ea1c2edc..ca1c469d 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/TlsNegotiator.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/TlsNegotiator.java @@ -5,6 +5,7 @@ import javax.net.ssl.SSLSocketFactory; import org.jspecify.annotations.Nullable; import org.postgresql.client.core.transport.SocketTransport; +import org.postgresql.client.core.transport.TlsTransport; import org.postgresql.client.core.transport.Transport; import org.postgresql.client.protocol.ProtocolEncoder; import org.postgresql.client.protocol.message.SSLRequest; @@ -55,7 +56,26 @@ static Transport upgrade(SocketTransport plain, PgConnectionConfig config, Strin SSLSocketFactory factory = config.sslConfig().sslSocketFactory() != null ? config.sslConfig().sslSocketFactory() : context.getSocketFactory(); - return plain.upgradeToTls(factory, parameters, host, port); + TlsTransport tls = plain.upgradeToTls(factory, parameters, host, port); + if (config.sslNegotiation() == SslNegotiation.DIRECT) { + requirePostgresqlAlpn(tls, host, port); + } + return tls; + } + + /** + * Direct TLS has no SSLRequest exchange, so the ALPN result is the only sign that the peer + * agreed to speak the PostgreSQL protocol on this connection rather than some other TLS + * service on the same port. Offering the protocol is not enough; libpq also fails closed when + * the server did not select it. + */ + private static void requirePostgresqlAlpn(TlsTransport tls, String host, int port) { + String selected = tls.sslSocket().getApplicationProtocol(); + if (!TlsContexts.PG_ALPN_PROTOCOL.equals(selected)) { + tls.close(); + throw new PgTlsException("direct TLS connection to " + host + ":" + port + + " was established without the server selecting the postgresql ALPN protocol"); + } } private static byte readResponseByte(SocketTransport plain) { diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java b/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java index 66c3010e..cdeb9acf 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/TypeCache.java @@ -37,6 +37,11 @@ final class TypeCache { private final Map compositeOidByName = new HashMap<>(); private final Map compositeArrayOidByName = new HashMap<>(); + /** Far deeper than any real chain of domains, arrays and composites. */ + static final int MAX_DEPTH = 64; + + private int depth; + TypeCache(CoreConnection connection, CodecRegistry registry) { this.connection = connection; this.registry = registry; @@ -49,7 +54,19 @@ Codec resolve(int oid) { return registry.forOid(oid); } if (attempted.add(oid)) { - queryAndRegister(oid); + // Each domain base, array element or composite field recurses through here, and the chain + // comes from the server's catalog answers: an endless one would otherwise overflow the + // stack after a thousand-odd round trips. + if (depth >= MAX_DEPTH) { + throw new PgException("type " + Integer.toUnsignedString(oid) + " is nested more than " + MAX_DEPTH + + " levels deep in the catalog"); + } + depth++; + try { + queryAndRegister(oid); + } finally { + depth--; + } } return registry.forOid(oid); } @@ -58,9 +75,10 @@ Codec resolve(int oid) { * Resolves a composite (row) type by name to its codec for a bind parameter, querying the catalog * on first use and caching the name-to-OID mapping (C10.9). Returns {@code null} when the name does * not resolve to a composite type, so the encoder falls back to the record literal under the - * unspecified OID (server type inference). The lookup uses {@code to_regtype} (never throwing, so it - * cannot abort a caller's transaction); on servers without it (before 9.4) the fallback still binds - * a composite that has column or cast context. + * unspecified OID (server type inference). The lookup uses {@code to_regtype}, which returns NULL + * for an unknown name rather than raising (a name that does not parse is never sent; see + * {@link #lookupOid}), so it cannot abort a caller's transaction; on servers without it (before 9.4) + * the fallback still binds a composite that has column or cast context. */ @Nullable Codec resolveComposite(String typeName) { @@ -135,7 +153,12 @@ void clear() { /** The OID of {@code pg_type.typarray} for an element OID, or 0 when it has no array type. */ private int lookupArrayOid(int elementOid) { - String[] row = queryRow("SELECT typarray FROM pg_type WHERE oid = " + Integer.toUnsignedString(elementOid), 1); + // These queries qualify operators and functions: pg_catalog has no exact oid = int4, and the + // backend takes an exact match from any search_path schema over a pg_catalog one that casts. + String[] row = queryRow( + "SELECT typarray FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) " + + Integer.toUnsignedString(elementOid), + 1); if (row == null || row[0] == null) { return 0; } @@ -144,20 +167,88 @@ private int lookupArrayOid(int elementOid) { /** Resolves a (possibly schema-qualified) type name to its OID, or 0 when it does not exist. */ private int lookupOid(String typeName) { - String literal = "'" + typeName.replace("'", "''") + "'"; - String[] row = queryRow("SELECT to_regtype(" + literal + ")::oid", 1); + // to_regtype returns NULL for a name that does not exist but, before PostgreSQL 16, raises a + // syntax error for one that does not parse, and that error aborts the caller's transaction. + // A composite type is always named by a plain (possibly qualified, possibly quoted) name, so + // anything else cannot resolve here and is not worth the round trip or the risk. + if (!isQualifiedName(typeName)) { + return 0; + } + // An E'' literal escapes the same way whatever standard_conforming_strings says: a plain '' + // literal with only the quotes doubled let a type name ending in a backslash break out + // once the session turned the setting off. Not bound as a parameter because this also + // runs in SIMPLE query mode, which has none. + String literal = "E'" + typeName.replace("\\", "\\\\").replace("'", "''") + "'"; + String[] row = queryRow("SELECT pg_catalog.to_regtype(" + literal + ")::oid", 1); if (row == null || row[0] == null) { return 0; } return parseOid(row[0]); } + /** + * Whether {@code name} is one to three dot-separated identifiers, each either unquoted (a letter, + * underscore or non-ASCII character, then those, digits or {@code $}) or double-quoted with + * {@code ""} as the escaped quote -- the forms {@code oid::regtype::text} produces for a composite. + */ + static boolean isQualifiedName(String name) { + int parts = 0; + int i = 0; + int n = name.length(); + while (true) { + if (i >= n) { + return false; + } + if (name.charAt(i) == '"') { + int j = i + 1; + while (true) { + if (j >= n) { + return false; + } + if (name.charAt(j) == '"') { + if (j + 1 < n && name.charAt(j + 1) == '"') { + j += 2; + continue; + } + break; + } + j++; + } + if (j == i + 1) { + return false; // "" is not an identifier + } + i = j + 1; + } else { + char first = name.charAt(i); + if (!(Character.isLetter(first) || first == '_' || first >= 0x80)) { + return false; + } + i++; + while (i < n) { + char c = name.charAt(i); + if (!(Character.isLetterOrDigit(c) || c == '_' || c == '$' || c >= 0x80)) { + break; + } + i++; + } + } + parts++; + if (i == n) { + return parts <= 3; + } + if (name.charAt(i) != '.') { + return false; + } + i++; + } + } + private void queryAndRegister(int oid) { // oid::regtype::text is the search_path-aware type name (qualified/quoted only when needed), // so a decoded composite's name round-trips through the to_regtype bind lookup. String[] type = queryRow( "SELECT typtype, typbasetype, typrelid, typelem, typcategory, oid::regtype::text" - + " FROM pg_type WHERE oid = " + Integer.toUnsignedString(oid), + + " FROM pg_catalog.pg_type WHERE oid OPERATOR(pg_catalog.=) " + Integer.toUnsignedString(oid), 6); if (type == null) { return; // unknown OID: leave the text/raw fallback in place @@ -166,13 +257,13 @@ private void queryAndRegister(int oid) { // handled before the typtype switch: resolve the element codec and register an array codec over // it so enum[]/composite[]/domain[] decode instead of falling back to the raw literal (C10.8). if ("A".equals(type[4])) { - registerArray(oid, parseOid(type[3])); + registerArray(oid, parseOid(requireColumn(type[3], "typelem"))); return; } - switch (type[0]) { + switch (requireColumn(type[0], "typtype")) { case "e" -> register(oid, UserTypeCodecs.enumCodec(oid, requireColumn(type[5], "typname"))); case "d" -> { - int baseOid = parseOid(type[1]); + int baseOid = parseOid(requireColumn(type[1], "typbasetype")); Codec base = resolve(baseOid); // A domain decodes through its base type's codec, so it is only registrable when // the base resolved; otherwise leave the text/raw fallback in place, exactly as @@ -181,7 +272,8 @@ private void queryAndRegister(int oid) { register(oid, UserTypeCodecs.domainCodec(oid, requireColumn(type[5], "typname"), base)); } } - case "c" -> registerComposite(oid, type[5], parseOid(type[2])); + case "c" -> + registerComposite(oid, requireColumn(type[5], "typname"), parseOid(requireColumn(type[2], "typrelid"))); default -> { // a plain base type with no specific codec keeps the text/raw fallback } @@ -202,12 +294,13 @@ private void registerArray(int oid, int elementOid) { private void registerComposite(int oid, String typeName, int relationOid) { List names = new ArrayList<>(); List fieldOids = new ArrayList<>(); - try (PgResultStream rs = connection.execute("SELECT attname, atttypid FROM pg_attribute WHERE attrelid = " - + Integer.toUnsignedString(relationOid) - + " AND attnum > 0 AND NOT attisdropped ORDER BY attnum")) { + try (PgResultStream rs = connection.execute( + "SELECT attname, atttypid FROM pg_catalog.pg_attribute WHERE attrelid OPERATOR(pg_catalog.=) " + + Integer.toUnsignedString(relationOid) + + " AND attnum > 0 AND NOT attisdropped ORDER BY attnum")) { while (rs.next()) { Row row = rs.currentRow(); - names.add(row.getString(1)); + names.add(requireColumn(row.getString(1), "pg_attribute.attname")); fieldOids.add(parseOid(requireColumn(row.getString(2), "pg_attribute.atttypid"))); } } @@ -249,6 +342,10 @@ private static String requireColumn(@Nullable String value, String column) { } private static int parseOid(String text) { - return (int) Long.parseLong(text.trim()); + try { + return (int) Long.parseLong(text.trim()); + } catch (NumberFormatException e) { + throw new PgException("malformed OID in the catalog: " + text, e); + } } } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/auth/Authenticator.java b/postgresql-client/src/main/java/org/postgresql/client/core/auth/Authenticator.java index 77eac104..68f5b638 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/auth/Authenticator.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/auth/Authenticator.java @@ -9,14 +9,23 @@ * writes any response message(s) via the {@link AuthExchange} and may keep state across * calls (for the multi-round-trip SCRAM exchange). * - *

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

    An {@code AuthenticationOk} is handled by the orchestration itself and never reaches + * {@link #handle}; the orchestration calls {@link #authenticationOk} instead. */ @Experimental public interface Authenticator { void handle(AuthenticationRequest request, AuthExchange exchange); + /** + * Called when the server reports {@code AuthenticationOk}, before the orchestration accepts it. + * An authenticator that started a multi-step exchange throws here if that exchange has not + * finished: a SCRAM server that skips {@code AuthenticationSASLFinal} never proves it knows the + * password, so accepting its {@code Ok} lets anyone in the middle of a TLS session that is not + * verified (below {@code verify-ca}) complete the login. The default does nothing. + */ + default void authenticationOk() {} + /** * Releases any driver-owned secret the authenticator holds across calls (the multi-round-trip * SCRAM exchange keeps one). The startup orchestration calls this in a {@code finally} around diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/auth/ScramMechanism.java b/postgresql-client/src/main/java/org/postgresql/client/core/auth/ScramMechanism.java index fd114160..b7575c5b 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/auth/ScramMechanism.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/auth/ScramMechanism.java @@ -31,6 +31,7 @@ final class ScramMechanism { private final ScramClient client; private final Secret password; + private boolean complete; private ScramMechanism(ScramClient client, Secret password) { this.client = client; @@ -86,22 +87,31 @@ static ScramMechanism begin(AuthenticationRequest.Sasl request, AuthExchange exc /** Processes the server-first message and sends the client-final message. */ void continueExchange(AuthenticationRequest.SaslContinue request, AuthExchange exchange) { + String clientFinal; try { client.serverFirstMessage(new String(request.data(), StandardCharsets.UTF_8)); - String clientFinal = client.clientFinalMessage().toString(); - exchange.send(new SASLResponse(clientFinal.getBytes(StandardCharsets.UTF_8))); - } catch (ScramException e) { + clientFinal = client.clientFinalMessage().toString(); + } catch (ScramException | IllegalArgumentException e) { + // The SCRAM client reports a bad base64 salt or a non-positive iteration count as an + // IllegalArgumentException; it is still the server's malformed message (ADR-0007). throw new PgAuthenticationException("invalid SCRAM server-first message", e); } + exchange.send(new SASLResponse(clientFinal.getBytes(StandardCharsets.UTF_8))); } /** Verifies the server-final message (server signature); throws on mismatch. */ void finish(AuthenticationRequest.SaslFinal request) { try { client.serverFinalMessage(new String(request.data(), StandardCharsets.UTF_8)); - } catch (ScramException e) { + } catch (ScramException | IllegalArgumentException e) { throw new PgAuthenticationException("SCRAM server signature verification failed", e); } + complete = true; + } + + /** Whether the server-final message arrived and its signature verified. */ + boolean isComplete() { + return complete; } /** diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/auth/StandardAuthenticator.java b/postgresql-client/src/main/java/org/postgresql/client/core/auth/StandardAuthenticator.java index 2572ea68..5d383ea2 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/auth/StandardAuthenticator.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/auth/StandardAuthenticator.java @@ -51,8 +51,13 @@ public void handle(AuthenticationRequest request, AuthExchange exchange) { switch (request) { case AuthenticationRequest.CleartextPassword ignored -> cleartextPassword(exchange); case AuthenticationRequest.Md5Password md5 -> md5Password(md5, exchange); - case AuthenticationRequest.Sasl sasl -> + case AuthenticationRequest.Sasl sasl -> { + if (scram != null) { + // Replacing the exchange would also orphan its secret, which cleanup() never zeroes. + throw new PgAuthenticationException("server restarted the SASL exchange"); + } scram = ScramMechanism.begin(sasl, exchange, requireSecret(AuthMethod.SCRAM, exchange)); + } case AuthenticationRequest.SaslContinue cont -> requireScram().continueExchange(cont, exchange); case AuthenticationRequest.SaslFinal fin -> requireScram().finish(fin); case AuthenticationRequest.Gss ignored -> throw unsupportedMechanism("GSSAPI"); @@ -76,6 +81,15 @@ private static PgAuthenticationException unsupportedMechanism(String name) { return new PgAuthenticationException("unsupported authentication mechanism: " + name); } + /** Refuses an {@code AuthenticationOk} that arrives while a SCRAM exchange is still open, as libpq does. */ + @Override + public void authenticationOk() { + if (scram != null && !scram.isComplete()) { + throw new PgAuthenticationException("server sent AuthenticationOk before completing the SCRAM exchange," + + " so it never proved knowledge of the password (possible man-in-the-middle)"); + } + } + /** Zeroes the driver-owned SCRAM secret if one is in flight; a no-op otherwise. */ @Override public void cleanup() { diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/codec/AbstractCodec.java b/postgresql-client/src/main/java/org/postgresql/client/core/codec/AbstractCodec.java index 038c3096..0e0d0b33 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/codec/AbstractCodec.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/codec/AbstractCodec.java @@ -1,5 +1,6 @@ package org.postgresql.client.core.codec; +import java.time.DateTimeException; import org.postgresql.client.core.Experimental; import org.postgresql.client.core.PgException; import org.postgresql.client.protocol.ProtocolConstants; @@ -43,10 +44,25 @@ public final int primaryOid() { @Override public final T decode(ByteSlice value, int formatCode, CodecContext context) { - if (formatCode == ProtocolConstants.FORMAT_BINARY) { - return decodeBinary(value, context); + try { + if (formatCode == ProtocolConstants.FORMAT_BINARY) { + return decodeBinary(value, context); + } + return decodeText(asText(value, context), context); + } catch (IllegalArgumentException | IndexOutOfBoundsException | DateTimeException | ArithmeticException e) { + throw malformedValue(javaType, e); } - return decodeText(asText(value, context), context); + } + + /** + * The value bytes come from the server, so a parser that rejects them (UUID.fromString, + * BigDecimal, java.time, a slice bound) is reporting malformed server data, which callers + * branching on the PgException hierarchy must see as one (ADR-0007). The value itself is left + * out of the message. + */ + static PgException malformedValue(Class javaType, RuntimeException cause) { + return new PgException( + "malformed " + javaType.getSimpleName() + " value from the server: " + cause.getMessage(), cause); } @Override diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/codec/ArrayCodecs.java b/postgresql-client/src/main/java/org/postgresql/client/core/codec/ArrayCodecs.java index 3e3dfec6..8becd711 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/codec/ArrayCodecs.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/codec/ArrayCodecs.java @@ -476,7 +476,7 @@ List parse() { if (i >= end || b[i] != '{') { throw new PgException("malformed array value: " + text()); } - return parseArray(); + return parseArray(1); } /** Skips an optional explicit-bounds prefix such as {@code [1:3]=} or {@code [-2:0][1:2]=}. */ @@ -492,7 +492,14 @@ private void skipDimensionPrefix() { } } - private List parseArray() { + private List parseArray(int depth) { + // The recursion is one frame per '{', and the value comes from the server: a few thousand + // nested braces would otherwise overflow the stack. The binary decoder enforces the same + // bound. + if (depth > BinaryDecoder.MAX_DIMENSIONS) { + throw new PgException( + "array exceeds PostgreSQL's " + BinaryDecoder.MAX_DIMENSIONS + "-dimension maximum"); + } i++; // consume '{' List out = new ArrayList<>(); skipWhitespace(); @@ -505,7 +512,7 @@ private List parseArray() { if (i >= end) { throw new PgException("unterminated array value: " + text()); } - out.add(b[i] == '{' ? parseArray() : parseElement()); + out.add(b[i] == '{' ? parseArray(depth + 1) : parseElement()); skipWhitespace(); if (i >= end) { throw new PgException("unterminated array value: " + text()); diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/codec/ScalarCodecs.java b/postgresql-client/src/main/java/org/postgresql/client/core/codec/ScalarCodecs.java index 313d34b8..ee1ed6a4 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/codec/ScalarCodecs.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/codec/ScalarCodecs.java @@ -311,6 +311,25 @@ static final class NumericCodec extends AbstractCodec { private static final int NUMERIC_NINF = 0xF000; // -Infinity (PG14+) private static final int NBASE = 10000; // base-10000 digits, 4 decimal places each + /** PostgreSQL's NUMERIC_DSCALE_MAX: the most fractional digits a numeric can carry. */ + private static final int MAX_DSCALE = 0x3FFF; + + /** Integer digits a numeric can carry: 4 per base-10000 group, weight at most int16 max. */ + private static final long MAX_INTEGER_DIGITS = 4L * (Short.MAX_VALUE + 1); + + /** + * Refuses what the server could not store, before any work proportional to the exponent: + * the binary form would otherwise wrap weight or dscale to 16 bits and store another value. + */ + private static void checkRange(BigDecimal value) { + if (value.scale() > MAX_DSCALE) { + throw new PgException("numeric value has more than " + MAX_DSCALE + " fractional digits"); + } + if (value.signum() != 0 && (long) value.precision() - value.scale() > MAX_INTEGER_DIGITS) { + throw new PgException("numeric value has more than " + MAX_INTEGER_DIGITS + " integer digits"); + } + } + NumericCodec() { super(BigDecimal.class, Oids.NUMERIC); } @@ -391,6 +410,7 @@ protected BigDecimal decodeBinary(ByteSlice value, CodecContext context) { @Override protected String encodeAsText(BigDecimal value, CodecContext context) { + checkRange(value); return value.toPlainString(); } @@ -441,6 +461,7 @@ public boolean prefersBinaryParameter() { */ @Override public void encodeBinaryTo(PgWriteBuffer buf, BigDecimal value, CodecContext context) { + checkRange(value); int dscale = Math.max(0, value.scale()); if (value.signum() == 0) { buf.writeShort(0); // ndigits diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/codec/UserTypeCodecs.java b/postgresql-client/src/main/java/org/postgresql/client/core/codec/UserTypeCodecs.java index 45194985..a3767713 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/codec/UserTypeCodecs.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/codec/UserTypeCodecs.java @@ -1,5 +1,6 @@ package org.postgresql.client.core.codec; +import java.time.DateTimeException; import java.util.ArrayList; import java.util.List; import org.jspecify.annotations.Nullable; @@ -124,7 +125,12 @@ public int[] oids() { @Override public Object decode(ByteSlice value, int formatCode, CodecContext context) { - return base.decode(value, formatCode, context); + try { + return base.decode(value, formatCode, context); + } catch (IllegalArgumentException | IndexOutOfBoundsException | DateTimeException | ArithmeticException e) { + // The base may be a user-registered codec rather than an AbstractCodec. + throw AbstractCodec.malformedValue(base.javaType(), e); + } } @Override diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/LocalFiles.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/LocalFiles.java new file mode 100644 index 00000000..fd4394fe --- /dev/null +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/LocalFiles.java @@ -0,0 +1,38 @@ +package org.postgresql.client.core.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.FileSystemException; +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * Reads the small local files a connection is configured with (TLS material, pgpass) without + * assuming the configured path names one. {@code /dev/zero} or {@code /dev/urandom} would otherwise + * be read until the heap ran out, and a FIFO or {@code /dev/stdin} would block the connect forever: + * {@code loginTimeout} does not interrupt a file read. + */ +public final class LocalFiles { + + /** Far beyond any certificate bundle, private key or pgpass file. */ + static final int MAX_BYTES = 16 << 20; + + private LocalFiles() {} + + /** + * Reads {@code file} whole, refusing anything but a regular file of at most {@link #MAX_BYTES}. + * A missing file fails the same way it did before, from the open. + */ + public static byte[] readRegularFile(Path file) throws IOException { + if (Files.exists(file) && !Files.isRegularFile(file)) { + throw new FileSystemException(file.toString(), null, "not a regular file"); + } + try (InputStream in = Files.newInputStream(file)) { + byte[] bytes = in.readNBytes(MAX_BYTES + 1); + if (bytes.length > MAX_BYTES) { + throw new FileSystemException(file.toString(), null, "larger than " + MAX_BYTES + " bytes"); + } + return bytes; + } + } +} diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/LogText.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/LogText.java new file mode 100644 index 00000000..f3fbf4a5 --- /dev/null +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/LogText.java @@ -0,0 +1,43 @@ +package org.postgresql.client.core.internal; + +import org.jspecify.annotations.Nullable; + +/** + * Makes text the server controls safe to put in a log line. A server error or notice can hold a + * newline, and logged as is it would start what looks like a separate, driver-written entry. + */ +public final class LogText { + + private LogText() {} + + /** {@code text} with CR, LF, tab and other control characters written as escapes. */ + public static @Nullable String escape(@Nullable String text) { + if (text == null) { + return null; + } + int i = 0; + while (i < text.length() && !Character.isISOControl(text.charAt(i))) { + i++; + } + if (i == text.length()) { + return text; + } + StringBuilder out = new StringBuilder(text.length() + 8).append(text, 0, i); + for (; i < text.length(); i++) { + char c = text.charAt(i); + switch (c) { + case '\r' -> out.append("\\r"); + case '\n' -> out.append("\\n"); + case '\t' -> out.append("\\t"); + default -> { + if (Character.isISOControl(c)) { + out.append(String.format("\\u%04x", (int) c)); + } else { + out.append(c); + } + } + } + } + return out.toString(); + } +} diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgPassFile.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgPassFile.java index cb8f42b7..4c269ecb 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgPassFile.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgPassFile.java @@ -48,7 +48,8 @@ public static Optional lookupFile(Path file, String host, int port, Stri return Optional.empty(); } try { - return lookup(Files.readString(file, StandardCharsets.UTF_8), host, port, database, user); + return lookup( + new String(LocalFiles.readRegularFile(file), StandardCharsets.UTF_8), host, port, database, user); } catch (IOException e) { throw new UncheckedIOException("failed to read pgpass file: " + file, e); } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgServiceFile.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgServiceFile.java index dfe36d1a..6a849097 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgServiceFile.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/PgServiceFile.java @@ -55,7 +55,7 @@ public static Optional> lookupFile(Path file, String service return Optional.empty(); } try { - return lookup(Files.readString(file, StandardCharsets.UTF_8), serviceName); + return lookup(new String(LocalFiles.readRegularFile(file), StandardCharsets.UTF_8), serviceName); } catch (IOException e) { throw new UncheckedIOException("failed to read service file: " + file, e); } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/Redaction.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/Redaction.java index 250070d2..1e19c893 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/Redaction.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/Redaction.java @@ -12,11 +12,10 @@ public final class Redaction { /** The placeholder substituted for a redacted secret. */ public static final String REDACTED = "***"; - // Password in a URI userinfo: scheme://user:PASSWORD@host - private static final Pattern USERINFO_PASSWORD = Pattern.compile("(//[^/@:\\s]+:)[^@/\\s]*(@)"); - - // password= / sslpassword= in key-value or query-string form. - private static final Pattern PASSWORD_PARAM = Pattern.compile("(?i)((?:password|sslpassword)=)[^&;\\s]*"); + // password= / sslpassword= in key-value or query-string form. A quoted key-value value runs to + // its closing quote, spaces and all; an unquoted one to the next '&' or whitespace. + private static final Pattern PASSWORD_PARAM = + Pattern.compile("(?i)((?:password|sslpassword)\\s*=\\s*)('(?:[^'\\\\]|\\\\.)*'?|[^&\\s]*)"); private Redaction() {} @@ -25,7 +24,25 @@ private Redaction() {} if (url == null) { return null; } - String redacted = USERINFO_PASSWORD.matcher(url).replaceAll("$1" + REDACTED + "$2"); + String redacted = redactUserinfoPassword(url); return PASSWORD_PARAM.matcher(redacted).replaceAll("$1" + REDACTED); } + + /** + * Replaces everything from the first ':' after "//" to the last '@'. A password may itself hold + * '/', '@', '?' or whitespace, so no narrower rule finds its end; when the '@' turns out to be in + * the query instead, this redacts too much, which is the safe way to be wrong. + */ + private static String redactUserinfoPassword(String url) { + int authority = url.indexOf("//"); + if (authority < 0) { + return url; + } + int colon = url.indexOf(':', authority + 2); + int at = url.lastIndexOf('@'); + if (colon < 0 || at < colon) { + return url; + } + return url.substring(0, colon + 1) + REDACTED + url.substring(at); + } } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java index ee6c5fda..1b1f7e93 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/StartupOrchestrator.java @@ -50,6 +50,20 @@ public final class StartupOrchestrator implements AuthExchange { */ private static final int MAX_STARTUP_PARAMETERS = 2048; + /** + * Messages startup reads before giving up. Each read succeeds, so socketTimeout never fires, and + * loginTimeout is off by default: a peer repeating password requests or notices would otherwise + * hold the handshake open forever. Room for the parameter cap plus a long notice stream. + */ + private static final int MAX_STARTUP_MESSAGES = 2 * MAX_STARTUP_PARAMETERS + 1024; + + /** + * Message length limit until AuthenticationOk, so a peer that has authenticated nothing cannot + * make the driver buffer up to the configured maximum. libpq refuses a message of a type outside + * VALID_LONG_MESSAGE_TYPE longer than 30000 bytes; none of the pre-authentication types is one. + */ + private static final int MAX_PRE_AUTH_MESSAGE_LENGTH = 30000; + private final WireChannel channel; private final PgConnectionConfig config; private final HostAndPort host; @@ -104,19 +118,29 @@ public StartupResult run() { BackendKeyData backendKeyData = null; int negotiatedVersion = requestedVersionCode; boolean credentialRequested = false; + boolean authenticated = false; // cleanup() zeroes any driver-owned secret the authenticator holds across calls (the SCRAM // exchange); the finally guarantees it runs on a failed login too, not only on success. + int messages = 0; + channel.limitMessageLength(MAX_PRE_AUTH_MESSAGE_LENGTH); try { while (true) { + if (++messages > MAX_STARTUP_MESSAGES) { + throw new PgConnectionException( + "the server sent more than " + MAX_STARTUP_MESSAGES + " messages during startup"); + } BackendMessage message = readNext(); switch (message) { case AuthenticationRequest.Ok ignored -> { + channel.clearMessageLengthLimit(); + authenticator.authenticationOk(); // authentication succeeded; enforce require_auth for the trust (no-credential) case if (!credentialRequested) { enforceRequireAuth(AuthMethod.NONE); enforceChannelBinding(AuthMethod.NONE); } + authenticated = true; } case AuthenticationRequest request -> { AuthMethod method = AuthMethod.of(request); @@ -126,6 +150,7 @@ public StartupResult run() { authenticator.handle(request, this); } case ParameterStatus status -> { + requireAuthenticated(authenticated, status); // Bounded: everything else read during startup is consumed and dropped, but a // ParameterStatus adds a map entry, so an unauthenticated peer could otherwise // make the driver allocate without limit before the login even completes. A real @@ -136,11 +161,15 @@ public StartupResult run() { } parameters.put(status.name(), status.value()); } - case BackendKeyData keyData -> backendKeyData = keyData; + case BackendKeyData keyData -> { + requireAuthenticated(authenticated, keyData); + backendKeyData = keyData; + } case NegotiateProtocolVersion negotiate -> negotiatedVersion = handleNegotiation(negotiate); case NoticeResponse notice -> listener.onNotice(ServerErrors.toNotice(notice.fields())); case ErrorResponse error -> throw mapStartupError(error); case ReadyForQuery ready -> { + requireAuthenticated(authenticated, ready); return new StartupResult(parameters, backendKeyData, negotiatedVersion, ready.status()); } default -> @@ -149,10 +178,24 @@ public StartupResult run() { } } } finally { + channel.clearMessageLengthLimit(); authenticator.cleanup(); } } + /** + * Refuses the post-authentication messages until {@code AuthenticationOk} has arrived. A peer + * that skips authentication altogether would otherwise complete startup without ever reaching + * the {@code AuthenticationOk} arm, where {@code require_auth} and {@code channelBinding=require} + * are enforced. libpq rejects anything but an authentication request or an error at this point. + */ + private static void requireAuthenticated(boolean authenticated, BackendMessage message) { + if (!authenticated) { + throw new PgConnectionException("expected authentication request from server, but received " + + message.getClass().getSimpleName()); + } + } + private List buildParameters() { List parameters = new ArrayList<>(); parameters.add(new StartupMessage.Parameter("user", config.user())); @@ -178,7 +221,20 @@ private int handleNegotiation(NegotiateProtocolVersion negotiate) { throw new PgConnectionException("server does not support the requested protocol version " + "and protocol-version fallback is not enabled"); } - return ProtocolConstants.protocolVersion(3, negotiate.newestMinorVersion()); + // A negotiation can only go down. Anything else is a broken or hostile peer claiming a + // version we never offered, which would switch on protocol features the session never + // agreed to; libpq refuses it the same way. + // The field is documented as the newest minor version, but servers send a whole version + // code (3 << 16 | minor), and libpq reads it as one. + int offered = ProtocolConstants.protocolMinor(requestedVersionCode); + int version = negotiate.newestMinorVersion(); + int major = ProtocolConstants.protocolMajor(version); + int minor = ProtocolConstants.protocolMinor(version); + if (major != 3 || minor >= offered) { + throw new PgConnectionException("invalid protocol negotiation: the server offered " + major + "." + minor + + " in reply to a request for 3." + offered); + } + return version; } /** Rejects an authentication method the {@code require_auth} policy does not permit. */ diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/TlsChannelBinding.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/TlsChannelBinding.java index a3650dfa..23dcac66 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/TlsChannelBinding.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/TlsChannelBinding.java @@ -1,10 +1,15 @@ package org.postgresql.client.core.internal; +import java.io.IOException; +import java.security.AlgorithmParameters; +import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; +import java.security.spec.PSSParameterSpec; import java.util.Locale; +import org.jspecify.annotations.Nullable; import org.postgresql.client.core.PgTlsException; /** @@ -21,7 +26,8 @@ private TlsChannelBinding() {} /** The {@code tls-server-end-point} value for {@code certificate}. */ static byte[] tlsServerEndPoint(X509Certificate certificate) { - String hashAlgorithm = hashAlgorithmFor(certificate.getSigAlgName()); + String hashAlgorithm = hashAlgorithmFor( + certificate.getSigAlgName(), certificate.getSigAlgOID(), certificate.getSigAlgParams()); try { MessageDigest digest = MessageDigest.getInstance(hashAlgorithm); return digest.digest(certificate.getEncoded()); @@ -32,9 +38,17 @@ static byte[] tlsServerEndPoint(X509Certificate certificate) { /** * Maps a certificate signature algorithm (for example {@code SHA256withRSA}) to the - * digest used for channel binding, upgrading MD5/SHA-1 to SHA-256. + * digest used for channel binding, upgrading MD5/SHA-1 to SHA-256. RSASSA-PSS names no hash in + * its algorithm name; the hash is in the signature parameters, and a PSS certificate signed with + * SHA-384 or SHA-512 must bind with that hash, as the server computes it. */ - private static String hashAlgorithmFor(String signatureAlgorithm) { + static String hashAlgorithmFor(String signatureAlgorithm, String oid, byte @Nullable [] parameters) { + if (RSASSA_PSS_OID.equals(oid) || "RSASSA-PSS".equalsIgnoreCase(signatureAlgorithm)) { + String pssHash = pssDigest(parameters); + if (pssHash != null) { + return hashAlgorithmFor(pssHash, "", null); + } + } String name = signatureAlgorithm.toUpperCase(Locale.ROOT); int with = name.indexOf("WITH"); String hash = with > 0 ? name.substring(0, with) : name; @@ -48,4 +62,20 @@ private static String hashAlgorithmFor(String signatureAlgorithm) { default -> "SHA-256"; }; } + + private static final String RSASSA_PSS_OID = "1.2.840.113549.1.1.10"; + + /** The digest named by DER-encoded RSASSA-PSS parameters, or {@code null} if they do not decode. */ + private static @Nullable String pssDigest(byte @Nullable [] parameters) { + if (parameters == null) { + return null; + } + try { + AlgorithmParameters decoded = AlgorithmParameters.getInstance("RSASSA-PSS"); + decoded.init(parameters); + return decoded.getParameterSpec(PSSParameterSpec.class).getDigestAlgorithm(); + } catch (GeneralSecurityException | IOException e) { + return null; // fall back to the name-based mapping, as before + } + } } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/WireChannel.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/WireChannel.java index afeffb4d..fc1542e5 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/WireChannel.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/WireChannel.java @@ -8,6 +8,7 @@ import org.postgresql.client.core.transport.Transport; import org.postgresql.client.protocol.ProtocolDecoder; import org.postgresql.client.protocol.ProtocolEncoder; +import org.postgresql.client.protocol.ProtocolException; import org.postgresql.client.protocol.message.BackendMessage; import org.postgresql.client.protocol.message.FrontendMessage; @@ -132,18 +133,24 @@ public void flush() { /** Blocks until the next backend message is available, or fails if the server closes. */ public BackendMessage next() { - BackendMessage message = decoder.next(); - while (message == null) { - // Read straight into the decoder's framing buffer (no staging array + copy): the - // transport fills the buffer's writable tail directly. Safe because a message is only - // returned once fully framed, and the caller consumes it before the next read here. - int n = decoder.fillFrom(transport::read); - if (n < 0) { - throw new PgConnectionException("server closed the connection"); + try { + BackendMessage message = decoder.next(); + while (message == null) { + // Read straight into the decoder's framing buffer (no staging array + copy): the + // transport fills the buffer's writable tail directly. Safe because a message is only + // returned once fully framed, and the caller consumes it before the next read here. + int n = decoder.fillFrom(transport::read); + if (n < 0) { + throw new PgConnectionException("server closed the connection"); + } + message = decoder.next(); } - message = decoder.next(); + return message; + } catch (ProtocolException e) { + // A PgConnectionException, so the callers that mark the connection broken on PgException + // do so for a malformed message too. + throw new PgConnectionException("protocol violation: " + e.getMessage(), e); } - return message; } public Transport transport() { @@ -158,6 +165,16 @@ public void shrinkReadBuffer() { decoder.shrinkIfIdle(); } + /** Caps inbound messages at {@code limit} bytes, within the configured maximum, until cleared. */ + public void limitMessageLength(long limit) { + decoder.limitMessageLength(limit); + } + + /** Restores the configured maximum inbound message length. */ + public void clearMessageLengthLimit() { + decoder.clearMessageLengthLimit(); + } + /** Whether this connection is running over TLS. */ public boolean isTls() { return transport instanceof TlsTransport; diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java index a5b2cab6..f1a3662a 100644 --- a/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/ConnectionStringParser.java @@ -1,7 +1,6 @@ package org.postgresql.client.core.internal.jdbc; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.PosixFilePermission; @@ -124,6 +123,9 @@ private static void parseUri(String rest, Map params, List queryParams = new LinkedHashMap<>(); for (String pair : query.split("&")) { if (pair.isEmpty()) { continue; @@ -131,8 +133,9 @@ private static void parseUri(String rest, Map params, List putIfAbsent(params, key, value)); } } @@ -212,7 +215,7 @@ private static void parseKeyValue(String input, Map params) { i++; } } - putIfAbsent(params, key, value.toString()); + params.put(key, value.toString()); // a repeated key keeps its last value, as in libpq } } @@ -272,8 +275,13 @@ private static PgConnectionConfig toConfig( // environment does not defer it: a URL parameter outranks the environment, so a stray // PGSSLMODE=disable must not silently turn an explicit ssl=true into a cleartext session. String ssl = params.get("ssl"); - if (ssl != null && urlSslMode == null && isTruthy(ssl)) { - builder.sslMode(SslMode.VERIFY_FULL); + if (ssl != null && urlSslMode == null) { + if (isTruthy(ssl)) { + builder.sslMode(SslMode.VERIFY_FULL); + } else if (!isFalsy(ssl)) { + // ssl=require or ssl=verify-full must not quietly leave the connection at prefer. + throw new PgConfigurationException("invalid ssl: " + ssl + " (expected true or false)"); + } } String channelBinding = firstNonNull(params.get("channel_binding"), env.get("PGCHANNELBINDING")); if (channelBinding != null) { @@ -571,6 +579,11 @@ private static boolean isTruthy(String value) { return v.isEmpty() || v.equals("true") || v.equals("1") || v.equals("yes") || v.equals("on"); } + private static boolean isFalsy(String value) { + String v = value.trim().toLowerCase(java.util.Locale.ROOT); + return v.equals("false") || v.equals("0") || v.equals("no") || v.equals("off"); + } + private static @Nullable String firstNonNull(@Nullable String... values) { for (String value : values) { if (value != null) { @@ -581,20 +594,6 @@ private static boolean isTruthy(String value) { } private static String decode(String s) { - if (s.indexOf('%') < 0) { - return s; - } - byte[] bytes = new byte[s.length()]; - int len = 0; - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c == '%' && i + 2 < s.length()) { - bytes[len++] = (byte) Integer.parseInt(s.substring(i + 1, i + 3), 16); - i += 2; - } else { - bytes[len++] = (byte) c; - } - } - return new String(bytes, 0, len, StandardCharsets.UTF_8); + return PercentDecoding.decode(s); } } diff --git a/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/PercentDecoding.java b/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/PercentDecoding.java new file mode 100644 index 00000000..308722a4 --- /dev/null +++ b/postgresql-client/src/main/java/org/postgresql/client/core/internal/jdbc/PercentDecoding.java @@ -0,0 +1,50 @@ +package org.postgresql.client.core.internal.jdbc; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import org.postgresql.client.core.PgConfigurationException; + +/** + * Decodes the {@code %XX} escapes in a connection-URL component, for the core parser and the + * pgjdbc-compat driver alike. Only {@code %XX} is special; a {@code +} stays a {@code +}, as in libpq. + */ +public final class PercentDecoding { + + private PercentDecoding() {} + + /** + * Decodes {@code s}, reading the escaped bytes as UTF-8. Characters outside the escapes are kept + * whole: the decoders this replaced narrowed each one to a single byte whenever the component + * also held a {@code %}, which mangled any non-ASCII character. A {@code %} not followed by two + * hex digits is refused, as libpq does; the message gives its position, not the value, which can + * be a password. + */ + public static String decode(String s) { + int percent = s.indexOf('%'); + if (percent < 0) { + return s; + } + ByteArrayOutputStream bytes = new ByteArrayOutputStream(s.length()); + bytes.writeBytes(s.substring(0, percent).getBytes(StandardCharsets.UTF_8)); + int i = percent; + while (i < s.length()) { + char c = s.charAt(i); + if (c == '%') { + int high = i + 2 < s.length() ? Character.digit(s.charAt(i + 1), 16) : -1; + int low = high >= 0 ? Character.digit(s.charAt(i + 2), 16) : -1; + if (low < 0) { + throw new PgConfigurationException( + "invalid percent-encoding at position " + i + " of a connection URL component"); + } + bytes.write(high << 4 | low); + i += 3; + } else { + int next = s.indexOf('%', i); + int end = next < 0 ? s.length() : next; + bytes.writeBytes(s.substring(i, end).getBytes(StandardCharsets.UTF_8)); + i = end; + } + } + return bytes.toString(StandardCharsets.UTF_8); + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java index f3f9bbf8..2099bcde 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/ConnectionStringParserTest.java @@ -158,6 +158,33 @@ void anSslModeParameterStillOutranksSslTrue() { assertEquals(SslMode.REQUIRE, c.sslMode()); } + @Test + void anUnrecognisedSslValueIsRefused() { + for (String value : new String[] {"require", "verify-full", "y", "enabled"}) { + assertThrows( + PgConfigurationException.class, + () -> parse("postgresql://h/db?user=app&ssl=" + value), + "ssl=" + value); + } + } + + @Test + void sslFalseKeepsTheDefaultMode() { + for (String value : new String[] {"false", "0", "no", "off", "FALSE"}) { + assertEquals( + SslMode.PREFER, + parse("postgresql://h/db?user=app&ssl=" + value).sslMode(), + value); + } + } + + @Test + void anSslModeParameterMakesTheSslValueIrrelevant() { + // As in pgjdbc, ssl is ignored when sslmode is set, so its value is not checked either. + PgConnectionConfig c = parse("postgresql://h/db?user=app&ssl=require&sslmode=verify-ca"); + assertEquals(SslMode.VERIFY_CA, c.sslMode()); + } + @Test void ignoreEnvironmentDropsEveryPgVariable() { // One switch rather than a list of variables to distrust: the set grows, and what the @@ -245,4 +272,45 @@ void rejectsNullAndMalformed() { assertThrows(PgConfigurationException.class, () -> ConnectionStringParser.parse(null, Map.of())); assertThrows(PgConfigurationException.class, () -> ConnectionStringParser.parse("host user=app", Map.of())); } + + @Test + void malformedPercentEscapeIsAConfigurationError() { + for (String url : + new String[] {"postgresql://h/db?user=app&password=a%zzb", "postgresql://h/d%4", "postgresql://h/db%" + }) { + PgConfigurationException e = assertThrows( + PgConfigurationException.class, () -> ConnectionStringParser.parse(url, Map.of()), url); + assertFalse(e.getMessage().contains("a%zzb"), e.getMessage()); + } + } + + @Test + void nonAsciiCharactersSurviveAlongsideEscapes() { + PgConnectionConfig c = ConnectionStringParser.parse( + "postgresql://h/caf\u00e9%20db?user=\u00fcser%2B1&application_name=\u65e5%41", Map.of()); + assertEquals("caf\u00e9 db", c.database()); + assertEquals("\u00fcser+1", c.user()); + assertEquals("\u65e5A", c.applicationName()); + } + + @Test + void repeatedQueryKeyKeepsItsLastValue() { + PgConnectionConfig c = parse("postgresql://h/db?user=app&sslmode=disable&application_name=a&sslmode=require"); + assertEquals(SslMode.REQUIRE, c.sslMode()); + assertEquals("a", c.applicationName()); + } + + @Test + void userinfoAndPathStillOutrankTheQuery() { + PgConnectionConfig c = parse("postgresql://alice@h/db?user=mallory&dbname=other&user=eve"); + assertEquals("alice", c.user()); + assertEquals("db", c.database()); + } + + @Test + void repeatedKeyValueKeyKeepsItsLastValue() { + PgConnectionConfig c = + ConnectionStringParser.parse("host=h user=app sslmode=disable sslmode=require", Map.of()); + assertEquals(SslMode.REQUIRE, c.sslMode()); + } } diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/DirectTlsAlpnTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/DirectTlsAlpnTest.java new file mode 100644 index 00000000..4b86f619 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/DirectTlsAlpnTest.java @@ -0,0 +1,100 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLSocket; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +/** + * Direct TLS has no SSLRequest exchange, so the server selecting the {@code postgresql} ALPN + * protocol is the only confirmation that it speaks PostgreSQL on this connection. + */ +@Timeout(30) +class DirectTlsAlpnTest { + + @TempDir + Path dir; + + private SSLContext serverContext() throws Exception { + SslConfig material = SslConfig.builder() + .certFile(copy("/tls/test-client.crt")) + .keyFile(copy("/tls/test-client.key")) + .build(); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(SslMaterials.keyManagers(material), null, null); + return context; + } + + private Path copy(String resource) throws IOException { + try (InputStream in = DirectTlsAlpnTest.class.getResourceAsStream(resource)) { + assertNotNull(in, resource); + return Files.write(dir.resolve(Path.of(resource).getFileName().toString()), in.readAllBytes()); + } + } + + /** Accepts one connection, completes the handshake selecting {@code alpn} (none if null), then hangs up. */ + private static Thread serve(SSLServerSocket server, String alpn) { + return Thread.ofVirtual().start(() -> { + try (SSLSocket socket = (SSLSocket) server.accept()) { + if (alpn != null) { + SSLParameters parameters = socket.getSSLParameters(); + parameters.setApplicationProtocols(new String[] {alpn}); + socket.setSSLParameters(parameters); + } + socket.startHandshake(); + socket.getInputStream().read(); + } catch (IOException e) { + // the client gave up, which is what the refusing case expects + } + }); + } + + private static PgConnectionConfig config(int port) { + return PgConnectionConfig.builder() + .host("127.0.0.1", port) + .user("app") + .database("appdb") + .sslMode(SslMode.REQUIRE) + .sslNegotiation(SslNegotiation.DIRECT) + .loginTimeout(Duration.ofSeconds(5)) + .build(); + } + + @Test + void handshakeWithoutAlpnIsRefused() throws Exception { + try (SSLServerSocket server = (SSLServerSocket) + serverContext().getServerSocketFactory().createServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + Thread t = serve(server, null); + PgException e = assertThrows(PgException.class, () -> PgConnections.connect(config(server.getLocalPort()))); + assertTrue(e.getMessage().contains("ALPN"), e.getMessage()); + t.join(5000); + } + } + + @Test + void handshakeSelectingPostgresqlProceeds() throws Exception { + try (SSLServerSocket server = (SSLServerSocket) + serverContext().getServerSocketFactory().createServerSocket(0, 1, InetAddress.getLoopbackAddress())) { + Thread t = serve(server, "postgresql"); + // The fake server hangs up after reading the startup message, so the connect still + // fails, but past the ALPN check. + PgException e = assertThrows(PgException.class, () -> PgConnections.connect(config(server.getLocalPort()))); + assertFalse(String.valueOf(e.getMessage()).contains("ALPN"), e.getMessage()); + t.join(5000); + } + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/EmbeddedNulConfigTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/EmbeddedNulConfigTest.java new file mode 100644 index 00000000..b6e516e2 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/EmbeddedNulConfigTest.java @@ -0,0 +1,42 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.function.UnaryOperator; +import org.junit.jupiter.api.Test; + +/** + * Startup values go out NUL-terminated, so an embedded NUL is refused when the configuration is + * built: as a PgConfigurationException, not an IllegalArgumentException from the wire encoder. + */ +class EmbeddedNulConfigTest { + + private static PgConfigurationException refuse(UnaryOperator setting) { + PgConnectionConfig.Builder builder = + PgConnectionConfig.builder().host("h").user("app").database("db"); + return assertThrows( + PgConfigurationException.class, () -> setting.apply(builder).build()); + } + + @Test + void everyStartupValueIsChecked() { + assertTrue(refuse(b -> b.user("ap\0p")).getMessage().contains("user")); + assertTrue(refuse(b -> b.database("d\0b")).getMessage().contains("database")); + assertTrue(refuse(b -> b.applicationName("a\0")).getMessage().contains("application_name")); + assertTrue(refuse(b -> b.options("-c a=\0")).getMessage().contains("options")); + assertTrue(refuse(b -> b.runtimeParameter("search_path", "a\0b")) + .getMessage() + .contains("search_path")); + assertTrue( + refuse(b -> b.runtimeParameter("bad\0name", "x")).getMessage().contains("name")); + } + + @Test + void passwordIsCheckedWithoutBeingQuoted() { + PgConfigurationException e = refuse(b -> b.password("s3c\0ret")); + assertTrue(e.getMessage().contains("password"), e.getMessage()); + assertFalse(e.getMessage().contains("s3c"), e.getMessage()); + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/LargeObjectReadLengthTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/LargeObjectReadLengthTest.java new file mode 100644 index 00000000..22822bc5 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/LargeObjectReadLengthTest.java @@ -0,0 +1,63 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.nio.ByteBuffer; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.auth.TrustAuthenticator; +import org.postgresql.client.core.internal.StartupOrchestrator; +import org.postgresql.client.core.internal.StartupResult; +import org.postgresql.client.core.internal.WireChannel; +import org.postgresql.client.core.transport.BackendWire; +import org.postgresql.client.core.transport.MockServer; +import org.postgresql.client.protocol.MessageType; + +/** An {@code lo_read} reply longer than requested would overrun a caller's buffer sized by the request. */ +class LargeObjectReadLengthTest { + + private static byte[] functionCallResponse(byte[] result) { + return ByteBuffer.allocate(1 + 4 + 4 + result.length) + .put((byte) 'V') + .putInt(4 + 4 + result.length) + .putInt(result.length) + .put(result) + .array(); + } + + /** Opens fd 7, then answers every lo_read with {@code readReply}. */ + private static PgLargeObject open(byte[] readReply) { + int[] calls = {0}; + MockServer server = new MockServer().onMessage((s, f) -> { + if (f.type() == MessageType.Frontend.FUNCTION_CALL) { + byte[] result = calls[0]++ == 0 ? new byte[] {0, 0, 0, 7} : readReply; + s.send(functionCallResponse(result), BackendWire.readyForQuery('T')); + } + }); + PgConnectionConfig config = PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .build(); + server.onStartup((s, f) -> s.send(BackendWire.authenticationOk(), BackendWire.readyForQuery('I'))); + WireChannel channel = new WireChannel(server, SizeLimits.unlimited()); + StartupResult startup = new StartupOrchestrator( + channel, config, HostAndPort.of("h"), TrustAuthenticator.INSTANCE, PgConnectionListener.NO_OP) + .run(); + CoreConnection connection = + new CoreConnection(channel, config, startup, HostAndPort.of("h"), PgConnectionListener.NO_OP); + return connection.openLargeObject(1234, LargeObjects.INV_READ); + } + + @Test + void longerReplyThanRequestedIsRefused() { + PgLargeObject lo = open(new byte[1000]); + assertThrows(PgException.class, () -> lo.read(4)); + } + + @Test + void shortOrExactRepliesAreReturned() { + assertArrayEquals(new byte[] {1, 2}, open(new byte[] {1, 2}).read(4)); + assertArrayEquals(new byte[] {1, 2, 3, 4}, open(new byte[] {1, 2, 3, 4}).read(4)); + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/LocalFileSpecialPathTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/LocalFileSpecialPathTest.java new file mode 100644 index 00000000..22c117c9 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/LocalFileSpecialPathTest.java @@ -0,0 +1,82 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.io.RandomAccessFile; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.postgresql.client.core.internal.PgPassFile; + +/** + * TLS material and pgpass paths that do not name a regular file fail fast: {@code /dev/zero} used + * to run the heap out, and a FIFO blocked the connect forever, out of {@code loginTimeout}'s reach. + */ +@Timeout(value = 30, unit = TimeUnit.SECONDS) +class LocalFileSpecialPathTest { + + private static final Path DEV_ZERO = Path.of("/dev/zero"); + + @TempDir + Path dir; + + private Path fifo() throws Exception { + Path fifo = dir.resolve("fifo"); + Process mkfifo; + try { + mkfifo = new ProcessBuilder("mkfifo", fifo.toString()).start(); + } catch (java.io.IOException e) { + assumeTrue(false, "mkfifo is not available"); + throw e; + } + assumeTrue(mkfifo.waitFor() == 0 && Files.exists(fifo), "mkfifo failed"); + return fifo; + } + + @Test + void rootCertOnDevZeroFails() { + assumeTrue(Files.exists(DEV_ZERO)); + SslConfig ssl = SslConfig.builder().rootCertFile(DEV_ZERO).build(); + assertThrows(PgTlsException.class, () -> SslMaterials.verifyingTrustManagers(ssl)); + } + + @Test + void rootCertOnAFifoFails() throws Exception { + SslConfig ssl = SslConfig.builder().rootCertFile(fifo()).build(); + assertThrows(PgTlsException.class, () -> SslMaterials.verifyingTrustManagers(ssl)); + } + + @Test + void crlOnADirectoryFails() { + SslConfig ssl = SslConfig.builder().crlFile(dir).build(); + assertThrows(PgTlsException.class, () -> SslMaterials.verifyingTrustManagers(ssl)); + } + + @Test + void clientCertAndKeyOnDevZeroFail() { + assumeTrue(Files.exists(DEV_ZERO)); + SslConfig ssl = SslConfig.builder().certFile(DEV_ZERO).keyFile(DEV_ZERO).build(); + assertThrows(PgTlsException.class, () -> SslMaterials.keyManagers(ssl)); + } + + @Test + void oversizedRegularFileFails() throws Exception { + Path big = dir.resolve("big.pem"); + try (RandomAccessFile file = new RandomAccessFile(big.toFile(), "rw")) { + file.setLength(17L << 20); // sparse: costs no disk + } + SslConfig ssl = SslConfig.builder().rootCertFile(big).build(); + assertThrows(PgTlsException.class, () -> SslMaterials.verifyingTrustManagers(ssl)); + } + + @Test + void pgpassOnAFifoFails() throws Exception { + Path fifo = fifo(); + assertThrows(UncheckedIOException.class, () -> PgPassFile.lookupFile(fifo, "h", 5432, "db", "u")); + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/LogTextTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/LogTextTest.java new file mode 100644 index 00000000..90bd9c51 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/LogTextTest.java @@ -0,0 +1,26 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.internal.LogText; + +/** Server text goes into log lines escaped, so a newline in it cannot start a forged entry. */ +class LogTextTest { + + @Test + void escapesLineBreaksAndControlCharacters() { + assertEquals( + "relation does not exist\\n12:00:00 WARN admin password reset\\r\\t\\u0007", + LogText.escape("relation does not exist\n12:00:00 WARN admin password reset\r\t\u0007")); + } + + @Test + void leavesOrdinaryTextAlone() { + String text = "duplicate key value violates unique constraint \"t_pkey\" (caf\u00e9)"; + assertSame(text, LogText.escape(text)); + assertNull(LogText.escape(null)); + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/MalformedMessageTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/MalformedMessageTest.java new file mode 100644 index 00000000..4c3d682f --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/MalformedMessageTest.java @@ -0,0 +1,73 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.auth.TrustAuthenticator; +import org.postgresql.client.core.internal.StartupOrchestrator; +import org.postgresql.client.core.internal.StartupResult; +import org.postgresql.client.core.internal.WireChannel; +import org.postgresql.client.core.transport.BackendWire; +import org.postgresql.client.core.transport.MockServer; + +/** A message the decoder refuses breaks the connection, on every read path. */ +class MalformedMessageTest { + + /** A RowDescription claiming one field but carrying none. */ + private static final byte[] TRUNCATED_ROW_DESCRIPTION = {'T', 0, 0, 0, 6, 0, 1}; + + private static CoreConnection connect(MockServer server) { + PgConnectionConfig config = PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .build(); + server.onStartup((s, f) -> s.send( + BackendWire.authenticationOk(), + BackendWire.parameterStatus("server_version", "17.0"), + BackendWire.parameterStatus("client_encoding", "UTF8"), + BackendWire.parameterStatus("DateStyle", "ISO, MDY"), + BackendWire.parameterStatus("IntervalStyle", "iso_8601"), + BackendWire.parameterStatus("standard_conforming_strings", "on"), + BackendWire.parameterStatus("TimeZone", "UTC"), + BackendWire.readyForQuery('I'))); + WireChannel channel = new WireChannel(server, SizeLimits.unlimited()); + StartupResult startup = new StartupOrchestrator( + channel, config, HostAndPort.of("h"), TrustAuthenticator.INSTANCE, PgConnectionListener.NO_OP) + .run(); + CoreConnection connection = + new CoreConnection(channel, config, startup, HostAndPort.of("h"), PgConnectionListener.NO_OP); + connection.bootstrapSession(); + return connection; + } + + @Test + void simpleQueryBreaksTheConnection() { + MockServer server = new MockServer().onMessage((s, f) -> s.send(TRUNCATED_ROW_DESCRIPTION)); + CoreConnection connection = connect(server); + + assertThrows(PgConnectionException.class, () -> { + try (PgResultStream rs = connection.execute("SELECT 1")) { + rs.next(); + } + }); + assertTrue(connection.isBroken()); + assertFalse(connection.isValid()); + } + + @Test + void extendedQueryBreaksTheConnection() { + MockServer server = new MockServer().onMessage((s, f) -> s.send(TRUNCATED_ROW_DESCRIPTION)); + CoreConnection connection = connect(server); + + assertThrows(PgConnectionException.class, () -> { + try (PgResultStream rs = connection.execute("SELECT $1::int4", List.of(1))) { + rs.next(); + } + }); + assertTrue(connection.isBroken()); + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/PgEncodingsTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/PgEncodingsTest.java index 022c3192..bfb768c7 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/PgEncodingsTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/PgEncodingsTest.java @@ -22,6 +22,13 @@ void utf8NamesMapToUtf8() { assertEquals(StandardCharsets.UTF_8, PgEncodings.toCharset("UNICODE")); } + @Test + void asciiUnsafeEncodingsAreRefused() { + for (String name : new String[] {"SJIS", "SHIFT_JIS_2004", "BIG5", "GBK", "UHC", "JOHAB", "GB18030", "sjis"}) { + assertThrows(PgConfigurationException.class, () -> PgEncodings.toCharset(name), name); + } + } + @Test void nullDefaultsToUtf8() { assertEquals(StandardCharsets.UTF_8, PgEncodings.toCharset(null)); diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/SecretTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/SecretTest.java index ceae1bf8..a38e7b55 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/SecretTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/SecretTest.java @@ -89,6 +89,19 @@ void redactsPasswordParameters() { Redaction.redactUrl("postgresql://db/app?user=app&password=hunter2&x=1")); } + @Test + void redactsPasswordsWithAwkwardCharacters() { + for (String password : new String[] {"a/b", "p@ss", "p ss", "q?x", "a\"b"}) { + String redacted = Redaction.redactUrl("postgresql://user:" + password + "@db.example.com/app"); + assertEquals("postgresql://user:***@db.example.com/app", redacted, password); + } + assertEquals( + "host=h user=u password=*** dbname=d", + Redaction.redactUrl("host=h user=u password='my secret' dbname=d")); + assertEquals("host=h password = *** dbname=d", Redaction.redactUrl("host=h password = 'it\\'s' dbname=d")); + assertEquals("host=h password=***", Redaction.redactUrl("host=h password=a;b")); + } + @Test void redactUrlWithoutPasswordIsUnchanged() { assertEquals( diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/SessionParameterChangeTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/SessionParameterChangeTest.java new file mode 100644 index 00000000..e2e60149 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/SessionParameterChangeTest.java @@ -0,0 +1,114 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.auth.TrustAuthenticator; +import org.postgresql.client.core.internal.StartupOrchestrator; +import org.postgresql.client.core.internal.StartupResult; +import org.postgresql.client.core.internal.WireChannel; +import org.postgresql.client.core.transport.BackendWire; +import org.postgresql.client.core.transport.MockServer; + +/** + * A runtime {@code ParameterStatus} the connection cannot live with throws out of the middle of a + * response. The rest of that response is still on the wire, so the connection must be marked broken + * rather than reused: on a pre-14 server, where the report precedes {@code CommandComplete}, the next + * statement would otherwise read this one's tail and the one after it the next one's rows. + */ +class SessionParameterChangeTest { + + private static CoreConnection connect(MockServer server) { + PgConnectionConfig config = PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .build(); + server.onStartup((s, f) -> s.send( + BackendWire.authenticationOk(), + BackendWire.parameterStatus("server_version", "13.0"), + BackendWire.parameterStatus("client_encoding", "UTF8"), + BackendWire.parameterStatus("DateStyle", "ISO, MDY"), + BackendWire.parameterStatus("IntervalStyle", "iso_8601"), + BackendWire.parameterStatus("standard_conforming_strings", "on"), + BackendWire.parameterStatus("TimeZone", "UTC"), + BackendWire.readyForQuery('I'))); + WireChannel channel = new WireChannel(server, SizeLimits.unlimited()); + StartupResult startup = new StartupOrchestrator( + channel, config, HostAndPort.of("h"), TrustAuthenticator.INSTANCE, PgConnectionListener.NO_OP) + .run(); + CoreConnection connection = + new CoreConnection(channel, config, startup, HostAndPort.of("h"), PgConnectionListener.NO_OP); + connection.bootstrapSession(); + return connection; + } + + @Test + void reportBeforeCommandCompleteBreaksTheConnection() { + MockServer server = new MockServer() + .onMessage((s, f) -> s.send( + BackendWire.parameterStatus("client_encoding", "WIN1251"), + BackendWire.commandComplete("SET"), + BackendWire.readyForQuery('I'))); + CoreConnection connection = connect(server); + + assertThrows(PgException.class, () -> connection.execute("SET client_encoding TO 'WIN1251'")); + assertTrue(connection.isBroken(), "the SET's remaining messages are still unread"); + } + + @Test + void reportBeforeReadyForQueryBreaksTheConnection() { + MockServer server = new MockServer() + .onMessage((s, f) -> s.send( + BackendWire.commandComplete("SET"), + BackendWire.parameterStatus("client_encoding", "WIN1251"), + BackendWire.readyForQuery('I'))); + CoreConnection connection = connect(server); + + assertThrows(PgException.class, () -> { + try (PgResultStream rs = connection.execute("SET client_encoding TO 'WIN1251'")) { + rs.next(); + } + }); + assertTrue(connection.isBroken()); + } + + @Test + void standardConformingStringsTurnedOffBreaksTheConnection() { + // The connect-time refusal of "off" (forceSessionDefaults) has to hold for a later SET too: + // the SQL lexers would otherwise misread 'It\'s' on this connection from then on. + MockServer server = new MockServer() + .onMessage((s, f) -> s.send( + BackendWire.commandComplete("SET"), + BackendWire.parameterStatus("standard_conforming_strings", "off"), + BackendWire.readyForQuery('I'))); + CoreConnection connection = connect(server); + + PgConnectionException e = assertThrows(PgConnectionException.class, () -> { + try (PgResultStream rs = connection.execute("SET standard_conforming_strings = off")) { + rs.next(); + } + }); + assertTrue(e.getMessage().contains("standard_conforming_strings"), e.getMessage()); + assertTrue(connection.isBroken()); + } + + @Test + void anAsciiUnsafeClientEncodingBreaksTheConnection() { + MockServer server = new MockServer() + .onMessage((s, f) -> s.send( + BackendWire.commandComplete("SET"), + BackendWire.parameterStatus("client_encoding", "SJIS"), + BackendWire.readyForQuery('I'))); + CoreConnection connection = connect(server); + + PgException e = assertThrows(PgException.class, () -> { + try (PgResultStream rs = connection.execute("SET client_encoding TO 'SJIS'")) { + rs.next(); + } + }); + assertTrue(e.getMessage().contains("SJIS"), e.getMessage()); + assertTrue(connection.isBroken()); + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/SimpleRowBinaryDecodeTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/SimpleRowBinaryDecodeTest.java index d227d4eb..f98690fb 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/SimpleRowBinaryDecodeTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/SimpleRowBinaryDecodeTest.java @@ -236,6 +236,10 @@ void binaryFastPathsRejectMismatchedWidths() { // N1.21 Oids.FLOAT8, new byte[] {0, 0, 0, 0}, row -> assertThrows(PgException.class, () -> row.getDoublePrimitive(1))); + // A zero-length bool read the byte after the column, or past the end of a buffered row. + assertBinaryColumn( + Oids.BOOL, new byte[0], row -> assertThrows(PgException.class, () -> row.getBooleanPrimitive(1))); + assertBinaryColumn(Oids.BOOL, new byte[] {1}, row -> assertTrue(row.getBooleanPrimitive(1))); } @Test diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/SizeLimitsTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/SizeLimitsTest.java index fdce94ec..eddb6760 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/SizeLimitsTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/SizeLimitsTest.java @@ -25,7 +25,7 @@ void defaultsBoundMessagesButNotValues() { SizeLimits limits = SizeLimits.defaults(); assertTrue(limits.limitsMessages(), "the default must cap whole messages (M2)"); assertFalse(limits.limitsValues()); - assertEquals(1L << 30, limits.maxMessageLength()); + assertEquals(0x3FFFFFFEL + 4, limits.maxMessageLength()); } @Test diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/SslMaterialsClientKeyTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/SslMaterialsClientKeyTest.java index a3fb16ba..4cb165b7 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/SslMaterialsClientKeyTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/SslMaterialsClientKeyTest.java @@ -1,6 +1,5 @@ package org.postgresql.client.core; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -12,13 +11,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.security.AlgorithmParameters; -import java.util.Base64; -import javax.crypto.Cipher; -import javax.crypto.EncryptedPrivateKeyInfo; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.PBEKeySpec; import javax.net.ssl.KeyManager; import javax.net.ssl.X509KeyManager; import org.junit.jupiter.api.BeforeAll; @@ -35,8 +27,8 @@ *

    The certificate and matching plaintext key are small throwaway self-signed test-only * materials checked in under {@code src/test/resources/tls/} (generated offline with openssl, * expiring far in the future); an X.509 certificate cannot be minted with public JDK APIs. - * The encrypted-key variants are derived from the plaintext key at runtime with JDK crypto - * (PBES2), so the passphrase paths need no extra checked-in secrets. The end-to-end + * The encrypted variant ({@code test-client-enc.key}) is the same key encrypted by openssl with + * PBES2, the format users actually have; its header holds the passphrase and command. The end-to-end * counterpart against a {@code clientcert}-enforcing server is {@code TlsNegativeMatrixIT}. */ class SslMaterialsClientKeyTest { @@ -54,13 +46,13 @@ class SslMaterialsClientKeyTest { static void materializeTestMaterials() throws Exception { certFile = copyResource("/tls/test-client.crt", "client.crt"); keyFile = copyResource("/tls/test-client.key", "client.key"); - encryptedKeyFile = writeEncryptedCopy(keyFile, PASSPHRASE, "client-enc.key"); + encryptedKeyFile = copyResource("/tls/test-client-enc.key", "client-enc.key"); } /** * Copies a classpath PEM resource to a plain file, dropping the {@code #} comment header. * The driver tolerates the header ({@link #pemFilesWithLeadingCommentaryLoadDirectly} - * proves it); the stripped copy keeps this class's own {@link #decodePem} helper simple. + * proves it); the other tests use the stripped copy. */ private static Path copyResource(String resource, String name) throws IOException { try (InputStream in = SslMaterialsClientKeyTest.class.getResourceAsStream(resource)) { @@ -83,41 +75,6 @@ private static Path copyRawResource(String resource, String name) throws IOExcep } } - /** - * Encrypts the plaintext PKCS#8 key under {@code passphrase} with PBES2 - * (PBKDF2-HmacSHA256 + AES-256-CBC, what modern openssl emits) using only public JDK - * APIs, and writes it as a {@code BEGIN ENCRYPTED PRIVATE KEY} PEM file. - */ - private static Path writeEncryptedCopy(Path plainKey, String passphrase, String name) throws Exception { - byte[] plainDer = decodePem(Files.readString(plainKey, StandardCharsets.US_ASCII)); - String algorithm = "PBEWithHmacSHA256AndAES_256"; - SecretKey secret = - SecretKeyFactory.getInstance(algorithm).generateSecret(new PBEKeySpec(passphrase.toCharArray())); - Cipher cipher = Cipher.getInstance(algorithm); - cipher.init(Cipher.ENCRYPT_MODE, secret); - byte[] encrypted = cipher.doFinal(plainDer); - // Re-house the cipher's parameters under the generic PBES2 name so the JDK can map - // them to the PBES2 OID when encoding the EncryptedPrivateKeyInfo structure. - AlgorithmParameters params = AlgorithmParameters.getInstance("PBES2"); - params.init(cipher.getParameters().getEncoded()); - byte[] der = new EncryptedPrivateKeyInfo(params, encrypted).getEncoded(); - StringBuilder pem = new StringBuilder("-----BEGIN ENCRYPTED PRIVATE KEY-----\n"); - pem.append(Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(der)); - pem.append("\n-----END ENCRYPTED PRIVATE KEY-----\n"); - return Files.writeString(tempDir.resolve(name), pem.toString(), StandardCharsets.US_ASCII); - } - - private static byte[] decodePem(String text) { - StringBuilder base64 = new StringBuilder(); - for (String line : text.split("\\R")) { - String trimmed = line.trim(); - if (!trimmed.isEmpty() && !trimmed.startsWith("-----")) { - base64.append(trimmed); - } - } - return Base64.getDecoder().decode(base64.toString()); - } - /** Asserts the key managers actually expose the client key and its certificate chain. */ private static void assertHoldsClientCredentials(KeyManager[] keyManagers) { assertNotNull(keyManagers, "key managers must be built when client cert material is configured"); @@ -231,19 +188,4 @@ void missingKeyFileFailsClosed() { .build(); assertThrows(PgTlsException.class, () -> SslMaterials.keyManagers(ssl)); } - - @Test - void jdkEncryptedVariantRoundTripsSanityCheck() throws Exception { - // Guard for the helper itself: the runtime-encrypted PEM must decrypt back to the - // exact plaintext PKCS#8 bytes with plain JDK crypto, independent of SslMaterials. - byte[] plainDer = decodePem(Files.readString(keyFile, StandardCharsets.US_ASCII)); - byte[] encDer = decodePem(Files.readString(encryptedKeyFile, StandardCharsets.US_ASCII)); - EncryptedPrivateKeyInfo info = new EncryptedPrivateKeyInfo(encDer); - SecretKey secret = SecretKeyFactory.getInstance(info.getAlgName()) - .generateSecret(new PBEKeySpec(PASSPHRASE.toCharArray())); - Cipher cipher = Cipher.getInstance(info.getAlgName()); - cipher.init(Cipher.DECRYPT_MODE, secret, info.getAlgParameters()); - byte[] decrypted = info.getKeySpec(cipher).getEncoded(); - assertArrayEquals(plainDer, decrypted); - } } diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/StartupAuthSequenceTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/StartupAuthSequenceTest.java new file mode 100644 index 00000000..1b606f46 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/StartupAuthSequenceTest.java @@ -0,0 +1,79 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.auth.Authenticator; +import org.postgresql.client.core.auth.StandardAuthenticator; +import org.postgresql.client.core.internal.StartupOrchestrator; +import org.postgresql.client.core.internal.WireChannel; +import org.postgresql.client.core.transport.BackendWire; +import org.postgresql.client.core.transport.MockServer; + +/** Out-of-order authentication messages from a peer that should not be trusted to finish the login. */ +class StartupAuthSequenceTest { + + private static PgConnectionConfig config() { + return PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .password("scram-pass") + .build(); + } + + private static void run(MockServer server, PgConnectionConfig config, Authenticator authenticator) { + WireChannel channel = new WireChannel(server, config.sizeLimits()); + new StartupOrchestrator(channel, config, HostAndPort.of("h"), authenticator, PgConnectionListener.NO_OP).run(); + } + + @Test + void okInPlaceOfSaslContinueIsRefused() { + MockServer server = new MockServer() + .onStartup((s, f) -> s.send(BackendWire.authenticationSasl("SCRAM-SHA-256"))) + .onMessage((s, f) -> s.send(BackendWire.authenticationOk(), BackendWire.readyForQuery('I'))); + + PgAuthenticationException e = + assertThrows(PgAuthenticationException.class, () -> run(server, config(), new StandardAuthenticator())); + assertTrue(e.getMessage().contains("before completing the SCRAM exchange"), e.getMessage()); + } + + @Test + void readyForQueryWithoutAuthenticationIsRefused() { + MockServer server = new MockServer() + .onStartup((s, f) -> + s.send(BackendWire.parameterStatus("server_version", "17.0"), BackendWire.readyForQuery('I'))); + + PgConnectionException e = + assertThrows(PgConnectionException.class, () -> run(server, config(), new StandardAuthenticator())); + assertTrue(e.getMessage().contains("expected authentication request"), e.getMessage()); + } + + @Test + void skippedAuthenticationCannotBypassRequireAuth() { + // require_auth and channelBinding=require are checked in the AuthenticationOk arm; a peer + // that never sends one must not get past them by going straight to ReadyForQuery. + PgConnectionConfig requireScram = PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .requireAuth(RequireAuth.fromString("scram-sha-256")) + .channelBinding(ChannelBindingMode.REQUIRE) + .build(); + MockServer server = new MockServer().onStartup((s, f) -> s.send(BackendWire.readyForQuery('I'))); + + assertThrows(PgConnectionException.class, () -> run(server, requireScram, new StandardAuthenticator())); + } + + @Test + void backendKeyDataBeforeAuthenticationIsRefused() { + MockServer server = new MockServer() + .onStartup((s, f) -> s.send( + BackendWire.backendKeyData(1, 2), + BackendWire.authenticationOk(), + BackendWire.readyForQuery('I'))); + + assertThrows(PgConnectionException.class, () -> run(server, config(), new StandardAuthenticator())); + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java index 02cba3eb..1271ab98 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/StartupOrchestratorTest.java @@ -143,6 +143,34 @@ void channelBindingRequireRejectsTrustOk() { assertTrue(e.getMessage().contains("channelBinding=require"), e.getMessage()); } + @Test + void aLongMessageBeforeAuthenticationIsRefused() { + String longText = "x".repeat(40_000); + MockServer server = new MockServer().onStartup((s, frame) -> s.send(BackendWire.noticeResponse(longText))); + PgConnectionException e = assertThrows(PgConnectionException.class, () -> run(server, config())); + assertTrue(e.getMessage().contains("exceeds max message length 30000"), e.getMessage()); + } + + @Test + void aLongMessageAfterAuthenticationIsAccepted() { + String longValue = "x".repeat(40_000); + MockServer server = new MockServer() + .onStartup((s, frame) -> s.send( + BackendWire.authenticationOk(), + BackendWire.parameterStatus("long_setting", longValue), + BackendWire.readyForQuery('I'))); + assertEquals(longValue, run(server, config()).parameters().get("long_setting")); + } + + @Test + void endlessStartupMessagesAreRefused() { + byte[][] notices = new byte[10_000][]; + java.util.Arrays.fill(notices, BackendWire.noticeResponse("still here")); + MockServer server = new MockServer().onStartup((s, frame) -> s.send(notices)); + PgConnectionException e = assertThrows(PgConnectionException.class, () -> run(server, config())); + assertTrue(e.getMessage().contains("messages during startup"), e.getMessage()); + } + @Test void serverCloseDuringStartupFails() { MockServer server = new MockServer(); // sends nothing @@ -167,6 +195,26 @@ void negotiateProtocolVersionAcceptedWhenLatest() { assertEquals(ProtocolConstants.PROTOCOL_3_0, result.negotiatedProtocolVersion()); } + @Test + void negotiationCanOnlyGoDown() { + // The driver asks for 3.2 and sends no protocol options, so a reply naming 3.2 or above, or + // anything but major version 3, is not a negotiation the server could legitimately make. + PgConnectionConfig latest = PgConnectionConfig.builder() + .host("h") + .user("app") + .protocolVersionPolicy(ProtocolVersionPolicy.LATEST) + .build(); + // Whole version codes, as servers send them: 3.2, 3.3, 3.99, 4.0, and a bare minor 1. + for (int code : new int[] {ProtocolConstants.PROTOCOL_3_2, 196611, 196707, 4 << 16, 1, -1}) { + MockServer server = new MockServer() + .onStartup((s, frame) -> s.send( + BackendWire.negotiateProtocolVersionCode(code), + BackendWire.authenticationOk(), + BackendWire.readyForQuery('I'))); + assertThrows(PgConnectionException.class, () -> run(server, latest), Integer.toString(code)); + } + } + @Test void negotiateProtocolVersionRejectedWhenStrict() { MockServer server = new MockServer().onStartup((s, frame) -> s.send(BackendWire.negotiateProtocolVersion(0))); diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java new file mode 100644 index 00000000..b57f3b9c --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/TypeCacheLookupTest.java @@ -0,0 +1,126 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.auth.TrustAuthenticator; +import org.postgresql.client.core.codec.Codecs; +import org.postgresql.client.core.internal.StartupOrchestrator; +import org.postgresql.client.core.internal.StartupResult; +import org.postgresql.client.core.internal.WireChannel; +import org.postgresql.client.core.transport.BackendWire; +import org.postgresql.client.core.transport.MockServer; + +/** + * The composite type name lookup interpolates the name into SQL, so the literal must stay closed + * whatever {@code standard_conforming_strings} is: with it off, a plain {@code '...'} literal + * treats a backslash as an escape and a name ending in one swallows the closing quote. + */ +class TypeCacheLookupTest { + + private static CoreConnection connect(MockServer server) { + PgConnectionConfig config = PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .build(); + server.onStartup((s, f) -> s.send(BackendWire.authenticationOk(), BackendWire.readyForQuery('I'))); + WireChannel channel = new WireChannel(server, SizeLimits.unlimited()); + StartupResult startup = new StartupOrchestrator( + channel, config, HostAndPort.of("h"), TrustAuthenticator.INSTANCE, PgConnectionListener.NO_OP) + .run(); + return new CoreConnection(channel, config, startup, HostAndPort.of("h"), PgConnectionListener.NO_OP); + } + + @Test + void typeNameIsSentAsAnEscapeStringLiteral() { + List queries = new ArrayList<>(); + MockServer server = new MockServer().onMessage((s, f) -> { + queries.add(f.payloadReader().readCString()); + s.send( + BackendWire.rowDescription("to_regtype"), + BackendWire.dataRow((String) null), + BackendWire.commandComplete("SELECT 1"), + BackendWire.readyForQuery('I')); + }); + TypeCache cache = new TypeCache(connect(server), Codecs.defaultRegistry()); + + // A quoted identifier may hold anything but a lone double quote, so the escaping still matters. + assertNull(cache.resolveComposite("\"x\\' || NULL); DROP TABLE t; --\"")); + assertEquals(List.of("SELECT pg_catalog.to_regtype(E'\"x\\\\'' || NULL); DROP TABLE t; --\"')::oid"), queries); + } + + @Test + void impossibleCatalogRowsFailAsPgException() { + // typtype is NOT NULL and typbasetype an OID; a server that says otherwise is answering + // something impossible, which must not surface as a NullPointerException or a + // NumberFormatException. + String[][] rows = { + {null, "0", "0", "0", "U", "t"}, + {"d", "not-an-oid", "0", "0", "U", "t"}, + {"c", "0", null, "0", "C", "t"}, + }; + for (String[] typeRow : rows) { + MockServer server = new MockServer() + .onMessage((s, f) -> s.send( + BackendWire.rowDescription( + "typtype", "typbasetype", "typrelid", "typelem", "typcategory", "oid"), + BackendWire.dataRow(typeRow), + BackendWire.commandComplete("SELECT 1"), + BackendWire.readyForQuery('I'))); + TypeCache cache = new TypeCache(connect(server), Codecs.defaultRegistry()); + assertThrows(PgException.class, () -> cache.resolve(99999), Arrays.toString(typeRow)); + } + } + + @Test + void endlessDomainChainIsCut() { + // Each lookup answers with a domain over a type it has not been asked about yet. + AtomicInteger next = new AtomicInteger(100_000); + AtomicInteger lookups = new AtomicInteger(); + MockServer server = new MockServer().onMessage((s, f) -> { + lookups.incrementAndGet(); + s.send( + BackendWire.rowDescription("typtype", "typbasetype", "typrelid", "typelem", "typcategory", "oid"), + BackendWire.dataRow("d", Integer.toString(next.incrementAndGet()), "0", "0", "U", "t"), + BackendWire.commandComplete("SELECT 1"), + BackendWire.readyForQuery('I')); + }); + CoreConnection connection = connect(server); + TypeCache cache = new TypeCache(connection, Codecs.defaultRegistry()); + + PgException e = assertThrows(PgException.class, () -> cache.resolve(next.get())); + assertTrue(e.getMessage().contains("nested"), e.getMessage()); + assertEquals(TypeCache.MAX_DEPTH, lookups.get()); + assertFalse(connection.isBroken()); + } + + @Test + void unparseableNamesAreNotSentAtAll() { + // Before PostgreSQL 16 to_regtype raises a syntax error for these, aborting the transaction. + List queries = new ArrayList<>(); + MockServer server = new MockServer() + .onMessage((s, f) -> queries.add(f.payloadReader().readCString())); + TypeCache cache = new TypeCache(connect(server), Codecs.defaultRegistry()); + + for (String name : new String[] {"x' || 1", "a b", "a..b", "1abc", "a.b.c.d", "\"\"", "\"open", ""}) { + assertNull(cache.resolveComposite(name), name); + } + assertEquals(List.of(), queries); + } + + @Test + void qualifiedNameRecognizesWhatRegtypeTextProduces() { + for (String name : new String[] {"t", "public.t", "db.public.t", "\"My Type\"", "s.\"a\"\"b\"", "t$1", "_x"}) { + assertTrue(TypeCache.isQualifiedName(name), name); + } + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/UnexpectedCopyInTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/UnexpectedCopyInTest.java new file mode 100644 index 00000000..30c5a725 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/UnexpectedCopyInTest.java @@ -0,0 +1,79 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.postgresql.client.core.auth.TrustAuthenticator; +import org.postgresql.client.core.internal.StartupOrchestrator; +import org.postgresql.client.core.internal.StartupResult; +import org.postgresql.client.core.internal.WireChannel; +import org.postgresql.client.core.transport.BackendWire; +import org.postgresql.client.core.transport.MockServer; +import org.postgresql.client.protocol.MessageType; + +/** + * A COPY FROM STDIN later in a multi-statement string leaves the server waiting for data. The drain + * has to answer it with CopyFail rather than read on: the next message would never come. + */ +@Timeout(30) +class UnexpectedCopyInTest { + + private static CoreConnection connect(MockServer server) { + PgConnectionConfig config = PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .build(); + server.onStartup((s, f) -> s.send(BackendWire.authenticationOk(), BackendWire.readyForQuery('I'))); + WireChannel channel = new WireChannel(server, SizeLimits.unlimited()); + StartupResult startup = new StartupOrchestrator( + channel, config, HostAndPort.of("h"), TrustAuthenticator.INSTANCE, PgConnectionListener.NO_OP) + .run(); + return new CoreConnection(channel, config, startup, HostAndPort.of("h"), PgConnectionListener.NO_OP); + } + + @Test + void trailingCopyInIsRefusedWithCopyFail() { + List received = new ArrayList<>(); + MockServer server = new MockServer().onMessage((s, f) -> { + received.add((char) f.type()); + if (f.type() == MessageType.Frontend.QUERY && received.size() == 1) { + s.send( + BackendWire.rowDescription("?column?"), + BackendWire.dataRow("1"), + BackendWire.commandComplete("SELECT 1"), + BackendWire.copyInResponse(1)); + } else if (f.type() == MessageType.Frontend.COPY_FAIL) { + s.send( + BackendWire.errorResponse("ERROR", "57014", "COPY from stdin failed"), + BackendWire.readyForQuery('I')); + } else { + s.send( + BackendWire.rowDescription("?column?"), + BackendWire.dataRow("2"), + BackendWire.commandComplete("SELECT 1"), + BackendWire.readyForQuery('I')); + } + }); + CoreConnection connection = connect(server); + + PgException e = assertThrows(PgException.class, () -> { + try (PgResultStream rs = connection.execute("SELECT 1; COPY t FROM STDIN")) { + assertTrue(rs.next()); + assertFalse(rs.next()); + } + }); + assertTrue(e.getMessage().contains("COPY"), e.getMessage()); + assertEquals(List.of('Q', 'f'), received); + assertFalse(connection.isBroken()); + try (PgResultStream rs = connection.execute("SELECT 2")) { + assertTrue(rs.next(), "the connection is usable again"); + } + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/ZeroColumnResultTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/ZeroColumnResultTest.java new file mode 100644 index 00000000..369e4e45 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/ZeroColumnResultTest.java @@ -0,0 +1,148 @@ +package org.postgresql.client.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.auth.TrustAuthenticator; +import org.postgresql.client.core.internal.StartupOrchestrator; +import org.postgresql.client.core.internal.StartupResult; +import org.postgresql.client.core.internal.WireChannel; +import org.postgresql.client.core.transport.BackendWire; +import org.postgresql.client.core.transport.MockServer; + +/** + * {@code SELECT FROM t} is legal: its RowDescription declares no columns, and a DataRow with no + * values still follows for every row. Those rows have to be counted, not trip over a missing + * transient row. + */ +class ZeroColumnResultTest { + + private static CoreConnection connect(MockServer server) { + PgConnectionConfig config = PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .build(); + server.onStartup((s, f) -> s.send(BackendWire.authenticationOk(), BackendWire.readyForQuery('I'))); + WireChannel channel = new WireChannel(server, SizeLimits.unlimited()); + StartupResult startup = new StartupOrchestrator( + channel, config, HostAndPort.of("h"), TrustAuthenticator.INSTANCE, PgConnectionListener.NO_OP) + .run(); + return new CoreConnection(channel, config, startup, HostAndPort.of("h"), PgConnectionListener.NO_OP); + } + + private static int drain(PgResultStream rs) { + assertEquals(0, rs.metadata().columnCount()); + int rows = 0; + while (rs.next()) { + assertNotNull(rs.currentRow()); + rows++; + } + return rows; + } + + @Test + void simpleProtocolCountsZeroColumnRows() { + MockServer server = new MockServer() + .onMessage((s, f) -> s.send( + BackendWire.rowDescription(), + BackendWire.dataRow(), + BackendWire.dataRow(), + BackendWire.commandComplete("SELECT 2"), + BackendWire.readyForQuery('I'))); + CoreConnection connection = connect(server); + + try (PgResultStream rs = connection.execute("SELECT FROM generate_series(1, 2)")) { + assertEquals(2, drain(rs)); + } + assertFalse(connection.isBroken()); + try (PgResultStream rs = connection.execute("SELECT FROM generate_series(1, 2)")) { + assertEquals(2, drain(rs), "the connection is idle again"); + } + } + + @Test + void extendedProtocolCountsZeroColumnRows() { + MockServer server = new MockServer().onMessage((s, f) -> { + if (f.type() == 'S') { + s.send( + BackendWire.parseComplete(), + BackendWire.bindComplete(), + BackendWire.rowDescription(), + BackendWire.dataRow(), + BackendWire.dataRow(), + BackendWire.dataRow(), + BackendWire.commandComplete("SELECT 3"), + BackendWire.readyForQuery('I')); + } + }); + CoreConnection connection = connect(server); + + try (PgResultStream rs = connection.execute("SELECT FROM generate_series(1, $1)", List.of(3))) { + assertEquals(3, drain(rs)); + } + assertTrue(connection.isOpen()); + assertFalse(connection.isBroken()); + } + + /** Answers a statement Describe with {@code describe}, and an execute of it with {@code execute}. */ + private static MockServer preparedServer(byte[] describe, byte[]... execute) { + boolean[] bound = {false}; + return new MockServer().onMessage((s, f) -> { + if (f.type() == 'B') { + bound[0] = true; + } else if (f.type() == 'S') { + if (bound[0]) { + s.send(BackendWire.concat(execute)); + } else { + s.send( + BackendWire.parseComplete(), + BackendWire.parameterDescription(), + describe, + BackendWire.readyForQuery('I')); + } + bound[0] = false; + } + }); + } + + @Test + void namedPreparedStatementCountsZeroColumnRows() { + // The named path skips the portal Describe and goes by what the statement Describe said; a + // zero-column RowDescription there still means a row phase, unlike NoData. + CoreConnection connection = connect(preparedServer( + BackendWire.rowDescription(), + BackendWire.bindComplete(), + BackendWire.dataRow(), + BackendWire.dataRow(), + BackendWire.commandComplete("SELECT 2"), + BackendWire.readyForQuery('I'))); + PgPreparedStatement statement = connection.prepare("SELECT FROM t"); + + for (int i = 0; i < 2; i++) { + try (PgResultStream rs = statement.execute(List.of())) { + assertEquals(2, drain(rs)); + } + } + assertFalse(connection.isBroken()); + } + + @Test + void namedPreparedCommandStillCompletesWhilePriming() { + CoreConnection connection = connect(preparedServer( + BackendWire.noData(), + BackendWire.bindComplete(), + BackendWire.commandComplete("UPDATE 4"), + BackendWire.readyForQuery('I'))); + PgPreparedStatement statement = connection.prepare("UPDATE t SET x = 1"); + + try (PgResultStream rs = statement.execute(List.of())) { + assertEquals(4L, rs.summary().affectedRows().getAsLong()); + assertFalse(rs.next()); + } + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java new file mode 100644 index 00000000..dbf32e2e --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/auth/ScramCompletionTest.java @@ -0,0 +1,151 @@ +package org.postgresql.client.core.auth; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import javax.crypto.Mac; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.PgAuthenticationException; +import org.postgresql.client.core.PgConnectionConfig; +import org.postgresql.client.protocol.message.AuthenticationRequest; +import org.postgresql.client.protocol.message.SASLInitialResponse; +import org.postgresql.client.protocol.message.SASLResponse; + +/** + * An {@code AuthenticationOk} is accepted only once the SCRAM exchange has verified the server + * signature; a peer that skips {@code AuthenticationSASLFinal} has not proven it knows the password. + */ +class ScramCompletionTest { + + private static final String PASSWORD = "scram-pass"; + private static final byte[] SALT = "0123456789abcdef".getBytes(StandardCharsets.US_ASCII); + private static final int ITERATIONS = 4096; + + private static PgConnectionConfig config() { + return PgConnectionConfig.builder() + .host("h") + .user("app") + .database("appdb") + .password(PASSWORD) + .build(); + } + + @Test + void okAfterClientFirstIsRefused() { + FakeAuthExchange exchange = new FakeAuthExchange(config(), false, null); + StandardAuthenticator auth = new StandardAuthenticator(); + auth.handle(new AuthenticationRequest.Sasl(List.of("SCRAM-SHA-256")), exchange); + + PgAuthenticationException e = assertThrows(PgAuthenticationException.class, auth::authenticationOk); + assertTrue(e.getMessage().contains("SCRAM"), e.getMessage()); + } + + @Test + void okAfterClientFinalIsRefused() { + FakeAuthExchange exchange = new FakeAuthExchange(config(), false, null); + StandardAuthenticator auth = new StandardAuthenticator(); + auth.handle(new AuthenticationRequest.Sasl(List.of("SCRAM-SHA-256")), exchange); + auth.handle(new AuthenticationRequest.SaslContinue(serverFirst(clientFirstBare(exchange))), exchange); + assertInstanceOf(SASLResponse.class, exchange.sent.get(1)); + + assertThrows(PgAuthenticationException.class, auth::authenticationOk); + } + + @Test + void okAfterVerifiedServerFinalIsAccepted() throws GeneralSecurityException { + FakeAuthExchange exchange = new FakeAuthExchange(config(), false, null); + StandardAuthenticator auth = new StandardAuthenticator(); + auth.handle(new AuthenticationRequest.Sasl(List.of("SCRAM-SHA-256")), exchange); + String clientFirstBare = clientFirstBare(exchange); + String serverFirst = new String(serverFirst(clientFirstBare), StandardCharsets.UTF_8); + auth.handle(new AuthenticationRequest.SaslContinue(serverFirst.getBytes(StandardCharsets.UTF_8)), exchange); + String clientFinal = new String(((SASLResponse) exchange.sent.get(1)).data(), StandardCharsets.UTF_8); + String withoutProof = clientFinal.substring(0, clientFinal.indexOf(",p=")); + byte[] signature = serverSignature(clientFirstBare + "," + serverFirst + "," + withoutProof); + auth.handle( + new AuthenticationRequest.SaslFinal( + ("v=" + Base64.getEncoder().encodeToString(signature)).getBytes(StandardCharsets.UTF_8)), + exchange); + + assertDoesNotThrow(auth::authenticationOk); + } + + @Test + void okWithoutAnyExchangeIsAccepted() { + // Trust, cleartext and MD5 have no server proof to wait for. + assertDoesNotThrow(new StandardAuthenticator()::authenticationOk); + } + + @Test + void malformedServerFirstIsAnAuthenticationFailure() { + for (String tail : new String[] {",s=***,i=4096", ",s=MDEyMw==,i=0", ",s=MDEyMw==,i=-1"}) { + FakeAuthExchange exchange = new FakeAuthExchange(config(), false, null); + StandardAuthenticator auth = new StandardAuthenticator(); + auth.handle(new AuthenticationRequest.Sasl(List.of("SCRAM-SHA-256")), exchange); + String bare = clientFirstBare(exchange); + byte[] serverFirst = + ("r=" + bare.substring(bare.indexOf("r=") + 2) + "srv" + tail).getBytes(StandardCharsets.UTF_8); + + assertThrows( + PgAuthenticationException.class, + () -> auth.handle(new AuthenticationRequest.SaslContinue(serverFirst), exchange), + tail); + } + } + + @Test + void secondSaslRequestIsRefusedAndTheFirstSecretStillZeroed() { + List issued = new ArrayList<>(); + StandardAuthenticator auth = new StandardAuthenticator(context -> { + char[] token = "token-pass".toCharArray(); + issued.add(token); + return token.clone(); + }); + FakeAuthExchange exchange = new FakeAuthExchange(config(), false, null); + AuthenticationRequest.Sasl sasl = new AuthenticationRequest.Sasl(List.of("SCRAM-SHA-256")); + auth.handle(sasl, exchange); + + PgAuthenticationException e = assertThrows(PgAuthenticationException.class, () -> auth.handle(sasl, exchange)); + assertTrue(e.getMessage().contains("restarted"), e.getMessage()); + assertEquals(1, issued.size(), "the provider must not be asked for a second secret"); + assertEquals(1, exchange.sent.size()); + } + + private static String clientFirstBare(FakeAuthExchange exchange) { + SASLInitialResponse first = (SASLInitialResponse) exchange.sent.get(0); + String message = new String(first.initialResponse(), StandardCharsets.UTF_8); + // Strip the gs2 header ("n,," or "y,,"). + return message.substring(message.indexOf(",,") + 2); + } + + private static byte[] serverFirst(String clientFirstBare) { + String clientNonce = clientFirstBare.substring(clientFirstBare.indexOf("r=") + 2); + return ("r=" + clientNonce + "srvnonce,s=" + Base64.getEncoder().encodeToString(SALT) + ",i=" + ITERATIONS) + .getBytes(StandardCharsets.UTF_8); + } + + private static byte[] serverSignature(String authMessage) throws GeneralSecurityException { + SecretKeyFactory pbkdf2 = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); + byte[] salted = pbkdf2.generateSecret(new PBEKeySpec(PASSWORD.toCharArray(), SALT, ITERATIONS, 256)) + .getEncoded(); + byte[] serverKey = hmac(salted, "Server Key".getBytes(StandardCharsets.US_ASCII)); + return hmac(serverKey, authMessage.getBytes(StandardCharsets.UTF_8)); + } + + private static byte[] hmac(byte[] key, byte[] data) throws GeneralSecurityException { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(key, "HmacSHA256")); + return mac.doFinal(data); + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/codec/ArrayCodecsTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/codec/ArrayCodecsTest.java index 04ae10a7..d75914df 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/codec/ArrayCodecsTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/codec/ArrayCodecsTest.java @@ -136,6 +136,22 @@ void decodesMultiDimensionalArray() { assertEquals(List.of(List.of(1, 2), List.of(3, 4)), decode(Oids.INT4_ARRAY, "{{1,2},{3,4}}")); } + @Test + void textArrayAtTheDimensionLimitDecodes() { + List value = decode(Oids.INT4_ARRAY, "{{{{{{1}}}}}}"); + assertEquals(List.of(List.of(List.of(List.of(List.of(List.of(1)))))), value); + } + + @Test + void textArrayNestingIsCapped() { + // The parser recurses once per '{'; a server-supplied value nested thousands deep used to + // overflow the stack with an Error rather than fail as a PgException. + String deep = "{".repeat(20_000) + "}".repeat(20_000); + PgException e = assertThrows(PgException.class, () -> decode(Oids.INT4_ARRAY, deep)); + assertTrue(e.getMessage().contains("dimension"), e.getMessage()); + assertThrows(PgException.class, () -> decode(Oids.INT4_ARRAY, "{{{{{{{1}}}}}}}")); + } + @Test void skipsDimensionPrefix() { assertEquals(List.of(7, 8, 9), decode(Oids.INT4_ARRAY, "[-1:1]={7,8,9}")); diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/codec/MalformedServerValueTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/codec/MalformedServerValueTest.java new file mode 100644 index 00000000..f91168ef --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/codec/MalformedServerValueTest.java @@ -0,0 +1,54 @@ +package org.postgresql.client.core.codec; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; +import org.postgresql.client.core.PgException; +import org.postgresql.client.protocol.Oids; +import org.postgresql.client.protocol.ProtocolConstants; +import org.postgresql.client.protocol.buffer.ByteSlice; + +/** + * Value bytes come from the server; a decoder that rejects them must say so as a PgException + * (ADR-0007), not leak the JDK parser's own exception type. + */ +class MalformedServerValueTest { + + private final CodecRegistry registry = Codecs.defaultRegistry(); + private final CodecContext context = CodecContext.defaults(); + + private void assertTextRejected(int oid, String text) { + byte[] bytes = text.getBytes(StandardCharsets.UTF_8); + assertThrows( + PgException.class, + () -> registry.forOid(oid) + .decode(new ByteSlice(bytes, 0, bytes.length), ProtocolConstants.FORMAT_TEXT, context), + text); + } + + private void assertBinaryRejected(int oid, byte[] bytes) { + assertThrows(PgException.class, () -> registry.forOid(oid) + .decode(new ByteSlice(bytes, 0, bytes.length), ProtocolConstants.FORMAT_BINARY, context)); + } + + @Test + void malformedTextValues() { + assertTextRejected(Oids.UUID, "zz"); + assertTextRejected(Oids.MONEY, "1.2.3"); + assertTextRejected(Oids.TIMETZ, "12:00:00+"); + assertTextRejected(Oids.TIMETZ, "12:00:00+ab"); + assertTextRejected(Oids.DATE, "2020-13-45"); + assertTextRejected(Oids.DATE, "garbage"); + } + + @Test + void malformedBinaryValues() { + assertBinaryRejected(Oids.TIME, ByteBuffer.allocate(8).putLong(-1).array()); + // An int4[] header cut off after the element type. + assertBinaryRejected( + Oids.INT4_ARRAY, + ByteBuffer.allocate(12).putInt(1).putInt(0).putInt(Oids.INT4).array()); + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/codec/ScalarCodecsTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/codec/ScalarCodecsTest.java index 5e551449..45739620 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/codec/ScalarCodecsTest.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/codec/ScalarCodecsTest.java @@ -139,6 +139,23 @@ void binaryParameterEncodingRoundTripsThroughDecode() { // task 10 assertBinaryRoundTrip(Oids.BOOL, false); } + @Test + void numericOutsideTheServerRangeIsRefused() { + @SuppressWarnings("unchecked") + Codec numeric = (Codec) registry.forOid(Oids.NUMERIC); + // 1e131072 would wrap weight to -32768 and 999999.99e-262144 dscale to 2: both store another value. + for (String text : new String[] {"1e131072", "999999.99e-262144", "1e100000000", "-1e-16384"}) { + BigDecimal value = new BigDecimal(text); + assertThrows(PgException.class, () -> numeric.encodeBinary(value, context), text); + assertThrows(PgException.class, () -> numeric.encodeText(value, context), text); + } + } + + @Test + void numericAtTheServerLimitsRoundTrips() { + assertBinaryRoundTrip(Oids.NUMERIC, new BigDecimal("1e-16383")); + } + @Test void numericBinaryParameterRoundTripsThroughDecode() { // P4, N5.7: numeric now binds in binary Codec numeric = registry.forOid(Oids.NUMERIC); diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/internal/TlsChannelBindingHashTest.java b/postgresql-client/src/test/java/org/postgresql/client/core/internal/TlsChannelBindingHashTest.java new file mode 100644 index 00000000..67561805 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/internal/TlsChannelBindingHashTest.java @@ -0,0 +1,45 @@ +package org.postgresql.client.core.internal; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.security.AlgorithmParameters; +import java.security.spec.MGF1ParameterSpec; +import java.security.spec.PSSParameterSpec; +import org.junit.jupiter.api.Test; + +/** The tls-server-end-point hash follows the certificate's signature hash, PSS included. */ +class TlsChannelBindingHashTest { + + private static byte[] pss(String digest, MGF1ParameterSpec mgf, int saltLength) throws Exception { + AlgorithmParameters parameters = AlgorithmParameters.getInstance("RSASSA-PSS"); + parameters.init(new PSSParameterSpec(digest, "MGF1", mgf, saltLength, 1)); + return parameters.getEncoded(); + } + + @Test + void pssUsesTheHashFromItsParameters() throws Exception { + String oid = "1.2.840.113549.1.1.10"; + assertEquals( + "SHA-384", + TlsChannelBinding.hashAlgorithmFor("RSASSA-PSS", oid, pss("SHA-384", MGF1ParameterSpec.SHA384, 48))); + assertEquals( + "SHA-512", + TlsChannelBinding.hashAlgorithmFor("RSASSA-PSS", oid, pss("SHA-512", MGF1ParameterSpec.SHA512, 64))); + assertEquals( + "SHA-256", + TlsChannelBinding.hashAlgorithmFor("RSASSA-PSS", oid, pss("SHA-256", MGF1ParameterSpec.SHA256, 32))); + // PSS with SHA-1 is upgraded like any SHA-1 signature. + assertEquals( + "SHA-256", + TlsChannelBinding.hashAlgorithmFor("RSASSA-PSS", oid, pss("SHA-1", MGF1ParameterSpec.SHA1, 20))); + } + + @Test + void namedSignaturesAreUnchanged() { + assertEquals("SHA-384", TlsChannelBinding.hashAlgorithmFor("SHA384withRSA", "1.2.840.113549.1.1.12", null)); + assertEquals("SHA-256", TlsChannelBinding.hashAlgorithmFor("SHA1withRSA", "1.2.840.113549.1.1.5", null)); + assertEquals( + "SHA-256", + TlsChannelBinding.hashAlgorithmFor("RSASSA-PSS", "1.2.840.113549.1.1.10", new byte[] {1, 2})); + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/it/SearchPathShadowingIT.java b/postgresql-client/src/test/java/org/postgresql/client/core/it/SearchPathShadowingIT.java new file mode 100644 index 00000000..cbfddf62 --- /dev/null +++ b/postgresql-client/src/test/java/org/postgresql/client/core/it/SearchPathShadowingIT.java @@ -0,0 +1,72 @@ +package org.postgresql.client.core.it; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.postgresql.client.core.PgComposite; +import org.postgresql.client.core.PgConnection; +import org.postgresql.client.core.PgConnections; +import org.postgresql.client.core.PgResultStream; + +/** + * The driver's own catalog queries must not run an operator or function that a search_path schema + * supplies with an exact signature match pg_catalog lacks. Each shadowing object raises, so a + * query that resolved to it fails the test. + */ +@Timeout(60) +class SearchPathShadowingIT extends AbstractPostgresIT { + + private static PgConnection shadowedConnection(String schema) { + PgConnection c = PgConnections.connect(connectionConfig().build()); + c.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE").close(); + c.execute("CREATE SCHEMA " + schema).close(); + c.execute("SET search_path = " + schema + ", public").close(); + c.execute("CREATE FUNCTION " + schema + ".shadow_eq(oid, int4) RETURNS bool LANGUAGE plpgsql" + + " AS $$BEGIN RAISE EXCEPTION 'shadowing operator ran'; END$$") + .close(); + c.execute("CREATE OPERATOR " + schema + ".= (LEFTARG = oid, RIGHTARG = int4, FUNCTION = " + schema + + ".shadow_eq)") + .close(); + c.execute("CREATE FUNCTION " + schema + ".set_config(text, varchar, bool) RETURNS text" + + " LANGUAGE plpgsql AS $$BEGIN RAISE EXCEPTION 'shadowing function ran'; END$$") + .close(); + return c; + } + + private static int typeOid(PgConnection c, String typeName) { + try (PgResultStream rs = c.execute("SELECT '" + typeName + "'::regtype::oid")) { + assertTrue(rs.next(), "expected one row"); + return rs.currentRow().getLong(1).intValue(); + } + } + + @Test + void typeLookupsUsePgCatalogOperators() { + try (PgConnection c = shadowedConnection("shadow_types")) { + c.execute("CREATE TYPE shadow_mood AS ENUM ('sad', 'ok')").close(); + c.execute("CREATE TYPE shadow_pt AS (x int4, y int4)").close(); + + c.resolveType(typeOid(c, "shadow_mood")); + c.resolveType(typeOid(c, "shadow_pt")); + List points = List.of(new PgComposite("shadow_pt", List.of(1, 2))); + try (PgResultStream rs = c.execute("SELECT cardinality($1::shadow_pt[])", List.of(points))) { + assertTrue(rs.next(), "expected one row"); + assertEquals(1, rs.currentRow().getInt(1)); + } + } + } + + @Test + void setApplicationNameUsesPgCatalogSetConfig() { + try (PgConnection c = shadowedConnection("shadow_config")) { + c.setApplicationName("shadow-test"); + try (PgResultStream rs = c.execute("SHOW application_name")) { + assertTrue(rs.next(), "expected one row"); + assertEquals("shadow-test", rs.currentRow().getString(1)); + } + } + } +} diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/it/VirtualThreadPinningIT.java b/postgresql-client/src/test/java/org/postgresql/client/core/it/VirtualThreadPinningIT.java index 9d159752..de015454 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/it/VirtualThreadPinningIT.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/it/VirtualThreadPinningIT.java @@ -13,9 +13,16 @@ import java.util.concurrent.Future; import java.util.stream.Collectors; import jdk.jfr.Recording; +import jdk.jfr.ValueDescriptor; +import jdk.jfr.consumer.RecordedClass; import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordedFrame; +import jdk.jfr.consumer.RecordedMethod; +import jdk.jfr.consumer.RecordedObject; import jdk.jfr.consumer.RecordedStackTrace; +import jdk.jfr.consumer.RecordedThread; import jdk.jfr.consumer.RecordingFile; +import org.jspecify.annotations.Nullable; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.postgresql.client.core.PgConnection; @@ -60,13 +67,25 @@ class VirtualThreadPinningIT extends AbstractPostgresIT { * {@code max_connections=100} since each task holds its own connection for its lifetime. */ private static final int TASKS = 50; + private static final String PINNED_EVENT = "jdk.VirtualThreadPinned"; + private static final int ROUNDS = 3; private static final int SERIES = 5000; @Test void driverIoDoesNotPinCarriersUnderVirtualThreadLoad() throws Exception { + // The JDK sets up sun.nio.ch.Poller lazily, the first time a virtual thread parks on socket + // I/O. If many virtual threads reach that point at once, all but one wait on the class + // initializer and pin their carriers ("Waited for initialization of sun.nio.ch.Poller by + // another thread"). That is a JDK limitation (JDK-8369238), not a driver pin, so one virtual + // thread runs the same blocking-read workload first to initialize the poller before + // recording starts. + try (ExecutorService warmup = Executors.newVirtualThreadPerTaskExecutor()) { + warmup.submit(VirtualThreadPinningIT::runQueries).get(); + } + Recording recording = new Recording(); - recording.enable("jdk.VirtualThreadPinned").withThreshold(Duration.ZERO); + recording.enable(PINNED_EVENT).withThreshold(Duration.ZERO); recording.start(); try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { @@ -80,21 +99,37 @@ void driverIoDoesNotPinCarriersUnderVirtualThreadLoad() throws Exception { } recording.stop(); - Path dump = Files.createTempFile("vthread-pinning", ".jfr"); + // Dumped under the module's target/ (failsafe's working directory) rather than the system + // temp dir, so a failing run leaves the recording where CI uploads it as an artifact. + Path dumpDir = Files.createDirectories(Path.of("target", "jfr")); + Path dump = Files.createTempFile(dumpDir, "virtual-thread-pinning-", ".jfr"); + boolean passed = false; try { recording.dump(dump); + List allPins = new ArrayList<>(); List driverPins = new ArrayList<>(); for (RecordedEvent event : RecordingFile.readAllEvents(dump)) { + if (PINNED_EVENT.equals(event.getEventType().getName())) { + allPins.add(event); + } if (pinnedInDriverTransport(event)) { driverPins.add(event); } } assertTrue( driverPins.isEmpty(), - () -> "the driver transport pinned a carrier thread " + driverPins.size() + " time(s):\n" + () -> "the driver transport pinned a carrier thread " + driverPins.size() + " time(s)" + + " (" + allPins.size() + " " + PINNED_EVENT + " event(s) recorded in total)\n" + + describeJvm() + "\n" + + " recording kept at: " + dump.toAbsolutePath() + "\n" + describe(driverPins)); + passed = true; } finally { - Files.deleteIfExists(dump); + if (passed) { + Files.deleteIfExists(dump); + } else { + System.err.println("VirtualThreadPinningIT: JFR recording kept at " + dump.toAbsolutePath()); + } recording.close(); } } @@ -130,11 +165,88 @@ private static String describe(List pins) { return pins.stream().map(VirtualThreadPinningIT::describeEvent).collect(Collectors.joining("\n --\n")); } + private static String describeJvm() { + return " jvm: " + System.getProperty("java.vm.name") + " " + System.getProperty("java.runtime.version") + + " (" + System.getProperty("java.vm.vendor") + ", vm " + System.getProperty("java.vm.version") + + ", " + System.getProperty("os.name") + " " + System.getProperty("os.arch") + ")"; + } + + /** + * Reports every field the running JDK recorded for the event, not a fixed list: the field set of + * {@code jdk.VirtualThreadPinned} varies by release (newer JDKs record more, such as the pinning + * reason, blocking operation and carrier thread), so a fixed list would either miss data on a newer + * JDK or fail on an older one. The fields this test most wants are also named when absent, so a + * report from an older JDK says so rather than silently omitting them. + */ private static String describeEvent(RecordedEvent event) { - return event.getStackTrace().getFrames().stream() - .limit(8) - .map(frame -> " at " + frame.getMethod().getType().getName() + "." - + frame.getMethod().getName()) - .collect(Collectors.joining("\n")); + StringBuilder out = new StringBuilder(); + out.append(" event: ").append(event.getEventType().getName()); + if (event.getEventType().getLabel() != null) { + out.append(" (").append(event.getEventType().getLabel()).append(')'); + } + out.append('\n'); + for (ValueDescriptor field : event.getFields()) { + if (field.getName().equals("stackTrace")) { + continue; + } + out.append(" ").append(field.getName()); + if (field.getLabel() != null) { + out.append(" [").append(field.getLabel()).append(']'); + } + out.append(": ") + .append(describeValue(event.getValue(field.getName()))) + .append('\n'); + } + for (String expected : new String[] {"pinnedReason", "blockingOperation", "carrierThread"}) { + if (!event.hasField(expected)) { + out.append(" ").append(expected).append(": \n"); + } + } + RecordedStackTrace stack = event.getStackTrace(); + if (stack == null) { + out.append(" stackTrace: "); + return out.toString(); + } + out.append(" stackTrace (") + .append(stack.getFrames().size()) + .append(" frame(s)") + .append(stack.isTruncated() ? ", TRUNCATED by the JFR stack depth limit" : "") + .append("):\n"); + out.append(stack.getFrames().stream() + .map(VirtualThreadPinningIT::describeFrame) + .collect(Collectors.joining("\n"))); + return out.toString(); + } + + private static String describeValue(@Nullable Object value) { + if (value instanceof RecordedThread thread) { + return "javaName=" + thread.getJavaName() + + ", javaThreadId=" + thread.getJavaThreadId() + + ", virtual=" + thread.isVirtual() + + ", osName=" + thread.getOSName() + + ", osThreadId=" + thread.getOSThreadId(); + } + if (value instanceof RecordedClass type) { + return type.getName(); + } + if (value instanceof RecordedObject object) { + return object.toString().replace("\n", " ").replaceAll("\\s+", " ").trim(); + } + return String.valueOf(value); + } + + private static String describeFrame(RecordedFrame frame) { + RecordedMethod method = frame.getMethod(); + String where; + if (method == null) { + where = ""; + } else { + String type = method.getType() == null + ? "" + : method.getType().getName(); + where = type + "." + method.getName() + method.getDescriptor(); + } + return " at " + where + " (line " + frame.getLineNumber() + ", bci " + frame.getBytecodeIndex() + ", " + + frame.getType() + ")"; } } diff --git a/postgresql-client/src/test/java/org/postgresql/client/core/transport/BackendWire.java b/postgresql-client/src/test/java/org/postgresql/client/core/transport/BackendWire.java index 500bd3a8..1b25f0ac 100644 --- a/postgresql-client/src/test/java/org/postgresql/client/core/transport/BackendWire.java +++ b/postgresql-client/src/test/java/org/postgresql/client/core/transport/BackendWire.java @@ -160,9 +160,16 @@ public static byte[] dataRow(String... textColumns) { return framed(MessageType.Backend.DATA_ROW, buf.toByteArray()); } + /** As a server sends it: the version field carries the whole code, 3 in the major half. */ public static byte[] negotiateProtocolVersion(int newestMinorVersion, String... unsupportedOptions) { + return negotiateProtocolVersionCode( + ProtocolConstants.protocolVersion(3, newestMinorVersion), unsupportedOptions); + } + + /** A NegotiateProtocolVersion carrying {@code versionCode} as is. */ + public static byte[] negotiateProtocolVersionCode(int versionCode, String... unsupportedOptions) { PgWriteBuffer buf = new PgWriteBuffer(); - buf.writeInt(newestMinorVersion); + buf.writeInt(versionCode); buf.writeInt(unsupportedOptions.length); for (String option : unsupportedOptions) { buf.writeCString(option); diff --git a/postgresql-client/src/test/resources/tls/test-client-enc.key b/postgresql-client/src/test/resources/tls/test-client-enc.key new file mode 100644 index 00000000..648183e4 --- /dev/null +++ b/postgresql-client/src/test/resources/tls/test-client-enc.key @@ -0,0 +1,37 @@ +# Throwaway TEST-ONLY encrypted PKCS#8 copy of test-client.key for +# SslMaterialsClientKeyTest. The passphrase is correct-horse-battery. Made with: +# openssl pkcs8 -topk8 -in test-client.key -out test-client-enc.key \ +# -v2 aes-256-cbc -v2prf hmacWithSHA256 -iter 2048 +# (PBES2: PBKDF2-HmacSHA256 + AES-256-CBC, what modern openssl emits). Checked in +# rather than encrypted at runtime: re-encoding PBES2 parameters through the JDK +# loses the PRF on JDK 25, which made the test key unreadable there. +-----BEGIN ENCRYPTED PRIVATE KEY----- +MIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQUYD51sSBDnWou2QL +QNYpDAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEAdoWYtGg20zB1OR +q+hI5WoEggTQ/hrmbQEP/8j4NikPiBYLB/QAeDCBs871yECgmSOo5+nrXoJm2/ue +UMrKzAasJ6XjPN4mv8vO12vaotAEqwmJHrqM3Rxv1L4chykmIj+LV2O9Z8aAV2Nx +lILTOMhHrGnMjF1xNVViOvnHY8Ww3whXhRoeuLHP3DKsY06LZLazB7WcVYP8/Jyb +k/ncwg3uyLAILTMahTsp1FKQhLySl5rADVSkWhPcaoLj/XqLv7GAvH67fFgzHG0T +XCT9a6Pb8Bw+HR9OhnuzlIVQPe+mNw6y9LaNlAOhxxzIPDfzwmO+vDkoooDaWbdy +RduBIl+hEp1aQaVimvkoc84NsFreqjjlBLtJOfCKhqdWQUlEw7r/RWQCt63bUJGP +habDh1keWidtquh0y37SAfbpBcYuf3VMafReqZExA8jqC10AgosAQOeDyTls516c +d26OX5rE4slTZDurMJB+9EdIJ4KJRNVqrusf7YU8ZN1nxr7JbXRxuju8Rb9sQVN7 +ncL3sZ6FskSH+zi2uDh9QIYqz90CrVhTk8Lf3lbu710n/1bGmUY7whYF7CtmNNTk +3ML58NoNTx/75d32cUcpC4TG6rXvh55SiSE6C2mfwA2nGX7RvY6PB/VJAl2lWGzs +iVbl4Xc71b+FaROfZKkEC8MlIJGs0O3JmqZ/rl5M5QwHBo/vDAVWMbfHm/LZS3PM +gheNQ+GHh1rnTD5Pxk+JEUfH+7+sZh25jYNy7Jq63CM31LsH2xKEuUlOjql5a4mR +J8MkW/KZpmzFpTOcKV5I064AkjK/KyTkUpRrHt/n9/8E02x5IqytXCBuSU+DsJBr +dAB4M/LN/THxI0UVZz8lblPvK96qVJg/QNFdy0vmCd/qnRWJ8wn6BOAAzy6JvinQ +fFjS1xpuh2u6P5C62gR+UOx9ar5mJ4hURBmbqowAyuVhKDA3M6j+la/atnAn2doz +ajj102nTm2dL4lgSc26IlGzIuO9CHMqKUdiILGZLQlHUuLiby1d5skuKsh51cNJv +SQH/UO2is8ZpG4ErYjYT9nxI9nMppQTFSmEY/A614PX8hsBgaCteOKKWW/YGnrHg +s8cKq9vQR5H7uUr6WyskPlwa2uM4FWBQ/ym73q7E3ZznIKz7PE80csalpv3LxQTV +fESLLCacZ7KdAB2RXX5I7pkVFLNb0MBC7wFdFSqfFVLTL+3rnNEzgXdxory9B7QJ +GKRVQYtHZSZ5baUaHr7GWuWWkVDDEzBXyzjnXZuuNyeH5ioeMA4ar89Ew40+VqkR +NtMjWzHCge6TODl7k8/O+nTfa4NdMcHDyw6sLh4e0+aBFXeDqnfj1WfGSHF1CrBJ +X6IsywNbF+xjFrbPU7iluBfrudMJ7YNIJ9RMm6xw3MB74qSov1HKQG8KX7JpPVH/ +CAOsat6QAbUeARZAdcXf5HCgRESOBjq7sJ/PAnh3a6TwE7t539nlDes75q2NAqN1 +ri0MYYyvLFq9kWuuhatywNJRqBqY5tfcL9q/4mQtQv4JH4bJdEcugq8ByiTyo4Q1 +6xFWML8TxV7LUVuzaHFYj6Ydl7FZ+MBKWz3kjU1CzlCN0GBSPM2sVHKpLYZYu+W3 +99mN77xHp9cLtEVvhzWjpVtwcnn6ZvBFht4fRq+SIadVsVGyYPTHewg= +-----END ENCRYPTED PRIVATE KEY----- diff --git a/postgresql-client/src/test/resources/tls/test-client.key b/postgresql-client/src/test/resources/tls/test-client.key index 583f59a0..8131d9bb 100644 --- a/postgresql-client/src/test/resources/tls/test-client.key +++ b/postgresql-client/src/test/resources/tls/test-client.key @@ -1,7 +1,7 @@ # Throwaway TEST-ONLY plaintext PKCS#8 private key for SslMaterialsClientKeyTest. # It matches test-client.crt, protects nothing, and was generated offline with -# openssl (see the header of test-client.crt for the exact command). The tests -# derive the encrypted-key variants from this key at runtime with JDK crypto. +# openssl (see the header of test-client.crt for the exact command). +# test-client-enc.key is this key encrypted with a passphrase. # The driver tolerates this comment header (text outside the PEM envelope is # skipped, like libpq), and the tests feed this file both raw and stripped. -----BEGIN PRIVATE KEY-----