mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(firehose): load Redshift COPY with temporary credentials of the stream role (#7337)
This commit is contained in:
1 parent
fca988cea1
commit
814232c43f
13 files changed
+352
-37
No files matched your search
+76
-2
@@ -4,7 +4,9 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.services.firehose.model.DeliveryStreamDescription;
|
||||
import io.github.hectorvent.floci.services.firehose.model.RedshiftDestination;
|
||||
import io.github.hectorvent.floci.services.iam.IamService;
|
||||
import io.github.hectorvent.floci.services.iam.ServiceRoleAuthorizer;
|
||||
import io.github.hectorvent.floci.services.iam.model.IamRole;
|
||||
import io.github.hectorvent.floci.services.redshift.RedshiftService;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Cluster;
|
||||
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
|
||||
@@ -18,19 +20,24 @@ import org.junit.jupiter.api.Test;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
@@ -43,6 +50,7 @@ class FirehoseRedshiftDeliveryTest {
|
||||
private RedshiftServerlessService serverless;
|
||||
private SecretsManagerService secrets;
|
||||
private ServiceRoleAuthorizer roleAuthorizer;
|
||||
private IamService iamService;
|
||||
private final List<String[]> executed = new ArrayList<>();
|
||||
private FirehoseRedshiftDelivery delivery;
|
||||
|
||||
@@ -56,7 +64,8 @@ class FirehoseRedshiftDeliveryTest {
|
||||
when(redshift.describeClustersForAccount("000000000000", "c1")).thenReturn(List.of(cluster));
|
||||
serverless = mock(RedshiftServerlessService.class);
|
||||
roleAuthorizer = mock(ServiceRoleAuthorizer.class);
|
||||
delivery = new FirehoseRedshiftDelivery(redshift, serverless, secrets, roleAuthorizer, mapper,
|
||||
iamService = mock(IamService.class);
|
||||
delivery = new FirehoseRedshiftDelivery(redshift, serverless, secrets, roleAuthorizer, iamService, mapper,
|
||||
(url, user, password, sql) -> executed.add(new String[] {url, user, password, sql}));
|
||||
}
|
||||
|
||||
@@ -234,6 +243,71 @@ class FirehoseRedshiftDeliveryTest {
|
||||
assertEquals("COPY events FROM 's3://stage/k1' json 'auto'", executed.get(0)[3]);
|
||||
}
|
||||
|
||||
private void knownLoadRole() {
|
||||
when(iamService.findRole("000000000000", "firehose"))
|
||||
.thenReturn(Optional.of(new IamRole("id-firehose", "firehose", "/", LOAD_ROLE, "{}")));
|
||||
}
|
||||
|
||||
private static String sessionKey(String sql) {
|
||||
return sql.substring(sql.indexOf("aws_access_key_id=") + "aws_access_key_id=".length(), sql.indexOf(';'));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loadsWithTemporaryCredentialsOfTheDestinationRole() throws Exception {
|
||||
knownLoadRole();
|
||||
|
||||
delivery.copy("000000000000", "us-east-1", destination(), "stage", "k1");
|
||||
|
||||
String sql = executed.get(0)[3];
|
||||
assertTrue(sql.startsWith("COPY events FROM 's3://stage/k1' CREDENTIALS 'aws_access_key_id=ASIA"), sql);
|
||||
assertTrue(sql.contains(";aws_secret_access_key="), sql);
|
||||
assertTrue(sql.contains(";token="), sql);
|
||||
assertTrue(sql.endsWith("' json 'auto'"), sql);
|
||||
verify(iamService).registerSessionForAccount(eq("000000000000"), anyString(), anyString(), anyString(),
|
||||
eq(LOAD_ROLE), any(Instant.class), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyAttemptMintsFreshCredentialsAndReleasesThem() throws Exception {
|
||||
knownLoadRole();
|
||||
|
||||
delivery.copy("000000000000", "us-east-1", destination(), "stage", "k1");
|
||||
delivery.copy("000000000000", "us-east-1", destination(), "stage", "k1");
|
||||
|
||||
assertNotEquals(sessionKey(executed.get(0)[3]), sessionKey(executed.get(1)[3]));
|
||||
verify(iamService, times(2)).unregisterSession(eq("000000000000"), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFailedCopyNeitherLeaksCredentialsIntoTheErrorNorKeepsTheSession() throws Exception {
|
||||
knownLoadRole();
|
||||
List<String> sent = new ArrayList<>();
|
||||
FirehoseRedshiftDelivery failing = new FirehoseRedshiftDelivery(redshift, serverless, secrets,
|
||||
roleAuthorizer, iamService, mapper, (url, user, password, sql) -> {
|
||||
sent.add(sql);
|
||||
throw new SQLException("rejected: " + sql, "XX000");
|
||||
});
|
||||
|
||||
IllegalStateException e = assertThrows(IllegalStateException.class,
|
||||
() -> failing.copy("000000000000", "us-east-1", destination(), "stage", "k1"));
|
||||
|
||||
String secret = sent.get(0).substring(sent.get(0).indexOf("aws_secret_access_key=") + 22,
|
||||
sent.get(0).indexOf(";token="));
|
||||
String token = sent.get(0).substring(sent.get(0).indexOf(";token=") + 7, sent.get(0).indexOf("' json"));
|
||||
assertFalse(e.getMessage().contains(secret), e.getMessage());
|
||||
assertFalse(e.getMessage().contains(token), e.getMessage());
|
||||
verify(iamService).unregisterSession(eq("000000000000"), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRoleIamDoesNotKnowLoadsWithoutCredentials() throws Exception {
|
||||
delivery.copy("000000000000", "us-east-1", destination(), "stage", "k1");
|
||||
|
||||
assertFalse(executed.get(0)[3].contains("CREDENTIALS"), executed.get(0)[3]);
|
||||
verify(iamService, never()).registerSessionForAccount(anyString(), anyString(), anyString(), anyString(),
|
||||
anyString(), any(Instant.class), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void secretOverridesInlineCredentialsWhenEnabled() throws Exception {
|
||||
RedshiftDestination dest = destination();
|
||||
@@ -275,7 +349,7 @@ class FirehoseRedshiftDeliveryTest {
|
||||
@Test
|
||||
void jdbcFailureIsWrappedWithTableClusterAndSqlState() {
|
||||
FirehoseRedshiftDelivery failing = new FirehoseRedshiftDelivery(redshift, serverless, secrets,
|
||||
roleAuthorizer, mapper,
|
||||
roleAuthorizer, iamService, mapper,
|
||||
(url, user, password, sql) -> {
|
||||
throw new SQLException("relation \"events\" does not exist", "42P01");
|
||||
});
|
||||
|
||||
+1
-1
@@ -69,7 +69,7 @@ class FirehoseRedshiftRoleAccessTest {
|
||||
ServiceRoleAuthorizer authorizer = new ServiceRoleAuthorizer(config, iamService, evaluator,
|
||||
new AssumeRolePolicyEvaluator(new ObjectMapper(), evaluator), scpProvider);
|
||||
delivery = new FirehoseRedshiftDelivery(mock(RedshiftService.class), mock(RedshiftServerlessService.class),
|
||||
mock(SecretsManagerService.class), authorizer, new ObjectMapper(),
|
||||
mock(SecretsManagerService.class), authorizer, iamService, new ObjectMapper(),
|
||||
(url, user, password, sql) -> { });
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.firehose;
|
||||
|
||||
import io.github.hectorvent.floci.services.redshift.proxy.RedshiftRoleAccess;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
@@ -126,6 +127,35 @@ class RedshiftCopySqlTest {
|
||||
assertEquals("COPY events FROM 's3://stage/2026/10/19/f.gz' json 'auto' gzip", sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildPutsCredentialsRightAfterTheSourceAndBeforeTheOptions() {
|
||||
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAEXAMPLE", "s3cr3t/+x", "tok==");
|
||||
|
||||
String sql = RedshiftCopySql.build("events", "id, name", "stage", "k", "json 'auto'", session);
|
||||
|
||||
assertEquals("COPY events (id, name) FROM 's3://stage/k' CREDENTIALS "
|
||||
+ "'aws_access_key_id=ASIAEXAMPLE;aws_secret_access_key=s3cr3t/+x;token=tok==' json 'auto'", sql);
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildRefusesCredentialsItCannotQuoteWithoutEchoingThem() {
|
||||
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAEXAMPLE", "bad'secret", "tok");
|
||||
|
||||
IllegalArgumentException e = assertThrows(IllegalArgumentException.class,
|
||||
() -> RedshiftCopySql.build("t", null, "b", "k", null, session));
|
||||
|
||||
assertFalse(e.getMessage().contains("bad"), e.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void redactHidesTheSecretAndTokenOnly() {
|
||||
RedshiftRoleAccess.RoleSession session = new RedshiftRoleAccess.RoleSession("ASIAEXAMPLE", "s3cr3t", "t0k3n9");
|
||||
|
||||
assertEquals("key ASIAEXAMPLE secret=*** token=***",
|
||||
RedshiftCopySql.redact("key ASIAEXAMPLE secret=s3cr3t token=t0k3n9", session));
|
||||
assertEquals("plain", RedshiftCopySql.redact("plain", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void buildDropsTheClosingTerminatorOfTheApiReferenceExample() {
|
||||
String sql = RedshiftCopySql.build("t", null, "b", "k", "delimiter '\\t' lzop;");
|
||||
|
||||
+18
@@ -116,6 +116,24 @@ class RedshiftAuditLogPublisherTest {
|
||||
"ALTER USER alice PASSWORD 'top-secret'"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void redactsCopyCredentialClausesFromActivityRecords() {
|
||||
assertEquals("COPY t FROM 's3://b/k' ACCESS_KEY_ID 'AKIAEXAMPLE' SECRET_ACCESS_KEY '[REDACTED]' "
|
||||
+ "SESSION_TOKEN '[REDACTED]'",
|
||||
RedshiftAuditLogPublisher.sanitizeSql("COPY t FROM 's3://b/k' ACCESS_KEY_ID 'AKIAEXAMPLE' "
|
||||
+ "SECRET_ACCESS_KEY 'top-secret' SESSION_TOKEN 'tok'"));
|
||||
assertEquals("COPY t FROM 's3://b/k' ACCESS_KEY_ID AS 'AKIAEXAMPLE' SECRET_ACCESS_KEY AS '[REDACTED]' "
|
||||
+ "SESSION_TOKEN AS '[REDACTED]'",
|
||||
RedshiftAuditLogPublisher.sanitizeSql("COPY t FROM 's3://b/k' ACCESS_KEY_ID AS 'AKIAEXAMPLE' "
|
||||
+ "SECRET_ACCESS_KEY AS 'top-secret' SESSION_TOKEN AS 'tok'"));
|
||||
assertEquals("COPY t FROM 's3://b/k' CREDENTIALS '[REDACTED]' CSV",
|
||||
RedshiftAuditLogPublisher.sanitizeSql("COPY t FROM 's3://b/k' "
|
||||
+ "CREDENTIALS 'aws_access_key_id=AKIA;aws_secret_access_key=top-secret' CSV"));
|
||||
assertEquals("COPY t FROM 's3://b/k' CREDENTIALS AS '[REDACTED]' CSV",
|
||||
RedshiftAuditLogPublisher.sanitizeSql("COPY t FROM 's3://b/k' "
|
||||
+ "CREDENTIALS AS 'aws_access_key_id=AKIA;aws_secret_access_key=top-secret' CSV"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {
|
||||
"ALTER USER alice PASSWORD /* rotation */ 'secret'",
|
||||
|
||||
+52
@@ -17,8 +17,10 @@ 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.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
@@ -120,6 +122,26 @@ class RedshiftRoleAccessTest {
|
||||
eq(session.sessionToken()), eq(held), any(Instant.class), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findRoleLooksUpTheRoleHonouringItsPath() {
|
||||
String held = "arn:aws:iam::111111111111:role/app/spectrum-role";
|
||||
String otherPath = "arn:aws:iam::111111111111:role/sandbox/spectrum-role";
|
||||
IamService iamService = iamServiceWithRole(TRUST_POLICY, held);
|
||||
|
||||
assertTrue(RedshiftRoleAccess.findRole(held, iamService).isPresent());
|
||||
assertTrue(RedshiftRoleAccess.findRole(otherPath, iamService).isEmpty());
|
||||
assertTrue(RedshiftRoleAccess.findRole(ROLE_ARN, iamService).isEmpty());
|
||||
assertTrue(RedshiftRoleAccess.findRole("not-an-arn", iamService).isEmpty());
|
||||
assertTrue(RedshiftRoleAccess.findRole("arn:aws:iam::111111111111:user/someone", iamService).isEmpty());
|
||||
assertTrue(RedshiftRoleAccess.findRole(null, iamService).isEmpty());
|
||||
|
||||
assertTrue(RedshiftRoleAccess.roleExists(held, iamService));
|
||||
assertFalse(RedshiftRoleAccess.roleExists(otherPath, iamService));
|
||||
assertFalse(RedshiftRoleAccess.roleExists(ROLE_ARN, iamService));
|
||||
assertFalse(RedshiftRoleAccess.roleExists("not-an-arn", iamService));
|
||||
assertFalse(RedshiftRoleAccess.roleExists(null, iamService));
|
||||
}
|
||||
|
||||
@Test
|
||||
void resolveRoleSessionRefusesARoleWhoseTrustPolicyExcludesRedshift() {
|
||||
assertRefused("trust policy", ROLE_ARN, iamServiceWithRole(EC2_TRUST_POLICY), ACCOUNT, List.of(ROLE_ARN));
|
||||
@@ -230,4 +252,34 @@ class RedshiftRoleAccessTest {
|
||||
// No exception, and resolvePrincipalContext is never consulted when enforcement is off.
|
||||
verifyNoInteractions(iamService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void authorizeRoleActionSuppliesPrincipalArnToOrganizationPolicies() {
|
||||
authorizeRoleWithOrganizationPolicy(ROLE_ARN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void authorizeRoleActionDeniesWhenPrincipalArnDoesNotMatchApprovedRoleInOrganizationPolicy() {
|
||||
String otherRole = "arn:aws:iam::111111111111:role/other-role";
|
||||
S3CopySimulator.S3TransferException exception = assertThrows(S3CopySimulator.S3TransferException.class,
|
||||
() -> authorizeRoleWithOrganizationPolicy(otherRole));
|
||||
|
||||
assertThat(exception.sqlState(), equalTo("42501"));
|
||||
assertThat(exception.getMessage(), containsString("S3 access denied"));
|
||||
}
|
||||
|
||||
private void authorizeRoleWithOrganizationPolicy(String roleArn) {
|
||||
S3Service s3 = mock(S3Service.class);
|
||||
when(s3.isAuthEnforced()).thenReturn(true);
|
||||
IamService iamService = mock(IamService.class);
|
||||
when(iamService.resolvePrincipalContext(roleArn)).thenReturn(CallerContext.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject","Resource":"*"}]}""")));
|
||||
when(iamService.effectiveScpLevels(ACCOUNT)).thenReturn(List.of(List.of("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"*","Resource":"*"},
|
||||
{"Effect":"Deny","Action":"s3:GetObject","Resource":"*",
|
||||
"Condition":{"ArnNotLike":{"aws:PrincipalArn":"%s"}}}]}""".formatted(ROLE_ARN))));
|
||||
|
||||
RedshiftRoleAccess.authorizeRoleAction(s3, iamService, roleArn, "s3:GetObject", "arn:aws:s3:::bucket/key");
|
||||
}
|
||||
}
|
||||
+18
-1
@@ -43,6 +43,7 @@ import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.inOrder;
|
||||
@@ -176,6 +177,22 @@ class S3CopySimulatorTest {
|
||||
return iamService;
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOrganizationPolicyDenyStillAppliesToTheKeysCopy() {
|
||||
IamService iamService = knownKey();
|
||||
when(iamService.findAccountForAccessKeyId("ASIAEXAMPLE")).thenReturn(Optional.of("222222222222"));
|
||||
when(iamService.effectiveScpLevels("222222222222")).thenReturn(List.of(List.of(policy(
|
||||
"{\"Effect\":\"Allow\",\"Action\":\"*\",\"Resource\":\"*\"},"
|
||||
+ "{\"Effect\":\"Deny\",\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}"))));
|
||||
when(iamService.resolveCallerContext("ASIAEXAMPLE")).thenReturn(CallerContext.of(List.of(policy(
|
||||
"{\"Effect\":\"Allow\",\"Action\":\"s3:*\",\"Resource\":\"*\"}"))));
|
||||
|
||||
S3CopySimulator.S3TransferException error = assertThrows(S3CopySimulator.S3TransferException.class,
|
||||
() -> S3CopySimulator.prepareCopy(keyCopy(), s3, iamService));
|
||||
|
||||
assertEquals("42501", error.sqlState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConditionalDenyOnThePrincipalArnStillAppliesToTheKeysCopy() {
|
||||
IamService iamService = knownKey();
|
||||
@@ -233,7 +250,7 @@ class S3CopySimulatorTest {
|
||||
|
||||
S3CopySimulator.prepareCopy(keyCopy(), s3, iamService);
|
||||
|
||||
verify(iamService).findAccountForAccessKeyId("ASIAEXAMPLE");
|
||||
verify(iamService, atLeastOnce()).findAccountForAccessKeyId("ASIAEXAMPLE");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user