From cedc1073ec3e04954c510fe8777637db3c60fc40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C5=A9=20Th=E1=BA=BF=20Huy?= <31652864+vuthehuyht@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:26:32 +0700 Subject: [PATCH] feat(redshift): sign the Spectrum floci-duck transfer with the role session when S3 auth is enforced (#7162) --- docs/services/redshift.md | 14 +- .../core/common/IamEnforcementFilter.java | 102 ++++++++++- .../services/floci/duck/FlociDuckClient.java | 40 ++++- .../floci/services/iam/IamService.java | 25 +++ .../services/iam/model/CallerContext.java | 8 + .../services/iam/model/SessionCredential.java | 7 + .../redshift/proxy/RedshiftRoleAccess.java | 12 +- .../spectrum/ExternalTableMaterializer.java | 102 +++++++++-- .../floci/services/s3/S3Service.java | 8 + .../core/common/IamEnforcementFilterTest.java | 128 ++++++++++++++ .../duck/FlociDuckClientServiceTest.java | 80 +++++++++ .../floci/services/iam/IamServiceTest.java | 24 +++ ...SpectrumS3AuthEnforcedIntegrationTest.java | 161 ++++++++++++++++++ .../proxy/RedshiftRoleAccessTest.java | 20 ++- .../ExternalTableMaterializerTest.java | 125 +++++++++++++- .../testing/SidecarS3AuthEnforcedProfile.java | 19 +++ 16 files changed, 843 insertions(+), 32 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumS3AuthEnforcedIntegrationTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/testing/SidecarS3AuthEnforcedProfile.java diff --git a/docs/services/redshift.md b/docs/services/redshift.md index 5e75366076..eac87c3305 100644 --- a/docs/services/redshift.md +++ b/docs/services/redshift.md @@ -678,10 +678,16 @@ Creating an external schema or table inside a transaction, including a Data API batch (which runs as one transaction), is rejected before changing the catalogs: AWS does not allow `CREATE EXTERNAL TABLE` inside a transaction block (SQLSTATE `25001`). Cold loads and reloads require database privileges to maintain the materialized table and catalog; ordinary users with schema USAGE and table SELECT can read an existing committed cache entry. -The current floci-duck transfer uses account-scoped development credentials. Cold loads and reloads -with `FLOCI_SERVICES_S3_ENFORCE_AUTH=true` are not supported by that transfer path yet. -Role association and trust are still checked before cached reads; S3 policy checks follow the -configured enforcement mode. This is a Floci limitation, not AWS behavior. +Role association and trust are checked before every read, cached or not, and S3 policy checks follow +the configured enforcement mode. With `FLOCI_SERVICES_S3_ENFORCE_AUTH=true` the floci-duck transfer of +a cold load or reload is signed with the role's own short-lived session (access key, secret key and +session token), so the role's identity policy and the bucket policy are evaluated for the transfer +itself, and a deny stops it with SQLSTATE `42501`. The transfer writes its result to Floci's internal +scratch bucket; because AWS Spectrum performs no S3 write and realistic role policies, permissions +boundaries or SCPs follow AWS's read-only permissions on source data, this internal scratch write +is authorized ahead of the role's policies directly for the minted transfer session key and scratch key, +verifying Floci's internal tag on the bucket. Reads of the scratch bucket and every other bucket stay under +normal policy evaluation. 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 diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java index 7bfd052421..e0bb0696de 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java @@ -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 s3ServiceProvider; @Inject public IamEnforcementFilter(EmulatorConfig config, @@ -232,7 +234,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { Instance resourcePolicyProviders, Instance passedRoleLookups, Clock clock, - @Context ResourceInfo resourceInfo) { + @Context ResourceInfo resourceInfo, + Instance 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, + SessionAccountLookup sessionAccountLookup, + Instance resourcePolicyProviders, + Instance 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, + SessionAccountLookup sessionAccountLookup, + Instance resourcePolicyProviders, + Instance 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 = TagOnCreate.of(resolvedAuthorization.operation(), ctx); @@ -658,6 +717,14 @@ public class IamEnforcementFilter implements ContainerRequestFilter { // presigned URLs add, is a DeleteObject. private static final Set NON_DELETE_OBJECT_SUBRESOURCES = Set.of("uploadId", "tagging", "annotation"); + private static final Set 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 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 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 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 diff --git a/src/main/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClient.java b/src/main/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClient.java index 034aa06ce8..d8e313fd6c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClient.java +++ b/src/main/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClient.java @@ -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 body = buildBaseBody(sql, setupDdl, accessKeyId); + String effectiveSetup = injectSessionToken(setupDdl, sessionToken); + Map 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> 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> query(String sql, String setupDdl, + String accessKeyId, String secretAccessKey, String sessionToken) { String duckUrl = duckManager.ensureReady(); - Map body = buildBaseBody(sql, setupDdl, accessKeyId); + String effectiveSetup = injectSessionToken(setupDdl, sessionToken); + Map 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 buildBaseBody(String sql, String setupDdl) { - return buildBaseBody(sql, setupDdl, null); + return buildBaseBody(sql, setupDdl, null, null); } private Map buildBaseBody(String sql, String setupDdl, String accessKeyId) { + return buildBaseBody(sql, setupDdl, accessKeyId, null); + } + + private Map buildBaseBody(String sql, String setupDdl, String accessKeyId, String secretAccessKey) { Map 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; } diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java index 17fa42ce05..496e101769 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java @@ -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 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. diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/CallerContext.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/CallerContext.java index 8896e8ca5c..220a2577b5 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/model/CallerContext.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/CallerContext.java @@ -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 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); diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java index 07f5a3dd8c..1d111f4490 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/SessionCredential.java @@ -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; } 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 index 236b5ee051..1f6ce01087 100644 --- 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 @@ -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) { diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializer.java b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializer.java index 3f8833f022..b7175c9784 100644 --- a/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializer.java +++ b/src/main/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializer.java @@ -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> rows = duckClient.query(sql, ICEBERG_SETUP, accountId); + List> rows = duckQuery(accountId, roleSession, sql); for (Map 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> manifests = duckClient.query( - ICEBERG_MANIFESTS.formatted(sqlPathLiteral(manifestListUri)), ICEBERG_SETUP, accountId); + List> manifests = duckQuery(accountId, roleSession, + ICEBERG_MANIFESTS.formatted(sqlPathLiteral(manifestListUri))); for (Map 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 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 sources, long maxRows, + private void readWithDuckDb(String accountId, RedshiftRoleAccess.RoleSession roleSession, + Table table, List sources, long maxRows, String scratchKey) { List 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> 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"); + } } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java index 3dd28ff7a7..d6ce08eba4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java @@ -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) diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java index 0953dd2725..8f348d29f3 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/IamEnforcementFilterTest.java @@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider; import io.github.hectorvent.floci.services.iam.ScpProvider; import io.github.hectorvent.floci.services.iam.model.CallerContext; import io.github.hectorvent.floci.services.s3.S3Controller; +import io.github.hectorvent.floci.services.s3.S3Service; import io.github.hectorvent.floci.services.scheduler.SchedulerController; import io.quarkus.vertx.http.runtime.CurrentVertxRequest; import io.vertx.core.http.HttpServerRequest; @@ -1591,6 +1592,133 @@ class IamEnforcementFilterTest { verify(containerRequest).abortWith(any(Response.class)); } + private static final String SCRATCH_OBJECT = "arn:aws:s3:::floci-internal-redshift-spectrum-scratch/" + + "spectrum-123e4567-e89b-12d3-a456-426614174000.csv"; + + private IamEnforcementFilter newFilterWithRealEvaluator() { + return newFilterWithRealEvaluator(null); + } + + private IamEnforcementFilter newFilterWithRealEvaluator(Instance s3ServiceProvider) { + @SuppressWarnings("unchecked") + Instance scpProvider = mock(Instance.class); + when(scpProvider.isResolvable()).thenReturn(false); + return new IamEnforcementFilter( + config, accountResolver, iamService, new IamPolicyEvaluator(new ObjectMapper()), + actionRegistry, arnBuilder, requestContext, conditionContextResolver, + mock(CloudTrailService.class), + mock(CurrentVertxRequest.class), + catalog, scpProvider, sessionAccountLookup, null, s3ServiceProvider); + } + + private void stubSignedS3Request(ContainerRequestContext containerRequest, String action, String resource, + IamService.CallerArns callerArns, String identityPolicy) { + String auth = "AWS4-HMAC-SHA256 Credential=ASIASESSION/20260726/us-east-1/s3/aws4_request, " + + "SignedHeaders=host, Signature=abc"; + requestContext.setAccountId("222233334444"); + requestContext.setRegion("us-east-1"); + when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASESSION"); + when(containerRequest.getHeaderString("Authorization")).thenReturn(auth); + when(actionRegistry.resolve("s3", containerRequest)).thenReturn(action); + when(iamService.resolveCallerContext(eq("ASIASESSION"), any())) + .thenReturn(CallerContext.of(List.of(identityPolicy))); + when(iamService.resolveCallerArns("ASIASESSION")).thenReturn(Optional.of(callerArns)); + when(iamService.spectrumScratchResourceArn("ASIASESSION")).thenReturn(Optional.of(SCRATCH_OBJECT)); + when(arnBuilder.buildResources(eq("s3"), any(), eq(containerRequest), anyString(), anyString(), anyString())) + .thenReturn(List.of(resource)); + UriInfo uriInfo = mock(UriInfo.class); + when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>()); + when(containerRequest.getUriInfo()).thenReturn(uriInfo); + when(containerRequest.getMethod()).thenReturn("PUT"); + } + + private static IamService.CallerArns assumedRoleArns() { + return new IamService.CallerArns("arn:aws:sts::222233334444:assumed-role/SpectrumRole/session", + "arn:aws:iam::222233334444:role/SpectrumRole", IamService.CallerArns.TYPE_ASSUMED_ROLE, null, null, + false); + } + + private static final String NO_STATEMENTS = "{\"Version\":\"2012-10-17\",\"Statement\":[]}"; + + @Test + void anAssumedRoleSessionMayWriteTheSpectrumScratchBucketWithoutAPolicyNamingIt() { + ContainerRequestContext containerRequest = mock(ContainerRequestContext.class); + stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, assumedRoleArns(), NO_STATEMENTS); + + newFilterWithRealEvaluator().filter(containerRequest); + + verify(containerRequest, never()).abortWith(any()); + } + + @Test + void spectrumScratchWriteIsAuthorizedAheadOfRolePoliciesAndDenies() { + ContainerRequestContext containerRequest = mock(ContainerRequestContext.class); + stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, assumedRoleArns(), + "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"s3:*\"," + + "\"Resource\":\"*\"}]}"); + + newFilterWithRealEvaluator().filter(containerRequest); + + verify(containerRequest, never()).abortWith(any()); + } + + @Test + void scratchWriteDeniedWhenBucketIsNotInternalScratchBucket() { + @SuppressWarnings("unchecked") + Instance s3ServiceProvider = mock(Instance.class); + S3Service s3Service = mock(S3Service.class); + when(s3ServiceProvider.isResolvable()).thenReturn(true); + when(s3ServiceProvider.get()).thenReturn(s3Service); + when(s3Service.isSpectrumScratchBucket(S3Service.REDSHIFT_SPECTRUM_SCRATCH_BUCKET)).thenReturn(false); + + ContainerRequestContext containerRequest = mock(ContainerRequestContext.class); + stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, assumedRoleArns(), NO_STATEMENTS); + + newFilterWithRealEvaluator(s3ServiceProvider).filter(containerRequest); + + verify(containerRequest).abortWith(any(Response.class)); + } + + @Test + void theScratchBucketAllowDoesNotCoverReadsOtherBucketsOrOtherKeys() { + String bucket = "arn:aws:s3:::floci-internal-redshift-spectrum-scratch/"; + for (String[] attempt : new String[][] { + {"s3:GetObject", SCRATCH_OBJECT}, + {"s3:PutObject", "arn:aws:s3:::user-bucket/spectrum-123e4567-e89b-12d3-a456-426614174000.csv"}, + {"s3:PutObject", bucket + "nested/other.csv"}}) { + ContainerRequestContext containerRequest = mock(ContainerRequestContext.class); + stubSignedS3Request(containerRequest, attempt[0], attempt[1], assumedRoleArns(), NO_STATEMENTS); + + newFilterWithRealEvaluator().filter(containerRequest); + + verify(containerRequest).abortWith(any(Response.class)); + } + } + + @Test + void theScratchBucketAllowDoesNotCoverAnIamUser() { + ContainerRequestContext containerRequest = mock(ContainerRequestContext.class); + stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, + new IamService.CallerArns("arn:aws:iam::222233334444:user/alice", + "arn:aws:iam::222233334444:user/alice", IamService.CallerArns.TYPE_USER, null, "alice", + false), NO_STATEMENTS); + + newFilterWithRealEvaluator().filter(containerRequest); + + verify(containerRequest).abortWith(any(Response.class)); + } + + @Test + void anUnrelatedRoleSessionCannotWriteTheSpectrumScratchBucket() { + ContainerRequestContext containerRequest = mock(ContainerRequestContext.class); + stubSignedS3Request(containerRequest, "s3:PutObject", SCRATCH_OBJECT, assumedRoleArns(), NO_STATEMENTS); + when(iamService.spectrumScratchResourceArn("ASIASESSION")).thenReturn(Optional.empty()); + + newFilterWithRealEvaluator().filter(containerRequest); + + verify(containerRequest).abortWith(any(Response.class)); + } + // FullAWSAccess baseline auto-attached to every OU/account when SCP enforcement is on. private static final String FULL_AWS_ACCESS = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"}]}"; diff --git a/src/test/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClientServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClientServiceTest.java index 3585d955c6..dfe6a6dc7c 100644 --- a/src/test/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClientServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/floci/duck/FlociDuckClientServiceTest.java @@ -17,6 +17,7 @@ import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -94,4 +95,83 @@ class FlociDuckClientServiceTest { assertEquals("http://172.18.0.2:4566", requestBody.get().path("s3_endpoint").asText()); } + + @Test + void executeInjectsSessionTokenDdlAndPassesCredentials() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + AtomicReference requestBody = new AtomicReference<>(); + server = HttpServer.create(new InetSocketAddress(0), 0); + server.createContext("/execute", exchange -> { + requestBody.set(mapper.readTree(exchange.getRequestBody().readAllBytes())); + exchange.sendResponseHeaders(200, -1); + exchange.close(); + }); + server.start(); + + FlociDuckManager duckManager = mock(FlociDuckManager.class); + EmulatorConfig config = mock(EmulatorConfig.class); + DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class); + EmbeddedDnsServer embeddedDnsServer = mock(EmbeddedDnsServer.class); + when(duckManager.ensureReady()).thenReturn("http://localhost:" + server.getAddress().getPort()); + when(config.baseUrl()).thenReturn("http://localhost:4566"); + when(config.defaultRegion()).thenReturn("us-east-1"); + when(config.tls()).thenReturn(mock(EmulatorConfig.TlsConfig.class)); + when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty()); + when(dockerHostResolver.resolve()).thenReturn("127.0.0.1"); + + FlociDuckClient client = new FlociDuckClient(duckManager, config, + new ContainerReachableEndpoint(config, dockerHostResolver, embeddedDnsServer, 4566), mapper); + client.execute("SELECT 1", "INSTALL iceberg;", "s3://bucket/out.csv", + "ASIAEXAMPLE", "secretKey123", "tokenXYZ"); + + JsonNode body = requestBody.get(); + assertEquals("ASIAEXAMPLE", body.path("s3_access_key").asText()); + assertEquals("secretKey123", body.path("s3_secret_key").asText()); + assertEquals("s3://bucket/out.csv", body.path("output_s3_path").asText()); + String setupSql = body.path("setup_sql").asText(); + assertTrue(setupSql.startsWith("SET s3_session_token = 'tokenXYZ';\n")); + assertTrue(setupSql.contains("INSTALL iceberg;")); + } + + @Test + void queryInjectsSessionTokenDdlAndPassesCredentials() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + AtomicReference requestBody = new AtomicReference<>(); + server = HttpServer.create(new InetSocketAddress(0), 0); + server.createContext("/query", exchange -> { + requestBody.set(mapper.readTree(exchange.getRequestBody().readAllBytes())); + String response = "{\"status\": \"success\", \"rows\": [{\"col\": 1}]}"; + exchange.sendResponseHeaders(200, response.length()); + exchange.getResponseBody().write(response.getBytes(StandardCharsets.UTF_8)); + exchange.close(); + }); + server.start(); + + FlociDuckManager duckManager = mock(FlociDuckManager.class); + EmulatorConfig config = mock(EmulatorConfig.class); + DockerHostResolver dockerHostResolver = mock(DockerHostResolver.class); + EmbeddedDnsServer embeddedDnsServer = mock(EmbeddedDnsServer.class); + when(duckManager.ensureReady()).thenReturn("http://localhost:" + server.getAddress().getPort()); + when(config.baseUrl()).thenReturn("http://localhost:4566"); + when(config.defaultRegion()).thenReturn("us-east-1"); + when(config.tls()).thenReturn(mock(EmulatorConfig.TlsConfig.class)); + when(embeddedDnsServer.getServerIp()).thenReturn(Optional.empty()); + when(dockerHostResolver.resolve()).thenReturn("127.0.0.1"); + + FlociDuckClient client = new FlociDuckClient(duckManager, config, + new ContainerReachableEndpoint(config, dockerHostResolver, embeddedDnsServer, 4566), mapper); + client.query("SELECT 1 AS col", "", "ASIAEXAMPLE", "secretKey123", "tokenXYZ"); + + JsonNode body = requestBody.get(); + assertEquals("ASIAEXAMPLE", body.path("s3_access_key").asText()); + assertEquals("secretKey123", body.path("s3_secret_key").asText()); + String setupSql = body.path("setup_sql").asText(); + assertEquals("SET s3_session_token = 'tokenXYZ';\n", setupSql); + } + + @Test + void sessionTokenQuotesAreEscaped() { + assertEquals("SET s3_session_token = 'a''b';\nINSTALL x;", + FlociDuckClient.injectSessionToken("INSTALL x;", "a'b")); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java index ab0b9bce25..7e86974d65 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java @@ -2611,6 +2611,30 @@ class IamServiceTest { assertTrue(sessions.getForAccount("000000000000", "ASIASTSSESSION").isPresent()); } + @Test + void spectrumScratchResourceRegistrationAndClear() { + String accountId = "222233334444"; + String accessKeyId = "ASIASPECTRUM"; + AccountAwareStorageBackend sessions = new AccountAwareStorageBackend<>( + new InMemoryStorage<>(), null, "000000000000"); + IamService service = iamService(false, new InMemoryStorage<>(), sessions); + + service.registerSessionForAccount( + accountId, accessKeyId, "secret", "token", + "arn:aws:iam::222233334444:role/R", Instant.now().plusSeconds(900), null); + + assertTrue(service.spectrumScratchResourceArn(accessKeyId).isEmpty()); + + String scratchArn = "arn:aws:s3:::floci-internal-redshift-spectrum-scratch/spectrum-1234.csv"; + service.registerSpectrumScratchResource(accessKeyId, scratchArn); + + assertEquals(Optional.of(scratchArn), service.spectrumScratchResourceArn(accessKeyId)); + + service.clearSpectrumScratchResource(accessKeyId); + + assertTrue(service.spectrumScratchResourceArn(accessKeyId).isEmpty()); + } + // ========================================================================= // Instance Profiles // ========================================================================= diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumS3AuthEnforcedIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumS3AuthEnforcedIntegrationTest.java new file mode 100644 index 0000000000..ba12739b02 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/RedshiftSpectrumS3AuthEnforcedIntegrationTest.java @@ -0,0 +1,161 @@ +package io.github.hectorvent.floci.services.redshift; + +import io.github.hectorvent.floci.services.glue.GlueService; +import io.github.hectorvent.floci.services.glue.model.Database; +import io.github.hectorvent.floci.services.iam.IamService; +import io.github.hectorvent.floci.services.redshift.model.Cluster; +import io.github.hectorvent.floci.services.redshift.spectrum.ExternalStatement; +import io.github.hectorvent.floci.services.redshift.spectrum.ExternalStatementParser; +import io.github.hectorvent.floci.services.redshift.spectrum.GlueTableBuilder; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.testing.RestAssuredJsonUtils; +import io.github.hectorvent.floci.testing.SidecarContainersProfile; +import io.github.hectorvent.floci.testing.SidecarS3AuthEnforcedProfile; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import jakarta.inject.Inject; +import org.awaitility.Awaitility; +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.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.util.List; +import java.util.Objects; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Cold load, cached read and reload of a Spectrum external table with {@code s3.enforce-auth} on: + * the floci-duck transfer runs under the role's signed session, and a bucket policy that denies the + * role stops the next query with SQLSTATE 42501 even though the table is already cached. + */ +@QuarkusTest +@TestProfile(SidecarS3AuthEnforcedProfile.class) +class RedshiftSpectrumS3AuthEnforcedIntegrationTest { + + private static final String ROLE_NAME = "SpectrumAuthItRole"; + 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; + + private String clusterId; + private String bucket; + private String glueDatabase; + + @BeforeAll + static void requireDocker() { + SidecarContainersProfile.requireDocker(); + } + + @AfterEach + void cleanUp() { + if (clusterId != null) { + redshiftService.deleteCluster(clusterId); + } + if (bucket != null) { + s3Service.deleteBucketPolicy(bucket); + 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 coldLoadReloadAndCachedReadUseTheRoleSessionAndHonorABucketPolicyDeny() 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-auth-" + System.nanoTime(); + s3Service.createBucket(bucket, "us-east-1"); + s3Service.putObject(bucket, "events/part-1.csv", "1,10\n2,7\n".getBytes(StandardCharsets.UTF_8), + "text/csv", null); + glueDatabase = "spectrum_auth_" + System.nanoTime(); + Database database = new Database(); + database.setName(glueDatabase); + glueService.createDatabase(database); + clusterId = "it-auth-" + 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)); + + assertEquals(17L, sumAmount(statement)); + assertEquals(17L, sumAmount(statement)); + + s3Service.putObject(bucket, "events/part-1.csv", "1,10\n2,30\n".getBytes(StandardCharsets.UTF_8), + "text/csv", null); + assertEquals(40L, sumAmount(statement)); + + RestAssuredJsonUtils.configureAwsContentTypes(); + s3Service.putObject(bucket, "events/part-1.csv", "1,10\n2,50\n".getBytes(StandardCharsets.UTF_8), + "text/csv", null); + String queryId = RestAssuredJsonUtils.awsAction("RedshiftData", "ExecuteStatement", """ + {"ClusterIdentifier":"%s","DbUser":"admin","Database":"dev", + "Sql":"SELECT SUM(amount) AS total FROM lake.events","WaitTimeSeconds":30} + """.formatted(clusterId)).then().statusCode(200).extract().path("Id"); + assertEquals("FINISHED", RestAssuredJsonUtils.awsAction("RedshiftData", "DescribeStatement", + "{\"Id\":\"" + queryId + "\"}").then().statusCode(200).extract().path("Status")); + Number total = RestAssuredJsonUtils.awsAction("RedshiftData", "GetStatementResult", + "{\"Id\":\"" + queryId + "\"}").then().statusCode(200).extract().path("Records[0][0].longValue"); + assertEquals(60L, total.longValue()); + + s3Service.putBucketPolicy(bucket, """ + {"Version":"2012-10-17","Statement":[{"Effect":"Deny", + "Principal":{"AWS":"%s"},"Action":["s3:GetObject","s3:ListBucket"], + "Resource":["arn:aws:s3:::%s","arn:aws:s3:::%s/*"]}]}""".formatted(ROLE_ARN, bucket, bucket)); + SQLException denied = assertThrows(SQLException.class, () -> sumAmount(statement)); + assertEquals("42501", denied.getSQLState()); + } + } + + 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); + } + } + + private static Connection waitForConnection(Cluster cluster) { + String url = "jdbc:postgresql://127.0.0.1:" + cluster.getEndpoint().getPort() + "/dev"; + return Awaitility.await().atMost(Duration.ofSeconds(30)).pollDelay(Duration.ZERO) + .pollInterval(Duration.ofMillis(500)).ignoreExceptions() + .until(() -> DriverManager.getConnection(url, "admin", "Secret123"), Objects::nonNull); + } +} 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 index 8498c5eadb..451d1cfeda 100644 --- 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 @@ -17,6 +17,7 @@ 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.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -139,6 +140,19 @@ class RedshiftRoleAccessTest { assertThat(expiry.getValue().isBefore(before.plus(Duration.ofMinutes(31))), equalTo(true)); } + @Test + void resolveRoleSessionIncludesSecretAccessKeyMatchingIamSession() { + IamService iamService = iamServiceWithRole(TRUST_POLICY); + + RedshiftRoleAccess.RoleSession session = RedshiftRoleAccess.resolveRoleSession( + ROLE_ARN, iamService, ACCOUNT, List.of(ROLE_ARN)); + + assertNotNull(session.secretAccessKey()); + assertThat(session.secretAccessKey().length(), equalTo(40)); + verify(iamService).registerSessionForAccount(eq(ACCOUNT), eq(session.accessKeyId()), + eq(session.secretAccessKey()), eq(session.sessionToken()), eq(ROLE_ARN), any(), isNull()); + } + @Test void authorizeRoleActionAllowsWhatTheIdentityPolicyGrants() { S3Service s3 = mock(S3Service.class); @@ -158,7 +172,7 @@ class RedshiftRoleAccessTest { when(iamService.resolvePrincipalContext(ROLE_ARN)).thenReturn(CallerContext.of(List.of(""" {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:ListBucket", "Resource":"arn:aws:s3:::bucket","Condition":{"StringLike":{"s3:prefix":["events/*"]}}}]}"""))); - RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "token"); + RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "secret", "token"); RedshiftRoleAccess.authorizeRoleList(s3, iamService, session, ROLE_ARN, "bucket", "events/"); S3CopySimulator.S3TransferException denied = assertThrows(S3CopySimulator.S3TransferException.class, @@ -172,7 +186,7 @@ class RedshiftRoleAccessTest { S3Service s3 = mock(S3Service.class); when(s3.isAuthEnforced()).thenReturn(false); IamService iamService = mock(IamService.class); - RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "token"); + RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "secret", "token"); doThrow(new AwsException("NoSuchBucket", "The specified bucket does not exist", 404)).when(s3) .authorizeSignedListBucket("ASIAX", "token", "bucket"); @@ -188,7 +202,7 @@ class RedshiftRoleAccessTest { S3Service s3 = mock(S3Service.class); when(s3.isAuthEnforced()).thenReturn(false); IamService iamService = mock(IamService.class); - RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "token"); + RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAX", "secret", "token"); doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3) .authorizeSignedListBucket("ASIAX", "token", "bucket"); doThrow(new AwsException("AccessDenied", "Access Denied", 403)).when(s3) diff --git a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializerTest.java b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializerTest.java index 94f48c9a73..75ea55ad28 100644 --- a/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/redshift/spectrum/ExternalTableMaterializerTest.java @@ -50,6 +50,8 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; +import static org.mockito.ArgumentMatchers.notNull; +import static org.mockito.ArgumentMatchers.startsWith; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -200,7 +202,7 @@ class ExternalTableMaterializerTest { Table table = icebergTable("s3://bucket/events/metadata/v[1].json"); when(glue.getTable("lake", "events")).thenReturn(table); when(s3.isAuthEnforced()).thenReturn(true); - when(duck.query(anyString(), any(), eq(ACCOUNT))).thenAnswer(invocation -> { + when(duck.query(anyString(), any(), startsWith("ASIA"), anyString(), anyString())).thenAnswer(invocation -> { String sql = invocation.getArgument(0); if (!sql.contains("status IN ('ADDED', 'EXISTING')") || sql.contains("content = 'DATA'")) { return List.of(); @@ -222,16 +224,129 @@ class ExternalTableMaterializerTest { assertThat(exception.sqlState(), equalTo("42501")); verify(duck).query(argThat(sql -> sql.contains("iceberg_metadata('s3://bucket/events/metadata/v[[]1].json')")), - any(), eq(ACCOUNT)); + any(), startsWith("ASIA"), anyString(), anyString()); verify(duck, never()).execute(anyString(), any(), anyString(), anyString()); } + @Test + void coldLoadWithAuthEnforcedTransfersWithTheRoleSessionCredentials() { + when(glue.getTable("lake", "events")).thenReturn(csvTable()); + when(s3.isAuthEnforced()).thenReturn(true); + when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"} + ]}"""))); + + assertThat(materializer.ensureCurrent(backend, session(false), BINDING, "events"), + equalTo(ExternalTableMaterializer.Outcome.LOADED)); + + verify(duck).execute(argThat(sql -> sql.contains("LIMIT 1001")), isNull(), anyString(), + startsWith("ASIA"), anyString(), notNull()); + verify(duck, never()).execute(anyString(), any(), anyString(), eq(ACCOUNT)); + verify(iam).registerSpectrumScratchResource(startsWith("ASIA"), + startsWith("arn:aws:s3:::floci-internal-redshift-spectrum-scratch/spectrum-")); + verify(iam).clearSpectrumScratchResource(startsWith("ASIA")); + } + + @Test + void transferDenialDuringColdLoadReturns42501() { + when(glue.getTable("lake", "events")).thenReturn(csvTable()); + when(s3.isAuthEnforced()).thenReturn(true); + when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"} + ]}"""))); + doThrow(new RuntimeException("floci-duck execute returned HTTP 500: HTTP Error: HTTP 403 (Forbidden) while writing scratch")) + .when(duck).execute(anyString(), any(), anyString(), anyString(), anyString(), anyString()); + + SpectrumReadException exception = assertThrows(SpectrumReadException.class, + () -> materializer.ensureCurrent(backend, session(false), BINDING, "events")); + + assertThat(exception.sqlState(), equalTo("42501")); + verify(iam).clearSpectrumScratchResource(startsWith("ASIA")); + } + + @Test + void accessDenialDuringIcebergScanReturns42501() { + Table table = icebergTable("s3://bucket/events/metadata/v1.json"); + when(glue.getTable("lake", "events")).thenReturn(table); + when(s3.isAuthEnforced()).thenReturn(true); + when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"} + ]}"""))); + when(duck.query(anyString(), any(), startsWith("ASIA"), anyString(), anyString())) + .thenThrow(new RuntimeException("floci-duck query error: AccessDenied: Access Denied")); + + SpectrumReadException exception = assertThrows(SpectrumReadException.class, + () -> materializer.ensureCurrent(backend, session(false), BINDING, "events")); + + assertThat(exception.sqlState(), equalTo("42501")); + } + + @Test + void unrelatedExecutionErrorDuringColdLoadReturns58030() { + when(glue.getTable("lake", "events")).thenReturn(csvTable()); + when(s3.isAuthEnforced()).thenReturn(true); + when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"} + ]}"""))); + doThrow(new RuntimeException("floci-duck execute returned HTTP 500: Parser Error: syntax error")) + .when(duck).execute(anyString(), any(), anyString(), anyString(), anyString(), anyString()); + + SpectrumReadException exception = assertThrows(SpectrumReadException.class, + () -> materializer.ensureCurrent(backend, session(false), BINDING, "events")); + + assertThat(exception.sqlState(), equalTo("58030")); + verify(iam).clearSpectrumScratchResource(startsWith("ASIA")); + } + + @Test + void conversionErrorCarrying403InScratchPathReturns58030() { + when(glue.getTable("lake", "events")).thenReturn(csvTable()); + when(s3.isAuthEnforced()).thenReturn(true); + when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"} + ]}"""))); + doThrow(new RuntimeException("floci-duck execute returned HTTP 500: Failed to write to " + + "'s3://floci-internal-redshift-spectrum-scratch/spectrum-e403d511-1234.csv': " + + "Conversion Error: Could not convert string 'foo' to INT32")) + .when(duck).execute(anyString(), any(), anyString(), anyString(), anyString(), anyString()); + + SpectrumReadException exception = assertThrows(SpectrumReadException.class, + () -> materializer.ensureCurrent(backend, session(false), BINDING, "events")); + + assertThat(exception.sqlState(), equalTo("58030")); + verify(iam).clearSpectrumScratchResource(startsWith("ASIA")); + } + + @Test + void conversionErrorOnFailedValueContaining403Returns58030() { + when(glue.getTable("lake", "events")).thenReturn(csvTable()); + when(s3.isAuthEnforced()).thenReturn(true); + when(iam.resolvePrincipalContext(BINDING.iamRoleArn())).thenReturn(CallerContext.of(List.of(""" + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":["s3:ListBucket","s3:GetObject"],"Resource":"*"} + ]}"""))); + doThrow(new RuntimeException("floci-duck execute returned HTTP 500: " + + "Conversion Error: Could not convert string '403' to INT32")) + .when(duck).execute(anyString(), any(), anyString(), anyString(), anyString(), anyString()); + + SpectrumReadException exception = assertThrows(SpectrumReadException.class, + () -> materializer.ensureCurrent(backend, session(false), BINDING, "events")); + + assertThat(exception.sqlState(), equalTo("58030")); + verify(iam).clearSpectrumScratchResource(startsWith("ASIA")); + } + @Test void deniesIcebergManifestBeforeTheMetadataScanReadsIt() { Table table = icebergTable("s3://bucket/events/metadata/v1.json"); when(glue.getTable("lake", "events")).thenReturn(table); when(s3.isAuthEnforced()).thenReturn(true); - when(duck.query(anyString(), any(), eq(ACCOUNT))).thenAnswer(invocation -> { + when(duck.query(anyString(), any(), startsWith("ASIA"), anyString(), anyString())).thenAnswer(invocation -> { String sql = invocation.getArgument(0); if (sql.contains("read_avro")) { return List.of(Map.of("manifest_path", "s3://bucket/private/manifest.avro")); @@ -249,8 +364,8 @@ class ExternalTableMaterializerTest { assertThat(exception.sqlState(), equalTo("42501")); verify(duck).query(argThat(sql -> sql.contains("read_avro('s3://bucket/events/metadata/snap[*].avro')")), - any(), eq(ACCOUNT)); - verify(duck, never()).query(argThat(sql -> sql.contains("iceberg_metadata")), any(), eq(ACCOUNT)); + any(), startsWith("ASIA"), anyString(), anyString()); + verify(duck, never()).query(argThat(sql -> sql.contains("iceberg_metadata")), any(), anyString(), anyString(), anyString()); verify(duck, never()).execute(anyString(), any(), anyString(), anyString()); } diff --git a/src/test/java/io/github/hectorvent/floci/testing/SidecarS3AuthEnforcedProfile.java b/src/test/java/io/github/hectorvent/floci/testing/SidecarS3AuthEnforcedProfile.java new file mode 100644 index 0000000000..6c586d049e --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/testing/SidecarS3AuthEnforcedProfile.java @@ -0,0 +1,19 @@ +package io.github.hectorvent.floci.testing; + +import java.util.HashMap; +import java.util.Map; + +/** + * {@link SidecarContainersProfile} with S3 authorization enforced, so the floci-duck transfer of a + * Spectrum cold load has to present a signed role session instead of the account-scoped development + * credentials. + */ +public class SidecarS3AuthEnforcedProfile extends SidecarContainersProfile { + + @Override + public Map getConfigOverrides() { + Map overrides = new HashMap<>(super.getConfigOverrides()); + overrides.put("floci.services.s3.enforce-auth", "true"); + return overrides; + } +}