Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

refactor(glue): extract shared Glue and Redshift role helpers (#4459)

Vũ Thế Huyb8cae89a2d0d
diff --git a/src/main/java/io/github/hectorvent/floci/services/athena/AthenaService.java b/src/main/java/io/github/hectorvent/floci/services/athena/AthenaService.java
index 1fe39c2bb8..89afdbd2cf 100644
--- a/src/main/java/io/github/hectorvent/floci/services/athena/AthenaService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/athena/AthenaService.java
@@ -24,6 +24,7 @@ import io.github.hectorvent.floci.services.athena.model.WorkGroupEngineVersionRe
import io.github.hectorvent.floci.services.athena.model.WorkGroupTag;
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
import io.github.hectorvent.floci.services.glue.GlueService;
+import io.github.hectorvent.floci.services.glue.PartitionProjection;
import io.github.hectorvent.floci.services.glue.model.Column;
import io.github.hectorvent.floci.services.glue.model.Database;
import io.github.hectorvent.floci.services.glue.model.Table;
diff --git a/src/main/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilder.java b/src/main/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilder.java
index 21dd7da1ed..f13ff0e8ea 100644
--- a/src/main/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilder.java
+++ b/src/main/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilder.java
@@ -1,18 +1,14 @@
package io.github.hectorvent.floci.services.athena;
import io.github.hectorvent.floci.services.glue.GlueService;
-import io.github.hectorvent.floci.services.glue.model.Column;
+import io.github.hectorvent.floci.services.glue.GlueTableResolver;
import io.github.hectorvent.floci.services.glue.model.Database;
import io.github.hectorvent.floci.services.glue.model.Table;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
-import java.util.ArrayList;
-import java.util.HashSet;
import java.util.List;
-import java.util.Locale;
-import java.util.Set;
@ApplicationScoped
public class GlueViewDdlBuilder {
@@ -26,14 +22,6 @@ public class GlueViewDdlBuilder {
*/
private static final String ICEBERG_EXTENSION_SETUP = "INSTALL iceberg; LOAD iceberg;\n";
- /** Glue table property AWS/pyiceberg set to mark a table as Iceberg-format. */
- private static final String PARAM_TABLE_TYPE = "table_type";
-
- /** Glue table property holding the path to the table's current Iceberg metadata JSON. */
- private static final String PARAM_METADATA_LOCATION = "metadata_location";
-
- private static final String ICEBERG_TABLE_TYPE = "ICEBERG";
-
private final GlueService glueService;
@Inject
@@ -112,18 +100,19 @@ public class GlueViewDdlBuilder {
? quote(schemaOrNull) + "." + quote(t.getName())
: quote(t.getName());
String fromClause;
- if (isIcebergTable(t) && icebergMetadataLocation(t) != null && !icebergMetadataLocation(t).isBlank()) {
- fromClause = icebergReadExpression(icebergMetadataLocation(t));
+ if (GlueTableResolver.isIcebergTable(t) && GlueTableResolver.icebergMetadataLocation(t) != null
+ && !GlueTableResolver.icebergMetadataLocation(t).isBlank()) {
+ fromClause = GlueTableResolver.icebergReadExpression(GlueTableResolver.icebergMetadataLocation(t));
usesIceberg = true;
} else {
- String readFn = inferReadFunction(t);
- String readPath = PartitionProjection.readPath(t, normalizedLocation);
- fromClause = readExpression(readFn, readPath);
+ String readFn = GlueTableResolver.inferReadFunction(t);
+ String readPath = GlueTableResolver.readPath(t, normalizedLocation);
+ fromClause = GlueTableResolver.readExpression(readFn, readPath);
}
sb.append("CREATE OR REPLACE VIEW ")
.append(target)
.append(" AS SELECT ")
- .append(buildProjection(t))
+ .append(GlueTableResolver.buildProjection(t))
.append(" FROM ")
.append(fromClause)
.append(";\n");
@@ -134,112 +123,6 @@ public class GlueViewDdlBuilder {
return usesIceberg;
}
- /**
- * Projects the columns the catalog declares, rather than whatever the underlying files spell.
- *
- * <p>Athena reports a table's declared column names: a JSON body written with {@code tenantId}
- * surfaces as {@code tenantid} when the table declares it that way, because the catalog owns the
- * schema and the SerDe maps onto it. Inference sees only the data, so without this the view
- * exposes the file's spelling and a client reading the declared name finds nothing. Identifier
- * resolution is case-insensitive here, so a declared name still binds to an inferred one that
- * differs from it only by case.
- *
- * <p>Partition keys are part of the table's schema and are what partition predicates filter on,
- * so they are projected too. A table that declares no columns keeps {@code *}, leaving inference
- * in charge.
- */
- static String buildProjection(Table table) {
- List<Column> declared = new ArrayList<>();
- if (table != null) {
- if (table.getStorageDescriptor() != null && table.getStorageDescriptor().getColumns() != null) {
- declared.addAll(table.getStorageDescriptor().getColumns());
- }
- if (table.getPartitionKeys() != null) {
- declared.addAll(table.getPartitionKeys());
- }
- }
-
- List<String> names = new ArrayList<>();
- Set<String> seen = new HashSet<>();
- for (Column c : declared) {
- if (c == null || c.getName() == null || c.getName().isBlank()) {
- continue;
- }
- String name = c.getName();
- // A partition key repeating a data column would bind twice and make the view ambiguous.
- if (seen.add(name.toLowerCase(Locale.ROOT))) {
- names.add(name);
- }
- }
-
- if (names.isEmpty()) {
- return "*";
- }
-
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < names.size(); i++) {
- if (i > 0) {
- sb.append(", ");
- }
- sb.append(quote(names.get(i))).append(" AS ").append(quote(names.get(i)));
- }
- return sb.toString();
- }
-
- static String inferReadFunction(Table table) {
- if (table == null || table.getStorageDescriptor() == null) {
- return "read_csv_auto";
- }
- String format = table.getStorageDescriptor().getInputFormat();
- String serde = table.getStorageDescriptor().getSerdeInfo() != null
- ? table.getStorageDescriptor().getSerdeInfo().getSerializationLibrary()
- : null;
- if (containsIgnoreCase(format, "parquet") || containsIgnoreCase(serde, "parquet")) {
- return "read_parquet";
- }
- if (containsIgnoreCase(format, "json") || containsIgnoreCase(serde, "json")
- || containsIgnoreCase(format, "hive")) {
- return "read_json_auto";
- }
- return "read_csv_auto";
- }
-
- static String readExpression(String readFn, String normalizedLocation) {
- String escapedLocation = normalizedLocation.replace("'", "''");
- String glob = escapedLocation + "/**";
- if ("read_parquet".equals(readFn)) {
- return "read_parquet('" + glob + "', union_by_name = true)";
- }
- return readFn + "('" + glob + "')";
- }
-
- /**
- * Iceberg tables are not read via a Hive {@code InputFormat}/{@code SerializationLibrary}
- * pair at all: pyiceberg and the AWS Glue-Iceberg integration leave those unset, so
- * {@link #inferReadFunction} would otherwise fall through to {@code read_csv_auto} and fail
- * on the table's binary Parquet data files, or a forced {@code read_parquet} would silently
- * glob every data file ever written under the table's location, including ones no longer
- * referenced by the current snapshot. Following the catalog's own {@code metadata_location}
- * into {@code iceberg_scan} instead resolves the table through its real manifest list.
- */
- static boolean isIcebergTable(Table table) {
- return table != null
- && table.getParameters() != null
- && ICEBERG_TABLE_TYPE.equalsIgnoreCase(table.getParameters().get(PARAM_TABLE_TYPE));
- }
-
- static String icebergMetadataLocation(Table table) {
- return table.getParameters().get(PARAM_METADATA_LOCATION);
- }
-
- static String icebergReadExpression(String metadataLocation) {
- return "iceberg_scan('" + metadataLocation.replace("'", "''") + "')";
- }
-
- static boolean containsIgnoreCase(String str, String sub) {
- return str != null && str.toLowerCase(Locale.ROOT).contains(sub);
- }
-
static String quote(String id) {
return "\"" + id.replace("\"", "\"\"") + "\"";
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/glue/GlueTableResolver.java b/src/main/java/io/github/hectorvent/floci/services/glue/GlueTableResolver.java
new file mode 100644
index 0000000000..492018b45f
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/glue/GlueTableResolver.java
@@ -0,0 +1,150 @@
+package io.github.hectorvent.floci.services.glue;
+
+import io.github.hectorvent.floci.services.glue.model.Column;
+import io.github.hectorvent.floci.services.glue.model.Table;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+/**
+ * Resolves a Glue {@link Table} into the pieces of a DuckDB read plan: which {@code read_*}
+ * function to use, the glob or Iceberg expression to read from, and the column projection that
+ * exposes the catalog's declared names instead of the underlying files' inferred ones.
+ *
+ * <p>Extracted from {@code GlueViewDdlBuilder}, which was the only caller until Redshift Spectrum's
+ * Glue-backed external tables needed the same table-to-read-plan logic outside Athena.
+ */
+public final class GlueTableResolver {
+
+ /** Glue table property AWS/pyiceberg set to mark a table as Iceberg-format. */
+ private static final String PARAM_TABLE_TYPE = "table_type";
+
+ /** Glue table property holding the path to the table's current Iceberg metadata JSON. */
+ private static final String PARAM_METADATA_LOCATION = "metadata_location";
+
+ private static final String ICEBERG_TABLE_TYPE = "ICEBERG";
+
+ private GlueTableResolver() {
+ }
+
+ /**
+ * Projects the columns the catalog declares, rather than whatever the underlying files spell.
+ *
+ * <p>Athena reports a table's declared column names: a JSON body written with {@code tenantId}
+ * surfaces as {@code tenantid} when the table declares it that way, because the catalog owns the
+ * schema and the SerDe maps onto it. Inference sees only the data, so without this the view
+ * exposes the file's spelling and a client reading the declared name finds nothing. Identifier
+ * resolution is case-insensitive here, so a declared name still binds to an inferred one that
+ * differs from it only by case.
+ *
+ * <p>Partition keys are part of the table's schema and are what partition predicates filter on,
+ * so they are projected too. A table that declares no columns keeps {@code *}, leaving inference
+ * in charge.
+ */
+ public static String buildProjection(Table table) {
+ List<Column> declared = new ArrayList<>();
+ if (table != null) {
+ if (table.getStorageDescriptor() != null && table.getStorageDescriptor().getColumns() != null) {
+ declared.addAll(table.getStorageDescriptor().getColumns());
+ }
+ if (table.getPartitionKeys() != null) {
+ declared.addAll(table.getPartitionKeys());
+ }
+ }
+
+ List<String> names = new ArrayList<>();
+ Set<String> seen = new HashSet<>();
+ for (Column c : declared) {
+ if (c == null || c.getName() == null || c.getName().isBlank()) {
+ continue;
+ }
+ String name = c.getName();
+ // A partition key repeating a data column would bind twice and make the view ambiguous.
+ if (seen.add(name.toLowerCase(Locale.ROOT))) {
+ names.add(name);
+ }
+ }
+
+ if (names.isEmpty()) {
+ return "*";
+ }
+
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < names.size(); i++) {
+ if (i > 0) {
+ sb.append(", ");
+ }
+ sb.append(quote(names.get(i))).append(" AS ").append(quote(names.get(i)));
+ }
+ return sb.toString();
+ }
+
+ public static String inferReadFunction(Table table) {
+ if (table == null || table.getStorageDescriptor() == null) {
+ return "read_csv_auto";
+ }
+ String format = table.getStorageDescriptor().getInputFormat();
+ String serde = table.getStorageDescriptor().getSerdeInfo() != null
+ ? table.getStorageDescriptor().getSerdeInfo().getSerializationLibrary()
+ : null;
+ if (containsIgnoreCase(format, "parquet") || containsIgnoreCase(serde, "parquet")) {
+ return "read_parquet";
+ }
+ if (containsIgnoreCase(format, "json") || containsIgnoreCase(serde, "json")
+ || containsIgnoreCase(format, "hive")) {
+ return "read_json_auto";
+ }
+ return "read_csv_auto";
+ }
+
+ public static String readExpression(String readFn, String normalizedLocation) {
+ String escapedLocation = normalizedLocation.replace("'", "''");
+ String glob = escapedLocation + "/**";
+ if ("read_parquet".equals(readFn)) {
+ return "read_parquet('" + glob + "', union_by_name = true)";
+ }
+ return readFn + "('" + glob + "')";
+ }
+
+ /**
+ * The path to read for {@code table}, accounting for partition projection: see
+ * {@link PartitionProjection#readPath(Table, String)}.
+ */
+ public static String readPath(Table table, String normalizedLocation) {
+ return PartitionProjection.readPath(table, normalizedLocation);
+ }
+
+ /**
+ * Iceberg tables are not read via a Hive {@code InputFormat}/{@code SerializationLibrary}
+ * pair at all: pyiceberg and the AWS Glue-Iceberg integration leave those unset, so
+ * {@link #inferReadFunction} would otherwise fall through to {@code read_csv_auto} and fail
+ * on the table's binary Parquet data files, or a forced {@code read_parquet} would silently
+ * glob every data file ever written under the table's location, including ones no longer
+ * referenced by the current snapshot. Following the catalog's own {@code metadata_location}
+ * into {@code iceberg_scan} instead resolves the table through its real manifest list.
+ */
+ public static boolean isIcebergTable(Table table) {
+ return table != null
+ && table.getParameters() != null
+ && ICEBERG_TABLE_TYPE.equalsIgnoreCase(table.getParameters().get(PARAM_TABLE_TYPE));
+ }
+
+ public static String icebergMetadataLocation(Table table) {
+ return table.getParameters().get(PARAM_METADATA_LOCATION);
+ }
+
+ public static String icebergReadExpression(String metadataLocation) {
+ return "iceberg_scan('" + metadataLocation.replace("'", "''") + "')";
+ }
+
+ private static boolean containsIgnoreCase(String str, String sub) {
+ return str != null && str.toLowerCase(Locale.ROOT).contains(sub);
+ }
+
+ private static String quote(String id) {
+ return "\"" + id.replace("\"", "\"\"") + "\"";
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/athena/PartitionProjection.java b/src/main/java/io/github/hectorvent/floci/services/glue/PartitionProjection.java
similarity index 97%
rename from src/main/java/io/github/hectorvent/floci/services/athena/PartitionProjection.java
rename to src/main/java/io/github/hectorvent/floci/services/glue/PartitionProjection.java
index bb3d61d211..b76ff9dd94 100644
--- a/src/main/java/io/github/hectorvent/floci/services/athena/PartitionProjection.java
+++ b/src/main/java/io/github/hectorvent/floci/services/glue/PartitionProjection.java
@@ -1,4 +1,4 @@
-package io.github.hectorvent.floci.services.athena;
+package io.github.hectorvent.floci.services.glue;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.glue.model.Column;
@@ -16,7 +16,7 @@ import java.util.regex.Pattern;
* Partition projection: the table properties describing where a table's partitions live and what
* values they take, so the partitions need not be listed from the catalog or from storage.
*/
-final class PartitionProjection {
+public final class PartitionProjection {
/** Table property switching partition projection on. */
private static final String ENABLED = "projection.enabled";
@@ -80,7 +80,7 @@ final class PartitionProjection {
* them to the partitions a query actually needs requires that query's predicates, so the read
* stays wide and the query itself does the filtering.
*/
- static String readPath(Table table, String normalizedLocation) {
+ public static String readPath(Table table, String normalizedLocation) {
if (!enabled(table)) {
return normalizedLocation;
}
@@ -123,7 +123,7 @@ final class PartitionProjection {
* or a {@code GROUP BY}, so {@code SELECT tenant, count(*) FROM audit_events GROUP BY tenant}
* would pass while filtering nothing at all - exactly the case this exists to catch.
*/
- static void assertInjectedColumnsFiltered(String query, List<Table> tables) {
+ public static void assertInjectedColumnsFiltered(String query, List<Table> tables) {
if (query == null || tables == null) {
return;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java
new file mode 100644
index 0000000000..00dc83f760
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java
@@ -0,0 +1,153 @@
+package io.github.hectorvent.floci.services.redshift.proxy;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.model.CallerContext;
+import io.github.hectorvent.floci.services.iam.model.IamRole;
+import io.github.hectorvent.floci.services.s3.S3Service;
+
+import java.security.SecureRandom;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Role resolution and S3 authorization shared by {@code COPY}, {@code UNLOAD}, and Redshift
+ * Spectrum: validates an {@code IAM_ROLE} ARN against the cluster and Redshift's trust policy,
+ * mints a short-lived session, and evaluates the role's identity policy for one S3 action.
+ *
+ * <p>Extracted from {@link S3CopySimulator}, whose {@code S3TransferException} this still throws
+ * (same package, matching {@link ManifestReader}'s existing precedent for this kind of extraction).
+ */
+final class RedshiftRoleAccess {
+
+ private static final String SQLSTATE_INSUFFICIENT_PRIVILEGE = "42501";
+
+ private static final SecureRandom SECURE_RANDOM = new SecureRandom();
+ private static final String UPPER_ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
+ private static final String SECRET_CHARACTERS =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ /** COPY/UNLOAD is synchronous end-to-end; this only needs to outlive one statement. */
+ private static final Duration ROLE_SESSION_TTL = Duration.ofMinutes(5);
+
+ // S3Service's signed-request authorization only checks the bucket's resource policy: for a
+ // genuine HTTP request the identity-policy gate already happened upstream in
+ // IamEnforcementFilter before the request ever reached S3Service. This in-process call never
+ // goes through that filter, so the role's identity policy is evaluated here explicitly.
+ // Stateless (only needs an ObjectMapper), so a local instance avoids threading a new
+ // dependency through the whole proxy chain for this one check.
+ private static final IamPolicyEvaluator ROLE_POLICY_EVALUATOR = new IamPolicyEvaluator(new ObjectMapper());
+ private static final AssumeRolePolicyEvaluator ROLE_TRUST_POLICY_EVALUATOR =
+ new AssumeRolePolicyEvaluator(new ObjectMapper());
+
+ private RedshiftRoleAccess() {
+ }
+
+ record RoleSession(String accessKeyId, String sessionToken) {
+ }
+
+ /**
+ * Validates the role ARN, its account and Redshift trust policy, then mints a short-lived session.
+ */
+ static RoleSession resolveRoleSession(String iamRoleArn, IamService iamService,
+ String clusterAccountId, List<String> associatedRoleArns) {
+ AwsArnUtils.Arn parsed;
+ try {
+ parsed = AwsArnUtils.parse(iamRoleArn);
+ } catch (IllegalArgumentException e) {
+ throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
+ "IAM Role '" + iamRoleArn + "' could not be assumed: malformed ARN", e);
+ }
+ if (!"iam".equals(parsed.service()) || !parsed.resource().startsWith("role/")) {
+ throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
+ "IAM Role '" + iamRoleArn + "' could not be assumed: not an IAM role ARN", null);
+ }
+ if (clusterAccountId != null && !clusterAccountId.equals(parsed.accountId())) {
+ throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
+ "IAM Role '" + iamRoleArn + "' could not be assumed: cross-account role ARNs are not supported", null);
+ }
+ if (clusterAccountId != null && associatedRoleArns != null && !associatedRoleArns.contains(iamRoleArn)) {
+ throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
+ "IAM Role '" + iamRoleArn
+ + "' could not be assumed: role is not associated with the Redshift cluster", null);
+ }
+ String roleName = parsed.resource().substring(parsed.resource().lastIndexOf('/') + 1);
+ Optional<IamRole> role = iamService.findRole(parsed.accountId(), roleName);
+ if (role.isEmpty()) {
+ throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
+ "IAM Role '" + iamRoleArn + "' could not be assumed: role does not exist", null);
+ }
+ if (clusterAccountId != null
+ && !ROLE_TRUST_POLICY_EVALUATOR.allowsService(
+ role.get().getAssumeRolePolicyDocument(), "redshift.amazonaws.com")) {
+ throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
+ "IAM Role '" + iamRoleArn + "' could not be assumed: trust policy does not allow redshift.amazonaws.com",
+ null);
+ }
+
+ String accessKeyId = "ASIA" + randomString(UPPER_ALPHANUMERIC, 16);
+ // A session token is required: IamService.findSecretKey(accessKeyId, sessionToken) treats a
+ // null token on either side as a non-match, so a tokenless session can never be recognised
+ // as a known access key and every signed authorization call would fail closed.
+ String sessionToken = randomString(SECRET_CHARACTERS, 200);
+ iamService.registerSessionForAccount(parsed.accountId(), accessKeyId,
+ randomString(SECRET_CHARACTERS, 40), sessionToken, iamRoleArn,
+ Instant.now().plus(ROLE_SESSION_TTL), null);
+ return new RoleSession(accessKeyId, sessionToken);
+ }
+
+ static void releaseRoleSession(RoleSession roleSession, String iamRoleArn, IamService iamService) {
+ if (roleSession == null) {
+ return;
+ }
+ AwsArnUtils.Arn parsed = AwsArnUtils.parse(iamRoleArn);
+ iamService.unregisterSession(parsed.accountId(), roleSession.accessKeyId());
+ }
+
+ /**
+ * Evaluates the role's identity-based policy for one S3 action, skipped entirely when
+ * {@code FLOCI_SERVICES_S3_ENFORCE_AUTH} is off (matching the anonymous path's behavior).
+ */
+ static void authorizeRoleAction(S3Service s3, IamService iamService, String roleArn,
+ String action, String resourceArn) {
+ if (!s3.isAuthEnforced()) {
+ return;
+ }
+ CallerContext caller;
+ try {
+ caller = iamService.resolvePrincipalContext(roleArn);
+ } catch (AwsException e) {
+ throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
+ "IAM Role '" + roleArn + "' could not be assumed: " + e.getMessage(), e);
+ }
+ IamPolicyEvaluator.SimulationDecision decision =
+ ROLE_POLICY_EVALUATOR.simulatePrincipalPolicy(caller, action, resourceArn, Map.of());
+ if (decision != IamPolicyEvaluator.SimulationDecision.ALLOWED) {
+ throw new S3CopySimulator.S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
+ "S3 access denied for IAM Role '" + roleArn + "': " + action + " on " + resourceArn, null);
+ }
+ }
+
+ /** The bucket and object ARNs live in the role's partition: a China role authorizes China buckets. */
+ static String bucketArn(String roleArn, String bucket) {
+ return AwsArnUtils.Arn.global(AwsArnUtils.parse(roleArn).partition(), "s3", "", bucket).toString();
+ }
+
+ static String objectArn(String roleArn, String bucket, String key) {
+ return bucketArn(roleArn, bucket) + "/" + key;
+ }
+
+ private static String randomString(String characters, int length) {
+ StringBuilder value = new StringBuilder(length);
+ for (int i = 0; i < length; i++) {
+ value.append(characters.charAt(SECURE_RANDOM.nextInt(characters.length())));
+ }
+ return value.toString();
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/S3CopySimulator.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/S3CopySimulator.java
index af4e2f00fe..315521bd0f 100644
--- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/S3CopySimulator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/S3CopySimulator.java
@@ -1,13 +1,7 @@
package io.github.hectorvent.floci.services.redshift.proxy;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
-import io.github.hectorvent.floci.services.iam.AssumeRolePolicyEvaluator;
-import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
import io.github.hectorvent.floci.services.iam.IamService;
-import io.github.hectorvent.floci.services.iam.model.CallerContext;
-import io.github.hectorvent.floci.services.iam.model.IamRole;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import org.jboss.logging.Logger;
@@ -19,13 +13,9 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
-import java.security.SecureRandom;
-import java.time.Duration;
-import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import java.util.Optional;
import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;
import java.util.stream.Collectors;
@@ -67,130 +57,11 @@ public final class S3CopySimulator {
private static final String SQLSTATE_INSUFFICIENT_PRIVILEGE = "42501";
private static final String SQLSTATE_INTERNAL = "XX000";
- private static final SecureRandom SECURE_RANDOM = new SecureRandom();
- private static final String UPPER_ALPHANUMERIC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
- private static final String SECRET_CHARACTERS =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- /** COPY/UNLOAD is synchronous end-to-end; this only needs to outlive one statement. */
- private static final Duration ROLE_SESSION_TTL = Duration.ofMinutes(5);
-
- // S3Service's signed-request authorization only checks the bucket's resource policy: for a
- // genuine HTTP request the identity-policy gate already happened upstream in
- // IamEnforcementFilter before the request ever reached S3Service. This in-process call never
- // goes through that filter, so the role's identity policy is evaluated here explicitly.
- // Stateless (only needs an ObjectMapper), so a local instance avoids threading a new
- // dependency through the whole proxy chain for this one check.
- private static final IamPolicyEvaluator ROLE_POLICY_EVALUATOR = new IamPolicyEvaluator(new ObjectMapper());
- private static final AssumeRolePolicyEvaluator ROLE_TRUST_POLICY_EVALUATOR =
- new AssumeRolePolicyEvaluator(new ObjectMapper());
-
private S3CopySimulator() {
}
record CopyInput(CopyStatementParser.S3CopyFrom spec, List<String> keys, S3Service s3,
- IamService iamService, RoleSession roleSession) {
- }
-
- private record RoleSession(String accessKeyId, String sessionToken) {
- }
-
- /**
- * Validates the role ARN, its account and Redshift trust policy, then mints a short-lived session.
- */
- private static RoleSession resolveRoleSession(String iamRoleArn, IamService iamService,
- String clusterAccountId, List<String> associatedRoleArns) {
- AwsArnUtils.Arn parsed;
- try {
- parsed = AwsArnUtils.parse(iamRoleArn);
- } catch (IllegalArgumentException e) {
- throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
- "IAM Role '" + iamRoleArn + "' could not be assumed: malformed ARN", e);
- }
- if (!"iam".equals(parsed.service()) || !parsed.resource().startsWith("role/")) {
- throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
- "IAM Role '" + iamRoleArn + "' could not be assumed: not an IAM role ARN", null);
- }
- if (clusterAccountId != null && !clusterAccountId.equals(parsed.accountId())) {
- throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
- "IAM Role '" + iamRoleArn + "' could not be assumed: cross-account role ARNs are not supported", null);
- }
- if (clusterAccountId != null && associatedRoleArns != null && !associatedRoleArns.contains(iamRoleArn)) {
- throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
- "IAM Role '" + iamRoleArn
- + "' could not be assumed: role is not associated with the Redshift cluster", null);
- }
- String roleName = parsed.resource().substring(parsed.resource().lastIndexOf('/') + 1);
- Optional<IamRole> role = iamService.findRole(parsed.accountId(), roleName);
- if (role.isEmpty()) {
- throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
- "IAM Role '" + iamRoleArn + "' could not be assumed: role does not exist", null);
- }
- if (clusterAccountId != null
- && !ROLE_TRUST_POLICY_EVALUATOR.allowsService(
- role.get().getAssumeRolePolicyDocument(), "redshift.amazonaws.com")) {
- throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
- "IAM Role '" + iamRoleArn + "' could not be assumed: trust policy does not allow redshift.amazonaws.com",
- null);
- }
-
- String accessKeyId = "ASIA" + randomString(UPPER_ALPHANUMERIC, 16);
- // A session token is required: IamService.findSecretKey(accessKeyId, sessionToken) treats a
- // null token on either side as a non-match, so a tokenless session can never be recognised
- // as a known access key and every signed authorization call would fail closed.
- String sessionToken = randomString(SECRET_CHARACTERS, 200);
- iamService.registerSessionForAccount(parsed.accountId(), accessKeyId,
- randomString(SECRET_CHARACTERS, 40), sessionToken, iamRoleArn,
- Instant.now().plus(ROLE_SESSION_TTL), null);
- return new RoleSession(accessKeyId, sessionToken);
- }
-
- private static void releaseRoleSession(RoleSession roleSession, String iamRoleArn, IamService iamService) {
- if (roleSession == null) {
- return;
- }
- AwsArnUtils.Arn parsed = AwsArnUtils.parse(iamRoleArn);
- iamService.unregisterSession(parsed.accountId(), roleSession.accessKeyId());
- }
-
- /**
- * Evaluates the role's identity-based policy for one S3 action, skipped entirely when
- * {@code FLOCI_SERVICES_S3_ENFORCE_AUTH} is off (matching the anonymous path's behavior).
- */
- private static void authorizeRoleAction(S3Service s3, IamService iamService, String roleArn,
- String action, String resourceArn) {
- if (!s3.isAuthEnforced()) {
- return;
- }
- CallerContext caller;
- try {
- caller = iamService.resolvePrincipalContext(roleArn);
- } catch (AwsException e) {
- throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
- "IAM Role '" + roleArn + "' could not be assumed: " + e.getMessage(), e);
- }
- IamPolicyEvaluator.SimulationDecision decision =
- ROLE_POLICY_EVALUATOR.simulatePrincipalPolicy(caller, action, resourceArn, Map.of());
- if (decision != IamPolicyEvaluator.SimulationDecision.ALLOWED) {
- throw new S3TransferException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
- "S3 access denied for IAM Role '" + roleArn + "': " + action + " on " + resourceArn, null);
- }
- }
-
- /** The bucket and object ARNs live in the role's partition: a China role authorizes China buckets. */
- private static String bucketArn(String roleArn, String bucket) {
- return AwsArnUtils.Arn.global(AwsArnUtils.parse(roleArn).partition(), "s3", "", bucket).toString();
- }
-
- private static String objectArn(String roleArn, String bucket, String key) {
- return bucketArn(roleArn, bucket) + "/" + key;
- }
-
- private static String randomString(String characters, int length) {
- StringBuilder value = new StringBuilder(length);
- for (int i = 0; i < length; i++) {
- value.append(characters.charAt(SECURE_RANDOM.nextInt(characters.length())));
- }
- return value.toString();
+ IamService iamService, RedshiftRoleAccess.RoleSession roleSession) {
}
interface UnloadCollector extends AutoCloseable {
@@ -228,21 +99,23 @@ public final class S3CopySimulator {
static CopyInput prepareCopy(CopyStatementParser.S3CopyFrom spec, S3Service s3, IamService iamService,
String clusterAccountId, List<String> associatedRoleArns) {
- RoleSession roleSession = spec.iamRoleArn() != null
- ? resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId, associatedRoleArns)
+ RedshiftRoleAccess.RoleSession roleSession = spec.iamRoleArn() != null
+ ? RedshiftRoleAccess.resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId, associatedRoleArns)
: null;
try {
try {
if (spec.manifest()) {
if (roleSession != null) {
- authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject", objectArn(spec.iamRoleArn(), spec.bucket(), spec.keyOrPrefix()));
+ RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject",
+ RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), spec.keyOrPrefix()));
s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), spec.keyOrPrefix());
} else {
s3.authorizeAnonymousGetObject(spec.bucket(), spec.keyOrPrefix());
}
} else {
if (roleSession != null) {
- authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket", bucketArn(spec.iamRoleArn(), spec.bucket()));
+ RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket",
+ RedshiftRoleAccess.bucketArn(spec.iamRoleArn(), spec.bucket()));
s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket());
} else {
s3.authorizeAnonymousListBucket(spec.bucket());
@@ -268,7 +141,8 @@ public final class S3CopySimulator {
try {
for (String key : keys) {
if (roleSession != null) {
- authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject", objectArn(spec.iamRoleArn(), spec.bucket(), key));
+ RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject",
+ RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), key));
s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key);
} else {
s3.authorizeAnonymousGetObject(spec.bucket(), key);
@@ -280,7 +154,7 @@ public final class S3CopySimulator {
}
return new CopyInput(spec, List.copyOf(keys), s3, iamService, roleSession);
} catch (RuntimeException e) {
- releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
+ RedshiftRoleAccess.releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
throw e;
}
}
@@ -302,7 +176,7 @@ public final class S3CopySimulator {
}
static void releaseCopySession(CopyInput input) {
- releaseRoleSession(input.roleSession(), input.spec().iamRoleArn(), input.iamService());
+ RedshiftRoleAccess.releaseRoleSession(input.roleSession(), input.spec().iamRoleArn(), input.iamService());
}
static UnloadCollector prepareUnload(CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService) {
@@ -316,21 +190,24 @@ public final class S3CopySimulator {
static UnloadCollector prepareUnload(CopyStatementParser.S3Unload spec, S3Service s3, IamService iamService,
String clusterAccountId, List<String> associatedRoleArns) {
- RoleSession roleSession = spec.iamRoleArn() != null
- ? resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId, associatedRoleArns)
+ RedshiftRoleAccess.RoleSession roleSession = spec.iamRoleArn() != null
+ ? RedshiftRoleAccess.resolveRoleSession(spec.iamRoleArn(), iamService, clusterAccountId, associatedRoleArns)
: null;
String probeKey = unloadDataKey(spec, 0);
try {
if (roleSession != null) {
- authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.iamRoleArn(), spec.bucket(), probeKey));
+ RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject",
+ RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), probeKey));
s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), probeKey);
if (spec.manifest()) {
String manifestKey = spec.prefix() + "manifest";
- authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.iamRoleArn(), spec.bucket(), manifestKey));
+ RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject",
+ RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), manifestKey));
s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), manifestKey);
}
if (!spec.allowOverwrite()) {
- authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket", bucketArn(spec.iamRoleArn(), spec.bucket()));
+ RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:ListBucket",
+ RedshiftRoleAccess.bucketArn(spec.iamRoleArn(), spec.bucket()));
s3.authorizeSignedListBucket(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket());
if (targetPrefixHasObjects(spec, s3)) {
throw new S3TransferException(SQLSTATE_INTERNAL,
@@ -353,15 +230,15 @@ public final class S3CopySimulator {
}
}
} catch (AwsException e) {
- releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
+ RedshiftRoleAccess.releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
throw new S3TransferException(unloadWriteSqlState(e), unloadWriteMessage(e, spec), e);
} catch (RuntimeException e) {
- releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
+ RedshiftRoleAccess.releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
throw e;
}
if (!UNLOAD_HEAP_MIB.tryAcquire(UNLOAD_INITIAL_MIB)) {
- releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
+ RedshiftRoleAccess.releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
throw new S3TransferException(SQLSTATE_CONFIGURATION_LIMIT_EXCEEDED,
"UNLOAD memory budget exhausted; retry shortly", null);
}
@@ -369,7 +246,7 @@ public final class S3CopySimulator {
return new S3UnloadCollector(spec, s3, iamService, roleSession);
} catch (IOException e) {
UNLOAD_HEAP_MIB.release(UNLOAD_INITIAL_MIB);
- releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
+ RedshiftRoleAccess.releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
throw new S3TransferException(SQLSTATE_INTERNAL, "UNLOAD failed: " + e.getMessage(), e);
}
}
@@ -554,12 +431,13 @@ public final class S3CopySimulator {
}
private static void streamObjects(CopyStatementParser.S3CopyFrom spec, List<String> discoveredColumns,
- S3Service s3, IamService iamService, RoleSession roleSession,
+ S3Service s3, IamService iamService, RedshiftRoleAccess.RoleSession roleSession,
List<String> keys, OutputStream backendOut) throws IOException {
byte[] buffer = new byte[CHUNK];
for (int i = 0; i < keys.size(); i++) {
if (roleSession != null) {
- authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject", objectArn(spec.iamRoleArn(), spec.bucket(), keys.get(i)));
+ RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:GetObject",
+ RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), keys.get(i)));
s3.authorizeSignedGetObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), keys.get(i));
} else {
s3.authorizeAnonymousGetObject(spec.bucket(), keys.get(i));
@@ -1037,7 +915,7 @@ public final class S3CopySimulator {
private final CopyStatementParser.S3Unload spec;
private final S3Service s3;
private final IamService iamService;
- private final RoleSession roleSession;
+ private final RedshiftRoleAccess.RoleSession roleSession;
private final long threshold;
private final String contentType;
private final List<String> writtenKeys = new ArrayList<>();
@@ -1060,7 +938,7 @@ public final class S3CopySimulator {
private int heldMib = UNLOAD_INITIAL_MIB;
private S3UnloadCollector(CopyStatementParser.S3Unload spec, S3Service s3,
- IamService iamService, RoleSession roleSession) throws IOException {
+ IamService iamService, RedshiftRoleAccess.RoleSession roleSession) throws IOException {
this.spec = spec;
this.s3 = s3;
this.iamService = iamService;
@@ -1131,7 +1009,8 @@ public final class S3CopySimulator {
try {
String key = spec.prefix() + "manifest";
if (roleSession != null) {
- authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.iamRoleArn(), spec.bucket(), key));
+ RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject",
+ RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), key));
s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key);
} else {
s3.authorizeAnonymousPutObject(spec.bucket(), key);
@@ -1169,7 +1048,7 @@ public final class S3CopySimulator {
}
UNLOAD_HEAP_MIB.release(heldMib);
heldMib = 0;
- releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
+ RedshiftRoleAccess.releaseRoleSession(roleSession, spec.iamRoleArn(), iamService);
closed = true;
}
@@ -1194,7 +1073,8 @@ public final class S3CopySimulator {
String key = unloadDataKey(spec, index);
try {
if (roleSession != null) {
- authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject", objectArn(spec.iamRoleArn(), spec.bucket(), key));
+ RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:PutObject",
+ RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), key));
s3.authorizeSignedPutObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), key);
} else {
s3.authorizeAnonymousPutObject(spec.bucket(), key);
@@ -1303,7 +1183,7 @@ public final class S3CopySimulator {
private static void deleteWritten(S3Service s3, IamService iamService,
CopyStatementParser.S3Unload spec, List<String> keys,
- RoleSession roleSession) {
+ RedshiftRoleAccess.RoleSession roleSession) {
if (spec.allowOverwrite()) {
// Under ALLOWOVERWRITE a slice key may have replaced a pre-existing object, and there is no
// reliable way to tell an overwrite from a fresh write (the check and the write are not
@@ -1318,7 +1198,8 @@ public final class S3CopySimulator {
for (String k : keys) {
try {
if (roleSession != null) {
- authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:DeleteObject", objectArn(spec.iamRoleArn(), spec.bucket(), k));
+ RedshiftRoleAccess.authorizeRoleAction(s3, iamService, spec.iamRoleArn(), "s3:DeleteObject",
+ RedshiftRoleAccess.objectArn(spec.iamRoleArn(), spec.bucket(), k));
s3.authorizeSignedDeleteObject(roleSession.accessKeyId(), roleSession.sessionToken(), spec.bucket(), k);
} else {
s3.authorizeAnonymousDeleteObject(spec.bucket(), k);
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index decccea277..7f495bce67 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -111,7 +111,7 @@ quarkus:
- --initialize-at-run-time=io.github.hectorvent.floci.services.lambda.launcher.LambdaExecutionRoleCredentials
- --initialize-at-run-time=io.github.hectorvent.floci.services.ecs.container.EcsTaskRoleCredentials
- --initialize-at-run-time=io.github.hectorvent.floci.services.ssoportal.SsoPortalService
- - --initialize-at-run-time=io.github.hectorvent.floci.services.redshift.proxy.S3CopySimulator
+ - --initialize-at-run-time=io.github.hectorvent.floci.services.redshift.proxy.RedshiftRoleAccess
- --initialize-at-run-time=io.github.hectorvent.floci.services.redshift.spectrum.SpectrumMaterializer
- --initialize-at-run-time=io.github.hectorvent.floci.services.ecs.exec.EcsExecSessionRegistry
# snappy-java (Firehose Snappy/HADOOP_SNAPPY delivery) extracts and loads a
diff --git a/src/test/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilderTest.java b/src/test/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilderTest.java
index 48e88ec356..4461eabb52 100644
--- a/src/test/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilderTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/athena/GlueViewDdlBuilderTest.java
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.athena;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.glue.GlueService;
+import io.github.hectorvent.floci.services.glue.GlueTableResolver;
import io.github.hectorvent.floci.services.glue.model.Column;
import io.github.hectorvent.floci.services.glue.model.Database;
import io.github.hectorvent.floci.services.glue.model.StorageDescriptor;
@@ -368,21 +369,21 @@ class GlueViewDdlBuilderTest {
@Test
void testIsIcebergTableDetection() {
- assertFalse(GlueViewDdlBuilder.isIcebergTable(null));
- assertFalse(GlueViewDdlBuilder.isIcebergTable(createTable("t", "s3://b/t", null, null)));
+ assertFalse(GlueTableResolver.isIcebergTable(null));
+ assertFalse(GlueTableResolver.isIcebergTable(createTable("t", "s3://b/t", null, null)));
Table table = createTable("t", "s3://b/t", null, null);
table.setParameters(Map.of("table_type", "iceberg"));
- assertTrue(GlueViewDdlBuilder.isIcebergTable(table), "table_type comparison should be case-insensitive");
+ assertTrue(GlueTableResolver.isIcebergTable(table), "table_type comparison should be case-insensitive");
table.setParameters(Map.of("table_type", "EXTERNAL_TABLE"));
- assertFalse(GlueViewDdlBuilder.isIcebergTable(table));
+ assertFalse(GlueTableResolver.isIcebergTable(table));
}
@Test
void testIcebergReadExpressionEscapesSingleQuotes() {
assertEquals("iceberg_scan('s3://bucket/it''s-a-table/metadata/x.json')",
- GlueViewDdlBuilder.icebergReadExpression("s3://bucket/it's-a-table/metadata/x.json"));
+ GlueTableResolver.icebergReadExpression("s3://bucket/it's-a-table/metadata/x.json"));
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/glue/GlueTableResolverTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/GlueTableResolverTest.java
new file mode 100644
index 0000000000..e9f46f51d9
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/glue/GlueTableResolverTest.java
@@ -0,0 +1,67 @@
+package io.github.hectorvent.floci.services.glue;
+
+import io.github.hectorvent.floci.services.glue.model.Column;
+import io.github.hectorvent.floci.services.glue.model.StorageDescriptor;
+import io.github.hectorvent.floci.services.glue.model.Table;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.is;
+
+class GlueTableResolverTest {
+
+ @Test
+ void inferReadFunctionDetectsParquetFromInputFormat() {
+ StorageDescriptor sd = new StorageDescriptor();
+ sd.setInputFormat("org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat");
+ Table table = new Table();
+ table.setStorageDescriptor(sd);
+
+ assertThat(GlueTableResolver.inferReadFunction(table), equalTo("read_parquet"));
+ }
+
+ @Test
+ void inferReadFunctionDefaultsToCsvAutoForNullTable() {
+ assertThat(GlueTableResolver.inferReadFunction(null), equalTo("read_csv_auto"));
+ }
+
+ @Test
+ void readExpressionEscapesSingleQuotesInLocation() {
+ String expr = GlueTableResolver.readExpression("read_csv_auto", "s3://bucket/o'brien");
+ assertThat(expr, equalTo("read_csv_auto('s3://bucket/o''brien/**')"));
+ }
+
+ @Test
+ void readExpressionForParquetAddsUnionByName() {
+ String expr = GlueTableResolver.readExpression("read_parquet", "s3://bucket/data");
+ assertThat(expr, equalTo("read_parquet('s3://bucket/data/**', union_by_name = true)"));
+ }
+
+ @Test
+ void buildProjectionReturnsStarForTableWithNoDeclaredColumns() {
+ Table table = new Table();
+ table.setStorageDescriptor(new StorageDescriptor());
+
+ assertThat(GlueTableResolver.buildProjection(table), equalTo("*"));
+ }
+
+ @Test
+ void buildProjectionQuotesDeclaredColumnNames() {
+ Column tenantId = new Column();
+ tenantId.setName("tenantId");
+ StorageDescriptor sd = new StorageDescriptor();
+ sd.setColumns(List.of(tenantId));
+ Table table = new Table();
+ table.setStorageDescriptor(sd);
+
+ assertThat(GlueTableResolver.buildProjection(table), equalTo("\"tenantId\" AS \"tenantId\""));
+ }
+
+ @Test
+ void isIcebergTableFalseWhenParametersMissing() {
+ assertThat(GlueTableResolver.isIcebergTable(new Table()), is(false));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/athena/PartitionProjectionTest.java b/src/test/java/io/github/hectorvent/floci/services/glue/PartitionProjectionTest.java
similarity index 99%
rename from src/test/java/io/github/hectorvent/floci/services/athena/PartitionProjectionTest.java
rename to src/test/java/io/github/hectorvent/floci/services/glue/PartitionProjectionTest.java
index ce8815a129..052fcb971e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/athena/PartitionProjectionTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/glue/PartitionProjectionTest.java
@@ -1,4 +1,4 @@
-package io.github.hectorvent.floci.services.athena;
+package io.github.hectorvent.floci.services.glue;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.glue.model.Column;
diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccessTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccessTest.java
new file mode 100644
index 0000000000..4cf4415df2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccessTest.java
@@ -0,0 +1,50 @@
+package io.github.hectorvent.floci.services.redshift.proxy;
+
+import io.github.hectorvent.floci.services.iam.IamService;
+import io.github.hectorvent.floci.services.iam.model.CallerContext;
+import io.github.hectorvent.floci.services.s3.S3Service;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+class RedshiftRoleAccessTest {
+
+ @Test
+ void authorizeRoleActionThrowsWhenEnforcedPolicyDeniesTheAction() {
+ S3Service s3 = mock(S3Service.class);
+ when(s3.isAuthEnforced()).thenReturn(true);
+ IamService iamService = mock(IamService.class);
+ String roleArn = "arn:aws:iam::111111111111:role/spectrum-role";
+ // An empty identity-policy list simulates a role with no attached grants, so
+ // simulatePrincipalPolicy never finds an Allow for any action.
+ when(iamService.resolvePrincipalContext(roleArn)).thenReturn(CallerContext.of(List.of()));
+
+ S3CopySimulator.S3TransferException exception = assertThrows(S3CopySimulator.S3TransferException.class,
+ () -> RedshiftRoleAccess.authorizeRoleAction(s3, iamService, roleArn, "s3:GetObject",
+ "arn:aws:s3:::bucket/key"));
+
+ assertThat(exception.sqlState(), equalTo("42501"));
+ assertThat(exception.getMessage(), containsString("S3 access denied"));
+ }
+
+ @Test
+ void authorizeRoleActionSkipsCheckWhenEnforcementDisabled() {
+ S3Service s3 = mock(S3Service.class);
+ when(s3.isAuthEnforced()).thenReturn(false);
+ IamService iamService = mock(IamService.class);
+
+ RedshiftRoleAccess.authorizeRoleAction(s3, iamService, "arn:aws:iam::111111111111:role/x",
+ "s3:GetObject", "arn:aws:s3:::bucket/key");
+
+ // No exception, and resolvePrincipalContext is never consulted when enforcement is off.
+ verifyNoInteractions(iamService);
+ }
+}
diff --git a/tools/partition/baseline.tsv b/tools/partition/baseline.tsv
index 41ca8099a0..3afc379157 100644
--- a/tools/partition/baseline.tsv
+++ b/tools/partition/baseline.tsv
@@ -20,7 +20,7 @@ dns-suffix src/main/java/io/github/hectorvent/floci/services/iam/SAMLAssertionVe
dns-suffix src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java 2
dns-suffix src/main/java/io/github/hectorvent/floci/services/macie2/MacieController.java 1
dns-suffix src/main/java/io/github/hectorvent/floci/services/ram/RamController.java 2
-dns-suffix src/main/java/io/github/hectorvent/floci/services/redshift/proxy/S3CopySimulator.java 2
+dns-suffix src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java 2
dns-suffix src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java 1
dns-suffix src/main/java/io/github/hectorvent/floci/services/signin/SigninService.java 1
dns-suffix src/main/java/io/github/hectorvent/floci/services/ssoportal/SsoPortalService.java 1