fix(rds): check caller database permissions before retrying failed zero-ETL load (#9518)

Retrying a failed zero-ETL destination reloaded it through the admin connection without checking the caller, so a role that could not create the database still got it back. The retry now checks the caller's own privileges first: it goes ahead only for a superuser, or a role with CREATEDB that is a member of the database's owner, and otherwise refuses with PostgreSQL's own "permission denied to create database". The database name is quoted with PostgresWire.quoteLiteral. A nightly Docker check runs each condition against a real PostgreSQL 16, and both test classes share one fixture.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-11-27 11:55:27 -04:00
1 parent d6deccc5ba
commit 9fe75bf985
5 files changed
+301 -43

No files matched your search

+3
View File
@@ -58,6 +58,9 @@ if starts SsmSessionManagerDockerNightlyIntegrationTest; then
pull debian:bookworm-slim
pull postgres:17
fi
if starts RdsIntegrationRetryPermissionDockerNightlyIntegrationTest; then
pull postgres:16-alpine
fi
if starts Ec2PublishedConnectionNightlyIntegrationTest; then
ecr public.ecr.aws/docker/library/alpine:latest
pull alpine/socat
@@ -30,6 +30,7 @@ public class RdsIntegrationDatabases implements IntegrationDatabaseCreator {
private static final String UNDEFINED_OBJECT = "42704";
private static final String SYNTAX_ERROR = "42601";
private static final String INSUFFICIENT_PRIVILEGE = "42501";
private static final String INVALID_PARAMETER_VALUE = "22023";
private static final String DUPLICATE_DATABASE = "42P04";
private static final String NOT_IN_PREREQUISITE_STATE = "55000";
@@ -79,6 +80,7 @@ public class RdsIntegrationDatabases implements IntegrationDatabaseCreator {
.filter(error -> RdsIntegrationService.isErrorForSourceDatabase(error, sourceDatabase))
.toList();
if (reuseFailedDatabase) {
requireRetryPermission(statement.databaseName(), backend);
Integration syncing = runDestinationRegistration(
() -> integrations.addDestination(integration, statement.databaseName(), sourceDatabase, false));
String loadId = syncing.destinationFor(sourceDatabase)
@@ -123,6 +125,21 @@ public class RdsIntegrationDatabases implements IntegrationDatabaseCreator {
}
}
/**
* Checks that the calling session may create databases and owns the existing failed database (or is a superuser)
* before reusing it, since retrying skips {@code CREATE DATABASE} and loads tables using the target's admin
* connection.
*/
private static void requireRetryPermission(String databaseName, BackendSql backend) {
Optional<String> allowed = backend.queryString("SELECT 1 FROM pg_catalog.pg_roles r "
+ "JOIN pg_catalog.pg_database d ON d.datname = " + PostgresWire.quoteLiteral(databaseName) + " "
+ "WHERE r.rolname = current_user "
+ "AND (r.rolsuper OR (r.rolcreatedb AND pg_catalog.pg_has_role(r.oid, d.datdba, 'MEMBER')))");
if (allowed.isEmpty()) {
throw new SpectrumSqlException(INSUFFICIENT_PRIVILEGE, "permission denied to create database");
}
}
/**
* Whether a database was created from {@code sourceDatabase} before and has since been dropped on the target,
* so that it can be created and loaded again.
@@ -0,0 +1,74 @@
package io.floci.aws.services.rds.integration;
import io.floci.aws.services.rds.model.Integration;
import io.floci.aws.services.redshift.RedshiftService;
import io.floci.aws.services.redshift.spectrum.ExternalStatement;
import io.floci.aws.services.redshift.spectrum.SpectrumSession;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
import java.util.List;
import java.util.Optional;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/** Shared mocks, integration and statement helpers for {@link RdsIntegrationDatabases} tests. */
final class RdsIntegrationDatabasesFixture {
static final String ACCOUNT = "000000000000";
static final String INTEGRATION_ID = "4b2f2f9c-7d1e-4f55-9a77-1a2b3c4d5e6f";
final RdsIntegrationService integrations;
final RdsIntegrationLoader loader;
final RedshiftService redshiftService;
final RedshiftServerlessService serverless;
final RdsIntegrationDatabases databases;
final Integration integration;
RdsIntegrationDatabasesFixture() {
integrations = mock(RdsIntegrationService.class);
loader = mock(RdsIntegrationLoader.class);
redshiftService = mock(RedshiftService.class);
serverless = mock(RedshiftServerlessService.class);
databases = new RdsIntegrationDatabases(integrations, loader, redshiftService, serverless);
integration = new Integration();
integration.setIntegrationArn("arn:aws:rds:us-east-1:000000000000:integration:" + INTEGRATION_ID);
integration.setTargetArn("arn:aws:redshift:us-east-1:000000000000:cluster:orders-dw");
integration.setDataFilter("include: orders.*.*");
integration.setAccountId(ACCOUNT);
integration.setRegion("us-east-1");
when(integrations.findById(anyString())).thenReturn(Optional.empty());
when(integrations.findById(INTEGRATION_ID)).thenReturn(Optional.of(integration));
when(integrations.addDestination(any(), anyString(), anyString(), anyBoolean())).thenAnswer(invocation -> {
Integration updated = new Integration(integration);
updated.getDestinations().removeIf(d -> invocation.getArgument(2).equals(d.getSourceDatabase()));
updated.getDestinations().add(new Integration.Destination(invocation.getArgument(1),
invocation.getArgument(2), Integration.Destination.STATE_SYNCING, null, "load-1"));
return updated;
});
when(integrations.reserveDestination(any(), anyString(), anyString(), any(), any())).thenAnswer(invocation -> {
Integration updated = new Integration(integration);
updated.getDestinations().removeIf(d -> invocation.getArgument(2).equals(d.getSourceDatabase()));
updated.getDestinations().add(new Integration.Destination(invocation.getArgument(1),
invocation.getArgument(2), Integration.Destination.STATE_CREATING, null, "load-1"));
return updated;
});
when(integrations.startDestinationSync(any(), anyString(), any())).thenReturn(integration);
when(redshiftService.clusterRegion(ACCOUNT, "orders-dw")).thenReturn(Optional.of("us-east-1"));
}
static SpectrumSession session(String clusterIdentifier) {
return new SpectrumSession(ACCOUNT, ACCOUNT + ":" + clusterIdentifier, "dev", List.of(), false);
}
static ExternalStatement.CreateIntegrationDatabase statement(String sourceDatabase) {
return statement("orders_dw", sourceDatabase);
}
static ExternalStatement.CreateIntegrationDatabase statement(String databaseName, String sourceDatabase) {
return new ExternalStatement.CreateIntegrationDatabase(databaseName, INTEGRATION_ID, sourceDatabase);
}
}
@@ -5,7 +5,6 @@ import io.floci.aws.services.rds.model.Integration;
import io.floci.aws.services.redshift.RedshiftService;
import io.floci.aws.services.redshift.spectrum.BackendSql;
import io.floci.aws.services.redshift.spectrum.ExternalStatement;
import io.floci.aws.services.redshift.spectrum.SpectrumSession;
import io.floci.aws.services.redshift.spectrum.SpectrumSqlException;
import io.floci.aws.services.redshiftserverless.RedshiftServerlessService;
import org.junit.jupiter.api.BeforeEach;
@@ -16,6 +15,9 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static io.floci.aws.services.rds.integration.RdsIntegrationDatabasesFixture.ACCOUNT;
import static io.floci.aws.services.rds.integration.RdsIntegrationDatabasesFixture.session;
import static io.floci.aws.services.rds.integration.RdsIntegrationDatabasesFixture.statement;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;
@@ -26,7 +28,6 @@ import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -37,8 +38,6 @@ import static org.mockito.Mockito.when;
*/
class RdsIntegrationDatabasesTest {
private static final String ACCOUNT = "000000000000";
private static final String INTEGRATION_ID = "4b2f2f9c-7d1e-4f55-9a77-1a2b3c4d5e6f";
private static final String NAMESPACE_ARN = "arn:aws:redshift-serverless:us-east-1:000000000000:"
+ "namespace/1a2b3c4d-0000-0000-0000-000000000000";
@@ -52,44 +51,14 @@ class RdsIntegrationDatabasesTest {
@BeforeEach
void setUp() {
integrations = mock(RdsIntegrationService.class);
loader = mock(RdsIntegrationLoader.class);
redshiftService = mock(RedshiftService.class);
serverless = mock(RedshiftServerlessService.class);
databases = new RdsIntegrationDatabases(integrations, loader, redshiftService, serverless);
RdsIntegrationDatabasesFixture fixture = new RdsIntegrationDatabasesFixture();
integrations = fixture.integrations;
loader = fixture.loader;
redshiftService = fixture.redshiftService;
serverless = fixture.serverless;
databases = fixture.databases;
integration = fixture.integration;
backend = new RecordingBackend();
integration = new Integration();
integration.setIntegrationArn("arn:aws:rds:us-east-1:000000000000:integration:" + INTEGRATION_ID);
integration.setTargetArn("arn:aws:redshift:us-east-1:000000000000:cluster:orders-dw");
integration.setDataFilter("include: orders.*.*");
integration.setAccountId(ACCOUNT);
integration.setRegion("us-east-1");
when(integrations.findById(anyString())).thenReturn(Optional.empty());
when(integrations.findById(INTEGRATION_ID)).thenReturn(Optional.of(integration));
when(integrations.addDestination(any(), anyString(), anyString(), anyBoolean())).thenAnswer(invocation -> {
Integration updated = new Integration(integration);
updated.getDestinations().removeIf(d -> invocation.getArgument(2).equals(d.getSourceDatabase()));
updated.getDestinations().add(new Integration.Destination(invocation.getArgument(1),
invocation.getArgument(2), Integration.Destination.STATE_SYNCING, null, "load-1"));
return updated;
});
when(integrations.reserveDestination(any(), anyString(), anyString(), any(), any())).thenAnswer(invocation -> {
Integration updated = new Integration(integration);
updated.getDestinations().removeIf(d -> invocation.getArgument(2).equals(d.getSourceDatabase()));
updated.getDestinations().add(new Integration.Destination(invocation.getArgument(1),
invocation.getArgument(2), Integration.Destination.STATE_CREATING, null, "load-1"));
return updated;
});
when(integrations.startDestinationSync(any(), anyString(), any())).thenReturn(integration);
when(redshiftService.clusterRegion(ACCOUNT, "orders-dw")).thenReturn(Optional.of("us-east-1"));
}
private static SpectrumSession session(String clusterIdentifier) {
return new SpectrumSession(ACCOUNT, ACCOUNT + ":" + clusterIdentifier, "dev", List.of(), false);
}
private static ExternalStatement.CreateIntegrationDatabase statement(String sourceDatabase) {
return new ExternalStatement.CreateIntegrationDatabase("orders_dw", INTEGRATION_ID, sourceDatabase);
}
private void assertState(String sqlState, Runnable call) {
@@ -160,7 +129,7 @@ class RdsIntegrationDatabasesTest {
new AwsException("IntegrationAlreadyExistsFault", "already", 400));
assertState("42P04", () -> databases.create(
new ExternalStatement.CreateIntegrationDatabase("orders_dw2", INTEGRATION_ID, "orders"),
statement("orders_dw2", "orders"),
session("orders-dw"), backend));
verify(integrations).reserveDestination(integration, "orders_dw2", "orders", null, null);
assertThat(backend.statements, empty());
@@ -230,6 +199,23 @@ class RdsIntegrationDatabasesTest {
verify(loader).submit(any(), eq("orders"), eq("orders_dw"), eq("load-1"));
}
@Test
void refusesRetryingAFailedLoadWhenCallerLacksPermission() {
integration.getDestinations().add(new Integration.Destination("orders_dw", "orders",
Integration.Destination.STATE_FAILED, null));
backend.existingDatabase = true;
backend.canRetryDatabase = false;
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> databases.create(statement("orders"), session("orders-dw"), backend));
assertEquals("42501", error.sqlState(), error.getMessage());
assertEquals("permission denied to create database", error.getMessage());
assertThat(backend.statements, empty());
verify(integrations, never()).addDestination(any(), anyString(), anyString(), anyBoolean());
verify(loader, never()).submit(any(), anyString(), anyString(), any());
}
@Test
void restoresPreviousFailedDestinationAndErrorsWhenRetryDatabaseCreationFails() {
Integration.Destination failed = new Integration.Destination("orders_dw", "orders",
@@ -244,7 +230,7 @@ class RdsIntegrationDatabasesTest {
failing.failure = new SpectrumSqlException("42P04", "database \"orders_dw_v2\" already exists");
assertState("42P04", () -> databases.create(
new ExternalStatement.CreateIntegrationDatabase("orders_dw_v2", INTEGRATION_ID, "orders"),
statement("orders_dw_v2", "orders"),
session("orders-dw"), failing));
verify(integrations).restoreDestination(integration, "orders", "load-1", failed, List.of(error));
@@ -256,9 +242,13 @@ class RdsIntegrationDatabasesTest {
private final List<String> statements = new ArrayList<>();
private RuntimeException failure;
private boolean existingDatabase;
private boolean canRetryDatabase = true;
@Override
public Optional<String> queryString(String sql) {
if (sql.contains("pg_catalog.pg_roles")) {
return canRetryDatabase ? Optional.of("1") : Optional.empty();
}
return existingDatabase ? Optional.of("1") : Optional.empty();
}
@@ -0,0 +1,174 @@
package io.floci.aws.services.rds.integration;
import io.floci.aws.services.dsql.ExternalPostgresServer;
import io.floci.aws.services.rds.model.Integration;
import io.floci.aws.services.redshift.spectrum.BackendSql;
import io.floci.aws.services.redshift.spectrum.SpectrumSqlException;
import io.floci.aws.testing.ParallelLocks;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.api.parallel.ResourceAccessMode;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.opentest4j.TestAbortedException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static io.floci.aws.services.rds.integration.RdsIntegrationDatabasesFixture.session;
import static io.floci.aws.services.rds.integration.RdsIntegrationDatabasesFixture.statement;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* Retrying a failed zero-ETL destination checks the caller's privileges against a real PostgreSQL 16: each case
* holds exactly one of the conditions the check combines, so dropping any of them flips a result here.
*/
@Tag("docker")
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
@ResourceLock(value = ParallelLocks.PORTS, mode = ResourceAccessMode.READ)
class RdsIntegrationRetryPermissionDockerNightlyIntegrationTest {
private static final String SUPERUSER_PASSWORD = "floci-test";
private static final String ROLE_PASSWORD = "retry-test";
private ExternalPostgresServer server;
private RdsIntegrationDatabasesFixture fixture;
@BeforeAll
void startServer() throws Exception {
try {
server = ExternalPostgresServer.start("floci-rds-zero-etl-retry", SUPERUSER_PASSWORD,
"POSTGRES_PASSWORD=" + SUPERUSER_PASSWORD);
} catch (ExternalPostgresServer.DockerUnavailableException e) {
throw new TestAbortedException(e.getMessage(), e);
}
ExternalPostgresServer.Superuser postgres = server.superuser();
postgres.execute("CREATE ROLE retry_team NOLOGIN");
postgres.execute("CREATE ROLE retry_owner LOGIN NOCREATEDB PASSWORD '" + ROLE_PASSWORD + "'");
postgres.execute("CREATE ROLE retry_creator LOGIN CREATEDB PASSWORD '" + ROLE_PASSWORD + "'");
postgres.execute("CREATE ROLE retry_member LOGIN CREATEDB PASSWORD '" + ROLE_PASSWORD
+ "' IN ROLE retry_team");
postgres.execute("CREATE ROLE retry_super LOGIN SUPERUSER NOCREATEDB PASSWORD '" + ROLE_PASSWORD + "'");
postgres.execute("CREATE DATABASE owned_by_owner OWNER retry_owner");
postgres.execute("CREATE DATABASE owned_by_postgres");
postgres.execute("CREATE DATABASE owned_by_team OWNER retry_team");
}
@AfterAll
void removeServer() {
if (server != null) {
server.close();
}
}
@BeforeEach
void setUp() {
fixture = new RdsIntegrationDatabasesFixture();
}
@Test
void refusesAnOwnerWithoutCreatedb() throws Exception {
assertRefused("retry_owner", "owned_by_owner");
}
@Test
void refusesANonOwnerWithCreatedb() throws Exception {
assertRefused("retry_creator", "owned_by_postgres");
}
@Test
void allowsAMemberOfTheOwnerRoleWithCreatedb() throws Exception {
assertAllowed("retry_member", "owned_by_team");
}
@Test
void allowsASuperuserWithoutCreatedb() throws Exception {
assertAllowed("retry_super", "owned_by_team");
}
private void assertRefused(String role, String databaseName) throws SQLException {
try (JdbcBackend backend = connectAs(role)) {
SpectrumSqlException error = assertThrows(SpectrumSqlException.class,
() -> retry(databaseName, backend));
assertEquals("42501", error.sqlState(), error.getMessage());
assertEquals("permission denied to create database", error.getMessage());
assertThat(backend.statements, empty());
}
verify(fixture.integrations, never()).addDestination(any(), anyString(), anyString(), anyBoolean());
verify(fixture.loader, never()).submit(any(), anyString(), anyString(), any());
}
private void assertAllowed(String role, String databaseName) throws SQLException {
try (JdbcBackend backend = connectAs(role)) {
retry(databaseName, backend);
assertThat(backend.statements, empty());
}
verify(fixture.integrations).addDestination(fixture.integration, databaseName, "orders", false);
verify(fixture.loader).submit(any(), eq("orders"), eq(databaseName), eq("load-1"));
}
private void retry(String databaseName, BackendSql backend) {
fixture.integration.getDestinations().add(new Integration.Destination(databaseName, "orders",
Integration.Destination.STATE_FAILED, null));
fixture.databases.create(statement(databaseName, "orders"), session("orders-dw"), backend);
}
private JdbcBackend connectAs(String role) throws SQLException {
return new JdbcBackend(DriverManager.getConnection(server.jdbcUrl("postgres"), role, ROLE_PASSWORD));
}
/** Answers queries from the server as the connected role and records, without running, every statement. */
private static final class JdbcBackend implements BackendSql, AutoCloseable {
private final Connection connection;
private final List<String> statements = new ArrayList<>();
JdbcBackend(Connection connection) {
this.connection = connection;
}
@Override
public Optional<String> queryString(String sql) {
try (Statement statement = connection.createStatement(); ResultSet rows = statement.executeQuery(sql)) {
return rows.next() ? Optional.ofNullable(rows.getString(1)) : Optional.empty();
} catch (SQLException e) {
throw new IllegalStateException(sql, e);
}
}
@Override
public void execute(String sql) {
statements.add(sql);
}
@Override
public long copyIn(String copySql, InputStream data) {
throw new UnsupportedOperationException();
}
@Override
public void close() throws SQLException {
connection.close();
}
}
}