Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,58 @@

import lombok.extern.slf4j.Slf4j;
import org.postgresql.ds.PGSimpleDataSource;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain;
import software.amazon.awssdk.services.rds.RdsUtilities;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.function.Supplier;

@Slf4j
public class PostgresAwsIamAuthDataSource extends PGSimpleDataSource {

static final String UNSET_REGION_SENTINEL = "aws-region-not-set";
private static final long TOKEN_EXPIRY_TIME = 5L * 60L * 1000L;

private transient AwsCredentialsProvider credentialsProvider;
private Region awsRegion;
private String authToken;
private long lastTokenRefresh = 0;
private static final long TOKEN_EXPIRY_TIME = 5L * 60L * 1000L;

public PostgresAwsIamAuthDataSource() {
this(DefaultCredentialsProvider.builder().build());
}

PostgresAwsIamAuthDataSource(AwsCredentialsProvider credentialsProvider) {
this.credentialsProvider = credentialsProvider;
}

public void setRegion(String region) {
this.awsRegion = Region.of(region);
setRegion(region, () -> DefaultAwsRegionProviderChain.builder().build().getRegion());
}

void setRegion(String region, Supplier<Region> defaultRegionSupplier) {
if (region != null && !region.isBlank() && !UNSET_REGION_SENTINEL.equals(region.trim())) {
this.awsRegion = Region.of(region.trim());
return;
}
try {
Region resolved = defaultRegionSupplier.get();
if (resolved == null) {
throw new IllegalStateException("No AWS region configured for RDS IAM authentication; set DatasourceAwsRegion or AWS_REGION");
}
this.awsRegion = resolved;
} catch (SdkClientException e) {
throw new IllegalStateException("No AWS region configured for RDS IAM authentication; set DatasourceAwsRegion or AWS_REGION", e);
}
}

Region getAwsRegion() {
return awsRegion;
}

@Override
Expand All @@ -34,19 +69,25 @@ public Connection getConnection(String user, String password) throws SQLExceptio
}
}

private void refreshAuthTokenIfNeeded() {
private synchronized void refreshAuthTokenIfNeeded() {
long currentTime = System.currentTimeMillis();
if (currentTime - lastTokenRefresh > TOKEN_EXPIRY_TIME) {
refreshAuthToken();
}
}

private void refreshAuthToken() {
private synchronized void refreshAuthToken() {
log.debug("Refreshing Postgres IAM token using AWS SDK");

if (awsRegion == null) {
setRegion(null);
}
if (credentialsProvider == null) {
credentialsProvider = DefaultCredentialsProvider.builder().build();
}
RdsUtilities rdsUtilities = RdsUtilities.builder()
.region(awsRegion)
.credentialsProvider(DefaultCredentialsProvider.create())
.credentialsProvider(credentialsProvider)
.build();

authToken = rdsUtilities.generateAuthenticationToken(r -> r
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public class EphemeralConfiguration {

private String namespace;
private String image;
private String serviceAccountName;
private List<String> secret;
private boolean emptyDirSecret = false;
private String initSecretImage = "busybox:1.37.0";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,13 @@ public void send(Job job, ExecutorContext executorContext) throws ExecutionExcep

Optional<String> serviceAccountInfo = Optional.ofNullable(
executorContext.getEnvironmentVariables().getOrDefault(SERVICE_ACCOUNT, null));
String serviceAccount = serviceAccountInfo.orElse(null);
String serviceAccount = serviceAccountInfo
.map(String::trim)
.filter(s -> !s.isEmpty())
.orElseGet(() -> {
String configured = ephemeralConfiguration.getServiceAccountName();
return (configured != null && !configured.isBlank()) ? configured.trim() : null;
});

// Volume and VolumeMount for ConfigMap if specified
List<Volume> volumes = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,23 @@
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.checksums.RequestChecksumCalculation;
import software.amazon.awssdk.core.checksums.ResponseChecksumValidation;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.core.retry.RetryPolicy;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.providers.DefaultAwsRegionProviderChain;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.S3Configuration;

import java.net.URI;
import java.time.Duration;
import java.util.function.Supplier;

@Configuration
@EnableConfigurationProperties({
Expand Down Expand Up @@ -63,11 +67,48 @@ static S3Configuration s3ServiceConfiguration(AwsStorageTypeProperties props) {
.build();
}

static AwsCredentialsProvider awsCredentialsProvider(
AwsStorageTypeProperties props, Supplier<AwsCredentialsProvider> defaultProvider) {
if (props.isEnableRoleAuthentication()) {
log.info("Creating AWS S3 client with default credential chain (role authentication enabled)");
return defaultProvider.get();
}
boolean hasAccess = props.getAccessKey() != null && !props.getAccessKey().isBlank();
boolean hasSecret = props.getSecretKey() != null && !props.getSecretKey().isBlank();
if (!hasAccess && !hasSecret) {
log.info("No static AWS keys configured; using default credential chain (IRSA / EKS Pod Identity)");
return defaultProvider.get();
}
if (hasAccess != hasSecret) {
throw new IllegalStateException("Both AwsStorageAccessKey and AwsStorageSecretKey must be set, or leave both empty for IRSA / Pod Identity");
}
return StaticCredentialsProvider.create(AwsBasicCredentials.create(props.getAccessKey(), props.getSecretKey()));
}

static Region awsRegion(String configuredRegion, Supplier<Region> defaultRegion) {
if (configuredRegion != null && !configuredRegion.isBlank()) {
return Region.of(configuredRegion.trim());
}
try {
Region resolved = defaultRegion.get();
if (resolved != null) {
return resolved;
}
} catch (SdkClientException e) {
throw new IllegalStateException("AwsStorageRegion is not set and AWS_REGION could not be resolved", e);
}
throw new IllegalStateException("AwsStorageRegion is not set and AWS_REGION could not be resolved");
}

static S3Client s3CompatibleClient(AwsStorageTypeProperties props, ClientOverrideConfiguration override) {
Supplier<Region> regionFallback = () -> DefaultAwsRegionProviderChain.builder().build().getRegion();
String signingRegion = props.getEndpointRegion() != null && !props.getEndpointRegion().isBlank()
? props.getEndpointRegion()
: props.getRegion();
return S3Client.builder()
.region(Region.of(props.getEndpointRegion()))
.credentialsProvider(StaticCredentialsProvider.create(getAwsBasicCredentials(props)))
.endpointOverride(URI.create(props.getEndpoint()))
.region(awsRegion(signingRegion, regionFallback))
.credentialsProvider(awsCredentialsProvider(props, () -> DefaultCredentialsProvider.builder().build()))
.endpointOverride(URI.create(props.getEndpoint().trim()))
.serviceConfiguration(s3ServiceConfiguration(props))
.requestChecksumCalculation(RequestChecksumCalculation.WHEN_REQUIRED)
.responseChecksumValidation(props.isChecksumValidationEnabled()
Expand Down Expand Up @@ -98,21 +139,17 @@ public StorageTypeService terraformOutput(StreamingService streamingService, Sto
case AWS:
S3Client s3client;
ClientOverrideConfiguration s3Override = storageClientOverride(awsStorageTypeProperties);
if (awsStorageTypeProperties.isEnableRoleAuthentication()) {
log.info("Creating AWS SDK with default credentials");
s3client = S3Client.builder()
.region(Region.of(awsStorageTypeProperties.getRegion()))
.credentialsProvider(DefaultCredentialsProvider.create())
.overrideConfiguration(s3Override)
.build();
} else if (awsStorageTypeProperties.getEndpoint() != null && !awsStorageTypeProperties.getEndpoint().isEmpty()) {
log.info("Creating AWS SDK with custom endpoint and custom credentials");
if (awsStorageTypeProperties.getEndpoint() != null && !awsStorageTypeProperties.getEndpoint().isBlank()) {
log.info("Creating AWS S3 client with custom endpoint {}", awsStorageTypeProperties.getEndpoint().trim());
s3client = s3CompatibleClient(awsStorageTypeProperties, s3Override);
} else {
log.info("Creating AWS SDK with custom credentials");
Region region = awsRegion(
awsStorageTypeProperties.getRegion(),
() -> DefaultAwsRegionProviderChain.builder().build().getRegion());
s3client = S3Client.builder()
.region(Region.of(awsStorageTypeProperties.getRegion()))
.credentialsProvider(StaticCredentialsProvider.create(getAwsBasicCredentials(awsStorageTypeProperties)))
.region(region)
.credentialsProvider(awsCredentialsProvider(
awsStorageTypeProperties, () -> DefaultCredentialsProvider.builder().build()))
.overrideConfiguration(s3Override)
.build();
}
Expand Down Expand Up @@ -141,9 +178,4 @@ public StorageTypeService terraformOutput(StreamingService streamingService, Sto
}
return storageTypeService;
}

private static AwsBasicCredentials getAwsBasicCredentials(AwsStorageTypeProperties awsStorageTypeProperties) {
AwsBasicCredentials awsCreds = AwsBasicCredentials.create(awsStorageTypeProperties.getAccessKey(), awsStorageTypeProperties.getSecretKey());
return awsCreds;
}
}
11 changes: 6 additions & 5 deletions api/src/main/resources/application-demo.properties
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ io.terrakube.agent.ssrf.blockPrivateNetworks=${AgentSsrfBlockPrivateNetworks:fal
##########################
io.terrakube.executor.ephemeral.namespace=${ExecutorEphemeralNamespace:terrakube}
io.terrakube.executor.ephemeral.image=${ExecutorEphemeralImage:azbuilder/executor:2.34.0}
io.terrakube.executor.ephemeral.serviceAccountName=${ExecutorEphemeralServiceAccount:}
## Comma-separated list for multiple secrets: e.g. "secret-one,secret-two"
io.terrakube.executor.ephemeral.secret=${ExecutorEphemeralSecret:terrakube-executor-secrets}
## Maximum seconds a job's pod may run before Kubernetes terminates it as failed; unset means no deadline (unbounded).
Expand Down Expand Up @@ -184,11 +185,11 @@ io.terrakube.storage.azure.accountKey=${AzureAccountKey}
###############
# AWS Storage #
###############
io.terrakube.storage.aws.accessKey=${AwsStorageAccessKey}
io.terrakube.storage.aws.secretKey=${AwsStorageSecretKey}
io.terrakube.storage.aws.bucketName=${AwsStorageBucketName}
io.terrakube.storage.aws.region=${AwsStorageRegion}
io.terrakube.storage.aws.endpoint=${AwsEndpoint}
io.terrakube.storage.aws.accessKey=${AwsStorageAccessKey:}
io.terrakube.storage.aws.secretKey=${AwsStorageSecretKey:}
io.terrakube.storage.aws.bucketName=${AwsStorageBucketName:}
io.terrakube.storage.aws.region=${AwsStorageRegion:}
io.terrakube.storage.aws.endpoint=${AwsEndpoint:}
io.terrakube.storage.aws.enableRoleAuthentication=${AwsEnableRoleAuth:false}

###############
Expand Down
12 changes: 7 additions & 5 deletions api/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,8 @@ io.terrakube.executor.url=${AzBuilderExecutorUrl}
##########################
io.terrakube.executor.ephemeral.namespace=${ExecutorEphemeralNamespace:terrakube}
io.terrakube.executor.ephemeral.image=${ExecutorEphemeralImage:azbuilder/executor:2.34.0}
# Optional default Kubernetes ServiceAccount for ephemeral executor pods (e.g. bound to an AWS IAM role via IRSA or EKS Pod Identity).
io.terrakube.executor.ephemeral.serviceAccountName=${ExecutorEphemeralServiceAccount:}
## Comma-separated list for multiple secrets: e.g. "secret-one,secret-two"
io.terrakube.executor.ephemeral.secret=${ExecutorEphemeralSecret:terrakube-executor-secrets}
io.terrakube.executor.ephemeral.emptyDirSecret=${ExecutorEphemeralEmptyDirSecret:true}
Expand Down Expand Up @@ -233,11 +235,11 @@ io.terrakube.storage.azure.accountKey=${AzureAccountKey}
###############
# AWS Storage #
###############
io.terrakube.storage.aws.accessKey=${AwsStorageAccessKey}
io.terrakube.storage.aws.secretKey=${AwsStorageSecretKey}
io.terrakube.storage.aws.bucketName=${AwsStorageBucketName}
io.terrakube.storage.aws.region=${AwsStorageRegion}
io.terrakube.storage.aws.endpoint=${AwsEndpoint}
io.terrakube.storage.aws.accessKey=${AwsStorageAccessKey:}
io.terrakube.storage.aws.secretKey=${AwsStorageSecretKey:}
io.terrakube.storage.aws.bucketName=${AwsStorageBucketName:}
io.terrakube.storage.aws.region=${AwsStorageRegion:}
io.terrakube.storage.aws.endpoint=${AwsEndpoint:}
io.terrakube.storage.aws.enableRoleAuthentication=${AwsEnableRoleAuth:false}
# S3-compatible backends (Qumulo, MinIO, ...) that need a real signing region or no chunked/checksum support
io.terrakube.storage.aws.endpointRegion=${AwsEndpointRegion:auto}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package io.terrakube.api.plugin.datasource;

import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.regions.Region;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;

class PostgresAwsIamAuthDataSourceTest {

@Test
void setRegionUsesExplicitConfiguredRegion() {
PostgresAwsIamAuthDataSource dataSource = new PostgresAwsIamAuthDataSource(mock(AwsCredentialsProvider.class));
dataSource.setRegion("eu-central-1");

assertEquals(Region.EU_CENTRAL_1, dataSource.getAwsRegion());
}

@Test
void setRegionFallsBackToDefaultChainWhenUnsetSentinelProvided() {
String previousAwsRegion = System.getProperty("aws.region");
System.setProperty("aws.region", "us-west-2");
try {
PostgresAwsIamAuthDataSource dataSource = new PostgresAwsIamAuthDataSource(mock(AwsCredentialsProvider.class));
dataSource.setRegion(PostgresAwsIamAuthDataSource.UNSET_REGION_SENTINEL);

assertEquals(Region.US_WEST_2, dataSource.getAwsRegion());
} finally {
if (previousAwsRegion == null) {
System.clearProperty("aws.region");
} else {
System.setProperty("aws.region", previousAwsRegion);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,15 @@ public void populatedValuesBindCorrectly() {
properties.put("io.terrakube.executor.ephemeral.backoffLimit", "2");
properties.put("io.terrakube.executor.ephemeral.ttlSecondsAfterFinished", "60");
properties.put("io.terrakube.executor.ephemeral.terminationGracePeriodSeconds", "90");
properties.put("io.terrakube.executor.ephemeral.serviceAccountName", "terrakube-executor-irsa");

EphemeralConfiguration config = bind(properties);

assertEquals(3600L, config.getActiveDeadlineSeconds());
assertEquals(2, config.getBackoffLimit());
assertEquals(60, config.getTtlSecondsAfterFinished());
assertEquals(90L, config.getTerminationGracePeriodSeconds());
assertEquals("terrakube-executor-irsa", config.getServiceAccountName());
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -666,4 +666,28 @@ public void logsWarningWhenEmptyDirSecretIsDisabled() throws ExecutionException
e.getLevel() == Level.WARN && e.getFormattedMessage().contains("emptyDirSecret is disabled")),
"Must log a warning when emptyDirSecret is false");
}

@Test
public void usesDefaultServiceAccountNameWhenWorkspaceDoesNotOverrideIt() throws ExecutionException {
config.setServiceAccountName("terrakube-executor-irsa");

subject().send(job(), context());

verify(namespaced, times(1)).resource(job.capture());
PodSpec podSpec = job.getValue().getSpec().getTemplate().getSpec();
assertEquals("terrakube-executor-irsa", podSpec.getServiceAccountName());
}

@Test
public void workspaceServiceAccountOverridesConfiguredDefault() throws ExecutionException {
config.setServiceAccountName("terrakube-executor-default");
ExecutorContext ctx = context();
ctx.getEnvironmentVariables().put("EPHEMERAL_CONFIG_SERVICE_ACCOUNT", "workspace-custom-sa");

subject().send(job(), ctx);

verify(namespaced, times(1)).resource(job.capture());
PodSpec podSpec = job.getValue().getSpec().getTemplate().getSpec();
assertEquals("workspace-custom-sa", podSpec.getServiceAccountName());
}
}
Loading
Loading