|
| 1 | +package com.dbaagent.util; |
| 2 | + |
| 3 | +import org.junit.jupiter.api.Test; |
| 4 | + |
| 5 | +import static org.junit.jupiter.api.Assertions.*; |
| 6 | + |
| 7 | +/** |
| 8 | + * Identifier quoting for the SQL that cannot be parameterised. |
| 9 | + * |
| 10 | + * <p>Table and column names cannot be bind parameters, so they are interpolated into SQL by |
| 11 | + * hand. {@code CardinalityEstimationService.quoteIdentifier} wrapped them in quotes and never |
| 12 | + * doubled an embedded one, which is no protection at all — the same way |
| 13 | + * {@code "'" + value + "'"} is no protection for a string literal. |
| 14 | + * |
| 15 | + * <p>Verified against a real PostgreSQL, not inferred. A {@code tableName} path variable of |
| 16 | + * {@code victim" AS t; DROP TABLE zz_inj.probe; SELECT 1 FROM zz_inj."victim} produced |
| 17 | + * |
| 18 | + * <pre>SELECT COUNT(*) FROM zz_inj."victim" AS t; DROP TABLE zz_inj.probe; SELECT 1 FROM zz_inj."victim"</pre> |
| 19 | + * |
| 20 | + * which ran with no errors: the count returned, the table was dropped (it existed before and |
| 21 | + * did not after), and the trailing select returned its rows. The payload carries no {@code /}, |
| 22 | + * so Spring's {@code StrictHttpFirewall} does not stand in its way. |
| 23 | + */ |
| 24 | +class SqlIdentifierTest { |
| 25 | + |
| 26 | + // ── the injection that was proven to execute ────────────────────────────── |
| 27 | + |
| 28 | + @Test |
| 29 | + void doublesAnEmbeddedDoubleQuoteSoTheIdentifierCannotBeClosed() { |
| 30 | + String payload = "victim\" AS t; DROP TABLE zz_inj.probe; SELECT 1 FROM zz_inj.\"victim"; |
| 31 | + |
| 32 | + String quoted = SqlIdentifier.quote(payload, "postgres"); |
| 33 | + |
| 34 | + assertEquals( |
| 35 | + "\"victim\"\" AS t; DROP TABLE zz_inj.probe; SELECT 1 FROM zz_inj.\"\"victim\"", |
| 36 | + quoted); |
| 37 | + // the whole payload is now one identifier: no unescaped quote can terminate it |
| 38 | + assertEquals(1, countUnescapedQuotes(quoted, '"'), |
| 39 | + "an unescaped quote inside the body would end the identifier early: " + quoted); |
| 40 | + } |
| 41 | + |
| 42 | + @Test |
| 43 | + void doublesAnEmbeddedBacktickForMysql() { |
| 44 | + String payload = "victim` ; DROP TABLE probe; SELECT 1 FROM `victim"; |
| 45 | + |
| 46 | + String quoted = SqlIdentifier.quote(payload, "mysql"); |
| 47 | + |
| 48 | + assertEquals("`victim`` ; DROP TABLE probe; SELECT 1 FROM ``victim`", quoted); |
| 49 | + assertEquals(1, countUnescapedQuotes(quoted, '`'), quoted); |
| 50 | + } |
| 51 | + |
| 52 | + /** |
| 53 | + * The sinks build {@code SELECT COUNT(*) FROM %s}, so the property that matters is that the |
| 54 | + * whole payload lands inside one identifier rather than becoming a second statement. |
| 55 | + * |
| 56 | + * <p>Asserted on the parse, not on the text. A first version of this test used the regex |
| 57 | + * {@code .*"\s*;.*} and failed on correct output, because {@code "";} is an <em>escaped</em> |
| 58 | + * quote followed by a semicolon <em>inside</em> the identifier — textually close to a |
| 59 | + * terminator and semantically its opposite. That is the same confusion the vulnerable |
| 60 | + * quoter made, so it is worth not repeating in the test. |
| 61 | + * |
| 62 | + * <p>Confirmed against a real PostgreSQL: this exact SQL answers |
| 63 | + * {@code ERROR: relation "t"; DROP TABLE zz_v.probe; --" does not exist} — the server read |
| 64 | + * the payload as one table name — and the probe table it names was still there afterwards, |
| 65 | + * where the unescaped form had dropped it. |
| 66 | + */ |
| 67 | + @Test |
| 68 | + void theInjectedStatementCollapsesIntoASingleIdentifier() { |
| 69 | + String payload = "t\"; DROP TABLE probe; --"; |
| 70 | + |
| 71 | + String quoted = SqlIdentifier.quote(payload, "postgres"); |
| 72 | + String sql = "SELECT COUNT(*) FROM " + quoted; |
| 73 | + |
| 74 | + assertEquals("SELECT COUNT(*) FROM \"t\"\"; DROP TABLE probe; --\"", sql); |
| 75 | + assertTrue(sql.endsWith(quoted), "the identifier must be the whole tail of the statement"); |
| 76 | + assertEquals(1, countUnescapedQuotes(quoted, '"'), |
| 77 | + "only the closing quote may be unescaped, or the identifier ends early: " + quoted); |
| 78 | + } |
| 79 | + |
| 80 | + // ── ordinary identifiers must keep working ──────────────────────────────── |
| 81 | + |
| 82 | + @Test |
| 83 | + void leavesAnOrdinaryIdentifierAloneApartFromTheQuotes() { |
| 84 | + assertEquals("\"orders\"", SqlIdentifier.quote("orders", "postgres")); |
| 85 | + assertEquals("\"total_amount\"", SqlIdentifier.quote("total_amount", "postgres")); |
| 86 | + assertEquals("`orders`", SqlIdentifier.quote("orders", "mysql")); |
| 87 | + } |
| 88 | + |
| 89 | + @Test |
| 90 | + void picksTheQuoteCharacterFromTheDialect() { |
| 91 | + assertEquals("`t`", SqlIdentifier.quote("t", "mysql")); |
| 92 | + assertEquals("`t`", SqlIdentifier.quote("t", "MySQL")); |
| 93 | + assertEquals("\"t\"", SqlIdentifier.quote("t", "postgres")); |
| 94 | + assertEquals("\"t\"", SqlIdentifier.quote("t", "postgresql")); |
| 95 | + } |
| 96 | + |
| 97 | + /** |
| 98 | + * An unknown or null dialect must not fall through to "no quoting". Postgres double quotes |
| 99 | + * are the ANSI form and the safe default; guessing MySQL backticks for an unknown dialect |
| 100 | + * would be the riskier direction. |
| 101 | + */ |
| 102 | + @Test |
| 103 | + void defaultsToAnsiQuotingForAnUnknownDialect() { |
| 104 | + assertEquals("\"t\"", SqlIdentifier.quote("t", null)); |
| 105 | + assertEquals("\"t\"", SqlIdentifier.quote("t", "oracle")); |
| 106 | + assertEquals("\"t\"", SqlIdentifier.quote("t", "")); |
| 107 | + } |
| 108 | + |
| 109 | + // ── rejecting what should never reach SQL at all ────────────────────────── |
| 110 | + |
| 111 | + /** |
| 112 | + * Escaping alone makes injection impossible but still lets a caller name an identifier the |
| 113 | + * feature never meant to touch. {@code requireSafe} is the second layer: the brain's |
| 114 | + * statistics paths only ever address real tables and columns, so anything that cannot be |
| 115 | + * one is refused before a statement is built. |
| 116 | + */ |
| 117 | + @Test |
| 118 | + void refusesAnIdentifierCarryingSqlSyntax() { |
| 119 | + for (String bad : new String[] { |
| 120 | + "victim\" AS t; DROP TABLE probe; --", |
| 121 | + "t; DROP TABLE probe", |
| 122 | + "t--comment", |
| 123 | + "t/*x*/", |
| 124 | + "t'or'1'='1" |
| 125 | + }) { |
| 126 | + assertThrows(IllegalArgumentException.class, |
| 127 | + () -> SqlIdentifier.requireSafe(bad), "should refuse: " + bad); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + @Test |
| 132 | + void refusesBlankAndNull() { |
| 133 | + assertThrows(IllegalArgumentException.class, () -> SqlIdentifier.requireSafe(null)); |
| 134 | + assertThrows(IllegalArgumentException.class, () -> SqlIdentifier.requireSafe(" ")); |
| 135 | + } |
| 136 | + |
| 137 | + /** |
| 138 | + * Real schemas carry all of these. A validator that refused them would break the feature it |
| 139 | + * is protecting, which is the usual reason such a check gets deleted later. |
| 140 | + */ |
| 141 | + @Test |
| 142 | + void acceptsTheIdentifiersRealSchemasActuallyUse() { |
| 143 | + for (String ok : new String[] { |
| 144 | + "orders", |
| 145 | + "total_amount", |
| 146 | + "Orders", |
| 147 | + "order_items_2026", |
| 148 | + "public.orders", |
| 149 | + "_private", |
| 150 | + "v_daily_revenue", |
| 151 | + "tableName$" |
| 152 | + }) { |
| 153 | + assertEquals(ok, SqlIdentifier.requireSafe(ok), "should accept: " + ok); |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + @Test |
| 158 | + void requireSafeReturnsTheIdentifierSoItComposesWithQuote() { |
| 159 | + assertEquals("\"orders\"", |
| 160 | + SqlIdentifier.quote(SqlIdentifier.requireSafe("orders"), "postgres")); |
| 161 | + } |
| 162 | + |
| 163 | + /** Counts quote characters that are not part of a doubled pair. */ |
| 164 | + private static int countUnescapedQuotes(String quoted, char q) { |
| 165 | + String body = quoted.substring(1, quoted.length() - 1); |
| 166 | + int unescaped = 0; |
| 167 | + for (int i = 0; i < body.length(); i++) { |
| 168 | + if (body.charAt(i) != q) continue; |
| 169 | + if (i + 1 < body.length() && body.charAt(i + 1) == q) { i++; continue; } |
| 170 | + unescaped++; |
| 171 | + } |
| 172 | + return unescaped + 1; // the closing quote |
| 173 | + } |
| 174 | +} |
0 commit comments