From be4803d3d8df477d95c5ca1bbf141a8d86b7035a Mon Sep 17 00:00:00 2001 From: Hector Ventura Date: Thu, 26 Nov 2026 13:04:07 -0600 Subject: [PATCH] fix(batch): keep compute environments, job queues, definitions and jobs in their Region (#9489) The four Batch stores were shared by every Region, and every list, describe and name lookup scanned them whole, so a compute environment, job queue, job definition or job of one Region was listed, resolved, tagged and submitted to from another, names could not be reused across Regions and job definition revisions counted across them. Reads now filter by the Region each record stores, and a job definition ARN of another Region answers not found instead of falling back to a local revision of the same name. An EventBridge target submits in its queue's Region. --- .../aws/services/batch/BatchService.java | 75 ++++-- .../services/batch/BatchIntegrationTest.java | 221 +++++++++++++++++- 2 files changed, 276 insertions(+), 20 deletions(-) diff --git a/src/main/java/io/floci/aws/services/batch/BatchService.java b/src/main/java/io/floci/aws/services/batch/BatchService.java index 6efd6f177f..cf44c19637 100644 --- a/src/main/java/io/floci/aws/services/batch/BatchService.java +++ b/src/main/java/io/floci/aws/services/batch/BatchService.java @@ -159,7 +159,7 @@ public class BatchService { int offset = parseNextToken(textOrNull(request, "nextToken")); List envs; if (refs.isEmpty()) { - envs = computeEnvironmentStore.scan(k -> true).stream() + envs = computeEnvironmentsInRegion().stream() .sorted(Comparator.comparing(BatchComputeEnvironment::getComputeEnvironmentName)) .toList(); } else { @@ -215,7 +215,7 @@ public class BatchService { throw client("Cannot delete compute environment in " + target.getState() + " state: " + target.getComputeEnvironmentName()); } - boolean stillAttached = jobQueueStore.scan(k -> true).stream() + boolean stillAttached = jobQueuesInRegion().stream() .flatMap(q -> q.getComputeEnvironmentOrder().stream()) .anyMatch(order -> resolveComputeEnvironmentOptional(order.getComputeEnvironment()) .map(BatchComputeEnvironment::getComputeEnvironmentArn) @@ -434,7 +434,7 @@ public class BatchService { } if (resource.startsWith("job/")) { String jobId = resource.substring("job/".length()); - BatchJob job = jobStore.get(jobId).orElseThrow(() -> client("Job not found: " + resourceArn)); + BatchJob job = getJob(jobId).orElseThrow(() -> client("Job not found: " + resourceArn)); return new Taggable(tagsOf(job.getTags()), tags -> { job.setTags(tags); jobStore.put(job.getJobId(), job); @@ -456,7 +456,7 @@ public class BatchService { int offset = parseNextToken(textOrNull(request, "nextToken")); List queues; if (refs.isEmpty()) { - queues = jobQueueStore.scan(k -> true).stream() + queues = jobQueuesInRegion().stream() .sorted(Comparator.comparing(BatchJobQueue::getJobQueueName)) .toList(); } else { @@ -546,7 +546,7 @@ public class BatchService { } int maxResults = describeMaxResults(request); int offset = parseNextToken(textOrNull(request, "nextToken")); - List definitions = jobDefinitionStore.scan(k -> true).stream() + List definitions = jobDefinitionsInRegion().stream() .filter(def -> status == null || status.equals(def.getStatus())) .filter(def -> name == null || name.equals(def.getJobDefinitionName())) .filter(def -> refs.isEmpty() || refs.stream().anyMatch(ref -> matchesJobDefinition(def, ref))) @@ -621,7 +621,7 @@ public class BatchService { BatchJob job = getJob(jobId).orElseThrow(() -> client("Job not found: " + jobId)); if (job.getArraySize() != null) { boolean changed = false; - List children = jobStore.scan(k -> true).stream() + List children = jobsInRegion().stream() .filter(child -> jobId.equals(child.getArrayJobId())) .toList(); for (BatchJob child : children) { @@ -908,7 +908,7 @@ public class BatchService { int offset = parseNextToken(textOrNull(request, "nextToken")); // A queue-level listing shows one entry per array job (the parent), matching AWS. - List jobs = jobStore.scan(k -> true).stream() + List jobs = jobsInRegion().stream() .filter(job -> queue.getJobQueueArn().equals(job.getJobQueue())) .filter(job -> job.getArrayIndex() == null) .filter(job -> (filter != null && !"SHARE_IDENTIFIER".equals(filter.name())) @@ -941,7 +941,7 @@ public class BatchService { : FILTERED_MAX_RESULTS; int offset = parseNextToken(textOrNull(request, "nextToken")); - List children = jobStore.scan(k -> true).stream() + List children = jobsInRegion().stream() .filter(job -> arrayJobId.equals(job.getArrayJobId())) .filter(job -> status == null || status.equals(job.getStatus())) .sorted(Comparator.comparingInt(BatchJob::getArrayIndex)) @@ -996,7 +996,7 @@ public class BatchService { if (!retry.isEmpty()) { request.set("retryStrategy", retry); } - submitJob(request, region); + RequestScopes.runAs(regionResolver.getAccountId(), region, () -> submitJob(request, region)); } private ObjectNode eventBridgeRetryStrategy(JsonNode retryStrategy) { @@ -1319,11 +1319,11 @@ public class BatchService { if (ref == null || ref.isBlank()) { return Optional.empty(); } - Optional byArn = jobQueueStore.get(ref); + Optional byArn = jobQueueStore.get(ref).filter(q -> inRequestRegion(q.getRegion())); if (byArn.isPresent()) { return byArn; } - return jobQueueStore.scan(k -> true).stream() + return jobQueuesInRegion().stream() .filter(q -> ref.equals(q.getJobQueueName()) || ref.equals(q.getJobQueueArn())) .findFirst(); } @@ -1337,11 +1337,12 @@ public class BatchService { if (ref == null || ref.isBlank()) { return Optional.empty(); } - Optional byArn = computeEnvironmentStore.get(ref); + Optional byArn = computeEnvironmentStore.get(ref) + .filter(env -> inRequestRegion(env.getRegion())); if (byArn.isPresent()) { return byArn; } - return computeEnvironmentStore.scan(k -> true).stream() + return computeEnvironmentsInRegion().stream() .filter(env -> ref.equals(env.getComputeEnvironmentName()) || ref.equals(env.getComputeEnvironmentArn())) .findFirst(); } @@ -1355,7 +1356,7 @@ public class BatchService { if (ref == null || ref.isBlank()) { return Optional.empty(); } - Optional byArn = jobDefinitionStore.get(ref); + Optional byArn = jobDefinitionStore.get(ref).filter(def -> inRequestRegion(def.getRegion())); if (byArn.isPresent() && (includeInactive || "ACTIVE".equals(byArn.get().getStatus()))) { return byArn; } @@ -1363,6 +1364,9 @@ public class BatchService { if (AwsArnUtils.looksLikeArn(ref)) { try { String resource = AwsArnUtils.parse(ref).resource(); + if (!regionResolver.inRequestRegion(ref)) { + return Optional.empty(); + } if (resource.startsWith("job-definition/")) { logical = resource.substring("job-definition/".length()); } @@ -1383,7 +1387,7 @@ public class BatchService { } String finalName = name; Integer finalRevision = revision; - return jobDefinitionStore.scan(k -> true).stream() + return jobDefinitionsInRegion().stream() .filter(def -> finalName.equals(def.getJobDefinitionName())) .filter(def -> finalRevision == null || finalRevision == def.getRevision()) .filter(def -> includeInactive || "ACTIVE".equals(def.getStatus())) @@ -1401,7 +1405,7 @@ public class BatchService { if (AwsArnUtils.looksLikeArn(ref)) { try { String resource = AwsArnUtils.parse(ref).resource(); - if (!resource.startsWith("job-definition/")) { + if (!regionResolver.inRequestRegion(ref) || !resource.startsWith("job-definition/")) { return false; } logical = resource.substring("job-definition/".length()); @@ -1423,7 +1427,7 @@ public class BatchService { } private int nextRevision(String name) { - return jobDefinitionStore.scan(k -> true).stream() + return jobDefinitionsInRegion().stream() .filter(def -> name.equals(def.getJobDefinitionName())) .mapToInt(BatchJobDefinition::getRevision) .max() @@ -1788,7 +1792,7 @@ public class BatchService { // Computed live from children on every read, rather than an incrementally updated counter, to avoid races. private ArrayRollup arrayRollup(String parentJobId) { - List children = jobStore.scan(k -> true).stream() + List children = jobsInRegion().stream() .filter(job -> parentJobId.equals(job.getArrayJobId())) .toList(); Map statusSummary = new LinkedHashMap<>(); @@ -2080,8 +2084,41 @@ public class BatchService { return Math.max(1, Math.min(DESCRIBE_JOBS_LIMIT, request.path("maxResults").asInt())); } + /** The request's Region's job {@code jobId}: job ids are unique, but a job is visible only in its own Region. */ private Optional getJob(String jobId) { - return jobStore.get(jobId); + return jobStore.get(jobId).filter(job -> inRequestRegion(job.getRegion())); + } + + /* + * The four stores are shared by every Region, keyed by ARN or job id, and each record carries the Region it was + * created in, records stored before this filter included, so a request sees only its own Region's records. + */ + private List computeEnvironmentsInRegion() { + return computeEnvironmentStore.scan(k -> true).stream() + .filter(env -> inRequestRegion(env.getRegion())) + .toList(); + } + + private List jobQueuesInRegion() { + return jobQueueStore.scan(k -> true).stream() + .filter(queue -> inRequestRegion(queue.getRegion())) + .toList(); + } + + private List jobDefinitionsInRegion() { + return jobDefinitionStore.scan(k -> true).stream() + .filter(def -> inRequestRegion(def.getRegion())) + .toList(); + } + + private List jobsInRegion() { + return jobStore.scan(k -> true).stream() + .filter(job -> inRequestRegion(job.getRegion())) + .toList(); + } + + private boolean inRequestRegion(String region) { + return regionResolver.getRegion().equals(region != null ? region : regionResolver.getDefaultRegion()); } @SuppressWarnings("unchecked") diff --git a/src/test/java/io/floci/aws/services/batch/BatchIntegrationTest.java b/src/test/java/io/floci/aws/services/batch/BatchIntegrationTest.java index 12b8496e5e..28c3d3bc88 100644 --- a/src/test/java/io/floci/aws/services/batch/BatchIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/batch/BatchIntegrationTest.java @@ -10,7 +10,9 @@ import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; @@ -19,6 +21,8 @@ class BatchIntegrationTest { private static final String AUTH = "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/batch/aws4_request"; + private static final String EU_AUTH = + "AWS4-HMAC-SHA256 Credential=test/20260205/eu-west-1/batch/aws4_request"; @Test void submitDescribeAndListImmediateJob() { @@ -808,9 +812,224 @@ class BatchIntegrationTest { .header("X-Amzn-Errortype", "ClientException"); } + @Test + void resourcesOfOneRegionAreInvisibleFromAnother() { + String suffix = uniqueSuffix(); + String ceName = "batch-region-ce-" + suffix; + String queueName = "batch-region-queue-" + suffix; + String definitionName = "batch-region-job-" + suffix; + String ceArn = createComputeEnvironment(ceName); + String queueArn = createQueue(queueName, ceArn); + String definitionArn = registerJobDefinition(definitionName, "[]", "[]"); + String jobId = submit(queueArn, definitionArn, "batch-region-submit-" + suffix); + + givenJson(EU_AUTH, "{}") + .when() + .post("/v1/describecomputeenvironments") + .then() + .statusCode(200) + .body("computeEnvironments.computeEnvironmentArn", not(hasItem(ceArn))); + givenJson(EU_AUTH, "{\"computeEnvironments\":[\"%s\",\"%s\"]}".formatted(ceName, ceArn)) + .when() + .post("/v1/describecomputeenvironments") + .then() + .statusCode(200) + .body("computeEnvironments", hasSize(0)); + givenJson(EU_AUTH, "{}") + .when() + .post("/v1/describejobqueues") + .then() + .statusCode(200) + .body("jobQueues.jobQueueArn", not(hasItem(queueArn))); + givenJson(EU_AUTH, "{\"jobQueues\":[\"%s\",\"%s\"]}".formatted(queueName, queueArn)) + .when() + .post("/v1/describejobqueues") + .then() + .statusCode(200) + .body("jobQueues", hasSize(0)); + givenJson(EU_AUTH, "{}") + .when() + .post("/v1/describejobdefinitions") + .then() + .statusCode(200) + .body("jobDefinitions.jobDefinitionArn", not(hasItem(definitionArn))); + givenJson(EU_AUTH, "{\"jobDefinitions\":[\"%s\"]}".formatted(definitionArn)) + .when() + .post("/v1/describejobdefinitions") + .then() + .statusCode(200) + .body("jobDefinitions", hasSize(0)); + givenJson(EU_AUTH, "{\"jobs\":[\"%s\"]}".formatted(jobId)) + .when() + .post("/v1/describejobs") + .then() + .statusCode(200) + .body("jobs", hasSize(0)); + givenJson(EU_AUTH, "{\"jobId\":\"%s\",\"reason\":\"other region\"}".formatted(jobId)) + .when() + .post("/v1/terminatejob") + .then() + .statusCode(400) + .header("X-Amzn-Errortype", "ClientException"); + givenJson(EU_AUTH, "{\"jobQueue\":\"%s\"}".formatted(queueName)) + .when() + .post("/v1/listjobs") + .then() + .statusCode(400) + .header("X-Amzn-Errortype", "ClientException"); + givenJson(EU_AUTH, """ + {"jobName":"batch-region-eu-%s","jobQueue":"%s","jobDefinition":"%s"} + """.formatted(suffix, queueArn, definitionArn)) + .when() + .post("/v1/submitjob") + .then() + .statusCode(400) + .header("X-Amzn-Errortype", "ClientException"); + given() + .header("Authorization", EU_AUTH) + .when() + .get("/v1/tags/" + ceArn) + .then() + .statusCode(400) + .header("X-Amzn-Errortype", "ClientException"); + + String euCeArn = givenJson(EU_AUTH, """ + {"computeEnvironmentName":"%s","type":"MANAGED", + "computeResources":{"type":"FARGATE","maxvCpus":4}} + """.formatted(ceName)) + .when() + .post("/v1/createcomputeenvironment") + .then() + .statusCode(200) + .body("computeEnvironmentArn", containsString(":batch:eu-west-1:")) + .extract().path("computeEnvironmentArn"); + givenJson(EU_AUTH, """ + {"jobDefinitionName":"%s","type":"container","platformCapabilities":["FARGATE"], + "containerProperties":{"image":"public.ecr.aws/example/job:latest","command":[], + "resourceRequirements":[{"type":"VCPU","value":"1"},{"type":"MEMORY","value":"512"}]}} + """.formatted(definitionName)) + .when() + .post("/v1/registerjobdefinition") + .then() + .statusCode(200) + .body("revision", equalTo(1)); + String secondRevisionArn = registerJobDefinition(definitionName, "[]", "[]"); + givenJson("{\"jobDefinitions\":[\"%s\"]}".formatted(secondRevisionArn)) + .when() + .post("/v1/describejobdefinitions") + .then() + .statusCode(200) + .body("jobDefinitions[0].revision", equalTo(2)); + + givenJson("{\"computeEnvironments\":[\"%s\"]}".formatted(ceName)) + .when() + .post("/v1/describecomputeenvironments") + .then() + .statusCode(200) + .body("computeEnvironments", hasSize(1)) + .body("computeEnvironments[0].computeEnvironmentArn", equalTo(ceArn)); + givenJson("{\"jobs\":[\"%s\"]}".formatted(jobId)) + .when() + .post("/v1/describejobs") + .then() + .statusCode(200) + .body("jobs", hasSize(1)); + + deregister(AUTH, definitionName + ":1"); + deregister(AUTH, definitionName + ":2"); + deregister(EU_AUTH, definitionName + ":1"); + deleteQueue(AUTH, queueArn); + deleteComputeEnvironment(AUTH, ceArn); + deleteComputeEnvironment(EU_AUTH, euCeArn); + } + + @Test + void aJobDefinitionArnOfAnotherRegionNeverReachesTheLocalRevision() { + String definitionName = "batch-region-arn-" + uniqueSuffix(); + String usArn = registerJobDefinition(definitionName, "[]", "[]"); + String euArn = givenJson(EU_AUTH, """ + {"jobDefinitionName":"%s","type":"container","platformCapabilities":["FARGATE"], + "containerProperties":{"image":"public.ecr.aws/example/job:latest","command":[], + "resourceRequirements":[{"type":"VCPU","value":"1"},{"type":"MEMORY","value":"512"}]}} + """.formatted(definitionName)) + .when() + .post("/v1/registerjobdefinition") + .then() + .statusCode(200) + .body("revision", equalTo(1)) + .extract().path("jobDefinitionArn"); + + givenJson(EU_AUTH, "{\"jobDefinitions\":[\"%s\"]}".formatted(usArn)) + .when() + .post("/v1/describejobdefinitions") + .then() + .statusCode(200) + .body("jobDefinitions", hasSize(0)); + given() + .header("Authorization", EU_AUTH) + .when() + .get("/v1/tags/" + usArn) + .then() + .statusCode(400) + .header("X-Amzn-Errortype", "ClientException"); + givenJson(EU_AUTH, "{\"jobDefinition\":\"%s\"}".formatted(usArn)) + .when() + .post("/v1/deregisterjobdefinition") + .then() + .statusCode(400) + .header("X-Amzn-Errortype", "ClientException"); + givenJson(EU_AUTH, "{\"jobDefinitions\":[\"%s\"]}".formatted(euArn)) + .when() + .post("/v1/describejobdefinitions") + .then() + .statusCode(200) + .body("jobDefinitions[0].status", equalTo("ACTIVE")); + + deregister(AUTH, definitionName + ":1"); + deregister(EU_AUTH, definitionName + ":1"); + } + + private static void deregister(String auth, String definition) { + givenJson(auth, "{\"jobDefinition\":\"%s\"}".formatted(definition)) + .when() + .post("/v1/deregisterjobdefinition") + .then() + .statusCode(200); + } + + private static void deleteQueue(String auth, String queueArn) { + givenJson(auth, "{\"jobQueue\":\"%s\",\"state\":\"DISABLED\"}".formatted(queueArn)) + .when() + .post("/v1/updatejobqueue") + .then() + .statusCode(200); + givenJson(auth, "{\"jobQueue\":\"%s\"}".formatted(queueArn)) + .when() + .post("/v1/deletejobqueue") + .then() + .statusCode(200); + } + + private static void deleteComputeEnvironment(String auth, String ceArn) { + givenJson(auth, "{\"computeEnvironment\":\"%s\",\"state\":\"DISABLED\"}".formatted(ceArn)) + .when() + .post("/v1/updatecomputeenvironment") + .then() + .statusCode(200); + givenJson(auth, "{\"computeEnvironment\":\"%s\"}".formatted(ceArn)) + .when() + .post("/v1/deletecomputeenvironment") + .then() + .statusCode(200); + } + private static RequestSpecification givenJson(String body) { + return givenJson(AUTH, body); + } + + private static RequestSpecification givenJson(String auth, String body) { return given() - .header("Authorization", AUTH) + .header("Authorization", auth) .contentType("application/json") .body(body); }