diff --git a/docs/services/redshift.md b/docs/services/redshift.md index e5313a7cfc..ee137442a8 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -1160,7 +1160,9 @@ registration; a `DROP FUNCTION` of any function Floci does not track is left to Lambda UDFs. `IAM_ROLE DEFAULT` is refused with `0A000`. - `MAX_BATCH_SIZE` takes `KB` or `MB` (`KB` when omitted) between 1 KB and 5 MB, and `MAX_BATCH_ROWS` is at least 1. The defaults are the documented 20000 ms, 2147483647 rows and 5 MB. The options are stored, and not applied yet. -- An unqualified name is created in `public`. The role and the Lambda function are not checked at creation. +- An unqualified name is created in the session's current schema (`search_path`), failing with `3F000` if no schema is + selected, and unqualified `DROP FUNCTION` resolves through `search_path`. The role and the Lambda function are not + checked at creation. - `CREATE EXTERNAL FUNCTION` and `DROP FUNCTION` of such a function inside an explicit transaction fail with SQLSTATE `25001`, because the registration is not part of the PostgreSQL transaction. - Privileges on `LANGUAGE exfunc` are not modeled: any user the backend lets create a function can create one. diff --git a/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java b/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java index a782906a58..828ce0c8fd 100644 --- a/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java +++ b/src/main/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridge.java @@ -155,8 +155,14 @@ public class RedshiftInterceptingBridge { * budget the caller supplies. */ RedshiftInterceptingBridge(Socket client, Socket backend, ReentrantLock backendLock, long ownershipWaitMillis) { - this(client, backend, null, null, null, List.of(), null, null, null, null, null, null, backendLock, - ownershipWaitMillis, null); + this(client, backend, null, backendLock, ownershipWaitMillis); + } + + /** For tests: as above, with the Spectrum interceptor whose ownership-gated paths the test drives. */ + RedshiftInterceptingBridge(Socket client, Socket backend, SpectrumInterceptor spectrumInterceptor, + ReentrantLock backendLock, long ownershipWaitMillis) { + this(client, backend, null, null, null, List.of(), spectrumInterceptor, "000000000000:c", "dev", null, null, + null, backendLock, ownershipWaitMillis, null); } private RedshiftInterceptingBridge(Socket client, Socket backend, S3Service s3Service, IamService iamService, @@ -364,7 +370,23 @@ public class RedshiftInterceptingBridge { if (spectrumInterceptor != null && parse.parameterTypeOids().isEmpty() && !coordinator.isDiscardingUntilSync()) { try { - SpectrumInterceptor.Plan plan = spectrumInterceptor.plan(parse.sql(), spectrumSession()); + SpectrumInterceptor.Plan plan; + if (spectrumInterceptor.preparation() != null + && spectrumInterceptor.preparation().needsBackendForDdl(parse.sql(), spectrumSession())) { + write(backendOut, new byte[]{'H', 0, 0, 0, 4}); + SpectrumInterceptor.Plan[] resolved = new SpectrumInterceptor.Plan[1]; + boolean owned = runWithBackendOwned(() -> { + resolved[0] = spectrumInterceptor.plan(parse.sql(), spectrumSession(), relationalBackend); + return true; + }); + if (!owned) { + // Forwarding would let PostgreSQL drop the stub and leave its binding behind. + throw new SpectrumReadException("58030", "Unable to prepare external function DDL"); + } + plan = resolved[0]; + } else { + plan = spectrumInterceptor.plan(parse.sql(), spectrumSession()); + } if (plan instanceof SpectrumInterceptor.Plan.Ddl || plan instanceof SpectrumInterceptor.Plan.Query || plan instanceof SpectrumInterceptor.Plan.ExternalDdl) { awaitPriorBackendResponses(); diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/BackendSql.java b/src/main/java/io/floci/aws/services/redshift/spectrum/BackendSql.java index 730cc902ca..66819bd40c 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/BackendSql.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/BackendSql.java @@ -1,6 +1,7 @@ package io.floci.aws.services.redshift.spectrum; import java.io.InputStream; +import java.util.Optional; public interface BackendSql { default boolean permitsCachePublication() { @@ -15,6 +16,14 @@ public interface BackendSql { return null; } + /** + * Runs a query that yields at most one text value: the first column of the first row, or empty when there is no + * row or the value is SQL NULL. + */ + default Optional queryString(String sql) { + return Optional.empty(); + } + void execute(String sql); long copyIn(String copySql, InputStream data); } diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalFunctionRegistry.java b/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalFunctionRegistry.java index b820d9dc47..52ab132375 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalFunctionRegistry.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalFunctionRegistry.java @@ -27,6 +27,12 @@ public class ExternalFunctionRegistry extends SchemaBindingRegistry argumentTypes) { + return list(session.accountId(), session.clusterKey(), session.databaseName()).stream() + .anyMatch(binding -> binding.functionName().equals(functionName) + && binding.argumentTypes().equals(argumentTypes)); + } + public void unbindFunction(ExternalFunctionBinding binding) { unbind(binding.accountId(), binding.clusterKey(), binding.databaseName(), binding.bindingName()); } diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSession.java b/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSession.java index e975dbb993..c1ed92634a 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSession.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSession.java @@ -7,6 +7,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.nio.charset.StandardCharsets; +import java.util.Optional; public final class PostgresBackendSession implements BackendSql { private static final String SQLSTATE_IO = "58030"; @@ -21,6 +22,32 @@ public final class PostgresBackendSession implements BackendSql { return backend; } + @Override + public Optional queryString(String sql) { + try { + OutputStream output = backend.getOutputStream(); + output.write(PostgresWireDecoder.encodeQuery(sql)); + output.flush(); + return awaitSingleString(new PostgresWireDecoder(backend.getInputStream())); + } catch (IOException exception) { + abandon(backend, exception); + throw new SpectrumReadException(SQLSTATE_IO, "Unable to run a statement on the Redshift backend", exception); + } + } + + /** + * Closes a backend whose private exchange did not finish. Its replies may still arrive, and the response pump + * would forward them to the client as if the client had asked; a closed connection is the one state where + * nothing can be misattributed. + */ + static void abandon(Socket backend, IOException cause) { + try { + backend.close(); + } catch (IOException closeFailure) { + cause.addSuppressed(closeFailure); + } + } + @Override public void execute(String sql) { try { @@ -126,6 +153,44 @@ public final class PostgresBackendSession implements BackendSql { throw new IOException("PostgreSQL closed before ReadyForQuery"); } + private static Optional awaitSingleString(PostgresWireDecoder decoder) throws IOException { + SpectrumReadException failure = null; + String value = null; + boolean seenRow = false; + PostgresWireDecoder.FrontendMessage message = decoder.nextMessage(); + while (message != null) { + if (message.type() == 'D' && !seenRow) { + seenRow = true; + value = firstColumn(message.body()); + } else if (message.type() == 'E') { + failure = toException(message.body()); + } else if (message.type() == 'Z') { + if (failure != null) { + throw failure; + } + return Optional.ofNullable(value); + } + message = decoder.nextMessage(); + } + throw new IOException("PostgreSQL closed before ReadyForQuery"); + } + + static String firstColumn(byte[] body) { + if (body == null || body.length < 6) { + return null; + } + int columns = ((body[0] & 0xff) << 8) | (body[1] & 0xff); + if (columns < 1) { + return null; + } + int length = ((body[2] & 0xff) << 24) | ((body[3] & 0xff) << 16) + | ((body[4] & 0xff) << 8) | (body[5] & 0xff); + if (length < 0 || body.length < 6 + length) { + return null; + } + return new String(body, 6, length, StandardCharsets.UTF_8); + } + private static long rowCount(String tag) { int space = tag.lastIndexOf(' '); if (space < 0) { diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresExtendedBackendSession.java b/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresExtendedBackendSession.java index f410f16ea5..0c63d91016 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresExtendedBackendSession.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/PostgresExtendedBackendSession.java @@ -7,6 +7,7 @@ import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.nio.charset.StandardCharsets; +import java.util.Optional; import java.util.UUID; /** Runs preparation without ending the client's transaction or destroying its portals. */ @@ -38,6 +39,18 @@ public final class PostgresExtendedBackendSession implements BackendSql { failedUntilSync = false; } + @Override + public Optional queryString(String sql) { + try { + start(sql); + closeAndFlush(); + return awaitSingleStringClosed(); + } catch (IOException exception) { + PostgresBackendSession.abandon(backend, exception); + throw failure(exception); + } + } + @Override public void execute(String sql) { try { @@ -136,6 +149,21 @@ public final class PostgresExtendedBackendSession implements BackendSql { return tag; } + private Optional awaitSingleStringClosed() throws IOException { + String value = null; + boolean seenRow = false; + for (int closed = 0; closed < 2;) { + Response response = read(); + if (response.type() == 'D' && !seenRow) { + seenRow = true; + value = PostgresBackendSession.firstColumn(response.body()); + } else if (response.type() == '3') { + closed++; + } + } + return Optional.ofNullable(value); + } + private void readUntil(char type) throws IOException { Response response; do { diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumInterceptor.java b/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumInterceptor.java index 0accb6c457..55060382da 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumInterceptor.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumInterceptor.java @@ -45,7 +45,11 @@ public final class SpectrumInterceptor { } public Plan plan(String sql, SpectrumSession session) { - if (preparation != null && preparation.handlesDdl(sql, session)) { + return plan(sql, session, null); + } + + public Plan plan(String sql, SpectrumSession session, BackendSql backend) { + if (preparation != null && preparation.handlesDdl(sql, session, backend)) { return new Plan.ExternalDdl(sql, session); } if (preparation != null && preparation.referencesExternal(sql, session)) { @@ -55,9 +59,10 @@ public final class SpectrumInterceptor { } public Decision intercept(String sql, SpectrumSession session, Socket backend) { - Plan plan = plan(sql, session); + PostgresBackendSession backendSql = new PostgresBackendSession(backend); + Plan plan = plan(sql, session, backendSql); if (plan instanceof Plan.Forward && preparation != null) { - preparation.prepare(sql, session, new PostgresBackendSession(backend)); + preparation.prepare(sql, session, backendSql); } return execute(plan, session.accountId(), session.databaseName(), backend); } diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java b/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java index be7cdd549b..b6b82cbda9 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/SpectrumQueryPreparation.java @@ -33,8 +33,10 @@ public class SpectrumQueryPreparation { private static final Logger LOG = Logger.getLogger(SpectrumQueryPreparation.class); private static final String DUPLICATE_SCHEMA = "42P06"; private static final String UNDEFINED_FUNCTION = "42883"; - /** Where an unqualified function lands: the default search path of a Redshift database resolves to it. */ + private static final String INVALID_SCHEMA_NAME = "3F000"; + /** Fallback when checking an unqualified DROP FUNCTION without a live backend session. */ private static final String DEFAULT_FUNCTION_SCHEMA = "public"; + static final String CURRENT_SCHEMA_SQL = "SELECT pg_catalog.current_schema()"; private static final Pattern JOIN = Pattern.compile("\\bJOIN\\b", Pattern.CASE_INSENSITIVE); // Each batch is inserted on its own, so a view that groups or aggregates would keep a partial row per batch. private static final Pattern AGGREGATE = Pattern.compile( @@ -175,16 +177,24 @@ public class SpectrumQueryPreparation { externalSchemaNames(schemas, kinesisSchemaNames, mskSchemaNames)).isPresent(); } + public boolean needsBackendForDdl(String sql, SpectrumSession session) { + return parser.parse(sql).orElse(null) instanceof ExternalStatement.DropFunction function + && function.schemaName() == null + && functions.hasFunctionNamed(session, function.functionName(), function.argumentTypes()); + } + public boolean handlesDdl(String sql, SpectrumSession session) { + return handlesDdl(sql, session, null); + } + + public boolean handlesDdl(String sql, SpectrumSession session, BackendSql backend) { ExternalStatement statement = parser.parse(sql).orElse(null); return switch (statement) { case ExternalStatement.CreateSchema ignored -> true; case ExternalStatement.CreateKinesisSchema ignored -> true; case ExternalStatement.CreateMskSchema ignored -> true; case ExternalStatement.CreateFunction ignored -> true; - case ExternalStatement.DropFunction function -> functions.findFunction(session, - schemaOrDefault(function.schemaName()), function.functionName(), - function.argumentTypes()).isPresent(); + case ExternalStatement.DropFunction function -> findFunctionToDrop(function, session, backend).isPresent(); case ExternalStatement.CreateTable table -> session.inTransaction() || bindingsOf(registry, session).containsKey(table.schemaName()) || bindingsOf(kinesisSchemas, session).containsKey(table.schemaName()) @@ -556,7 +566,7 @@ public class SpectrumQueryPreparation { private boolean createFunction(ExternalStatement.CreateFunction function, SpectrumSession session, BackendSql backend) { rejectTransaction(session); - String schema = schemaOrDefault(function.schemaName()); + String schema = function.schemaName() != null ? function.schemaName() : currentSchema(backend); ExternalFunctionBinding binding = new ExternalFunctionBinding(session.accountId(), session.clusterKey(), session.databaseName(), schema, function.functionName(), function.argumentTypes(), function.returnType(), function.volatility(), function.lambdaFunction(), function.iamRoleArn(), @@ -583,13 +593,12 @@ public class SpectrumQueryPreparation { } private boolean dropFunction(ExternalStatement.DropFunction function, SpectrumSession session, BackendSql backend) { - rejectTransaction(session); - String schema = schemaOrDefault(function.schemaName()); - Optional binding = functions.findFunction(session, schema, function.functionName(), - function.argumentTypes()); + Optional binding = findFunctionToDrop(function, session, backend); if (binding.isEmpty()) { return false; } + rejectTransaction(session); + String schema = binding.get().schemaName(); try { backend.execute(dropStubSql(schema, function.functionName(), function.argumentTypes(), function.ifExists(), function.cascade())); @@ -604,8 +613,46 @@ public class SpectrumQueryPreparation { return true; } - private static String schemaOrDefault(String schemaName) { - return schemaName == null ? DEFAULT_FUNCTION_SCHEMA : schemaName; + private Optional findFunctionToDrop(ExternalStatement.DropFunction function, + SpectrumSession session, BackendSql backend) { + if (function.schemaName() != null) { + return functions.findFunction(session, function.schemaName(), function.functionName(), + function.argumentTypes()); + } + if (!functions.hasFunctionNamed(session, function.functionName(), function.argumentTypes())) { + return Optional.empty(); + } + if (backend == null) { + return functions.findFunction(session, DEFAULT_FUNCTION_SCHEMA, function.functionName(), + function.argumentTypes()); + } + Optional resolved = backend.queryString(resolveFunctionSchemaSql( + function.functionName(), function.argumentTypes())); + if (resolved.isPresent()) { + return functions.findFunction(session, resolved.get(), function.functionName(), function.argumentTypes()); + } + // The stub may already be gone; check the current schema so a stale binding is cleared when DROP fails (42883). + return currentSchemaOf(backend) + .flatMap(schema -> functions.findFunction(session, schema, function.functionName(), + function.argumentTypes())); + } + + private static String currentSchema(BackendSql backend) { + return currentSchemaOf(backend).orElseThrow(() -> new SpectrumSqlException(INVALID_SCHEMA_NAME, + "no schema has been selected to create in")); + } + + /** The session's current schema, empty when the search_path selects none. */ + private static Optional currentSchemaOf(BackendSql backend) { + return backend.queryString(CURRENT_SCHEMA_SQL).filter(schema -> !schema.isEmpty()); + } + + static String resolveFunctionSchemaSql(String functionName, List argumentTypes) { + String signature = ExternalTableMaterializer.quote(functionName) + + "(" + String.join(", ", argumentTypes) + ")"; + return "SELECT n.nspname FROM pg_catalog.pg_proc p " + + "JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace " + + "WHERE p.oid = pg_catalog.to_regprocedure(" + PostgresWire.quoteLiteral(signature) + ")"; } private static String stubSql(ExternalStatement.CreateFunction function, String schema, boolean replace) { diff --git a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataBackendSql.java b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataBackendSql.java index be312c056f..3e652ec45d 100644 --- a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataBackendSql.java +++ b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataBackendSql.java @@ -7,8 +7,10 @@ import org.postgresql.PGConnection; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; +import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.util.Optional; final class RedshiftDataBackendSql implements BackendSql { private final Connection connection; @@ -23,6 +25,24 @@ final class RedshiftDataBackendSql implements BackendSql { this.execution = execution; } + @Override + public Optional queryString(String sql) { + try (Statement statement = connection.createStatement()) { + if (execution != null) { + execution.track(statement); + } + try (ResultSet rows = statement.executeQuery(sql)) { + return rows.next() ? Optional.ofNullable(rows.getString(1)) : Optional.empty(); + } finally { + if (execution != null) { + execution.untrack(statement); + } + } + } catch (SQLException exception) { + throw failure(exception); + } + } + @Override public void execute(String sql) { try (Statement statement = connection.createStatement()) { diff --git a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataService.java b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataService.java index d601962fa1..fe2dc54cec 100644 --- a/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataService.java +++ b/src/main/java/io/floci/aws/services/redshiftdata/RedshiftDataService.java @@ -548,7 +548,10 @@ public class RedshiftDataService implements Resettable, StoredResourceArns { } boolean autoCommit = AUTO_COMMIT_SQL.matcher(sql).find() || CopyJobSql.requiresAutoCommit(sql) || preparation != null && target.spectrum() != null - && preparation.handlesDdl(sql, target.spectrum()); + && (preparation.needsBackendForDdl(sql, target.spectrum()) + ? preparation.handlesDdl(sql, target.spectrum(), + new RedshiftDataBackendSql(connection, execution)) + : preparation.handlesDdl(sql, target.spectrum())); if (autoCommit) { if (session != null && session.inTransaction()) { throw new SQLException("Statement cannot run inside a transaction block", "25001"); diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftExternalFunctionIntegrationTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftExternalFunctionIntegrationTest.java index 125102c17a..a7bf83bf84 100644 --- a/src/test/java/io/floci/aws/services/redshift/RedshiftExternalFunctionIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftExternalFunctionIntegrationTest.java @@ -57,8 +57,12 @@ class RedshiftExternalFunctionIntegrationTest { } private static int stubCount(Statement statement, String name) throws SQLException { + return stubCount(statement, "public", name); + } + + private static int stubCount(Statement statement, String schema, String name) throws SQLException { try (ResultSet rows = statement.executeQuery("SELECT count(*) FROM pg_proc p JOIN pg_namespace n " - + "ON n.oid = p.pronamespace WHERE n.nspname = 'public' AND p.proname = '" + name + "'")) { + + "ON n.oid = p.pronamespace WHERE n.nspname = '" + schema + "' AND p.proname = '" + name + "'")) { rows.next(); return rows.getInt(1); } @@ -127,4 +131,43 @@ class RedshiftExternalFunctionIntegrationTest { assertEquals(0, stubCount(statement, "exfunc_tx")); } } + + @Test + @Timeout(120) + void createsCallsAndDropsUnqualifiedFunctionInSessionSearchPath() throws Exception { + clusterId = "it-fn-" + UUID.randomUUID().toString().substring(0, 8); + Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123"); + try (Connection connection = waitForConnection(cluster, "admin", "Secret123"); + Statement statement = connection.createStatement()) { + statement.execute("CREATE SCHEMA analytics"); + statement.execute("CREATE SCHEMA other"); + statement.execute("SET search_path TO analytics"); + + statement.execute(create("exfunc_sum", "INT, INT", "lambda_sum")); + + assertTrue(bound("analytics", "exfunc_sum", List.of("integer", "integer"))); + assertFalse(bound("public", "exfunc_sum", List.of("integer", "integer"))); + assertEquals(1, stubCount(statement, "analytics", "exfunc_sum")); + assertEquals(0, stubCount(statement, "public", "exfunc_sum")); + + SQLException qualifiedCall = assertThrows(SQLException.class, + () -> statement.executeQuery("SELECT analytics.exfunc_sum(1, 2)")); + assertEquals("0A000", qualifiedCall.getSQLState()); + + statement.execute("DROP FUNCTION analytics.exfunc_sum(INT, INT)"); + assertFalse(bound("analytics", "exfunc_sum", List.of("integer", "integer"))); + assertEquals(0, stubCount(statement, "analytics", "exfunc_sum")); + + statement.execute(create("exfunc_sum", "INT, INT", "lambda_sum")); + statement.execute("SET search_path TO other, analytics"); + statement.execute("DROP FUNCTION exfunc_sum(INT, INT)"); + assertFalse(bound("analytics", "exfunc_sum", List.of("integer", "integer"))); + assertEquals(0, stubCount(statement, "analytics", "exfunc_sum")); + + statement.execute("SET search_path TO nonexistent_schema"); + SQLException noSchema = assertThrows(SQLException.class, + () -> statement.execute(create("exfunc_none", "INT", "lambda_none"))); + assertEquals("3F000", noSchema.getSQLState()); + } + } } diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/FakeCopyBackend.java b/src/test/java/io/floci/aws/services/redshift/proxy/FakeCopyBackend.java index 57ebcabc7d..aafea07561 100644 --- a/src/test/java/io/floci/aws/services/redshift/proxy/FakeCopyBackend.java +++ b/src/test/java/io/floci/aws/services/redshift/proxy/FakeCopyBackend.java @@ -14,6 +14,8 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.function.ToLongFunction; +import static io.floci.aws.testing.PostgresDataRows.dataRow; + /** Extended-query backend for COPY tests, including catalog discovery and transaction recovery. */ final class FakeCopyBackend { private final Socket socket; @@ -208,19 +210,4 @@ final class FakeCopyBackend { new byte[]{'W'}, PostgresWire.cStringBytes("COPY events, line " + line + ", column id: \"bad\""), new byte[1]); } - - private static byte[] dataRow(List row) throws Exception { - ByteArrayOutputStream bytes = new ByteArrayOutputStream(); - bytes.write(new byte[]{(byte) (row.size() >> 8), (byte) row.size()}); - for (String value : row) { - if (value == null) { - bytes.write(PostgresWire.int32(-1)); - continue; - } - byte[] field = value.getBytes(StandardCharsets.UTF_8); - bytes.write(PostgresWire.int32(field.length)); - bytes.write(field); - } - return bytes.toByteArray(); - } } diff --git a/src/test/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridgeTest.java b/src/test/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridgeTest.java index 61b51fcfa3..4ab27461db 100644 --- a/src/test/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridgeTest.java +++ b/src/test/java/io/floci/aws/services/redshift/proxy/RedshiftInterceptingBridgeTest.java @@ -2,6 +2,7 @@ package io.floci.aws.services.redshift.proxy; import io.floci.aws.services.iam.IamService; import io.floci.aws.services.redshift.RedshiftAuditLogPublisher; +import io.floci.aws.services.redshift.spectrum.BackendSql; import io.floci.aws.services.redshift.spectrum.SpectrumInterceptor; import io.floci.aws.services.redshift.spectrum.SpectrumQueryPreparation; import io.floci.aws.services.redshift.spectrum.SpectrumSession; @@ -26,7 +27,10 @@ import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.ReentrantLock; import static io.floci.aws.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertArrayEquals; @@ -72,6 +76,15 @@ class RedshiftInterceptingBridgeTest { } private void startBridge(SpectrumInterceptor spectrumInterceptor, RedshiftAuditLogPublisher audit) throws IOException { + openSockets(); + s3Stub = Mockito.mock(S3Service.class); + RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge( + bridgeClientEnd, bridgeBackendEnd, s3Stub, Mockito.mock(IamService.class), "000000000000", List.of(), + spectrumInterceptor, "000000000000:c", "dev", null, audit, "analyst", null); + bridgeThread = Thread.ofVirtual().name("bridge-under-test").start(bridge::run); + } + + private void openSockets() throws IOException { clientListener = new ServerSocket(0); testClientEnd = new Socket("localhost", clientListener.getLocalPort()); bridgeClientEnd = clientListener.accept(); @@ -79,12 +92,6 @@ class RedshiftInterceptingBridgeTest { backendListener = new ServerSocket(0); bridgeBackendEnd = new Socket("localhost", backendListener.getLocalPort()); testBackendEnd = backendListener.accept(); - - s3Stub = Mockito.mock(S3Service.class); - RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge( - bridgeClientEnd, bridgeBackendEnd, s3Stub, Mockito.mock(IamService.class), "000000000000", List.of(), - spectrumInterceptor, "000000000000:c", "dev", null, audit, "analyst", null); - bridgeThread = Thread.ofVirtual().name("bridge-under-test").start(bridge::run); } @Test @@ -669,6 +676,59 @@ class RedshiftInterceptingBridgeTest { Mockito.verify(interceptor, Mockito.never()).execute(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.any()); } + @Test + @Timeout(20) + void aRegisteredDropFunctionIsRefusedNotForwardedWhenTheBackendStaysBusy() throws Exception { + String sql = "DROP FUNCTION exfunc_sum(INT)"; + SpectrumInterceptor interceptor = inlineMock(SpectrumInterceptor.class); + SpectrumQueryPreparation preparation = Mockito.mock(SpectrumQueryPreparation.class); + Mockito.when(interceptor.preparation()).thenReturn(preparation); + Mockito.when(preparation.needsBackendForDdl(Mockito.eq(sql), Mockito.any())).thenReturn(true); + openSockets(); + // a held backend lock stands in for a busy backend; the short budget keeps the test from waiting out 2 s + ReentrantLock backendLock = new ReentrantLock(true); + RedshiftInterceptingBridge bridge = new RedshiftInterceptingBridge( + bridgeClientEnd, bridgeBackendEnd, interceptor, backendLock, 100); + CountDownLatch held = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + Thread holder = Thread.ofVirtual().start(() -> { + backendLock.lock(); + try { + held.countDown(); + release.await(); + } catch (InterruptedException expected) { + // Only an interrupt from outside the test ends the wait early; keep its status. + Thread.currentThread().interrupt(); + } finally { + backendLock.unlock(); + } + }); + assertTrue(held.await(1, TimeUnit.SECONDS)); + bridgeThread = Thread.ofVirtual().name("bridge-under-test").start(bridge::run); + PostgresWireDecoder backendIn = new PostgresWireDecoder(testBackendEnd.getInputStream()); + PostgresWireDecoder.ParseMessage parse = new PostgresWireDecoder.ParseMessage("drop", sql, List.of()); + testClientEnd.getOutputStream().write(PostgresWireDecoder.encodeParse(parse, sql)); + testClientEnd.getOutputStream().flush(); + + // the flush the bridge sends to look for the backend's replies is all that reaches it + assertEquals('H', backendIn.nextMessage().type()); + + InputStream response = testClientEnd.getInputStream(); + assertEquals('E', response.read()); + int length = ByteBuffer.wrap(response.readNBytes(4)).getInt(); + String error = new String(response.readNBytes(length - 4), StandardCharsets.UTF_8); + + release.countDown(); + holder.join(1000); + assertTrue(error.contains("58030"), error); + assertTrue(error.contains("Unable to prepare external function DDL"), error); + Mockito.verify(interceptor, Mockito.never()).plan(Mockito.anyString(), Mockito.any(SpectrumSession.class), + Mockito.any(BackendSql.class)); + // the Parse itself never reaches the backend, so PostgreSQL cannot drop the stub behind the registry + testBackendEnd.setSoTimeout(500); + assertThrows(SocketTimeoutException.class, backendIn::nextMessage); + } + private static void skipFrameBody(InputStream in) throws IOException { int length = ByteBuffer.wrap(in.readNBytes(4)).getInt(); in.readNBytes(length - 4); diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSessionTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSessionTest.java index 1fcb75710a..a2e429ed81 100644 --- a/src/test/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSessionTest.java +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/PostgresBackendSessionTest.java @@ -9,13 +9,18 @@ import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.List; +import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; +import static io.floci.aws.testing.PostgresDataRows.dataRow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; class PostgresBackendSessionTest { @@ -269,4 +274,123 @@ class PostgresBackendSessionTest { assertEquals("25P02", error.sqlState()); session.onSync(); } + + @Test + void queryStringReadsFirstColumnOfFirstRowAndHandlesNullAndEmpty() throws Exception { + try (ServerSocket listener = new ServerSocket(0); + Socket backend = new Socket("localhost", listener.getLocalPort())) { + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future server = executor.submit(() -> { + try (Socket socket = listener.accept()) { + InputStream input = socket.getInputStream(); + OutputStream output = socket.getOutputStream(); + // First query returns "analytics". + readFrame(input); + send(output, 'D', dataRow(List.of("analytics"))); + send(output, 'C', "SELECT 1\0".getBytes(StandardCharsets.UTF_8)); + send(output, 'Z', new byte[]{'I'}); + // Second query returns SQL NULL. + readFrame(input); + send(output, 'D', dataRow(Collections.singletonList(null))); + send(output, 'C', "SELECT 1\0".getBytes(StandardCharsets.UTF_8)); + send(output, 'Z', new byte[]{'I'}); + // Third query returns no rows. + readFrame(input); + send(output, 'C', "SELECT 0\0".getBytes(StandardCharsets.UTF_8)); + send(output, 'Z', new byte[]{'I'}); + return null; + } + }); + PostgresBackendSession session = new PostgresBackendSession(backend); + assertEquals(Optional.of("analytics"), session.queryString("SELECT pg_catalog.current_schema()")); + assertEquals(Optional.empty(), session.queryString("SELECT pg_catalog.current_schema()")); + assertEquals(Optional.empty(), session.queryString("SELECT n.nspname FROM pg_proc WHERE false")); + server.get(); + executor.shutdownNow(); + } + } + + @Test + void extendedQueryStringReadsFirstColumnWithoutSync() throws Exception { + try (ServerSocket listener = new ServerSocket(0); + Socket backend = new Socket("localhost", listener.getLocalPort())) { + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future messages = executor.submit(() -> { + try (Socket socket = listener.accept()) { + StringBuilder types = new StringBuilder(); + Frame frame; + do { + frame = readFrame(socket.getInputStream()); + types.append(frame.type()); + } while (frame.type() != 'H'); + send(socket.getOutputStream(), '1', new byte[0]); + send(socket.getOutputStream(), '2', new byte[0]); + send(socket.getOutputStream(), 'D', dataRow(List.of("analytics"))); + send(socket.getOutputStream(), 'C', "SELECT 1\0".getBytes(StandardCharsets.UTF_8)); + send(socket.getOutputStream(), '3', new byte[0]); + send(socket.getOutputStream(), '3', new byte[0]); + return types.toString(); + } + }); + Optional schema = new PostgresExtendedBackendSession(backend) + .queryString("SELECT pg_catalog.current_schema()"); + assertEquals(Optional.of("analytics"), schema); + assertEquals("PBECCH", messages.get()); + executor.shutdownNow(); + } + } + + @Test + void aSimpleLookupThatTimesOutClosesTheBackendSoLateRepliesCannotReachTheClient() throws Exception { + try (ServerSocket listener = new ServerSocket(0); + Socket backend = new Socket("localhost", listener.getLocalPort())) { + backend.setSoTimeout(200); + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future server = executor.submit(() -> { + try (Socket socket = listener.accept()) { + readFrame(socket.getInputStream()); + // never replies: the lookup times out while its answer is still to come + assertEquals(-1, socket.getInputStream().read()); + return null; + } + }); + + SpectrumReadException error = assertThrows(SpectrumReadException.class, + () -> new PostgresBackendSession(backend).queryString("SELECT pg_catalog.current_schema()")); + + assertEquals("58030", error.sqlState()); + assertTrue(backend.isClosed()); + server.get(); + executor.shutdownNow(); + } + } + + @Test + void anExtendedLookupThatTimesOutClosesTheBackendSoLateRepliesCannotReachTheClient() throws Exception { + try (ServerSocket listener = new ServerSocket(0); + Socket backend = new Socket("localhost", listener.getLocalPort())) { + backend.setSoTimeout(200); + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future server = executor.submit(() -> { + try (Socket socket = listener.accept()) { + Frame frame; + do { + frame = readFrame(socket.getInputStream()); + } while (frame.type() != 'H'); + // ParseComplete only: the rest of the exchange is still to come when the lookup gives up + send(socket.getOutputStream(), '1', new byte[0]); + assertEquals(-1, socket.getInputStream().read()); + return null; + } + }); + + SpectrumReadException error = assertThrows(SpectrumReadException.class, + () -> new PostgresExtendedBackendSession(backend).queryString("SELECT pg_catalog.current_schema()")); + + assertEquals("58030", error.sqlState()); + assertTrue(backend.isClosed()); + server.get(); + executor.shutdownNow(); + } + } } diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumExternalFunctionPreparationTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumExternalFunctionPreparationTest.java index ee72beaca3..6fa3fa64a6 100644 --- a/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumExternalFunctionPreparationTest.java +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumExternalFunctionPreparationTest.java @@ -20,6 +20,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; class SpectrumExternalFunctionPreparationTest { private static final String ACCOUNT = "000000000000"; @@ -36,6 +37,7 @@ class SpectrumExternalFunctionPreparationTest { void setUp() { functions = new ExternalFunctionRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)); backend = mock(BackendSql.class); + when(backend.queryString(SpectrumQueryPreparation.CURRENT_SCHEMA_SQL)).thenReturn(Optional.of("public")); GlueService glue = mock(GlueService.class); KinesisStreamingViews views = new KinesisStreamingViews( new KinesisViewRegistry(AccountAwareStorageBackend.inMemory(ACCOUNT)), @@ -231,4 +233,68 @@ class SpectrumExternalFunctionPreparationTest { verify(backend).execute(argThat(sql -> sql.contains("public.exfunc_sum") && sql.contains("invoking Lambda from SQL is not supported yet"))); } + + @Test + void createsUnqualifiedFunctionInTheCurrentSchemaReportedByTheBackend() { + when(backend.queryString(SpectrumQueryPreparation.CURRENT_SCHEMA_SQL)).thenReturn(Optional.of("analytics")); + + assertThat(preparation.prepare(CREATE, SESSION, backend), equalTo(true)); + + verify(backend).execute(argThat(sql -> sql.startsWith("CREATE FUNCTION \"analytics\".\"exfunc_sum\"(integer, integer) ") + && sql.contains("External function analytics.exfunc_sum"))); + assertThat(bound("analytics", "exfunc_sum", List.of("integer", "integer")).isPresent(), equalTo(true)); + assertThat(bound("public", "exfunc_sum", List.of("integer", "integer")).isPresent(), equalTo(false)); + } + + @Test + void refusesUnqualifiedCreateWhenNoSchemaIsSelected() { + when(backend.queryString(SpectrumQueryPreparation.CURRENT_SCHEMA_SQL)).thenReturn(Optional.empty()); + + SpectrumSqlException error = assertThrows(SpectrumSqlException.class, + () -> preparation.prepare(CREATE, SESSION, backend)); + + assertThat(error.sqlState(), equalTo("3F000")); + verify(backend, never()).execute(argThat(sql -> sql.startsWith("CREATE FUNCTION"))); + } + + @Test + void qualifiedCreateDoesNotAskTheBackendForCurrentSchema() { + preparation.prepare("CREATE EXTERNAL FUNCTION \"Sales\".f_now() RETURNS VARCHAR(8) STABLE " + + "LAMBDA 'now' IAM_ROLE '" + ROLE + "'", SESSION, backend); + + verify(backend, never()).queryString(SpectrumQueryPreparation.CURRENT_SCHEMA_SQL); + } + + @Test + void unqualifiedDropResolvesFunctionAlongSearchPath() { + when(backend.queryString(SpectrumQueryPreparation.CURRENT_SCHEMA_SQL)).thenReturn(Optional.of("analytics")); + preparation.prepare(CREATE, SESSION, backend); + + String resolveSql = SpectrumQueryPreparation.resolveFunctionSchemaSql("exfunc_sum", List.of("integer", "integer")); + when(backend.queryString(SpectrumQueryPreparation.CURRENT_SCHEMA_SQL)).thenReturn(Optional.of("other")); + when(backend.queryString(resolveSql)).thenReturn(Optional.of("analytics")); + + String drop = "DROP FUNCTION exfunc_sum(INT, INT)"; + assertThat(preparation.needsBackendForDdl(drop, SESSION), equalTo(true)); + assertThat(preparation.handlesDdl(drop, SESSION, backend), equalTo(true)); + assertThat(preparation.prepare(drop, SESSION, backend), equalTo(true)); + + verify(backend).execute("DROP FUNCTION \"analytics\".\"exfunc_sum\"(integer, integer) RESTRICT"); + assertThat(bound("analytics", "exfunc_sum", List.of("integer", "integer")).isPresent(), equalTo(false)); + } + + @Test + void unqualifiedDropLeavesOrdinaryFunctionInEarlierSearchPathSchemaToBackend() { + preparation.prepare(CREATE, SESSION, backend); + + String resolveSql = SpectrumQueryPreparation.resolveFunctionSchemaSql("exfunc_sum", List.of("integer", "integer")); + when(backend.queryString(resolveSql)).thenReturn(Optional.of("analytics")); + + String drop = "DROP FUNCTION exfunc_sum(INT, INT)"; + assertThat(preparation.handlesDdl(drop, SESSION, backend), equalTo(false)); + assertThat(preparation.prepare(drop, SESSION, backend), equalTo(false)); + + verify(backend, never()).execute(argThat(sql -> sql.startsWith("DROP FUNCTION"))); + assertThat(bound("public", "exfunc_sum", List.of("integer", "integer")).isPresent(), equalTo(true)); + } } diff --git a/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataBackendSqlTest.java b/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataBackendSqlTest.java index a8cafeb7a5..f31302905f 100644 --- a/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataBackendSqlTest.java +++ b/src/test/java/io/floci/aws/services/redshiftdata/RedshiftDataBackendSqlTest.java @@ -8,8 +8,10 @@ import org.postgresql.copy.CopyManager; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.sql.Connection; +import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.util.Optional; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; @@ -44,4 +46,20 @@ class RedshiftDataBackendSqlTest { () -> new RedshiftDataBackendSql(connection).execute("SELECT 1")); assertEquals("42501", error.sqlState()); } + + @Test + void queryStringReadsFirstColumnAndHandlesNullOrNoRows() throws Exception { + Connection connection = mock(Connection.class); + Statement statement = mock(Statement.class); + ResultSet rows = mock(ResultSet.class); + when(connection.createStatement()).thenReturn(statement); + when(statement.executeQuery("SELECT pg_catalog.current_schema()")).thenReturn(rows); + when(rows.next()).thenReturn(true, true, false); + when(rows.getString(1)).thenReturn("analytics", (String) null); + + RedshiftDataBackendSql backend = new RedshiftDataBackendSql(connection); + assertEquals(Optional.of("analytics"), backend.queryString("SELECT pg_catalog.current_schema()")); + assertEquals(Optional.empty(), backend.queryString("SELECT pg_catalog.current_schema()")); + assertEquals(Optional.empty(), backend.queryString("SELECT pg_catalog.current_schema()")); + } } diff --git a/src/test/java/io/floci/aws/testing/PostgresDataRows.java b/src/test/java/io/floci/aws/testing/PostgresDataRows.java new file mode 100644 index 0000000000..5d2c6fc9b4 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/PostgresDataRows.java @@ -0,0 +1,37 @@ +package io.floci.aws.testing; + +import io.floci.aws.core.common.PostgresWire; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.List; + +/** Builds the body of a PostgreSQL {@code DataRow} message for tests that fake a backend. */ +public final class PostgresDataRows { + + private PostgresDataRows() { + } + + /** One text column per value; a null value is an SQL NULL. */ + public static byte[] dataRow(List row) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try { + bytes.write(new byte[]{(byte) (row.size() >> 8), (byte) row.size()}); + for (String value : row) { + if (value == null) { + bytes.write(PostgresWire.int32(-1)); + continue; + } + byte[] field = value.getBytes(StandardCharsets.UTF_8); + bytes.write(PostgresWire.int32(field.length)); + bytes.write(field); + } + } catch (IOException e) { + // a ByteArrayOutputStream does not fail, so this cannot happen + throw new UncheckedIOException(e); + } + return bytes.toByteArray(); + } +}