diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 6c660b82cb..a2e691e722 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -216,7 +216,7 @@ With TLS, set `FLOCI_DNS_SPOOF_AWS_ENDPOINTS` as an environment variable (or `-D ### Floci running natively -The embedded DNS server answers the names above, Cloud Map `.` names, Route 53 private zone records and, with `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC=true`, the endpoint names of RDS instances and clusters served in their VPC. When Floci runs in Docker it listens on its own container address, and publishing the container's port 53/udp (for example `-p 127.0.0.1:53:53/udp`) lets the host reach it as well. +The embedded DNS server answers the names above, Cloud Map `.` names, Route 53 private zone records and, with `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC=true`, the endpoint names of RDS instances, clusters and DB proxies served in their VPC. When Floci runs in Docker it listens on its own container address, and publishing the container's port 53/udp (for example `-p 127.0.0.1:53:53/udp`) lets the host reach it as well. When Floci runs natively, it starts up to two listeners: @@ -522,7 +522,7 @@ These services spawn Docker containers. They require access to the Docker socket | `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` | `7001` | First port in the RDS proxy range | | `FLOCI_SERVICES_RDS_PROXY_MAX_PORT` | `7099` | Last port in the RDS proxy range | | `FLOCI_SERVICES_RDS_ADVERTISE_REQUESTED_PORT` | `false` | Report the requested `Port` instead of the proxy port in `Describe*` | -| `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC` | `false` | Serve a DB instance in a VPC at its own address, on its `Port`, under its RDS endpoint name, and resolve a DB cluster's endpoint names to its instances | +| `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC` | `false` | Serve a DB instance in a VPC at its own address, on its `Port`, under its RDS endpoint name, resolve a DB cluster's endpoint names to its instances, and serve a DB proxy's endpoints at their own addresses | | `FLOCI_SERVICES_RDS_ENDPOINT_HOST` | _(auto-detected)_ | Hostname advertised in RDS endpoints; when set in Docker, Floci advertises each proxy's published host port | | `FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING` | `true` | Refuse a PostgreSQL IAM auth token generated for another hostname, port or region than the endpoint publishes, as RDS does; set `false` to accept such tokens. MySQL and MariaDB always refuse them | | `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Default PostgreSQL Docker image | diff --git a/docs/services/rds.md b/docs/services/rds.md index a57a9e0a82..b0b183650a 100644 --- a/docs/services/rds.md +++ b/docs/services/rds.md @@ -348,7 +348,7 @@ they belong to, as the model requires. An omitted `Enabled` activates the subscr | `FLOCI_SERVICES_RDS_PROXY_BASE_PORT` | `7001` | First host port in the RDS proxy range | | `FLOCI_SERVICES_RDS_PROXY_MAX_PORT` | `7099` | Last host port in the RDS proxy range | | `FLOCI_SERVICES_RDS_ADVERTISE_REQUESTED_PORT` | `false` | `true` = `Describe*` reports the requested `Port` instead of the proxy port; connect via the proxy port | -| `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC` | `false` | `true` = a DB instance serves its `Port` at its own address in its VPC, under its RDS endpoint name, and a DB cluster's endpoint names resolve to its instances; see [Endpoints in a VPC](#endpoints-in-a-vpc) | +| `FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC` | `false` | `true` = a DB instance serves its `Port` at its own address in its VPC, under its RDS endpoint name, a DB cluster's endpoint names resolve to its instances, and a DB proxy's endpoints are served at their own addresses; see [Endpoints in a VPC](#endpoints-in-a-vpc) | | `FLOCI_SERVICES_RDS_ENDPOINT_HOST` | _(auto-detected)_ | Hostname advertised in RDS endpoints; when set in Docker, Floci advertises each proxy's published host port | | `FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING` | `true` | Refuse a PostgreSQL IAM auth token generated for another hostname, port or region than the endpoint publishes, as RDS does; set `false` to accept such tokens. MySQL and MariaDB always refuse them | | `FLOCI_SERVICES_RDS_DEFAULT_POSTGRES_IMAGE` | `postgres:16-alpine` | Docker image for PostgreSQL instances | @@ -442,11 +442,13 @@ services: !!! warning "DB proxy endpoint routing" - DB proxy control-plane resources and target registration are modeled, but Floci's current - single-host TCP relay cannot expose multiple same-engine DB proxies as distinct AWS-style bare - hostnames on the same engine-default port. The standard Docker Compose mapping also exposes - only the `7001-7099` instance/cluster proxy range, not `1433`, `3306`, or `5432`. Use mock mode - for DB proxy provisioning workflows until a dedicated endpoint-routing design is implemented. + DB proxy control-plane resources and target registration are modeled. Without + [Endpoints in a VPC](#endpoints-in-a-vpc), Floci's single-host TCP relay cannot expose multiple + same-engine DB proxies as distinct AWS-style bare hostnames on the same engine-default port, and + the standard Docker Compose mapping exposes only the `7001-7099` instance/cluster proxy range, + not `1433`, `3306`, or `5432`; use mock mode for DB proxy provisioning workflows there, or turn + endpoints in their VPC on, which serves each proxy endpoint at its own address on its engine + family's port. RDS reserves the configured listener port of enabled, non-mock DSQL before allocating or restoring a relay. A DB proxy whose preferred or persisted port belongs to DSQL uses the RDS proxy range instead. This avoids startup-order collisions; it does not provide @@ -475,13 +477,14 @@ services: is rejected with `InvalidParameterValue` unless the proxy's VPC and every subnet in `VpcSubnetIds` already carry an associated IPv6 CIDR block, matching AWS's own network prerequisites for RDS Proxy. - Proxy endpoints report the proxy's own host, so a client connects through one as through the - proxy, and an IAM token signed for that host verifies there. The host is read from the proxy + Without endpoints in their VPC, proxy endpoints report the proxy's own host, so a client + connects through one as through the proxy, and an IAM token signed for that host verifies there. The host is read from the proxy for each response, so when a restore gives the proxy a new host every endpoint reports it. `TargetRole` is recorded: Floci proxies have one target, so a `READ_ONLY` endpoint reaches the same target as the proxy rather than an Aurora reader. Each proxy's default endpoint (`default`, `IsDefault` true, `READ_WRITE`) is built from the proxy, has no ARN, and cannot be modified or deleted - (`InvalidDBProxyEndpointStateFault`). Endpoint names are unique per account and Region, a proxy + (`InvalidDBProxyEndpointStateFault`). Proxy and endpoint names are unique regardless of case, as + each names a hostname and DNS names ignore case. Endpoint names are unique per account and Region, a proxy holds at most 20 endpoints (`DBProxyEndpointQuotaExceededFault`), and an endpoint with no `VpcSecurityGroupIds` gets its VPC's default security group. @@ -624,6 +627,19 @@ sharing Floci's address on a proxy port: static members have all been deleted. So does a cluster with no instance yet, as on AWS: "Until you create the primary DB instance, the DB cluster endpoints remain in the Creating status" (Aurora user guide). An IAM authentication token generated for any of a cluster's names is good at each of its instances, as is one for the instance's own name. +- A DB proxy's default endpoint is served at its own address in the first of the proxy's `VpcSubnetIds`, under the + name RDS gives it, `.proxy-..rds.amazonaws.com`, and each endpoint added to it at its + own address in the first of its own `VpcSubnetIds`, which may be in another VPC, under + `.endpoint.proxy-...` (the CLI reference's examples). Each serves the proxy's engine family's + port, as "all proxies listen on port 5432 for PostgreSQL" and "on port 3306 for MySQL" (RDS user guide), and + 1433 for SQL Server, which the guide does not name, so two proxies can both serve 5432; the proxy's own listener + takes a free port in the proxy range. `DescribeDBProxies` and `DescribeDBProxyEndpoints` report the names, which + resolve as soon as the proxy or endpoint exists; connections reach the target once one is registered. An IAM + authentication token generated for any of the proxy's endpoints is good at the proxy, a renamed endpoint answers + by its new name, and deleting an endpoint or the proxy removes its names and relays. A relay Docker does not + confirm removed stays, holding its address and keeping the port it forwards to from other databases, until Floci + stops or restarts; so does one a restart with the setting off cannot remove, though the proxy leaves its VPC. A + `READ_ONLY` endpoint reaches the proxy's one target, as the default endpoint does. - A `DeleteDBInstance` whose relays Docker does not confirm removed, its current one or one a subnet move left, fails, and the instance keeps its proxy port, so a relay never forwards to another database; a retry removes them. A `StopDBInstance` stops all the same, and the next start, a delete or a restart removes the relay. Until a relay @@ -637,12 +653,12 @@ host, still connects through the proxy port, which keeps listening in the proxy the name and port `DescribeDBInstances` reports. The name resolves to the private address alone: `PubliclyAccessible` changes nothing, and the address is IPv4 only. -A state reset removes the relays with the instances, and the cluster names with the clusters. +A state reset removes the relays with the instances and proxies, and the cluster names with the clusters. The setting needs Docker-backed VPC networks (`FLOCI_SERVICES_EC2_VPC_NETWORKS_ENABLED`, on by default) and does nothing in mock mode. The relay runs EC2's socat image (`FLOCI_SERVICES_EC2_SOCAT_IMAGE`). An instance's VPC security -groups do not filter traffic to its address, even with security-group enforcement on. DB proxies keep the proxy -endpoint on Floci's address. +groups do not filter traffic to its address, even with security-group enforcement on, nor do a DB proxy's or its +endpoints'. A proxy endpoint is served over IPv4 whatever its `EndpointNetworkType`. ## Modifying a DB instance diff --git a/src/main/java/io/floci/aws/config/EmulatorConfig.java b/src/main/java/io/floci/aws/config/EmulatorConfig.java index 353b87e829..973165f358 100644 --- a/src/main/java/io/floci/aws/config/EmulatorConfig.java +++ b/src/main/java/io/floci/aws/config/EmulatorConfig.java @@ -2138,7 +2138,8 @@ public interface EmulatorConfig { * When true, a DB instance in a subnet with a Docker-backed VPC network gets its own address there and * serves the Port it was created with, or its engine's default, under the endpoint name RDS gives it, * which Floci's DNS server answers. A DB cluster's instances serve its port the same way, and its cluster, - * reader and custom endpoint names resolve to them. Off, every endpoint is Floci's address and a proxy port. + * reader and custom endpoint names resolve to them; a DB proxy's endpoints serve its engine family's port + * at their own addresses. Off, every endpoint is Floci's address and a proxy port. */ @WithDefault("false") boolean endpointsInVpc(); diff --git a/src/main/java/io/floci/aws/core/common/AwsEndpoints.java b/src/main/java/io/floci/aws/core/common/AwsEndpoints.java index f360362a3e..960666dbec 100644 --- a/src/main/java/io/floci/aws/core/common/AwsEndpoints.java +++ b/src/main/java/io/floci/aws/core/common/AwsEndpoints.java @@ -65,6 +65,22 @@ public final class AwsEndpoints { + region + ".rds." + AwsRegions.dnsSuffixFor(region); } + /** + * A DB proxy's default endpoint address, {@code .proxy-..rds.}, as the CLI + * reference's {@code proxyExample.proxy-ab0cd1efghij.us-west-2.rds.amazonaws.com}. + */ + public static String rdsProxyHost(String dbProxyName, String accountId, String region) { + return rdsClusterEndpointHost(dbProxyName, "proxy", accountId, region); + } + + /** + * The address of an endpoint added to a DB proxy, {@code .endpoint.proxy-...}, as the CLI + * reference's {@code proxyep1.endpoint.proxy-ab0cd1efghij.us-west-2.rds.amazonaws.com}. + */ + public static String rdsProxyEndpointHost(String endpointName, String accountId, String region) { + return rdsClusterEndpointHost(endpointName + ".endpoint", "proxy", accountId, region); + } + /** {@code .execute-api..}. */ public static String executeApiHost(String apiId, String region) { return apiId + "." + host("execute-api", region); diff --git a/src/main/java/io/floci/aws/services/rds/RdsEndpointAddresses.java b/src/main/java/io/floci/aws/services/rds/RdsEndpointAddresses.java index 9e89a2fc03..a9f120e84e 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsEndpointAddresses.java +++ b/src/main/java/io/floci/aws/services/rds/RdsEndpointAddresses.java @@ -65,6 +65,8 @@ public class RdsEndpointAddresses implements VpcDependencyProvider, ContainerTea private final Map relayIdsByHost = new ConcurrentHashMap<>(); /** The endpoint names of each DB cluster in its VPC, lowercase, and the instances they resolve to. */ private final Map clusterNamesByHost = new ConcurrentHashMap<>(); + /** The resource whose listener each relay of an endpoint added to a DB proxy forwards to, by relay id. */ + private final Map ownersByRelayId = new ConcurrentHashMap<>(); /** * A DB cluster endpoint name and the instances it resolves to: one of {@code hosts}, at random among those served, @@ -257,15 +259,59 @@ public class RdsEndpointAddresses implements VpcDependencyProvider, ContainerTea return relays.targetsPort(port); } - // The relay reaches the proxy at Floci's address on the network it joins besides its VPC's, as RDS's database - // containers on that network are reached. private VpcAddressRelays.Relay relay(DbInstance instance, String accountId, String region, int proxyPort) { return new VpcAddressRelays.Relay(instance.getVpcEndpointId(), accountId, region, instance.getVpcId(), - instance.getVpcEndpointSubnetId(), servedPort(instance), - dockerHostResolver.resolveOn(relays.network().orElse(null)), proxyPort, + instance.getVpcEndpointSubnetId(), servedPort(instance), relayTarget(), proxyPort, "DB instance " + instance.getDbInstanceIdentifier()); } + // The relay reaches the proxy at Floci's address on the network it joins besides its VPC's, as RDS's database + // containers on that network are reached. + private String relayTarget() { + return dockerHostResolver.resolveOn(relays.network().orElse(null)); + } + + /** + * Serves an endpoint that is not an instance's, such as a DB proxy's, at an address of {@code subnetId} on + * {@code port}, relayed to the Floci listener on {@code proxyPort}, and returns the address: {@code + * preferredAddress}, the one it held before, when the subnet still has it. + * + * @param relayId the endpoint's relay id, from {@link #newRelayId} + * @param name the endpoint, for the log + * @throws IllegalStateException as {@link #serve(DbInstance, String, String, int)} does + */ + public String serve(String relayId, String accountId, String region, String vpcId, String subnetId, int port, + int proxyPort, String name, String preferredAddress) { + return relays.serve(new VpcAddressRelays.Relay(relayId, accountId, region, vpcId, subnetId, port, + relayTarget(), proxyPort, name), preferredAddress); + } + + /** + * Makes {@code host}, as {@link AwsEndpoints} gives it, the name of the endpoint the relay {@code relayId} serves, + * in place of any name it had. The endpoint reaches the listener of {@code ownerResourceId}, such as a DB proxy, + * so an IAM token generated for the name is good there ({@link #reaches}). + */ + public void remember(String host, String relayId, String ownerResourceId) { + relayIdsByHost.values().removeIf(relayId::equals); + relayIdsByHost.put(host, relayId); + ownersByRelayId.put(relayId, ownerResourceId); + } + + /** + * Forgets the name of the endpoint the relay {@code relayId} serves and removes the relay, as its endpoint goes. + * One Docker does not confirm removed stays tracked, holding its address and keeping the port it forwards to from + * other databases ({@link #targetsPort}), until Floci stops or a restart removes it. + */ + public void discard(String relayId) { + relayIdsByHost.values().removeIf(relayId::equals); + ownersByRelayId.remove(relayId); + try { + relays.stop(relayId); + } catch (RuntimeException e) { + LOG.warnv(e, "Relay {0} stays until Docker confirms it removed", relayId); + } + } + /** * Makes the instance's endpoint name known under its identifier now, for one not served yet, such as a stopped * instance after a restart, or one whose identifier a blue/green switchover changed. @@ -352,12 +398,18 @@ public class RdsEndpointAddresses implements VpcDependencyProvider, ContainerTea } /** - * Whether {@code host} is one of the endpoint names of the DB cluster {@code clusterResourceId}: each of its - * instances is reached by them, so an IAM token generated for one is good at the instance. + * Whether {@code host} names an endpoint that reaches the listener of {@code resourceId}: one of the endpoint names + * of the DB cluster of that resource id, which resolve to its instances, or the name of an endpoint added to the + * DB proxy of that id. An IAM token generated for the name is good at the listener. */ - public boolean namesCluster(String clusterResourceId, String host) { - ClusterName name = clusterNamesByHost.get(host.toLowerCase(Locale.ROOT)); - return name != null && name.clusterResourceId().equals(clusterResourceId); + public boolean reaches(String resourceId, String host) { + String lower = host.toLowerCase(Locale.ROOT); + ClusterName name = clusterNamesByHost.get(lower); + if (name != null) { + return name.clusterResourceId().equals(resourceId); + } + String relayId = relayIdsByHost.get(lower); + return relayId != null && resourceId.equals(ownersByRelayId.get(relayId)); } /** Whether {@code host} is the name of an endpoint in its VPC Floci knows, served or stopped. */ @@ -406,11 +458,12 @@ public class RdsEndpointAddresses implements VpcDependencyProvider, ContainerTea relays.stopAll(); } - /** A reset wipes the instances and clusters whose names the index holds. */ + /** A reset wipes the instances, clusters and proxies whose names the index holds. */ @Override public void clear() { relayIdsByHost.clear(); clusterNamesByHost.clear(); + ownersByRelayId.clear(); } /** Writes down again the relays a reset could not remove, whose placements the storage wipe took. */ diff --git a/src/main/java/io/floci/aws/services/rds/RdsService.java b/src/main/java/io/floci/aws/services/rds/RdsService.java index 5352bf96e2..a69a20e813 100644 --- a/src/main/java/io/floci/aws/services/rds/RdsService.java +++ b/src/main/java/io/floci/aws/services/rds/RdsService.java @@ -5356,9 +5356,10 @@ public class RdsService implements Resettable, ResourceProvider { tokensBoundToEndpoint); } // A cluster's endpoint names resolve to its instances in its VPC, so the cluster's proxy and each of its - // instances' (whose resource id is the cluster's) take a token generated for any of them. + // instances' (whose resource id is the cluster's) take a token generated for any of them; a DB proxy takes one + // generated for any of the endpoints added to it. return new RdsProxyBinding(advertisedHost, publishedPort, region, accountId, resourceId, - tokensBoundToEndpoint, host -> endpointAddresses.namesCluster(resourceId, host)); + tokensBoundToEndpoint, host -> endpointAddresses.reaches(resourceId, host)); } private static boolean hasBackend(String host, int port) { @@ -7434,15 +7435,21 @@ public class RdsService implements Resettable, ResourceProvider { } String proxyKey = dbProxyKey(effectiveRegion, dbProxyName); String accountId = currentAccountId(); + // A proxy's endpoint hostname is built from its name and DNS names ignore case, so names that differ only + // in case would be one hostname. if (findDbProxy(dbProxyName, effectiveRegion).isPresent() - || scopedKeyExists(proxies, accountId, proxyKey)) { + || scopedKeyExists(proxies, accountId, proxyKey) + || listDbProxies(null, effectiveRegion).stream() + .anyMatch(existing -> existing.getDbProxyName().equalsIgnoreCase(dbProxyName))) { throw new AwsException("DBProxyAlreadyExistsFault", "DB proxy " + dbProxyName + " already exists.", 400); } boolean mock = config.services().rds().mock(); - // Proxies share a hostname, so each needs its own listener port. - int proxyPort = reserveOrAllocateProxyPort(defaultPortForEngineFamily(engineFamily)); + // Proxies share a hostname, so each needs its own listener port. In their VPC each endpoint serves the engine + // family's port at its own address, so the listener's is any free one. + int proxyPort = endpointsInVpc() ? allocateProxyPort() + : reserveOrAllocateProxyPort(defaultPortForEngineFamily(engineFamily)); DbProxy proxy = new DbProxy(); proxy.setDbProxyName(dbProxyName); proxy.setEngineFamily(engineFamily.toUpperCase()); @@ -7474,6 +7481,15 @@ public class RdsService implements Resettable, ResourceProvider { String resourceId = "prx-" + randomResourceSuffix(); proxy.setDbProxyResourceId(resourceId); proxy.setDbProxyArn(regionResolver.buildArn("rds", effectiveRegion, "db-proxy:" + resourceId)); + if (assignProxyEndpoint(proxy)) { + try { + serveProxyInVpc(proxy); + } catch (RuntimeException serveFailure) { + endpointAddresses.discard(proxy.getVpcEndpointId()); + releaseProxyPort(proxyPort); + throw serveFailure; + } + } DbProxyTargetGroup targetGroup = new DbProxyTargetGroup(); targetGroup.setDbProxyName(dbProxyName); @@ -7504,6 +7520,9 @@ public class RdsService implements Resettable, ResourceProvider { createFailure.addSuppressed(verificationFailure); } if (stateRemoved) { + if (proxyInVpc(proxy)) { + endpointAddresses.discard(proxy.getVpcEndpointId()); + } releaseProxyPort(proxyPort); throw createFailure; } @@ -7766,7 +7785,7 @@ public class RdsService implements Resettable, ResourceProvider { proxyAccountId, targetRegion, targetId, user, pw) : validateDbPasswordForScope( proxyAccountId, targetRegion, targetId, user, pw), - proxyBinding(engine, proxy.getEndpointHost(), proxy.getProxyPort(), + proxyBinding(engine, proxy.getEndpointHost(), proxyPublishedPort(proxy), targetRegion, proxyAccountId, proxy.getDbProxyResourceId()), RdsAuthProxy.EndpointKind.STANDARD_DB_PROXY); } @@ -8140,6 +8159,8 @@ public class RdsService implements Resettable, ResourceProvider { restartDbProxyRelayAfterFailure(proxy, relayTargetGroup, deleteFailure); throw deleteFailure; } + // Gone with the records: a relay Docker keeps still holds the port it forwards to from other databases. + discardProxyRelays(proxy, endpoints); releaseProxyPort(proxy.getProxyPort()); LOG.infov("DB proxy {0} deleted", name); } @@ -8284,7 +8305,7 @@ public class RdsService implements Resettable, ResourceProvider { "DB proxy " + proxy.getDbProxyName() + " is not available.", 400); } String key = proxyEndpointKey(effectiveRegion, name); - if (DEFAULT_PROXY_ENDPOINT_NAME.equals(name) || proxyEndpoints.get(key).isPresent()) { + if (proxyEndpointNameTaken(effectiveRegion, name, null)) { throw new AwsException("DBProxyEndpointAlreadyExistsFault", "DB proxy endpoint " + name + " already exists.", 400); } @@ -8313,7 +8334,22 @@ public class RdsService implements Resettable, ResourceProvider { endpoint.setTargetRole(role); endpoint.setEndpointNetworkType(networkType); endpoint.setTags(tags); - proxyEndpoints.put(key, endpoint); + if (assignProxyEndpoint(proxy, endpoint)) { + try { + serveProxyInVpc(proxy, endpoint); + } catch (RuntimeException serveFailure) { + endpointAddresses.discard(endpoint.getVpcEndpointId()); + throw serveFailure; + } + } + try { + proxyEndpoints.put(key, endpoint); + } catch (RuntimeException storeFailure) { + if (proxyEndpointInVpc(endpoint)) { + endpointAddresses.discard(endpoint.getVpcEndpointId()); + } + throw storeFailure; + } return withProxyHost(endpoint, proxy); } @@ -8362,19 +8398,38 @@ public class RdsService implements Resettable, ResourceProvider { String name = isBlank(newName) ? endpoint.getDbProxyEndpointName() : requireProxyEndpointName(newName, "NewDBProxyEndpointName"); boolean renamed = !name.equals(endpoint.getDbProxyEndpointName()); - if (renamed && (DEFAULT_PROXY_ENDPOINT_NAME.equals(name) - || proxyEndpoints.get(proxyEndpointKey(effectiveRegion, name)).isPresent())) { + if (renamed && proxyEndpointNameTaken(effectiveRegion, name, endpoint)) { throw new AwsException("DBProxyEndpointAlreadyExistsFault", "DB proxy endpoint " + name + " already exists.", 400); } - String oldKey = proxyEndpointKey(effectiveRegion, endpoint.getDbProxyEndpointName()); + String oldName = endpoint.getDbProxyEndpointName(); + List oldGroups = endpoint.getVpcSecurityGroupIds(); + String oldKey = proxyEndpointKey(effectiveRegion, oldName); + String newKey = proxyEndpointKey(effectiveRegion, name); endpoint.setDbProxyEndpointName(name); if (vpcSecurityGroupIds != null) { endpoint.setVpcSecurityGroupIds(vpcSecurityGroupIds); } - proxyEndpoints.put(proxyEndpointKey(effectiveRegion, name), endpoint); - if (renamed) { - proxyEndpoints.delete(oldKey); + try { + proxyEndpoints.put(newKey, endpoint); + if (renamed) { + proxyEndpoints.delete(oldKey); + } + } catch (RuntimeException storeFailure) { + // The endpoint keeps the name it had, the one its DNS entry and IAM tokens still name. + endpoint.setDbProxyEndpointName(oldName); + endpoint.setVpcSecurityGroupIds(oldGroups); + if (renamed) { + attemptRollback(storeFailure, () -> proxyEndpoints.delete(newKey)); + } + attemptRollback(storeFailure, () -> proxyEndpoints.put(oldKey, endpoint)); + throw storeFailure; + } + if (renamed && proxyEndpointInVpc(endpoint)) { + // The relay and address stay; the endpoint answers by its new name only. + String host = proxyEndpointHost(proxy, endpoint); + endpointAddresses.remember(host, endpoint.getVpcEndpointId(), proxy.getDbProxyResourceId()); + coverTlsHost(host); } return withProxyHost(endpoint, proxy); } @@ -8384,6 +8439,9 @@ public class RdsService implements Resettable, ResourceProvider { String effectiveRegion = effectiveRegion(region); DbProxyEndpoint endpoint = requireProxyEndpoint(effectiveRegion, endpointName); proxyEndpoints.delete(proxyEndpointKey(effectiveRegion, endpoint.getDbProxyEndpointName())); + if (proxyEndpointInVpc(endpoint)) { + endpointAddresses.discard(endpoint.getVpcEndpointId()); + } endpoint.setStatus("deleting"); return withProxyHost(endpoint, getDbProxy(endpoint.getDbProxyName(), effectiveRegion)); } @@ -8407,9 +8465,13 @@ public class RdsService implements Resettable, ResourceProvider { return name; } - /** Reports the proxy's current host, which a restore can change after the endpoint was created. */ - private static DbProxyEndpoint withProxyHost(DbProxyEndpoint endpoint, DbProxy proxy) { - endpoint.setEndpoint(proxy.getEndpoint()); + /** + * Reports the endpoint's host: its own name in its VPC, otherwise the proxy's current host, which a restore can + * change after the endpoint was created. + */ + private DbProxyEndpoint withProxyHost(DbProxyEndpoint endpoint, DbProxy proxy) { + endpoint.setEndpoint(endpoint.getVpcEndpointId() != null ? proxyEndpointHost(proxy, endpoint) + : proxy.getEndpoint()); return endpoint; } @@ -8445,6 +8507,122 @@ public class RdsService implements Resettable, ResourceProvider { return effectiveRegion(region) + "::" + endpointName; } + /** + * Whether {@code name} is the default endpoint's or another endpoint's of the Region, ignoring case: an endpoint's + * hostname is built from its name and DNS names ignore case, so names that differ only in case would be one + * hostname. {@code self}, an endpoint being renamed, does not count. + */ + private boolean proxyEndpointNameTaken(String region, String name, DbProxyEndpoint self) { + if (DEFAULT_PROXY_ENDPOINT_NAME.equalsIgnoreCase(name)) { + return true; + } + String prefix = effectiveRegion(region) + "::"; + return proxyEndpoints.scan(key -> key.startsWith(prefix)).stream() + .filter(endpoint -> self == null + || !endpoint.getDbProxyEndpointName().equals(self.getDbProxyEndpointName())) + .anyMatch(endpoint -> endpoint.getDbProxyEndpointName().equalsIgnoreCase(name)); + } + + /** Whether endpoints go in their VPC, as a new proxy's and its endpoints' do. */ + private boolean endpointsInVpc() { + return endpointAddresses != null && endpointAddresses.enabled(); + } + + /** Whether the proxy's endpoints are in its VPC, each served at its own address. */ + private boolean proxyInVpc(DbProxy proxy) { + return endpointAddresses != null && proxy.getVpcEndpointId() != null; + } + + /** Whether an endpoint added to a proxy is in its VPC, served at its own address. */ + private boolean proxyEndpointInVpc(DbProxyEndpoint endpoint) { + return endpointAddresses != null && endpoint.getVpcEndpointId() != null; + } + + /** + * The port a proxy's endpoints serve in its VPC: its engine family's, as "all proxies listen on port 5432 for + * PostgreSQL" and "on port 3306 for MySQL" (RDS user guide); SQL Server's 1433, which the guide does not name. + */ + private int proxyServedPort(DbProxy proxy) { + return defaultPortForEngineFamily(proxy.getEngineFamily()); + } + + /** The port an IAM token for the proxy names, which its listener checks: the one its endpoints serve. */ + private int proxyPublishedPort(DbProxy proxy) { + return proxyInVpc(proxy) ? proxyServedPort(proxy) : proxy.getProxyPort(); + } + + /** + * Gives a proxy its default endpoint in its VPC, served in the first of its subnets under the name RDS gives it, + * when endpoints go in their VPC; false, leaving the proxy as it was, otherwise. + */ + private boolean assignProxyEndpoint(DbProxy proxy) { + if (!endpointsInVpc() || proxy.getVpcSubnetIds().isEmpty()) { + return false; + } + proxy.setVpcEndpointId(RdsEndpointAddresses.newRelayId()); + proxy.setVpcEndpointSubnetId(proxy.getVpcSubnetIds().getFirst()); + proxy.setVpcEndpointAddress(null); + proxy.setEndpointHost(AwsEndpoints.rdsProxyHost(proxy.getDbProxyName(), + accountIdFromArn(proxy.getDbProxyArn()), regionResolver.regionOf(proxy.getDbProxyArn()))); + return true; + } + + /** {@link #assignProxyEndpoint(DbProxy)} for an endpoint added to a proxy, in the first of its own subnets. */ + private boolean assignProxyEndpoint(DbProxy proxy, DbProxyEndpoint endpoint) { + if (!proxyInVpc(proxy) || endpoint.getVpcSubnetIds().isEmpty()) { + return false; + } + endpoint.setVpcEndpointId(RdsEndpointAddresses.newRelayId()); + endpoint.setVpcEndpointSubnetId(endpoint.getVpcSubnetIds().getFirst()); + endpoint.setVpcEndpointAddress(null); + return true; + } + + /** The name of an endpoint added to a proxy, in its VPC. */ + private String proxyEndpointHost(DbProxy proxy, DbProxyEndpoint endpoint) { + return AwsEndpoints.rdsProxyEndpointHost(endpoint.getDbProxyEndpointName(), + accountIdFromArn(proxy.getDbProxyArn()), regionResolver.regionOf(proxy.getDbProxyArn())); + } + + /** + * Serves the proxy's default endpoint at its address, relayed to the proxy's listener, records the address and + * makes the name known. Nothing listens until a target is registered, as an RDS proxy without one takes no + * connections. + * + * @throws IllegalStateException when the subnet has no address to give + */ + private void serveProxyInVpc(DbProxy proxy) { + String accountId = accountIdFromArn(proxy.getDbProxyArn()); + endpointAddresses.remember(proxy.getEndpointHost(), proxy.getVpcEndpointId(), proxy.getDbProxyResourceId()); + proxy.setVpcEndpointAddress(endpointAddresses.serve(proxy.getVpcEndpointId(), accountId, + regionResolver.regionOf(proxy.getDbProxyArn()), proxy.getVpcId(), proxy.getVpcEndpointSubnetId(), + proxyServedPort(proxy), proxy.getProxyPort(), "DB proxy " + proxy.getDbProxyName(), + proxy.getVpcEndpointAddress())); + } + + /** + * {@link #serveProxyInVpc(DbProxy)} for an endpoint added to the proxy, in its own VPC. An IAM token generated + * for its name is good at the proxy, and the proxies' certificate covers the name. + */ + private void serveProxyInVpc(DbProxy proxy, DbProxyEndpoint endpoint) { + String host = proxyEndpointHost(proxy, endpoint); + endpointAddresses.remember(host, endpoint.getVpcEndpointId(), proxy.getDbProxyResourceId()); + coverTlsHost(host); + endpoint.setVpcEndpointAddress(endpointAddresses.serve(endpoint.getVpcEndpointId(), + accountIdFromArn(proxy.getDbProxyArn()), regionResolver.regionOf(proxy.getDbProxyArn()), + endpoint.getVpcId(), endpoint.getVpcEndpointSubnetId(), proxyServedPort(proxy), proxy.getProxyPort(), + "DB proxy endpoint " + endpoint.getDbProxyEndpointName(), endpoint.getVpcEndpointAddress())); + } + + /** Discards the relays of a proxy's endpoints and its default endpoint ({@link RdsEndpointAddresses#discard}). */ + private void discardProxyRelays(DbProxy proxy, List endpoints) { + endpoints.stream().filter(this::proxyEndpointInVpc) + .forEach(endpoint -> endpointAddresses.discard(endpoint.getVpcEndpointId())); + if (proxyInVpc(proxy)) { + endpointAddresses.discard(proxy.getVpcEndpointId()); + } + } + // ── DB Subnet Groups ────────────────────────────────────────────────────── public DbSubnetGroup createDbSubnetGroup(String name, String description, List subnetIds) { @@ -9637,13 +9815,16 @@ public class RdsService implements Resettable, ResourceProvider { synchronized (clusterNameRoutes) { hosts = publishClusterNames(cluster); } - for (String host : hosts) { - try { - proxyManager.coverTlsHost(host); - } catch (RuntimeException e) { - // The name still resolves; only a client that checks the certificate's names refuses it. - LOG.warnv(e, "The RDS proxies' certificate does not cover {0}", host); - } + hosts.forEach(this::coverTlsHost); + } + + /** Puts {@code host} on the proxies' certificate, which TLS clients check a name they connect by against. */ + private void coverTlsHost(String host) { + try { + proxyManager.coverTlsHost(host); + } catch (RuntimeException e) { + // The name still resolves; only a client that checks the certificate's names refuses it. + LOG.warnv(e, "The RDS proxies' certificate does not cover {0}", host); } } @@ -10388,6 +10569,9 @@ public class RdsService implements Resettable, ResourceProvider { ? source.getTargetConnectionNetworkType() : "IPV4"); copy.setVpcSubnetIds(source.getVpcSubnetIds()); copy.setVpcSecurityGroupIds(source.getVpcSecurityGroupIds()); + copy.setVpcEndpointId(source.getVpcEndpointId()); + copy.setVpcEndpointSubnetId(source.getVpcEndpointSubnetId()); + copy.setVpcEndpointAddress(source.getVpcEndpointAddress()); copy.setAuth(source.getAuth().stream().map(this::copyDbProxyAuth).toList()); copy.setTags(source.getTags()); return copy; @@ -10502,7 +10686,7 @@ public class RdsService implements Resettable, ResourceProvider { accountId, proxyRegion, targetId, user, password) : validateDbPasswordForScope( accountId, proxyRegion, targetId, user, password), - proxyBinding(engine, proxy.getEndpointHost(), proxy.getProxyPort(), + proxyBinding(engine, proxy.getEndpointHost(), proxyPublishedPort(proxy), proxyRegion, accountId, proxy.getDbProxyResourceId()), RdsAuthProxy.EndpointKind.STANDARD_DB_PROXY); } @@ -10947,12 +11131,14 @@ public class RdsService implements Resettable, ResourceProvider { proxy.setProxyPort(proxyPort); if (config.services().rds().mock()) { proxy.setEndpointHost("localhost"); + placeRestoredProxy(proxy); proxy.setStatus("available"); persistRestoredProxy(proxy); ensureRestoredDefaultTargetGroup(proxy); continue; } proxy.setEndpointHost(dbProxyEndpointHost()); + placeRestoredProxy(proxy); persistRestoredProxy(proxy); DbProxyTargetGroup targetGroup = ensureRestoredDefaultTargetGroup(proxy); if (targetGroup.getTargets().isEmpty()) { @@ -10992,6 +11178,67 @@ public class RdsService implements Resettable, ResourceProvider { } } + /** + * Puts a restored proxy's endpoints in its VPC, or takes them out, as {@code endpoints-in-vpc} now says: the + * setting may have changed across the restart. Those in it are served again at the addresses they had; one whose + * relay cannot be served keeps its name, with no address. + */ + private void placeRestoredProxy(DbProxy proxy) { + if (endpointAddresses == null) { + return; + } + String accountId = accountIdFromArn(proxy.getDbProxyArn()); + String region = regionResolver.regionOf(proxy.getDbProxyArn()); + // In the proxy's account, which a restart reads outside any request. + List endpoints = RequestScopes.callAs(accountId, region, + () -> proxyEndpointsOf(region, proxy.getDbProxyName())); + if (!endpointsInVpc()) { + if (!proxyInVpc(proxy) && endpoints.stream().noneMatch(this::proxyEndpointInVpc)) { + return; + } + // Out of the VPC whatever Docker says: a relay it keeps stays tracked until it is removed. + discardProxyRelays(proxy, endpoints); + proxy.setVpcEndpointId(null); + proxy.setVpcEndpointSubnetId(null); + proxy.setVpcEndpointAddress(null); + for (DbProxyEndpoint endpoint : endpoints) { + endpoint.setVpcEndpointId(null); + endpoint.setVpcEndpointSubnetId(null); + endpoint.setVpcEndpointAddress(null); + } + persistRestoredProxyEndpoints(accountId, region, endpoints); + return; + } + if (proxyInVpc(proxy)) { + proxy.setEndpointHost(AwsEndpoints.rdsProxyHost(proxy.getDbProxyName(), accountId, region)); + } else if (!assignProxyEndpoint(proxy)) { + return; + } + try { + serveProxyInVpc(proxy); + } catch (RuntimeException e) { + LOG.warnv(e, "DB proxy {0} is known by its name with no address until its relay can be served", + proxy.getDbProxyName()); + } + for (DbProxyEndpoint endpoint : endpoints) { + if (!proxyEndpointInVpc(endpoint)) { + assignProxyEndpoint(proxy, endpoint); + } + try { + serveProxyInVpc(proxy, endpoint); + } catch (RuntimeException e) { + LOG.warnv(e, "DB proxy endpoint {0} is known by its name with no address until its relay can be " + + "served", endpoint.getDbProxyEndpointName()); + } + } + persistRestoredProxyEndpoints(accountId, region, endpoints); + } + + private void persistRestoredProxyEndpoints(String accountId, String region, List endpoints) { + RequestScopes.runAs(accountId, region, () -> endpoints.forEach(endpoint -> proxyEndpoints.put( + proxyEndpointKey(region, endpoint.getDbProxyEndpointName()), endpoint))); + } + private void persistRestoredProxy(DbProxy proxy) { String accountId = AwsArnUtils.accountOrDefault(proxy.getDbProxyArn(), defaultAccountId()); String proxyKey = dbProxyKey(regionResolver.regionOf(proxy.getDbProxyArn()), proxy.getDbProxyName()); @@ -11981,9 +12228,13 @@ public class RdsService implements Resettable, ResourceProvider { return allocateProxyPort(); } - private int reserveOrAllocateProxyPort(int persistedPort) { - if (persistedPort > 0 && reserveOwnedProxyPort(persistedPort)) { - return persistedPort; + /** + * {@code preferredPort} when it is free, as a new proxy's engine-default port, otherwise a free port of the range. + * A port a relay that may still run forwards to is not free, whoever it served. + */ + private int reserveOrAllocateProxyPort(int preferredPort) { + if (preferredPort > 0 && reserveAvailableProxyPort(preferredPort)) { + return preferredPort; } return allocateProxyPort(); } diff --git a/src/main/java/io/floci/aws/services/rds/model/DbProxy.java b/src/main/java/io/floci/aws/services/rds/model/DbProxy.java index 61fa7bd33a..deda1b256f 100644 --- a/src/main/java/io/floci/aws/services/rds/model/DbProxy.java +++ b/src/main/java/io/floci/aws/services/rds/model/DbProxy.java @@ -34,6 +34,11 @@ public class DbProxy { private Instant createdAt; private Instant updatedAt; private String vpcId; + // With endpoints-in-vpc: the relay that serves the proxy's default endpoint at its own address in + // vpcEndpointSubnetId, and that address once it has one. + private String vpcEndpointId; + private String vpcEndpointSubnetId; + private String vpcEndpointAddress; private String endpointNetworkType = "IPV4"; private String targetConnectionNetworkType = "IPV4"; private List vpcSubnetIds = new ArrayList<>(); @@ -99,6 +104,15 @@ public class DbProxy { public String getVpcId() { return vpcId; } public void setVpcId(String vpcId) { this.vpcId = vpcId; } + public String getVpcEndpointId() { return vpcEndpointId; } + public void setVpcEndpointId(String vpcEndpointId) { this.vpcEndpointId = vpcEndpointId; } + + public String getVpcEndpointSubnetId() { return vpcEndpointSubnetId; } + public void setVpcEndpointSubnetId(String vpcEndpointSubnetId) { this.vpcEndpointSubnetId = vpcEndpointSubnetId; } + + public String getVpcEndpointAddress() { return vpcEndpointAddress; } + public void setVpcEndpointAddress(String vpcEndpointAddress) { this.vpcEndpointAddress = vpcEndpointAddress; } + public String getEndpointNetworkType() { return endpointNetworkType; } public void setEndpointNetworkType(String endpointNetworkType) { this.endpointNetworkType = endpointNetworkType; diff --git a/src/main/java/io/floci/aws/services/rds/model/DbProxyEndpoint.java b/src/main/java/io/floci/aws/services/rds/model/DbProxyEndpoint.java index 3cc05bcc37..7fb31de87c 100644 --- a/src/main/java/io/floci/aws/services/rds/model/DbProxyEndpoint.java +++ b/src/main/java/io/floci/aws/services/rds/model/DbProxyEndpoint.java @@ -24,6 +24,11 @@ public class DbProxyEndpoint { private String dbProxyName; private String status; private String vpcId; + // With endpoints-in-vpc: the relay that serves this endpoint at its own address in vpcEndpointSubnetId, and + // that address once it has one. + private String vpcEndpointId; + private String vpcEndpointSubnetId; + private String vpcEndpointAddress; private List vpcSubnetIds = new ArrayList<>(); private List vpcSecurityGroupIds = new ArrayList<>(); /** The owning proxy's host, filled in for each response. */ @@ -53,6 +58,15 @@ public class DbProxyEndpoint { public String getVpcId() { return vpcId; } public void setVpcId(String vpcId) { this.vpcId = vpcId; } + public String getVpcEndpointId() { return vpcEndpointId; } + public void setVpcEndpointId(String vpcEndpointId) { this.vpcEndpointId = vpcEndpointId; } + + public String getVpcEndpointSubnetId() { return vpcEndpointSubnetId; } + public void setVpcEndpointSubnetId(String vpcEndpointSubnetId) { this.vpcEndpointSubnetId = vpcEndpointSubnetId; } + + public String getVpcEndpointAddress() { return vpcEndpointAddress; } + public void setVpcEndpointAddress(String vpcEndpointAddress) { this.vpcEndpointAddress = vpcEndpointAddress; } + public List getVpcSubnetIds() { return vpcSubnetIds; } public void setVpcSubnetIds(List vpcSubnetIds) { this.vpcSubnetIds = vpcSubnetIds != null ? new ArrayList<>(vpcSubnetIds) : new ArrayList<>(); diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index bce9ef836a..7205e3ca48 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -661,7 +661,7 @@ floci: proxy-base-port: 7001 proxy-max-port: 7099 # advertise-requested-port: false # FLOCI_SERVICES_RDS_ADVERTISE_REQUESTED_PORT; true = Describe* reports the requested Port, not the proxy port - # endpoints-in-vpc: false # FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC; true = an instance in a VPC serves its Port at its own address and RDS endpoint name, and a cluster's endpoint names resolve to its instances + # endpoints-in-vpc: false # FLOCI_SERVICES_RDS_ENDPOINTS_IN_VPC; true = an instance in a VPC serves its Port at its own address and RDS endpoint name, a cluster's endpoint names resolve to its instances, and a DB proxy's endpoints get their own addresses # endpoint-host: localhost # Hostname clients use; enables published-port translation in Docker # iam-token-endpoint-binding: true # FLOCI_SERVICES_RDS_IAM_TOKEN_ENDPOINT_BINDING; false accepts PostgreSQL IAM tokens generated for another hostname or port # Omit image overrides to adapt Floci's built-in images to EngineVersion. diff --git a/src/test/java/io/floci/aws/core/common/AwsEndpointsTest.java b/src/test/java/io/floci/aws/core/common/AwsEndpointsTest.java index 685fd5d195..1992a07a7b 100644 --- a/src/test/java/io/floci/aws/core/common/AwsEndpointsTest.java +++ b/src/test/java/io/floci/aws/core/common/AwsEndpointsTest.java @@ -103,6 +103,19 @@ class AwsEndpointsTest { AwsEndpoints.rdsClusterEndpointHost("orders", "cluster", "123456789012", region)); } + @ParameterizedTest + @MethodSource("io.floci.aws.testing.PartitionMatrix#cases") + void aDbProxyAndItsEndpointsHostsCarryTheIdentifierAfterProxy(PartitionCase partitionCase) { + String region = partitionCase.region(); + String identifier = AwsEndpoints.rdsEndpointIdentifier("123456789012", region); + + assertEquals("app-proxy.proxy-" + identifier + "." + region + ".rds." + partitionCase.dnsSuffix(), + AwsEndpoints.rdsProxyHost("App-Proxy", "123456789012", region)); + assertEquals("reader.endpoint.proxy-" + identifier + "." + region + ".rds." + partitionCase.dnsSuffix(), + AwsEndpoints.rdsProxyEndpointHost("Reader", "123456789012", region)); + PartitionMatrix.assertHostIn(partitionCase, AwsEndpoints.rdsProxyHost("app-proxy", "123456789012", region)); + } + @Test void theRdsEndpointIdentifierIsTwelveLettersAndDigitsALetterFirst() { String identifier = AwsEndpoints.rdsEndpointIdentifier("123456789012", "us-east-1"); diff --git a/src/test/java/io/floci/aws/services/rds/RdsEndpointAddressesTest.java b/src/test/java/io/floci/aws/services/rds/RdsEndpointAddressesTest.java index c26b558187..ee066a334e 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsEndpointAddressesTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsEndpointAddressesTest.java @@ -306,9 +306,9 @@ class RdsEndpointAddressesTest { addresses.route("cluster-1", Map.of(writer, clusterName("cluster-1", List.of(), List.of()))); assertFalse(addresses.names(reports)); - assertTrue(addresses.namesCluster("cluster-1", writer.toUpperCase())); - assertFalse(addresses.namesCluster("cluster-2", writer)); - assertTrue(addresses.namesCluster("cluster-2", other)); + assertTrue(addresses.reaches("cluster-1", writer.toUpperCase())); + assertFalse(addresses.reaches("cluster-2", writer)); + assertTrue(addresses.reaches("cluster-2", other)); addresses.forgetCluster("cluster-1"); @@ -338,6 +338,63 @@ class RdsEndpointAddressesTest { assertFalse(addresses.inVpc(cluster)); } + @Test + void aProxysEndpointIsServedUnderItsNameAndReachesItsProxyAlone() { + String relayId = RdsEndpointAddresses.newRelayId(); + String name = AwsEndpoints.rdsProxyEndpointHost("reader", ACCOUNT, REGION); + + String address = addresses.serve(relayId, ACCOUNT, REGION, "vpc-1", "subnet-a", 5432, 7005, "proxy endpoint", + null); + addresses.remember(name, relayId, "prx-1"); + + assertEquals("10.0.1.20", address); + assertEquals(Optional.of(address), addresses.addressOf(name.toUpperCase())); + assertTrue(addresses.reaches("prx-1", name.toUpperCase())); + assertFalse(addresses.reaches("prx-2", name)); + assertTrue(addresses.targetsPort(7005)); + verify(fixture.builder).withCmd(List.of("TCP-LISTEN:5432,fork,reuseaddr,nodelay,backlog=4096", + "TCP:host.docker.internal:7005,nodelay")); + + String renamed = AwsEndpoints.rdsProxyEndpointHost("reports", ACCOUNT, REGION); + addresses.remember(renamed, relayId, "prx-1"); + assertFalse(addresses.names(name)); + assertTrue(addresses.reaches("prx-1", renamed)); + + addresses.discard(relayId); + + assertFalse(addresses.names(renamed)); + assertFalse(addresses.reaches("prx-1", renamed)); + assertFalse(addresses.targetsPort(7005)); + } + + @Test + void aDiscardedEndpointWhoseRelayDockerKeepsLosesItsNameAndKeepsItsPort() { + String relayId = RdsEndpointAddresses.newRelayId(); + String name = AwsEndpoints.rdsProxyHost("app-proxy", ACCOUNT, REGION); + addresses.serve(relayId, ACCOUNT, REGION, "vpc-1", "subnet-a", 5432, 7005, "proxy", null); + addresses.remember(name, relayId, "prx-1"); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-1"); + + addresses.discard(relayId); + + assertFalse(addresses.names(name)); + assertFalse(addresses.reaches("prx-1", name)); + assertTrue(addresses.targetsPort(7005)); + assertTrue(addresses.hasSubnetDependency(REGION, "subnet-a")); + } + + @Test + void aResetForgetsWhichProxyAnEndpointReaches() { + String relayId = RdsEndpointAddresses.newRelayId(); + String name = AwsEndpoints.rdsProxyEndpointHost("reader", ACCOUNT, REGION); + addresses.remember(name, relayId, "prx-1"); + + addresses.clear(); + + assertFalse(addresses.reaches("prx-1", name)); + } + /** An instance served at its own address, with its name known. */ private DbInstance served(String id, int proxyPort) { DbInstance instance = instance(id, "us-east-1a", null); diff --git a/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcDockerNightlyIntegrationTest.java b/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcDockerNightlyIntegrationTest.java index ee7dbc10e3..f9d8814a43 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcDockerNightlyIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcDockerNightlyIntegrationTest.java @@ -5,6 +5,7 @@ import com.github.dockerjava.api.model.HostConfig; import io.floci.aws.core.common.AwsEndpoints; import io.floci.aws.core.common.dns.DnsAnswer; import io.floci.aws.core.common.docker.ContainerExec; +import io.floci.aws.services.ec2.Ec2Service; import io.floci.aws.services.ec2.net.VpcNetworkManager; import io.floci.aws.testing.AwsTestClients; import io.floci.aws.testing.DockerAvailability; @@ -20,8 +21,10 @@ import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.condition.EnabledIfSystemProperty; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rds.RdsClient; +import software.amazon.awssdk.services.rds.model.AuthScheme; import software.amazon.awssdk.services.rds.model.DBCluster; import software.amazon.awssdk.services.rds.model.DBInstance; +import software.amazon.awssdk.services.rds.model.UserAuthConfig; import java.time.Duration; import java.util.LinkedHashSet; @@ -43,7 +46,8 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; * VPC's Docker network, the stand-in for a container in the same VPC, signs in through each address and sees each * database's own data. A stopped instance's name has no address, and a started one is served again at the address it * had. A real Aurora PostgreSQL cluster's instances serve its port the same way, and its cluster endpoint name - * resolves to the writer, before and after a failover, and its reader endpoint name to the reader. + * resolves to the writer, before and after a failover, and its reader endpoint name to the reader. A DB proxy's default + * endpoint and an endpoint added to it serve 5432 at their own addresses, through the proxy to its target. * *

A Docker end-to-end check: it runs real database and relay containers. The client connects by address, as * Floci's DNS server is not reachable from containers on every runner. The tests share the default VPC, whose Docker @@ -227,6 +231,69 @@ class RdsEndpointsInVpcDockerNightlyIntegrationTest { } } + @Test + void aProxysEndpointsServe5432AtTheirOwnAddressesThroughTheProxy() throws Exception { + String instanceId = "vpc-target-" + UUID.randomUUID().toString().substring(0, 8); + String proxyName = "vpc-proxy-" + UUID.randomUUID().toString().substring(0, 8); + String endpointName = "vpc-reader-" + UUID.randomUUID().toString().substring(0, 8); + String client = null; + try (RdsClient rds = AwsTestClients.create(RdsClient.builder(), ACCOUNT, Region.US_EAST_1)) { + try { + rds.createDBInstance(r -> r.dbInstanceIdentifier(instanceId).engine("postgres").engineVersion("16.3") + .masterUsername("admin").masterUserPassword(PASSWORD).dbName("appdb") + .dbInstanceClass("db.t3.micro").allocatedStorage(20).port(5432)); + vpcIds.add(rdsService.getDbInstance(instanceId).getVpcId()); + List subnets = List.of(Ec2Service.defaultSubnetId(REGION, "a", ACCOUNT), + Ec2Service.defaultSubnetId(REGION, "b", ACCOUNT)); + String proxyEndpoint = rds.createDBProxy(r -> r.dbProxyName(proxyName).engineFamily("POSTGRESQL") + .roleArn("arn:aws:iam::" + ACCOUNT + ":role/proxy").vpcSubnetIds(subnets) + .auth(UserAuthConfig.builder().authScheme(AuthScheme.SECRETS) + .secretArn("arn:aws:secretsmanager:" + REGION + ":" + ACCOUNT + ":secret:db-AbCdEf") + .build())).dbProxy().endpoint(); + assertEquals(AwsEndpoints.rdsProxyHost(proxyName, ACCOUNT, REGION), proxyEndpoint); + rds.registerDBProxyTargets(r -> r.dbProxyName(proxyName).dbInstanceIdentifiers(instanceId)); + String added = rds.createDBProxyEndpoint(r -> r.dbProxyName(proxyName) + .dbProxyEndpointName(endpointName).vpcSubnetIds(subnets)).dbProxyEndpoint().endpoint(); + assertEquals(AwsEndpoints.rdsProxyEndpointHost(endpointName, ACCOUNT, REGION), added); + String proxyAddress = address(proxyEndpoint); + String addedAddress = address(added); + assertNotEquals(proxyAddress, addedAddress); + + String vpcId = rdsService.getDbProxy(proxyName, REGION).getVpcId(); + vpcIds.add(vpcId); + String network = vpcNetworkManager.networkNameFor(ACCOUNT, REGION, vpcId).orElseThrow(); + String image = dockerClient.inspectContainerCmd(rdsService.getDbInstance(instanceId).getContainerId()) + .exec().getConfig().getImage(); + client = dockerClient.createContainerCmd(image) + .withEntrypoint("sleep") + .withCmd("600") + .withHostConfig(HostConfig.newHostConfig().withNetworkMode(network)) + .exec().getId(); + dockerClient.startContainerCmd(client).exec(); + + assertEquals("proxied", psql(client, proxyAddress, + "CREATE TABLE IF NOT EXISTS marker(v text PRIMARY KEY); " + + "INSERT INTO marker VALUES ('proxied') ON CONFLICT DO NOTHING; SELECT v FROM marker;")); + assertEquals("proxied", psql(client, addedAddress, "SELECT v FROM marker;")); + } finally { + try { + rds.deleteDBProxy(r -> r.dbProxyName(proxyName)); + } catch (RuntimeException ignored) { + // Not created, or already gone. + } + try { + rds.deleteDBInstance(r -> r.dbInstanceIdentifier(instanceId).skipFinalSnapshot(true)); + } catch (RuntimeException ignored) { + // Not created, or already gone. + } + } + } finally { + if (client != null) { + dockerClient.removeContainerCmd(client).withForce(true).exec(); + } + } + } + @AfterAll void removeVpcNetworks() { for (String vpcId : vpcIds) { diff --git a/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcTest.java b/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcTest.java index 092ff642c7..f565b5259b 100644 --- a/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcTest.java +++ b/src/test/java/io/floci/aws/services/rds/RdsEndpointsInVpcTest.java @@ -21,6 +21,10 @@ import io.floci.aws.services.rds.model.DbEndpoint; import io.floci.aws.services.rds.model.DbInstance; import io.floci.aws.services.rds.model.DbInstanceSettings; import io.floci.aws.services.rds.model.DbInstanceStatus; +import io.floci.aws.services.rds.model.DbProxy; +import io.floci.aws.services.rds.model.DbProxyAuth; +import io.floci.aws.services.rds.model.DbProxyEndpoint; +import io.floci.aws.services.rds.model.DbProxyTargetGroup; import io.floci.aws.services.rds.model.ReadReplicaRequest; import io.floci.aws.services.rds.proxy.RdsProxyBinding; import io.floci.aws.services.rds.proxy.RdsProxyManager; @@ -30,6 +34,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.ResourceLock; import org.mockito.ArgumentCaptor; +import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -63,7 +68,8 @@ import static org.mockito.Mockito.when; /** * With {@code endpoints-in-vpc} on, a standalone instance serves the Port it was created with at its own address in * its subnet, under the name RDS gives it, through every step of its life, and a cluster's instances serve the - * cluster's port the same way, its endpoint names resolving to them; the relay is a real + * cluster's port the same way, its endpoint names resolving to them, as do a DB proxy's endpoints on its engine + * family's port; the relay is a real * {@link io.floci.aws.services.ec2.VpcAddressRelays} over a mocked EC2 and Docker. */ @ResourceLock(ParallelLocks.PORTS) @@ -87,6 +93,8 @@ class RdsEndpointsInVpcTest { private RdsEndpointAddresses endpointAddresses; private StorageBackend instances; private StorageBackend clusters; + private StorageBackend proxies; + private StorageBackend proxyTargetGroups; private RdsService rdsService; @BeforeEach @@ -126,6 +134,8 @@ class RdsEndpointsInVpcTest { endpointAddresses = newEndpointAddresses(); instances = new FailingStore(); clusters = new InMemoryStorage<>(); + proxies = new FailingProxyStore(); + proxyTargetGroups = new InMemoryStorage<>(); rdsService = newService(instances); } @@ -1299,6 +1309,340 @@ class RdsEndpointsInVpcTest { assertEquals(new DbEndpoint(clusterHost("orders-copy", "cluster"), 6000), restored.getEndpoint()); } + @Test + void aProxyServesItsEngineFamilysPortAtItsOwnAddressUnderItsName() { + DbProxy proxy = createProxy("app-proxy", "POSTGRESQL"); + + String name = AwsEndpoints.rdsProxyHost("app-proxy", ACCOUNT, REGION); + assertEquals(name, proxy.getEndpoint()); + assertEquals("10.0.1.20", proxy.getVpcEndpointAddress()); + assertEquals(SUBNET_A, proxy.getVpcEndpointSubnetId()); + assertTrue(proxy.getProxyPort() >= 7000 && proxy.getProxyPort() <= 7099); + verify(fixture.builder).withCmd(List.of("TCP-LISTEN:5432,fork,reuseaddr,nodelay,backlog=4096", + "TCP:host.docker.internal:" + proxy.getProxyPort() + ",nodelay")); + assertEquals(Optional.of("10.0.1.20"), endpointAddresses.addressOf(name)); + assertEquals(name, rdsService.describeDbProxyEndpoints(REGION, "app-proxy", "default", null, null) + .endpoints().getFirst().getEndpoint()); + } + + @Test + void twoProxiesBothServeTheirEngineFamilysPortEachAtItsOwnAddress() { + DbProxy first = createProxy("first-proxy", "POSTGRESQL"); + DbProxy second = createProxy("second-proxy", "POSTGRESQL"); + createProxy("mysql-proxy", "MYSQL"); + + assertNotEquals(first.getVpcEndpointAddress(), second.getVpcEndpointAddress()); + assertNotEquals(first.getProxyPort(), second.getProxyPort()); + verify(fixture.builder).withCmd(List.of("TCP-LISTEN:3306,fork,reuseaddr,nodelay,backlog=4096", + "TCP:host.docker.internal:" + rdsService.getDbProxy("mysql-proxy", REGION).getProxyPort() + + ",nodelay")); + } + + @Test + void anEndpointAddedToAProxyHasItsOwnNameAndAddressInItsOwnVpc() { + DbProxy proxy = createProxy("app-proxy", "POSTGRESQL"); + + DbProxyEndpoint reader = rdsService.createDbProxyEndpoint(REGION, "app-proxy", "reader", + List.of(SUBNET_E, SUBNET_F), null, "READ_ONLY", null, Map.of()); + + String name = AwsEndpoints.rdsProxyEndpointHost("reader", ACCOUNT, REGION); + assertEquals(name, reader.getEndpoint()); + assertEquals("vpc-other", reader.getVpcId()); + assertEquals(SUBNET_E, reader.getVpcEndpointSubnetId()); + assertEquals(Optional.of(reader.getVpcEndpointAddress()), endpointAddresses.addressOf(name)); + assertNotEquals(proxy.getVpcEndpointAddress(), reader.getVpcEndpointAddress()); + assertEquals(name, rdsService.describeDbProxyEndpoints(REGION, "app-proxy", "reader", null, null) + .endpoints().getFirst().getEndpoint()); + verify(proxyManager).coverTlsHost(name); + } + + @Test + void aTokenGeneratedForAnyOfAProxysEndpointsIsGoodAtTheProxy() { + create("app", "postgres", 5432); + createProxy("app-proxy", "POSTGRESQL"); + createProxy("other-proxy", "POSTGRESQL"); + rdsService.createDbProxyEndpoint(REGION, "app-proxy", "reader", List.of(SUBNET_A, SUBNET_B), null, + "READ_ONLY", null, Map.of()); + rdsService.createDbProxyEndpoint(REGION, "other-proxy", "elsewhere", List.of(SUBNET_A, SUBNET_B), null, + "READ_WRITE", null, Map.of()); + + rdsService.registerDbProxyTargets("app-proxy", null, List.of(), List.of("app"), 90, 40); + + ArgumentCaptor binding = ArgumentCaptor.forClass(RdsProxyBinding.class); + verify(proxyManager).startProxy(any(), any(), any(), anyBoolean(), + eq(rdsService.getDbProxy("app-proxy", REGION).getProxyPort()), any(), anyInt(), + eq(AwsEndpoints.rdsProxyHost("app-proxy", ACCOUNT, REGION)), any(), any(), any(), any(), + binding.capture(), any()); + assertEquals(5432, binding.getValue().publishedPort()); + assertTrue(binding.getValue().acceptsHost(AwsEndpoints.rdsProxyHost("app-proxy", ACCOUNT, REGION))); + assertTrue(binding.getValue().acceptsHost(AwsEndpoints.rdsProxyEndpointHost("reader", ACCOUNT, REGION))); + assertFalse(binding.getValue().acceptsHost( + AwsEndpoints.rdsProxyEndpointHost("elsewhere", ACCOUNT, REGION))); + assertFalse(binding.getValue().acceptsHost(AwsEndpoints.rdsProxyHost("other-proxy", ACCOUNT, REGION))); + } + + @Test + void aRenamedProxyEndpointAnswersByItsNewNameAtTheSameAddress() { + createProxy("app-proxy", "POSTGRESQL"); + DbProxyEndpoint endpoint = rdsService.createDbProxyEndpoint(REGION, "app-proxy", "reader", + List.of(SUBNET_A, SUBNET_B), null, "READ_ONLY", null, Map.of()); + String address = endpoint.getVpcEndpointAddress(); + + DbProxyEndpoint renamed = rdsService.modifyDbProxyEndpoint(REGION, "reader", "reports", null); + + String name = AwsEndpoints.rdsProxyEndpointHost("reports", ACCOUNT, REGION); + assertEquals(name, renamed.getEndpoint()); + assertEquals(Optional.of(address), endpointAddresses.addressOf(name)); + assertFalse(endpointAddresses.names(AwsEndpoints.rdsProxyEndpointHost("reader", ACCOUNT, REGION))); + verify(proxyManager).coverTlsHost(name); + } + + @Test + void aProxyEndpointCreateTheSubnetHasNoAddressForFailsAndLeavesNothingBehind() { + createProxy("app-proxy", "POSTGRESQL"); + when(ec2Service.allocateVpcPrivateIp(anyString(), anyString(), anyString())).thenReturn(Optional.empty()); + + assertThrows(IllegalStateException.class, () -> rdsService.createDbProxyEndpoint(REGION, "app-proxy", + "reader", List.of(SUBNET_A, SUBNET_B), null, "READ_ONLY", null, Map.of())); + + assertFalse(endpointAddresses.names(AwsEndpoints.rdsProxyEndpointHost("reader", ACCOUNT, REGION))); + assertEquals(1, rdsService.describeDbProxyEndpoints(REGION, "app-proxy", null, null, null) + .endpoints().size()); + } + + @Test + void aProxyWhoseRecordCannotBeStoredLeavesNoRelayOrPortBehind() { + ((FailingProxyStore) proxies).failNextPut = true; + + assertThrows(IllegalStateException.class, () -> createProxy("app-proxy", "POSTGRESQL")); + + assertTrue(fixture.present.isEmpty()); + assertFalse(endpointAddresses.names(AwsEndpoints.rdsProxyHost("app-proxy", ACCOUNT, REGION))); + assertEquals(7000, createProxy("next-proxy", "POSTGRESQL").getProxyPort()); + } + + @Test + void modifyingAProxyKeepsItsEndpointInItsVpc() { + DbProxy proxy = createProxy("app-proxy", "POSTGRESQL"); + + rdsService.modifyDbProxy("app-proxy", null, null, null, null, true, null, null, null, REGION); + + DbProxy modified = rdsService.getDbProxy("app-proxy", REGION); + assertEquals(proxy.getVpcEndpointId(), modified.getVpcEndpointId()); + assertEquals(proxy.getVpcEndpointAddress(), modified.getVpcEndpointAddress()); + } + + @Test + void aRestartStartsAProxysListenerForItsEndpointsName() { + create("app", "postgres", 5432); + createProxy("app-proxy", "POSTGRESQL"); + rdsService.registerDbProxyTargets("app-proxy", null, List.of(), List.of("app"), 90, 40); + endpointAddresses.stopManagedContainers(); + clearInvocations(proxyManager); + + newService(instances, newEndpointAddresses()).restorePersistedRuntime(); + + ArgumentCaptor binding = ArgumentCaptor.forClass(RdsProxyBinding.class); + verify(proxyManager).startProxy(any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(), + eq(AwsEndpoints.rdsProxyHost("app-proxy", ACCOUNT, REGION)), any(), any(), any(), any(), + binding.capture(), any()); + assertEquals(5432, binding.getValue().publishedPort()); + } + + @Test + void aRenameTheStoreRefusesKeepsTheNameDnsAnswers() throws Exception { + createProxy("app-proxy", "POSTGRESQL"); + DbProxyEndpoint endpoint = rdsService.createDbProxyEndpoint(REGION, "app-proxy", "reader", + List.of(SUBNET_A, SUBNET_B), null, "READ_ONLY", null, Map.of()); + InMemoryStorage refusing = new InMemoryStorage<>() { + @Override + public void delete(String key) { + throw new IllegalStateException("store refused the delete"); + } + }; + refusing.put(REGION + "::reader", endpoint); + Field store = RdsService.class.getDeclaredField("proxyEndpoints"); + store.setAccessible(true); + store.set(rdsService, refusing); + + assertThrows(IllegalStateException.class, + () -> rdsService.modifyDbProxyEndpoint(REGION, "reader", "reports", null)); + + String name = AwsEndpoints.rdsProxyEndpointHost("reader", ACCOUNT, REGION); + assertEquals(name, rdsService.describeDbProxyEndpoints(REGION, "app-proxy", "reader", null, null) + .endpoints().getFirst().getEndpoint()); + assertEquals(Optional.of(endpoint.getVpcEndpointAddress()), endpointAddresses.addressOf(name)); + assertFalse(endpointAddresses.names(AwsEndpoints.rdsProxyEndpointHost("reports", ACCOUNT, REGION))); + } + + @Test + void deletingAProxysEndpointAndThenTheProxyRemovesTheirRelaysAndNames() { + createProxy("app-proxy", "POSTGRESQL"); + rdsService.createDbProxyEndpoint(REGION, "app-proxy", "reader", List.of(SUBNET_A, SUBNET_B), null, + "READ_ONLY", null, Map.of()); + rdsService.createDbProxyEndpoint(REGION, "app-proxy", "writer", List.of(SUBNET_A, SUBNET_B), null, + "READ_WRITE", null, Map.of()); + assertEquals(3, fixture.present.size()); + + rdsService.deleteDbProxyEndpoint(REGION, "reader"); + + assertEquals(2, fixture.present.size()); + assertFalse(endpointAddresses.names(AwsEndpoints.rdsProxyEndpointHost("reader", ACCOUNT, REGION))); + + rdsService.deleteDbProxy("app-proxy", REGION); + + assertTrue(fixture.present.isEmpty()); + assertFalse(endpointAddresses.names(AwsEndpoints.rdsProxyHost("app-proxy", ACCOUNT, REGION))); + assertFalse(endpointAddresses.names(AwsEndpoints.rdsProxyEndpointHost("writer", ACCOUNT, REGION))); + } + + @Test + void aProxyWhoseRelayDockerKeepsIsDeletedAndItsRelayKeepsItsPortFromOthers() { + DbProxy proxy = createProxy("app-proxy", "POSTGRESQL"); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict("relay-1"); + + rdsService.deleteDbProxy("app-proxy", REGION); + + assertThrows(AwsException.class, () -> rdsService.getDbProxy("app-proxy", REGION)); + assertFalse(endpointAddresses.names(AwsEndpoints.rdsProxyHost("app-proxy", ACCOUNT, REGION))); + assertTrue(endpointAddresses.targetsPort(proxy.getProxyPort())); + assertNotEquals(proxy.getProxyPort(), createProxy("next-proxy", "POSTGRESQL").getProxyPort()); + } + + @Test + void aProxyDeleteThatFailsKeepsItsEndpointsServed() { + DbProxy proxy = createProxy("app-proxy", "POSTGRESQL"); + rdsService.createDbProxyEndpoint(REGION, "app-proxy", "reader", List.of(SUBNET_A, SUBNET_B), null, + "READ_ONLY", null, Map.of()); + doThrow(new IllegalStateException("listener stuck")).when(proxyManager).stopProxy(any()); + + assertThrows(IllegalStateException.class, () -> rdsService.deleteDbProxy("app-proxy", REGION)); + + assertEquals(2, fixture.present.size()); + assertEquals(Optional.of(proxy.getVpcEndpointAddress()), + endpointAddresses.addressOf(AwsEndpoints.rdsProxyHost("app-proxy", ACCOUNT, REGION))); + assertTrue(endpointAddresses.names(AwsEndpoints.rdsProxyEndpointHost("reader", ACCOUNT, REGION))); + } + + @Test + void aProxyCreateTheSubnetHasNoAddressForFailsAndLeavesNothingBehind() { + when(ec2Service.allocateVpcPrivateIp(anyString(), anyString(), anyString())).thenReturn(Optional.empty()); + + assertThrows(IllegalStateException.class, () -> createProxy("app-proxy", "POSTGRESQL")); + + assertFalse(endpointAddresses.names(AwsEndpoints.rdsProxyHost("app-proxy", ACCOUNT, REGION))); + assertThrows(AwsException.class, () -> rdsService.getDbProxy("app-proxy", REGION)); + assertTrue(fixture.present.isEmpty()); + when(ec2Service.allocateVpcPrivateIp(anyString(), anyString(), anyString())) + .thenReturn(Optional.of("10.0.1.30")); + assertEquals(7000, createProxy("next-proxy", "POSTGRESQL").getProxyPort()); + } + + @Test + void aRestartServesAProxyAgainAtItsAddressAndTheSettingOffTakesItOut() { + DbProxy proxy = createProxy("app-proxy", "POSTGRESQL"); + String address = proxy.getVpcEndpointAddress(); + endpointAddresses.stopManagedContainers(); + + RdsEndpointAddresses restarted = newEndpointAddresses(); + newService(instances, restarted).restorePersistedRuntime(); + + assertEquals(Optional.of(address), + restarted.addressOf(AwsEndpoints.rdsProxyHost("app-proxy", ACCOUNT, REGION))); + restarted.stopManagedContainers(); + + when(config.services().rds().endpointsInVpc()).thenReturn(false); + RdsEndpointAddresses off = newEndpointAddresses(); + RdsService offService = newService(instances, off); + offService.restorePersistedRuntime(); + + DbProxy outside = offService.getDbProxy("app-proxy", REGION); + assertNull(outside.getVpcEndpointId()); + assertEquals("localhost", outside.getEndpoint()); + } + + @Test + void theSettingOffTakesAProxyOutOfItsVpcWhileARelayDockerKeepsHoldsItsPort() { + DbProxy proxy = createProxy("app-proxy", "POSTGRESQL"); + when(config.services().rds().endpointsInVpc()).thenReturn(false); + doThrow(new IllegalStateException("daemon down")).when(fixture.lifecycleManager) + .removeIfExistsStrict(any(String.class)); + + RdsEndpointAddresses restarted = newEndpointAddresses(); + RdsService service = newService(instances, restarted); + service.restorePersistedRuntime(); + + DbProxy outside = service.getDbProxy("app-proxy", REGION); + assertEquals("localhost", outside.getEndpoint()); + assertNull(outside.getVpcEndpointId()); + assertTrue(restarted.targetsPort(proxy.getProxyPort())); + } + + @Test + void theSettingOffRemovesARelayTheStartupSweepCouldNotOnceDockerConfirms() { + DbProxy proxy = createProxy("app-proxy", "POSTGRESQL"); + when(config.services().rds().endpointsInVpc()).thenReturn(false); + // The startup sweep's removal fails; the proxy's own retry goes through. + doThrow(new IllegalStateException("daemon down")) + .doAnswer(invocation -> fixture.present.remove(invocation.getArgument(0))) + .when(fixture.lifecycleManager).removeIfExistsStrict(any(String.class)); + + RdsEndpointAddresses restarted = newEndpointAddresses(); + newService(instances, restarted).restorePersistedRuntime(); + + assertTrue(fixture.placements.all().isEmpty()); + assertFalse(restarted.targetsPort(proxy.getProxyPort())); + } + + @Test + void aProxyOutsideItsVpcIsNotGivenAPortARetainedRelayForwardsTo() { + endpointAddresses.serve(RdsEndpointAddresses.newRelayId(), ACCOUNT, REGION, "vpc-default", SUBNET_A, 5432, + 5432, "retained", null); + when(config.services().rds().endpointsInVpc()).thenReturn(false); + + DbProxy proxy = createProxy("app-proxy", "POSTGRESQL"); + + assertNotEquals(5432, proxy.getProxyPort()); + // A free engine-default port is still the one a new proxy takes. + assertEquals(3306, createProxy("mysql-proxy", "MYSQL").getProxyPort()); + } + + @Test + void namesThatDifferOnlyInCaseAreOneProxyOrEndpointName() { + createProxy("Orders", "POSTGRESQL"); + rdsService.createDbProxyEndpoint(REGION, "Orders", "Reader", List.of(SUBNET_A, SUBNET_B), null, + "READ_ONLY", null, Map.of()); + + assertEquals("DBProxyAlreadyExistsFault", + assertThrows(AwsException.class, () -> createProxy("orders", "POSTGRESQL")).getErrorCode()); + for (String name : List.of("reader", "Default")) { + assertEquals("DBProxyEndpointAlreadyExistsFault", assertThrows(AwsException.class, + () -> rdsService.createDbProxyEndpoint(REGION, "Orders", name, List.of(SUBNET_A, SUBNET_B), null, + "READ_ONLY", null, Map.of())).getErrorCode()); + } + DbProxyEndpoint renamed = rdsService.modifyDbProxyEndpoint(REGION, "Reader", "reader", null); + assertEquals(AwsEndpoints.rdsProxyEndpointHost("reader", ACCOUNT, REGION), renamed.getEndpoint()); + } + + @Test + void mockModeKeepsTheProxyOnFloci() { + when(config.services().rds().mock()).thenReturn(true); + + DbProxy proxy = createProxy("app-proxy", "POSTGRESQL"); + + assertEquals("localhost", proxy.getEndpoint()); + assertNull(proxy.getVpcEndpointId()); + assertTrue(fixture.present.isEmpty()); + } + + private DbProxy createProxy(String name, String engineFamily) { + return rdsService.createDbProxy(name, engineFamily, false, false, "arn:aws:iam::123456789012:role/proxy", + List.of(SUBNET_A, SUBNET_B), List.of(), List.of(new DbProxyAuth("SECRETS", + "arn:aws:secretsmanager:us-east-1:123456789012:secret:db-AbCdEf", "DISABLED", null, null)), + Map.of()); + } + private DbCluster createCluster(String id, Integer port) { return rdsService.createDbCluster(id, "aurora-postgresql", "16.3", "admin", "password", "app", false, null, null, null, false, REGION, null, null, null, false, null, null, false, port); @@ -1327,7 +1671,7 @@ class RdsEndpointsInVpcTest { private RdsService newService(StorageBackend store, RdsEndpointAddresses addresses) { return new RdsService(containerManager, proxyManager, ec2Service, new RegionResolver(REGION, ACCOUNT), config, store, clusters, new InMemoryStorage<>(), new InMemoryStorage<>(), - new InMemoryStorage<>(), null, null, null, new InMemoryStorage<>(), new InMemoryStorage<>(), + new InMemoryStorage<>(), null, null, null, proxies, proxyTargetGroups, new InMemoryStorage<>(), null, null, null, addresses); } @@ -1341,6 +1685,20 @@ class RdsEndpointsInVpcTest { return newService(instances); } + /** A proxy store whose next write fails, as a full disk would make it. */ + private static final class FailingProxyStore extends InMemoryStorage { + boolean failNextPut; + + @Override + public synchronized void put(String key, DbProxy value) { + if (failNextPut) { + failNextPut = false; + throw new IllegalStateException("store refused the write"); + } + super.put(key, value); + } + } + /** A store whose next write of an available instance fails, as a full disk would make it. */ private static final class FailingStore extends InMemoryStorage { boolean failNextAvailableWrite;