feat(opensearch): report VPC domains under Endpoints.vpc and emulate VPC endpoints (#7351)

This commit is contained in:
Ovidiu (Ovi) authored and GitHub committed 2026-11-02 21:28:13 -04:00
1 parent 055036508e
commit d74a084a61
11 files changed
+1063 -11

No files matched your search

@@ -0,0 +1,132 @@
package com.floci.test;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
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.services.ec2.Ec2Client;
import software.amazon.awssdk.services.opensearch.OpenSearchClient;
import software.amazon.awssdk.services.opensearch.model.ClusterConfig;
import software.amazon.awssdk.services.opensearch.model.CreateDomainResponse;
import software.amazon.awssdk.services.opensearch.model.DescribeVpcEndpointsResponse;
import software.amazon.awssdk.services.opensearch.model.DomainStatus;
import software.amazon.awssdk.services.opensearch.model.OpenSearchPartitionInstanceType;
import software.amazon.awssdk.services.opensearch.model.VPCOptions;
import software.amazon.awssdk.services.opensearch.model.VpcEndpoint;
import software.amazon.awssdk.services.opensearch.model.VpcEndpointErrorCode;
import software.amazon.awssdk.services.opensearch.model.VpcEndpointStatus;
import software.amazon.awssdk.services.opensearch.model.VpcEndpointSummary;
import java.net.URI;
import java.util.List;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
/** A domain in a VPC and its OpenSearch Service-managed VPC endpoints, through the AWS SDK for Java v2. */
@DisplayName("OpenSearch VPC endpoints")
class OpenSearchVpcEndpointTest {
private static final String DOMAIN_NAME = "os-vpce-" + UUID.randomUUID().toString().substring(0, 8);
private static OpenSearchClient opensearch;
private static Ec2Client ec2;
private static String vpcId;
private static List<String> subnetIds;
@BeforeAll
static void setUp() {
String endpoint = System.getenv("FLOCI_ENDPOINT");
if (endpoint == null || endpoint.isBlank()) {
endpoint = "http://localhost:4566";
}
if (!endpoint.startsWith("http")) {
endpoint = "http://" + endpoint;
}
StaticCredentialsProvider credentials =
StaticCredentialsProvider.create(AwsBasicCredentials.create("test", "test"));
opensearch = OpenSearchClient.builder().endpointOverride(URI.create(endpoint))
.region(Region.US_EAST_1).credentialsProvider(credentials).build();
ec2 = Ec2Client.builder().endpointOverride(URI.create(endpoint))
.region(Region.US_EAST_1).credentialsProvider(credentials).build();
vpcId = ec2.createVpc(r -> r.cidrBlock("10.42.0.0/16")).vpc().vpcId();
subnetIds = List.of(
ec2.createSubnet(r -> r.vpcId(vpcId).cidrBlock("10.42.1.0/24").availabilityZone("us-east-1a"))
.subnet().subnetId(),
ec2.createSubnet(r -> r.vpcId(vpcId).cidrBlock("10.42.2.0/24").availabilityZone("us-east-1b"))
.subnet().subnetId());
}
@AfterAll
static void cleanup() {
try {
opensearch.listVpcEndpointsForDomain(r -> r.domainName(DOMAIN_NAME)).vpcEndpointSummaryList()
.forEach(summary -> opensearch.deleteVpcEndpoint(r -> r.vpcEndpointId(summary.vpcEndpointId())));
opensearch.deleteDomain(r -> r.domainName(DOMAIN_NAME));
} catch (Exception ignored) {
// Best effort: the test may have failed before creating them.
}
try {
subnetIds.forEach(id -> ec2.deleteSubnet(r -> r.subnetId(id)));
ec2.deleteVpc(r -> r.vpcId(vpcId));
} catch (Exception ignored) {
// Best effort.
}
opensearch.close();
ec2.close();
}
@Test
void aVpcDomainAndItsEndpointRoundTripThroughTheSdk() {
CreateDomainResponse created = opensearch.createDomain(r -> r.domainName(DOMAIN_NAME)
.engineVersion("OpenSearch_2.19")
.clusterConfig(ClusterConfig.builder()
.instanceType(OpenSearchPartitionInstanceType.T3_SMALL_SEARCH).instanceCount(1).build())
.vpcOptions(VPCOptions.builder().subnetIds(subnetIds).build()));
String domainArn = created.domainStatus().arn();
// A domain in a VPC is reached through Endpoints.vpc and carries no Endpoint.
DomainStatus status = opensearch.describeDomain(r -> r.domainName(DOMAIN_NAME)).domainStatus();
assertThat(status.endpoint()).isNull();
VpcEndpoint createdEndpoint = opensearch.createVpcEndpoint(r -> r.domainArn(domainArn)
.vpcOptions(VPCOptions.builder().subnetIds(subnetIds).securityGroupIds("sg-sdk").build()))
.vpcEndpoint();
String id = createdEndpoint.vpcEndpointId();
assertThat(id).matches("^aos-[0-9a-f]{12}$");
assertThat(createdEndpoint.status()).isEqualTo(VpcEndpointStatus.CREATING);
assertThat(createdEndpoint.domainArn()).isEqualTo(domainArn);
assertThat(createdEndpoint.vpcOptions().vpcId()).isEqualTo(vpcId);
assertThat(createdEndpoint.vpcOptions().subnetIds()).containsExactlyElementsOf(subnetIds);
assertThat(createdEndpoint.vpcOptions().availabilityZones()).containsExactly("us-east-1a", "us-east-1b");
DescribeVpcEndpointsResponse described =
opensearch.describeVpcEndpoints(r -> r.vpcEndpointIds(id, "aos-000000000000"));
assertThat(described.vpcEndpoints()).singleElement()
.satisfies(endpoint -> assertThat(endpoint.status()).isEqualTo(VpcEndpointStatus.ACTIVE));
assertThat(described.vpcEndpointErrors()).singleElement().satisfies(error -> {
assertThat(error.vpcEndpointId()).isEqualTo("aos-000000000000");
assertThat(error.errorCode()).isEqualTo(VpcEndpointErrorCode.ENDPOINT_NOT_FOUND);
});
VpcEndpoint updated = opensearch.updateVpcEndpoint(r -> r.vpcEndpointId(id)
.vpcOptions(VPCOptions.builder().subnetIds(subnetIds.get(0)).securityGroupIds("sg-other").build()))
.vpcEndpoint();
assertThat(updated.status()).isEqualTo(VpcEndpointStatus.UPDATING);
assertThat(updated.vpcOptions().securityGroupIds()).containsExactly("sg-other");
List<VpcEndpointSummary> forDomain =
opensearch.listVpcEndpointsForDomain(r -> r.domainName(DOMAIN_NAME)).vpcEndpointSummaryList();
assertThat(forDomain).extracting(VpcEndpointSummary::vpcEndpointId).containsExactly(id);
assertThat(opensearch.listVpcEndpoints(r -> { }).vpcEndpointSummaryList())
.extracting(VpcEndpointSummary::vpcEndpointId).contains(id);
VpcEndpointSummary deleted = opensearch.deleteVpcEndpoint(r -> r.vpcEndpointId(id)).vpcEndpointSummary();
assertThat(deleted.status()).isEqualTo(VpcEndpointStatus.DELETING);
assertThat(opensearch.describeVpcEndpoints(r -> r.vpcEndpointIds(id)).vpcEndpoints()).isEmpty();
}
}
+23 -1
View File
@@ -55,6 +55,19 @@ services:
| `ListTags` | `GET /2021-01-01/tags/?arn=` | List tags for a domain |
| `RemoveTags` | `POST /2021-01-01/tags-removal` | Remove tag keys from a domain |
### VPC Endpoints
OpenSearch Service-managed VPC endpoints, which Terraform's `aws_opensearch_vpc_endpoint` manages.
| Operation | Method + Path | Description |
|---|---|---|
| `CreateVpcEndpoint` | `POST /2021-01-01/opensearch/vpcEndpoints` | Create an endpoint for a domain, idempotent on `ClientToken` |
| `DescribeVpcEndpoints` | `POST /2021-01-01/opensearch/vpcEndpoints/describe` | Describe endpoints by id; an unknown id is a `VpcEndpointErrors` entry |
| `UpdateVpcEndpoint` | `POST /2021-01-01/opensearch/vpcEndpoints/update` | Replace an endpoint's subnets and security groups |
| `DeleteVpcEndpoint` | `DELETE /2021-01-01/opensearch/vpcEndpoints/{id}` | Delete an endpoint |
| `ListVpcEndpoints` | `GET /2021-01-01/opensearch/vpcEndpoints` | List the Region's endpoints |
| `ListVpcEndpointsForDomain` | `GET /2021-01-01/opensearch/domain/{name}/vpcEndpoints` | List one domain's endpoints |
### Legacy Elasticsearch Service API
The `2015-01-01` API used by `aws es` and Terraform's `aws_elasticsearch_domain` is served over the same domains. It differs only in spelling: `ElasticsearchVersion` (bare, e.g. `7.10`, stored as `Elasticsearch_7.10`; `OS_2.11` and `OpenSearch_2.11` both store and report as `OpenSearch_2.11`) for `EngineVersion`, `ElasticsearchClusterConfig` for `ClusterConfig`, and instance types ending in `.elasticsearch` (`t3.small.elasticsearch` is stored, and reported by the 2021 API, as `t3.small.search`). A domain created without `ElasticsearchVersion` gets `7.10`.
@@ -126,6 +139,14 @@ services:
- **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}`
- **Domains in a VPC:** a domain created with `VPCOptions` reports its address under `Endpoints.vpc` and has no `Endpoint`, as AWS answers and as the Terraform AWS provider requires. In mock mode the address is `vpc-<domain>-<suffix>.<region>.es.amazonaws.com`; in real mode it is the container's address. `Endpoints` is left out until the address is known.
- **VPC endpoints:**
- An id reads `aos-` followed by 12 hexadecimal digits, and endpoints are scoped to an account and a Region like domains.
- `CreateVpcEndpoint`, `UpdateVpcEndpoint` and `DeleteVpcEndpoint` answer `CREATING`, `UPDATING` and `DELETING`, and the next read sees the endpoint `ACTIVE` or gone: the change takes effect at once.
- `VPCId` and `AvailabilityZones` are filled from the EC2 subnets the request names; a subnet EC2 does not know stays unresolved. Without `SecurityGroupIds` the endpoint takes the VPC's default security group, as in AWS.
- `Endpoint` is the domain's own address, since Floci serves a domain at one address; no network interface is created.
- A list returns every endpoint in one page, without `NextToken`. A domain name that names no domain lists nothing.
- An unknown domain ARN on `CreateVpcEndpoint`, or the ARN of a domain in another Region, is a `ValidationException`, and an unknown id on `UpdateVpcEndpoint` or `DeleteVpcEndpoint` a `ResourceNotFoundException`, as the API reference lists for each operation. Deleting a domain does not delete its VPC endpoints.
- **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`.
- **`Processing` flag:** `false` immediately in mock mode; `true` until the container is ready in real mode.
@@ -257,4 +278,5 @@ os_client.delete_domain(DomainName="my-search")
- No Elasticsearch-compatible management endpoints (`/2015-01-01/es/domain/...`).
- `AccessPolicies`, `VPCOptions`, `AdvancedSecurityOptions`, `EncryptionAtRestOptions`, `NodeToNodeEncryptionOptions`, and `DomainEndpointOptions` round-trip on `CreateDomain` / `UpdateDomainConfig` / `DescribeDomain` / `DescribeDomainConfig`, but are not enforced by the running container — Floci serves the domain over plain HTTP with the security plugin disabled regardless, and `AccessPolicies` is stored verbatim without being evaluated. Round-tripping is enough for SDK clients (Terraform, CDK, Pulumi) to detect drift correctly.
- Master passwords for `AdvancedSecurityOptions.MasterUserOptions` are accepted but never echoed back, matching AWS behavior.
- Cross-cluster connections, VPC endpoints, packages, applications, and data sources are not supported and return `UnsupportedOperationException`.
- Cross-cluster connections, packages, applications, and data sources are not supported and return `UnsupportedOperationException`.
- The legacy `2015-01-01` API serves no VPC endpoint operations.
@@ -553,6 +553,15 @@ public class IamActionRegistry {
rule("ses", "POST", "^/v2/email/update-configuration-sets/?$", "ses:UpdateConfigurationSet"),
rule("ses", "POST", "^/v2/email/vdm/recommendations/?$", "ses:ListRecommendations"),
// ── OpenSearch Service VPC endpoints ───────────────────────────────────
rule("es", "POST", "^/2021-01-01/opensearch/vpcEndpoints/?$", "es:CreateVpcEndpoint"),
rule("es", "GET", "^/2021-01-01/opensearch/vpcEndpoints/?$", "es:ListVpcEndpoints"),
rule("es", "POST", "^/2021-01-01/opensearch/vpcEndpoints/describe/?$", "es:DescribeVpcEndpoints"),
rule("es", "POST", "^/2021-01-01/opensearch/vpcEndpoints/update/?$", "es:UpdateVpcEndpoint"),
rule("es", "DELETE", "^/2021-01-01/opensearch/vpcEndpoints/[^/]+/?$", "es:DeleteVpcEndpoint"),
rule("es", "GET", "^/2021-01-01/opensearch/domain/[^/]+/vpcEndpoints/?$",
"es:ListVpcEndpointsForDomain"),
// ── Resource Groups ─────────────────────────────────────────────────────
rule("resource-groups", "POST", "^/_rg/groups/?$", "resource-groups:CreateGroup"),
rule("resource-groups", "POST", "^/_rg/get-group/?$", "resource-groups:GetGroup"),
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.opensearch.model.DomainEndpointOption
import io.github.hectorvent.floci.services.opensearch.model.EbsOptions;
import io.github.hectorvent.floci.services.opensearch.model.EncryptionAtRestOptions;
import io.github.hectorvent.floci.services.opensearch.model.NodeToNodeEncryptionOptions;
import io.github.hectorvent.floci.services.opensearch.model.OpenSearchVpcEndpoint;
import io.github.hectorvent.floci.services.opensearch.model.VpcOptions;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
@@ -37,17 +38,24 @@ public class OpenSearchController {
private static final Logger LOG = Logger.getLogger(OpenSearchController.class);
private final OpenSearchService service;
private final OpenSearchVpcEndpointService vpcEndpoints;
private final RegionResolver regionResolver;
private final ObjectMapper objectMapper;
@Inject
public OpenSearchController(OpenSearchService service, RegionResolver regionResolver,
ObjectMapper objectMapper) {
public OpenSearchController(OpenSearchService service, OpenSearchVpcEndpointService vpcEndpoints,
RegionResolver regionResolver, ObjectMapper objectMapper) {
this.service = service;
this.vpcEndpoints = vpcEndpoints;
this.regionResolver = regionResolver;
this.objectMapper = objectMapper;
}
/** For {@link ElasticsearchController}, which delegates the domain operations only. */
OpenSearchController(OpenSearchService service, RegionResolver regionResolver, ObjectMapper objectMapper) {
this(service, null, regionResolver, objectMapper);
}
@POST
@Path("/opensearch/domain")
public Response createDomain(@Context HttpHeaders headers, String body) {
@@ -484,6 +492,125 @@ public class OpenSearchController {
return Response.ok(response).build();
}
// ── VPC endpoints ────────────────────────────────────────────────────────
@POST
@Path("/opensearch/vpcEndpoints")
public Response createVpcEndpoint(@Context HttpHeaders headers, String body) {
JsonNode req = readBody(body);
OpenSearchVpcEndpoint endpoint = vpcEndpoints.create(req.path("DomainArn").asText(null),
parseVpcOptions(req.path("VpcOptions")), egressEnabled(req), req.path("ClientToken").asText(null),
regionResolver.resolveRegion(headers));
ObjectNode response = objectMapper.createObjectNode();
response.set("VpcEndpoint", toVpcEndpointNode(endpoint, "CREATING"));
return Response.ok(response).build();
}
@POST
@Path("/opensearch/vpcEndpoints/describe")
public Response describeVpcEndpoints(@Context HttpHeaders headers, String body) {
JsonNode req = readBody(body);
List<String> ids = null;
if (req.path("VpcEndpointIds").isArray()) {
ids = new ArrayList<>();
for (JsonNode id : req.path("VpcEndpointIds")) {
ids.add(id.asText());
}
}
OpenSearchVpcEndpointService.DescribeResult result =
vpcEndpoints.describe(ids, regionResolver.resolveRegion(headers));
ObjectNode response = objectMapper.createObjectNode();
ArrayNode found = response.putArray("VpcEndpoints");
result.endpoints().forEach(endpoint -> found.add(toVpcEndpointNode(endpoint, endpoint.getStatus())));
ArrayNode errors = response.putArray("VpcEndpointErrors");
for (OpenSearchVpcEndpointService.EndpointError error : result.errors()) {
errors.addObject()
.put("VpcEndpointId", error.vpcEndpointId())
.put("ErrorCode", error.errorCode())
.put("ErrorMessage", error.errorMessage());
}
return Response.ok(response).build();
}
@POST
@Path("/opensearch/vpcEndpoints/update")
public Response updateVpcEndpoint(@Context HttpHeaders headers, String body) {
JsonNode req = readBody(body);
OpenSearchVpcEndpoint endpoint = vpcEndpoints.update(req.path("VpcEndpointId").asText(null),
parseVpcOptions(req.path("VpcOptions")), egressEnabled(req), regionResolver.resolveRegion(headers));
ObjectNode response = objectMapper.createObjectNode();
response.set("VpcEndpoint", toVpcEndpointNode(endpoint, "UPDATING"));
return Response.ok(response).build();
}
@DELETE
@Path("/opensearch/vpcEndpoints/{vpcEndpointId}")
public Response deleteVpcEndpoint(@Context HttpHeaders headers,
@PathParam("vpcEndpointId") String vpcEndpointId) {
OpenSearchVpcEndpoint endpoint = vpcEndpoints.delete(vpcEndpointId, regionResolver.resolveRegion(headers));
ObjectNode response = objectMapper.createObjectNode();
response.set("VpcEndpointSummary", toVpcEndpointSummaryNode(endpoint, "DELETING"));
return Response.ok(response).build();
}
/** One page holds every endpoint, so no {@code NextToken} is returned. */
@GET
@Path("/opensearch/vpcEndpoints")
public Response listVpcEndpoints(@Context HttpHeaders headers) {
return vpcEndpointSummaries(vpcEndpoints.list(regionResolver.resolveRegion(headers)));
}
@GET
@Path("/opensearch/domain/{domainName}/vpcEndpoints")
public Response listVpcEndpointsForDomain(@Context HttpHeaders headers,
@PathParam("domainName") String domainName) {
return vpcEndpointSummaries(vpcEndpoints.listForDomain(domainName, regionResolver.resolveRegion(headers)));
}
private Response vpcEndpointSummaries(List<OpenSearchVpcEndpoint> endpoints) {
ObjectNode response = objectMapper.createObjectNode();
ArrayNode list = response.putArray("VpcEndpointSummaryList");
endpoints.forEach(endpoint -> list.add(toVpcEndpointSummaryNode(endpoint, endpoint.getStatus())));
return Response.ok(response).build();
}
private ObjectNode toVpcEndpointNode(OpenSearchVpcEndpoint endpoint, String status) {
ObjectNode node = objectMapper.createObjectNode();
node.put("VpcEndpointId", endpoint.getVpcEndpointId());
node.put("VpcEndpointOwner", endpoint.getVpcEndpointOwner());
node.put("DomainArn", endpoint.getDomainArn());
ObjectNode options = toVpcOptionsNode(endpoint.getVpcOptions());
if (endpoint.getEgressEnabled() != null) {
options.put("EgressEnabled", endpoint.getEgressEnabled());
}
node.set("VpcOptions", options);
node.put("Status", status);
vpcEndpoints.endpointAddress(endpoint).ifPresent(address -> node.put("Endpoint", address));
return node;
}
private ObjectNode toVpcEndpointSummaryNode(OpenSearchVpcEndpoint endpoint, String status) {
ObjectNode node = objectMapper.createObjectNode();
node.put("VpcEndpointId", endpoint.getVpcEndpointId());
node.put("VpcEndpointOwner", endpoint.getVpcEndpointOwner());
node.put("DomainArn", endpoint.getDomainArn());
node.put("Status", status);
return node;
}
private static Boolean egressEnabled(JsonNode req) {
JsonNode egress = req.path("VpcOptions").path("EgressEnabled");
return egress.isBoolean() ? egress.asBoolean() : null;
}
private JsonNode readBody(String body) {
try {
return body == null || body.isBlank() ? objectMapper.createObjectNode() : objectMapper.readTree(body);
} catch (IOException e) {
throw new AwsException("ValidationException", e.getMessage(), 400);
}
}
// ── Helpers ───────────────────────────────────────────────────────────────
private ObjectNode toDomainStatusNode(Domain domain) {
@@ -495,7 +622,14 @@ public class OpenSearchController {
node.put("Created", !domain.isProcessing());
node.put("Processing", domain.isProcessing());
node.put("Deleted", domain.isDeleted());
node.put("Endpoint", domain.getEndpoint() != null ? domain.getEndpoint() : "");
String endpoint = domain.getEndpoint() != null ? domain.getEndpoint() : "";
if (domain.getVpcOptions() == null) {
node.put("Endpoint", endpoint);
} else if (!endpoint.isEmpty()) {
// AWS reports a domain in a VPC under Endpoints.vpc and leaves Endpoint out; the Terraform
// AWS provider refuses a VPC domain that carries an Endpoint.
node.putObject("Endpoints").put("vpc", endpoint);
}
if (domain.getAccessPolicies() != null) {
node.put("AccessPolicies", domain.getAccessPolicies());
}
@@ -161,12 +161,12 @@ public class OpenSearchService implements ResourceProvider {
if (config.services().opensearch().mock()) {
domain.setProcessing(false);
domain.setEndpoint(synthesizedEndpoint(domainName, region));
domain.setEndpoint(synthesizedEndpoint(domain, region));
} else {
domain.setProcessing(true);
if (!domainManager.tryStartDomain(domain)) {
domain.setProcessing(false);
domain.setEndpoint(synthesizedEndpoint(domainName, region));
domain.setEndpoint(synthesizedEndpoint(domain, region));
}
}
@@ -181,15 +181,17 @@ public class OpenSearchService implements ResourceProvider {
* {@link OpenSearchDomainManager#tryStartDomain} returns false rather than rethrowing.
*
* <p>It reports an AWS-shaped endpoint in place of a blank one,
* {@code search-<domain>-<suffix>.<region>.es.<dnsSuffix>}, taking the DNS suffix from the
* region's partition rather than assuming the commercial one, with the name suffix derived from the
* domain name so it survives a restart. A domain reporting {@code Processing false} alongside
* {@code search-<domain>-<suffix>.<region>.es.<dnsSuffix>}, or {@code vpc-<domain>-...} for a domain in a
* VPC, taking the DNS suffix from the region's partition rather than assuming the commercial one, with the
* name suffix derived from the domain name so it survives a restart. A domain reporting {@code Processing false} alongside
* {@code Endpoint ""} describes a state AWS never returns, and a client that reads the endpoint
* to address the domain gets an empty string to connect to.
*/
private static String synthesizedEndpoint(String domainName, String region) {
private static String synthesizedEndpoint(Domain domain, String region) {
String domainName = domain.getDomainName();
String suffix = Integer.toHexString(domainName.hashCode() & 0x7fffffff);
return "search-" + domainName + "-" + suffix + "." + region + ".es."
String prefix = domain.getVpcOptions() != null ? "vpc-" : "search-";
return prefix + domainName + "-" + suffix + "." + region + ".es."
+ AwsRegions.dnsSuffixFor(region);
}
@@ -199,6 +201,20 @@ public class OpenSearchService implements ResourceProvider {
"Domain not found: " + domainName, 409));
}
/** The domain called {@code domainName} in the caller's account and {@code region}, empty when there is none. */
public Optional<Domain> findDomain(String domainName, String region) {
return findDomain(regionResolver.getAccountId(), region, domainName);
}
/** The domain an ARN names in the caller's account, empty when there is none. */
public Optional<Domain> findDomainByArn(String arn) {
try {
return Optional.of(findByArn(arn));
} catch (AwsException e) {
return Optional.empty();
}
}
public List<Domain> describeDomains(List<String> domainNames, String region) {
return domainNames.stream()
.map(name -> describeDomain(name, region))
@@ -0,0 +1,276 @@
package io.github.hectorvent.floci.services.opensearch;
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.common.SmithyValidationErrors;
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.opensearch.model.Domain;
import io.github.hectorvent.floci.services.opensearch.model.OpenSearchVpcEndpoint;
import io.github.hectorvent.floci.services.opensearch.model.VpcOptions;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
/**
* OpenSearch Service-managed VPC endpoints, scoped to an account and a region like the domains
* they lead to. An endpoint is stored {@code ACTIVE}: the create, update and delete responses carry
* the transitional status AWS answers with, and the next read already sees the settled one.
*/
@ApplicationScoped
public class OpenSearchVpcEndpointService {
private static final Logger LOG = Logger.getLogger(OpenSearchVpcEndpointService.class);
static final String ENDPOINT_NOT_FOUND = "ENDPOINT_NOT_FOUND";
// Both captured from DescribeVpcEndpoints against AWS for an id that does not exist.
static final String ENDPOINT_NOT_FOUND_MESSAGE = "Endpoint does not exist";
private static final String ID_PATTERN = "^aos-[a-zA-Z0-9]*$";
private static final Pattern ID = Pattern.compile(ID_PATTERN);
private static final int ID_MIN = 5;
private static final int ID_MAX = 256;
private final AccountAwareStorageBackend<OpenSearchVpcEndpoint> endpoints;
private final OpenSearchService domains;
private final RegionResolver regionResolver;
private final Ec2Service ec2Service;
@Inject
public OpenSearchVpcEndpointService(StorageFactory storageFactory, OpenSearchService domains,
RegionResolver regionResolver, Ec2Service ec2Service) {
this(storageFactory.create("opensearch", "opensearch-vpc-endpoints.json",
new TypeReference<Map<String, OpenSearchVpcEndpoint>>() {}), domains, regionResolver, ec2Service);
}
OpenSearchVpcEndpointService(AccountAwareStorageBackend<OpenSearchVpcEndpoint> endpoints,
OpenSearchService domains, RegionResolver regionResolver, Ec2Service ec2Service) {
this.endpoints = endpoints;
this.domains = domains;
this.regionResolver = regionResolver;
this.ec2Service = ec2Service;
}
/** One {@code VpcEndpointErrors} entry. */
public record EndpointError(String vpcEndpointId, String errorCode, String errorMessage) {}
/** The endpoints found and an error for each id that names none, as {@code DescribeVpcEndpoints} answers. */
public record DescribeResult(List<OpenSearchVpcEndpoint> endpoints, List<EndpointError> errors) {}
/**
* Creates an endpoint for the domain the ARN names. A retry carrying the same {@code ClientToken}
* for the same domain answers the endpoint the first call created.
*/
public synchronized OpenSearchVpcEndpoint create(String domainArn, VpcOptions requested, Boolean egressEnabled,
String clientToken, String region) {
List<String> violations = new ArrayList<>();
if (domainArn == null || domainArn.isBlank()) {
violations.add(SmithyValidationErrors.notNull("domainArn"));
}
if (requested == null) {
violations.add(SmithyValidationErrors.notNull("vpcOptions"));
}
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
// The endpoint is kept in the request's Region, so a domain of another Region is refused as
// unknown: neither Region's ListVpcEndpointsForDomain could otherwise find the endpoint.
Domain domain = domains.findDomainByArn(domainArn)
.filter(found -> region.equals(AwsArnUtils.parse(found.getArn()).region()))
.orElseThrow(() -> new AwsException("ValidationException",
"Domain not found for ARN: " + domainArn, 400));
if (clientToken != null && !clientToken.isBlank()) {
Optional<OpenSearchVpcEndpoint> earlier = inRegion(region).stream()
.filter(endpoint -> clientToken.equals(endpoint.getClientToken())
&& domain.getArn().equals(endpoint.getDomainArn()))
.findFirst();
if (earlier.isPresent()) {
return earlier.get();
}
}
OpenSearchVpcEndpoint endpoint = new OpenSearchVpcEndpoint();
endpoint.setVpcEndpointId("aos-" + newIdSuffix());
endpoint.setVpcEndpointOwner(regionResolver.getAccountId());
endpoint.setDomainArn(domain.getArn());
endpoint.setVpcOptions(resolved(requested, region));
endpoint.setEgressEnabled(egressEnabled);
endpoint.setClientToken(clientToken);
endpoint.setStatus("ACTIVE");
endpoints.put(storageKey(region, endpoint.getVpcEndpointId()), endpoint);
LOG.infov("Created OpenSearch VPC endpoint {0} for {1}", endpoint.getVpcEndpointId(), domain.getArn());
return endpoint;
}
public DescribeResult describe(List<String> vpcEndpointIds, String region) {
if (vpcEndpointIds == null) {
throw SmithyValidationErrors.validationException(SmithyValidationErrors.notNull("vpcEndpointIds"));
}
// AWS checks the list as a whole, quoting all of it, as captured for one malformed id.
if (vpcEndpointIds.stream().anyMatch(id -> !validId(id))) {
throw SmithyValidationErrors.validationException("Value '" + vpcEndpointIds
+ "' at 'vpcEndpointIds' failed to satisfy constraint: Member must satisfy constraint: "
+ SmithyValidationErrors.constraintSet(ID_MIN, ID_MAX, ID_PATTERN, null));
}
List<OpenSearchVpcEndpoint> found = new ArrayList<>();
List<EndpointError> errors = new ArrayList<>();
for (String id : new LinkedHashSet<>(vpcEndpointIds)) {
Optional<OpenSearchVpcEndpoint> endpoint = endpoints.get(storageKey(region, id));
if (endpoint.isPresent()) {
found.add(endpoint.get());
} else {
errors.add(new EndpointError(id, ENDPOINT_NOT_FOUND, ENDPOINT_NOT_FOUND_MESSAGE));
}
}
return new DescribeResult(found, errors);
}
/** Replaces the subnets, the security groups and the egress setting the request names. */
public synchronized OpenSearchVpcEndpoint update(String vpcEndpointId, VpcOptions requested,
Boolean egressEnabled, String region) {
List<String> violations = new ArrayList<>(idViolations(vpcEndpointId));
if (requested == null) {
violations.add(SmithyValidationErrors.notNull("vpcOptions"));
}
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
OpenSearchVpcEndpoint endpoint = require(vpcEndpointId, region);
endpoint.setVpcOptions(resolved(requested, region));
if (egressEnabled != null) {
endpoint.setEgressEnabled(egressEnabled);
}
endpoints.put(storageKey(region, vpcEndpointId), endpoint);
return endpoint;
}
public synchronized OpenSearchVpcEndpoint delete(String vpcEndpointId, String region) {
List<String> violations = idViolations(vpcEndpointId);
if (!violations.isEmpty()) {
throw SmithyValidationErrors.validationException(violations);
}
OpenSearchVpcEndpoint endpoint = require(vpcEndpointId, region);
endpoints.delete(storageKey(region, vpcEndpointId));
LOG.infov("Deleted OpenSearch VPC endpoint {0}", vpcEndpointId);
return endpoint;
}
/** Every endpoint in the caller's account and region, in id order. */
public List<OpenSearchVpcEndpoint> list(String region) {
return inRegion(region);
}
/**
* The endpoints of the domain called {@code domainName}. A name no domain carries lists nothing
* rather than failing, as AWS was captured answering.
*/
public List<OpenSearchVpcEndpoint> listForDomain(String domainName, String region) {
Optional<Domain> domain = domains.findDomain(domainName, region);
if (domain.isEmpty()) {
return List.of();
}
String domainArn = domain.get().getArn();
return inRegion(region).stream()
.filter(endpoint -> domainArn.equals(endpoint.getDomainArn()))
.toList();
}
/** The address a client reaches the endpoint's domain at, which in Floci is the domain's own. */
public Optional<String> endpointAddress(OpenSearchVpcEndpoint endpoint) {
return domains.findDomainByArn(endpoint.getDomainArn())
.map(Domain::getEndpoint)
.filter(address -> !address.isEmpty());
}
private OpenSearchVpcEndpoint require(String vpcEndpointId, String region) {
return endpoints.get(storageKey(region, vpcEndpointId))
.orElseThrow(() -> new AwsException("ResourceNotFoundException", ENDPOINT_NOT_FOUND_MESSAGE, 409));
}
private List<OpenSearchVpcEndpoint> inRegion(String region) {
return endpoints.scan(key -> key.startsWith(region + "::")).stream()
.sorted(Comparator.comparing(OpenSearchVpcEndpoint::getVpcEndpointId))
.toList();
}
/**
* The requested subnets and security groups, with the VPC and zones EC2 knows the subnets by. A
* subnet EC2 does not know is kept as given and left unresolved. Without security groups the
* endpoint takes the VPC's default one, as AWS does, when EC2 knows the VPC and still has it.
*/
private VpcOptions resolved(VpcOptions requested, String region) {
VpcOptions options = new VpcOptions();
options.setSubnetIds(new ArrayList<>(requested.getSubnetIds()));
options.setSecurityGroupIds(new ArrayList<>(requested.getSecurityGroupIds()));
if (ec2Service != null && !requested.getSubnetIds().isEmpty()) {
Map<String, Subnet> known = new HashMap<>();
ec2Service.describeSubnets(region, requested.getSubnetIds(), Map.of())
.forEach(subnet -> known.put(subnet.getSubnetId(), subnet));
// In the order the subnets were requested.
Set<String> zones = new LinkedHashSet<>();
for (String subnetId : requested.getSubnetIds()) {
Subnet subnet = known.get(subnetId);
if (subnet != null) {
zones.add(subnet.getAvailabilityZone());
if (options.getVpcId() == null) {
options.setVpcId(subnet.getVpcId());
}
}
}
options.setAvailabilityZones(new ArrayList<>(zones));
if (options.getSecurityGroupIds().isEmpty() && options.getVpcId() != null) {
ec2Service.defaultSecurityGroupOf(region, options.getVpcId())
.ifPresent(group -> options.setSecurityGroupIds(new ArrayList<>(List.of(group.getGroupId()))));
}
}
return options;
}
private static List<String> idViolations(String vpcEndpointId) {
if (vpcEndpointId == null || vpcEndpointId.isEmpty()) {
return List.of(SmithyValidationErrors.notNull("vpcEndpointId"));
}
List<String> violations = new ArrayList<>();
String length = SmithyValidationErrors.lengthOutOfRange("vpcEndpointId", vpcEndpointId, ID_MIN, ID_MAX);
if (length != null) {
violations.add(length);
}
if (!ID.matcher(vpcEndpointId).matches()) {
violations.add(SmithyValidationErrors.pattern("vpcEndpointId", vpcEndpointId, ID_PATTERN));
}
return violations;
}
private static boolean validId(String id) {
return id != null && id.length() >= ID_MIN && id.length() <= ID_MAX && ID.matcher(id).matches();
}
/**
* Twelve hexadecimal digits, the form AWS endpoint ids take. An id is no secret, and a random
* held in a static field would be fixed into the native image at build time.
*/
private static String newIdSuffix() {
byte[] bytes = new byte[6];
ThreadLocalRandom.current().nextBytes(bytes);
return HexFormat.of().formatHex(bytes);
}
private static String storageKey(String region, String vpcEndpointId) {
return region + "::" + vpcEndpointId;
}
}
@@ -0,0 +1,58 @@
package io.github.hectorvent.floci.services.opensearch.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.quarkus.runtime.annotations.RegisterForReflection;
/**
* An OpenSearch Service-managed VPC endpoint ({@code CreateVpcEndpoint}): a way into a VPC domain
* from another VPC. Floci keeps the record; no network interface is created.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class OpenSearchVpcEndpoint {
@JsonProperty("VpcEndpointId")
private String vpcEndpointId;
@JsonProperty("VpcEndpointOwner")
private String vpcEndpointOwner;
@JsonProperty("DomainArn")
private String domainArn;
/** Subnets and security groups as requested, with the VPC and zones EC2 knows them by. */
@JsonProperty("VpcOptions")
private VpcOptions vpcOptions = new VpcOptions();
@JsonProperty("EgressEnabled")
private Boolean egressEnabled;
@JsonProperty("Status")
private String status;
/** Scopes a retried {@code CreateVpcEndpoint} to the endpoint it already created. */
@JsonProperty("ClientToken")
private String clientToken;
public String getVpcEndpointId() { return vpcEndpointId; }
public void setVpcEndpointId(String vpcEndpointId) { this.vpcEndpointId = vpcEndpointId; }
public String getVpcEndpointOwner() { return vpcEndpointOwner; }
public void setVpcEndpointOwner(String vpcEndpointOwner) { this.vpcEndpointOwner = vpcEndpointOwner; }
public String getDomainArn() { return domainArn; }
public void setDomainArn(String domainArn) { this.domainArn = domainArn; }
public VpcOptions getVpcOptions() { return vpcOptions; }
public void setVpcOptions(VpcOptions vpcOptions) { this.vpcOptions = vpcOptions; }
public Boolean getEgressEnabled() { return egressEnabled; }
public void setEgressEnabled(Boolean egressEnabled) { this.egressEnabled = egressEnabled; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public String getClientToken() { return clientToken; }
public void setClientToken(String clientToken) { this.clientToken = clientToken; }
}
@@ -89,6 +89,19 @@ class IamActionRegistryTest {
new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}")));
}
@ParameterizedTest
@CsvSource({"POST,/2021-01-01/opensearch/vpcEndpoints,CreateVpcEndpoint",
"GET,/2021-01-01/opensearch/vpcEndpoints,ListVpcEndpoints",
"POST,/2021-01-01/opensearch/vpcEndpoints/describe,DescribeVpcEndpoints",
"POST,/2021-01-01/opensearch/vpcEndpoints/update,UpdateVpcEndpoint",
"DELETE,/2021-01-01/opensearch/vpcEndpoints/aos-0123456789ab,DeleteVpcEndpoint",
"GET,/2021-01-01/opensearch/domain/orders/vpcEndpoints,ListVpcEndpointsForDomain"})
void openSearchVpcEndpointRoutesResolveTheirOwnActions(String method, String path, String operation) {
ContainerRequestContext ctx = mockCtx(method, path,
new MultivaluedHashMap<>(), MediaType.APPLICATION_JSON_TYPE, "{}");
assertEquals("es:" + operation, registry.resolveRoute("es", ctx));
}
@Test
void inspector2DisableRouteResolvesItsAction() {
ContainerRequestContext ctx = mockCtx("POST", "/disable",
@@ -0,0 +1,77 @@
package io.github.hectorvent.floci.services.opensearch;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.util.UUID;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
/** The VPC endpoint operations are checked as their own {@code es:} actions. */
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class OpenSearchVpcEndpointIamEnforcementIntegrationTest {
private static final String ACCOUNT_ID = "000000000000";
@TestHTTPResource("/")
static URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void aCallerAllowedOnlyToListEndpointsCannotCreateDescribeUpdateOrDeleteThem() {
String accessKeyId = userAllowed("es:ListVpcEndpoints");
String authorization = auth(accessKeyId, "es");
given().header("Authorization", authorization)
.when().get("/2021-01-01/opensearch/vpcEndpoints")
.then().statusCode(200);
given().header("Authorization", authorization).contentType("application/json")
.body("""
{"DomainArn": "arn:aws:es:us-east-1:000000000000:domain/orders",
"VpcOptions": {"SubnetIds": ["subnet-a"]}}""")
.when().post("/2021-01-01/opensearch/vpcEndpoints")
.then().statusCode(403);
given().header("Authorization", authorization).contentType("application/json")
.body("{\"VpcEndpointIds\": [\"aos-0123456789ab\"]}")
.when().post("/2021-01-01/opensearch/vpcEndpoints/describe")
.then().statusCode(403);
given().header("Authorization", authorization).contentType("application/json")
.body("{\"VpcEndpointId\": \"aos-0123456789ab\", \"VpcOptions\": {\"SubnetIds\": [\"subnet-a\"]}}")
.when().post("/2021-01-01/opensearch/vpcEndpoints/update")
.then().statusCode(403);
given().header("Authorization", authorization)
.when().delete("/2021-01-01/opensearch/vpcEndpoints/aos-0123456789ab")
.then().statusCode(403);
given().header("Authorization", authorization)
.when().get("/2021-01-01/opensearch/domain/orders/vpcEndpoints")
.then().statusCode(403);
}
private String userAllowed(String action) {
String userName = "os-endpoints-" + UUID.randomUUID().toString().substring(0, 8);
String rootAuthorization = auth(ACCOUNT_ID, "iam");
String accessKeyId = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), rootAuthorization, userName)
.accessKeyId();
EnforcementFixtures.putUserPolicy(baseUri.getPort(), rootAuthorization, userName, "only", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"%s","Resource":"*"}
]}""".formatted(action));
return accessKeyId;
}
}
@@ -0,0 +1,261 @@
package io.github.hectorvent.floci.services.opensearch;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import jakarta.inject.Inject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* A domain in a VPC and the OpenSearch Service-managed VPC endpoints that lead into one. The
* shapes, the {@code ENDPOINT_NOT_FOUND} error entry, the malformed-id message and the empty list
* for an unknown domain were captured from AWS.
*/
@QuarkusTest
class OpenSearchVpcEndpointIntegrationTest {
private static final String AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/us-east-1/es/aws4_request";
private static final String WEST_AUTH_HEADER =
"AWS4-HMAC-SHA256 Credential=AKID/20260101/eu-west-1/es/aws4_request";
private static final String VPC_DOMAIN = "vpce-domain";
private static final String PUBLIC_DOMAIN = "vpce-public";
// The seeded default subnets, so EC2 can name their VPC and zones.
private static final String SUBNET_A = Ec2Service.defaultSubnetId("us-east-1", "a");
private static final String SUBNET_B = Ec2Service.defaultSubnetId("us-east-1", "b");
@Inject
Ec2Service ec2Service;
@AfterEach
void cleanup() {
for (String name : new String[]{VPC_DOMAIN, PUBLIC_DOMAIN}) {
given().header("Authorization", AUTH_HEADER).when().delete("/2021-01-01/opensearch/domain/" + name);
}
List<String> ids = given().header("Authorization", AUTH_HEADER)
.when().get("/2021-01-01/opensearch/vpcEndpoints")
.then().extract().path("VpcEndpointSummaryList.VpcEndpointId");
if (ids != null) {
ids.forEach(id -> given().header("Authorization", AUTH_HEADER)
.when().delete("/2021-01-01/opensearch/vpcEndpoints/" + id));
}
}
@Test
void aDomainInAVpcIsReportedUnderEndpointsVpcAndAPublicOneUnderEndpoint() {
createVpcDomain()
.body("DomainStatus.Endpoint", nullValue())
.body("DomainStatus.Endpoints.vpc", startsWith("vpc-" + VPC_DOMAIN + "-"))
.body("DomainStatus.Endpoints.vpc", endsWith(".us-east-1.es.amazonaws.com"));
given().header("Authorization", AUTH_HEADER)
.when().get("/2021-01-01/opensearch/domain/" + VPC_DOMAIN)
.then().statusCode(200)
.body("DomainStatus.Endpoint", nullValue())
.body("DomainStatus.Endpoints.vpc", startsWith("vpc-" + VPC_DOMAIN + "-"));
// The legacy Elasticsearch API reports the same domain the same way.
given().header("Authorization", AUTH_HEADER)
.when().get("/2015-01-01/es/domain/" + VPC_DOMAIN)
.then().statusCode(200)
.body("DomainStatus.Endpoint", nullValue())
.body("DomainStatus.Endpoints.vpc", startsWith("vpc-" + VPC_DOMAIN + "-"));
given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"DomainName\":\"" + PUBLIC_DOMAIN + "\",\"EngineVersion\":\"OpenSearch_2.19\"}")
.when().post("/2021-01-01/opensearch/domain")
.then().statusCode(200)
.body("DomainStatus.Endpoint", startsWith("search-" + PUBLIC_DOMAIN + "-"))
.body("DomainStatus.Endpoints", nullValue());
}
@Test
void anEndpointIsCreatedDescribedUpdatedListedAndDeleted() {
String domainArn = createVpcDomain().extract().path("DomainStatus.ARN");
String domainAddress = given().header("Authorization", AUTH_HEADER)
.when().get("/2021-01-01/opensearch/domain/" + VPC_DOMAIN)
.then().extract().path("DomainStatus.Endpoints.vpc");
String id = createEndpoint(domainArn, null)
.body("VpcEndpoint.VpcEndpointId", matchesPattern("^aos-[0-9a-f]{12}$"))
.body("VpcEndpoint.VpcEndpointOwner", equalTo("000000000000"))
.body("VpcEndpoint.DomainArn", equalTo(domainArn))
.body("VpcEndpoint.Status", equalTo("CREATING"))
.body("VpcEndpoint.VpcOptions.SubnetIds", contains(SUBNET_A, SUBNET_B))
.body("VpcEndpoint.VpcOptions.SecurityGroupIds", contains("sg-one"))
.body("VpcEndpoint.VpcOptions.VPCId", startsWith("vpc-"))
.body("VpcEndpoint.VpcOptions.AvailabilityZones", contains("us-east-1a", "us-east-1b"))
.body("VpcEndpoint.Endpoint", equalTo(domainAddress))
.extract().path("VpcEndpoint.VpcEndpointId");
describe("[\"" + id + "\",\"aos-000000000000\"]")
.body("VpcEndpoints", hasSize(1))
.body("VpcEndpoints[0].VpcEndpointId", equalTo(id))
.body("VpcEndpoints[0].Status", equalTo("ACTIVE"))
.body("VpcEndpointErrors", hasSize(1))
.body("VpcEndpointErrors[0].VpcEndpointId", equalTo("aos-000000000000"))
.body("VpcEndpointErrors[0].ErrorCode", equalTo("ENDPOINT_NOT_FOUND"))
.body("VpcEndpointErrors[0].ErrorMessage", equalTo("Endpoint does not exist"));
given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"VpcEndpointId\":\"" + id + "\",\"VpcOptions\":{\"SubnetIds\":[\"" + SUBNET_A
+ "\"],\"SecurityGroupIds\":[\"sg-two\"]}}")
.when().post("/2021-01-01/opensearch/vpcEndpoints/update")
.then().statusCode(200)
.body("VpcEndpoint.Status", equalTo("UPDATING"))
.body("VpcEndpoint.VpcOptions.SubnetIds", contains(SUBNET_A))
.body("VpcEndpoint.VpcOptions.SecurityGroupIds", contains("sg-two"))
.body("VpcEndpoint.VpcOptions.AvailabilityZones", contains("us-east-1a"));
describe("[\"" + id + "\"]")
.body("VpcEndpoints[0].Status", equalTo("ACTIVE"))
.body("VpcEndpoints[0].VpcOptions.SecurityGroupIds", contains("sg-two"));
given().header("Authorization", AUTH_HEADER)
.when().get("/2021-01-01/opensearch/vpcEndpoints")
.then().statusCode(200)
.body("VpcEndpointSummaryList.VpcEndpointId", hasItem(id))
.body("VpcEndpointSummaryList[0].Status", equalTo("ACTIVE"))
.body("NextToken", nullValue());
given().header("Authorization", AUTH_HEADER)
.when().get("/2021-01-01/opensearch/domain/" + VPC_DOMAIN + "/vpcEndpoints")
.then().statusCode(200)
.body("VpcEndpointSummaryList", hasSize(1))
.body("VpcEndpointSummaryList[0].VpcEndpointId", equalTo(id))
.body("VpcEndpointSummaryList[0].DomainArn", equalTo(domainArn));
// Endpoints belong to their region.
given().header("Authorization", WEST_AUTH_HEADER)
.when().get("/2021-01-01/opensearch/vpcEndpoints")
.then().statusCode(200)
.body("VpcEndpointSummaryList.VpcEndpointId", not(hasItem(id)));
// A domain of another Region is unknown to a create signed for this one.
given().contentType("application/json").header("Authorization", WEST_AUTH_HEADER)
.body("{\"DomainArn\":\"" + domainArn + "\",\"VpcOptions\":{\"SubnetIds\":[\"" + SUBNET_A + "\"]}}")
.when().post("/2021-01-01/opensearch/vpcEndpoints")
.then().statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("Domain not found for ARN: " + domainArn));
given().header("Authorization", AUTH_HEADER)
.when().delete("/2021-01-01/opensearch/vpcEndpoints/" + id)
.then().statusCode(200)
.body("VpcEndpointSummary.VpcEndpointId", equalTo(id))
.body("VpcEndpointSummary.Status", equalTo("DELETING"));
describe("[\"" + id + "\"]")
.body("VpcEndpoints", empty())
.body("VpcEndpointErrors[0].ErrorCode", equalTo("ENDPOINT_NOT_FOUND"));
given().header("Authorization", AUTH_HEADER)
.when().delete("/2021-01-01/opensearch/vpcEndpoints/" + id)
.then().statusCode(409)
.body("__type", containsString("ResourceNotFoundException"));
}
@Test
void anEndpointWithoutSecurityGroupsTakesTheVpcsDefaultOneOnCreateAndUpdate() {
String domainArn = createVpcDomain().extract().path("DomainStatus.ARN");
ValidatableResponse created = given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"DomainArn\":\"" + domainArn + "\",\"VpcOptions\":{\"SubnetIds\":[\"" + SUBNET_A + "\"]}}")
.when().post("/2021-01-01/opensearch/vpcEndpoints")
.then().statusCode(200);
String vpcId = created.extract().path("VpcEndpoint.VpcOptions.VPCId");
String id = created.extract().path("VpcEndpoint.VpcEndpointId");
String defaultGroup = ec2Service.defaultSecurityGroupOf("us-east-1", vpcId).orElseThrow().getGroupId();
created.body("VpcEndpoint.VpcOptions.SecurityGroupIds", contains(defaultGroup));
given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"VpcEndpointId\":\"" + id + "\",\"VpcOptions\":{\"SubnetIds\":[\"" + SUBNET_B + "\"]}}")
.when().post("/2021-01-01/opensearch/vpcEndpoints/update")
.then().statusCode(200)
.body("VpcEndpoint.VpcOptions.SecurityGroupIds", contains(defaultGroup));
}
@Test
void aRetriedCreateWithTheSameClientTokenAnswersTheSameEndpoint() {
String domainArn = createVpcDomain().extract().path("DomainStatus.ARN");
String first = createEndpoint(domainArn, "token-1").extract().path("VpcEndpoint.VpcEndpointId");
String retried = createEndpoint(domainArn, "token-1").extract().path("VpcEndpoint.VpcEndpointId");
String other = createEndpoint(domainArn, "token-2").extract().path("VpcEndpoint.VpcEndpointId");
assertEquals(first, retried);
assertNotEquals(first, other);
}
@Test
void requestsAreValidatedAsAwsAnswers() {
describe("[]").body("VpcEndpoints", empty()).body("VpcEndpointErrors", empty());
given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"VpcEndpointIds\":[\"not-an-id\"]}")
.when().post("/2021-01-01/opensearch/vpcEndpoints/describe")
.then().statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", equalTo("1 validation error detected: Value '[not-an-id]' at 'vpcEndpointIds' "
+ "failed to satisfy constraint: Member must satisfy constraint: [Member must have length "
+ "less than or equal to 256, Member must have length greater than or equal to 5, Member "
+ "must satisfy regular expression pattern: ^aos-[a-zA-Z0-9]*$]"));
given().header("Authorization", AUTH_HEADER)
.when().get("/2021-01-01/opensearch/domain/no-such-domain/vpcEndpoints")
.then().statusCode(200)
.body("VpcEndpointSummaryList", empty());
given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"VpcOptions\":{\"SubnetIds\":[\"" + SUBNET_A + "\"]}}")
.when().post("/2021-01-01/opensearch/vpcEndpoints")
.then().statusCode(400)
.body("__type", containsString("ValidationException"))
.body("message", containsString("'domainArn' failed to satisfy constraint: Member must not be null"));
createEndpointResponse("arn:aws:es:us-east-1:000000000000:domain/no-such-domain", null)
.statusCode(400)
.body("__type", containsString("ValidationException"));
given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"VpcEndpointId\":\"aos-000000000000\",\"VpcOptions\":{\"SubnetIds\":[]}}")
.when().post("/2021-01-01/opensearch/vpcEndpoints/update")
.then().statusCode(409)
.body("__type", containsString("ResourceNotFoundException"));
}
private ValidatableResponse createVpcDomain() {
return given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"DomainName\":\"" + VPC_DOMAIN + "\",\"EngineVersion\":\"OpenSearch_2.19\","
+ "\"VPCOptions\":{\"SubnetIds\":[\"" + SUBNET_A + "\",\"" + SUBNET_B + "\"]}}")
.when().post("/2021-01-01/opensearch/domain")
.then().statusCode(200)
.body("DomainStatus.ARN", notNullValue());
}
private ValidatableResponse createEndpoint(String domainArn, String clientToken) {
return createEndpointResponse(domainArn, clientToken).statusCode(200);
}
private ValidatableResponse createEndpointResponse(String domainArn, String clientToken) {
String token = clientToken == null ? "" : ",\"ClientToken\":\"" + clientToken + "\"";
return given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"DomainArn\":\"" + domainArn + "\",\"VpcOptions\":{\"SubnetIds\":[\"" + SUBNET_A + "\",\""
+ SUBNET_B + "\"],\"SecurityGroupIds\":[\"sg-one\"]}" + token + "}")
.when().post("/2021-01-01/opensearch/vpcEndpoints")
.then();
}
private ValidatableResponse describe(String idsJson) {
return given().contentType("application/json").header("Authorization", AUTH_HEADER)
.body("{\"VpcEndpointIds\":" + idsJson + "}")
.when().post("/2021-01-01/opensearch/vpcEndpoints/describe")
.then().statusCode(200);
}
}
@@ -0,0 +1,54 @@
package io.github.hectorvent.floci.services.opensearch.model;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** A VPC endpoint survives the persistent storage modes. */
class OpenSearchVpcEndpointJacksonRoundTripTest {
/** Same configuration {@code PersistentStorage}, {@code HybridStorage} and {@code WalStorage} use. */
private final ObjectMapper mapper = new ObjectMapper();
OpenSearchVpcEndpointJacksonRoundTripTest() {
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
@Test
void anEndpointSurvivesARoundTrip() throws Exception {
OpenSearchVpcEndpoint endpoint = new OpenSearchVpcEndpoint();
endpoint.setVpcEndpointId("aos-0123456789ab");
endpoint.setVpcEndpointOwner("000000000000");
endpoint.setDomainArn("arn:aws:es:us-east-1:000000000000:domain/orders");
VpcOptions options = new VpcOptions();
options.setSubnetIds(List.of("subnet-a", "subnet-b"));
options.setSecurityGroupIds(List.of("sg-one"));
options.setAvailabilityZones(List.of("us-east-1a", "us-east-1b"));
options.setVpcId("vpc-one");
endpoint.setVpcOptions(options);
endpoint.setEgressEnabled(true);
endpoint.setStatus("ACTIVE");
endpoint.setClientToken("token-1");
OpenSearchVpcEndpoint reloaded =
mapper.readValue(mapper.writeValueAsString(endpoint), OpenSearchVpcEndpoint.class);
assertEquals("aos-0123456789ab", reloaded.getVpcEndpointId());
assertEquals("000000000000", reloaded.getVpcEndpointOwner());
assertEquals("arn:aws:es:us-east-1:000000000000:domain/orders", reloaded.getDomainArn());
assertEquals(List.of("subnet-a", "subnet-b"), reloaded.getVpcOptions().getSubnetIds());
assertEquals(List.of("sg-one"), reloaded.getVpcOptions().getSecurityGroupIds());
assertEquals(List.of("us-east-1a", "us-east-1b"), reloaded.getVpcOptions().getAvailabilityZones());
assertEquals("vpc-one", reloaded.getVpcOptions().getVpcId());
assertTrue(reloaded.getEgressEnabled());
assertEquals("ACTIVE", reloaded.getStatus());
assertEquals("token-1", reloaded.getClientToken());
}
}