mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(rds-data): reject SQL containing multiple statements (#5556)
* fix(rds-data): reject SQL containing multiple statements * fix(rds-data): honor MySQL line comment rules * test(cognito): serialize temporary passwords in invitation auth * fix(rds-data): align statement validation with AWS review * fix(rds-data): preserve AWS validation message punctuation
This commit is contained in:
1 parent
c4a809f47f
commit
f833ca9e12
6 files changed
+189
-10
No files matched your search
@@ -43,6 +43,7 @@ The deprecated `ExecuteSql` operation is recognized at `POST /ExecuteSql` and re
|
||||
- `BatchExecuteStatement` runs the statement once per entry in `parameterSets` through a JDBC batch and returns one `updateResults` entry per set, each carrying the `generatedFields` that set produced under the same engine rules as `ExecuteStatement` — a set inserting several rows reports one field per generated key. On MySQL and MariaDB the sets are executed one at a time so each entry owns its own keys, because `getGeneratedKeys()` after a JDBC batch reports every key the batch generated with nothing tying a key back to the set that produced it. It accepts `transactionId`, so a batch can take part in a Data API transaction; without one the batch commits automatically. An absent or empty `parameterSets` runs nothing and returns an empty `updateResults`: AWS runs the statement once per parameter set provided and points a caller who wants a single parameterless execution at one empty set (`[[]]`, which runs once here) or at `ExecuteStatement`. A statement that returns rows rather than an update count — a `SELECT`, or a CTE ending in one — is rejected with `BadRequestException` before any set runs, because a batch reports one `UpdateResult` per set and has nowhere to carry a result set, and AWS documents the operation as taking a DML statement. The check reads the driver's description of the prepared statement, so nothing executes first, and a DML statement that also reports rows through a PostgreSQL `RETURNING` clause is left alone: the batch still performs its writes, and `generatedFields` is empty on PostgreSQL anyway.
|
||||
- A result set in which any single row is larger than 64 KB is rejected with `UnsupportedResultException` and the message `Packet for query is too large`, as the Data API troubleshooting guide describes. A row is measured by its values as the driver returns them (the raw length of a binary value, the UTF-8 length of anything else), so JSON escaping and base64 encoding in the response do not count toward it.
|
||||
- A PostgreSQL result set with a `point`, `box`, `circle`, `line`, `lseg`, `path`, `polygon`, `interval`, or `money` column is rejected with `UnsupportedResultException`, as on Aurora PostgreSQL. Cast the column to text to read it.
|
||||
- Each executed SQL string must contain one statement. Multi-statement input is rejected with `ValidationException` and `Multistatements aren't supported.` before any statement runs, including in a transaction or a nonempty batch. Semicolons inside quoted literals, identifiers, comments, or dollar-quoted strings do not separate statements.
|
||||
- SQL errors are returned as `DatabaseErrorException` so AWS SDK callers can handle database failures with normal AWS error decoding.
|
||||
- If `secretArn` points to a local Secrets Manager secret with JSON credentials (`username` or `user`, plus `password`), those credentials are used. A missing or unavailable secret returns `SecretsErrorException`; malformed or incomplete credentials return `InvalidSecretException`. Floci does not fall back to the resolved RDS resource's master credentials when a secret ARN was supplied.
|
||||
- `formatRecordsAs=JSON`, `formattedRecords`, and `resultSetOptions` are not implemented yet, and `ExecuteStatement` requests asking for those result modes return `BadRequestException`. They are `ExecuteStatement`-only fields in the AWS API, so `BatchExecuteStatement` — whose input is limited to `resourceArn`, `secretArn`, `sql`, `database`, `schema`, `parameterSets`, and `transactionId` — ignores them as AWS does rather than rejecting them.
|
||||
|
||||
@@ -31,12 +31,13 @@ public final class SqlParameterParser {
|
||||
* honor backslash escapes (e.g. Redshift Data API)
|
||||
* @param numericNames whether a parameter name may start with a digit, as in
|
||||
* {@code :1} (RDS Data API)
|
||||
* @param mysqlComments whether comments follow MySQL's hash, double-dash, and non-nesting rules
|
||||
*/
|
||||
public record Options(boolean allowBackticks, boolean backslashEscapes, boolean escapeStrings,
|
||||
boolean numericNames) {
|
||||
public static final Options REDSHIFT = new Options(false, false, true, false);
|
||||
public static final Options RDS_MYSQL = new Options(true, true, false, true);
|
||||
public static final Options RDS_POSTGRESQL = new Options(true, false, false, true);
|
||||
boolean numericNames, boolean mysqlComments) {
|
||||
public static final Options REDSHIFT = new Options(false, false, true, false, false);
|
||||
public static final Options RDS_MYSQL = new Options(true, true, false, true, true);
|
||||
public static final Options RDS_POSTGRESQL = new Options(true, false, false, true, false);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -68,7 +69,7 @@ public final class SqlParameterParser {
|
||||
while (i < len) {
|
||||
char c = sql.charAt(i);
|
||||
|
||||
if (c == '-' && i + 1 < len && sql.charAt(i + 1) == '-') {
|
||||
if (startsLineComment(sql, i, options)) {
|
||||
int end = sql.indexOf('\n', i);
|
||||
end = end < 0 ? len : end;
|
||||
out.append(sql, i, end);
|
||||
@@ -77,8 +78,7 @@ public final class SqlParameterParser {
|
||||
}
|
||||
|
||||
if (c == '/' && i + 1 < len && sql.charAt(i + 1) == '*') {
|
||||
int end = sql.indexOf("*/", i + 2);
|
||||
end = end < 0 ? len : end + 2;
|
||||
int end = skipBlockComment(sql, i, !options.mysqlComments());
|
||||
out.append(sql, i, end);
|
||||
i = end;
|
||||
continue;
|
||||
@@ -196,15 +196,14 @@ public final class SqlParameterParser {
|
||||
while (i < len) {
|
||||
char c = sql.charAt(i);
|
||||
|
||||
if (c == '-' && i + 1 < len && sql.charAt(i + 1) == '-') {
|
||||
if (startsLineComment(sql, i, options)) {
|
||||
int end = sql.indexOf('\n', i);
|
||||
i = end < 0 ? len : end;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (c == '/' && i + 1 < len && sql.charAt(i + 1) == '*') {
|
||||
int end = sql.indexOf("*/", i + 2);
|
||||
i = end < 0 ? len : end + 2;
|
||||
i = skipBlockComment(sql, i, !options.mysqlComments());
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -232,6 +231,38 @@ public final class SqlParameterParser {
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean startsLineComment(String sql, int start, Options options) {
|
||||
boolean mysql = options.mysqlComments();
|
||||
if (mysql && sql.charAt(start) == '#') {
|
||||
return true;
|
||||
}
|
||||
if (sql.charAt(start) != '-' || start + 1 >= sql.length() || sql.charAt(start + 1) != '-') {
|
||||
return false;
|
||||
}
|
||||
return !mysql || (start + 2 < sql.length()
|
||||
&& (Character.isWhitespace(sql.charAt(start + 2)) || Character.isISOControl(sql.charAt(start + 2))));
|
||||
}
|
||||
|
||||
private static int skipBlockComment(String sql, int start, boolean nested) {
|
||||
int depth = 1;
|
||||
int i = start + 2;
|
||||
while (i + 1 < sql.length()) {
|
||||
if (nested && sql.charAt(i) == '/' && sql.charAt(i + 1) == '*') {
|
||||
depth++;
|
||||
i += 2;
|
||||
} else if (sql.charAt(i) == '*' && sql.charAt(i + 1) == '/') {
|
||||
depth--;
|
||||
i += 2;
|
||||
if (depth == 0) {
|
||||
return i;
|
||||
}
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return sql.length();
|
||||
}
|
||||
|
||||
private static int skipQuoted(String sql, int start, char quote, Options options) {
|
||||
int len = sql.length();
|
||||
boolean escapable = (options.backslashEscapes() && quote != '`')
|
||||
|
||||
@@ -50,6 +50,11 @@ final class RdsDataSqlParameters {
|
||||
* colon inside any of those is left untouched.
|
||||
*/
|
||||
static ParsedSql parse(String sql, boolean backslashEscapes) {
|
||||
SqlParameterParser.Options statementOptions = new SqlParameterParser.Options(
|
||||
true, backslashEscapes, !backslashEscapes, true, backslashEscapes);
|
||||
if (SqlParameterParser.isMultiStatement(sql, statementOptions)) {
|
||||
throw new AwsException("ValidationException", "Multistatements aren't supported.", 400);
|
||||
}
|
||||
return SqlParameterParser.parse(sql, backslashEscapes
|
||||
? SqlParameterParser.Options.RDS_MYSQL
|
||||
: SqlParameterParser.Options.RDS_POSTGRESQL);
|
||||
|
||||
@@ -153,6 +153,18 @@ class SqlParameterParserTest {
|
||||
assertTrue(SqlParameterParser.isMultiStatement("insert into t values (1); delete from t", Options.REDSHIFT));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nestedBlockCommentsFollowTheSqlDialect() {
|
||||
String sql = "select 1; /* outer /* inner */ select 2; */";
|
||||
assertFalse(SqlParameterParser.isMultiStatement(sql, Options.REDSHIFT));
|
||||
assertTrue(SqlParameterParser.isMultiStatement(sql, Options.RDS_MYSQL));
|
||||
assertTrue(SqlParameterParser.isMultiStatement(sql + " select 3", Options.REDSHIFT));
|
||||
|
||||
ParsedSql parsed = SqlParameterParser.parse("select 1 /* outer /* inner */ :ignored */ + :value",
|
||||
Options.REDSHIFT);
|
||||
assertEquals(List.of("value"), parsed.parameterOrder());
|
||||
}
|
||||
|
||||
@Test
|
||||
void escapeStringWithAnEscapedQuoteIsNotSeenAsMultiStatement() {
|
||||
assertFalse(SqlParameterParser.isMultiStatement("select E'a\\';b' as v", Options.REDSHIFT));
|
||||
@@ -164,6 +176,39 @@ class SqlParameterParserTest {
|
||||
assertFalse(SqlParameterParser.isMultiStatement("select `a;b`", Options.RDS_MYSQL));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mysqlCommentsFollowTheMysqlLineCommentRules() {
|
||||
ParsedSql parsed = SqlParameterParser.parse("select 1--:value # :ignored\n", Options.RDS_MYSQL);
|
||||
assertEquals("select 1--? # :ignored\n", parsed.sql());
|
||||
assertEquals(List.of("value"), parsed.parameterOrder());
|
||||
assertTrue(SqlParameterParser.isMultiStatement("select 1--1; select 2", Options.RDS_MYSQL));
|
||||
assertFalse(SqlParameterParser.isMultiStatement("select 1--1; select 2", Options.REDSHIFT));
|
||||
assertFalse(SqlParameterParser.isMultiStatement("select 1; # ignored; select 2\n", Options.RDS_MYSQL));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mysqlCommentRulesAreIndependentOfQuotingAndParameterOptions() {
|
||||
Options options = new Options(false, false, true, false, true);
|
||||
assertFalse(SqlParameterParser.isMultiStatement("select 1; # ignored; select 2\n", options));
|
||||
assertTrue(SqlParameterParser.isMultiStatement("select 1--1; select 2", options));
|
||||
assertTrue(SqlParameterParser.isMultiStatement("select 1; /* outer /* inner */ select 2; */", options));
|
||||
|
||||
ParsedSql hash = SqlParameterParser.parse("select :value # :ignored\n", options);
|
||||
assertEquals(List.of("value"), hash.parameterOrder());
|
||||
ParsedSql dash = SqlParameterParser.parse("select 1--:value", options);
|
||||
assertEquals(List.of("value"), dash.parameterOrder());
|
||||
ParsedSql block = SqlParameterParser.parse("select :first /* outer /* inner */ + :second", options);
|
||||
assertEquals(List.of("first", "second"), block.parameterOrder());
|
||||
}
|
||||
|
||||
@Test
|
||||
void mysqlQuotingOptionsDoNotEnableMysqlComments() {
|
||||
Options options = new Options(true, true, false, true, false);
|
||||
assertTrue(SqlParameterParser.isMultiStatement("select 1; # not a comment", options));
|
||||
assertFalse(SqlParameterParser.isMultiStatement("select 1--1; select 2", options));
|
||||
assertFalse(SqlParameterParser.isMultiStatement("select 1; /* outer /* inner */ select 2; */", options));
|
||||
}
|
||||
|
||||
@Test
|
||||
void numericNamesAreNotArraySliceBounds() {
|
||||
for (String sql : new String[] {
|
||||
|
||||
@@ -53,6 +53,66 @@ class RdsDataServiceTest {
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@Test
|
||||
void rejectsMultipleStatementsBeforeEitherWriteRuns() throws Exception {
|
||||
TestHarness harness = new TestHarness(DatabaseEngine.POSTGRES);
|
||||
harness.createEventsTable();
|
||||
|
||||
AwsException error = assertThrows(AwsException.class, () -> harness.service.executeStatement(harness.request(
|
||||
"insert into data_api_events(name) values ('first'); insert into data_api_events(name) values ('second')"),
|
||||
REGION));
|
||||
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals("Multistatements aren't supported.", error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
assertEquals(0, harness.countEvents());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMultipleStatementsInsideATransactionWithoutChangingItsData() throws Exception {
|
||||
TestHarness harness = new TestHarness(DatabaseEngine.POSTGRES);
|
||||
harness.createEventsTable();
|
||||
String transactionId = harness.service.beginTransaction(harness.beginRequest(), REGION)
|
||||
.path("transactionId").asText();
|
||||
ObjectNode request = harness.request(
|
||||
"insert into data_api_events(name) values ('first'); insert into data_api_events(name) values ('second')");
|
||||
request.put("transactionId", transactionId);
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> harness.service.executeStatement(request, REGION));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals("Multistatements aren't supported.", error.getMessage());
|
||||
|
||||
harness.service.commitTransaction(harness.transactionRequest(transactionId), REGION);
|
||||
assertEquals(0, harness.countEvents());
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchRejectsMultipleStatementsBeforeAnyParameterSetRuns() throws Exception {
|
||||
for (DatabaseEngine engine : List.of(DatabaseEngine.POSTGRES, DatabaseEngine.MYSQL)) {
|
||||
TestHarness harness = new TestHarness(engine);
|
||||
harness.createEventsTable();
|
||||
ObjectNode request = harness.request(
|
||||
"insert into data_api_events(name) values (:name); insert into data_api_events(name) values ('second')");
|
||||
request.set("parameterSets", parameterSets("first"));
|
||||
|
||||
AwsException error = assertThrows(AwsException.class,
|
||||
() -> harness.service.batchExecuteStatement(request, REGION));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals("Multistatements aren't supported.", error.getMessage());
|
||||
assertEquals(0, harness.countEvents());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void executesSingleStatementsContainingLiteralAndCommentSemicolons() throws Exception {
|
||||
TestHarness harness = new TestHarness(DatabaseEngine.POSTGRES);
|
||||
ObjectNode response = harness.service.executeStatement(harness.request(
|
||||
"select ';' as separator /* ignored; statement */; -- trailing; comment\n"), REGION);
|
||||
|
||||
assertEquals(";", response.path("records").get(0).get(0).path("stringValue").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void executeStatementRejectsAResponseOverOneMebibyte() throws Exception {
|
||||
TestHarness harness = new TestHarness();
|
||||
|
||||
+37
@@ -1,14 +1,51 @@
|
||||
package io.github.hectorvent.floci.services.rdsdata;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.SqlParameterParser.ParsedSql;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class RdsDataSqlParametersTest {
|
||||
|
||||
@Test
|
||||
void rejectsRealStatementsAfterQuotedOrCommentedSemicolons() {
|
||||
for (String sql : List.of("select 1; select 2", "select ';'; select 2",
|
||||
"select $tag$;$tag$; select 2", "select 1; /* ignored */ select 2")) {
|
||||
AwsException error = assertThrows(AwsException.class, () -> RdsDataSqlParameters.parse(sql, false));
|
||||
assertEquals("ValidationException", error.getErrorCode());
|
||||
assertEquals("Multistatements aren't supported.", error.getMessage());
|
||||
assertEquals(400, error.getHttpStatus());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void permitsSingleStatementsWithQuotedAndCommentedSemicolons() {
|
||||
for (String sql : List.of("select ';' as value; -- ignored; text\n", "select \"semi;colon\" from t",
|
||||
"select $tag$a;b$tag$", "select 1; /* outer /* inner */ select 2; */",
|
||||
"select E'it\\';s' as value")) {
|
||||
assertDoesNotThrow(() -> RdsDataSqlParameters.parse(sql, false), sql);
|
||||
}
|
||||
assertDoesNotThrow(() -> RdsDataSqlParameters.parse("select `semi;colon` from t", true));
|
||||
assertDoesNotThrow(() -> RdsDataSqlParameters.parse("select 'it\\';s' as value", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mysqlDoubleMinusOperatorsDoNotHideASecondStatement() {
|
||||
assertThrows(AwsException.class, () -> RdsDataSqlParameters.parse("select 1--1; select 2", true));
|
||||
assertDoesNotThrow(() -> RdsDataSqlParameters.parse("select 1; -- ignored; comment\n", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void mysqlHashCommentsDoNotCreateASecondStatement() {
|
||||
assertDoesNotThrow(() -> RdsDataSqlParameters.parse("select 1; # ignored; select 2\n", true));
|
||||
assertThrows(AwsException.class, () -> RdsDataSqlParameters.parse("select 1; # ignored\n select 2", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rewritesNamedPlaceholdersToPositional() {
|
||||
ParsedSql parsed = RdsDataSqlParameters.parse(
|
||||
|
||||
Reference in new issue
Block a user