diff --git a/docs/services/lakeformation.md b/docs/services/lakeformation.md index 6355337ee7..e59ccdd053 100644 --- a/docs/services/lakeformation.md +++ b/docs/services/lakeformation.md @@ -38,6 +38,8 @@ The `lakeformation` service allows you to manage data lake settings, resources, * `RemoveLFTagsFromResource` ## Implementation Details -Floci currently supports basic CRUD operations for Lake Formation resources, permissions, and tags. This state is strictly persisted without deep integration into other data-plane emulators. +Floci currently supports basic CRUD operations for Lake Formation resources, permissions, and tags. This state is persisted and, apart from the Redshift Spectrum enforcement below, not consulted by other data-plane emulators. + +**Redshift Spectrum enforcement.** Set `floci.services.redshift.spectrum-lake-formation-enforcement=true` (`FLOCI_SERVICES_REDSHIFT_SPECTRUM_LAKE_FORMATION_ENFORCEMENT`, default `false`) to make Spectrum queries honor the grants stored here. The IAM role of the external schema must hold `SELECT` (or `ALL`) on the table, on a `TableWildcard` of its database, or on a column wildcard without exclusions, or the query fails with SQLSTATE `42501`. A grant to `IAM_ALLOWED_PRINCIPALS` leaves the table to IAM, and so does a catalog with no data lake settings stored or whose `CreateTableDefaultPermissions` names `IAM_ALLOWED_PRINCIPALS`; store settings with that list empty to hand tables to Lake Formation. A schema without a Glue database (the legacy catalog) is refused. Column grants, LF-Tags and data cells filters are not evaluated. A local view over an external table is not followed, so only a query that names the table is checked. See [Redshift](redshift.md). Permissions retrieval via `ListPermissions` currently lists all explicitly granted permissions to satisfy Terraform state expectations without strict caller permission filtering. diff --git a/docs/services/redshift.md b/docs/services/redshift.md index 70c33ee82d..ba649bb0c1 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -940,9 +940,26 @@ is authorized ahead of the role's policies directly for the minted transfer sess verifying Floci's internal tag on the bucket. Reads of the scratch bucket and every other bucket stay under normal policy evaluation. +With `floci.services.redshift.spectrum-lake-formation-enforcement=true` +(`FLOCI_SERVICES_REDSHIFT_SPECTRUM_LAKE_FORMATION_ENFORCEMENT`, default `false`), a query on an external +table also needs a Lake Formation `SELECT` grant for the IAM role bound to its external schema. The grant can +be on the table, on every table of its database (`TableWildcard`), or on the whole table through a column +wildcard without exclusions; `ALL` also counts. A grant to `IAM_ALLOWED_PRINCIPALS` leaves the table to IAM +alone, so only the S3 checks above apply to it, as in AWS's IAM-only and hybrid modes. Floci's Glue never +stores that grant, so a catalog that keeps AWS's initial settings leaves every table to IAM: that is the case +when no data lake settings are stored, or when `CreateTableDefaultPermissions` names `IAM_ALLOWED_PRINCIPALS`. +Call `PutDataLakeSettings` with `CreateTableDefaultPermissions` empty to hand tables to Lake Formation. +Without a grant the query then fails with SQLSTATE `42501`. A schema created without a Glue database reads +through the legacy catalog, where no grant can name its tables, so the flag refuses those queries as well. +The check runs on every query, ahead of the cache, so a +`RevokePermissions` stops the next query even for a table already loaded. Column grants, LF-Tags and data +cells filters are not evaluated: a table reachable only through them is refused. +The check runs where Floci reads the external table, which is a query that names it: a local view over an +external table is not followed, so a query on such a view is not checked until the table is next named. + Writes to external relations are rejected. AWS prohibits external UPDATE/DELETE but supports some external INSERT operations; external INSERT is an intentional Floci limitation here. Use -schema-qualified external table names. Full Glue IAM enforcement, Lake Formation, role chaining +schema-qualified external table names. Full Glue IAM enforcement, Lake Formation column and tag permissions, role chaining and `IAM_ROLE SESSION` are outside this implementation. Metadata is exposed through `svv_external_schemas`, `svv_external_tables`, `svv_external_columns` and `svv_external_partitions`. diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 405d70fdbc..f07e40958b 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -1891,6 +1891,9 @@ public interface EmulatorConfig { @WithDefault("1000000") long spectrumMaxRows(); + + @WithDefault("false") + boolean spectrumLakeFormationEnforcement(); } interface RdsServiceConfig { diff --git a/src/main/java/io/floci/aws/services/lakeformation/LakeFormationAuthorizer.java b/src/main/java/io/floci/aws/services/lakeformation/LakeFormationAuthorizer.java new file mode 100644 index 0000000000..9a1b00ecc0 --- /dev/null +++ b/src/main/java/io/floci/aws/services/lakeformation/LakeFormationAuthorizer.java @@ -0,0 +1,109 @@ +package io.floci.aws.services.lakeformation; + +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.core.common.RequestScopes; +import io.floci.aws.services.lakeformation.model.ColumnWildcard; +import io.floci.aws.services.lakeformation.model.DataLakePrincipal; +import io.floci.aws.services.lakeformation.model.PrincipalResourcePermissions; +import io.floci.aws.services.lakeformation.model.Resource; +import io.floci.aws.services.lakeformation.model.TableResource; +import io.floci.aws.services.lakeformation.model.TableWithColumnsResource; +import jakarta.enterprise.context.ApplicationScoped; + +import java.util.List; + +/** + * Decides whether a principal may read a table, from the grants Lake Formation stores. + * Only table-level {@code SELECT} is evaluated: a grant on columns, an LF-Tag or a data cells filter + * does not count, so a table reachable only through those is denied. + */ +@ApplicationScoped +public class LakeFormationAuthorizer { + + /** The group AWS grants to every Glue database that is not under Lake Formation control. */ + static final String IAM_ALLOWED_PRINCIPALS = "IAM_ALLOWED_PRINCIPALS"; + + private static final String SELECT = "SELECT"; + private static final String ALL = "ALL"; + + private final LakeFormationStorage storage; + private final RegionResolver regionResolver; + + public LakeFormationAuthorizer(LakeFormationStorage storage, RegionResolver regionResolver) { + this.storage = storage; + this.regionResolver = regionResolver; + } + + /** + * Whether {@code principalArn} holds {@code SELECT} on the table, by a grant to the principal itself or + * to {@code IAMAllowedPrincipals}, the group that leaves the table to IAM alone. Floci's Glue never stores + * that grant, so a catalog that keeps AWS's initial settings (none stored, or + * {@code CreateTableDefaultPermissions} naming {@code IAM_ALLOWED_PRINCIPALS}) leaves every table to IAM. + */ + public boolean canSelect(String accountId, String principalArn, String databaseName, String tableName) { + return RequestScopes.callAs(accountId, () -> { + String region = regionResolver.getRegion(); + return grants(region, accountId, principalArn, databaseName, tableName) + || grants(region, accountId, IAM_ALLOWED_PRINCIPALS, databaseName, tableName) + || newTablesAreLeftToIam(region, accountId); + }); + } + + private boolean newTablesAreLeftToIam(String region, String catalogId) { + return storage.getDataLakeSettings(region, catalogId) + .map(settings -> settings.getCreateTableDefaultPermissions() != null + && settings.getCreateTableDefaultPermissions().stream().anyMatch(permissions -> + permissions.getPrincipal() != null + && IAM_ALLOWED_PRINCIPALS.equals(permissions.getPrincipal().getDataLakePrincipalIdentifier()))) + .orElse(true); + } + + private boolean grants(String region, String catalogId, String principalId, String databaseName, + String tableName) { + DataLakePrincipal principal = new DataLakePrincipal(); + principal.setDataLakePrincipalIdentifier(principalId); + List held = + storage.listPermissions(region, catalogId, principal, null, null, false, null, null); + for (PrincipalResourcePermissions grant : held) { + if (allowsSelect(grant.getPermissions()) && covers(grant.getResource(), catalogId, databaseName, tableName)) { + return true; + } + } + return false; + } + + private static boolean allowsSelect(List permissions) { + return permissions != null && (permissions.contains(SELECT) || permissions.contains(ALL)); + } + + private static boolean covers(Resource resource, String catalogId, String databaseName, String tableName) { + if (resource == null) { + return false; + } + TableResource table = resource.getTable(); + if (table != null) { + return sameCatalog(table.getCatalogId(), catalogId) + && sameName(table.getDatabaseName(), databaseName) + && (table.getTableWildcard() != null || sameName(table.getName(), tableName)); + } + TableWithColumnsResource columns = resource.getTableWithColumns(); + if (columns != null) { + ColumnWildcard wildcard = columns.getColumnWildcard(); + boolean wholeTable = wildcard != null + && (wildcard.getExcludedColumnNames() == null || wildcard.getExcludedColumnNames().isEmpty()); + return wholeTable && sameCatalog(columns.getCatalogId(), catalogId) + && sameName(columns.getDatabaseName(), databaseName) + && sameName(columns.getName(), tableName); + } + return false; + } + + /** Glue resolves database and table names ignoring case, so a grant written in another case still applies. */ + private static boolean sameName(String left, String right) { + return left != null && left.equalsIgnoreCase(right); + } + + private static boolean sameCatalog(String grantCatalogId, String catalogId) { + return grantCatalogId == null || grantCatalogId.equals(catalogId); + } +} diff --git a/src/main/java/io/floci/aws/services/lakeformation/MemoryLakeFormationStorage.java b/src/main/java/io/floci/aws/services/lakeformation/MemoryLakeFormationStorage.java index a5f518e2c6..24e35852c8 100644 --- a/src/main/java/io/floci/aws/services/lakeformation/MemoryLakeFormationStorage.java +++ b/src/main/java/io/floci/aws/services/lakeformation/MemoryLakeFormationStorage.java @@ -203,10 +203,14 @@ public class MemoryLakeFormationStorage implements LakeFormationStorage { // Deliberate omission: MaxResults, NextToken, ResourceType, and IncludeRelated are ignored. // All results fit on a single page, and SDKs tolerate unset optional filters. String filterResourceKey = resource != null ? getResourceKey(resource) : null; - return permissionsStorage.scan(k -> k.startsWith(region + ":" + catalogId + ":")).stream() + String principalId = principal != null ? principal.getDataLakePrincipalIdentifier() : null; + String keyPrefix = principalId != null + ? region + ":" + catalogId + ":" + principalId + ":" + : region + ":" + catalogId + ":"; + return permissionsStorage.scan(k -> k.startsWith(keyPrefix)).stream() .filter(p -> { - if (principal != null && principal.getDataLakePrincipalIdentifier() != null) { - if (p.getPrincipal() == null || !principal.getDataLakePrincipalIdentifier().equals(p.getPrincipal().getDataLakePrincipalIdentifier())) { + if (principalId != null) { + if (p.getPrincipal() == null || !principalId.equals(p.getPrincipal().getDataLakePrincipalIdentifier())) { return false; } } diff --git a/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalTableMaterializer.java b/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalTableMaterializer.java index a17b89f038..c83b8940a9 100644 --- a/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalTableMaterializer.java +++ b/src/main/java/io/floci/aws/services/redshift/spectrum/ExternalTableMaterializer.java @@ -15,6 +15,7 @@ import io.floci.aws.services.glue.model.Partition; import io.floci.aws.services.glue.model.StorageDescriptor; import io.floci.aws.services.glue.model.Table; import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.lakeformation.LakeFormationAuthorizer; import io.floci.aws.services.redshift.proxy.RedshiftRoleAccess; import io.floci.aws.services.redshift.proxy.S3CopySimulator; import io.floci.aws.services.s3.S3ResourceArns; @@ -84,6 +85,7 @@ public class ExternalTableMaterializer { private final S3Service s3Service; private final IamService iamService; private final EmulatorConfig config; + private final LakeFormationAuthorizer lakeFormation; private final ExternalCatalogLocks catalogLocks; private final ConcurrentHashMap fingerprints = new ConcurrentHashMap<>(); /** Column definitions each loaded table was created with, to tell a data reload from a schema change. */ @@ -183,18 +185,21 @@ public class ExternalTableMaterializer { } public ExternalTableMaterializer(FlociDuckClient duckClient, GlueService glueService, S3Service s3Service, - IamService iamService, EmulatorConfig config) { - this(duckClient, glueService, s3Service, iamService, config, new ExternalCatalogLocks()); + IamService iamService, EmulatorConfig config, + LakeFormationAuthorizer lakeFormation) { + this(duckClient, glueService, s3Service, iamService, config, lakeFormation, new ExternalCatalogLocks()); } @Inject public ExternalTableMaterializer(FlociDuckClient duckClient, GlueService glueService, S3Service s3Service, - IamService iamService, EmulatorConfig config, ExternalCatalogLocks catalogLocks) { + IamService iamService, EmulatorConfig config, + LakeFormationAuthorizer lakeFormation, ExternalCatalogLocks catalogLocks) { this.duckClient = duckClient; this.glueService = glueService; this.s3Service = s3Service; this.iamService = iamService; this.config = config; + this.lakeFormation = lakeFormation; this.catalogLocks = catalogLocks; } @@ -243,6 +248,8 @@ public class ExternalTableMaterializer { throw exception; } String label = binding.schemaName() + "." + tableName; + // Checked ahead of the cache probe below, so a revoke takes effect on data already loaded. + authorizeLakeFormation(binding, session, table.getName(), label); // DuckDB reads as the account, so the bound role's access is enforced here, ahead of the read, // with the same signed authorization COPY uses: identity policy and bucket policy. RedshiftRoleAccess.RoleSession roleSession = openRoleSession(binding, session); @@ -588,6 +595,17 @@ public class ExternalTableMaterializer { } } + private void authorizeLakeFormation(ExternalSchemaBinding binding, SpectrumSession session, String glueTable, + String label) { + if (!config.services().redshift().spectrumLakeFormationEnforcement()) { + return; + } + if (!lakeFormation.canSelect(session.accountId(), binding.iamRoleArn(), binding.glueDatabase(), glueTable)) { + throw new SpectrumSqlException(SQLSTATE_INSUFFICIENT_PRIVILEGE, + "Insufficient Lake Formation permission(s) on external table \"" + label + "\""); + } + } + private void authorizeObjects(String accountId, ExternalSchemaBinding binding, RedshiftRoleAccess.RoleSession roleSession, List sources) { try { 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 500303dc60..0accb6c457 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 @@ -1,5 +1,6 @@ package io.floci.aws.services.redshift.spectrum; +import io.floci.aws.config.EmulatorConfig; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; @@ -16,18 +17,20 @@ public final class SpectrumInterceptor { private final SpectrumS3Reader reader; private final SpectrumMaterializer materializer; private final SpectrumQueryPreparation preparation; + private final EmulatorConfig config; public SpectrumInterceptor(SpectrumCatalog catalog, SpectrumStatementParser statementParser, SpectrumQueryClassifier queryClassifier, SpectrumQueryRewriter queryRewriter, SpectrumS3Reader reader, SpectrumMaterializer materializer) { - this(catalog, statementParser, queryClassifier, queryRewriter, reader, materializer, null); + this(catalog, statementParser, queryClassifier, queryRewriter, reader, materializer, null, null); } @Inject public SpectrumInterceptor(SpectrumCatalog catalog, SpectrumStatementParser statementParser, SpectrumQueryClassifier queryClassifier, SpectrumQueryRewriter queryRewriter, SpectrumS3Reader reader, SpectrumMaterializer materializer, - SpectrumQueryPreparation preparation) { + SpectrumQueryPreparation preparation, EmulatorConfig config) { + this.config = config; this.catalog = catalog; this.statementParser = statementParser; this.queryClassifier = queryClassifier; @@ -106,6 +109,7 @@ public final class SpectrumInterceptor { return new Decision.Handled(); } case Plan.Query(SpectrumQuery query, SpectrumExternalTable table, SpectrumExternalSchema schema, String identifier) -> { + requireLakeFormationFreeSchema(table); SpectrumMaterializer.Materialization materialized = materializer.materialize(backend, table, schema, reader, identifier); return new Decision.Rewritten(queryRewriter.rewrite(query, materialized.identifier()), materialized); } @@ -115,6 +119,17 @@ public final class SpectrumInterceptor { } } + /** + * A legacy-catalog table has no Glue resource, so no Lake Formation grant can ever cover it. With + * enforcement on it is refused rather than read unchecked. + */ + private void requireLakeFormationFreeSchema(SpectrumExternalTable table) { + if (config != null && config.services().redshift().spectrumLakeFormationEnforcement()) { + throw new SpectrumSqlException("42501", "Insufficient Lake Formation permission(s) on external table \"" + + table.schemaName() + "." + table.tableName() + "\": the table is not in a Glue database"); + } + } + /** * Drops the temp table a {@link Decision.Rewritten} materialized, once the client has finished * reading its rows (or failed while doing so). diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index e6a51d8b29..6b64c6bee6 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -572,6 +572,7 @@ floci: proxy-backend-connect-timeout-millis: 5000 # Max time to wait for the backend TCP connect proxy-max-connections: 2000 # Max concurrent proxy connections before new ones are refused spectrum-max-rows: 1000000 # FLOCI_SERVICES_REDSHIFT_SPECTRUM_MAX_ROWS; rows loaded per external table per query + spectrum-lake-formation-enforcement: false # FLOCI_SERVICES_REDSHIFT_SPECTRUM_LAKE_FORMATION_ENFORCEMENT; require a Lake Formation SELECT grant on each external table rds: enabled: true mock: false # FLOCI_SERVICES_RDS_MOCK — true = metadata only, no Docker (useful for CI) diff --git a/src/test/java/io/floci/aws/services/lakeformation/LakeFormationAuthorizerTest.java b/src/test/java/io/floci/aws/services/lakeformation/LakeFormationAuthorizerTest.java new file mode 100644 index 0000000000..9bb67e15a9 --- /dev/null +++ b/src/test/java/io/floci/aws/services/lakeformation/LakeFormationAuthorizerTest.java @@ -0,0 +1,204 @@ +package io.floci.aws.services.lakeformation; + +import io.floci.aws.core.common.RegionResolver; +import io.floci.aws.services.lakeformation.model.ColumnWildcard; +import io.floci.aws.services.lakeformation.model.DataLakePrincipal; +import io.floci.aws.services.lakeformation.model.DataLakeSettings; +import io.floci.aws.services.lakeformation.model.PrincipalPermissions; +import io.floci.aws.services.lakeformation.model.PrincipalResourcePermissions; +import io.floci.aws.services.lakeformation.model.Resource; +import io.floci.aws.services.lakeformation.model.TableResource; +import io.floci.aws.services.lakeformation.model.TableWildcard; +import io.floci.aws.services.lakeformation.model.TableWithColumnsResource; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +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.when; + +class LakeFormationAuthorizerTest { + + private static final String ACCOUNT = "000000000000"; + private static final String ROLE = "arn:aws:iam::000000000000:role/SpectrumRole"; + + private LakeFormationStorage storage; + private LakeFormationAuthorizer authorizer; + + @BeforeEach + void setUp() { + storage = mock(LakeFormationStorage.class); + RegionResolver regionResolver = new RegionResolver("us-east-1", ACCOUNT); + authorizer = new LakeFormationAuthorizer(storage, regionResolver); + storeSettings(List.of()); + } + + @Test + void aCatalogWithoutStoredSettingsLeavesEveryTableToIam() { + when(storage.getDataLakeSettings(anyString(), anyString())).thenReturn(Optional.empty()); + assertTrue(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + } + + @Test + void defaultTablePermissionsNamingIamAllowedPrincipalsLeaveTablesToIam() { + storeSettings(List.of(defaultPermissionFor(LakeFormationAuthorizer.IAM_ALLOWED_PRINCIPALS))); + assertTrue(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + } + + @Test + void defaultTablePermissionsForAnotherPrincipalDoNotLeaveTablesToIam() { + storeSettings(List.of(defaultPermissionFor("arn:aws:iam::000000000000:role/Other"))); + assertFalse(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + } + + private void storeSettings(List createTableDefaults) { + DataLakeSettings settings = new DataLakeSettings(); + settings.setCreateTableDefaultPermissions(createTableDefaults); + when(storage.getDataLakeSettings(anyString(), anyString())).thenReturn(Optional.of(settings)); + } + + private static PrincipalPermissions defaultPermissionFor(String principalId) { + DataLakePrincipal principal = new DataLakePrincipal(); + principal.setDataLakePrincipalIdentifier(principalId); + PrincipalPermissions permissions = new PrincipalPermissions(); + permissions.setPrincipal(principal); + permissions.setPermissions(List.of("ALL")); + return permissions; + } + + @Test + void noGrantDenies() { + assertFalse(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + } + + @Test + void selectOnTheTableAllows() { + grant(ROLE, tableResource("lake", "events"), "SELECT"); + assertTrue(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + } + + @Test + void allOnTheTableAllows() { + grant(ROLE, tableResource("lake", "events"), "ALL"); + assertTrue(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + } + + @Test + void namesMatchIgnoringCaseLikeGlue() { + grant(ROLE, tableResource("salesdb", "events"), "SELECT"); + assertTrue(authorizer.canSelect(ACCOUNT, ROLE, "SalesDB", "EVENTS")); + } + + @Test + void anotherTableDenies() { + grant(ROLE, tableResource("lake", "orders"), "SELECT"); + assertFalse(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + } + + @Test + void anotherDatabaseDenies() { + grant(ROLE, tableResource("other", "events"), "SELECT"); + assertFalse(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + } + + @Test + void describeAloneDenies() { + grant(ROLE, tableResource("lake", "events"), "DESCRIBE"); + assertFalse(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + } + + @Test + void tableWildcardCoversEveryTableOfTheDatabase() { + TableResource table = new TableResource(); + table.setDatabaseName("lake"); + table.setTableWildcard(new TableWildcard()); + Resource resource = new Resource(); + resource.setTable(table); + grant(ROLE, resource, "SELECT"); + assertTrue(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + assertFalse(authorizer.canSelect(ACCOUNT, ROLE, "other", "events")); + } + + @Test + void columnWildcardCoversTheWholeTable() { + grant(ROLE, columnsResource(new ColumnWildcard()), "SELECT"); + assertTrue(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + } + + @Test + void columnWildcardWithExclusionsDoesNotCoverTheWholeTable() { + ColumnWildcard wildcard = new ColumnWildcard(); + wildcard.setExcludedColumnNames(List.of("secret")); + grant(ROLE, columnsResource(wildcard), "SELECT"); + assertFalse(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + } + + @Test + void namedColumnsDoNotCoverTheWholeTable() { + grant(ROLE, columnsResource(null), "SELECT"); + assertFalse(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + } + + @Test + void iamAllowedPrincipalsLeavesTheTableToIam() { + grant(LakeFormationAuthorizer.IAM_ALLOWED_PRINCIPALS, tableResource("lake", "events"), "ALL"); + assertTrue(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + } + + @Test + void aGrantToAnotherPrincipalDenies() { + grant("arn:aws:iam::000000000000:role/Other", tableResource("lake", "events"), "SELECT"); + assertFalse(authorizer.canSelect(ACCOUNT, ROLE, "lake", "events")); + } + + @Test + void databaseAndTableNamesMatchIgnoringCase() { + grant(ROLE, tableResource("salesdb", "orders"), "SELECT"); + assertTrue(authorizer.canSelect(ACCOUNT, ROLE, "SalesDB", "Orders")); + } + + private void grant(String principalId, Resource resource, String permission) { + DataLakePrincipal principal = new DataLakePrincipal(); + principal.setDataLakePrincipalIdentifier(principalId); + PrincipalResourcePermissions grant = new PrincipalResourcePermissions(); + grant.setPrincipal(principal); + grant.setResource(resource); + grant.setPermissions(List.of(permission)); + when(storage.listPermissions(anyString(), anyString(), any(DataLakePrincipal.class), isNull(), isNull(), + eq(false), isNull(), isNull())) + .thenAnswer(invocation -> { + DataLakePrincipal asked = invocation.getArgument(2); + return principalId.equals(asked.getDataLakePrincipalIdentifier()) ? List.of(grant) : List.of(); + }); + } + + private static Resource tableResource(String database, String name) { + TableResource table = new TableResource(); + table.setDatabaseName(database); + table.setName(name); + Resource resource = new Resource(); + resource.setTable(table); + return resource; + } + + private static Resource columnsResource(ColumnWildcard wildcard) { + TableWithColumnsResource columns = new TableWithColumnsResource(); + columns.setDatabaseName("lake"); + columns.setName("events"); + columns.setColumnWildcard(wildcard); + if (wildcard == null) { + columns.setColumnNames(List.of("id")); + } + Resource resource = new Resource(); + resource.setTableWithColumns(columns); + return resource; + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/RedshiftSpectrumLakeFormationIntegrationTest.java b/src/test/java/io/floci/aws/services/redshift/RedshiftSpectrumLakeFormationIntegrationTest.java new file mode 100644 index 0000000000..065a78dd62 --- /dev/null +++ b/src/test/java/io/floci/aws/services/redshift/RedshiftSpectrumLakeFormationIntegrationTest.java @@ -0,0 +1,182 @@ +package io.floci.aws.services.redshift; + +import io.floci.aws.services.glue.GlueService; +import io.floci.aws.services.glue.model.Database; +import io.floci.aws.services.iam.IamService; +import io.floci.aws.services.lakeformation.LakeFormationService; +import io.floci.aws.services.lakeformation.model.DataLakePrincipal; +import io.floci.aws.services.lakeformation.model.DataLakeSettings; +import io.floci.aws.services.lakeformation.model.GrantPermissionsRequest; +import io.floci.aws.services.lakeformation.model.PutDataLakeSettingsRequest; +import io.floci.aws.services.lakeformation.model.Resource; +import io.floci.aws.services.lakeformation.model.RevokePermissionsRequest; +import io.floci.aws.services.lakeformation.model.TableResource; +import io.floci.aws.services.redshift.model.Cluster; +import io.floci.aws.services.redshift.spectrum.ExternalStatement; +import io.floci.aws.services.redshift.spectrum.ExternalStatementParser; +import io.floci.aws.services.redshift.spectrum.GlueTableBuilder; +import io.floci.aws.services.s3.S3Service; +import io.floci.aws.testing.SidecarContainersProfile; +import io.floci.aws.testing.SidecarSpectrumLakeFormationProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; + +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import static io.floci.aws.services.redshift.RedshiftConnections.waitForConnection; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * A Spectrum query is refused until the external schema's role holds a Lake Formation {@code SELECT} + * grant on the table, and a revoke stops the next query even though the table is already cached. + */ +@QuarkusTest +@TestProfile(SidecarSpectrumLakeFormationProfile.class) +class RedshiftSpectrumLakeFormationIntegrationTest { + + private static final String REGION = "us-east-1"; + private static final String ROLE_NAME = "SpectrumLfItRole"; + private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/" + ROLE_NAME; + private static final String TRUST_POLICY = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"Service":"redshift.amazonaws.com"},"Action":"sts:AssumeRole"}]}"""; + + @Inject + RedshiftService redshiftService; + + @Inject + S3Service s3Service; + + @Inject + IamService iamService; + + @Inject + GlueService glueService; + + @Inject + LakeFormationService lakeFormationService; + + private String clusterId; + private String bucket; + private String glueDatabase; + + @BeforeAll + static void requireDocker() throws ClassNotFoundException { + SidecarContainersProfile.requireDocker(); + Class.forName("org.postgresql.Driver"); + } + + @AfterEach + void cleanUp() { + if (clusterId != null) { + redshiftService.deleteCluster(clusterId); + } + if (bucket != null) { + s3Service.deleteObject(bucket, "events/part-1.csv"); + s3Service.deleteBucket(bucket); + } + if (glueDatabase != null) { + glueService.deleteDatabase(glueDatabase); + } + iamService.deleteRolePolicy(ROLE_NAME, "AllowS3"); + iamService.deleteRole(ROLE_NAME); + } + + @Test + @Timeout(180) + void aGrantOpensTheTableAndARevokeClosesItAgainOnceCached() throws Exception { + iamService.createRole(ROLE_NAME, "/", TRUST_POLICY, null, 0, null); + iamService.putRolePolicy(ROLE_NAME, "AllowS3", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":["s3:GetObject","s3:ListBucket"],"Resource":"*"}]}"""); + bucket = "spectrum-lf-" + System.nanoTime(); + s3Service.createBucket(bucket, REGION); + s3Service.putObject(bucket, "events/part-1.csv", "1,10\n2,7\n".getBytes(StandardCharsets.UTF_8), + "text/csv", null); + glueDatabase = "spectrum_lf_" + System.nanoTime(); + Database database = new Database(); + database.setName(glueDatabase); + glueService.createDatabase(database); + clusterId = "it-lf-" + System.nanoTime(); + Cluster cluster = redshiftService.createCluster(clusterId, "dc2.large", "admin", "Secret123", + null, List.of(), List.of(ROLE_ARN)); + try (Connection connection = waitForConnection(cluster); + Statement statement = connection.createStatement()) { + statement.execute("CREATE EXTERNAL SCHEMA lake FROM DATA CATALOG DATABASE '" + glueDatabase + + "' IAM_ROLE '" + ROLE_ARN + "'"); + String externalDdl = "CREATE EXTERNAL TABLE lake.events (id INTEGER, amount INTEGER) " + + "ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' STORED AS TEXTFILE LOCATION 's3://" + + bucket + "/events/'"; + ExternalStatement.CreateTable external = (ExternalStatement.CreateTable) + new ExternalStatementParser().parse(externalDdl).orElseThrow(); + glueService.createTable(glueDatabase, GlueTableBuilder.toGlueTable(external)); + + DataLakeSettings settings = new DataLakeSettings(); + settings.setCreateTableDefaultPermissions(List.of()); + PutDataLakeSettingsRequest managed = new PutDataLakeSettingsRequest(); + managed.setDataLakeSettings(settings); + lakeFormationService.putDataLakeSettings(REGION, managed); + + SQLException denied = assertThrows(SQLException.class, () -> sumAmount(statement)); + assertEquals("42501", denied.getSQLState()); + + lakeFormationService.grantPermissions(REGION, grant()); + assertEquals(17L, sumAmount(statement)); + assertEquals(17L, sumAmount(statement)); + + lakeFormationService.revokePermissions(REGION, revoke()); + SQLException revoked = assertThrows(SQLException.class, () -> sumAmount(statement)); + assertEquals("42501", revoked.getSQLState()); + } + } + + private GrantPermissionsRequest grant() { + GrantPermissionsRequest request = new GrantPermissionsRequest(); + request.setPrincipal(principal()); + request.setResource(tableResource()); + request.setPermissions(List.of("SELECT")); + return request; + } + + private RevokePermissionsRequest revoke() { + RevokePermissionsRequest request = new RevokePermissionsRequest(); + request.setPrincipal(principal()); + request.setResource(tableResource()); + request.setPermissions(List.of("SELECT")); + return request; + } + + private static DataLakePrincipal principal() { + DataLakePrincipal principal = new DataLakePrincipal(); + principal.setDataLakePrincipalIdentifier(ROLE_ARN); + return principal; + } + + private Resource tableResource() { + TableResource table = new TableResource(); + table.setDatabaseName(glueDatabase); + table.setName("events"); + Resource resource = new Resource(); + resource.setTable(table); + return resource; + } + + private static long sumAmount(Statement statement) throws SQLException { + try (ResultSet rows = statement.executeQuery("SELECT SUM(amount) FROM lake.events")) { + assertTrue(rows.next()); + return rows.getLong(1); + } + } +} diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/ExternalTableMaterializerTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/ExternalTableMaterializerTest.java index c4fd7b13ae..06b40dc262 100644 --- a/src/test/java/io/floci/aws/services/redshift/spectrum/ExternalTableMaterializerTest.java +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/ExternalTableMaterializerTest.java @@ -11,6 +11,7 @@ import io.floci.aws.services.glue.model.Table; import io.floci.aws.services.iam.IamService; import io.floci.aws.services.iam.model.CallerContext; import io.floci.aws.services.iam.model.IamRole; +import io.floci.aws.services.lakeformation.LakeFormationAuthorizer; import io.floci.aws.services.s3.S3Service; import io.floci.aws.services.s3.model.S3Object; import org.junit.jupiter.api.BeforeEach; @@ -77,6 +78,8 @@ class ExternalTableMaterializerTest { private IamService iam; private RecordingBackend backend; private ExternalTableMaterializer materializer; + private EmulatorConfig config; + private LakeFormationAuthorizer lakeFormation; private static final class RecordingBackend implements BackendSql { private final List statements = new ArrayList<>(); @@ -115,12 +118,13 @@ class ExternalTableMaterializerTest { when(role.getArn()).thenReturn("arn:aws:iam::000000000000:role/R"); when(role.getAssumeRolePolicyDocument()).thenReturn(TRUST_POLICY); when(iam.findRole(ACCOUNT, "R")).thenReturn(Optional.of(role)); - EmulatorConfig config = mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS); + config = mock(EmulatorConfig.class, Answers.RETURNS_DEEP_STUBS); + lakeFormation = mock(LakeFormationAuthorizer.class); when(config.services().redshift().spectrumMaxRows()).thenReturn(1000L); when(config.defaultRegion()).thenReturn("us-east-1"); when(duck.query(anyString(), any(), anyString())).thenReturn(List.of()); backend = new RecordingBackend(); - materializer = new ExternalTableMaterializer(duck, glue, s3, iam, config); + materializer = new ExternalTableMaterializer(duck, glue, s3, iam, config, lakeFormation); when(s3.openObjectStream(eq(ExternalTableMaterializer.SCRATCH_BUCKET), anyString(), isNull())) .thenReturn(new ByteArrayInputStream("id,name\n1,Alice\n2,Bob\n".getBytes(StandardCharsets.UTF_8))); S3Object icebergMetadata = new S3Object("bucket", "events/metadata/v1.json", @@ -139,6 +143,45 @@ class ExternalTableMaterializerTest { .thenReturn(new S3Service.ListObjectsResult(List.of(), List.of(), false, null)); } + @Test + void lakeFormationIsNotConsultedWhenEnforcementIsOff() { + when(glue.getTable("lake", "events")).thenReturn(csvTable()); + materializer.ensureCurrent(backend, session(false), BINDING, "events"); + verify(lakeFormation, never()).canSelect(anyString(), anyString(), anyString(), anyString()); + } + + @Test + void lakeFormationGrantAllowsTheQuery() { + when(config.services().redshift().spectrumLakeFormationEnforcement()).thenReturn(true); + when(glue.getTable("lake", "events")).thenReturn(csvTable()); + when(lakeFormation.canSelect(ACCOUNT, BINDING.iamRoleArn(), "lake", "events")).thenReturn(true); + assertEquals(ExternalTableMaterializer.Outcome.LOADED, + materializer.ensureCurrent(backend, session(false), BINDING, "events")); + } + + @Test + void lakeFormationRefusalDeniesWithInsufficientPrivilege() { + when(config.services().redshift().spectrumLakeFormationEnforcement()).thenReturn(true); + when(glue.getTable("lake", "events")).thenReturn(csvTable()); + SpectrumSqlException denied = assertThrows(SpectrumSqlException.class, + () -> materializer.ensureCurrent(backend, session(false), BINDING, "events")); + assertEquals("42501", denied.sqlState()); + assertThat(denied.getMessage(), containsString("Lake Formation")); + } + + @Test + void revokeDeniesATableAlreadyLoadedIntoTheBackend() { + when(config.services().redshift().spectrumLakeFormationEnforcement()).thenReturn(true); + when(glue.getTable("lake", "events")).thenReturn(csvTable()); + when(lakeFormation.canSelect(ACCOUNT, BINDING.iamRoleArn(), "lake", "events")).thenReturn(true); + materializer.ensureCurrent(backend, session(false), BINDING, "events"); + assertEquals(ExternalTableMaterializer.Outcome.CURRENT, + materializer.ensureCurrent(backend, session(false), BINDING, "events")); + when(lakeFormation.canSelect(ACCOUNT, BINDING.iamRoleArn(), "lake", "events")).thenReturn(false); + assertThrows(SpectrumSqlException.class, + () -> materializer.ensureCurrent(backend, session(false), BINDING, "events")); + } + @Test void confirmedExtendedCommitPublishesDefinitionsAndFingerprint() { when(glue.getTable("lake", "events")).thenReturn(csvTable()); diff --git a/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumInterceptorTest.java b/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumInterceptorTest.java index ef7107c192..e79746252a 100644 --- a/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumInterceptorTest.java +++ b/src/test/java/io/floci/aws/services/redshift/spectrum/SpectrumInterceptorTest.java @@ -1,5 +1,6 @@ package io.floci.aws.services.redshift.spectrum; +import io.floci.aws.config.EmulatorConfig; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -10,9 +11,12 @@ import java.util.Optional; import static io.floci.aws.testing.InlineMocks.inlineMock; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -73,4 +77,25 @@ class SpectrumInterceptorTest { interceptor.cleanup(backend, materialization); verify(materializer).cleanup(backend, materialization); } + + @Test + void aLegacyCatalogTableIsRefusedWhileLakeFormationIsEnforced() { + EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS); + when(config.services().redshift().spectrumLakeFormationEnforcement()).thenReturn(true); + SpectrumInterceptor enforcing = new SpectrumInterceptor(catalog, new SpectrumStatementParser(), + new SpectrumQueryClassifier(), null, inlineMock(SpectrumS3Reader.class), materializer, null, config); + SpectrumExternalTable table = new SpectrumExternalTable("000000000000", "dev", "analytics", "events", + List.of(new SpectrumColumn("id", SpectrumColumn.Type.INTEGER)), "s3://b/events/", ',', '"', '\\', "\\N", 0); + SpectrumExternalSchema schema = new SpectrumExternalSchema("000000000000", "dev", "analytics", + "s3://b/root/", null); + when(catalog.table("000000000000", "dev", "analytics", "events")).thenReturn(Optional.of(table)); + when(catalog.schema("000000000000", "dev", "analytics")).thenReturn(Optional.of(schema)); + when(materializer.nextIdentifier()).thenReturn("spectrum_tmp_x"); + + SpectrumSqlException refused = assertThrows(SpectrumSqlException.class, + () -> enforcing.intercept("SELECT * FROM analytics.events", "000000000000", "dev", null)); + + assertEquals("42501", refused.sqlState()); + verify(materializer, never()).materialize(any(), any(), any(), any(), any()); + } } diff --git a/src/test/java/io/floci/aws/testing/SidecarSpectrumLakeFormationProfile.java b/src/test/java/io/floci/aws/testing/SidecarSpectrumLakeFormationProfile.java new file mode 100644 index 0000000000..79bb0c3161 --- /dev/null +++ b/src/test/java/io/floci/aws/testing/SidecarSpectrumLakeFormationProfile.java @@ -0,0 +1,18 @@ +package io.floci.aws.testing; + +import java.util.HashMap; +import java.util.Map; + +/** + * {@link SidecarContainersProfile} with Lake Formation enforced on Spectrum queries, so an external + * table is readable only by a role that holds a Lake Formation {@code SELECT} grant on it. + */ +public class SidecarSpectrumLakeFormationProfile extends SidecarContainersProfile { + + @Override + public Map getConfigOverrides() { + Map overrides = new HashMap<>(super.getConfigOverrides()); + overrides.put("floci.services.redshift.spectrum-lake-formation-enforcement", "true"); + return overrides; + } +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml index ad67c2284b..be0a788104 100644 --- a/src/test/resources/application.yml +++ b/src/test/resources/application.yml @@ -230,6 +230,7 @@ floci: proxy-backend-connect-timeout-millis: 5000 proxy-max-connections: 2000 spectrum-max-rows: 1000000 + spectrum-lake-formation-enforcement: false rds: enabled: true mock: false