diff --git a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java index f5dfe62d23..2e4c439142 100644 --- a/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java +++ b/src/main/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionController.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint; import io.github.hectorvent.floci.services.appsync.AppSyncService; @@ -65,6 +66,7 @@ public class AppSyncExecutionController { private final ObjectMapper objectMapper; private final AuthMiddleware authMiddleware; private final RequestContext requestContext; + private final RegionResolver regionResolver; private final AppSyncResolverExecutor resolverExecutor; private final ResolverCallbackSessions callbackSessions; private final ContainerReachableEndpoint reachableEndpoint; @@ -79,6 +81,7 @@ public class AppSyncExecutionController { ObjectMapper objectMapper, AuthMiddleware authMiddleware, RequestContext requestContext, + RegionResolver regionResolver, AppSyncResolverExecutor resolverExecutor, ResolverCallbackSessions callbackSessions, ContainerReachableEndpoint reachableEndpoint) { @@ -91,6 +94,7 @@ public class AppSyncExecutionController { this.objectMapper = objectMapper; this.authMiddleware = authMiddleware; this.requestContext = requestContext; + this.regionResolver = regionResolver; this.resolverExecutor = resolverExecutor; this.callbackSessions = callbackSessions; this.reachableEndpoint = reachableEndpoint; @@ -341,7 +345,9 @@ public class AppSyncExecutionController { private AuthRequestInfo authRequestInfo(ParsedRequest parsed, HttpHeaders headers, String rawBody) { String accountId = requestContext.getAccountId() != null ? requestContext.getAccountId() : "000000000000"; - String region = requestContext.getRegion() != null ? requestContext.getRegion() : "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) + String region = requestContext.getRegion() != null + ? requestContext.getRegion() + : regionResolver.getDefaultRegion(); String requestId = headers.getHeaderString("x-amzn-RequestId"); if (requestId == null || requestId.isBlank()) { requestId = UUID.randomUUID().toString(); diff --git a/src/main/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumerator.java b/src/main/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumerator.java index d9e1a95f6b..223c5cd60f 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumerator.java +++ b/src/main/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumerator.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.ce.enumerator; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsRegions; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.ResourceUsageEnumerator; import io.github.hectorvent.floci.core.common.UsageLine; import io.github.hectorvent.floci.services.s3.S3Service; @@ -36,10 +37,12 @@ public class S3UsageEnumerator implements ResourceUsageEnumerator { private static final double SECONDS_PER_MONTH = 30.0 * 86_400.0; private final S3Service s3; + private final RegionResolver regionResolver; @Inject - public S3UsageEnumerator(S3Service s3) { + public S3UsageEnumerator(S3Service s3, RegionResolver regionResolver) { this.s3 = s3; + this.regionResolver = regionResolver; } @Override @@ -61,7 +64,7 @@ public class S3UsageEnumerator implements ResourceUsageEnumerator { for (Bucket bucket : buckets) { String bucketRegion = bucket.getRegion(); if (bucketRegion == null) { - bucketRegion = "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) + bucketRegion = regionResolver.getDefaultRegion(); } if (!bucketRegion.equals(region)) { continue; diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java index a1fe8864ec..7e566b74ab 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2JsonHandler.java @@ -469,8 +469,8 @@ public class CloudHsmV2JsonHandler { private ObjectNode backupNode(Backup backup, String region) { ObjectNode node = objectMapper.createObjectNode(); node.put("BackupId", backup.getBackupId()); - String arnRegion = region != null ? region : "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) - node.put("BackupArn", AwsArnUtils.Arn.of("cloudhsm", arnRegion, "000000000000", "backup/" + backup.getBackupId()).toString()); + node.put("BackupArn", AwsArnUtils.Arn.of("cloudhsm", region, "000000000000", + "backup/" + backup.getBackupId()).toString()); node.put("BackupState", backup.getBackupState()); node.put("ClusterId", backup.getClusterId()); if (backup.getHsmType() != null) { diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2Service.java b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2Service.java index d2c62bcabc..5a10012996 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudhsmv2/CloudHsmV2Service.java @@ -701,14 +701,14 @@ public class CloudHsmV2Service { public Backup copyBackupToRegion(String destinationRegion, String backupId, String sourceRegion) { // Source region emulation: we'll just clone the backup locally. - Backup source = getBackup(backupId, sourceRegion != null ? sourceRegion : "us-east-1"); // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) + Backup source = getBackup(backupId, sourceRegion); Backup copy = new Backup(); copy.setBackupId("backup-" + generateShortId()); copy.setBackupState("READY"); copy.setClusterId(source.getClusterId()); copy.setCreateTimestamp(source.getCreateTimestamp()); copy.setCopyTimestamp(Instant.now()); - copy.setSourceRegion(sourceRegion != null ? sourceRegion : "us-east-1"); // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) + copy.setSourceRegion(sourceRegion); copy.setSourceBackup(backupId); copy.setSourceCluster(source.getClusterId()); copy.setMode(source.getMode()); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java index 23472db181..5ee8dfbd90 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/CognitoService.java @@ -193,7 +193,7 @@ public class CognitoService implements ResourceProvider { lambdaService, acmService, new VerificationCodeService(storageFactory, clock), - new CognitoMessageDispatcher(sesService, snsService), + new CognitoMessageDispatcher(sesService, snsService, regionResolver.getDefaultRegion()), certificateManager, clock ); diff --git a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java index 5427272523..ef561df8c0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java +++ b/src/main/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcher.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.cognito.verification; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.services.cognito.model.CognitoUser; import io.github.hectorvent.floci.services.cognito.model.UserPool; import io.github.hectorvent.floci.services.ses.SesService; @@ -28,15 +29,17 @@ public final class CognitoMessageDispatcher { private static final String DEFAULT_EMAIL_BODY = "Your verification code is {####}."; private static final String DEFAULT_SMS_BODY = "Your verification code is {####}."; private static final String DEFAULT_FROM = "no-reply@verificationemail.com"; - private static final String DEFAULT_REGION = "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) private static final String CODE_PLACEHOLDER = "{####}"; private final SesService ses; private final SnsService sns; + private final String defaultRegion; - public CognitoMessageDispatcher(SesService ses, SnsService sns) { + /** {@code defaultRegion} serves a pool whose ARN names no region; a pool otherwise sends from its own. */ + public CognitoMessageDispatcher(SesService ses, SnsService sns, String defaultRegion) { this.ses = ses; this.sns = sns; + this.defaultRegion = defaultRegion; } public void dispatch(UserPool pool, CognitoUser user, VerificationCode.Purpose purpose, @@ -61,6 +64,7 @@ public final class CognitoMessageDispatcher { String phone = user.getAttributes().get("phone_number"); List mediums = resolveDeliveryMediums(deliveryMediums, email, phone); + String region = AwsArnUtils.regionOrDefault(pool.getArn(), defaultRegion); for (String medium : mediums) { if ("EMAIL".equalsIgnoreCase(medium) && email != null) { @@ -72,7 +76,7 @@ public final class CognitoMessageDispatcher { ses.sendEmail(SendEmailRequest.builder() .source(DEFAULT_FROM) .toAddresses(List.of(email)) - .region(DEFAULT_REGION) + .region(region) .content(new EmailContent.Simple(subject, body, null, List.of())) .build()); } else if ("SMS".equalsIgnoreCase(medium) && phone != null) { @@ -85,7 +89,7 @@ public final class CognitoMessageDispatcher { body, null, null, - DEFAULT_REGION + region ); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogController.java b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogController.java index cecbd885e4..6208208384 100644 --- a/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogController.java +++ b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogController.java @@ -4,7 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.JsonErrorResponseUtils; -import io.github.hectorvent.floci.core.common.RequestContext; +import io.github.hectorvent.floci.core.common.RegionResolver; import jakarta.inject.Inject; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.POST; @@ -21,22 +21,22 @@ import jakarta.ws.rs.core.Response; public class ControlCatalogController { private final ControlCatalogService controlCatalogService; private final ObjectMapper objectMapper; - private final RequestContext requestContext; + private final RegionResolver regionResolver; @Inject public ControlCatalogController(ControlCatalogService controlCatalogService, ObjectMapper objectMapper, - RequestContext requestContext) { + RegionResolver regionResolver) { this.controlCatalogService = controlCatalogService; this.objectMapper = objectMapper; - this.requestContext = requestContext; + this.regionResolver = regionResolver; } @POST @Path("/get-control") public Response getControl(String body) { JsonNode request = readTree(body); - return Response.ok(controlCatalogService.getControl(request, requestContext.getRegion())).build(); + return Response.ok(controlCatalogService.getControl(request, regionResolver.getRegion())).build(); } @POST @@ -45,7 +45,7 @@ public class ControlCatalogController { @QueryParam("nextToken") String nextToken, String body) { return Response.ok(controlCatalogService.listControls(readTree(body), maxResults, nextToken, - AwsRegions.partitionFor(requestContext.getRegion()))).build(); + AwsRegions.partitionFor(regionResolver.getRegion()))).build(); } private JsonNode readTree(String body) { diff --git a/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java index fabd529aed..7219dee881 100644 --- a/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java +++ b/src/main/java/io/github/hectorvent/floci/services/controlcatalog/ControlCatalogService.java @@ -74,8 +74,7 @@ public class ControlCatalogService implements Resettable { ObjectNode regionConfiguration = response.putObject("RegionConfiguration"); regionConfiguration.put("Scope", definition.scope()); if ("REGIONAL".equals(definition.scope())) { - String region = requestRegion == null || requestRegion.isBlank() ? "us-east-1" : requestRegion; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) - regionConfiguration.set("DeployableRegions", stringArray(List.of(region))); + regionConfiguration.set("DeployableRegions", stringArray(List.of(requestRegion))); } ObjectNode implementation = response.putObject("Implementation"); diff --git a/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java index 4af0dead3f..7698f027bd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/dynamodb/NativeDynamoDbJsonHandler.java @@ -2756,7 +2756,7 @@ public class NativeDynamoDbJsonHandler { sseDescription.put("KMSMasterKeyArn", table.getKmsMasterKeyArn() != null ? table.getKmsMasterKeyArn() : NativeDynamoDbTableService.defaultKmsMasterKeyArn( - AwsArnUtils.regionOrDefault(table.getTableArn(), "us-east-1"))); // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) + AwsArnUtils.parse(table.getTableArn()).region())); } node.set("SSEDescription", sseDescription); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java index 639d892a36..a52adb0d1d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServer.java @@ -374,14 +374,18 @@ public class Ec2MetadataServer { if (inst == null) { return; } - String body = instanceIdentityDocument(inst, config.defaultAccountId()); + String body = instanceIdentityDocument(inst, config.defaultAccountId(), config.defaultAvailabilityZone()); ctx.response().setStatusCode(200) .putHeader("content-type", "application/json") .end(body); } - static String instanceIdentityDocument(Instance inst, String accountId) { - String az = inst.getPlacement() != null ? inst.getPlacement().getAvailabilityZone() : "us-east-1a"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) + /** + * {@code defaultAvailabilityZone} answers for an instance with no placement, the same configured + * zone {@code /latest/meta-data/placement/availability-zone} reports for it. + */ + static String instanceIdentityDocument(Instance inst, String accountId, String defaultAvailabilityZone) { + String az = inst.getPlacement() != null ? inst.getPlacement().getAvailabilityZone() : defaultAvailabilityZone; String architecture = inst.getArchitecture() == null || inst.getArchitecture().isBlank() ? "x86_64" : inst.getArchitecture(); diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java index b89bd1cafa..82aca346f4 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksClusterManager.java @@ -7,6 +7,7 @@ import com.github.dockerjava.api.model.ContainerNetwork; import com.github.dockerjava.api.model.Info; import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.config.FlociCertificateAuthority; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsRegions; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.dns.DnsAnswer; @@ -1401,7 +1402,7 @@ public class EksClusterManager try { Files.createDirectories(localFile.getParent()); Files.writeString(localFile, buildWebhookKubeconfig("http://" + dockerHostResolver.resolve() + ":" - + config.port() + webhookPath(cluster))); + + config.port() + webhookPath(cluster, clusterRegion(cluster)))); } catch (IOException e) { LOG.warnv("EKS token-webhook disabled for cluster {0}: could not write kubeconfig: {1}", clusterName, e.getMessage()); @@ -2068,18 +2069,13 @@ public class EksClusterManager return "http://" + dockerHostResolver.resolve() + ":" + config.port() + webhookPath(clusterName); } - static String webhookPath(Cluster cluster) { + /** The cluster's ARN names its region; {@code defaultRegion} answers for a cluster without one. */ + static String webhookPath(Cluster cluster, String defaultRegion) { // client-go replaces a server URL query when constructing its TokenReview request. String accountId = cluster.getAccountId() != null && !cluster.getAccountId().isBlank() ? cluster.getAccountId() : (cluster.getArn() != null && cluster.getArn().split(":", 6).length > 4 ? cluster.getArn().split(":", 6)[4] : "000000000000"); - String region = "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) - if (cluster.getArn() != null) { - String[] parts = cluster.getArn().split(":", 6); - if (parts.length > 3 && !parts[3].isBlank()) { - region = parts[3]; - } - } + String region = AwsArnUtils.regionOrDefault(cluster.getArn(), defaultRegion); Instant createdAt = cluster.getCreatedAt() != null ? cluster.getCreatedAt() : Instant.EPOCH; return webhookPath(cluster.getName()) + "/scope/" + accountId + "/" + region + "/" + createdAt; @@ -2271,7 +2267,7 @@ public class EksClusterManager vpcId, vpcConfig.getSubnetIds(), vpcRouteTables); List entries = applicable.isEmpty() ? List.of() - : EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, applicable, ec2); + : EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, region, applicable, ec2); Set desiredDests = entries.stream() .map(EksVpcRouteProgramming.VpcRouteEntry::destinationCidrBlock) @@ -2386,7 +2382,8 @@ public class EksClusterManager if (config != null && config.defaultRegion() != null && !config.defaultRegion().isBlank()) { return config.defaultRegion(); } - return "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) + // Reached only by a test constructor that wires neither the resolver nor the config. + return "us-east-1"; // partition-literal: unreachable under CDI, where the resolver or config answers } String deriveClusterNodeAvailabilityZone(Cluster cluster, String region) { diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java index 8c0bc809af..fa79aac63d 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationService.java @@ -1,7 +1,9 @@ package io.github.hectorvent.floci.services.eks; import com.fasterxml.jackson.core.type.TypeReference; +import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; import io.github.hectorvent.floci.services.eks.model.Cluster; @@ -37,17 +39,20 @@ public class EksPodIdentityAssociationService { private final StorageBackend associations; private final IamService iam; + private final RegionResolver regionResolver; private final SecureRandom random = new SecureRandom(); @Inject - public EksPodIdentityAssociationService(StorageFactory factory, IamService iam) { + public EksPodIdentityAssociationService(StorageFactory factory, IamService iam, RegionResolver regionResolver) { this(factory.create("eks", "eks-pod-identity-associations.json", - new TypeReference>() {}), iam); + new TypeReference>() {}), iam, regionResolver); } - EksPodIdentityAssociationService(StorageBackend associations, IamService iam) { + EksPodIdentityAssociationService(StorageBackend associations, IamService iam, + RegionResolver regionResolver) { this.associations = associations; this.iam = iam; + this.regionResolver = regionResolver; } @RegisterForReflection @@ -118,19 +123,12 @@ public class EksPodIdentityAssociationService { } String associationId = generateAssociationId(); - String partition = "aws"; - String region = "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) - String accountId = cluster.getAccountId() != null ? cluster.getAccountId() : "000000000000"; - if (cluster.getArn() != null) { - String[] clusterArn = cluster.getArn().split(":", 6); - if (clusterArn.length == 6) { - partition = clusterArn[1]; - region = clusterArn[3]; - accountId = clusterArn[4]; - } - } - String associationArn = "arn:" + partition + ":eks:" + region + ":" - + accountId + ":podidentityassociation/" + cluster.getName() + "/" + associationId; + // The association lives in the cluster's region and account, which its ARN names. + String region = AwsArnUtils.regionOrDefault(cluster.getArn(), regionResolver.getDefaultRegion()); + String accountId = AwsArnUtils.accountOrDefault(cluster.getArn(), + cluster.getAccountId() != null ? cluster.getAccountId() : regionResolver.getDefaultAccountId()); + String associationArn = AwsArnUtils.Arn.of("eks", region, accountId, + "podidentityassociation/" + cluster.getName() + "/" + associationId).toString(); double now = Instant.now().toEpochMilli() / 1000.0; String externalId = UUID.randomUUID().toString(); @@ -315,15 +313,15 @@ public class EksPodIdentityAssociationService { } } + /** The partition role ARNs must share with the cluster: its own, or the deployment's without an ARN. */ + private String clusterPartition(Cluster cluster) { + return AwsArnUtils.partitionOrDefault(cluster != null ? cluster.getArn() : null, + regionResolver.getDefaultPartition()); + } + private void validateRoleArn(Cluster cluster, String roleArn, String fieldName) { String[] arn = roleArn.split(":", 6); - String expectedPartition = "aws"; - if (cluster != null && cluster.getArn() != null) { - String[] clusterArn = cluster.getArn().split(":", 6); - if (clusterArn.length > 1) { - expectedPartition = clusterArn[1]; - } - } + String expectedPartition = clusterPartition(cluster); if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].equals(expectedPartition) || !"iam".equals(arn[2]) || !arn[3].isEmpty() || !arn[4].matches("[0-9]{12}") || !arn[5].startsWith("role/") || arn[5].startsWith("role/aws-service-role/") @@ -336,15 +334,9 @@ public class EksPodIdentityAssociationService { .orElseThrow(() -> invalid("IAM role does not exist")); } - private static void validateTargetRoleArn(Cluster cluster, String targetRoleArn) { + private void validateTargetRoleArn(Cluster cluster, String targetRoleArn) { String[] arn = targetRoleArn.split(":", 6); - String expectedPartition = "aws"; - if (cluster != null && cluster.getArn() != null) { - String[] clusterArn = cluster.getArn().split(":", 6); - if (clusterArn.length > 1) { - expectedPartition = clusterArn[1]; - } - } + String expectedPartition = clusterPartition(cluster); if (arn.length != 6 || !"arn".equals(arn[0]) || !arn[1].equals(expectedPartition) || !"iam".equals(arn[2]) || !arn[3].isEmpty() || !arn[4].matches("[0-9]{12}") || !arn[5].startsWith("role/") || targetRoleArn.endsWith("/")) { diff --git a/src/main/java/io/github/hectorvent/floci/services/eks/EksVpcRouteProgramming.java b/src/main/java/io/github/hectorvent/floci/services/eks/EksVpcRouteProgramming.java index 4ca2ea413d..ad69e43175 100644 --- a/src/main/java/io/github/hectorvent/floci/services/eks/EksVpcRouteProgramming.java +++ b/src/main/java/io/github/hectorvent/floci/services/eks/EksVpcRouteProgramming.java @@ -128,12 +128,13 @@ public final class EksVpcRouteProgramming { return new ArrayList<>(result); } - public static List resolveProgrammableRoutes(Cluster cluster, List applicableTables, Ec2Service ec2Service) { + /** {@code region} is the cluster's own, as {@code EksClusterManager.clusterRegion} resolves it. */ + public static List resolveProgrammableRoutes(Cluster cluster, String region, + List applicableTables, Ec2Service ec2Service) { if (cluster == null || applicableTables == null || applicableTables.isEmpty() || ec2Service == null) { return List.of(); } String accountId = clusterAccountId(cluster); - String region = clusterRegion(cluster); Map resolved = new LinkedHashMap<>(); for (RouteTable table : applicableTables) { @@ -277,15 +278,6 @@ public final class EksVpcRouteProgramming { return null; } - private static String clusterRegion(Cluster cluster) { - if (cluster != null && cluster.getArn() != null) { - String[] parts = cluster.getArn().split(":"); - if (parts.length > 3 && !parts[3].isBlank()) { - return parts[3]; - } - } - return "us-east-1"; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) - } private static boolean isSet(String s) { return s != null && !s.isBlank(); diff --git a/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java b/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java index 03da92951b..333ac13854 100644 --- a/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java +++ b/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManager.java @@ -125,7 +125,7 @@ public class MwaaEnvironmentManager { .withExposedPort(POSTGRES_PORT) .withLogRotation() .withLabels(ContainerStorageHelper.resourceIdentityLabels( - "mwaa", name, environmentAccount(environment), environmentRegion(environment))) + "mwaa", name, environmentAccount(environment), regionOf(environment))) .build(); String dbContainerId = lifecycleManager.create(dbSpec); @@ -162,7 +162,7 @@ public class MwaaEnvironmentManager { // Points DAG code's own AWS SDK calls (boto3, botocore) at Floci itself, the same way // Lambda/ECS containers already do via LaunchedContainerAwsEnv — otherwise a real DAG's // boto3.client("s3") etc. would target real AWS instead of this emulator. - List env = new ArrayList<>(awsEnv.sdkBaselineEnv(environmentRegion(environment), Optional.empty())); + List env = new ArrayList<>(awsEnv.sdkBaselineEnv(regionOf(environment), Optional.empty())); env.addAll(List.of( "AIRFLOW__CORE__EXECUTOR=LocalExecutor", "AIRFLOW__DATABASE__SQL_ALCHEMY_CONN=" + sqlAlchemyConn, @@ -189,7 +189,7 @@ public class MwaaEnvironmentManager { .withDockerNetwork(config.services().mwaa().dockerNetwork()) .withLogRotation() .withLabels(ContainerStorageHelper.resourceIdentityLabels( - "mwaa", name, environmentAccount(environment), environmentRegion(environment))); + "mwaa", name, environmentAccount(environment), regionOf(environment))); if (!containerDetector.isRunningInContainer()) { specBuilder.withDynamicPort(AIRFLOW_WEBSERVER_PORT); @@ -486,16 +486,18 @@ public class MwaaEnvironmentManager { * Docker-backed service (EKS, RDS, ...). {@code config} may be {@code null} — the helper treats * that as "no namespace configured" and applies only the {@code floci-aws-} prefix. */ static String dbContainerName(EmulatorConfig config, Environment environment) { - return ContainerStorageHelper.dockerName(config, "mwaa-" + environmentIdentity(environment) + "-db"); + return ContainerStorageHelper.dockerName(config, "mwaa-" + environmentIdentity(config, environment) + "-db"); } static String airflowContainerName(EmulatorConfig config, Environment environment) { return ContainerStorageHelper.dockerName(config, - "mwaa-" + environmentIdentity(environment) + "-airflow"); + "mwaa-" + environmentIdentity(config, environment) + "-airflow"); } - private static String environmentIdentity(Environment environment) { - return environmentAccount(environment) + "." + environmentRegion(environment) + "." + environment.getName(); + private static String environmentIdentity(EmulatorConfig config, Environment environment) { + String defaultRegion = config != null ? config.defaultRegion() : null; + return environmentAccount(environment) + "." + environmentRegion(environment, defaultRegion) + "." + + environment.getName(); } static String environmentAccount(Environment environment) { @@ -504,8 +506,13 @@ public class MwaaEnvironmentManager { : AwsArnUtils.accountOrDefault(environment.getArn(), "000000000000"); } - static String environmentRegion(Environment environment) { - return AwsArnUtils.regionOrDefault(environment.getArn(), "us-east-1"); // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) + private String regionOf(Environment environment) { + return environmentRegion(environment, config.defaultRegion()); + } + + /** The region the environment's ARN names; {@code defaultRegion} answers for one without an ARN. */ + static String environmentRegion(Environment environment, String defaultRegion) { + return AwsArnUtils.regionOrDefault(environment.getArn(), defaultRegion); } /** diff --git a/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaService.java b/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaService.java index 0a110a6269..4b4912b980 100644 --- a/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaService.java +++ b/src/main/java/io/github/hectorvent/floci/services/mwaa/MwaaService.java @@ -715,7 +715,7 @@ public class MwaaService implements TagHandler { return region + "/" + name; } - static String environmentIdentity(Environment environment) { + String environmentIdentity(Environment environment) { return environmentAccount(environment) + "/" + environmentRegion(environment) + "/" + environment.getName(); } @@ -723,8 +723,8 @@ public class MwaaService implements TagHandler { return MwaaEnvironmentManager.environmentAccount(environment); } - private static String environmentRegion(Environment environment) { - return MwaaEnvironmentManager.environmentRegion(environment); + private String environmentRegion(Environment environment) { + return MwaaEnvironmentManager.environmentRegion(environment, regionResolver.getDefaultRegion()); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java index 3783316817..4352ad12e0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java +++ b/src/main/java/io/github/hectorvent/floci/services/pipes/PipesPoller.java @@ -50,6 +50,7 @@ public class PipesPoller implements Resettable { private final PipesFilterMatcher filterMatcher; private final ObjectMapper objectMapper; private final String baseUrl; + private final String defaultRegion; private final ConcurrentHashMap timerIds = new ConcurrentHashMap<>(); private final ConcurrentHashMap activePolls = new ConcurrentHashMap<>(); private final ConcurrentHashMap kinesisIterators = new ConcurrentHashMap<>(); @@ -80,6 +81,7 @@ public class PipesPoller implements Resettable { this.filterMatcher = filterMatcher; this.objectMapper = objectMapper; this.baseUrl = config.effectiveBaseUrl(); + this.defaultRegion = config.defaultRegion(); } @PreDestroy @@ -906,8 +908,9 @@ public class PipesPoller implements Resettable { return pipe.getArn() + "@" + pipe.getCreationTime(); } - private static String extractRegionFromArn(String arn) { - return AwsArnUtils.regionOrDefault(arn, "us-east-1"); // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) + /** The region a source ARN names; a source with none, such as a self-managed Kafka URI, polls in the default. */ + String extractRegionFromArn(String arn) { + return AwsArnUtils.regionOrDefault(arn, defaultRegion); } private static String extractResourceName(String arn) { diff --git a/src/main/java/io/github/hectorvent/floci/services/pricing/PricingService.java b/src/main/java/io/github/hectorvent/floci/services/pricing/PricingService.java index adca27adf8..ec36012e2a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/pricing/PricingService.java +++ b/src/main/java/io/github/hectorvent/floci/services/pricing/PricingService.java @@ -42,6 +42,8 @@ public class PricingService { private static final String ATTRIBUTE_VALUES_DIR = "attribute-values"; private static final String PRODUCTS_DIR = "products"; private static final String PRICE_LISTS_DIR = "price-lists"; + /** The products snapshot Floci bundles; a request without a region code reads it. */ + private static final String SNAPSHOT_REGION = "us-east-1"; // partition-literal: names the bundled snapshot file private final ObjectMapper objectMapper; private final SnapshotLoader loader; @@ -295,7 +297,7 @@ public class PricingService { } private List loadProducts(String serviceCode, String region) { - String resolvedRegion = (region == null || region.isEmpty()) ? "us-east-1" : region; // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) + String resolvedRegion = (region == null || region.isEmpty()) ? SNAPSHOT_REGION : region; requireSafePathSegment(resolvedRegion, "regionCode"); String resource = PRODUCTS_DIR + "/" + serviceCode + "/" + resolvedRegion + ".json"; JsonNode node; diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java index 53864e8957..25bc10bbb0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleDispatcher.java @@ -73,6 +73,7 @@ public class ScheduleDispatcher implements Resettable { private final ScheduleInvoker invoker; private final SqsService sqsService; private final String baseUrl; + private final String defaultRegion; private final long tickIntervalSeconds; private final boolean enabled; private final ScheduledExecutorService executor; @@ -89,6 +90,7 @@ public class ScheduleDispatcher implements Resettable { this.invoker = invoker; this.sqsService = sqsService; this.baseUrl = config.baseUrl(); + this.defaultRegion = config.defaultRegion(); this.tickIntervalSeconds = config.services().scheduler().tickIntervalSeconds(); this.enabled = config.services().scheduler().enabled() && config.services().scheduler().invocationEnabled(); @@ -364,8 +366,8 @@ public class ScheduleDispatcher implements Resettable { return "DELETE".equalsIgnoreCase(schedule.getActionAfterCompletion()); } - private static String regionOf(Schedule schedule) { - return ScheduleInvoker.regionOf(schedule); + private String regionOf(Schedule schedule) { + return ScheduleInvoker.regionOf(schedule, defaultRegion); } private record Occurrence(String scheduleArn, Instant scheduledAt) { diff --git a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java index 19a12e9e56..d83c27d9e2 100644 --- a/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java +++ b/src/main/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvoker.java @@ -56,6 +56,7 @@ public class ScheduleInvoker { private final StepFunctionsService stepFunctionsService; private final ObjectMapper objectMapper; private final String baseUrl; + private final String defaultRegion; @Inject public ScheduleInvoker(SqsService sqsService, @@ -74,6 +75,7 @@ public class ScheduleInvoker { this.stepFunctionsService = stepFunctionsService; this.objectMapper = objectMapper; this.baseUrl = config.baseUrl(); + this.defaultRegion = config.defaultRegion(); } /** @@ -86,7 +88,7 @@ public class ScheduleInvoker { return "{}"; } String arn = target.getArn(); - String region = regionOf(schedule); + String region = regionOf(schedule, defaultRegion); if (isUniversalTarget(arn)) { invokeUniversalTarget(arn.substring(arn.indexOf(":aws-sdk:") + ":aws-sdk:".length()), target.getInput(), region); @@ -478,8 +480,8 @@ public class ScheduleInvoker { return AwsArnUtils.regionOrDefault(arn, defaultRegion); } - /** The region a schedule lives in, taken from its ARN. */ - static String regionOf(Schedule schedule) { - return AwsArnUtils.regionOrDefault(schedule.getArn(), "us-east-1"); // partition-literal: fallback only when the record carries no region; no resolver in scope (follow-up) + /** The region a schedule lives in, taken from its ARN; {@code defaultRegion} answers for one without. */ + static String regionOf(Schedule schedule, String defaultRegion) { + return AwsArnUtils.regionOrDefault(schedule.getArn(), defaultRegion); } } diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java index 099b64821e..fa58e035c2 100644 --- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/AppSyncExecutionControllerTest.java @@ -2,12 +2,14 @@ package io.github.hectorvent.floci.services.appsync.graphql; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.services.appsync.AppSyncService; import io.github.hectorvent.floci.services.appsync.GraphqlSidecarClient; import io.github.hectorvent.floci.services.appsync.graphql.auth.AppSyncAuth; import io.github.hectorvent.floci.services.appsync.graphql.auth.AppSyncAuthContext; import io.github.hectorvent.floci.services.appsync.graphql.auth.AuthMiddleware; +import io.github.hectorvent.floci.services.appsync.graphql.auth.AuthRequestInfo; import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint; import io.github.hectorvent.floci.services.appsync.graphql.auth.SidecarFieldAuthorizationPlanner; import io.github.hectorvent.floci.services.appsync.graphql.resolver.AppSyncResolverError; @@ -80,6 +82,7 @@ class AppSyncExecutionControllerTest { new ObjectMapper(), authMiddleware, requestContext, + new RegionResolver("cn-north-1", "000000000000"), resolverExecutor, callbackSessions, reachableEndpoint); @@ -163,6 +166,20 @@ class AppSyncExecutionControllerTest { assertEquals("InternalFailure", error.get("message")); } + @Test + void aRequestWithoutARegionAuthorizesInTheDeploymentDefaultRegion() { + GraphqlApi api = new GraphqlApi(); + api.setApiId("api-1"); + when(appSyncService.getGraphqlApi("api-1")).thenReturn(api); + when(authMiddleware.authenticate(any(), any(), any())).thenThrow(AppSyncAuth.unauthorized()); + + controller.execute("api-1", jsonHeaders, "{\"query\":\"{ hello }\"}"); + + ArgumentCaptor info = ArgumentCaptor.forClass(AuthRequestInfo.class); + verify(authMiddleware).authenticate(any(), any(), info.capture()); + assertEquals("cn-north-1", info.getValue().region()); + } + @Test void authFailureReturns401WithoutCallingSidecar() { GraphqlApi api = new GraphqlApi(); diff --git a/src/test/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumeratorTest.java b/src/test/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumeratorTest.java new file mode 100644 index 0000000000..7cdef8a5d8 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ce/enumerator/S3UsageEnumeratorTest.java @@ -0,0 +1,40 @@ +package io.github.hectorvent.floci.services.ce.enumerator; + +import io.github.hectorvent.floci.core.common.RegionResolver; +import io.github.hectorvent.floci.core.common.UsageLine; +import io.github.hectorvent.floci.services.s3.S3Service; +import io.github.hectorvent.floci.services.s3.model.Bucket; +import io.github.hectorvent.floci.services.s3.model.S3Object; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class S3UsageEnumeratorTest { + + private static final Instant START = Instant.parse("2026-09-01T00:00:00Z"); + private static final Instant END = Instant.parse("2026-10-01T00:00:00Z"); + + @Test + void aBucketWithoutAStoredRegionIsBilledToTheDeploymentDefaultRegion() { + S3Service s3 = mock(S3Service.class); + when(s3.listBuckets()).thenReturn(List.of(new Bucket("legacy-bucket"))); + S3Object object = new S3Object(); + object.setSize(1_073_741_824L); + when(s3.listObjects(eq("legacy-bucket"), any(), any(), anyInt())).thenReturn(List.of(object)); + S3UsageEnumerator enumerator = new S3UsageEnumerator(s3, new RegionResolver("cn-north-1", "000000000000")); + + List lines = enumerator.enumerate(START, END, "cn-north-1").toList(); + + UsageLine bucketLine = lines.stream().filter(line -> line.resourceId() != null).findFirst().orElseThrow(); + assertEquals("cn-north-1", bucketLine.region()); + assertEquals("arn:aws-cn:s3:::legacy-bucket", bucketLine.resourceId()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java index d63948755a..b8e64ea0ee 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/CognitoLambdaTriggersTest.java @@ -92,7 +92,7 @@ class CognitoLambdaTriggersTest { new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>(), "http://localhost:4566", regionResolver, lambdaService, mock(AcmService.class), - verificationCodeService, new CognitoMessageDispatcher(ses, sns), + verificationCodeService, new CognitoMessageDispatcher(ses, sns, "us-east-1"), mock(TlsCertificateManager.class)); } diff --git a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.java b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.java index 1c5056c87c..1dc797547d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/cognito/verification/CognitoMessageDispatcherTest.java @@ -34,7 +34,7 @@ class CognitoMessageDispatcherTest { void setUp() { ses = mock(SesService.class); sns = mock(SnsService.class); - dispatcher = new CognitoMessageDispatcher(ses, sns); + dispatcher = new CognitoMessageDispatcher(ses, sns, "us-east-1"); } @Test @@ -183,6 +183,29 @@ class CognitoMessageDispatcherTest { verifyNoInteractions(ses); } + @Test + void dispatch_sendsFromThePoolsOwnRegion() { + UserPool pool = pool(Map.of()); + pool.setArn("arn:aws-cn:cognito-idp:cn-north-1:000000000000:userpool/cn-north-1_AbCdEfGhI"); + + dispatcher.dispatch(pool, user("alice@example.com", "+5215551234567"), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL", "SMS")); + + assertEquals("cn-north-1", sentEmail().region()); + verify(sns).publish(isNull(), isNull(), eq("+5215551234567"), anyString(), isNull(), isNull(), + eq("cn-north-1")); + } + + @Test + void dispatch_poolWithoutAnArnSendsFromTheDeploymentDefaultRegion() { + CognitoMessageDispatcher china = new CognitoMessageDispatcher(ses, sns, "cn-northwest-1"); + + china.dispatch(pool(Map.of()), user("alice@example.com", null), + VerificationCode.Purpose.SIGNUP_CONFIRMATION, "123456", List.of("EMAIL")); + + assertEquals("cn-northwest-1", sentEmail().region()); + } + private SendEmailRequest sentEmail() { ArgumentCaptor captor = ArgumentCaptor.forClass(SendEmailRequest.class); verify(ses).sendEmail(captor.capture()); diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServerTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServerTest.java index 344964fac6..54bd9a22e1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2MetadataServerTest.java @@ -80,14 +80,24 @@ class Ec2MetadataServerTest { instance.setPrivateIpAddress("10.0.0.10"); instance.setRegion("us-west-2"); - assertTrue(Ec2MetadataServer.instanceIdentityDocument(instance, "000000000000") + assertTrue(Ec2MetadataServer.instanceIdentityDocument(instance, "000000000000", "us-west-2a") .contains("\"architecture\":\"arm64\"")); instance.setArchitecture(null); - assertTrue(Ec2MetadataServer.instanceIdentityDocument(instance, "000000000000") + assertTrue(Ec2MetadataServer.instanceIdentityDocument(instance, "000000000000", "us-west-2a") .contains("\"architecture\":\"x86_64\"")); } + @Test + void identityDocumentOfAnInstanceWithoutPlacementReportsTheConfiguredZone() { + Instance instance = new Instance(); + instance.setInstanceId("i-china"); + instance.setRegion("cn-north-1"); + + assertTrue(Ec2MetadataServer.instanceIdentityDocument(instance, "000000000000", "cn-north-1b") + .contains("\"availabilityZone\":\"cn-north-1b\"")); + } + @Test void staleContainerUnregisterDoesNotRemoveCurrentRegistration() { Ec2MetadataServer server = new Ec2MetadataServer(null, null, null); diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksAddonServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksAddonServiceTest.java index 67c9271103..a66d0de779 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksAddonServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksAddonServiceTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.eks; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.eks.model.Addon; import io.github.hectorvent.floci.services.eks.model.AddonInfo; @@ -648,7 +649,8 @@ class EksAddonServiceTest { InMemoryStorage storage = new InMemoryStorage<>(); InMemoryStorage updatesStorage = new InMemoryStorage<>(); InMemoryStorage assocStorage = new InMemoryStorage<>(); - EksPodIdentityAssociationService podIdentityAssociations = new EksPodIdentityAssociationService(assocStorage, iam); + EksPodIdentityAssociationService podIdentityAssociations = new EksPodIdentityAssociationService( + assocStorage, iam, new RegionResolver("us-east-1", "000000000000")); EksAddonService service = new EksAddonService(storage, updatesStorage, catalog, iam, podIdentityAssociations); return new Fixture(cluster, iam, role, storage, updatesStorage, catalog, podIdentityAssociations, service); diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java index b534ebde40..5f925d5caa 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksClusterManagerTest.java @@ -104,16 +104,17 @@ class EksClusterManagerTest { cluster.setArn("arn:aws:eks:us-west-2:123456789012:cluster/demo"); cluster.setCreatedAt(Instant.parse("2026-09-17T00:00:00Z")); assertEquals("/_floci/eks/clusters/demo/token-webhook/scope/123456789012" - + "/us-west-2/2026-09-17T00:00:00Z", EksClusterManager.webhookPath(cluster)); + + "/us-west-2/2026-09-17T00:00:00Z", EksClusterManager.webhookPath(cluster, "cn-north-1")); } @Test void webhookPathHandlesMissingArnOrCreatedAtGracefully() { + // Without an ARN the region is the deployment default the caller passes, not us-east-1. Cluster cluster = new Cluster(); cluster.setName("demo"); cluster.setAccountId("123456789012"); assertEquals("/_floci/eks/clusters/demo/token-webhook/scope/123456789012" - + "/us-east-1/1970-01-01T00:00:00Z", EksClusterManager.webhookPath(cluster)); + + "/cn-north-1/1970-01-01T00:00:00Z", EksClusterManager.webhookPath(cluster, "cn-north-1")); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationServiceTest.java index a7b3f452f6..a2ed0b9880 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksPodIdentityAssociationServiceTest.java @@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.eks; import com.fasterxml.jackson.databind.ObjectMapper; import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.eks.model.Cluster; import io.github.hectorvent.floci.services.eks.model.ClusterStatus; @@ -265,6 +266,26 @@ class EksPodIdentityAssociationServiceTest { assertEquals(created.associationId(), found.get().associationId()); } + @Test + void anAssociationOnAClusterWithoutAnArnLivesInTheDeploymentRegionAndPartition() { + Cluster cluster = new Cluster(); + cluster.setName("cn-cluster"); + cluster.setAccountId("123456789012"); + cluster.setStatus(ClusterStatus.ACTIVE); + String chinaRole = "arn:aws-cn:iam::123456789012:role/pod-role"; + IamService iam = mock(IamService.class); + when(iam.findRole("123456789012", "pod-role")) + .thenReturn(Optional.of(new IamRole("AROA-pod", "pod-role", "/", chinaRole, "{}"))); + EksPodIdentityAssociationService service = new EksPodIdentityAssociationService(new InMemoryStorage<>(), iam, + new RegionResolver("cn-north-1", "000000000000")); + + PodIdentityAssociation created = service.create(cluster, new CreatePodIdentityAssociationRequest( + cluster.getName(), NAMESPACE, SERVICE_ACCOUNT, chinaRole, "token-cn", Map.of(), null, false, null)); + + assertEquals("arn:aws-cn:eks:cn-north-1:123456789012:podidentityassociation/cn-cluster/" + + created.associationId(), created.associationArn()); + } + private static Fixture fixture() { Cluster cluster = new Cluster(); cluster.setName("test-cluster"); @@ -277,7 +298,8 @@ class EksPodIdentityAssociationServiceTest { when(iam.findRole("123456789012", "pod-role")).thenReturn(Optional.of(role)); InMemoryStorage storage = new InMemoryStorage<>(); - return new Fixture(cluster, iam, role, storage, new EksPodIdentityAssociationService(storage, iam)); + return new Fixture(cluster, iam, role, storage, new EksPodIdentityAssociationService(storage, iam, + new RegionResolver("us-east-1", "000000000000"))); } private record Fixture(Cluster cluster, IamService iam, IamRole role, diff --git a/src/test/java/io/github/hectorvent/floci/services/eks/EksVpcRouteProgrammingTest.java b/src/test/java/io/github/hectorvent/floci/services/eks/EksVpcRouteProgrammingTest.java index d080618a93..1734dd60ba 100644 --- a/src/test/java/io/github/hectorvent/floci/services/eks/EksVpcRouteProgrammingTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/eks/EksVpcRouteProgrammingTest.java @@ -26,6 +26,7 @@ import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class EksVpcRouteProgrammingTest { @@ -224,13 +225,33 @@ class EksVpcRouteProgrammingTest { rt.setRoutes(List.of(r1, r2, rDefault, rPrefix, rIgw, rPcx)); List entries = - EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, List.of(rt), ec2); + EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, "us-east-1", List.of(rt), ec2); assertEquals(2, entries.size()); assertTrue(entries.stream().anyMatch(e -> "10.100.0.0/16".equals(e.destinationCidrBlock()) && "172.18.0.10".equals(e.gatewayIp()))); assertTrue(entries.stream().anyMatch(e -> "10.200.0.0/16".equals(e.destinationCidrBlock()) && "172.18.0.20".equals(e.gatewayIp()))); } + @Test + void resolveProgrammableRoutesLooksEnisUpInTheRegionItIsGiven() { + Ec2Service ec2 = mock(Ec2Service.class); + Cluster cluster = new Cluster(); + cluster.setName("test-cluster"); + cluster.setAccountId("123456789012"); + when(ec2.describeNetworkInterfaces(anyString(), anyString(), anyList(), any())) + .thenReturn(new NetworkInterfaceListResult(List.of(), null)); + + RouteTable rt = new RouteTable(); + rt.setRouteTableId("rtb-1"); + Route rEni = new Route("10.200.0.0/16", null, "CreateRoute"); + rEni.setNetworkInterfaceId("eni-1"); + rt.setRoutes(List.of(rEni)); + + EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, "cn-north-1", List.of(rt), ec2); + + verify(ec2).describeNetworkInterfaces(eq("123456789012"), eq("cn-north-1"), eq(List.of("eni-1")), any()); + } + @Test void resolveProgrammableRoutesSkipsUnattachedEni() { Ec2Service ec2 = mock(Ec2Service.class); @@ -254,7 +275,7 @@ class EksVpcRouteProgrammingTest { rt.setRoutes(List.of(rEni)); List entries = - EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, List.of(rt), ec2); + EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, "us-east-1", List.of(rt), ec2); assertTrue(entries.isEmpty(), "Unattached ENI must not be resolved as a route gateway"); } @@ -284,7 +305,7 @@ class EksVpcRouteProgrammingTest { rt.setRoutes(List.of(rMissing, rValid)); List entries = - EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, List.of(rt), ec2); + EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, "us-east-1", List.of(rt), ec2); assertEquals(1, entries.size(), "Valid instance route must still resolve despite missing ENI"); assertEquals("10.201.0.0/16", entries.get(0).destinationCidrBlock()); @@ -324,7 +345,7 @@ class EksVpcRouteProgrammingTest { rt.setRoutes(List.of(rEni)); List entries = - EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, List.of(rt), ec2); + EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, "us-east-1", List.of(rt), ec2); assertEquals(1, entries.size()); assertEquals("10.0.1.20", entries.get(0).gatewayIp()); @@ -363,7 +384,7 @@ class EksVpcRouteProgrammingTest { rt.setRoutes(List.of(rEni)); List entries = - EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, List.of(rt), ec2); + EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, "us-east-1", List.of(rt), ec2); assertEquals(1, entries.size()); assertEquals("172.18.0.20", entries.get(0).gatewayIp(), @@ -402,7 +423,7 @@ class EksVpcRouteProgrammingTest { rt.setRoutes(List.of(rEni)); List entries = - EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, List.of(rt), ec2); + EksVpcRouteProgramming.resolveProgrammableRoutes(cluster, "us-east-1", List.of(rt), ec2); assertEquals(1, entries.size()); assertEquals("172.17.0.5", entries.get(0).gatewayIp(), diff --git a/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManagerTest.java index 5a331a881f..98cd21fbd1 100644 --- a/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManagerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaEnvironmentManagerTest.java @@ -325,6 +325,25 @@ class MwaaEnvironmentManagerTest { MwaaEnvironmentManager.airflowContainerName(namespacedConfig, environment)); } + @Test + void anEnvironmentWithoutAnArnIsNamedInTheConfiguredDefaultRegion() { + EmulatorConfig.DockerConfig dockerConfig = Mockito.mock(EmulatorConfig.DockerConfig.class); + when(dockerConfig.resourceNamespace()).thenReturn(Optional.empty()); + EmulatorConfig chinaConfig = Mockito.mock(EmulatorConfig.class); + when(chinaConfig.docker()).thenReturn(dockerConfig); + when(chinaConfig.defaultRegion()).thenReturn("cn-north-1"); + + Environment environment = new Environment(); + environment.setName("my-env"); + environment.setAccountId("000000000000"); + + assertEquals("floci-aws-mwaa-000000000000.cn-north-1.my-env-db", + MwaaEnvironmentManager.dbContainerName(chinaConfig, environment)); + assertEquals("cn-north-1", MwaaEnvironmentManager.environmentRegion(environment, "cn-north-1")); + environment.setArn("arn:aws:airflow:eu-west-1:000000000000:environment/my-env"); + assertEquals("eu-west-1", MwaaEnvironmentManager.environmentRegion(environment, "cn-north-1")); + } + @Test void scopedContainerNamesDifferForSameNameEnvironments() { Environment eastEnvironment = new Environment(); diff --git a/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaServiceTest.java index a4caf05cd1..2e780a93cf 100644 --- a/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/mwaa/MwaaServiceTest.java @@ -120,10 +120,10 @@ class MwaaServiceTest { createRequest("arn:aws:s3:::west-bucket", "dags")); String westToken = (String) mwaaService.createCliToken("shared-name").get("CliToken"); - assertTrue(mwaaService.isValidCliToken(MwaaService.environmentIdentity(westEnvironment), westToken)); - assertFalse(mwaaService.isValidCliToken(MwaaService.environmentIdentity(westEnvironment), eastToken)); - assertTrue(mwaaService.isValidCliToken(MwaaService.environmentIdentity(eastEnvironment), eastToken)); - assertFalse(mwaaService.isValidCliToken(MwaaService.environmentIdentity(eastEnvironment), westToken)); + assertTrue(mwaaService.isValidCliToken(mwaaService.environmentIdentity(westEnvironment), westToken)); + assertFalse(mwaaService.isValidCliToken(mwaaService.environmentIdentity(westEnvironment), eastToken)); + assertTrue(mwaaService.isValidCliToken(mwaaService.environmentIdentity(eastEnvironment), eastToken)); + assertFalse(mwaaService.isValidCliToken(mwaaService.environmentIdentity(eastEnvironment), westToken)); } @Test @@ -535,9 +535,9 @@ class MwaaServiceTest { Map response = mwaaService.createCliToken("cli-token-env"); String token = (String) response.get("CliToken"); assertNotNull(token); - assertTrue(mwaaService.isValidCliToken(MwaaService.environmentIdentity( + assertTrue(mwaaService.isValidCliToken(mwaaService.environmentIdentity( mwaaService.getEnvironment("cli-token-env")), token)); - assertFalse(mwaaService.isValidCliToken(MwaaService.environmentIdentity( + assertFalse(mwaaService.isValidCliToken(mwaaService.environmentIdentity( mwaaService.getEnvironment("cli-token-env")), "not-a-real-token")); assertFalse(mwaaService.isValidCliToken("other-env", token)); } @@ -637,7 +637,7 @@ class MwaaServiceTest { assertEquals(EnvironmentStatus.CREATE_FAILED, environment.getStatus()); verify(portAllocator).release(8701); verify(environmentManager).stopEnvironment(environment); - verify(proxyManager).stopProxy(MwaaService.environmentIdentity(environment)); + verify(proxyManager).stopProxy(mwaaService.environmentIdentity(environment)); } @Test diff --git a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java index 2416074f20..beff9ac091 100644 --- a/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/pipes/PipesPollerTest.java @@ -129,6 +129,15 @@ class PipesPollerTest { } } + @Test + void aSourceWithoutAnArnRegionPollsInTheDeploymentDefaultRegion() { + when(config.defaultRegion()).thenReturn("cn-north-1"); + PipesPoller chinaPoller = pollerOver(streams); + + assertEquals("cn-north-1", chinaPoller.extractRegionFromArn("smk://broker.internal:9092")); + assertEquals("eu-west-1", chinaPoller.extractRegionFromArn("arn:aws:sqs:eu-west-1:000000000000:orders")); + } + @Test void asEventArrayWrapsSingleObjectInBatchArray() throws Exception { // Pipes delivers events to a target as a batch array; a single-object enrichment response diff --git a/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvokerTest.java b/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvokerTest.java index dff3ba2f0e..db10396284 100644 --- a/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvokerTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/scheduler/ScheduleInvokerTest.java @@ -90,6 +90,15 @@ class ScheduleInvokerTest { return schedule; } + @Test + void aScheduleWithoutAnArnLivesInTheDeploymentDefaultRegion() { + Schedule schedule = new Schedule(); + assertEquals("cn-north-1", ScheduleInvoker.regionOf(schedule, "cn-north-1")); + + schedule.setArn("arn:aws:scheduler:eu-west-1:000000000000:schedule/default/nightly"); + assertEquals("eu-west-1", ScheduleInvoker.regionOf(schedule, "cn-north-1")); + } + @Test void universalSnsPublishForwardsMessageAttributes() { Target target = new Target();