Light, fluffy, and always free - The AWS Local Emulator alternative
fix(opensearch): scope domains to the request's region (#6682)
Matheus Oliveira347e8f63a9b1
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OpenSearchRegionScopingTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OpenSearchRegionScopingTest.javanew file mode 100644index 0000000000..63fa2c60c2--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/OpenSearchRegionScopingTest.java@@ -0,0 +1,132 @@+package com.floci.test;++import org.junit.jupiter.api.Assumptions;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;+import software.amazon.awssdk.regions.Region;+import software.amazon.awssdk.regions.RegionMetadata;+import software.amazon.awssdk.services.opensearch.OpenSearchClient;+import software.amazon.awssdk.services.opensearch.model.ClusterConfig;+import software.amazon.awssdk.services.opensearch.model.CreateDomainRequest;+import software.amazon.awssdk.services.opensearch.model.DeleteDomainRequest;+import software.amazon.awssdk.services.opensearch.model.DescribeDomainRequest;+import software.amazon.awssdk.services.opensearch.model.ListDomainNamesRequest;+import software.amazon.awssdk.services.opensearch.model.ResourceAlreadyExistsException;+import software.amazon.awssdk.services.opensearch.model.ResourceNotFoundException;+import software.amazon.awssdk.services.opensearch.model.UpdateDomainConfigRequest;++import java.util.Optional;+import java.util.UUID;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++@DisplayName("OpenSearch domains are regional")+class OpenSearchRegionScopingTest {++ private static final String SHARED_NAME = "os-region-" + UUID.randomUUID().toString().substring(0, 8);+ private static final String HOME_ONLY_NAME = "os-home-" + UUID.randomUUID().toString().substring(0, 8);++ @Test+ @DisplayName("A domain is invisible outside its region and the same name coexists in two regions")+ void domainIsScopedToItsRegion() {+ Optional<Region> second = otherRegionInThePartition();+ Assumptions.assumeTrue(second.isPresent(),+ () -> "no second region in partition " + TestFixtures.partition());+ Region other = second.get();+ try (OpenSearchClient home = TestFixtures.openSearchClient(); OpenSearchClient away = clientFor(other)) {+ try {+ String homeRegion = TestFixtures.region().id();+ String awayRegion = other.id();++ String sharedArn = home.createDomain(CreateDomainRequest.builder()+ .domainName(SHARED_NAME).engineVersion("OpenSearch_2.11").build())+ .domainStatus().arn();+ assertThat(sharedArn).contains(":es:" + homeRegion + ":");++ assertThatThrownBy(() -> away.describeDomain(DescribeDomainRequest.builder()+ .domainName(SHARED_NAME).build()))+ .isInstanceOf(ResourceNotFoundException.class);++ String awayArn = away.createDomain(CreateDomainRequest.builder()+ .domainName(SHARED_NAME).engineVersion("OpenSearch_2.11").build())+ .domainStatus().arn();+ assertThat(awayArn).contains(":es:" + awayRegion + ":");++ home.createDomain(CreateDomainRequest.builder().domainName(HOME_ONLY_NAME).build());++ assertThat(away.listDomainNames(ListDomainNamesRequest.builder().build()).domainNames())+ .extracting(d -> d.domainName())+ .doesNotContain(HOME_ONLY_NAME);+ assertThat(home.listDomainNames(ListDomainNamesRequest.builder().build()).domainNames())+ .extracting(d -> d.domainName())+ .contains(HOME_ONLY_NAME);++ away.updateDomainConfig(UpdateDomainConfigRequest.builder()+ .domainName(SHARED_NAME)+ .clusterConfig(ClusterConfig.builder().instanceCount(3).build())+ .build());+ assertThat(home.describeDomain(DescribeDomainRequest.builder().domainName(SHARED_NAME).build())+ .domainStatus().clusterConfig().instanceCount()).isEqualTo(1);+ assertThat(away.describeDomain(DescribeDomainRequest.builder().domainName(SHARED_NAME).build())+ .domainStatus().clusterConfig().instanceCount()).isEqualTo(3);++ away.deleteDomain(DeleteDomainRequest.builder().domainName(SHARED_NAME).build());+ assertThatThrownBy(() -> away.describeDomain(DescribeDomainRequest.builder()+ .domainName(SHARED_NAME).build()))+ .isInstanceOf(ResourceNotFoundException.class);+ assertThat(home.describeDomain(DescribeDomainRequest.builder().domainName(SHARED_NAME).build())+ .domainStatus().arn()).isEqualTo(sharedArn);+ } finally {+ deleteQuietly(home, SHARED_NAME);+ deleteQuietly(home, HOME_ONLY_NAME);+ deleteQuietly(away, SHARED_NAME);+ }+ }+ }++ @Test+ @DisplayName("The same name in the same region still conflicts")+ void sameNameInTheSameRegionStillConflicts() {+ try (OpenSearchClient home = TestFixtures.openSearchClient()) {+ home.createDomain(CreateDomainRequest.builder().domainName(HOME_ONLY_NAME).build());++ assertThatThrownBy(() -> home.createDomain(CreateDomainRequest.builder()+ .domainName(HOME_ONLY_NAME).build()))+ .isInstanceOf(ResourceAlreadyExistsException.class);+ } finally {+ deleteQuietly(TestFixtures.openSearchClient(), HOME_ONLY_NAME);+ }+ }++ private static void deleteQuietly(OpenSearchClient client, String name) {+ try {+ client.deleteDomain(DeleteDomainRequest.builder().domainName(name).build());+ } catch (Exception ignored) {+ // Cleanup: a never-created domain and an already-deleted one both land here.+ }+ }++ private static Optional<Region> otherRegionInThePartition() {+ Region home = TestFixtures.region();+ String partition = TestFixtures.partition();+ return Region.regions().stream()+ .filter(region -> !region.isGlobalRegion() && !region.equals(home))+ .filter(region -> {+ RegionMetadata metadata = region.metadata();+ return metadata != null && partition.equals(metadata.partition().id());+ })+ .sorted((a, b) -> a.id().compareTo(b.id()))+ .findFirst();+ }++ private static OpenSearchClient clientFor(Region region) {+ return OpenSearchClient.builder()+ .endpointOverride(TestFixtures.endpoint())+ .region(region)+ .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test")))+ .build();+ }+}diff --git a/docs/services/opensearch.md b/docs/services/opensearch.mdindex c136f5e09f..d48aa40f1d 100644--- a/docs/services/opensearch.md+++ b/docs/services/opensearch.md@@ -1,7 +1,7 @@# OpenSearch Service-**Protocol:** REST JSON-**Endpoint:** `http://localhost:4566/2021-01-01/...`+**Protocol:** REST JSON+**Endpoint:** `http://localhost:4566/2021-01-01/...`**Credential scope:** `es`## Implementation Modes@@ -45,7 +45,7 @@ services:| `DescribeDomainConfig` | `GET /2021-01-01/opensearch/domain/{name}/config` | Get domain configuration || `UpdateDomainConfig` | `POST /2021-01-01/opensearch/domain/{name}/config` | Update cluster config, EBS options, engine version, access policies || `DeleteDomain` | `DELETE /2021-01-01/opensearch/domain/{name}` | Delete a domain |-| `ListDomainNames` | `GET /2021-01-01/domain` | List all domains (supports `?engineType=` filter) |+| `ListDomainNames` | `GET /2021-01-01/domain` | List the caller's Region's domains (supports `?engineType=` filter) |### Tags@@ -124,6 +124,7 @@ services:## Emulation Behaviour- **Domain name validation:** 3–28 characters, must start with a lowercase letter, only lowercase letters, digits, and hyphens.+- **Regional scoping:** a domain name is unique within one account and one Region, exactly as AWS scopes it. Describe, update, delete, upgrade and list resolve only in the Region the request is signed for, so the same name can exist in two Regions and one Region's requests never see, change or delete another Region's domain. Domain records persisted before regional scoping are migrated onto their Region on first use, taking it from the domain's ARN, which has always carried it.- **ARN format:** `arn:aws:es:{region}:{accountId}:domain/{domainName}`- **Domain ID format:** `{accountId}/{domainName}`- **`Created` flag:** `true` immediately in mock mode; set to `true` by the readiness poller in real mode once `/_cluster/health` reports `green` or `yellow`.@@ -134,7 +135,7 @@ services:- **Cluster defaults:** `m5.large.search`, 1 instance, EBS enabled with 10 GiB `gp2` volume.- **Instance type families:** `t3.*` / `m5/m6g/m7g.*` / `r5/r6g/r7g.*` / `c5/c6g/c7g.*` are EBS-backed (3584 GiB max). `i3.*` are local-NVMe instance-store. `or1.*` are S3-backed and surface a much larger volume ceiling on `DescribeInstanceTypeLimits` (8–36 TiB depending on size). Floci still boots one Docker container per domain regardless of family — the metadata fidelity matters for SDK clients that introspect, not for runtime data placement.- **Container identity:** containers are named `floci-aws-opensearch-<account-id>-<region>-<domain-name>`, or `floci-aws-<namespace>-opensearch-<account-id>-<region>-<domain-name>` when `FLOCI_DOCKER_RESOURCE_NAMESPACE` is set. Account and Region come from the domain's stored ARN and are also recorded in its container labels. Restarts remove older containers by their persisted container ID and preserve the stored volume name. Legacy names that omit account and Region are never removed solely by name, because another domain may own them.-- **Container storage:** each domain gets a named Docker volume (`floci-aws-opensearch-{volumeId}`) created automatically. In memory mode the volume is removed on domain delete; in persistent modes it is retained unless `FLOCI_STORAGE_PRUNE_VOLUMES_ON_DELETE=true`. Set `FLOCI_SERVICES_OPENSEARCH_DATA_VOLUME` to choose the storage yourself: an absolute path bind-mounts `<path>/<account-id>/<region>/<domain-name>` (a directory on the Docker daemon's host), and any other value is a Docker volume name the domain gets its own `<name>-<account-id>-<region>-<domain-name>` volume of. When `FLOCI_DOCKER_RESOURCE_NAMESPACE` is set, the namespace is inserted into both forms, so two namespaced deployments sharing a Docker daemon never converge on one data directory through the same configured base. Linux daemon paths starting with `/` retain Linux path syntax when Floci runs on Windows; native Windows absolute paths retain their native handling. Before a configured bind directory is mounted, a temporary root container using the selected OpenSearch image copies ownership from the image's data directory and grants the owner write access. Only the directory itself is adjusted; existing files retain their ownership and permissions. Preparation failures abort domain startup. Storage named that way is never removed on domain delete, and a volume created when absent carries no Floci label, so neither a floci-scoped volume prune nor a testcontainers run's labelled-children sweep collects it: the operator named it, so its lifecycle is theirs.+- **Container storage:** each domain gets a named Docker volume (`floci-aws-opensearch-{volumeId}`) created automatically. In memory mode the volume is removed on domain delete; in persistent modes it is retained unless `FLOCI_STORAGE_PRUNE_VOLUMES_ON_DELETE=true`. Set `FLOCI_SERVICES_OPENSEARCH_DATA_VOLUME` to choose the storage yourself: an absolute path bind-mounts `<path>/<account-id>/<region>/<domain-name>` (a directory on the Docker daemon's host), and any other value is a Docker volume name the domain gets its own `<name>-<account-id>-<region>-<domain-name>` volume of. When `FLOCI_DOCKER_RESOURCE_NAMESPACE` is set, the namespace is inserted into both forms, so two namespaced deployments sharing a Docker daemon never converge on one data directory through the same configured base. Linux daemon paths starting with `/` retain Linux path syntax when Floci runs on Windows; native Windows absolute paths retain their native handling. Before a configured bind directory is mounted, a temporary root container using the selected OpenSearch image copies ownership from the image's data directory and grants the owner write access. Only the directory itself is adjusted; existing files retain their ownership and permissions. Preparation failures abort domain startup. Storage named that way is never removed on domain delete, and a volume created when absent carries no Floci label, so neither a floci-scoped volume prune nor a testcontainers run's labelled-children sweep collects it: the operator named it, so its lifecycle is theirs. Legacy host-path mode (`FLOCI_STORAGE_HOST_PERSISTENT_PATH` set to an absolute path) gives each domain its own `<host-path>/[<namespace>/]opensearch/floci-aws[-<namespace>]-opensearch-<account-id>-<region>-<domain-name>` directory, so two domains sharing a name across Regions or accounts never share one data directory; a domain whose record predates regional scoping keeps the bare `<domain-name>` directory while it still exists, since that is where its data lives.## Examplesdiff --git a/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchController.java b/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchController.javaindex 6b73b06c05..2530e705b5 100644--- a/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchController.java+++ b/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchController.java@@ -85,7 +85,7 @@ public class OpenSearchController {@Path("/opensearch/domain/{domainName}")public Response describeDomain(@Context HttpHeaders headers,@PathParam("domainName") String domainName) {- Domain domain = service.describeDomain(domainName);+ Domain domain = service.describeDomain(domainName, regionResolver.resolveRegion(headers));ObjectNode response = objectMapper.createObjectNode();response.set("DomainStatus", toDomainStatusNode(domain));return Response.ok(response).build();@@ -98,7 +98,7 @@ public class OpenSearchController {JsonNode req = objectMapper.readTree(body);List<String> names = new ArrayList<>();req.path("DomainNames").forEach(n -> names.add(n.asText()));- List<Domain> domains = service.describeDomains(names);+ List<Domain> domains = service.describeDomains(names, regionResolver.resolveRegion(headers));ObjectNode response = objectMapper.createObjectNode();ArrayNode list = response.putArray("DomainStatusList");@@ -115,7 +115,7 @@ public class OpenSearchController {@Path("/domain")public Response listDomainNames(@Context HttpHeaders headers,@QueryParam("engineType") String engineType) {- List<Domain> domains = service.listDomainNames(engineType);+ List<Domain> domains = service.listDomainNames(engineType, regionResolver.resolveRegion(headers));ObjectNode response = objectMapper.createObjectNode();ArrayNode list = response.putArray("DomainNames");for (Domain d : domains) {@@ -132,7 +132,7 @@ public class OpenSearchController {@Path("/opensearch/domain/{domainName}/config")public Response describeDomainConfig(@Context HttpHeaders headers,@PathParam("domainName") String domainName) {- Domain domain = service.describeDomain(domainName);+ Domain domain = service.describeDomain(domainName, regionResolver.resolveRegion(headers));long epochSeconds = domain.getCreatedAt() != null ? domain.getCreatedAt().getEpochSecond() : 0;ObjectNode response = objectMapper.createObjectNode();@@ -175,7 +175,7 @@ public class OpenSearchController {parseDomainEndpointOptions(req.path("DomainEndpointOptions")));Domain domain = service.updateDomainConfig(domainName, engineVersion, clusterConfig,- ebsOptions, accessPolicies, options);+ ebsOptions, accessPolicies, options, regionResolver.resolveRegion(headers));long epochSeconds = domain.getCreatedAt() != null ? domain.getCreatedAt().getEpochSecond() : 0;ObjectNode response = objectMapper.createObjectNode();@@ -207,7 +207,7 @@ public class OpenSearchController {@Path("/opensearch/domain/{domainName}")public Response deleteDomain(@Context HttpHeaders headers,@PathParam("domainName") String domainName) {- Domain domain = service.deleteDomain(domainName);+ Domain domain = service.deleteDomain(domainName, regionResolver.resolveRegion(headers));ObjectNode response = objectMapper.createObjectNode();response.set("DomainStatus", toDomainStatusNode(domain));return Response.ok(response).build();@@ -292,7 +292,9 @@ public class OpenSearchController {// version — matches AWS's GetCompatibleVersions behavior. Otherwise// return the full matrix so SDK clients can render upgrade pickers.if (domainName != null && !domainName.isBlank()) {- String sourceVersion = service.describeDomain(domainName).getEngineVersion();+ String sourceVersion = service+ .describeDomain(domainName, regionResolver.resolveRegion(headers))+ .getEngineVersion();ObjectNode entry = objectMapper.createObjectNode();entry.put("SourceVersion", sourceVersion);ArrayNode targets = entry.putArray("TargetVersions");@@ -424,12 +426,13 @@ public class OpenSearchController {@POST@Path("/opensearch/upgradeDomain")- public Response upgradeDomain(String body) {+ public Response upgradeDomain(@Context HttpHeaders headers, String body) {try {JsonNode req = objectMapper.readTree(body);String domainName = req.path("DomainName").asText(null);String targetVersion = req.path("TargetVersion").asText(null);- Domain domain = service.upgradeDomain(domainName, targetVersion);+ Domain domain = service.upgradeDomain(domainName, targetVersion,+ regionResolver.resolveRegion(headers));ObjectNode response = objectMapper.createObjectNode();response.put("UpgradeId", UUID.randomUUID().toString());diff --git a/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManager.java b/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManager.javaindex 3ab25b053e..07c59cc102 100644--- a/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManager.java+++ b/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManager.java@@ -19,6 +19,7 @@ import org.jboss.logging.Logger;import java.io.File;import java.net.HttpURLConnection;import java.net.URI;+import java.nio.file.Files;import java.nio.file.Path;import java.util.Optional;@@ -164,7 +165,7 @@ public class OpenSearchDomainManager {resolveVolumeName(domain), CONTAINER_DATA_PATH);} else {// Legacy host-path mode: host-persistent-path is an absolute path- Path dataPath = ContainerStorageHelper.hostResourcePath(config, "opensearch", domain.getDomainName());+ Path dataPath = legacyCompatibleHostDataPath(domain);if (!containerDetector.isRunningInContainer()) {ContainerStorageHelper.ensureHostDir(dataPath.toString());}@@ -231,6 +232,24 @@ public class OpenSearchDomainManager {LOG.infov("Stopped OpenSearch container for domain {0}", domain.getDomainName());}+ /**+ * The domain's host data directory, scoped by the account and region its ARN carries, so two+ * domains sharing one name across regions or accounts never share a data directory: two+ * OpenSearch nodes on one directory corrupt each other's cluster state. A record persisted+ * before the region marker existed keeps the bare-name directory while that directory still+ * exists, since that is where its data lives; a record carrying the marker never falls back.+ */+ private Path legacyCompatibleHostDataPath(Domain domain) {+ Path legacyPath = ContainerStorageHelper.hostResourcePath(config, "opensearch", domain.getDomainName());+ if (domain.getRegion() == null && Files.exists(legacyPath)) {+ return legacyPath;+ }+ AwsArnUtils.Arn arn = AwsArnUtils.parse(domain.getArn());+ return ContainerStorageHelper.hostResourcePath(config, "opensearch",+ ContainerStorageHelper.dockerName(config,+ "opensearch-" + arn.accountId() + "-" + arn.region() + "-" + domain.getDomainName()));+ }+/*** Removes the domain's Docker volume on delete, honouring the configured prune policy.* The decision rides on the {@link VolumeOwnership} marker persisted when the storagediff --git a/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.java b/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.javaindex d9b8599368..e7cdacf75b 100644--- a/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.java+++ b/src/main/java/io/github/hectorvent/floci/services/opensearch/OpenSearchService.java@@ -11,7 +11,6 @@ import io.github.hectorvent.floci.core.resource.ExplorerResource;import io.github.hectorvent.floci.core.resource.ResourceProvider;import io.github.hectorvent.floci.core.resource.SupportedResourceType;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;-import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;import io.github.hectorvent.floci.services.opensearch.model.AdvancedSecurityOptions;import io.github.hectorvent.floci.services.opensearch.model.ClusterConfig;@@ -31,13 +30,22 @@ import org.jboss.logging.Logger;import java.security.SecureRandom;import java.time.Instant;import java.util.ArrayList;+import java.util.LinkedHashSet;import java.util.List;import java.util.Map;+import java.util.Optional;import java.util.Set;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;+/**+ * Domain metadata, scoped to an account and a region the way AWS scopes it: a domain name is+ * unique within one account and region, and every lookup (describe, update, delete, list)+ * resolves inside the caller's region only. The storage key carries the region next to the+ * name; records persisted before the region joined the key are migrated onto it, taking the+ * region from the domain's ARN, which has always carried it.+ */@ApplicationScopedpublic class OpenSearchService implements ResourceProvider {@@ -45,7 +53,7 @@ public class OpenSearchService implements ResourceProvider {private static final String DEFAULT_ENGINE_VERSION = OpenSearchVersions.DEFAULT_VERSION;- private final StorageBackend<String, Domain> domainStore;+ private final AccountAwareStorageBackend<Domain> domainStore;private final EmulatorConfig config;private final RegionResolver regionResolver;private final OpenSearchDomainManager domainManager;@@ -61,7 +69,7 @@ public class OpenSearchService implements ResourceProvider {this.domainManager = domainManager;}- OpenSearchService(StorageBackend<String, Domain> domainStore, EmulatorConfig config,+ OpenSearchService(AccountAwareStorageBackend<Domain> domainStore, EmulatorConfig config,RegionResolver regionResolver, OpenSearchDomainManager domainManager) {this.domainStore = domainStore;this.config = config;@@ -71,6 +79,7 @@ public class OpenSearchService implements ResourceProvider {@PostConstructpublic void init() {+ migrateLegacyDomainKeys();if (!config.services().opensearch().mock()) {startReadinessPoller();}@@ -115,16 +124,17 @@ public class OpenSearchService implements ResourceProvider {OpenSearchVersions.validate(engineVersion);validateOptions(options);- if (domainStore.get(domainName).isPresent()) {+ String accountId = regionResolver.getAccountId();+ if (findDomain(accountId, region, domainName).isPresent()) {throw new AwsException("ResourceAlreadyExistsException","Domain with name " + domainName + " already exists.", 409);}- String accountId = regionResolver.getAccountId();Domain domain = new Domain();domain.setDomainName(domainName);domain.setDomainId(accountId + "/" + domainName);domain.setAccountId(accountId);+ domain.setRegion(region);domain.setArn(AwsArnUtils.Arn.of("es", region, accountId, "domain/" + domainName).toString());domain.setEngineVersion(engineVersion != null ? engineVersion : DEFAULT_ENGINE_VERSION);domain.setAccessPolicies(accessPolicies);@@ -160,7 +170,7 @@ public class OpenSearchService implements ResourceProvider {}}- domainStore.put(domainName, domain);+ domainStore.putForAccount(accountId, storageKey(region, domainName), domain);LOG.infov("Created OpenSearch domain: {0}", domainName);return domain;}@@ -183,22 +193,22 @@ public class OpenSearchService implements ResourceProvider {+ AwsRegions.dnsSuffixFor(region);}- public Domain describeDomain(String domainName) {- return domainStore.get(domainName)+ public Domain describeDomain(String domainName, String region) {+ return findDomain(regionResolver.getAccountId(), region, domainName).orElseThrow(() -> new AwsException("ResourceNotFoundException","Domain not found: " + domainName, 409));}- public List<Domain> describeDomains(List<String> domainNames) {+ public List<Domain> describeDomains(List<String> domainNames, String region) {return domainNames.stream()- .map(name -> domainStore.get(name)- .orElseThrow(() -> new AwsException("ResourceNotFoundException",- "Domain not found: " + name, 409)))+ .map(name -> describeDomain(name, region)).toList();}- public List<Domain> listDomainNames(String engineType) {- return domainStore.scan(k -> true).stream()+ public List<Domain> listDomainNames(String engineType, String region) {+ String accountId = regionResolver.getAccountId();+ migrateLegacyDomainKeys(accountId);+ return domainStore.scanForAccount(accountId, key -> key.startsWith(region + "::")).stream().filter(d -> !d.isDeleted()).filter(d -> engineType == null || engineType.isBlank()|| matchesEngineType(d.getEngineVersion(), engineType))@@ -206,15 +216,15 @@ public class OpenSearchService implements ResourceProvider {}public Domain updateDomainConfig(String domainName, String engineVersion,- ClusterConfig clusterConfig, EbsOptions ebsOptions) {+ ClusterConfig clusterConfig, EbsOptions ebsOptions, String region) {return updateDomainConfig(domainName, engineVersion, clusterConfig, ebsOptions, null,- DomainOptions.EMPTY);+ DomainOptions.EMPTY, region);}public Domain updateDomainConfig(String domainName, String engineVersion,ClusterConfig clusterConfig, EbsOptions ebsOptions,- String accessPolicies, DomainOptions options) {- Domain domain = describeDomain(domainName);+ String accessPolicies, DomainOptions options, String region) {+ Domain domain = describeDomain(domainName, region);OpenSearchVersions.validate(engineVersion);validateOptions(options);@@ -228,7 +238,7 @@ public class OpenSearchService implements ResourceProvider {applyEbsOptions(domain.getEbsOptions(), ebsOptions);applyDomainOptions(domain, options);- domainStore.put(domainName, domain);+ putDomain(domain);return domain;}@@ -267,14 +277,14 @@ public class OpenSearchService implements ResourceProvider {}}- public Domain deleteDomain(String domainName) {- Domain domain = describeDomain(domainName);+ public Domain deleteDomain(String domainName, String region) {+ Domain domain = describeDomain(domainName, region);domain.setDeleted(true);if (!config.services().opensearch().mock()) {domainManager.stopDomain(domain);domainManager.removeDomainStorage(domain);}- domainStore.delete(domainName);+ domainStore.deleteForAccount(regionResolver.getAccountId(), storageKey(region, domainName));LOG.infov("Deleted OpenSearch domain: {0}", domainName);return domain;}@@ -282,7 +292,7 @@ public class OpenSearchService implements ResourceProvider {public void addTags(String arn, Map<String, String> tags) {Domain domain = findByArn(arn);domain.getTags().putAll(tags);- domainStore.put(domain.getDomainName(), domain);+ putDomain(domain);}public Map<String, String> listTags(String arn) {@@ -292,27 +302,91 @@ public class OpenSearchService implements ResourceProvider {public void removeTags(String arn, List<String> tagKeys) {Domain domain = findByArn(arn);tagKeys.forEach(domain.getTags()::remove);- domainStore.put(domain.getDomainName(), domain);+ putDomain(domain);}- public Domain upgradeDomain(String domainName, String targetVersion) {- Domain domain = describeDomain(domainName);+ public Domain upgradeDomain(String domainName, String targetVersion, String region) {+ Domain domain = describeDomain(domainName, region);if (targetVersion == null || targetVersion.isBlank()) {throw new AwsException("ValidationException","TargetVersion is required for UpgradeDomain.", 400);}OpenSearchVersions.validateUpgrade(domain.getEngineVersion(), targetVersion);domain.setEngineVersion(targetVersion);- domainStore.put(domainName, domain);+ putDomain(domain);return domain;}+ /**+ * Resolves a domain inside one account and region, migrating a pre-region-scoping record+ * stored under the bare name onto the region-scoped key when the domain's own ARN proves+ * it belongs to this account and region.+ */+ private Optional<Domain> findDomain(String accountId, String region, String domainName) {+ return domainStore.getForAccountMigratingLegacyKeys(accountId, storageKey(region, domainName),+ List.of(domainName), domain -> ownsDomain(domain, accountId, region));+ }++ /**+ * Resolves the domain an ARN names, the way the tag operations address domains. The ARN+ * carries the account, region and name, so it names exactly one key; a stored record+ * matches only when its own ARN is the one asked for.+ */private Domain findByArn(String arn) {- return domainStore.scan(k -> true).stream()- .filter(d -> arn.equals(d.getArn()))- .findFirst()- .orElseThrow(() -> new AwsException("ResourceNotFoundException",- "Domain not found for ARN: " + arn, 409));+ AwsArnUtils.Arn parsed;+ try {+ parsed = AwsArnUtils.parse(arn);+ } catch (IllegalArgumentException e) {+ throw domainNotFoundForArn(arn);+ }+ if (!"es".equals(parsed.service()) || !parsed.resource().startsWith("domain/")) {+ throw domainNotFoundForArn(arn);+ }+ if (AwsArnUtils.isForeignAccount(parsed, regionResolver.getAccountId())) {+ throw domainNotFoundForArn(arn);+ }+ String domainName = parsed.resource().substring("domain/".length());+ return domainStore.getForAccountMigratingLegacyKeys(+ parsed.accountId(), storageKey(parsed.region(), domainName),+ List.of(domainName), domain -> arn.equals(domain.getArn()))+ .orElseThrow(() -> domainNotFoundForArn(arn));+ }++ private static AwsException domainNotFoundForArn(String arn) {+ return new AwsException("ResourceNotFoundException",+ "Domain not found for ARN: " + arn, 409);+ }++ /**+ * Whether a stored record is the domain the account and region name: its ARN must be an+ * OpenSearch ARN carrying exactly that account and region.+ */+ private static boolean ownsDomain(Domain domain, String accountId, String region) {+ try {+ AwsArnUtils.Arn arn = AwsArnUtils.parse(domain.getArn());+ return "es".equals(arn.service()) && accountId.equals(arn.accountId())+ && region.equals(arn.region());+ } catch (IllegalArgumentException e) {+ return false;+ }+ }++ /**+ * Whether a stored record's ARN is an OpenSearch ARN naming exactly this account. The+ * migration's ownership proof: the destination region comes from the same ARN, so proving+ * the account is enough there.+ */+ private static boolean ownsAccount(Domain domain, String accountId) {+ try {+ AwsArnUtils.Arn arn = AwsArnUtils.parse(domain.getArn());+ return "es".equals(arn.service()) && accountId.equals(arn.accountId());+ } catch (IllegalArgumentException e) {+ return false;+ }+ }++ private static String storageKey(String region, String domainName) {+ return region + "::" + domainName;}private void validateDomainName(String name) {@@ -409,25 +483,65 @@ public class OpenSearchService implements ResourceProvider {}private List<Domain> allDomains() {- if (domainStore instanceof AccountAwareStorageBackend<Domain> aware) {- return aware.scanAllAccounts();- }- return domainStore.scan(k -> true);+ return domainStore.scanAllAccounts();}+ /**+ * Persists a domain under the key its ARN names, so the poller writes a record back to the+ * account and region that own it rather than to whatever account the background thread+ * happens to run under. A record whose ARN cannot be parsed is left un-persisted, with a+ * warning, rather than guessed at.+ */private void putDomain(Domain domain) {- if (domain.getAccountId() != null && domainStore instanceof AccountAwareStorageBackend<Domain> aware) {- aware.putForAccount(domain.getAccountId(), domain.getDomainName(), domain);- } else {- domainStore.put(domain.getDomainName(), domain);+ try {+ AwsArnUtils.Arn arn = AwsArnUtils.parse(domain.getArn());+ domainStore.putForAccount(arn.accountId(), storageKey(arn.region(), domain.getDomainName()), domain);+ } catch (IllegalArgumentException e) {+ LOG.warnv("Not persisting OpenSearch domain {0}: its ARN {1} cannot be parsed",+ domain.getDomainName(), domain.getArn());+ }+ }++ /**+ * Moves records persisted before domains were keyed by region, one account partition at a+ * time, from the bare domain name onto the region-scoped key. The destination region comes+ * from the domain's ARN, which has always carried it, so a pre-scoping domain stays in its+ * own region; a record whose ARN cannot be parsed is left where it is.+ */+ private void migrateLegacyDomainKeys() {+ Set<String> accounts = new LinkedHashSet<>();+ for (String rawKey : domainStore.scanAllAccountsWithRawKeys().keySet()) {+ accounts.add(AccountAwareStorageBackend.hasAccountPrefix(rawKey)+ ? rawKey.substring(0, 12)+ : regionResolver.getDefaultAccountId());+ }+ accounts.forEach(this::migrateLegacyDomainKeys);+ }++ private void migrateLegacyDomainKeys(String accountId) {+ domainStore.migrateLegacyEntries(accountId, key -> !key.contains("::"),+ this::legacyDomainDestinationKey, domain -> ownsAccount(domain, accountId));+ }++ /**+ * The region-scoped key for a legacy record, or null to leave it untouched when its ARN+ * cannot be parsed.+ */+ private String legacyDomainDestinationKey(Domain domain) {+ try {+ return storageKey(AwsArnUtils.parse(domain.getArn()).region(), domain.getDomainName());+ } catch (IllegalArgumentException e) {+ LOG.warnv("Leaving OpenSearch domain {0} under its pre-region-scoping key: "+ + "its ARN {1} cannot be parsed", domain.getDomainName(), domain.getArn());+ return null;}}@Overridepublic List<ExplorerResource> getResources() {List<ExplorerResource> resources = new ArrayList<>();- for (Domain domain : listDomainNames(null)) {- if (domain.getArn() == null) {+ for (Domain domain : domainStore.scan(key -> true)) {+ if (domain.isDeleted() || domain.getArn() == null) {continue;}AwsArnUtils.Arn parsed = AwsArnUtils.parse(domain.getArn());diff --git a/src/main/java/io/github/hectorvent/floci/services/opensearch/model/Domain.java b/src/main/java/io/github/hectorvent/floci/services/opensearch/model/Domain.javaindex f4fbde745b..302cc9faa2 100644--- a/src/main/java/io/github/hectorvent/floci/services/opensearch/model/Domain.java+++ b/src/main/java/io/github/hectorvent/floci/services/opensearch/model/Domain.java@@ -23,6 +23,14 @@ public class Domain {@JsonProperty("ARN")private String arn;+ /**+ * The AWS region the domain was created in. Null on records persisted before domains were+ * keyed by region, whose region comes from their ARN; also the marker that tells the+ * container manager those records predate region-scoped data directories.+ */+ @JsonProperty("Region")+ private String region;+@JsonProperty("EngineVersion")private String engineVersion;@@ -119,6 +127,14 @@ public class Domain {this.arn = arn;}+ public String getRegion() {+ return region;+ }++ public void setRegion(String region) {+ this.region = region;+ }+public String getEngineVersion() {return engineVersion;}diff --git a/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManagerTest.java b/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManagerTest.javaindex 8043fb268e..99c8e3aaa8 100644--- a/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManagerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchDomainManagerTest.java@@ -21,6 +21,7 @@ import org.mockito.InOrder;import org.mockito.MockMakers;import org.mockito.MockedStatic;+import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;@@ -578,6 +579,70 @@ class OpenSearchDomainManagerTest {assertNull(domain.getHostPort());}+ /**+ * Legacy host-path mode binds one directory per account and region, so two domains sharing+ * a name across regions (or accounts) never share one data directory, which would corrupt+ * both clusters.+ */+ @ParameterizedTest+ @ValueSource(strings = {"", "team-a"})+ void hostPathStorageSeparatesAccountsAndRegions(String namespace, @TempDir Path hostRoot) {+ when(storage.hostPersistentPath()).thenReturn(hostRoot.toString());+ when(docker.resourceNamespace()).thenReturn(Optional.of(namespace));+ List<Domain> domains = List.of(domain("000000000000", "us-east-1"),+ domain("111111111111", "us-east-1"), domain("000000000000", "eu-west-1"));+ for (Domain domain : domains) {+ domain.setRegion(AwsArnUtils.parse(domain.getArn()).region());+ }++ for (Domain domain : domains) {+ manager.startDomain(domain);+ }++ String prefix = namespace.isEmpty() ? "floci-aws-opensearch-" : "floci-aws-team-a-opensearch-";+ Path serviceRoot = namespace.isEmpty()+ ? hostRoot.resolve("opensearch")+ : hostRoot.resolve("team-a").resolve("opensearch");+ List<String> expectedBinds = List.of(+ serviceRoot.resolve(prefix + "000000000000-us-east-1-my-domain"),+ serviceRoot.resolve(prefix + "111111111111-us-east-1-my-domain"),+ serviceRoot.resolve(prefix + "000000000000-eu-west-1-my-domain"))+ .stream().map(path -> path.toAbsolutePath().normalize().toString()).toList();+ ArgumentCaptor<String> binds = ArgumentCaptor.forClass(String.class);+ verify(builder, times(3)).withBind(binds.capture(), anyString());+ assertEquals(expectedBinds, binds.getAllValues());+ }++ /**+ * A record persisted before the region marker keeps the bare-name directory while that+ * directory still exists, since that is where its data lives.+ */+ @Test+ void hostPathKeepsTheBareDirectoryForARecordPredatingTheRegionMarker(+ @TempDir Path hostRoot) throws IOException {+ when(storage.hostPersistentPath()).thenReturn(hostRoot.toString());+ Path legacyDir = hostRoot.resolve("opensearch").resolve("my-domain");+ Files.createDirectories(legacyDir);+ Domain domain = domain("000000000000", "us-east-1");++ manager.startDomain(domain);++ verify(builder).withBind(legacyDir.toAbsolutePath().normalize().toString(), "/usr/share/opensearch/data");+ }++ /** With no bare-name directory on disk, even a marker-less record starts on the scoped one. */+ @Test+ void hostPathUsesTheScopedDirectoryWhenNoBareDirectoryExists(@TempDir Path hostRoot) {+ when(storage.hostPersistentPath()).thenReturn(hostRoot.toString());+ Domain domain = domain("000000000000", "us-east-1");++ manager.startDomain(domain);++ verify(builder).withBind(hostRoot.resolve("opensearch")+ .resolve("floci-aws-opensearch-000000000000-us-east-1-my-domain")+ .toAbsolutePath().normalize().toString(), "/usr/share/opensearch/data");+ }+private Domain domain(String accountId, String region) {Domain domain = new Domain();domain.setDomainName("my-domain");diff --git a/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchRegionScopingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchRegionScopingIntegrationTest.javanew file mode 100644index 0000000000..f977218ddc--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchRegionScopingIntegrationTest.java@@ -0,0 +1,316 @@+package io.github.hectorvent.floci.services.opensearch;++import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.AfterEach;+import org.junit.jupiter.api.Test;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.equalTo;+import static org.hamcrest.Matchers.hasItem;+import static org.hamcrest.Matchers.not;++/**+ * OpenSearch domains are regional: a name is unique inside one account and region, and+ * describe, update, delete and list resolve only in the region the request is signed for.+ */+@QuarkusTest+class OpenSearchRegionScopingIntegrationTest {++ private static final String AUTH_HEADER =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/es/aws4_request";+ private static final String OTHER_REGION_AUTH_HEADER =+ "AWS4-HMAC-SHA256 Credential=AKID/20260101/eu-west-1/es/aws4_request";+ private static final String SHARED_NAME = "shared-regional";+ private static final String EAST_ONLY_NAME = "east-regional";+ private static final String WEST_ONLY_NAME = "west-regional";++ @AfterEach+ void cleanup() {+ for (String name : new String[]{SHARED_NAME, EAST_ONLY_NAME, WEST_ONLY_NAME}) {+ given().header("Authorization", AUTH_HEADER)+ .when().delete("/2021-01-01/opensearch/domain/" + name);+ given().header("Authorization", OTHER_REGION_AUTH_HEADER)+ .when().delete("/2021-01-01/opensearch/domain/" + name);+ }+ }++ @Test+ void theSameNameCoexistsInTwoRegionsAndEachArnCarriesItsRegion() {+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"DomainName\":\"" + SHARED_NAME + "\",\"EngineVersion\":\"OpenSearch_2.11\"}")+ .when()+ .post("/2021-01-01/opensearch/domain")+ .then()+ .statusCode(200)+ .body("DomainStatus.ARN", equalTo("arn:aws:es:us-east-1:000000000000:domain/" + SHARED_NAME));++ given()+ .contentType("application/json")+ .header("Authorization", OTHER_REGION_AUTH_HEADER)+ .body("{\"DomainName\":\"" + SHARED_NAME + "\",\"EngineVersion\":\"OpenSearch_2.11\"}")+ .when()+ .post("/2021-01-01/opensearch/domain")+ .then()+ .statusCode(200)+ .body("DomainStatus.ARN", equalTo("arn:aws:es:eu-west-1:000000000000:domain/" + SHARED_NAME));+ }++ @Test+ void createConflictsOnlyWithinTheSameRegion() {+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"DomainName\":\"" + SHARED_NAME + "\"}")+ .when()+ .post("/2021-01-01/opensearch/domain")+ .then()+ .statusCode(200);++ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"DomainName\":\"" + SHARED_NAME + "\"}")+ .when()+ .post("/2021-01-01/opensearch/domain")+ .then()+ .statusCode(409);++ given()+ .contentType("application/json")+ .header("Authorization", OTHER_REGION_AUTH_HEADER)+ .body("{\"DomainName\":\"" + SHARED_NAME + "\"}")+ .when()+ .post("/2021-01-01/opensearch/domain")+ .then()+ .statusCode(200);+ }++ @Test+ void describeAndDescribeConfigSeeOnlyTheRequestRegionsDomains() {+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"DomainName\":\"" + EAST_ONLY_NAME + "\"}")+ .when()+ .post("/2021-01-01/opensearch/domain")+ .then()+ .statusCode(200);++ given()+ .header("Authorization", OTHER_REGION_AUTH_HEADER)+ .when()+ .get("/2021-01-01/opensearch/domain/" + EAST_ONLY_NAME)+ .then()+ .statusCode(409);++ given()+ .header("Authorization", OTHER_REGION_AUTH_HEADER)+ .when()+ .get("/2021-01-01/opensearch/domain/" + EAST_ONLY_NAME + "/config")+ .then()+ .statusCode(409);+ }++ @Test+ void listDomainNamesListsOnlyTheRequestRegionsDomains() {+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"DomainName\":\"" + EAST_ONLY_NAME + "\"}")+ .when()+ .post("/2021-01-01/opensearch/domain")+ .then()+ .statusCode(200);+ given()+ .contentType("application/json")+ .header("Authorization", OTHER_REGION_AUTH_HEADER)+ .body("{\"DomainName\":\"" + WEST_ONLY_NAME + "\"}")+ .when()+ .post("/2021-01-01/opensearch/domain")+ .then()+ .statusCode(200);++ given()+ .header("Authorization", AUTH_HEADER)+ .when()+ .get("/2021-01-01/domain")+ .then()+ .statusCode(200)+ .body("DomainNames.DomainName", hasItem(EAST_ONLY_NAME))+ .body("DomainNames.DomainName", not(hasItem(WEST_ONLY_NAME)));++ given()+ .header("Authorization", OTHER_REGION_AUTH_HEADER)+ .when()+ .get("/2021-01-01/domain")+ .then()+ .statusCode(200)+ .body("DomainNames.DomainName", hasItem(WEST_ONLY_NAME))+ .body("DomainNames.DomainName", not(hasItem(EAST_ONLY_NAME)));+ }++ @Test+ void updateInOneRegionLeavesTheOtherRegionUntouched() {+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"DomainName\":\"" + SHARED_NAME + "\"}")+ .when()+ .post("/2021-01-01/opensearch/domain")+ .then()+ .statusCode(200);+ given()+ .contentType("application/json")+ .header("Authorization", OTHER_REGION_AUTH_HEADER)+ .body("{\"DomainName\":\"" + SHARED_NAME + "\"}")+ .when()+ .post("/2021-01-01/opensearch/domain")+ .then()+ .statusCode(200);++ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"ClusterConfig\":{\"InstanceCount\":5}}")+ .when()+ .post("/2021-01-01/opensearch/domain/" + SHARED_NAME + "/config")+ .then()+ .statusCode(200)+ .body("DomainConfig.ClusterConfig.Options.InstanceCount", equalTo(5));++ given()+ .header("Authorization", AUTH_HEADER)+ .when()+ .get("/2021-01-01/opensearch/domain/" + SHARED_NAME)+ .then()+ .statusCode(200)+ .body("DomainStatus.ClusterConfig.InstanceCount", equalTo(5));++ given()+ .header("Authorization", OTHER_REGION_AUTH_HEADER)+ .when()+ .get("/2021-01-01/opensearch/domain/" + SHARED_NAME)+ .then()+ .statusCode(200)+ .body("DomainStatus.ClusterConfig.InstanceCount", equalTo(1));+ }++ @Test+ void deleteInOneRegionLeavesTheOtherRegionIntact() {+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"DomainName\":\"" + SHARED_NAME + "\"}")+ .when()+ .post("/2021-01-01/opensearch/domain")+ .then()+ .statusCode(200);+ given()+ .contentType("application/json")+ .header("Authorization", OTHER_REGION_AUTH_HEADER)+ .body("{\"DomainName\":\"" + SHARED_NAME + "\"}")+ .when()+ .post("/2021-01-01/opensearch/domain")+ .then()+ .statusCode(200);++ given()+ .header("Authorization", AUTH_HEADER)+ .when()+ .delete("/2021-01-01/opensearch/domain/" + SHARED_NAME)+ .then()+ .statusCode(200)+ .body("DomainStatus.Deleted", equalTo(true));++ given()+ .header("Authorization", AUTH_HEADER)+ .when()+ .get("/2021-01-01/opensearch/domain/" + SHARED_NAME)+ .then()+ .statusCode(409);++ given()+ .header("Authorization", OTHER_REGION_AUTH_HEADER)+ .when()+ .get("/2021-01-01/opensearch/domain/" + SHARED_NAME)+ .then()+ .statusCode(200)+ .body("DomainStatus.ARN", equalTo("arn:aws:es:eu-west-1:000000000000:domain/" + SHARED_NAME));+ }++ @Test+ void upgradeDomainResolvesOnlyInTheRequestRegion() {+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"DomainName\":\"" + SHARED_NAME + "\",\"EngineVersion\":\"OpenSearch_2.11\"}")+ .when()+ .post("/2021-01-01/opensearch/domain")+ .then()+ .statusCode(200);++ given()+ .contentType("application/json")+ .header("Authorization", OTHER_REGION_AUTH_HEADER)+ .body("{\"DomainName\":\"" + SHARED_NAME + "\",\"TargetVersion\":\"OpenSearch_2.13\"}")+ .when()+ .post("/2021-01-01/opensearch/upgradeDomain")+ .then()+ .statusCode(409);+ }++ @Test+ void tagOperationsRejectAForeignAccountArnAsNotFound() {+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"DomainName\":\"" + EAST_ONLY_NAME + "\",\"EngineVersion\":\"OpenSearch_2.11\"}")+ .when()+ .post("/2021-01-01/opensearch/domain")+ .then()+ .statusCode(200);++ String foreignArn = "arn:aws:es:us-east-1:387263792837:domain/" + EAST_ONLY_NAME;++ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"ARN\":\"" + foreignArn + "\",\"TagList\":[{\"Key\":\"env\",\"Value\":\"test\"}]}")+ .when()+ .post("/2021-01-01/tags")+ .then()+ .statusCode(409)+ .body("__type", equalTo("ResourceNotFoundException"));++ given()+ .header("Authorization", AUTH_HEADER)+ .queryParam("arn", foreignArn)+ .when()+ .get("/2021-01-01/tags/")+ .then()+ .statusCode(409)+ .body("__type", equalTo("ResourceNotFoundException"));++ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"ARN\":\"" + foreignArn + "\",\"TagKeys\":[\"env\"]}")+ .when()+ .post("/2021-01-01/tags-removal")+ .then()+ .statusCode(409)+ .body("__type", equalTo("ResourceNotFoundException"));++ String localArn = "arn:aws:es:us-east-1:000000000000:domain/" + EAST_ONLY_NAME;+ given()+ .contentType("application/json")+ .header("Authorization", AUTH_HEADER)+ .body("{\"ARN\":\"" + localArn + "\",\"TagList\":[{\"Key\":\"env\",\"Value\":\"test\"}]}")+ .when()+ .post("/2021-01-01/tags")+ .then()+ .statusCode(200);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchServiceTest.javaindex f4d40c0f98..b15c6bcb00 100644--- a/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/opensearch/OpenSearchServiceTest.java@@ -1,16 +1,22 @@package io.github.hectorvent.floci.services.opensearch;import io.github.hectorvent.floci.config.EmulatorConfig;+import io.github.hectorvent.floci.core.common.AwsArnUtils;+import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.core.common.RegionResolver;import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;+import io.github.hectorvent.floci.services.opensearch.model.ClusterConfig;import io.github.hectorvent.floci.services.opensearch.model.Domain;import io.github.hectorvent.floci.services.opensearch.model.VolumeOwnership;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.mockito.Mockito;+import java.util.List;+import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.Mockito.atLeast;@@ -21,10 +27,18 @@ import static org.mockito.Mockito.when;/*** A domain stays {@code Processing=true} until the readiness poller flips it. Mock mode and a* Floci with no reachable Docker daemon report {@code Processing=false} from the first read.+ *+ * <p>Domains are scoped to an account and a region: the same name can exist in two regions,+ * and describe, update, delete and list only ever see the caller's region.*/class OpenSearchServiceTest {+ private static final String ACCOUNT = "000000000000";+ private static final String US_EAST_1 = "us-east-1";+ private static final String EU_WEST_1 = "eu-west-1";+private OpenSearchService service;+ private AccountAwareStorageBackend<Domain> domainStore;private OpenSearchDomainManager domainManager;private EmulatorConfig.OpenSearchServiceConfig osConfig;@@ -38,9 +52,9 @@ class OpenSearchServiceTest {when(servicesConfig.opensearch()).thenReturn(osConfig);when(osConfig.mock()).thenReturn(false);- RegionResolver regionResolver = new RegionResolver("us-east-1", "000000000000");- service = new OpenSearchService(AccountAwareStorageBackend.inMemory("000000000000"),- config, regionResolver, domainManager);+ RegionResolver regionResolver = new RegionResolver(US_EAST_1, ACCOUNT);+ domainStore = AccountAwareStorageBackend.inMemory(ACCOUNT);+ service = new OpenSearchService(domainStore, config, regionResolver, domainManager);}@Test@@ -48,11 +62,11 @@ class OpenSearchServiceTest {when(domainManager.tryStartDomain(any())).thenReturn(true);Domain domain = service.createDomain("docker-domain", "OpenSearch_2.11",- null, null, null, "us-east-1");+ null, null, null, US_EAST_1);assertTrue(domain.isProcessing(),"the readiness poller flips Processing once the container answers");- assertTrue(service.describeDomain("docker-domain").isProcessing());+ assertTrue(service.describeDomain("docker-domain", US_EAST_1).isProcessing());verify(domainManager).tryStartDomain(any());}@@ -66,7 +80,7 @@ class OpenSearchServiceTest {when(domainManager.tryStartDomain(any())).thenReturn(false);Domain domain = service.createDomain("stamped-domain", "OpenSearch_2.11",- null, null, null, "us-east-1");+ null, null, null, US_EAST_1);assertEquals(VolumeOwnership.FLOCI_MANAGED, domain.getVolumeOwnership());assertTrue(domain.getDockerVolumeName().startsWith("floci-aws-opensearch-"),@@ -81,11 +95,11 @@ class OpenSearchServiceTest {when(domainManager.tryStartDomain(any())).thenReturn(false);Domain domain = service.createDomain("no-docker-domain", "OpenSearch_2.11",- null, null, null, "us-east-1");+ null, null, null, US_EAST_1);assertFalse(domain.isProcessing());- assertEquals("no-docker-domain", service.describeDomain("no-docker-domain").getDomainName());- assertFalse(service.describeDomain("no-docker-domain").isProcessing());+ assertEquals("no-docker-domain", service.describeDomain("no-docker-domain", US_EAST_1).getDomainName());+ assertFalse(service.describeDomain("no-docker-domain", US_EAST_1).isProcessing());}@Test@@ -93,7 +107,7 @@ class OpenSearchServiceTest {when(osConfig.mock()).thenReturn(true);Domain domain = service.createDomain("mock-domain", "OpenSearch_2.11",- null, null, null, "us-east-1");+ null, null, null, US_EAST_1);assertFalse(domain.isProcessing());verify(domainManager, Mockito.never()).tryStartDomain(any());@@ -107,13 +121,13 @@ class OpenSearchServiceTest {.thenReturn(true);service.createDomain("ready-recovery", "OpenSearch_2.11",- null, null, null, "us-east-1");+ null, null, null, US_EAST_1);service.pollReadiness();- assertTrue(service.describeDomain("ready-recovery").isProcessing());+ assertTrue(service.describeDomain("ready-recovery", US_EAST_1).isProcessing());service.pollReadiness();- assertFalse(service.describeDomain("ready-recovery").isProcessing());+ assertFalse(service.describeDomain("ready-recovery", US_EAST_1).isProcessing());verify(domainManager, atLeast(2)).isReady(any());}@@ -121,10 +135,144 @@ class OpenSearchServiceTest {void shutdownLeavesDomainContainersRunningWhenRetentionIsEnabled() {when(domainManager.tryStartDomain(any())).thenReturn(true);when(osConfig.keepRunningOnShutdown()).thenReturn(true);- service.createDomain("kept-domain", "OpenSearch_2.11", null, null, null, "us-east-1");+ service.createDomain("kept-domain", "OpenSearch_2.11", null, null, null, US_EAST_1);service.shutdown();verify(domainManager, Mockito.never()).stopDomain(any());}++ @Test+ void sameNameInTwoRegionsCoexistsAndEachArnCarriesItsRegion() {+ when(domainManager.tryStartDomain(any())).thenReturn(false);++ Domain east = service.createDomain("dual-region", "OpenSearch_2.11", null, null, null, US_EAST_1);+ Domain west = service.createDomain("dual-region", "OpenSearch_2.11", null, null, null, EU_WEST_1);++ assertEquals(AwsArnUtils.Arn.of("es", US_EAST_1, ACCOUNT, "domain/dual-region").toString(),+ east.getArn());+ assertEquals(AwsArnUtils.Arn.of("es", EU_WEST_1, ACCOUNT, "domain/dual-region").toString(),+ west.getArn());+ assertEquals(US_EAST_1, service.describeDomain("dual-region", US_EAST_1).getRegion());+ assertEquals(EU_WEST_1, service.describeDomain("dual-region", EU_WEST_1).getRegion());+ }++ @Test+ void sameNameInTheSameRegionStillConflicts() {+ when(domainManager.tryStartDomain(any())).thenReturn(false);+ service.createDomain("occupied-name", "OpenSearch_2.11", null, null, null, US_EAST_1);++ AwsException duplicate = assertThrows(AwsException.class, () -> service.createDomain(+ "occupied-name", "OpenSearch_2.11", null, null, null, US_EAST_1));++ assertEquals("ResourceAlreadyExistsException", duplicate.getErrorCode());+ }++ @Test+ void describeFromAnotherRegionDoesNotSeeTheDomain() {+ when(domainManager.tryStartDomain(any())).thenReturn(false);+ service.createDomain("east-only", "OpenSearch_2.11", null, null, null, US_EAST_1);++ AwsException absent = assertThrows(AwsException.class,+ () -> service.describeDomain("east-only", EU_WEST_1));++ assertEquals("ResourceNotFoundException", absent.getErrorCode());+ }++ @Test+ void updateInOneRegionLeavesTheOtherRegionUntouched() {+ when(domainManager.tryStartDomain(any())).thenReturn(false);+ service.createDomain("split-update", "OpenSearch_2.11", null, null, null, US_EAST_1);+ service.createDomain("split-update", "OpenSearch_2.11", null, null, null, EU_WEST_1);++ ClusterConfig eastConfig = new ClusterConfig();+ eastConfig.setInstanceCount(5);+ service.updateDomainConfig("split-update", null, eastConfig, null, US_EAST_1);++ assertEquals(5, service.describeDomain("split-update", US_EAST_1).getClusterConfig().getInstanceCount());+ assertEquals(1, service.describeDomain("split-update", EU_WEST_1).getClusterConfig().getInstanceCount());+ }++ @Test+ void deleteInOneRegionLeavesTheOtherRegionIntact() {+ when(domainManager.tryStartDomain(any())).thenReturn(false);+ service.createDomain("split-delete", "OpenSearch_2.11", null, null, null, US_EAST_1);+ service.createDomain("split-delete", "OpenSearch_2.11", null, null, null, EU_WEST_1);++ Domain deleted = service.deleteDomain("split-delete", US_EAST_1);++ assertTrue(deleted.isDeleted());+ assertThrows(AwsException.class, () -> service.describeDomain("split-delete", US_EAST_1));+ assertEquals(EU_WEST_1, service.describeDomain("split-delete", EU_WEST_1).getRegion());+ }++ @Test+ void listDomainNamesReturnsOnlyTheRequestRegionsDomains() {+ when(domainManager.tryStartDomain(any())).thenReturn(false);+ service.createDomain("east-listed", "OpenSearch_2.11", null, null, null, US_EAST_1);+ service.createDomain("west-listed", "OpenSearch_2.11", null, null, null, EU_WEST_1);++ List<Domain> east = service.listDomainNames(null, US_EAST_1);+ List<Domain> west = service.listDomainNames(null, EU_WEST_1);++ assertTrue(east.stream().anyMatch(d -> d.getDomainName().equals("east-listed")));+ assertFalse(east.stream().anyMatch(d -> d.getDomainName().equals("west-listed")));+ assertTrue(west.stream().anyMatch(d -> d.getDomainName().equals("west-listed")));+ assertFalse(west.stream().anyMatch(d -> d.getDomainName().equals("east-listed")));+ }++ /**+ * A record persisted before domains were keyed by region sits under the bare name; its ARN,+ * which has always carried the region, decides which region may still see it, and the+ * lookup moves it onto the region-scoped key.+ */+ @Test+ void preRegionScopingRecordResolvesByItsArnRegionAndMigrates() {+ Domain legacy = new Domain();+ legacy.setDomainName("legacy-record");+ legacy.setAccountId(ACCOUNT);+ legacy.setArn(AwsArnUtils.Arn.of("es", US_EAST_1, ACCOUNT, "domain/legacy-record").toString());+ domainStore.putForAccount(ACCOUNT, "legacy-record", legacy);++ Domain resolved = service.describeDomain("legacy-record", US_EAST_1);++ assertEquals(US_EAST_1, AwsArnUtils.parse(resolved.getArn()).region());+ assertFalse(domainStore.keysForAccount(ACCOUNT).contains("legacy-record"),+ "the lookup migrates the bare-name key onto the region-scoped key");+ assertTrue(domainStore.keysForAccount(ACCOUNT).contains(US_EAST_1 + "::legacy-record"));+ assertThrows(AwsException.class, () -> service.describeDomain("legacy-record", EU_WEST_1));+ }++ /**+ * A pre-scoping record whose ARN names another region is invisible from, and does not+ * collide with, a same-named create in this region.+ */+ @Test+ void preRegionScopingRecordOfAnotherRegionDoesNotConflictWithACreateHere() {+ when(domainManager.tryStartDomain(any())).thenReturn(false);+ Domain legacy = new Domain();+ legacy.setDomainName("legacy-elsewhere");+ legacy.setAccountId(ACCOUNT);+ legacy.setArn(AwsArnUtils.Arn.of("es", EU_WEST_1, ACCOUNT, "domain/legacy-elsewhere").toString());+ domainStore.putForAccount(ACCOUNT, "legacy-elsewhere", legacy);++ Domain created = service.createDomain("legacy-elsewhere", "OpenSearch_2.11",+ null, null, null, US_EAST_1);++ assertEquals(US_EAST_1, AwsArnUtils.parse(created.getArn()).region());+ assertEquals(EU_WEST_1,+ AwsArnUtils.parse(service.describeDomain("legacy-elsewhere", EU_WEST_1).getArn()).region());+ }++ @Test+ void pollerFlipsReadinessUnderTheScopedKey() {+ when(domainManager.tryStartDomain(any())).thenReturn(true);+ when(domainManager.isReady(any())).thenReturn(true);+ service.createDomain("poller-scoped", "OpenSearch_2.11", null, null, null, EU_WEST_1);++ service.pollReadiness();++ assertFalse(service.describeDomain("poller-scoped", EU_WEST_1).isProcessing());+ assertTrue(domainStore.keysForAccount(ACCOUNT).contains(EU_WEST_1 + "::poller-scoped"));+ }}