Skip to content

Commit 88a90a7

Browse files
committed
SchemaController: User PreparedStatements where possible
Use PreparedStatements where possible in the SchemaController in order to avoid SQL Injections. Note that PreparedSatements can only dynamically bind values and not object names, so this technique could only be applied to the queries, and not the DDL statements. The security around these statement can probably be improved by sanitizing the schema values, but it's out of the scope of this PR. As a side bonus, this PR also uses the try-with-resource idiom when creating these PreparedStatements and ResultSets so they will be properly closed instead of the current implementation that may leak resources. Closes #120
1 parent 90459ed commit 88a90a7

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

samples/mysql-schema/src/main/java/com/github/containersolutions/operator/sample/SchemaController.java

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
import java.sql.Connection;
1515
import java.sql.DriverManager;
16+
import java.sql.PreparedStatement;
1617
import java.sql.ResultSet;
1718
import java.sql.SQLException;
1819
import java.sql.Statement;
@@ -140,17 +141,22 @@ private Connection getConnection() throws SQLException {
140141
}
141142

142143
private boolean schemaExists(Connection connection, String schemaName) throws SQLException {
143-
ResultSet resultSet = connection.createStatement().executeQuery(
144-
format("SELECT schema_name FROM information_schema.schemata WHERE schema_name = \"%1$s\"",
145-
schemaName));
146-
return resultSet.first();
144+
try (PreparedStatement ps =
145+
connection.prepareStatement("SELECT schema_name FROM information_schema.schemata WHERE schema_name = ?")) {
146+
ps.setString(1, schemaName);
147+
try (ResultSet resultSet = ps.executeQuery()) {
148+
return resultSet.first();
149+
}
150+
}
147151
}
148152

149153
private boolean userExists(Connection connection, String userName) throws SQLException {
150-
try (Statement statement = connection.createStatement()) {
151-
ResultSet resultSet = statement.executeQuery(format("SELECT User FROM mysql.user WHERE User='%1$s'",
152-
userName));
153-
return resultSet.first();
154+
try (PreparedStatement ps =
155+
connection.prepareStatement("SELECT User FROM mysql.user WHERE User = ?")) {
156+
ps.setString(1, userName);
157+
try (ResultSet resultSet = ps.executeQuery()) {
158+
return resultSet.first();
159+
}
154160
}
155161
}
156162
}

0 commit comments

Comments
 (0)