feat(ec2): add Client VPN endpoints, associations, rules and routes (#7425)

* feat(ec2): add Client VPN endpoints, associations, rules and routes

Store Client VPN endpoints with their target network associations,
authorization rules and routes, and export the OpenVPN client
configuration from the server certificate held in ACM. Fifteen EC2
Query actions; no VPN server runs.

* fix(ec2): apply Client VPN describe filters and pin associated subnets

Apply AWS's filters on the four Client VPN describe operations and refuse
unknown ones. Report selfServicePortalUrl for an endpoint with the portal
enabled. Require every requested security group to exist. Register
associations as subnet and VPC dependencies, saved under the subnet
reference lock. Compare rule and route CIDRs as networks. Replace the
endpoint's lists instead of changing them in place, and let only a
missing ACM certificate leave the export without its CA.

* refactor(ec2): share the Query protocol helpers and the id hex generator

Move the EC2 Query parameter and response helpers Ec2QueryHandler kept
private (getList, getFiltersList, boolParam, intParam, tagSetXml,
booleanResponse, xmlResponse) into Ec2QueryProtocol, which the Client VPN
handler now uses too, and replace the four randomHex copies in
Ec2Service, Ec2IpamService, FlowLogService and Ec2ClientVpnService with
Ec2Ids.randomHex. The Client VPN test builds its requests through
testing.Ec2Requests.

* style(ec2): brace the loop exits in Ec2QueryProtocol
This commit is contained in:
Ovidiu (Ovi) authored and GitHub committed 2026-11-03 15:16:59 -04:00
1 parent 5b955981fb
commit a772b27583
12 files changed
+1709 -117

No files matched your search

+54
View File
@@ -1211,6 +1211,60 @@ Spot prices returned by `DescribeSpotPriceHistory` are synthetic and derived det
|--------|-------------|
| DescribeVpnGateways | Returns an empty gateway set (no stored gateways). |
### Client VPN
| Action | Description |
|--------|-------------|
| CreateClientVpnEndpoint | Creates an endpoint; a `client-vpn-endpoint` `TagSpecification` tags it. |
| DescribeClientVpnEndpoints | Lists endpoints, or the ones `ClientVpnEndpointId.N` names. |
| ModifyClientVpnEndpoint | Changes the members the request gives. |
| DeleteClientVpnEndpoint | Deletes an endpoint with no associated target networks. |
| AssociateClientVpnTargetNetwork | Associates a subnet and adds the route to its VPC through it. |
| DescribeClientVpnTargetNetworks | Lists an endpoint's associations. |
| DisassociateClientVpnTargetNetwork | Removes an association and the routes through its subnet. |
| ApplySecurityGroupsToClientVpnTargetNetwork | Sets the security groups the endpoint applies in its VPC. |
| AuthorizeClientVpnIngress | Adds an authorization rule for a network, for one group or all. |
| DescribeClientVpnAuthorizationRules | Lists an endpoint's authorization rules. |
| RevokeClientVpnIngress | Removes an authorization rule. |
| CreateClientVpnRoute | Adds a route through an associated subnet. |
| DescribeClientVpnRoutes | Lists an endpoint's routes, the ones associations added included. |
| DeleteClientVpnRoute | Removes a route the endpoint was given. |
| ExportClientVpnClientConfiguration | Returns the OpenVPN client configuration for the endpoint. |
Client VPN is a configuration registry: no VPN server runs, so clients cannot connect. An endpoint
is `pending-associate` until a subnet is associated, then `available`, and its DNS name is
`*.cvpn-endpoint-<id>.prod.clientvpn.<region>.<dns suffix>`. Defaults are AWS's: `udp` on port 443,
a 24-hour session timeout, the self-service portal disabled, and, for a VPC given without security
groups, the VPC's default security group.
- Associations settle as `associated`, authorization rules and routes as `active`, at once; the
operation's response carries the transitional status AWS answers with (`associating`,
`authorizing`, `creating`).
- An association needs a subnet of the endpoint's VPC, one per Availability Zone. It adds a
`Default Route` to the VPC's CIDR through the subnet (`origin` `associate`, `type` `Nat`), which
goes with the association. An endpoint created without a VPC takes the first subnet's VPC and its
default security group.
- An association pins its subnet and VPC, as the network interface AWS places in the subnet does:
`DeleteSubnet` and `DeleteVpc` answer `DependencyViolation` until it is disassociated.
- An endpoint with associated target networks cannot be deleted (`IncorrectState`).
- Security groups named on create, modify or `ApplySecurityGroupsToClientVpnTargetNetwork` must
exist (`InvalidGroup.NotFound`) and be in the endpoint's VPC.
- Authorization rules and routes compare networks, not spellings: `10.0.0.9/16` is the same network
as `10.0.0.0/16`, so it is a duplicate on create and matches on revoke or delete.
- The describe operations take AWS's filters, with `*` and `?` wildcards: `endpoint-id`,
`transport-protocol`, `tag-key` and `tag:<key>` for endpoints; `association-id`,
`target-network-id` and `vpc-id` for target networks; `description`, `destination-cidr` and
`group-id` for authorization rules; `destination-cidr`, `origin` and `target-subnet` for routes.
Any other filter is `InvalidParameterValue` ("The filter '<name>' is invalid").
- An endpoint with the self-service portal enabled reports `selfServicePortalUrl`,
`https://self-service.clientvpn.<dns suffix>/endpoints/<id>`.
- The exported configuration names the endpoint's address, port and transport, carries the server
certificate's chain from ACM as its `<ca>`, and verifies the certificate's domain name, as AWS's
does. A server certificate ACM does not hold leaves those two parts out.
- An unknown endpoint id is `InvalidClientVpnEndpointId.NotFound` ("Endpoint `<id>` does not
exist"), and a malformed one `InvalidParameterValue` ("ClientVpnEndpointId you provided is not
valid").
### EBS Encryption Defaults
| Action | Description |
+1 -1
View File
@@ -86,7 +86,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac
| [Data Firehose](firehose.md) | `POST /` + `X-Amz-Target: Firehose_20150804.*` | JSON 1.1 | 12 |
| [ECS](ecs.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerServiceV20141113.*` | JSON 1.1 | 59 |
| [EFS](efs.md) | `/2015-02-01/...` | REST JSON | 26 |
| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 205 |
| [EC2](ec2.md) | `POST /` with `Action=` param | EC2 Query | 220 |
| [Lightsail](lightsail.md) | `POST /` + `X-Amz-Target: Lightsail_20161128.*` | JSON 1.1 | 79 local responses; 161 recognized actions |
| [ACM](acm.md) | `POST /` + `X-Amz-Target: CertificateManager.*` | JSON 1.1 | 16 |
| [ECR](ecr.md) | `POST /` + `X-Amz-Target: AmazonEC2ContainerRegistry_V20150921.*` (control plane) and `/v2/...` (data plane proxied to `registry:2`) | JSON 1.1 + OCI Distribution | 34 |
@@ -0,0 +1,387 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.ec2.model.ClientVpnEndpoint;
import io.github.hectorvent.floci.services.ec2.model.ClientVpnEndpoint.AuthorizationRule;
import io.github.hectorvent.floci.services.ec2.model.ClientVpnEndpoint.Route;
import io.github.hectorvent.floci.services.ec2.model.ClientVpnEndpoint.TargetNetwork;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiPredicate;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.boolParam;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.booleanResponse;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.endResponse;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.getFiltersList;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.getList;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.intParam;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.startResponse;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.tagSetXml;
/**
* The wire shapes of the Client VPN operations, reached through {@link Ec2QueryHandler}: query
* members as the EC2 protocol names them ({@code Authentication.N}, {@code SecurityGroupId.N}),
* responses as AWS answers them, including the members its responses carry beyond the model
* ({@code routeAction}, {@code IncludeAuthorizationPolicyContext}).
*/
class Ec2ClientVpnHandler {
/** AWS reports an endpoint's creation time without a zone or fraction. */
private static final DateTimeFormatter CREATION_TIME =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss").withZone(ZoneOffset.UTC);
private static final Set<String> ENDPOINT_FILTERS = Set.of("endpoint-id", "transport-protocol", "tag-key");
private static final Set<String> TARGET_NETWORK_FILTERS = Set.of("association-id", "target-network-id", "vpc-id");
private static final Set<String> AUTHORIZATION_RULE_FILTERS = Set.of("description", "destination-cidr", "group-id");
private static final Set<String> ROUTE_FILTERS = Set.of("destination-cidr", "origin", "target-subnet");
private final Ec2ClientVpnService clientVpn;
private final Ec2Service ec2;
Ec2ClientVpnHandler(Ec2ClientVpnService clientVpn, Ec2Service ec2) {
this.clientVpn = clientVpn;
this.ec2 = ec2;
}
Response create(MultivaluedMap<String, String> p, String region, List<Tag> tags) {
Ec2ClientVpnService.EndpointRequest request = new Ec2ClientVpnService.EndpointRequest(
p.getFirst("ClientCidrBlock"), p.getFirst("ServerCertificateArn"), authentication(p),
boolParam(p, "ConnectionLogOptions.Enabled"), p.getFirst("ConnectionLogOptions.CloudwatchLogGroup"),
p.getFirst("ConnectionLogOptions.CloudwatchLogStream"), listOrNull(p, "DnsServers"),
p.getFirst("TransportProtocol"), intParam(p, "VpnPort"), p.getFirst("Description"),
boolParam(p, "SplitTunnel"), getList(p, "SecurityGroupId"), p.getFirst("VpcId"),
p.getFirst("SelfServicePortal"), boolParam(p, "ClientConnectOptions.Enabled"),
p.getFirst("ClientConnectOptions.LambdaFunctionArn"), intParam(p, "SessionTimeoutHours"),
boolParam(p, "ClientLoginBannerOptions.Enabled"), p.getFirst("ClientLoginBannerOptions.BannerText"),
boolParam(p, "ClientRouteEnforcementOptions.Enforced"), boolParam(p, "DisconnectOnSessionTimeout"),
p.getFirst("ClientToken"));
ClientVpnEndpoint endpoint = clientVpn.createEndpoint(region, request, tags);
XmlBuilder xml = startResponse("CreateClientVpnEndpoint")
.elem("clientVpnEndpointId", endpoint.getClientVpnEndpointId())
.start("status").elem("code", Ec2ClientVpnService.statusOf(endpoint)).end("status")
.elem("dnsName", Ec2ClientVpnService.dnsNameOf(endpoint, region));
return endResponse(xml, "CreateClientVpnEndpoint");
}
Response describe(MultivaluedMap<String, String> p, String region) {
List<Map.Entry<String, List<String>>> filters = filters(p, ENDPOINT_FILTERS);
List<ClientVpnEndpoint> endpoints = clientVpn.describeEndpoints(region, getList(p, "ClientVpnEndpointId"));
XmlBuilder xml = startResponse("DescribeClientVpnEndpoints").start("clientVpnEndpoint");
for (ClientVpnEndpoint endpoint : endpoints) {
List<Tag> tags = ec2.resourceTags(region, endpoint.getClientVpnEndpointId());
boolean matches = matches(filters, (name, values) -> switch (name) {
case "endpoint-id" -> Ec2Service.matchesFilterValue(values, endpoint.getClientVpnEndpointId());
case "transport-protocol" -> Ec2Service.matchesFilterValue(values, endpoint.getTransportProtocol());
default -> Ec2Service.matchesTagFilter(tags, name, values, Ec2Service::matchesFilterValue);
});
if (!matches) {
continue;
}
endpoint(xml, endpoint, region);
}
xml.end("clientVpnEndpoint");
return endResponse(xml, "DescribeClientVpnEndpoints");
}
Response modify(MultivaluedMap<String, String> p, String region) {
Ec2ClientVpnService.EndpointChange change = new Ec2ClientVpnService.EndpointChange(
p.getFirst("ServerCertificateArn"), boolParam(p, "ConnectionLogOptions.Enabled"),
p.getFirst("ConnectionLogOptions.CloudwatchLogGroup"),
p.getFirst("ConnectionLogOptions.CloudwatchLogStream"), boolParam(p, "DnsServers.Enabled"),
listOrNull(p, "DnsServers.CustomDnsServers"), intParam(p, "VpnPort"), p.getFirst("Description"),
boolParam(p, "SplitTunnel"), listOrNull(p, "SecurityGroupId"), p.getFirst("VpcId"),
p.getFirst("SelfServicePortal"), boolParam(p, "ClientConnectOptions.Enabled"),
p.getFirst("ClientConnectOptions.LambdaFunctionArn"), intParam(p, "SessionTimeoutHours"),
boolParam(p, "ClientLoginBannerOptions.Enabled"), p.getFirst("ClientLoginBannerOptions.BannerText"),
boolParam(p, "ClientRouteEnforcementOptions.Enforced"), boolParam(p, "DisconnectOnSessionTimeout"));
clientVpn.modifyEndpoint(region, p.getFirst("ClientVpnEndpointId"), change);
return booleanResponse("ModifyClientVpnEndpoint");
}
Response delete(MultivaluedMap<String, String> p, String region) {
clientVpn.deleteEndpoint(region, p.getFirst("ClientVpnEndpointId"));
return endResponse(status(startResponse("DeleteClientVpnEndpoint"), "deleting"), "DeleteClientVpnEndpoint");
}
Response associate(MultivaluedMap<String, String> p, String region) {
TargetNetwork network = clientVpn.associate(region, p.getFirst("ClientVpnEndpointId"),
p.getFirst("SubnetId"), p.getFirst("ClientToken"));
XmlBuilder xml = startResponse("AssociateClientVpnTargetNetwork")
.elem("associationId", network.getAssociationId());
return endResponse(status(xml, "associating"), "AssociateClientVpnTargetNetwork");
}
Response describeTargetNetworks(MultivaluedMap<String, String> p, String region) {
String id = p.getFirst("ClientVpnEndpointId");
List<Map.Entry<String, List<String>>> filters = filters(p, TARGET_NETWORK_FILTERS);
List<TargetNetwork> networks = clientVpn.describeTargetNetworks(region, id, getList(p, "AssociationIds"));
List<String> securityGroups = clientVpn.require(region, id).getSecurityGroupIds();
XmlBuilder xml = startResponse("DescribeClientVpnTargetNetworks").start("clientVpnTargetNetworks");
for (TargetNetwork network : networks) {
boolean matches = matches(filters, (name, values) -> Ec2Service.matchesFilterValue(values,
switch (name) {
case "association-id" -> network.getAssociationId();
case "target-network-id" -> network.getSubnetId();
default -> network.getVpcId();
}));
if (!matches) {
continue;
}
xml.start("item")
.elem("associationId", network.getAssociationId())
.elem("clientVpnEndpointId", id)
.elem("targetNetworkId", network.getSubnetId());
items(xml, "securityGroups", securityGroups);
status(xml, "associated")
.elem("vpcId", network.getVpcId())
.end("item");
}
xml.end("clientVpnTargetNetworks");
return endResponse(xml, "DescribeClientVpnTargetNetworks");
}
Response disassociate(MultivaluedMap<String, String> p, String region) {
TargetNetwork network = clientVpn.disassociate(region, p.getFirst("ClientVpnEndpointId"),
p.getFirst("AssociationId"));
XmlBuilder xml = startResponse("DisassociateClientVpnTargetNetwork")
.elem("associationId", network.getAssociationId());
return endResponse(status(xml, "disassociating"), "DisassociateClientVpnTargetNetwork");
}
Response applySecurityGroups(MultivaluedMap<String, String> p, String region) {
List<String> groups = clientVpn.applySecurityGroups(region, p.getFirst("ClientVpnEndpointId"),
p.getFirst("VpcId"), getList(p, "SecurityGroupId"));
XmlBuilder xml = startResponse("ApplySecurityGroupsToClientVpnTargetNetwork");
items(xml, "securityGroupIds", groups);
return endResponse(xml, "ApplySecurityGroupsToClientVpnTargetNetwork");
}
Response authorize(MultivaluedMap<String, String> p, String region) {
clientVpn.authorize(region, p.getFirst("ClientVpnEndpointId"), p.getFirst("TargetNetworkCidr"),
p.getFirst("AccessGroupId"), boolParam(p, "AuthorizeAllGroups"), p.getFirst("Description"));
return endResponse(status(startResponse("AuthorizeClientVpnIngress"), "authorizing"), "AuthorizeClientVpnIngress");
}
Response describeAuthorizationRules(MultivaluedMap<String, String> p, String region) {
String id = p.getFirst("ClientVpnEndpointId");
List<Map.Entry<String, List<String>>> filters = filters(p, AUTHORIZATION_RULE_FILTERS);
XmlBuilder xml = startResponse("DescribeClientVpnAuthorizationRules").start("authorizationRule");
for (AuthorizationRule rule : clientVpn.describeAuthorizationRules(region, id)) {
boolean matches = matches(filters, (name, values) -> Ec2Service.matchesFilterValue(values,
switch (name) {
case "description" -> rule.getDescription();
case "destination-cidr" -> rule.getDestinationCidr();
default -> rule.getGroupId();
}));
if (!matches) {
continue;
}
xml.start("item")
.elem("accessAll", rule.isAccessAll())
.elem("description", rule.getDescription())
.elem("destinationCidr", rule.getDestinationCidr())
.elem("clientVpnEndpointId", id);
// An empty <groupId/> for a rule that applies to all groups, as AWS answers.
if (rule.getGroupId() == null || rule.getGroupId().isEmpty()) {
xml.raw("<groupId/>");
} else {
xml.elem("groupId", rule.getGroupId());
}
status(xml, "active").end("item");
}
xml.end("authorizationRule");
return endResponse(xml, "DescribeClientVpnAuthorizationRules");
}
Response revoke(MultivaluedMap<String, String> p, String region) {
clientVpn.revoke(region, p.getFirst("ClientVpnEndpointId"), p.getFirst("TargetNetworkCidr"),
p.getFirst("AccessGroupId"), boolParam(p, "RevokeAllGroups"));
return endResponse(status(startResponse("RevokeClientVpnIngress"), "revoking"), "RevokeClientVpnIngress");
}
Response createRoute(MultivaluedMap<String, String> p, String region) {
clientVpn.createRoute(region, p.getFirst("ClientVpnEndpointId"), p.getFirst("DestinationCidrBlock"),
p.getFirst("TargetVpcSubnetId"), p.getFirst("Description"));
return endResponse(status(startResponse("CreateClientVpnRoute"), "creating"), "CreateClientVpnRoute");
}
Response describeRoutes(MultivaluedMap<String, String> p, String region) {
String id = p.getFirst("ClientVpnEndpointId");
List<Map.Entry<String, List<String>>> filters = filters(p, ROUTE_FILTERS);
XmlBuilder xml = startResponse("DescribeClientVpnRoutes").start("routes");
for (Route route : clientVpn.describeRoutes(region, id)) {
boolean matches = matches(filters, (name, values) -> Ec2Service.matchesFilterValue(values,
switch (name) {
case "destination-cidr" -> route.getDestinationCidr();
case "origin" -> route.getOrigin();
default -> route.getTargetSubnet();
}));
if (!matches) {
continue;
}
xml.start("item")
.elem("description", route.getDescription())
.elem("destinationCidr", route.getDestinationCidr())
.elem("clientVpnEndpointId", id)
.elem("origin", route.getOrigin())
.elem("routeAction", "include");
status(xml, "active")
.elem("targetSubnet", route.getTargetSubnet())
.elem("type", "Nat")
.end("item");
}
xml.end("routes");
return endResponse(xml, "DescribeClientVpnRoutes");
}
Response deleteRoute(MultivaluedMap<String, String> p, String region) {
clientVpn.deleteRoute(region, p.getFirst("ClientVpnEndpointId"), p.getFirst("DestinationCidrBlock"),
p.getFirst("TargetVpcSubnetId"));
return endResponse(status(startResponse("DeleteClientVpnRoute"), "deleting"), "DeleteClientVpnRoute");
}
Response exportClientConfiguration(MultivaluedMap<String, String> p, String region) {
String configuration = clientVpn.exportClientConfiguration(region, p.getFirst("ClientVpnEndpointId"));
return endResponse(startResponse("ExportClientVpnClientConfiguration")
.elem("clientConfiguration", configuration), "ExportClientVpnClientConfiguration");
}
/** One endpoint as DescribeClientVpnEndpoints lists it, members in AWS's order. */
private void endpoint(XmlBuilder xml, ClientVpnEndpoint endpoint, String region) {
String id = endpoint.getClientVpnEndpointId();
xml.start("item").start("authenticationOptions");
for (ClientVpnEndpoint.Authentication option : endpoint.getAuthentication()) {
xml.start("item");
if (option.getDirectoryId() != null) {
xml.start("activeDirectory").elem("directoryId", option.getDirectoryId()).end("activeDirectory");
}
if (option.getSamlProviderArn() != null || option.getSelfServiceSamlProviderArn() != null) {
xml.start("federatedAuthentication")
.elem("samlProviderArn", option.getSamlProviderArn())
.elem("selfServiceSamlProviderArn", option.getSelfServiceSamlProviderArn())
.end("federatedAuthentication");
}
if (option.getClientRootCertificateChain() != null) {
xml.start("mutualAuthentication")
.elem("clientRootCertificateChain", option.getClientRootCertificateChain())
.end("mutualAuthentication");
}
xml.elem("type", option.getType()).end("item");
}
xml.end("authenticationOptions")
.elem("clientCidrBlock", endpoint.getClientCidrBlock())
.start("clientConnectOptions")
.elem("enabled", endpoint.isClientConnectEnabled())
.elem("lambdaFunctionArn", endpoint.getClientConnectLambdaFunctionArn())
.start("status").elem("code", "applied").end("status")
.end("clientConnectOptions")
.start("clientLoginBannerOptions")
.elem("enabled", endpoint.isClientLoginBannerEnabled())
.elem("bannerText", endpoint.getClientLoginBannerText())
.end("clientLoginBannerOptions")
.start("clientRouteEnforcementOptions")
.elem("enforced", endpoint.isClientRouteEnforced())
.end("clientRouteEnforcementOptions")
// AWS capitalizes these members on the wire, unlike the rest of the shape.
.start("connectionLogOptions")
.elem("Enabled", endpoint.isConnectionLogEnabled())
.elem("CloudwatchLogGroup", endpoint.getConnectionLogGroup())
.elem("CloudwatchLogStream", endpoint.getConnectionLogStream())
.elem("IncludeAuthorizationPolicyContext", false)
.end("connectionLogOptions")
.elem("creationTime", CREATION_TIME.format(endpoint.getCreationTime()))
.elem("description", endpoint.getDescription())
.elem("disconnectOnSessionTimeout", endpoint.isDisconnectOnSessionTimeout())
.elem("dnsName", Ec2ClientVpnService.dnsNameOf(endpoint, region));
if (!endpoint.getDnsServers().isEmpty()) {
items(xml, "dnsServer", endpoint.getDnsServers());
}
xml.elem("clientVpnEndpointId", id)
.elem("endpointIpAddressType", endpoint.getEndpointIpAddressType());
status(xml, Ec2ClientVpnService.statusOf(endpoint));
items(xml, "securityGroupIdSet", endpoint.getSecurityGroupIds());
// The model reports the portal only as its URL, present while the portal is enabled.
if ("enabled".equals(endpoint.getSelfServicePortal())) {
xml.elem("selfServicePortalUrl", "https://self-service.clientvpn." + AwsRegions.dnsSuffixFor(region)
+ "/endpoints/" + id);
}
xml.elem("serverCertificateArn", endpoint.getServerCertificateArn())
.elem("sessionTimeoutHours", endpoint.getSessionTimeoutHours())
.elem("splitTunnel", endpoint.isSplitTunnel());
xml.raw(tagSetXml(ec2.resourceTags(region, id)));
xml.elem("trafficIpAddressType", endpoint.getTrafficIpAddressType())
.elem("transportProtocol", endpoint.getTransportProtocol())
.elem("vpcId", endpoint.getVpcId())
.elem("vpnPort", endpoint.getVpnPort())
.elem("vpnProtocol", "openvpn")
.end("item");
}
/** {@code Authentication.N.*}, the members CreateClientVpnEndpoint takes its options in. */
private static List<ClientVpnEndpoint.Authentication> authentication(MultivaluedMap<String, String> p) {
List<ClientVpnEndpoint.Authentication> options = new ArrayList<>();
for (int i = 1; ; i++) {
String prefix = "Authentication." + i + ".";
String type = p.getFirst(prefix + "Type");
if (type == null) {
break;
}
if (!List.of("certificate-authentication", "directory-service-authentication",
"federated-authentication").contains(type)) {
throw new AwsException("InvalidParameterValue", "Authentication type " + type + " is not valid.", 400);
}
ClientVpnEndpoint.Authentication option = new ClientVpnEndpoint.Authentication();
option.setType(type);
option.setDirectoryId(p.getFirst(prefix + "ActiveDirectory.DirectoryId"));
option.setClientRootCertificateChain(p.getFirst(prefix + "MutualAuthentication.ClientRootCertificateChainArn"));
option.setSamlProviderArn(p.getFirst(prefix + "FederatedAuthentication.SAMLProviderArn"));
option.setSelfServiceSamlProviderArn(
p.getFirst(prefix + "FederatedAuthentication.SelfServiceSAMLProviderArn"));
options.add(option);
}
return options;
}
/**
* The request's {@code Filter.N} entries, each name one the operation supports (a {@code tag:}
* name where it takes {@code tag-key}); an unsupported name is refused as AWS refuses it.
*/
private static List<Map.Entry<String, List<String>>> filters(MultivaluedMap<String, String> p,
Set<String> supported) {
List<Map.Entry<String, List<String>>> filters = getFiltersList(p);
Ec2Service.requireSupportedFilters(filters.stream().map(Map.Entry::getKey).toList(), supported);
return filters;
}
/** Every filter matches: AND across filters, OR across one filter's values. */
private static boolean matches(List<Map.Entry<String, List<String>>> filters,
BiPredicate<String, List<String>> matcher) {
return filters.stream().allMatch(filter -> matcher.test(filter.getKey(), filter.getValue()));
}
private static XmlBuilder status(XmlBuilder xml, String code) {
return xml.start("status").elem("code", code).end("status");
}
private static void items(XmlBuilder xml, String element, List<String> values) {
xml.start(element);
values.forEach(value -> xml.elem("item", value));
xml.end(element);
}
private static List<String> listOrNull(MultivaluedMap<String, String> p, String prefix) {
List<String> values = getList(p, prefix);
return values.isEmpty() ? null : values;
}
}
@@ -0,0 +1,592 @@
package io.github.hectorvent.floci.services.ec2;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
import io.github.hectorvent.floci.core.common.CidrCanonicalizer;
import io.github.hectorvent.floci.core.storage.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
import io.github.hectorvent.floci.services.acm.AcmService;
import io.github.hectorvent.floci.services.acm.model.Certificate;
import io.github.hectorvent.floci.services.ec2.model.ClientVpnEndpoint;
import io.github.hectorvent.floci.services.ec2.model.ClientVpnEndpoint.AuthorizationRule;
import io.github.hectorvent.floci.services.ec2.model.ClientVpnEndpoint.Route;
import io.github.hectorvent.floci.services.ec2.model.ClientVpnEndpoint.TargetNetwork;
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
import io.github.hectorvent.floci.services.ec2.model.Subnet;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static io.github.hectorvent.floci.services.ec2.Ec2Ids.randomHex;
/**
* EC2 Client VPN: endpoints, their target network associations, authorization rules and routes, and
* the client configuration export. A configuration registry: no VPN server runs, so clients cannot
* connect. Associations, rules and routes settle at once in the state AWS reaches after its
* transitional one.
*
* <p>An endpoint's target networks, authorization rules and routes are replaced, never changed in
* place, so a describe reading them while another request writes sees one whole list or the other.
* An association pins its subnet and VPC, as the network interface AWS places in the subnet does:
* {@code DeleteSubnet} and {@code DeleteVpc} refuse them until it is disassociated.
*/
@ApplicationScoped
public class Ec2ClientVpnService implements VpcDependencyProvider {
static final String ENDPOINT_PREFIX = "cvpn-endpoint-";
private static final String ASSOCIATION_PREFIX = "cvpn-assoc-";
private static final Pattern ENDPOINT_ID = Pattern.compile("cvpn-endpoint-[0-9a-f]{8,17}");
private static final String ORIGIN_ASSOCIATE = "associate";
private static final String ORIGIN_ADD_ROUTE = "add-route";
private static final int DEFAULT_VPN_PORT = 443;
private static final int DEFAULT_SESSION_TIMEOUT_HOURS = 24;
private final StorageBackend<String, ClientVpnEndpoint> endpoints;
private final Ec2Service ec2;
private final AcmService acm;
@Inject
public Ec2ClientVpnService(StorageFactory storageFactory, Ec2Service ec2, AcmService acm) {
this(storageFactory.create("ec2", "ec2-client-vpn-endpoints.json",
new TypeReference<Map<String, ClientVpnEndpoint>>() {}), ec2, acm);
}
Ec2ClientVpnService(StorageBackend<String, ClientVpnEndpoint> endpoints, Ec2Service ec2, AcmService acm) {
this.endpoints = endpoints;
this.ec2 = ec2;
this.acm = acm;
}
/** What CreateClientVpnEndpoint takes; null members take AWS's defaults. */
public record EndpointRequest(String clientCidrBlock, String serverCertificateArn,
List<ClientVpnEndpoint.Authentication> authentication,
Boolean connectionLogEnabled, String connectionLogGroup,
String connectionLogStream, List<String> dnsServers, String transportProtocol,
Integer vpnPort, String description, Boolean splitTunnel,
List<String> securityGroupIds, String vpcId, String selfServicePortal,
Boolean clientConnectEnabled, String clientConnectLambdaFunctionArn,
Integer sessionTimeoutHours, Boolean clientLoginBannerEnabled,
String clientLoginBannerText, Boolean clientRouteEnforced,
Boolean disconnectOnSessionTimeout, String clientToken) {}
// ── Endpoints ──
public synchronized ClientVpnEndpoint createEndpoint(String region, EndpointRequest request, List<Tag> tags) {
if (request.clientToken() != null) {
Optional<ClientVpnEndpoint> replay = all(region).stream()
.filter(endpoint -> request.clientToken().equals(endpoint.getClientToken()))
.findFirst();
if (replay.isPresent()) {
return replay.get();
}
}
if (request.clientCidrBlock() == null || !Ipv4Cidrs.isIpv4(request.clientCidrBlock())) {
throw invalid("ClientCidrBlock must be an IPv4 CIDR block.");
}
if (blank(request.serverCertificateArn())) {
throw missing("ServerCertificateArn");
}
if (request.authentication() == null || request.authentication().isEmpty()) {
throw missing("Authentication");
}
if (request.connectionLogEnabled() == null) {
throw missing("ConnectionLogOptions.Enabled");
}
String transport = Objects.requireNonNullElse(request.transportProtocol(), "udp");
if (!transport.equals("udp") && !transport.equals("tcp")) {
throw invalid("TransportProtocol must be udp or tcp.");
}
List<String> securityGroups = request.securityGroupIds() == null ? List.of() : request.securityGroupIds();
if (!securityGroups.isEmpty() && blank(request.vpcId())) {
throw invalid("VpcId is required when SecurityGroupIds are specified.");
}
String vpcId = request.vpcId();
if (vpcId != null) {
ec2.requireVpc(region, vpcId);
securityGroups = securityGroupsOf(region, vpcId, securityGroups);
}
ClientVpnEndpoint endpoint = new ClientVpnEndpoint();
endpoint.setClientVpnEndpointId(ENDPOINT_PREFIX + randomHex(17));
endpoint.setDescription(request.description());
endpoint.setCreationTime(Instant.now());
endpoint.setClientCidrBlock(request.clientCidrBlock());
endpoint.setServerCertificateArn(request.serverCertificateArn());
endpoint.setAuthentication(new ArrayList<>(request.authentication()));
endpoint.setConnectionLogEnabled(request.connectionLogEnabled());
endpoint.setConnectionLogGroup(request.connectionLogGroup());
endpoint.setConnectionLogStream(request.connectionLogStream());
endpoint.setDnsServers(request.dnsServers() == null ? null : new ArrayList<>(request.dnsServers()));
endpoint.setTransportProtocol(transport);
endpoint.setVpnPort(Objects.requireNonNullElse(request.vpnPort(), DEFAULT_VPN_PORT));
endpoint.setSplitTunnel(Boolean.TRUE.equals(request.splitTunnel()));
endpoint.setVpcId(vpcId);
endpoint.setSecurityGroupIds(new ArrayList<>(securityGroups));
endpoint.setSelfServicePortal(Objects.requireNonNullElse(request.selfServicePortal(), "disabled"));
endpoint.setClientConnectEnabled(Boolean.TRUE.equals(request.clientConnectEnabled()));
endpoint.setClientConnectLambdaFunctionArn(request.clientConnectLambdaFunctionArn());
endpoint.setSessionTimeoutHours(Objects.requireNonNullElse(request.sessionTimeoutHours(),
DEFAULT_SESSION_TIMEOUT_HOURS));
endpoint.setClientLoginBannerEnabled(Boolean.TRUE.equals(request.clientLoginBannerEnabled()));
endpoint.setClientLoginBannerText(request.clientLoginBannerText());
endpoint.setClientRouteEnforced(Boolean.TRUE.equals(request.clientRouteEnforced()));
endpoint.setDisconnectOnSessionTimeout(Boolean.TRUE.equals(request.disconnectOnSessionTimeout()));
endpoint.setEndpointIpAddressType("ipv4");
endpoint.setTrafficIpAddressType("ipv4");
endpoint.setClientToken(request.clientToken());
endpoints.put(key(region, endpoint.getClientVpnEndpointId()), endpoint);
if (tags != null && !tags.isEmpty()) {
ec2.createTags(region, List.of(endpoint.getClientVpnEndpointId()), tags);
}
return endpoint;
}
/** The endpoints the ids name, or all of them; an unknown or malformed id is refused, as AWS does. */
public synchronized List<ClientVpnEndpoint> describeEndpoints(String region, List<String> ids) {
if (ids == null || ids.isEmpty()) {
return all(region);
}
List<ClientVpnEndpoint> found = new ArrayList<>();
for (String id : ids) {
found.add(require(region, id));
}
return found;
}
/** What ModifyClientVpnEndpoint changes; null members are left as they are. */
public record EndpointChange(String serverCertificateArn, Boolean connectionLogEnabled, String connectionLogGroup,
String connectionLogStream, Boolean dnsServersEnabled, List<String> dnsServers,
Integer vpnPort, String description, Boolean splitTunnel,
List<String> securityGroupIds, String vpcId, String selfServicePortal,
Boolean clientConnectEnabled, String clientConnectLambdaFunctionArn,
Integer sessionTimeoutHours, Boolean clientLoginBannerEnabled,
String clientLoginBannerText, Boolean clientRouteEnforced,
Boolean disconnectOnSessionTimeout) {}
public synchronized void modifyEndpoint(String region, String id, EndpointChange change) {
ClientVpnEndpoint endpoint = require(region, id);
String vpcId = change.vpcId() != null ? change.vpcId() : endpoint.getVpcId();
if (change.vpcId() != null && !change.vpcId().equals(endpoint.getVpcId())) {
ec2.requireVpc(region, change.vpcId());
if (!endpoint.getTargetNetworks().isEmpty()) {
throw invalid("The VPC of an endpoint with associated target networks cannot be changed.");
}
}
List<String> securityGroups = null;
if (change.securityGroupIds() != null || change.vpcId() != null) {
if (vpcId == null) {
throw invalid("VpcId is required when SecurityGroupIds are specified.");
}
securityGroups = securityGroupsOf(region, vpcId,
change.securityGroupIds() != null ? change.securityGroupIds() : List.of());
}
if (change.serverCertificateArn() != null) {
endpoint.setServerCertificateArn(change.serverCertificateArn());
}
if (change.connectionLogEnabled() != null) {
endpoint.setConnectionLogEnabled(change.connectionLogEnabled());
endpoint.setConnectionLogGroup(change.connectionLogGroup());
endpoint.setConnectionLogStream(change.connectionLogStream());
}
if (Boolean.FALSE.equals(change.dnsServersEnabled())) {
endpoint.setDnsServers(null);
} else if (change.dnsServers() != null) {
endpoint.setDnsServers(new ArrayList<>(change.dnsServers()));
}
if (change.vpnPort() != null) {
endpoint.setVpnPort(change.vpnPort());
}
if (change.description() != null) {
endpoint.setDescription(change.description());
}
if (change.splitTunnel() != null) {
endpoint.setSplitTunnel(change.splitTunnel());
}
if (securityGroups != null) {
endpoint.setVpcId(vpcId);
endpoint.setSecurityGroupIds(new ArrayList<>(securityGroups));
}
if (change.selfServicePortal() != null) {
endpoint.setSelfServicePortal(change.selfServicePortal());
}
if (change.clientConnectEnabled() != null) {
endpoint.setClientConnectEnabled(change.clientConnectEnabled());
endpoint.setClientConnectLambdaFunctionArn(change.clientConnectLambdaFunctionArn());
}
if (change.sessionTimeoutHours() != null) {
endpoint.setSessionTimeoutHours(change.sessionTimeoutHours());
}
if (change.clientLoginBannerEnabled() != null) {
endpoint.setClientLoginBannerEnabled(change.clientLoginBannerEnabled());
endpoint.setClientLoginBannerText(change.clientLoginBannerText());
}
if (change.clientRouteEnforced() != null) {
endpoint.setClientRouteEnforced(change.clientRouteEnforced());
}
if (change.disconnectOnSessionTimeout() != null) {
endpoint.setDisconnectOnSessionTimeout(change.disconnectOnSessionTimeout());
}
endpoints.put(key(region, id), endpoint);
}
/** Refused while target networks are associated, as AWS requires them disassociated first. */
public synchronized void deleteEndpoint(String region, String id) {
ClientVpnEndpoint endpoint = require(region, id);
if (!endpoint.getTargetNetworks().isEmpty()) {
throw new AwsException("IncorrectState",
"Client VPN endpoint " + id + " has associated target networks; disassociate them first.", 400);
}
endpoints.delete(key(region, id));
ec2.deleteTags(region, List.of(id), List.of());
}
/** {@code pending-associate} until a target network is associated, then {@code available}. */
public static String statusOf(ClientVpnEndpoint endpoint) {
return endpoint.getTargetNetworks().isEmpty() ? "pending-associate" : "available";
}
/** {@code *.cvpn-endpoint-<id>.prod.clientvpn.<region>.<dns suffix>}, as AWS names it. */
public static String dnsNameOf(ClientVpnEndpoint endpoint, String region) {
return "*." + endpoint.getClientVpnEndpointId() + ".prod.clientvpn." + region + "."
+ AwsRegions.dnsSuffixFor(region);
}
// ── Target networks ──
/**
* Associates a subnet of the endpoint's VPC (or, for an endpoint without one, sets the VPC and its
* default security group), one per Availability Zone, and adds the route to the VPC through it.
*/
public synchronized TargetNetwork associate(String region, String id, String subnetId, String clientToken) {
// Held while the subnet is checked and the association saved, so a DeleteSubnet cannot pass its
// dependency check in between.
return ec2.supplyWithSubnetReferencesHeld(region, () -> associateWithSubnetsHeld(region, id, subnetId,
clientToken));
}
private TargetNetwork associateWithSubnetsHeld(String region, String id, String subnetId, String clientToken) {
ClientVpnEndpoint endpoint = require(region, id);
if (clientToken != null) {
Optional<TargetNetwork> replay = endpoint.getTargetNetworks().stream()
.filter(network -> clientToken.equals(network.getClientToken())).findFirst();
if (replay.isPresent()) {
return replay.get();
}
}
if (blank(subnetId)) {
throw missing("SubnetId");
}
Subnet subnet = ec2.requireSubnet(region, subnetId);
if (endpoint.getVpcId() != null && !endpoint.getVpcId().equals(subnet.getVpcId())) {
throw invalid("Subnet " + subnetId + " is not in the endpoint's VPC " + endpoint.getVpcId() + ".");
}
for (TargetNetwork network : endpoint.getTargetNetworks()) {
if (network.getSubnetId().equals(subnetId)) {
throw invalid("Subnet " + subnetId + " is already associated with " + id + ".");
}
if (Objects.equals(network.getAvailabilityZone(), subnet.getAvailabilityZone())) {
throw invalid("A subnet in Availability Zone " + subnet.getAvailabilityZone()
+ " is already associated with " + id + ".");
}
}
if (endpoint.getVpcId() == null) {
endpoint.setVpcId(subnet.getVpcId());
endpoint.setSecurityGroupIds(new ArrayList<>(securityGroupsOf(region, subnet.getVpcId(), List.of())));
}
TargetNetwork network = new TargetNetwork();
network.setAssociationId(ASSOCIATION_PREFIX + randomHex(17));
network.setSubnetId(subnetId);
network.setVpcId(subnet.getVpcId());
network.setAvailabilityZone(subnet.getAvailabilityZone());
network.setClientToken(clientToken);
endpoint.setTargetNetworks(with(endpoint.getTargetNetworks(), network));
Route route = new Route();
route.setDestinationCidr(ec2.requireVpc(region, subnet.getVpcId()).getCidrBlock());
route.setTargetSubnet(subnetId);
route.setOrigin(ORIGIN_ASSOCIATE);
route.setDescription("Default Route");
endpoint.setRoutes(with(endpoint.getRoutes(), route));
endpoints.put(key(region, id), endpoint);
return network;
}
public synchronized List<TargetNetwork> describeTargetNetworks(String region, String id, List<String> associationIds) {
ClientVpnEndpoint endpoint = require(region, id);
if (associationIds == null || associationIds.isEmpty()) {
return endpoint.getTargetNetworks();
}
return endpoint.getTargetNetworks().stream()
.filter(network -> associationIds.contains(network.getAssociationId())).toList();
}
/** Removes the association and every route through its subnet. */
public synchronized TargetNetwork disassociate(String region, String id, String associationId) {
ClientVpnEndpoint endpoint = require(region, id);
TargetNetwork network = endpoint.getTargetNetworks().stream()
.filter(candidate -> candidate.getAssociationId().equals(associationId)).findFirst()
.orElseThrow(() -> new AwsException("InvalidClientVpnAssociationId.NotFound",
"Association " + associationId + " does not exist", 400));
endpoint.setTargetNetworks(without(endpoint.getTargetNetworks(), candidate -> candidate == network));
endpoint.setRoutes(without(endpoint.getRoutes(),
route -> network.getSubnetId().equals(route.getTargetSubnet())));
endpoints.put(key(region, id), endpoint);
return network;
}
/** Sets the security groups the endpoint applies in its VPC, for every associated network. */
public synchronized List<String> applySecurityGroups(String region, String id, String vpcId,
List<String> securityGroupIds) {
ClientVpnEndpoint endpoint = require(region, id);
if (blank(vpcId)) {
throw missing("VpcId");
}
if (securityGroupIds == null || securityGroupIds.isEmpty()) {
throw missing("SecurityGroupId");
}
if (endpoint.getVpcId() != null && !endpoint.getVpcId().equals(vpcId)) {
throw invalid("VPC " + vpcId + " is not the endpoint's VPC " + endpoint.getVpcId() + ".");
}
List<String> groups = securityGroupsOf(region, vpcId, securityGroupIds);
endpoint.setVpcId(vpcId);
endpoint.setSecurityGroupIds(new ArrayList<>(groups));
endpoints.put(key(region, id), endpoint);
return groups;
}
// ── Authorization rules ──
public synchronized void authorize(String region, String id, String targetNetworkCidr, String accessGroupId,
Boolean authorizeAllGroups, String description) {
ClientVpnEndpoint endpoint = require(region, id);
requireCidr(targetNetworkCidr, "TargetNetworkCidr");
boolean all = Boolean.TRUE.equals(authorizeAllGroups);
if (all == !blank(accessGroupId)) {
throw invalid("Specify either AccessGroupId or AuthorizeAllGroups.");
}
boolean exists = endpoint.getAuthorizationRules().stream()
.anyMatch(rule -> CidrCanonicalizer.sameBlock(rule.getDestinationCidr(), targetNetworkCidr)
&& rule.isAccessAll() == all && Objects.equals(rule.getGroupId(), all ? "" : accessGroupId));
if (exists) {
throw invalid("An authorization rule for " + targetNetworkCidr + " already exists.");
}
AuthorizationRule rule = new AuthorizationRule();
rule.setDestinationCidr(targetNetworkCidr);
rule.setGroupId(all ? "" : accessGroupId);
rule.setAccessAll(all);
rule.setDescription(description);
endpoint.setAuthorizationRules(with(endpoint.getAuthorizationRules(), rule));
endpoints.put(key(region, id), endpoint);
}
public synchronized List<AuthorizationRule> describeAuthorizationRules(String region, String id) {
return require(region, id).getAuthorizationRules();
}
public synchronized void revoke(String region, String id, String targetNetworkCidr, String accessGroupId,
Boolean revokeAllGroups) {
ClientVpnEndpoint endpoint = require(region, id);
requireCidr(targetNetworkCidr, "TargetNetworkCidr");
boolean all = Boolean.TRUE.equals(revokeAllGroups);
List<AuthorizationRule> kept = without(endpoint.getAuthorizationRules(), rule ->
CidrCanonicalizer.sameBlock(rule.getDestinationCidr(), targetNetworkCidr)
&& (all ? rule.isAccessAll() : Objects.equals(rule.getGroupId(), accessGroupId)));
if (kept.size() == endpoint.getAuthorizationRules().size()) {
throw new AwsException("InvalidClientVpnEndpointAuthorizationRuleNotFound",
"Authorization rule for " + targetNetworkCidr + " does not exist", 400);
}
endpoint.setAuthorizationRules(kept);
endpoints.put(key(region, id), endpoint);
}
// ── Routes ──
/** Adds a route through an associated subnet, or {@code local}. */
public synchronized void createRoute(String region, String id, String destinationCidr, String targetSubnet,
String description) {
ClientVpnEndpoint endpoint = require(region, id);
requireCidr(destinationCidr, "DestinationCidrBlock");
if (blank(targetSubnet)) {
throw missing("TargetVpcSubnetId");
}
boolean associated = "local".equals(targetSubnet) || endpoint.getTargetNetworks().stream()
.anyMatch(network -> network.getSubnetId().equals(targetSubnet));
if (!associated) {
throw invalid("Subnet " + targetSubnet + " is not associated with " + id + ".");
}
boolean exists = endpoint.getRoutes().stream()
.anyMatch(route -> CidrCanonicalizer.sameBlock(route.getDestinationCidr(), destinationCidr)
&& route.getTargetSubnet().equals(targetSubnet));
if (exists) {
throw new AwsException("InvalidClientVpnDuplicateRoute",
"Route " + destinationCidr + " through " + targetSubnet + " already exists", 400);
}
Route route = new Route();
route.setDestinationCidr(destinationCidr);
route.setTargetSubnet(targetSubnet);
route.setOrigin(ORIGIN_ADD_ROUTE);
route.setDescription(description);
endpoint.setRoutes(with(endpoint.getRoutes(), route));
endpoints.put(key(region, id), endpoint);
}
public synchronized List<Route> describeRoutes(String region, String id) {
return require(region, id).getRoutes();
}
/** Removes the matching routes; a route an association added goes with the association only. */
public synchronized void deleteRoute(String region, String id, String destinationCidr, String targetSubnet) {
ClientVpnEndpoint endpoint = require(region, id);
requireCidr(destinationCidr, "DestinationCidrBlock");
List<Route> kept = without(endpoint.getRoutes(), route -> ORIGIN_ADD_ROUTE.equals(route.getOrigin())
&& CidrCanonicalizer.sameBlock(route.getDestinationCidr(), destinationCidr)
&& (targetSubnet == null || route.getTargetSubnet().equals(targetSubnet)));
if (kept.size() == endpoint.getRoutes().size()) {
throw new AwsException("InvalidClientVpnRouteNotFound",
"Route " + destinationCidr + " does not exist", 400);
}
endpoint.setRoutes(kept);
endpoints.put(key(region, id), endpoint);
}
// ── Client configuration ──
/**
* The OpenVPN configuration AWS exports: the endpoint's address and port, its transport, the
* server certificate's chain as the CA, and its common name to verify. The chain and name come
* from the server certificate in ACM; a certificate ACM does not hold leaves them out.
*/
public String exportClientConfiguration(String region, String id) {
ClientVpnEndpoint endpoint = require(region, id);
Optional<Certificate> certificate = serverCertificate(endpoint, region);
StringBuilder config = new StringBuilder()
.append("client\n")
.append("dev tun\n")
.append("proto ").append(endpoint.getTransportProtocol()).append('\n')
.append("remote ").append(dnsNameOf(endpoint, region).substring(2)).append(' ')
.append(endpoint.getVpnPort()).append('\n')
.append("remote-random-hostname\n")
.append("resolv-retry infinite\n")
.append("nobind\n")
.append("remote-cert-tls server\n")
.append("cipher AES-256-GCM\n")
.append("verb 3\n");
certificate.map(Certificate::getCertificateChain).filter(chain -> !chain.isBlank())
.ifPresent(chain -> config.append("<ca>\n").append(chain.strip()).append("\n\n</ca>\n\n\n"));
config.append("reneg-sec 0\n\n");
certificate.map(Certificate::getDomainName).filter(name -> !name.isBlank())
.ifPresent(name -> config.append("verify-x509-name ").append(name).append(" name\n\n"));
return config.toString();
}
private Optional<Certificate> serverCertificate(ClientVpnEndpoint endpoint, String region) {
try {
return Optional.ofNullable(acm.getCertificate(endpoint.getServerCertificateArn(), region));
} catch (AwsException expected) {
// A certificate ACM does not hold: the export goes without the CA. Anything else surfaces.
if (!"ResourceNotFoundException".equals(expected.getErrorCode())) {
throw expected;
}
return Optional.empty();
}
}
// ── Helpers ──
/** The endpoint an id names: AWS's error for a malformed id and for an unknown one. */
public ClientVpnEndpoint require(String region, String id) {
if (id == null || !ENDPOINT_ID.matcher(id).matches()) {
throw invalid("ClientVpnEndpointId you provided is not valid");
}
return endpoints.get(key(region, id)).orElseThrow(() -> new AwsException(
"InvalidClientVpnEndpointId.NotFound", "Endpoint " + id + " does not exist", 400));
}
/** The groups given, each of the VPC; none given means the VPC's default security group. */
private List<String> securityGroupsOf(String region, String vpcId, List<String> requested) {
if (requested.isEmpty()) {
return ec2.defaultSecurityGroupOf(region, vpcId).map(SecurityGroup::getGroupId)
.map(List::of).orElse(List.of());
}
List<SecurityGroup> found = ec2.describeSecurityGroups(region, requested, List.of(), Map.of());
for (String groupId : requested) {
SecurityGroup group = found.stream().filter(candidate -> groupId.equals(candidate.getGroupId()))
.findFirst().orElseThrow(() -> new AwsException("InvalidGroup.NotFound",
"The security group '" + groupId + "' does not exist", 400));
if (!vpcId.equals(group.getVpcId())) {
throw invalid("Security group " + groupId + " is not in VPC " + vpcId + ".");
}
}
return List.copyOf(requested);
}
// ── Subnet and VPC references ──
/** A plain read over the stored endpoints, taking no lock of this service, as the interface requires. */
@Override
public boolean hasSubnetDependency(String region, String subnetId) {
return associations(region).anyMatch(network -> subnetId.equals(network.getSubnetId()));
}
@Override
public boolean hasVpcDependency(String region, String vpcId) {
return associations(region).anyMatch(network -> vpcId.equals(network.getVpcId()));
}
private Stream<TargetNetwork> associations(String region) {
return endpoints.scan(key -> key.startsWith(region + "::")).stream()
.flatMap(endpoint -> endpoint.getTargetNetworks().stream());
}
private static <T> List<T> with(List<T> list, T item) {
List<T> copy = new ArrayList<>(list);
copy.add(item);
return copy;
}
private static <T> List<T> without(List<T> list, Predicate<T> drop) {
return new ArrayList<>(list.stream().filter(drop.negate()).toList());
}
private List<ClientVpnEndpoint> all(String region) {
return endpoints.scan(key -> key.startsWith(region + "::")).stream()
.sorted(Comparator.comparing(ClientVpnEndpoint::getClientVpnEndpointId)).toList();
}
private static void requireCidr(String cidr, String member) {
if (blank(cidr)) {
throw missing(member);
}
if (!Ipv4Cidrs.isIpv4(cidr)) {
throw invalid(member + " must be an IPv4 CIDR block.");
}
}
private static boolean blank(String value) {
return value == null || value.isBlank();
}
private static AwsException invalid(String message) {
return new AwsException("InvalidParameterValue", message, 400);
}
private static AwsException missing(String member) {
return new AwsException("MissingParameter", "The request must contain the parameter " + member, 400);
}
private static String key(String region, String id) {
return region + "::" + id;
}
}
@@ -0,0 +1,22 @@
package io.github.hectorvent.floci.services.ec2;
import java.util.concurrent.ThreadLocalRandom;
/** The random parts of the resource ids EC2 mints. */
final class Ec2Ids {
private static final String HEX = "0123456789abcdef";
private Ec2Ids() {
}
/** {@code length} lowercase hex digits, as the suffix of an id like {@code subnet-0a1b2c3d}. */
static String randomHex(int length) {
StringBuilder sb = new StringBuilder(length);
ThreadLocalRandom random = ThreadLocalRandom.current();
for (int i = 0; i < length; i++) {
sb.append(HEX.charAt(random.nextInt(HEX.length())));
}
return sb.toString();
}
}
@@ -33,6 +33,8 @@ import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static io.github.hectorvent.floci.services.ec2.Ec2Ids.randomHex;
/**
* Amazon VPC IP Address Manager (IPAM) emulation: organization admin
* delegation, IPAMs with default scopes, hierarchical pools with provisioned
@@ -1004,13 +1006,4 @@ public class Ec2IpamService {
return region + "|" + id;
}
private static String randomHex(int len) {
String chars = "0123456789abcdef";
StringBuilder sb = new StringBuilder(len);
ThreadLocalRandom r = ThreadLocalRandom.current();
for (int i = 0; i < len; i++) {
sb.append(chars.charAt(r.nextInt(chars.length())));
}
return sb.toString();
}
}
@@ -26,6 +26,14 @@ import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Consumer;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.boolParam;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.booleanResponse;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.getFiltersList;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.getList;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.intParam;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.tagSetXml;
import static io.github.hectorvent.floci.services.ec2.Ec2QueryProtocol.xmlResponse;
@ApplicationScoped
public class Ec2QueryHandler {
@@ -55,12 +63,14 @@ public class Ec2QueryHandler {
private final Ec2BlockPublicAccessService blockPublicAccessService;
private final Ec2IpamService ipamService;
private final RegionResolver regionResolver;
private final Ec2ClientVpnHandler clientVpnHandler;
@Inject
public Ec2QueryHandler(Ec2Service service, EmulatorConfig config, FlowLogService flowLogService,
Ec2EbsEncryptionService ebsEncryptionService,
Ec2BlockPublicAccessService blockPublicAccessService,
Ec2IpamService ipamService, RegionResolver regionResolver) {
Ec2IpamService ipamService, RegionResolver regionResolver,
Ec2ClientVpnService clientVpnService) {
this.service = service;
this.config = config;
this.flowLogService = flowLogService;
@@ -68,6 +78,16 @@ public class Ec2QueryHandler {
this.blockPublicAccessService = blockPublicAccessService;
this.ipamService = ipamService;
this.regionResolver = regionResolver;
this.clientVpnHandler = clientVpnService == null ? null : new Ec2ClientVpnHandler(clientVpnService, service);
}
/** For unit tests that exercise no Client VPN operation. */
public Ec2QueryHandler(Ec2Service service, EmulatorConfig config, FlowLogService flowLogService,
Ec2EbsEncryptionService ebsEncryptionService,
Ec2BlockPublicAccessService blockPublicAccessService,
Ec2IpamService ipamService, RegionResolver regionResolver) {
this(service, config, flowLogService, ebsEncryptionService, blockPublicAccessService, ipamService,
regionResolver, null);
}
public Response handle(String action, MultivaluedMap<String, String> params, String region) {
@@ -129,6 +149,26 @@ public class Ec2QueryHandler {
case "CreateFlowLogs" -> handleCreateFlowLogs(params, region);
case "DescribeFlowLogs" -> handleDescribeFlowLogs(params, region);
case "DeleteFlowLogs" -> handleDeleteFlowLogs(params, region);
// Client VPN
case "CreateClientVpnEndpoint" -> clientVpnHandler.create(params, region,
parseTagsForResource(params, "client-vpn-endpoint"));
case "DescribeClientVpnEndpoints" -> clientVpnHandler.describe(params, region);
case "ModifyClientVpnEndpoint" -> clientVpnHandler.modify(params, region);
case "DeleteClientVpnEndpoint" -> clientVpnHandler.delete(params, region);
case "AssociateClientVpnTargetNetwork" -> clientVpnHandler.associate(params, region);
case "DescribeClientVpnTargetNetworks" -> clientVpnHandler.describeTargetNetworks(params, region);
case "DisassociateClientVpnTargetNetwork" -> clientVpnHandler.disassociate(params, region);
case "ApplySecurityGroupsToClientVpnTargetNetwork" ->
clientVpnHandler.applySecurityGroups(params, region);
case "AuthorizeClientVpnIngress" -> clientVpnHandler.authorize(params, region);
case "DescribeClientVpnAuthorizationRules" ->
clientVpnHandler.describeAuthorizationRules(params, region);
case "RevokeClientVpnIngress" -> clientVpnHandler.revoke(params, region);
case "CreateClientVpnRoute" -> clientVpnHandler.createRoute(params, region);
case "DescribeClientVpnRoutes" -> clientVpnHandler.describeRoutes(params, region);
case "DeleteClientVpnRoute" -> clientVpnHandler.deleteRoute(params, region);
case "ExportClientVpnClientConfiguration" ->
clientVpnHandler.exportClientConfiguration(params, region);
case "DescribePrefixLists" -> handleDescribePrefixLists(params, region);
case "CreateManagedPrefixList" -> handleCreateManagedPrefixList(params, region);
case "DescribeManagedPrefixLists" -> handleDescribeManagedPrefixLists(params, region);
@@ -364,24 +404,6 @@ public class Ec2QueryHandler {
// ─── Parameter helpers ────────────────────────────────────────────────────
private List<String> getList(MultivaluedMap<String, String> p, String prefix) {
List<String> result = new ArrayList<>();
for (int i = 1; ; i++) {
String v = p.getFirst(prefix + "." + i);
if (v == null) break;
result.add(v);
}
return result;
}
private List<String> getList(MultivaluedMap<String, String> p, String... prefixes) {
List<String> result = new ArrayList<>();
for (String prefix : prefixes) {
result.addAll(getList(p, prefix));
}
return result;
}
private String firstPresent(MultivaluedMap<String, String> p, String first, String second) {
String value = p.getFirst(first);
return value != null && !value.isBlank() ? value : p.getFirst(second);
@@ -409,26 +431,6 @@ public class Ec2QueryHandler {
}
}
/**
* Returns filters as a list of entries to preserve multiple filters with the same name
* (AND semantics across filters, OR within values of the same filter).
*/
private List<Map.Entry<String, List<String>>> getFiltersList(MultivaluedMap<String, String> p) {
List<Map.Entry<String, List<String>>> filters = new ArrayList<>();
for (int i = 1; ; i++) {
String name = p.getFirst("Filter." + i + ".Name");
if (name == null) break;
List<String> values = new ArrayList<>();
for (int j = 1; ; j++) {
String v = p.getFirst("Filter." + i + ".Value." + j);
if (v == null) break;
values.add(v);
}
filters.add(new AbstractMap.SimpleEntry<>(name, values));
}
return filters;
}
private List<BlockDeviceMapping> parseBlockDeviceMappings(MultivaluedMap<String, String> p) {
List<BlockDeviceMapping> mappings = new ArrayList<>();
for (int i = 1; ; i++) {
@@ -788,20 +790,6 @@ public class Ec2QueryHandler {
return xmlResponse(xml.build());
}
private Response xmlResponse(String xml) {
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
private Response booleanResponse(String action) {
String xml = new XmlBuilder()
.start(action + "Response", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.elem("return", "true")
.end(action + "Response")
.build();
return xmlResponse(xml);
}
// ─── Instance handlers ────────────────────────────────────────────────────
private Response handleRunInstances(MultivaluedMap<String, String> p, String region) {
@@ -6350,23 +6338,6 @@ public class Ec2QueryHandler {
return value != null && !value.isBlank();
}
private Boolean boolParam(MultivaluedMap<String, String> p, String name) {
String value = p.getFirst(name);
return isSet(value) ? Boolean.valueOf(Boolean.parseBoolean(value)) : null;
}
private Integer intParam(MultivaluedMap<String, String> p, String name) {
String value = p.getFirst(name);
if (!isSet(value)) {
return null;
}
try {
return Integer.valueOf(value);
} catch (NumberFormatException e) {
throw new AwsException("InvalidParameterValue", name + " is not a valid integer.", 400);
}
}
private Double doubleParam(MultivaluedMap<String, String> p, String name) {
String value = p.getFirst(name);
if (!isSet(value)) {
@@ -6456,21 +6427,6 @@ public class Ec2QueryHandler {
return xml.build();
}
private String tagSetXml(List<Tag> tagList) {
if (tagList == null || tagList.isEmpty()) {
return "<tagSet/>";
}
XmlBuilder xml = new XmlBuilder().start("tagSet");
for (Tag tag : tagList) {
xml.start("item")
.elem("key", tag.getKey())
.elem("value", tag.getValue())
.end("item");
}
xml.end("tagSet");
return xml.build();
}
private String blockDeviceMappingXml(List<BlockDeviceMapping> mappings) {
if (mappings == null || mappings.isEmpty()) {
return "<blockDeviceMapping/>";
@@ -0,0 +1,123 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* The EC2 Query protocol's parameter and response shapes, shared by the handlers that serve EC2
* actions: numbered members ({@code Name.1}, {@code Name.2}), {@code Filter.N} entries, optional
* booleans and integers, the {@code tagSet} element and the response envelope.
*/
final class Ec2QueryProtocol {
private Ec2QueryProtocol() {
}
/** The values of {@code prefix.1}, {@code prefix.2}, ... up to the first one missing. */
static List<String> getList(MultivaluedMap<String, String> p, String prefix) {
List<String> result = new ArrayList<>();
for (int i = 1; ; i++) {
String v = p.getFirst(prefix + "." + i);
if (v == null) {
break;
}
result.add(v);
}
return result;
}
/** The numbered values of each prefix in turn. */
static List<String> getList(MultivaluedMap<String, String> p, String... prefixes) {
List<String> result = new ArrayList<>();
for (String prefix : prefixes) {
result.addAll(getList(p, prefix));
}
return result;
}
/**
* Returns filters as a list of entries to preserve multiple filters with the same name
* (AND semantics across filters, OR within values of the same filter).
*/
static List<Map.Entry<String, List<String>>> getFiltersList(MultivaluedMap<String, String> p) {
List<Map.Entry<String, List<String>>> filters = new ArrayList<>();
for (int i = 1; ; i++) {
String name = p.getFirst("Filter." + i + ".Name");
if (name == null) {
break;
}
filters.add(new AbstractMap.SimpleEntry<>(name, getList(p, "Filter." + i + ".Value")));
}
return filters;
}
/** The boolean member, or null when it is absent or blank. */
static Boolean boolParam(MultivaluedMap<String, String> p, String name) {
String value = p.getFirst(name);
return isSet(value) ? Boolean.valueOf(Boolean.parseBoolean(value)) : null;
}
/** The integer member, or null when it is absent or blank; anything else is refused. */
static Integer intParam(MultivaluedMap<String, String> p, String name) {
String value = p.getFirst(name);
if (!isSet(value)) {
return null;
}
try {
return Integer.valueOf(value);
} catch (NumberFormatException e) {
throw new AwsException("InvalidParameterValue", name + " is not a valid integer.", 400);
}
}
/** A resource's tags as the {@code tagSet} element, {@code <tagSet/>} when it has none. */
static String tagSetXml(List<Tag> tagList) {
if (tagList == null || tagList.isEmpty()) {
return "<tagSet/>";
}
XmlBuilder xml = new XmlBuilder().start("tagSet");
for (Tag tag : tagList) {
xml.start("item")
.elem("key", tag.getKey())
.elem("value", tag.getValue())
.end("item");
}
xml.end("tagSet");
return xml.build();
}
/** {@code <ActionResponse>} opened in the EC2 namespace, with its request id. */
static XmlBuilder startResponse(String action) {
return new XmlBuilder().start(action + "Response", AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString());
}
/** Closes the response {@link #startResponse} opened and answers with it. */
static Response endResponse(XmlBuilder xml, String action) {
return xmlResponse(xml.end(action + "Response").build());
}
static Response xmlResponse(String xml) {
return Response.ok(xml).type(MediaType.APPLICATION_XML).build();
}
/** The response of an action that answers only {@code <return>true</return>}. */
static Response booleanResponse(String action) {
return endResponse(startResponse(action).elem("return", "true"), action);
}
private static boolean isSet(String value) {
return value != null && !value.isBlank();
}
}
@@ -156,6 +156,8 @@ import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static io.github.hectorvent.floci.services.ec2.Ec2Ids.randomHex;
@ApplicationScoped
public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettable {
@@ -173,7 +175,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
// An EC2 id is a known resource prefix, a hyphen and either 8 or more hex digits (8, 17, or 33
// for an IPAM pool allocation) or a UUID (EC2 Fleet and Spot Fleet requests). Longer prefixes
// come first so that eni-attach- is read as one type, not as eni-.
private static final String TAGGABLE_RESOURCE_TYPES = "(subnet-cidr-assoc|vpc-cidr-assoc"
private static final String TAGGABLE_RESOURCE_TYPES = "(cvpn-endpoint|subnet-cidr-assoc|vpc-cidr-assoc"
+ "|ipam-pool-alloc|ipam-scope|ipam-pool|ipam"
+ "|traf-mir-fil|traf-mir-tar|iip-assoc|eni-attach|tgw-attach|tgw-rtb|vpce-svc|aclassoc|eipassoc"
+ "|eipalloc|rtbassoc|subnet|fleet|cagw|dopt|eigw|snap|vpce|acl|ami|cgw|eni|igw|key|nat|pcx|rtb|scr"
@@ -2214,15 +2216,6 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return resourceLocks[Math.max(stripeOf(keyA), stripeOf(keyB))];
}
private String randomHex(int len) {
StringBuilder sb = new StringBuilder(len);
Random rand = new Random();
for (int i = 0; i < len; i++) {
sb.append(Integer.toHexString(rand.nextInt(16)));
}
return sb.toString();
}
/** Synthesizes a locally-administered unicast MAC (AWS never discloses how it derives its own). */
private String randomMac() {
Random rand = new Random();
@@ -7003,7 +6996,6 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
.collect(Collectors.toList());
}
public List<VpcEndpoint> deleteVpcEndpoints(String region, List<String> endpointIds) {
ensureDefaultResources(region);
List<VpcEndpoint> deleted = new ArrayList<>();
@@ -12155,7 +12147,6 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return findAnyVpcEntry(region, vpcId).map(AccountAwareStorageBackend.OwnedEntry::account);
}
public List<VpcPeeringConnection> describeVpcPeeringConnections(String region, List<String> ids,
Map<String, List<String>> filters) {
return describeVpcPeeringConnections(region, ids, filterList(filters));
@@ -39,6 +39,8 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import static io.github.hectorvent.floci.services.ec2.Ec2Ids.randomHex;
/**
* Manages VPC Flow Logs (a floci addition — absent upstream) and a background
* generator that synthesizes realistic VPC flow-log records and delivers them
@@ -649,16 +651,6 @@ public class FlowLogService {
return (s == null || s.isEmpty()) ? "-" : s;
}
private static String randomHex(int len) {
String chars = "0123456789abcdef";
StringBuilder sb = new StringBuilder(len);
ThreadLocalRandom r = ThreadLocalRandom.current();
for (int i = 0; i < len; i++) {
sb.append(chars.charAt(r.nextInt(chars.length())));
}
return sb.toString();
}
/** Lightweight holder for the ENI fields a flow record needs. */
private static final class Eni {
String eniId;
@@ -0,0 +1,194 @@
package io.github.hectorvent.floci.services.ec2.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
/**
* A Client VPN endpoint with its target network associations, authorization rules and routes,
* stored together so a change to any of them is one write.
*/
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public class ClientVpnEndpoint {
/** One entry of {@code authenticationOptions}. */
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Authentication {
private String type;
private String directoryId;
private String clientRootCertificateChain;
private String samlProviderArn;
private String selfServiceSamlProviderArn;
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public String getDirectoryId() { return directoryId; }
public void setDirectoryId(String directoryId) { this.directoryId = directoryId; }
public String getClientRootCertificateChain() { return clientRootCertificateChain; }
public void setClientRootCertificateChain(String arn) { this.clientRootCertificateChain = arn; }
public String getSamlProviderArn() { return samlProviderArn; }
public void setSamlProviderArn(String arn) { this.samlProviderArn = arn; }
public String getSelfServiceSamlProviderArn() { return selfServiceSamlProviderArn; }
public void setSelfServiceSamlProviderArn(String arn) { this.selfServiceSamlProviderArn = arn; }
}
/** A subnet the endpoint is associated with. */
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class TargetNetwork {
private String associationId;
private String subnetId;
private String vpcId;
private String availabilityZone;
private String clientToken;
public String getAssociationId() { return associationId; }
public void setAssociationId(String associationId) { this.associationId = associationId; }
public String getSubnetId() { return subnetId; }
public void setSubnetId(String subnetId) { this.subnetId = subnetId; }
public String getVpcId() { return vpcId; }
public void setVpcId(String vpcId) { this.vpcId = vpcId; }
public String getAvailabilityZone() { return availabilityZone; }
public void setAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; }
public String getClientToken() { return clientToken; }
public void setClientToken(String clientToken) { this.clientToken = clientToken; }
}
/** A network clients may reach, for all groups or one. */
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class AuthorizationRule {
private String destinationCidr;
private String groupId;
private boolean accessAll;
private String description;
public String getDestinationCidr() { return destinationCidr; }
public void setDestinationCidr(String destinationCidr) { this.destinationCidr = destinationCidr; }
public String getGroupId() { return groupId; }
public void setGroupId(String groupId) { this.groupId = groupId; }
public boolean isAccessAll() { return accessAll; }
public void setAccessAll(boolean accessAll) { this.accessAll = accessAll; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
}
/** A route in the endpoint's route table; {@code origin} is {@code associate} or {@code add-route}. */
@RegisterForReflection
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Route {
private String destinationCidr;
private String targetSubnet;
private String origin;
private String description;
public String getDestinationCidr() { return destinationCidr; }
public void setDestinationCidr(String destinationCidr) { this.destinationCidr = destinationCidr; }
public String getTargetSubnet() { return targetSubnet; }
public void setTargetSubnet(String targetSubnet) { this.targetSubnet = targetSubnet; }
public String getOrigin() { return origin; }
public void setOrigin(String origin) { this.origin = origin; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
}
private String clientVpnEndpointId;
private String description;
private Instant creationTime;
private String clientCidrBlock;
private List<String> dnsServers = new ArrayList<>();
private boolean splitTunnel;
private String transportProtocol;
private int vpnPort;
private String serverCertificateArn;
private List<Authentication> authentication = new ArrayList<>();
private boolean connectionLogEnabled;
private String connectionLogGroup;
private String connectionLogStream;
private List<String> securityGroupIds = new ArrayList<>();
private String vpcId;
private String selfServicePortal;
private boolean clientConnectEnabled;
private String clientConnectLambdaFunctionArn;
private int sessionTimeoutHours;
private boolean clientLoginBannerEnabled;
private String clientLoginBannerText;
private boolean clientRouteEnforced;
private boolean disconnectOnSessionTimeout;
private String endpointIpAddressType;
private String trafficIpAddressType;
private String clientToken;
private List<TargetNetwork> targetNetworks = new ArrayList<>();
private List<AuthorizationRule> authorizationRules = new ArrayList<>();
private List<Route> routes = new ArrayList<>();
public String getClientVpnEndpointId() { return clientVpnEndpointId; }
public void setClientVpnEndpointId(String id) { this.clientVpnEndpointId = id; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
public Instant getCreationTime() { return creationTime; }
public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; }
public String getClientCidrBlock() { return clientCidrBlock; }
public void setClientCidrBlock(String clientCidrBlock) { this.clientCidrBlock = clientCidrBlock; }
public List<String> getDnsServers() { return dnsServers; }
public void setDnsServers(List<String> dnsServers) { this.dnsServers = dnsServers != null ? dnsServers : new ArrayList<>(); }
public boolean isSplitTunnel() { return splitTunnel; }
public void setSplitTunnel(boolean splitTunnel) { this.splitTunnel = splitTunnel; }
public String getTransportProtocol() { return transportProtocol; }
public void setTransportProtocol(String transportProtocol) { this.transportProtocol = transportProtocol; }
public int getVpnPort() { return vpnPort; }
public void setVpnPort(int vpnPort) { this.vpnPort = vpnPort; }
public String getServerCertificateArn() { return serverCertificateArn; }
public void setServerCertificateArn(String arn) { this.serverCertificateArn = arn; }
public List<Authentication> getAuthentication() { return authentication; }
public void setAuthentication(List<Authentication> authentication) {
this.authentication = authentication != null ? authentication : new ArrayList<>();
}
public boolean isConnectionLogEnabled() { return connectionLogEnabled; }
public void setConnectionLogEnabled(boolean enabled) { this.connectionLogEnabled = enabled; }
public String getConnectionLogGroup() { return connectionLogGroup; }
public void setConnectionLogGroup(String group) { this.connectionLogGroup = group; }
public String getConnectionLogStream() { return connectionLogStream; }
public void setConnectionLogStream(String stream) { this.connectionLogStream = stream; }
public List<String> getSecurityGroupIds() { return securityGroupIds; }
public void setSecurityGroupIds(List<String> ids) { this.securityGroupIds = ids != null ? ids : new ArrayList<>(); }
public String getVpcId() { return vpcId; }
public void setVpcId(String vpcId) { this.vpcId = vpcId; }
public String getSelfServicePortal() { return selfServicePortal; }
public void setSelfServicePortal(String selfServicePortal) { this.selfServicePortal = selfServicePortal; }
public boolean isClientConnectEnabled() { return clientConnectEnabled; }
public void setClientConnectEnabled(boolean enabled) { this.clientConnectEnabled = enabled; }
public String getClientConnectLambdaFunctionArn() { return clientConnectLambdaFunctionArn; }
public void setClientConnectLambdaFunctionArn(String arn) { this.clientConnectLambdaFunctionArn = arn; }
public int getSessionTimeoutHours() { return sessionTimeoutHours; }
public void setSessionTimeoutHours(int hours) { this.sessionTimeoutHours = hours; }
public boolean isClientLoginBannerEnabled() { return clientLoginBannerEnabled; }
public void setClientLoginBannerEnabled(boolean enabled) { this.clientLoginBannerEnabled = enabled; }
public String getClientLoginBannerText() { return clientLoginBannerText; }
public void setClientLoginBannerText(String text) { this.clientLoginBannerText = text; }
public boolean isClientRouteEnforced() { return clientRouteEnforced; }
public void setClientRouteEnforced(boolean enforced) { this.clientRouteEnforced = enforced; }
public boolean isDisconnectOnSessionTimeout() { return disconnectOnSessionTimeout; }
public void setDisconnectOnSessionTimeout(boolean disconnect) { this.disconnectOnSessionTimeout = disconnect; }
public String getEndpointIpAddressType() { return endpointIpAddressType; }
public void setEndpointIpAddressType(String type) { this.endpointIpAddressType = type; }
public String getTrafficIpAddressType() { return trafficIpAddressType; }
public void setTrafficIpAddressType(String type) { this.trafficIpAddressType = type; }
public String getClientToken() { return clientToken; }
public void setClientToken(String clientToken) { this.clientToken = clientToken; }
public List<TargetNetwork> getTargetNetworks() { return targetNetworks; }
public void setTargetNetworks(List<TargetNetwork> networks) {
this.targetNetworks = networks != null ? networks : new ArrayList<>();
}
public List<AuthorizationRule> getAuthorizationRules() { return authorizationRules; }
public void setAuthorizationRules(List<AuthorizationRule> rules) {
this.authorizationRules = rules != null ? rules : new ArrayList<>();
}
public List<Route> getRoutes() { return routes; }
public void setRoutes(List<Route> routes) { this.routes = routes != null ? routes : new ArrayList<>(); }
}
@@ -0,0 +1,288 @@
package io.github.hectorvent.floci.services.ec2;
import io.github.hectorvent.floci.testing.Ec2Requests;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.matchesRegex;
import static org.hamcrest.Matchers.not;
/**
* EC2 Client VPN over the Query API, as {@code cloudposse/ec2-client-vpn/aws} drives it: an endpoint
* with certificate authentication, a subnet association per Availability Zone, an authorization rule
* for the VPC, routes, and the client configuration export.
*/
@QuarkusTest
class Ec2ClientVpnIntegrationTest {
private static final String ACCOUNT = "000000000000";
private static final String REGION = "us-east-1";
private static final String ACM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261103/us-east-1/acm/aws4_request";
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void anEndpointIsAssociatedAuthorizedRoutedExportedAndDeleted() {
String vpcId = ec2("CreateVpc").formParam("CidrBlock", "10.80.0.0/16").post("/").then().statusCode(200)
.extract().path("CreateVpcResponse.vpc.vpcId");
String subnetA = subnet(vpcId, "10.80.1.0/24", "us-east-1a");
String subnetSameZone = subnet(vpcId, "10.80.2.0/24", "us-east-1a");
String domain = "vpn-" + UUID.randomUUID().toString().substring(0, 8) + ".example.com";
String certificateArn = given().header("Authorization", ACM_AUTH)
.header("X-Amz-Target", "CertificateManager.RequestCertificate")
.contentType("application/x-amz-json-1.1")
.body("{\"DomainName\": \"" + domain + "\"}")
.post("/").then().statusCode(200).extract().path("CertificateArn");
String id = ec2("CreateClientVpnEndpoint")
.formParam("ClientCidrBlock", "172.16.0.0/20")
.formParam("ServerCertificateArn", certificateArn)
.formParam("Authentication.1.Type", "certificate-authentication")
.formParam("Authentication.1.MutualAuthentication.ClientRootCertificateChainArn", certificateArn)
.formParam("ConnectionLogOptions.Enabled", "false")
.formParam("DnsServers.1", "10.80.0.2")
.formParam("SplitTunnel", "true")
.formParam("VpcId", vpcId)
.formParam("Description", "team vpn")
.formParam("TagSpecification.1.ResourceType", "client-vpn-endpoint")
.formParam("TagSpecification.1.Tag.1.Key", "Name")
.formParam("TagSpecification.1.Tag.1.Value", "team-vpn")
.post("/").then().statusCode(200)
.body("CreateClientVpnEndpointResponse.status.code", equalTo("pending-associate"))
.body("CreateClientVpnEndpointResponse.dnsName", matchesRegex(
"\\*\\.cvpn-endpoint-[0-9a-f]{17}\\.prod\\.clientvpn\\.us-east-1\\.amazonaws\\.com"))
.extract().path("CreateClientVpnEndpointResponse.clientVpnEndpointId");
String item = "DescribeClientVpnEndpointsResponse.clientVpnEndpoint.item.";
ec2("DescribeClientVpnEndpoints").formParam("ClientVpnEndpointId.1", id).post("/").then().statusCode(200)
.body(item + "status.code", equalTo("pending-associate"))
.body(item + "transportProtocol", equalTo("udp"))
.body(item + "vpnPort", equalTo("443"))
.body(item + "vpnProtocol", equalTo("openvpn"))
.body(item + "sessionTimeoutHours", equalTo("24"))
.body(item + "splitTunnel", equalTo("true"))
.body(item + "vpcId", equalTo(vpcId))
.body(item + "securityGroupIdSet.item", matchesRegex("sg-[0-9a-f]+"))
.body(item + "authenticationOptions.item.type", equalTo("certificate-authentication"))
.body(item + "authenticationOptions.item.mutualAuthentication.clientRootCertificateChain",
equalTo(certificateArn))
.body(item + "connectionLogOptions.Enabled", equalTo("false"))
.body(item + "dnsServer.item", equalTo("10.80.0.2"))
.body(item + "tagSet.item.value", equalTo("team-vpn"));
String associationId = ec2("AssociateClientVpnTargetNetwork").formParam("ClientVpnEndpointId", id)
.formParam("SubnetId", subnetA).post("/").then().statusCode(200)
.body("AssociateClientVpnTargetNetworkResponse.status.code", equalTo("associating"))
.extract().path("AssociateClientVpnTargetNetworkResponse.associationId");
ec2("DescribeClientVpnTargetNetworks").formParam("ClientVpnEndpointId", id).post("/").then()
.body("DescribeClientVpnTargetNetworksResponse.clientVpnTargetNetworks.item.associationId",
equalTo(associationId))
.body("DescribeClientVpnTargetNetworksResponse.clientVpnTargetNetworks.item.status.code",
equalTo("associated"))
.body("DescribeClientVpnTargetNetworksResponse.clientVpnTargetNetworks.item.vpcId", equalTo(vpcId));
ec2("DescribeClientVpnEndpoints").formParam("ClientVpnEndpointId.1", id).post("/").then()
.body(item + "status.code", equalTo("available"));
// One subnet per Availability Zone.
ec2("AssociateClientVpnTargetNetwork").formParam("ClientVpnEndpointId", id)
.formParam("SubnetId", subnetSameZone).post("/").then().statusCode(400)
.body(containsString("<Code>InvalidParameterValue</Code>"));
ec2("AuthorizeClientVpnIngress").formParam("ClientVpnEndpointId", id)
.formParam("TargetNetworkCidr", "10.80.0.0/16").formParam("AuthorizeAllGroups", "true")
.formParam("Description", "Full VPC access").post("/").then().statusCode(200)
.body("AuthorizeClientVpnIngressResponse.status.code", equalTo("authorizing"));
ec2("DescribeClientVpnAuthorizationRules").formParam("ClientVpnEndpointId", id).post("/").then()
.body(containsString("<groupId/>"))
.body("DescribeClientVpnAuthorizationRulesResponse.authorizationRule.item.accessAll", equalTo("true"))
.body("DescribeClientVpnAuthorizationRulesResponse.authorizationRule.item.status.code",
equalTo("active"));
// The association added the route to the VPC through its subnet.
String routes = "DescribeClientVpnRoutesResponse.routes.item";
ec2("DescribeClientVpnRoutes").formParam("ClientVpnEndpointId", id).post("/").then()
.body(routes + ".destinationCidr", equalTo("10.80.0.0/16"))
.body(routes + ".origin", equalTo("associate"))
.body(routes + ".type", equalTo("Nat"))
.body(routes + ".targetSubnet", equalTo(subnetA))
.body(routes + ".description", equalTo("Default Route"));
ec2("CreateClientVpnRoute").formParam("ClientVpnEndpointId", id)
.formParam("DestinationCidrBlock", "192.168.0.0/16").formParam("TargetVpcSubnetId", subnetA)
.post("/").then().statusCode(200)
.body("CreateClientVpnRouteResponse.status.code", equalTo("creating"));
ec2("DescribeClientVpnRoutes").formParam("ClientVpnEndpointId", id).post("/").then()
.body(routes + ".destinationCidr", hasItem("192.168.0.0/16"));
ec2("DeleteClientVpnRoute").formParam("ClientVpnEndpointId", id)
.formParam("DestinationCidrBlock", "192.168.0.0/16").formParam("TargetVpcSubnetId", subnetA)
.post("/").then().statusCode(200);
ec2("ExportClientVpnClientConfiguration").formParam("ClientVpnEndpointId", id).post("/").then()
.statusCode(200)
.body("ExportClientVpnClientConfigurationResponse.clientConfiguration", containsString(
"remote " + id + ".prod.clientvpn.us-east-1.amazonaws.com 443\n"))
.body("ExportClientVpnClientConfigurationResponse.clientConfiguration",
containsString("proto udp\n"))
.body("ExportClientVpnClientConfigurationResponse.clientConfiguration",
containsString("<ca>\n-----BEGIN CERTIFICATE-----"))
.body("ExportClientVpnClientConfigurationResponse.clientConfiguration",
containsString("verify-x509-name " + domain + " name"));
ec2("CreateTags").formParam("ResourceId.1", id).formParam("Tag.1.Key", "team")
.formParam("Tag.1.Value", "data").post("/").then().statusCode(200);
ec2("DescribeClientVpnEndpoints").formParam("ClientVpnEndpointId.1", id).post("/").then()
.body(item + "tagSet.item.key", hasItem("team"));
ec2("DeleteClientVpnEndpoint").formParam("ClientVpnEndpointId", id).post("/").then().statusCode(400)
.body(containsString("<Code>IncorrectState</Code>"));
ec2("DisassociateClientVpnTargetNetwork").formParam("ClientVpnEndpointId", id)
.formParam("AssociationId", associationId).post("/").then().statusCode(200)
.body("DisassociateClientVpnTargetNetworkResponse.status.code", equalTo("disassociating"));
ec2("DescribeClientVpnRoutes").formParam("ClientVpnEndpointId", id).post("/").then()
.body(not(containsString("<item>")));
ec2("DeleteClientVpnEndpoint").formParam("ClientVpnEndpointId", id).post("/").then().statusCode(200)
.body("DeleteClientVpnEndpointResponse.status.code", equalTo("deleting"));
ec2("DescribeClientVpnEndpoints").formParam("ClientVpnEndpointId.1", id).post("/").then().statusCode(400)
.body(containsString("<Code>InvalidClientVpnEndpointId.NotFound</Code>"))
.body(containsString("<Message>Endpoint " + id + " does not exist</Message>"));
}
@Test
void describeFiltersSecurityGroupsSubnetPinsAndEquivalentCidrs() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String vpcId = ec2("CreateVpc").formParam("CidrBlock", "10.81.0.0/16").post("/").then().statusCode(200)
.extract().path("CreateVpcResponse.vpc.vpcId");
String subnetId = subnet(vpcId, "10.81.1.0/24", "us-east-1a");
String certificateArn = "arn:aws:acm:us-east-1:000000000000:certificate/" + UUID.randomUUID();
// Every requested security group must exist.
refused(endpoint(certificateArn, "udp").formParam("VpcId", vpcId)
.formParam("SecurityGroupId.1", "sg-0000000000000000f"),
"InvalidGroup.NotFound", "The security group 'sg-0000000000000000f' does not exist");
String tagged = endpoint(certificateArn, "udp")
.formParam("TagSpecification.1.ResourceType", "client-vpn-endpoint")
.formParam("TagSpecification.1.Tag.1.Key", "Name")
.formParam("TagSpecification.1.Tag.1.Value", "filter-" + suffix)
.post("/").then().statusCode(200).extract().path("CreateClientVpnEndpointResponse.clientVpnEndpointId");
String portal = endpoint(certificateArn, "tcp").formParam("SelfServicePortal", "enabled")
.post("/").then().statusCode(200).extract().path("CreateClientVpnEndpointResponse.clientVpnEndpointId");
String item = "DescribeClientVpnEndpointsResponse.clientVpnEndpoint.item";
ec2("DescribeClientVpnEndpoints").formParam("Filter.1.Name", "tag:Name")
.formParam("Filter.1.Value.1", "filter-" + suffix).post("/").then().statusCode(200)
.body(item + ".clientVpnEndpointId", equalTo(tagged));
ec2("DescribeClientVpnEndpoints").formParam("Filter.1.Name", "endpoint-id")
.formParam("Filter.1.Value.1", tagged).formParam("Filter.1.Value.2", portal)
.formParam("Filter.2.Name", "transport-protocol").formParam("Filter.2.Value.1", "tcp")
.post("/").then().statusCode(200)
.body(item + ".clientVpnEndpointId", equalTo(portal))
.body(item + ".selfServicePortalUrl",
equalTo("https://self-service.clientvpn.amazonaws.com/endpoints/" + portal));
refused(ec2("DescribeClientVpnEndpoints").formParam("Filter.1.Name", "bogus").formParam("Filter.1.Value.1", "x"),
"InvalidParameterValue", "The filter 'bogus' is invalid");
// An association pins its subnet until it is disassociated.
String associationId = ec2("AssociateClientVpnTargetNetwork").formParam("ClientVpnEndpointId", tagged)
.formParam("SubnetId", subnetId).post("/").then().statusCode(200)
.extract().path("AssociateClientVpnTargetNetworkResponse.associationId");
ec2("DeleteSubnet").formParam("SubnetId", subnetId).post("/").then().statusCode(400)
.body(containsString("<Code>DependencyViolation</Code>"));
String networks = "DescribeClientVpnTargetNetworksResponse.clientVpnTargetNetworks.item";
ec2("DescribeClientVpnTargetNetworks").formParam("ClientVpnEndpointId", tagged)
.formParam("Filter.1.Name", "vpc-id").formParam("Filter.1.Value.1", vpcId).post("/").then()
.body(networks + ".associationId", equalTo(associationId));
ec2("DescribeClientVpnTargetNetworks").formParam("ClientVpnEndpointId", tagged)
.formParam("Filter.1.Name", "association-id").formParam("Filter.1.Value.1", "cvpn-assoc-0").post("/")
.then().statusCode(200).body(not(containsString("<item>")));
// The same network spelled with host bits is the same rule and the same route.
ec2("AuthorizeClientVpnIngress").formParam("ClientVpnEndpointId", tagged)
.formParam("TargetNetworkCidr", "10.81.0.0/16").formParam("AuthorizeAllGroups", "true")
.post("/").then().statusCode(200);
ec2("AuthorizeClientVpnIngress").formParam("ClientVpnEndpointId", tagged)
.formParam("TargetNetworkCidr", "10.81.0.9/16").formParam("AuthorizeAllGroups", "true")
.post("/").then().statusCode(400).body(containsString("<Code>InvalidParameterValue</Code>"));
String rules = "DescribeClientVpnAuthorizationRulesResponse.authorizationRule.item";
ec2("DescribeClientVpnAuthorizationRules").formParam("ClientVpnEndpointId", tagged)
.formParam("Filter.1.Name", "destination-cidr").formParam("Filter.1.Value.1", "10.81.0.0/16")
.post("/").then().body(rules + ".destinationCidr", equalTo("10.81.0.0/16"));
ec2("DescribeClientVpnAuthorizationRules").formParam("ClientVpnEndpointId", tagged)
.formParam("Filter.1.Name", "destination-cidr").formParam("Filter.1.Value.1", "10.99.0.0/16")
.post("/").then().statusCode(200).body(not(containsString("<item>")));
ec2("RevokeClientVpnIngress").formParam("ClientVpnEndpointId", tagged)
.formParam("TargetNetworkCidr", "10.81.0.9/16").formParam("RevokeAllGroups", "true")
.post("/").then().statusCode(200);
String routes = "DescribeClientVpnRoutesResponse.routes.item";
ec2("CreateClientVpnRoute").formParam("ClientVpnEndpointId", tagged)
.formParam("DestinationCidrBlock", "192.168.0.0/16").formParam("TargetVpcSubnetId", subnetId)
.post("/").then().statusCode(200);
ec2("CreateClientVpnRoute").formParam("ClientVpnEndpointId", tagged)
.formParam("DestinationCidrBlock", "192.168.0.5/16").formParam("TargetVpcSubnetId", subnetId)
.post("/").then().statusCode(400).body(containsString("<Code>InvalidClientVpnDuplicateRoute</Code>"));
ec2("DescribeClientVpnRoutes").formParam("ClientVpnEndpointId", tagged)
.formParam("Filter.1.Name", "origin").formParam("Filter.1.Value.1", "associate").post("/").then()
.body(routes + ".destinationCidr", equalTo("10.81.0.0/16"));
ec2("DeleteClientVpnRoute").formParam("ClientVpnEndpointId", tagged)
.formParam("DestinationCidrBlock", "192.168.0.5/16").formParam("TargetVpcSubnetId", subnetId)
.post("/").then().statusCode(200);
ec2("DisassociateClientVpnTargetNetwork").formParam("ClientVpnEndpointId", tagged)
.formParam("AssociationId", associationId).post("/").then().statusCode(200);
ec2("DeleteSubnet").formParam("SubnetId", subnetId).post("/").then().statusCode(200);
ec2("DeleteClientVpnEndpoint").formParam("ClientVpnEndpointId", tagged).post("/").then().statusCode(200);
ec2("DeleteClientVpnEndpoint").formParam("ClientVpnEndpointId", portal).post("/").then().statusCode(200);
}
@Test
void unknownAndMalformedEndpointIdsAreRefusedWithAwsErrors() {
refused(ec2("DescribeClientVpnEndpoints").formParam("ClientVpnEndpointId.1", "cvpn-endpoint-0123456789abcdef0"),
"InvalidClientVpnEndpointId.NotFound", "Endpoint cvpn-endpoint-0123456789abcdef0 does not exist");
refused(ec2("DescribeClientVpnTargetNetworks").formParam("ClientVpnEndpointId", "cvpn-endpoint-0123456789abcdef0"),
"InvalidClientVpnEndpointId.NotFound", "Endpoint cvpn-endpoint-0123456789abcdef0 does not exist");
refused(ec2("DescribeClientVpnEndpoints").formParam("ClientVpnEndpointId.1", "not-an-id"),
"InvalidParameterValue", "ClientVpnEndpointId you provided is not valid");
ec2("CreateClientVpnEndpoint").formParam("ClientCidrBlock", "172.16.0.0/20")
.formParam("Authentication.1.Type", "certificate-authentication")
.formParam("ConnectionLogOptions.Enabled", "false")
.post("/").then().statusCode(400).body(containsString("<Code>MissingParameter</Code>"));
}
private static String subnet(String vpcId, String cidr, String zone) {
return ec2("CreateSubnet").formParam("VpcId", vpcId).formParam("CidrBlock", cidr)
.formParam("AvailabilityZone", zone).post("/").then().statusCode(200)
.extract().path("CreateSubnetResponse.subnet.subnetId");
}
private static RequestSpecification endpoint(String certificateArn, String transport) {
return ec2("CreateClientVpnEndpoint").formParam("ClientCidrBlock", "172.16.0.0/22")
.formParam("ServerCertificateArn", certificateArn)
.formParam("Authentication.1.Type", "certificate-authentication")
.formParam("Authentication.1.MutualAuthentication.ClientRootCertificateChainArn", certificateArn)
.formParam("ConnectionLogOptions.Enabled", "false")
.formParam("TransportProtocol", transport);
}
private static void refused(RequestSpecification request, String code, String message) {
ValidatableResponse response = request.post("/").then().statusCode(400);
response.body("Response.Errors.Error.Code", equalTo(code))
.body("Response.Errors.Error.Message", equalTo(message));
}
private static RequestSpecification ec2(String action) {
return Ec2Requests.ec2(action, ACCOUNT, REGION);
}
}