mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
feat(redshift): sign the Spectrum floci-duck transfer with the role session when S3 auth is enforced (#7162)
This commit is contained in:
1 parent
6d71c3599d
commit
cedc1073ec
16 files changed
+843
-32
No files matched your search
@@ -23,6 +23,7 @@ import io.github.hectorvent.floci.services.iam.ScpProvider;
|
||||
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.S3ObjectActions;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
|
||||
import io.vertx.core.http.HttpServerRequest;
|
||||
import io.vertx.ext.web.RoutingContext;
|
||||
@@ -213,6 +214,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
/** The clock {@link IamService} measures session expiry on, so both read the same time. */
|
||||
private final Clock clock;
|
||||
private final ResourceInfo resourceInfo;
|
||||
private final Instance<S3Service> s3ServiceProvider;
|
||||
|
||||
@Inject
|
||||
public IamEnforcementFilter(EmulatorConfig config,
|
||||
@@ -232,7 +234,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
Instance<ResourcePolicyProvider> resourcePolicyProviders,
|
||||
Instance<PassedRoleLookup> passedRoleLookups,
|
||||
Clock clock,
|
||||
@Context ResourceInfo resourceInfo) {
|
||||
@Context ResourceInfo resourceInfo,
|
||||
Instance<S3Service> s3ServiceProvider) {
|
||||
this.config = config;
|
||||
this.accountResolver = accountResolver;
|
||||
this.iamService = iamService;
|
||||
@@ -251,6 +254,32 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
this.passedRoleLookups = passedRoleLookups;
|
||||
this.clock = clock;
|
||||
this.resourceInfo = resourceInfo;
|
||||
this.s3ServiceProvider = s3ServiceProvider;
|
||||
}
|
||||
|
||||
/** Package-private constructor for callers predating s3ServiceProvider. */
|
||||
IamEnforcementFilter(EmulatorConfig config,
|
||||
AccountResolver accountResolver,
|
||||
IamService iamService,
|
||||
IamPolicyEvaluator evaluator,
|
||||
IamActionRegistry actionRegistry,
|
||||
AwsQueryServiceResolver queryServiceResolver,
|
||||
ResourceArnBuilder arnBuilder,
|
||||
RequestContext requestContext,
|
||||
IamConditionContextResolver conditionContextResolver,
|
||||
CloudTrailService cloudTrailService,
|
||||
CurrentVertxRequest currentVertxRequest,
|
||||
ResolvedServiceCatalog catalog,
|
||||
Instance<ScpProvider> scpProvider,
|
||||
SessionAccountLookup sessionAccountLookup,
|
||||
Instance<ResourcePolicyProvider> resourcePolicyProviders,
|
||||
Instance<PassedRoleLookup> passedRoleLookups,
|
||||
Clock clock,
|
||||
ResourceInfo resourceInfo) {
|
||||
this(config, accountResolver, iamService, evaluator, actionRegistry,
|
||||
queryServiceResolver, arnBuilder, requestContext,
|
||||
conditionContextResolver, cloudTrailService, currentVertxRequest, catalog,
|
||||
scpProvider, sessionAccountLookup, resourcePolicyProviders, passedRoleLookups, clock, resourceInfo, null);
|
||||
}
|
||||
|
||||
/** Package-private constructor for callers predating Query dispatch-aware enforcement. */
|
||||
@@ -271,7 +300,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
this(config, accountResolver, iamService, evaluator, actionRegistry,
|
||||
new AwsQueryServiceResolver(catalog), arnBuilder, requestContext,
|
||||
conditionContextResolver, cloudTrailService, currentVertxRequest, catalog,
|
||||
scpProvider, sessionAccountLookup, resourcePolicyProviders, null, Clock.systemUTC(), null);
|
||||
scpProvider, sessionAccountLookup, resourcePolicyProviders, null, Clock.systemUTC(), null, null);
|
||||
}
|
||||
|
||||
/** Package-private constructor for callers predating resourcePolicyProviders. */
|
||||
@@ -291,7 +320,29 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
this(config, accountResolver, iamService, evaluator, actionRegistry,
|
||||
new AwsQueryServiceResolver(catalog), arnBuilder, requestContext,
|
||||
conditionContextResolver, cloudTrailService, currentVertxRequest, catalog,
|
||||
scpProvider, sessionAccountLookup, null, null, Clock.systemUTC(), null);
|
||||
scpProvider, sessionAccountLookup, null, null, Clock.systemUTC(), null, null);
|
||||
}
|
||||
|
||||
/** Package-private constructor for testing with S3Service. */
|
||||
IamEnforcementFilter(EmulatorConfig config,
|
||||
AccountResolver accountResolver,
|
||||
IamService iamService,
|
||||
IamPolicyEvaluator evaluator,
|
||||
IamActionRegistry actionRegistry,
|
||||
ResourceArnBuilder arnBuilder,
|
||||
RequestContext requestContext,
|
||||
IamConditionContextResolver conditionContextResolver,
|
||||
CloudTrailService cloudTrailService,
|
||||
CurrentVertxRequest currentVertxRequest,
|
||||
ResolvedServiceCatalog catalog,
|
||||
Instance<ScpProvider> scpProvider,
|
||||
SessionAccountLookup sessionAccountLookup,
|
||||
Instance<ResourcePolicyProvider> resourcePolicyProviders,
|
||||
Instance<S3Service> s3ServiceProvider) {
|
||||
this(config, accountResolver, iamService, evaluator, actionRegistry,
|
||||
new AwsQueryServiceResolver(catalog), arnBuilder, requestContext,
|
||||
conditionContextResolver, cloudTrailService, currentVertxRequest, catalog,
|
||||
scpProvider, sessionAccountLookup, resourcePolicyProviders, null, Clock.systemUTC(), null, s3ServiceProvider);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -506,6 +557,14 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
conditionContext = conditionContext == null ? new HashMap<>() : new HashMap<>(conditionContext);
|
||||
callerArns.get().putPrincipalKeys(conditionContext);
|
||||
}
|
||||
// Floci Spectrum transfer writes internal materialization to its own scratch bucket under the minted
|
||||
// role session key. Since AWS Spectrum has no S3 write, this transfer is internal and must not be
|
||||
// evaluated against the role's policies, permissions boundary, or SCPs (which often enforce read-only
|
||||
// on data lake buckets). Tying authorization ahead of role policies directly to the minted transfer key
|
||||
// and scratch key ensures boundary/SCP checks apply only to the actual S3 source reads.
|
||||
if (isSpectrumScratchTransfer(credentialScope, action, resources, akid, callerArns.orElse(null))) {
|
||||
return;
|
||||
}
|
||||
// A create that carries tags is checked with them where its own action takes them, as the tagging
|
||||
// action it also needs is (see TagOnCreate); keys the service's own resolver gives are kept.
|
||||
Optional<TagOnCreate.Tagging> tagOnCreate = TagOnCreate.of(resolvedAuthorization.operation(), ctx);
|
||||
@@ -658,6 +717,14 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
// presigned URLs add, is a DeleteObject.
|
||||
private static final Set<String> NON_DELETE_OBJECT_SUBRESOURCES = Set.of("uploadId", "tagging", "annotation");
|
||||
|
||||
private static final Set<String> SPECTRUM_SCRATCH_ACTIONS =
|
||||
Set.of("s3:PutObject", "s3:DeleteObject", "s3:AbortMultipartUpload");
|
||||
|
||||
private static final Pattern SPECTRUM_SCRATCH_OBJECT = Pattern.compile(
|
||||
"arn:" + AwsArnUtils.PARTITION_REGEX + ":s3:::"
|
||||
+ Pattern.quote(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET)
|
||||
+ "/spectrum-[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}\\.csv");
|
||||
|
||||
private static final Set<String> GOVERNANCE_BYPASS_ACTIONS =
|
||||
Set.of("s3:PutObjectRetention", "s3:DeleteObject", "s3:DeleteObjectVersion");
|
||||
|
||||
@@ -698,6 +765,35 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
|
||||
return "POST".equalsIgnoreCase(ctx.getMethod()) && namesUpload && !params.containsKey("uploads");
|
||||
}
|
||||
|
||||
/**
|
||||
* A write or delete of the scratch object in the Spectrum scratch bucket by the exact assumed-role
|
||||
* session running that transfer. The transfer is Floci's own, so it is authorized ahead of the
|
||||
* role's policies and permissions boundaries; any other action, bucket, key or session stays
|
||||
* under normal policy evaluation.
|
||||
*/
|
||||
private boolean isSpectrumScratchTransfer(String credentialScope, String action,
|
||||
List<String> resources, String akid,
|
||||
CallerArns callerArns) {
|
||||
if (!"s3".equals(credentialScope) || akid == null || callerArns == null
|
||||
|| !CallerArns.TYPE_ASSUMED_ROLE.equals(callerArns.principalType())
|
||||
|| !SPECTRUM_SCRATCH_ACTIONS.contains(action) || resources.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
if (s3ServiceProvider != null && s3ServiceProvider.isResolvable()
|
||||
&& !s3ServiceProvider.get().isSpectrumScratchBucket(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET)) {
|
||||
return false;
|
||||
}
|
||||
Optional<String> allowedScratchArn = iamService.spectrumScratchResourceArn(akid);
|
||||
if (allowedScratchArn.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String expectedArn = allowedScratchArn.get();
|
||||
if (!SPECTRUM_SCRATCH_OBJECT.matcher(expectedArn).matches()) {
|
||||
return false;
|
||||
}
|
||||
return resources.stream().allMatch(expectedArn::equals);
|
||||
}
|
||||
|
||||
/**
|
||||
* PutObject and CopyObject (a PUT naming no uploadId, which would make it UploadPart) and
|
||||
* CreateMultipartUpload (a POST naming {@code uploads}): the operations checked as
|
||||
|
||||
@@ -73,9 +73,19 @@ public class FlociDuckClient {
|
||||
* default account.
|
||||
*/
|
||||
public void execute(String sql, String setupDdl, String outputS3Path, String accessKeyId) {
|
||||
execute(sql, setupDdl, outputS3Path, accessKeyId, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Variant of {@link #execute(String, String, String, String)} that passes
|
||||
* explicit credentials (including session token for SigV4 authentication).
|
||||
*/
|
||||
public void execute(String sql, String setupDdl, String outputS3Path,
|
||||
String accessKeyId, String secretAccessKey, String sessionToken) {
|
||||
String duckUrl = duckManager.ensureReady();
|
||||
|
||||
Map<String, Object> body = buildBaseBody(sql, setupDdl, accessKeyId);
|
||||
String effectiveSetup = injectSessionToken(setupDdl, sessionToken);
|
||||
Map<String, Object> body = buildBaseBody(sql, effectiveSetup, accessKeyId, secretAccessKey);
|
||||
if (outputS3Path != null) {
|
||||
body.put("output_s3_path", outputS3Path);
|
||||
}
|
||||
@@ -101,21 +111,43 @@ public class FlociDuckClient {
|
||||
* {@link #execute(String, String, String, String)} for details.
|
||||
*/
|
||||
public List<Map<String, Object>> query(String sql, String setupDdl, String accessKeyId) {
|
||||
return query(sql, setupDdl, accessKeyId, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Variant of {@link #query(String, String, String)} that passes
|
||||
* explicit credentials (including session token for SigV4 authentication).
|
||||
*/
|
||||
public List<Map<String, Object>> query(String sql, String setupDdl,
|
||||
String accessKeyId, String secretAccessKey, String sessionToken) {
|
||||
String duckUrl = duckManager.ensureReady();
|
||||
|
||||
Map<String, Object> body = buildBaseBody(sql, setupDdl, accessKeyId);
|
||||
String effectiveSetup = injectSessionToken(setupDdl, sessionToken);
|
||||
Map<String, Object> body = buildBaseBody(sql, effectiveSetup, accessKeyId, secretAccessKey);
|
||||
|
||||
String responseBody = post(duckUrl + "/query", body, "query");
|
||||
return parseQueryRows(responseBody);
|
||||
}
|
||||
|
||||
static String injectSessionToken(String setupDdl, String sessionToken) {
|
||||
if (sessionToken == null || sessionToken.isBlank()) {
|
||||
return setupDdl;
|
||||
}
|
||||
String setToken = "SET s3_session_token = '" + sessionToken.replace("'", "''") + "';\n";
|
||||
return setupDdl == null || setupDdl.isBlank() ? setToken : setToken + setupDdl;
|
||||
}
|
||||
|
||||
// ── internals ─────────────────────────────────────────────────────────────
|
||||
|
||||
private Map<String, Object> buildBaseBody(String sql, String setupDdl) {
|
||||
return buildBaseBody(sql, setupDdl, null);
|
||||
return buildBaseBody(sql, setupDdl, null, null);
|
||||
}
|
||||
|
||||
private Map<String, Object> buildBaseBody(String sql, String setupDdl, String accessKeyId) {
|
||||
return buildBaseBody(sql, setupDdl, accessKeyId, null);
|
||||
}
|
||||
|
||||
private Map<String, Object> buildBaseBody(String sql, String setupDdl, String accessKeyId, String secretAccessKey) {
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("sql", sql);
|
||||
if (setupDdl != null && !setupDdl.isBlank()) {
|
||||
@@ -127,7 +159,7 @@ public class FlociDuckClient {
|
||||
// matching account partition for any S3 read/write the SQL performs.
|
||||
// Anything else falls back to the configured default account.
|
||||
body.put("s3_access_key", accessKeyId == null || accessKeyId.isEmpty() ? "test" : accessKeyId);
|
||||
body.put("s3_secret_key", "test");
|
||||
body.put("s3_secret_key", secretAccessKey == null || secretAccessKey.isEmpty() ? "test" : secretAccessKey);
|
||||
body.put("s3_url_style", "path");
|
||||
return body;
|
||||
}
|
||||
|
||||
@@ -4828,6 +4828,31 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
session.getPresignedAction(), session.getPresignedResourceArn()));
|
||||
}
|
||||
|
||||
/** Binds a Redshift Spectrum scratch object ARN to an active transfer role session. */
|
||||
public void registerSpectrumScratchResource(String accessKeyId, String resourceArn) {
|
||||
currentSession(accessKeyId).ifPresent(session -> {
|
||||
session.setSpectrumScratchResourceArn(resourceArn);
|
||||
String accountId = session.getOriginAccountId() != null ? session.getOriginAccountId() : "000000000000";
|
||||
putSessionForAccount(accountId, accessKeyId, session);
|
||||
});
|
||||
}
|
||||
|
||||
/** Clears the Spectrum scratch object permission from the session when the transfer completes. */
|
||||
public void clearSpectrumScratchResource(String accessKeyId) {
|
||||
currentSession(accessKeyId).ifPresent(session -> {
|
||||
session.setSpectrumScratchResourceArn(null);
|
||||
String accountId = session.getOriginAccountId() != null ? session.getOriginAccountId() : "000000000000";
|
||||
putSessionForAccount(accountId, accessKeyId, session);
|
||||
});
|
||||
}
|
||||
|
||||
/** The exact scratch object ARN permitted for this session, if it is a Spectrum transfer session. */
|
||||
public Optional<String> spectrumScratchResourceArn(String accessKeyId) {
|
||||
return currentSession(accessKeyId)
|
||||
.map(SessionCredential::getSpectrumScratchResourceArn)
|
||||
.filter(arn -> arn != null && !arn.isBlank());
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores a non-expiring session for a Lambda execution role under the function's account.
|
||||
* Lambda launches can happen outside request scope, so the account namespace must be explicit.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.iam.model;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -47,6 +48,13 @@ public record CallerContext(
|
||||
return new CallerContext(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, levels, principalArn);
|
||||
}
|
||||
|
||||
/** Copy of this context with one more identity policy, evaluated like the caller's own. */
|
||||
public CallerContext withIdentityPolicy(String policyDocument) {
|
||||
List<String> policies = new ArrayList<>(identityPolicies);
|
||||
policies.add(policyDocument);
|
||||
return new CallerContext(policies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels, principalArn);
|
||||
}
|
||||
|
||||
/** Copy of this context with the caller principal ARN attached. */
|
||||
public CallerContext withPrincipalArn(String principalArn) {
|
||||
return new CallerContext(identityPolicies, sessionPolicyDocument, boundaryPolicyDocument, scpLevels, principalArn);
|
||||
|
||||
@@ -34,6 +34,8 @@ public class SessionCredential {
|
||||
/** Exact object action and ARN for an internally generated S3 presigned URL. */
|
||||
private String presignedAction;
|
||||
private String presignedResourceArn;
|
||||
/** Exact scratch object ARN permitted for an internal Redshift Spectrum transfer session. */
|
||||
private String spectrumScratchResourceArn;
|
||||
/**
|
||||
* The long-term identity whose key minted this session through GetSessionToken or
|
||||
* GetFederationToken: an IAM user's ARN, or the account root's. Null for every other session.
|
||||
@@ -139,6 +141,11 @@ public class SessionCredential {
|
||||
public String getPresignedResourceArn() { return presignedResourceArn; }
|
||||
public void setPresignedResourceArn(String presignedResourceArn) { this.presignedResourceArn = presignedResourceArn; }
|
||||
|
||||
public String getSpectrumScratchResourceArn() { return spectrumScratchResourceArn; }
|
||||
public void setSpectrumScratchResourceArn(String spectrumScratchResourceArn) {
|
||||
this.spectrumScratchResourceArn = spectrumScratchResourceArn;
|
||||
}
|
||||
|
||||
public boolean isLambdaExecutionRole() { return lambdaExecutionRole; }
|
||||
public void setLambdaExecutionRole(boolean lambdaExecutionRole) { this.lambdaExecutionRole = lambdaExecutionRole; }
|
||||
|
||||
|
||||
+9
-3
@@ -52,7 +52,12 @@ public final class RedshiftRoleAccess {
|
||||
private RedshiftRoleAccess() {
|
||||
}
|
||||
|
||||
public record RoleSession(String accessKeyId, String sessionToken) {
|
||||
public record RoleSession(String accessKeyId, String secretAccessKey, String sessionToken) {
|
||||
// Do not print secret and token to logs via the default toString
|
||||
@Override
|
||||
public String toString() {
|
||||
return "RoleSession[accessKeyId=" + accessKeyId + "]";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -109,10 +114,11 @@ public final class RedshiftRoleAccess {
|
||||
// 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);
|
||||
String secretAccessKey = randomString(SECRET_CHARACTERS, 40);
|
||||
iamService.registerSessionForAccount(parsed.accountId(), accessKeyId,
|
||||
randomString(SECRET_CHARACTERS, 40), sessionToken, iamRoleArn,
|
||||
secretAccessKey, sessionToken, iamRoleArn,
|
||||
Instant.now().plus(sessionTtl), null);
|
||||
return new RoleSession(accessKeyId, sessionToken);
|
||||
return new RoleSession(accessKeyId, secretAccessKey, sessionToken);
|
||||
}
|
||||
|
||||
public static void releaseRoleSession(RoleSession roleSession, String iamRoleArn, IamService iamService) {
|
||||
|
||||
+92
-10
@@ -3,7 +3,9 @@ package io.github.hectorvent.floci.services.redshift.spectrum;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.AwsRegions;
|
||||
import io.github.hectorvent.floci.core.common.Digests;
|
||||
import io.github.hectorvent.floci.core.common.RequestScopes;
|
||||
import io.github.hectorvent.floci.services.floci.duck.FlociDuckClient;
|
||||
@@ -37,6 +39,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@ApplicationScoped
|
||||
@@ -46,6 +49,8 @@ public class ExternalTableMaterializer {
|
||||
public static final String SCRATCH_BUCKET = S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET;
|
||||
private static final String SQLSTATE_LOAD_FAILED = "58030";
|
||||
private static final String SQLSTATE_INSUFFICIENT_PRIVILEGE = "42501";
|
||||
private static final Pattern DUCKDB_HTTP_403 = Pattern.compile(
|
||||
"\\bHTTP(?:/[0-9.]+)?\\s+(?:Error:\\s+)?(?:HTTP(?:/[0-9.]+)?\\s+)?403\\b|\\b403\\s*\\(Forbidden\\)|\\b403\\s+Forbidden\\b");
|
||||
private static final long LOCK_TIMEOUT_SECONDS = 30;
|
||||
private static final String SCRATCH_KEY_PREFIX = "spectrum-";
|
||||
private static final Duration STALE_SCRATCH_AGE = Duration.ofHours(1);
|
||||
@@ -168,7 +173,7 @@ public class ExternalTableMaterializer {
|
||||
}
|
||||
String previousSignature = local == null ? schemaSignatures.get(cacheKey) : local.definitions();
|
||||
latestLoads.remove(cacheKey);
|
||||
String definitions = load(backend, session, binding, table, sources, previousSignature);
|
||||
String definitions = load(backend, session, binding, roleSession, table, sources, previousSignature);
|
||||
if (!backend.permitsCachePublication()) {
|
||||
fingerprints.remove(cacheKey);
|
||||
PendingLoad loaded = new PendingLoad(fingerprint, definitions);
|
||||
@@ -200,6 +205,10 @@ public class ExternalTableMaterializer {
|
||||
} catch (SpectrumSqlException | SpectrumReadException exception) {
|
||||
throw exception;
|
||||
} catch (RuntimeException exception) {
|
||||
if (isAccessDenied(exception)) {
|
||||
throw new SpectrumReadException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
|
||||
"Access denied for external table \"" + label + "\"", exception);
|
||||
}
|
||||
// the cause can carry DuckDB request text, so it goes to the log and not to the client
|
||||
LOG.warnv(exception, "Unable to load external table {0}", label);
|
||||
throw new SpectrumReadException(SQLSTATE_LOAD_FAILED, "Unable to load external table \"" + label + "\"", exception);
|
||||
@@ -287,7 +296,7 @@ public class ExternalTableMaterializer {
|
||||
private RedshiftRoleAccess.RoleSession openRoleSession(ExternalSchemaBinding binding, SpectrumSession session) {
|
||||
try {
|
||||
return RedshiftRoleAccess.resolveRoleSession(binding.iamRoleArn(), iamService, session.accountId(),
|
||||
session.iamRoleArns());
|
||||
session.iamRoleArns(), RedshiftRoleAccess.STREAMING_ROLE_SESSION_TTL);
|
||||
} catch (S3CopySimulator.S3TransferException exception) {
|
||||
throw new SpectrumSqlException(exception.sqlState(), exception.getMessage());
|
||||
}
|
||||
@@ -368,7 +377,7 @@ public class ExternalTableMaterializer {
|
||||
+ "\" has no supported metadata_location");
|
||||
}
|
||||
String sql = ICEBERG_DATA_FILES.formatted(sqlPathLiteral(metadata));
|
||||
List<Map<String, Object>> rows = duckClient.query(sql, ICEBERG_SETUP, accountId);
|
||||
List<Map<String, Object>> rows = duckQuery(accountId, roleSession, sql);
|
||||
for (Map<String, Object> row : rows) {
|
||||
Object value = row.get("file_path");
|
||||
if (!(value instanceof String filePath) || filePath.isBlank()) {
|
||||
@@ -431,8 +440,8 @@ public class ExternalTableMaterializer {
|
||||
S3Location manifestList = icebergFileLocation(manifestListPath, location);
|
||||
authorizeIcebergObject(accountId, binding, roleSession, manifestList);
|
||||
String manifestListUri = "s3://" + manifestList.bucket() + "/" + manifestList.key();
|
||||
List<Map<String, Object>> manifests = duckClient.query(
|
||||
ICEBERG_MANIFESTS.formatted(sqlPathLiteral(manifestListUri)), ICEBERG_SETUP, accountId);
|
||||
List<Map<String, Object>> manifests = duckQuery(accountId, roleSession,
|
||||
ICEBERG_MANIFESTS.formatted(sqlPathLiteral(manifestListUri)));
|
||||
for (Map<String, Object> manifest : manifests) {
|
||||
Object manifestValue = manifest.get("manifest_path");
|
||||
if (!(manifestValue instanceof String manifestPath) || manifestPath.isBlank()) {
|
||||
@@ -623,7 +632,8 @@ public class ExternalTableMaterializer {
|
||||
* match {@code loadedDefinitions} the target table is refilled in place, so views and grants that
|
||||
* depend on it survive; a schema change replaces the table instead.
|
||||
*/
|
||||
private String load(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding, Table table,
|
||||
private String load(BackendSql backend, SpectrumSession session, ExternalSchemaBinding binding,
|
||||
RedshiftRoleAccess.RoleSession roleSession, Table table,
|
||||
List<ReadSource> sources, String loadedDefinitions) {
|
||||
GlueTableResolver.ReadPlan plan = GlueTableResolver.readPlan(table);
|
||||
if (plan.columns().isEmpty()) {
|
||||
@@ -644,7 +654,13 @@ public class ExternalTableMaterializer {
|
||||
// before a key exists: a scratch bucket that is not ours must see no write and no delete
|
||||
prepareScratchBucket(session.accountId());
|
||||
scratchKey = SCRATCH_KEY_PREFIX + UUID.randomUUID() + ".csv";
|
||||
readWithDuckDb(session.accountId(), table, sources,
|
||||
if (roleSession != null && roleSession.accessKeyId() != null) {
|
||||
String partition = AwsRegions.partitionFor(config.defaultRegion());
|
||||
String scratchArn = AwsArnUtils.Arn.global(partition, "s3", "",
|
||||
SCRATCH_BUCKET + "/" + scratchKey).toString();
|
||||
iamService.registerSpectrumScratchResource(roleSession.accessKeyId(), scratchArn);
|
||||
}
|
||||
readWithDuckDb(session.accountId(), roleSession, table, sources,
|
||||
config.services().redshift().spectrumMaxRows(), scratchKey);
|
||||
long rows;
|
||||
String resultKey = scratchKey;
|
||||
@@ -678,6 +694,9 @@ public class ExternalTableMaterializer {
|
||||
}
|
||||
throw exception;
|
||||
} finally {
|
||||
if (roleSession != null && roleSession.accessKeyId() != null) {
|
||||
iamService.clearSpectrumScratchResource(roleSession.accessKeyId());
|
||||
}
|
||||
if (scratchKey != null) {
|
||||
String cleanupKey = scratchKey;
|
||||
try {
|
||||
@@ -698,7 +717,8 @@ public class ExternalTableMaterializer {
|
||||
});
|
||||
}
|
||||
|
||||
private void readWithDuckDb(String accountId, Table table, List<ReadSource> sources, long maxRows,
|
||||
private void readWithDuckDb(String accountId, RedshiftRoleAccess.RoleSession roleSession,
|
||||
Table table, List<ReadSource> sources, long maxRows,
|
||||
String scratchKey) {
|
||||
List<String> selects = sources.stream().filter(source -> source.partition() == null || !source.objects().isEmpty())
|
||||
.map(this::readSelect).toList();
|
||||
@@ -709,8 +729,70 @@ public class ExternalTableMaterializer {
|
||||
String query = selects.size() == 1 ? selects.getFirst()
|
||||
: "SELECT * FROM (" + String.join(" UNION ALL ", selects) + ") AS spectrum_partitions";
|
||||
String setup = GlueTableResolver.isIcebergTable(table) ? ICEBERG_SETUP : null;
|
||||
duckClient.execute(query + " LIMIT " + (maxRows + 1), setup,
|
||||
"s3://" + SCRATCH_BUCKET + "/" + scratchKey, accountId);
|
||||
String outputPath = "s3://" + SCRATCH_BUCKET + "/" + scratchKey;
|
||||
try {
|
||||
if (s3Service.isAuthEnforced()) {
|
||||
requireSignedSession(roleSession);
|
||||
duckClient.execute(query + " LIMIT " + (maxRows + 1), setup, outputPath,
|
||||
roleSession.accessKeyId(), roleSession.secretAccessKey(), roleSession.sessionToken());
|
||||
} else {
|
||||
duckClient.execute(query + " LIMIT " + (maxRows + 1), setup, outputPath, accountId);
|
||||
}
|
||||
} catch (RuntimeException exception) {
|
||||
if (isAccessDenied(exception)) {
|
||||
throw new SpectrumReadException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
|
||||
"Access denied during external table transfer for \"" + table.getName() + "\"", exception);
|
||||
}
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> duckQuery(String accountId, RedshiftRoleAccess.RoleSession roleSession,
|
||||
String sql) {
|
||||
try {
|
||||
if (!s3Service.isAuthEnforced()) {
|
||||
return duckClient.query(sql, ICEBERG_SETUP, accountId);
|
||||
}
|
||||
requireSignedSession(roleSession);
|
||||
return duckClient.query(sql, ICEBERG_SETUP,
|
||||
roleSession.accessKeyId(), roleSession.secretAccessKey(), roleSession.sessionToken());
|
||||
} catch (RuntimeException exception) {
|
||||
if (isAccessDenied(exception)) {
|
||||
throw new SpectrumReadException(SQLSTATE_INSUFFICIENT_PRIVILEGE,
|
||||
"Access denied during Iceberg metadata scan", exception);
|
||||
}
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an exception represents an S3 or IAM access denial (e.g. HTTP 403 from S3/IAM,
|
||||
* DuckDB's HTTP 403 error, or an AccessDenied error response).
|
||||
*/
|
||||
private static boolean isAccessDenied(Throwable throwable) {
|
||||
Throwable current = throwable;
|
||||
while (current != null) {
|
||||
if (current instanceof AwsException aws && (aws.getHttpStatus() == 403
|
||||
|| "AccessDenied".equalsIgnoreCase(aws.getErrorCode()))) {
|
||||
return true;
|
||||
}
|
||||
String message = current.getMessage();
|
||||
if (message != null && (DUCKDB_HTTP_403.matcher(message).find()
|
||||
|| message.contains("AccessDenied")
|
||||
|| message.contains("Access Denied"))) {
|
||||
return true;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Under S3 auth enforcement a transfer never falls back to the account-scoped development credentials. */
|
||||
private static void requireSignedSession(RedshiftRoleAccess.RoleSession roleSession) {
|
||||
if (roleSession == null || roleSession.accessKeyId() == null || roleSession.secretAccessKey() == null) {
|
||||
throw new SpectrumReadException(SQLSTATE_LOAD_FAILED,
|
||||
"Unable to load external table: no signed role session for the S3 transfer");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -628,6 +628,14 @@ public class S3Service implements Resettable, ResourceProvider {
|
||||
&& REDSHIFT_SPECTRUM_SCRATCH_TAG_VALUE.equals(bucket.getTags().get(INTERNAL_BUCKET_TAG_KEY));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the named bucket is Floci's internal Redshift Spectrum scratch bucket,
|
||||
* verified by its name and internal tag.
|
||||
*/
|
||||
public boolean isSpectrumScratchBucket(String bucketName) {
|
||||
return resolveBucket(bucketName).filter(S3Service::isSpectrumScratchBucket).isPresent();
|
||||
}
|
||||
|
||||
public String getBucketOwnerAccountId(String bucketName) {
|
||||
return resolveBucketEntry(bucketName)
|
||||
.map(AccountAwareStorageBackend.OwnedEntry::account)
|
||||
|
||||
Reference in new issue
Block a user