Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ protected SchemaReader getSchemaReader(String sessionID) {

@Override
protected String getTableName(String database, String schema, String table) {
return String.format("\"%s\".\"%s\"", schema, table);
return quoteIdentifier(schema, '"') + "." + quoteIdentifier(table, '"');
}
Comment thread
vishwasvaidya-cloudsufi marked this conversation as resolved.
Resolved

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ public void getTableNameTest() {
CONNECTOR.getTableName("db", "schema", "table"));
}

/**
* Unit test for getTableName() with identifiers containing double quotes
*/
@Test
public void getTableNameEscapesQuotesTest() {
Assert.assertEquals("\"my\"\"schema\".\"t\"\"; DELETE FROM x; --\"",
CONNECTOR.getTableName("db", "my\"schema", "t\"; DELETE FROM x; --"));
}

@Test
public void getRandomQuery() {
Assert.assertEquals("SELECT * FROM TestData\n" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ protected SchemaReader getSchemaReader(String sessionID) {

@Override
protected String getTableName(String database, String schema, String table) {
return String.format("`%s`.`%s`", database, table);
return quoteIdentifier(database, '`') + "." + quoteIdentifier(table, '`');
}
Comment thread
vishwasvaidya-cloudsufi marked this conversation as resolved.
Resolved

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright © 2026 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

package io.cdap.plugin.cloudsql.mysql;

import org.junit.Assert;
import org.junit.Test;

/**
* Unit tests for {@link CloudSQLMySQLConnector}
*/
public class CloudSQLMySQLConnectorUnitTest {

private static final CloudSQLMySQLConnector CONNECTOR = new CloudSQLMySQLConnector(
new CloudSQLMySQLConnectorConfig("user", "password", "cloudsql-mysql", "", "public",
"project:region:instance", "db", null));

/**
* Unit test for getTableName()
*/
@Test
public void getTableNameTest() {
Assert.assertEquals("`db`.`table`",
CONNECTOR.getTableName("db", null, "table"));
}

/**
* Unit test for getTableName() with identifiers containing backticks
*/
@Test
public void getTableNameEscapesBackticksTest() {
Assert.assertEquals("`my``db`.`t``; DELETE FROM x; --`",
CONNECTOR.getTableName("my`db", null, "t`; DELETE FROM x; --"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ protected SchemaReader getSchemaReader(String sessionID) {

@Override
protected String getTableName(String database, String schema, String table) {
return String.format("\"%s\".\"%s\"", schema, table);
return quoteIdentifier(schema, '"') + "." + quoteIdentifier(table, '"');
}
Comment thread
vishwasvaidya-cloudsufi marked this conversation as resolved.
Resolved

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright © 2026 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

package io.cdap.plugin.cloudsql.postgres;

import org.junit.Assert;
import org.junit.Test;

/**
* Unit tests for {@link CloudSQLPostgreSQLConnector}
*/
public class CloudSQLPostgreSQLConnectorUnitTest {

private static final CloudSQLPostgreSQLConnector CONNECTOR = new CloudSQLPostgreSQLConnector(
new CloudSQLPostgreSQLConnectorConfig("user", "password", "cloudsql-postgresql", "", "public",
"project:region:instance", "db", null));

/**
* Unit test for getTableName()
*/
@Test
public void getTableNameTest() {
Assert.assertEquals("\"schema\".\"table\"",
CONNECTOR.getTableName("db", "schema", "table"));
}

/**
* Unit test for getTableName() with identifiers containing double quotes, using the payload from the
* reported sample path SQL injection
*/
@Test
public void getTableNameEscapesQuotesTest() {
String table = "pg_class\" LIMIT 0; UPDATE audit_vault.write_marker SET value='INJECTED_BY_SAMPLE_PATH' " +
"WHERE id=1; SELECT * FROM \"pg_catalog\".\"pg_class";
Assert.assertEquals("\"pg_catalog\".\"pg_class\"\" LIMIT 0; UPDATE audit_vault.write_marker SET " +
"value='INJECTED_BY_SAMPLE_PATH' WHERE id=1; SELECT * FROM \"\"pg_catalog\"\".\"\"pg_class\"",
CONNECTOR.getTableName("db", "pg_catalog", table));
Assert.assertEquals("\"my\"\"schema\".\"table\"",
CONNECTOR.getTableName("db", "my\"schema", "table"));
}
}
5 changes: 5 additions & 0 deletions database-commons/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,11 @@
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public class ConnectionConfigAccessor {
private static final String CONNECTION_ARGUMENTS = "io.cdap.plugin.db.connection.arguments";
private static final String INIT_QUERIES = "io.cdap.plugin.db.init.queries";
public static final String AUTO_COMMIT_ENABLED = "io.cdap.plugin.db.output.autocommit.enabled";
public static final String READ_ONLY = "io.cdap.plugin.db.readonly";
public static final String FETCH_SIZE = "io.cdap.plugin.db.fetch.size";
public static final String OPERATION_NAME = "io.cdap.plugin.db.operation.name";
public static final String RELATION_TABLE_KEY = "io.cdap.plugin.db.relation.table.key";
Expand Down Expand Up @@ -101,6 +102,14 @@ public boolean isAutoCommitEnabled() {
return configuration.getBoolean(AUTO_COMMIT_ENABLED, false);
}

public void setReadOnly(boolean readOnly) {
configuration.setBoolean(READ_ONLY, readOnly);
}

public boolean isReadOnly() {
return configuration.getBoolean(READ_ONLY, false);
}

public void setFetchSize(Integer fetchSize) {
configuration.setInt(FETCH_SIZE, fetchSize);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright © 2026 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/

package io.cdap.plugin.db;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;

/**
* A {@link ForwardingConnection} for read-only operations that turns {@link #commit()} into {@link #rollback()} and
* rolls back any active transaction before closing, so Hadoop's {@code DBRecordReader#close()} or an implicit
* driver commit-on-close can never commit changes.
*/
public class RollbackOnCloseConnection extends ForwardingConnection {

private static final Logger LOG = LoggerFactory.getLogger(RollbackOnCloseConnection.class);

public RollbackOnCloseConnection(Connection delegate) {
super(delegate);
}

@Override
public void commit() throws SQLException {
getDelegate().rollback();
}

@Override
public void close() throws SQLException {
try {
if (!getDelegate().isClosed() && !getDelegate().getAutoCommit()) {
getDelegate().rollback();
}
} catch (SQLException e) {
LOG.debug("Failed to roll back read-only connection before close.", e);
} finally {
super.close();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,16 @@
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBWritable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import javax.annotation.Nullable;

Expand All @@ -59,6 +62,8 @@
public abstract class AbstractDBSpecificConnector<T extends DBWritable> extends AbstractDBConnector
implements BatchConnector<LongWritable, T> {

private static final Logger LOG = LoggerFactory.getLogger(AbstractDBSpecificConnector.class);

private final AbstractDBConnectorConfig config;
private final RetryPolicy<?> retryPolicy;
protected DBErrorDetailsProvider dbErrorDetailsProvider;
Expand Down Expand Up @@ -105,6 +110,7 @@ public InputFormatProvider getInputFormatProvider(ConnectorContext context, Samp
request.getProperties().get("sampleType"), request.getProperties().get("strata"), sessionID);
DataDrivenETLDBInputFormat.setInput(connectionConfigAccessor.getConfiguration(), getDBRecordType(),
tableQuery, null, isAutoCommitEnabled());
connectionConfigAccessor.setReadOnly(true);
connectionConfigAccessor.setConnectionArguments(Maps.fromProperties(config.getConnectionArgumentsProperties()));
String isolationLevel = getTransactionIsolationLevel();
if (isolationLevel != null) {
Expand All @@ -115,11 +121,11 @@ public InputFormatProvider getInputFormatProvider(ConnectorContext context, Samp
for (Map.Entry<String, String> argument : additionalArguments.entrySet()) {
connectionConfigAccessor.getConfiguration().set(argument.getKey(), argument.getValue());
}
try {
try (Connection connection = getConnection(path)) {
Long timeoutMs = request.getTimeoutMs();
Integer timeoutSec = timeoutMs != null ? (int) (timeoutMs / 1000) : null;
connectionConfigAccessor
.setSchema(loadTableSchema(getConnection(path), tableQuery, timeoutSec, sessionID).toString());
.setSchema(loadTableSchema(connection, tableQuery, timeoutSec, sessionID).toString());
} catch (SQLException e) {
throw new IOException(String.format("Failed to get table schema due to: %s.",
ExceptionUtils.getRootCauseMessage(e)), e);
Expand Down Expand Up @@ -150,8 +156,18 @@ protected String getConnectionString(String database) {
}

protected String getTableName(String database, String schema, String table) {
return schema == null ? String.format("\"%s\".\"%s\"", database, table)
: String.format("\"%s\".\"%s\".\"%s\"", database, schema, table);
return schema == null ? quoteIdentifier(database, '"') + "." + quoteIdentifier(table, '"')
: quoteIdentifier(database, '"') + "." + quoteIdentifier(schema, '"') + "." + quoteIdentifier(table, '"');
}
Comment thread
vishwasvaidya-cloudsufi marked this conversation as resolved.
Resolved

/**
* Wraps the given identifier in the given quote character, doubling any embedded quote characters so that a
* user supplied database, schema, table or column name can never break out of the quoted identifier.
*/
protected static String quoteIdentifier(String identifier, char quote) {
Objects.requireNonNull(identifier, "identifier to quote must not be null");
String quoteString = String.valueOf(quote);
return quoteString + identifier.replace(quoteString, quoteString + quoteString) + quoteString;
}

protected String getTableQuery(String database, String schema, String table) {
Expand Down Expand Up @@ -197,15 +213,46 @@ protected String getStratifiedQuery(String tableName, int limit, String strata,

protected Schema loadTableSchema(Connection connection, String query, @Nullable Integer timeoutSec, String sessionID)
throws SQLException {
try (Statement statement = RetryUtils.createStatementWithRetry((RetryPolicy<Statement>) retryPolicy, connection,
getErrorDetailsProvider())) {
statement.setMaxRows(1);
if (timeoutSec != null) {
statement.setQueryTimeout(timeoutSec);
}
ResultSet resultSet = RetryUtils.executeQueryWithRetry((RetryPolicy<ResultSet>) retryPolicy, statement, query,
getErrorDetailsProvider());
boolean rollbackOnExit = configureReadOnlyTransaction(connection);
try (Statement statement = RetryUtils.createStatementWithRetry((RetryPolicy<Statement>) retryPolicy, connection,
getErrorDetailsProvider())) {
statement.setMaxRows(1);
if (timeoutSec != null) {
statement.setQueryTimeout(timeoutSec);
}
try (ResultSet resultSet = RetryUtils.executeQueryWithRetry((RetryPolicy<ResultSet>) retryPolicy, statement,
query, getErrorDetailsProvider())) {
return Schema.recordOf("outputSchema", getSchemaReader(sessionID).getSchemaFields(resultSet));
}
} finally {
if (rollbackOnExit) {
try {
connection.rollback();
} catch (SQLException e) {
LOG.debug("Failed to roll back read-only schema query transaction.", e);
}
}
}
}

private boolean configureReadOnlyTransaction(@Nullable Connection connection) {
if (connection == null) {
return false;
}
try {
connection.setReadOnly(true);
} catch (SQLException e) {
LOG.debug("Driver does not support setting connection read-only; continuing.", e);
}
if (isAutoCommitEnabled()) {
return false;
}
try {
connection.setAutoCommit(false);
return true;
} catch (SQLException e) {
LOG.debug("Driver does not support disabling auto-commit; continuing.", e);
return false;
}
}

Expand All @@ -218,8 +265,10 @@ protected void setConnectionProperties(Map<String, String> properties, Connector
protected Schema getTableSchema(Connection connection, String database,
String schema, String table) throws SQLException {
String sessionID = generateSessionID();
return loadTableSchema(getConnection(), getTableQuery(database, schema, table),
null, sessionID);
try (Connection schemaConnection = getConnection()) {
return loadTableSchema(schemaConnection, getTableQuery(database, schema, table),
null, sessionID);
}
}

protected String generateSessionID() {
Expand Down
Loading
Loading